/
api.go
562 lines (517 loc) · 17.2 KB
/
api.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
package model
import (
"encoding/json"
"errors"
"fmt"
"sort"
"strings"
"github.com/taskcluster/taskcluster/v55/tools/jsonschema2go/text"
)
//////////////////////////////////////////////////////////////////
//
// From: https://schemas.taskcluster.net/base/v1/api-reference.json
//
//////////////////////////////////////////////////////////////////
// API represents the HTTP interface of a Taskcluster service
type API struct {
*APIReferenceFile
apiDef *APIDefinition
typeName string
}
func (api *API) Name() string {
if api.typeName == "" {
api.typeName = text.GoIdentifierFrom(api.ServiceName, true, api.apiDef.members)
}
return api.typeName
}
func (api *API) String() string {
result := fmt.Sprintf(
"Schema = '%v'\n"+
"Title = '%v'\n"+
"Description = '%v'\n",
api.Schema, api.Title, api.Description,
)
for i, entry := range api.Entries {
result += fmt.Sprintf("Entry %-6v=\n%v", i, entry.String())
}
return result
}
func (api *API) postPopulate(apiDef *APIDefinition) {
// reserved package members
api.apiDef.members = map[string]bool{
"New": true,
"NewFromEnv": true,
}
// make sure each entry defined for this API has a unique generated method name
methods := map[string]bool{}
for i := range api.Entries {
api.Entries[i].Parent = api
api.Entries[i].MethodName = text.GoIdentifierFrom(api.Entries[i].Name, true, methods)
api.Entries[i].postPopulate(apiDef)
}
}
func (api *API) generateAPICode(apiName string) string {
// package name and variable name are ideally not the same
// so find a way to make them different...
// also don't allow type variable name to be the same as
// the type name
// e.g. switch case of first character, and if first
// character is not can't switch case for whatever
// reason, prefix variable name with "my"
exampleVarName := api.apiDef.ExampleVarName
var exampleCall string
// here we choose an example API method to call, just the first one in the list of api.Entries
// We need to first see if it returns one or two variables...
if api.Entries[0].Output == "" {
exampleCall = "// err := " + exampleVarName + "." + api.Entries[0].MethodName + "(.....)"
} else {
exampleCall = "// data, err := " + exampleVarName + "." + api.Entries[0].MethodName + "(.....)"
}
comment := ""
if api.Description != "" {
comment = text.Indent(api.Description, "// ")
}
if len(comment) >= 1 && comment[len(comment)-1:] != "\n" {
comment += "\n"
}
comment += "//\n"
comment += fmt.Sprintf("// See: %v\n", api.apiDef.DocRoot)
comment += "//\n"
comment += "// How to use this package\n"
comment += "//\n"
comment += "// First create " + text.IndefiniteArticle(api.Name()) + " " + api.Name() + " object:\n"
comment += "//\n"
comment += "// " + exampleVarName + " := " + api.apiDef.PackageName + ".New(nil)\n"
comment += "//\n"
comment += "// and then call one or more of " + exampleVarName + "'s methods, e.g.:\n"
comment += "//\n"
comment += exampleCall + "\n"
comment += "//\n"
comment += "// handling any errors...\n"
comment += "//\n"
comment += "// if err != nil {\n"
comment += "// // handle error...\n"
comment += "// }\n"
comment += "//\n"
comment += "// Taskcluster Schema\n"
comment += "//\n"
comment += "// The source code of this go package was auto-generated from the API definition at\n"
comment += "// <rootUrl>" + api.apiDef.URL + " together with the input and output schemas it references,\n"
content := comment
content += "package " + api.apiDef.PackageName + "\n"
// note: we remove unused imports later, so e.g. if net/url is not used, it
// will get removed later using:
// https://pkg.go.dev/golang.org/x/tools/imports
content += `
import (
"encoding/json"
"errors"
"net/url"
"time"
tcclient "github.com/taskcluster/taskcluster/v55/clients/client-go"
)
type ` + api.Name() + ` tcclient.Client
// New returns ` + text.IndefiniteArticle(api.Name()) + ` ` + api.Name() + ` client, configured to run against production. Pass in
// nil credentials to create a client without authentication. The
// returned client is mutable, so returned settings can be altered.
//
`
// Here we want to add spaces between commands and comments, such that the comments line up, e.g.:
//
// queue := tcqueue.New(
// nil, // client without authentication
// "http://localhost:1234/my/taskcluster", // taskcluster hosted at this root URL on local machine
// )
// err := queue.Ping(.....) // for example, call the Ping(.....) API endpoint (described further down)...
//
// We do this by generating the code, then calculating the max length of one of the code lines,
// and then padding with spaces based on max line length and adding comments.
commentedSection := [][]string{
{
"// " + exampleVarName + " := " + api.apiDef.PackageName + ".New(",
"",
},
{
"// nil,",
"// client without authentication",
},
{
"// \"http://localhost:1234/my/taskcluster\",",
"// taskcluster hosted at this root URL on local machine",
},
{
"// )",
"",
},
{
exampleCall,
"// for example, call the " + api.Entries[0].MethodName + "(.....) API endpoint (described further down)...",
},
}
maxLength := 0
for _, j := range commentedSection {
if len(j[0]) > maxLength {
maxLength = len(j[0])
}
}
for _, j := range commentedSection {
if len(j[1]) > 0 {
content += j[0] + strings.Repeat(" ", maxLength-len(j[0])+3) + j[1] + "\n"
} else {
content += j[0] + "\n"
}
}
content += "// if err != nil {\n"
content += "// // handle errors...\n"
content += "// }"
content += `
func New(credentials *tcclient.Credentials, rootURL string) *` + api.Name() + ` {
return &` + api.Name() + `{
Credentials: credentials,
RootURL: rootURL,
ServiceName: "` + api.ServiceName + `",
APIVersion: "` + api.APIVersion + `",
Authenticate: credentials != nil,
}
}
// NewFromEnv returns ` + text.IndefiniteArticle(api.Name()) + ` *` + api.Name() + ` configured from environment variables.
//
// The root URL is taken from TASKCLUSTER_PROXY_URL if set to a non-empty
// string, otherwise from TASKCLUSTER_ROOT_URL if set, otherwise the empty
// string.
//
// The credentials are taken from environment variables:
//
// TASKCLUSTER_CLIENT_ID
// TASKCLUSTER_ACCESS_TOKEN
// TASKCLUSTER_CERTIFICATE
//
// If TASKCLUSTER_CLIENT_ID is empty/unset, authentication will be
// disabled.
func NewFromEnv() *` + api.Name() + ` {
c := tcclient.CredentialsFromEnvVars()
rootURL := tcclient.RootURLFromEnvVars()
return &` + api.Name() + `{
Credentials: c,
RootURL: rootURL,
ServiceName: "` + api.ServiceName + `",
APIVersion: "` + api.APIVersion + `",
Authenticate: c.ClientID != "",
}
}
`
for _, entry := range api.Entries {
content += entry.generateAPICode(apiName)
}
return content
}
func (api *API) setAPIDefinition(apiDef *APIDefinition) {
api.apiDef = apiDef
}
// APIEntry represents an individual HTTP API call
// of a Taskcluster service
type APIEntry struct {
*Entry
MethodName string
Parent *API
InputURL string
OutputURL string
}
// Add entry.Input and entry.Output to schemaURLs, if they are set
func (entry *APIEntry) postPopulate(apiDef *APIDefinition) {
if x := &entry.Parent.apiDef.schemaURLs; entry.Input != "" {
entry.InputURL = ReferencesServerUrl(fmt.Sprintf("schemas/%s/%s", entry.Parent.ServiceName, entry.Input))
*x = append(*x, entry.InputURL)
}
if x := &entry.Parent.apiDef.schemaURLs; entry.Output != "" {
entry.OutputURL = ReferencesServerUrl(fmt.Sprintf("schemas/%s/%s", entry.Parent.ServiceName, entry.Output))
*x = append(*x, entry.OutputURL)
}
}
func (entry *APIEntry) String() string {
return fmt.Sprintf(
" Entry Type = '%v'\n"+
" Entry Method = '%v'\n"+
" Entry Route = '%v'\n"+
" Entry Args = '%v'\n"+
" Entry Query = '%v'\n"+
" Entry Name = '%v'\n"+
" Entry Stability = '%v'\n"+
" Entry Scopes = '%v'\n"+
" Entry Input = '%v'\n"+
" Entry InputURL = '%v'\n"+
" Entry Output = '%v'\n"+
" Entry OutputURL = '%v'\n"+
" Entry Title = '%v'\n"+
" Entry Description = '%v'\n",
entry.Type, entry.Method, entry.Route, entry.Args,
entry.Query, entry.Name, entry.Stability, &entry.Scopes,
entry.Input, entry.InputURL, entry.Output, entry.OutputURL,
entry.Title, entry.Description,
)
}
func (entry *APIEntry) generateAPICode(apiName string) string {
content := entry.generateDirectMethod(apiName)
if strings.ToUpper(entry.Method) == "GET" {
content += entry.generateSignedURLMethod(apiName)
}
return content
}
func (entry *APIEntry) getInputParamsAndQueryStringCode() (inputParams, queryCode, queryExpr string) {
inputArgs := append([]string{}, entry.Args...)
// add optional query parameters
queryCode = ""
queryExpr = "nil"
if len(entry.Query) > 0 {
queryExpr = "v"
sort.Strings(entry.Query)
queryCode = "v := url.Values{}\n"
for _, j := range entry.Query {
inputArgs = append(inputArgs, j)
queryCode += "if " + j + " != \"\" {\n\tv.Add(\"" + j + "\", " + j + ")\n}\n"
}
}
// all input parameters are strings, so if there are any, add the type to show it
if len(inputArgs) > 0 {
inputParams += strings.Join(inputArgs, ", ") + " string"
}
return
}
func (entry *APIEntry) generateDirectMethod(apiName string) string {
comment := ""
if entry.Stability != "stable" {
comment += "// Stability: *** " + strings.ToUpper(entry.Stability) + " ***\n"
comment += "//\n"
}
if entry.Description != "" {
comment += text.Indent(entry.Description, "// ")
}
if len(comment) >= 1 && comment[len(comment)-1:] != "\n" {
comment += "\n"
}
comment += requiredScopesComment(&entry.Scopes)
comment += "//\n"
comment += fmt.Sprintf("// See %v#%v\n", entry.Parent.apiDef.DocRoot, entry.Name)
inputParams, queryCode, queryExpr := entry.getInputParamsAndQueryStringCode()
apiArgsPayload := "nil"
if entry.InputURL != "" {
apiArgsPayload = "payload"
p := "payload *" + entry.Parent.apiDef.schemas.SubSchema(entry.InputURL).TypeName
if inputParams == "" {
inputParams = p
} else {
inputParams += ", " + p
}
}
responseType := "error"
if entry.OutputURL != "" {
responseType = "(*" + entry.Parent.apiDef.schemas.SubSchema(entry.OutputURL).TypeName + ", error)"
}
content := comment
content += "func (" + entry.Parent.apiDef.ExampleVarName + " *" + entry.Parent.Name() + ") " + entry.MethodName + "(" + inputParams + ") " + responseType + " {\n"
content += queryCode
content += "\tcd := tcclient.Client(*" + entry.Parent.apiDef.ExampleVarName + ")\n"
if entry.OutputURL != "" {
content += "\tresponseObject, _, err := (&cd).APICall(" + apiArgsPayload + ", \"" + strings.ToUpper(entry.Method) + "\", \"" + strings.Replace(strings.Replace(entry.Route, "<", "\" + url.QueryEscape(", -1), ">", ") + \"", -1) + "\", new(" + entry.Parent.apiDef.schemas.SubSchema(entry.OutputURL).TypeName + "), " + queryExpr + ")\n"
content += "\treturn responseObject.(*" + entry.Parent.apiDef.schemas.SubSchema(entry.OutputURL).TypeName + "), err\n"
} else {
content += "\t_, _, err := (&cd).APICall(" + apiArgsPayload + ", \"" + strings.ToUpper(entry.Method) + "\", \"" + strings.Replace(strings.Replace(entry.Route, "<", "\" + url.QueryEscape(", -1), ">", ") + \"", -1) + "\", nil, " + queryExpr + ")\n"
content += "\treturn err\n"
}
content += "}\n"
content += "\n"
// can remove any code that added an empty string to another string
return strings.Replace(content, ` + ""`, "", -1)
}
func (entry *APIEntry) generateSignedURLMethod(apiName string) string {
// if no required scopes, no reason to provide a signed url
// method, since no auth is required, so unsigned url already works,
// except for TestAuthenticateGet, which can be usefully used to test
// with signed URLs
if entry.Scopes.Type == "" && entry.MethodName != "TestAuthenticateGet" {
return ""
}
comment := "// Returns a signed URL for " + entry.MethodName + ", valid for the specified duration.\n"
comment += requiredScopesComment(&entry.Scopes)
comment += "//\n"
comment += fmt.Sprintf("// See %v for more details.\n", entry.MethodName)
inputParams, queryCode, queryExpr := entry.getInputParamsAndQueryStringCode()
if inputParams == "" {
inputParams = "duration time.Duration"
} else {
inputParams += ", duration time.Duration"
}
content := comment
content += "func (" + entry.Parent.apiDef.ExampleVarName + " *" + entry.Parent.Name() + ") " + entry.MethodName + "_SignedURL(" + inputParams + ") (*url.URL, error) {\n"
content += queryCode
content += "\tcd := tcclient.Client(*" + entry.Parent.apiDef.ExampleVarName + ")\n"
content += "\treturn (&cd).SignedURL(\"" + strings.Replace(strings.Replace(entry.Route, "<", "\" + url.QueryEscape(", -1), ">", ") + \"", -1) + "\", " + queryExpr + ", duration)\n"
content += "}\n"
content += "\n"
// can remove any code that added an empty string to another string
return strings.Replace(content, ` + ""`, "", -1)
}
func requiredScopesComment(scopes *ScopeExpressionTemplate) string {
if scopes.Type == "" {
return ""
}
comment := "\n"
comment += "Required scopes:\n"
comment += text.Indent(scopes.String()+"\n", " ")
return text.Indent(comment, "// ")
}
func (scopes *ScopeExpressionTemplate) String() string {
switch scopes.Type {
case "":
return ""
case "AllOf":
return scopes.AllOf.String()
case "AnyOf":
return scopes.AnyOf.String()
case "ForEachIn":
return scopes.ForEachIn.String()
case "IfThen":
return scopes.IfThen.String()
case "RequiredScope":
return scopes.RequiredScope.String()
default:
panic(fmt.Sprintf("Internal error - did not recognise scope form '%v'", scopes.Type))
}
}
func (allOf *Conjunction) String() string {
if allOf == nil {
return "WARNING: NIL AllOf"
}
switch len(allOf.AllOf) {
case 0:
return ""
case 1:
return allOf.AllOf[0].String()
}
var desc string
for _, exp := range allOf.AllOf {
x := text.Indent(exp.String(), " ")
if len(x) >= 2 {
desc += "\n" + "* " + x[2:]
}
}
return "All of:" + desc
}
func (anyOf *Disjunction) String() string {
if len(anyOf.AnyOf) == 0 {
return "AnyOf empty set - INVALID"
}
if len(anyOf.AnyOf) == 1 {
return anyOf.AnyOf[0].String()
}
var desc string
for _, exp := range anyOf.AnyOf {
x := text.Indent(exp.String(), " ")
if len(x) >= 2 {
desc += "\n" + "- " + x[2:]
}
}
return "Any of:" + desc
}
func (forEachIn *ForAll) String() string {
return "For " + forEachIn.For + " in " + forEachIn.In + " each " + forEachIn.Each
}
func (ifThen *Conditional) String() string {
return "If " + ifThen.If + ":\n" + text.Indent(ifThen.Then.String(), " ")
}
func (rs *RequiredScope) String() string {
return string(*rs)
}
// MarshalJSON calls json.RawMessage method of the same name. Required since
// ScopeExpressionTemplate is of type json.RawMessage...
func (m *ScopeExpressionTemplate) MarshalJSON() ([]byte, error) {
return (m.RawMessage).MarshalJSON()
}
// UnmarshalJSON identifies the data structure at runtime, and unmarshals in
// the appropriate type
func (m *ScopeExpressionTemplate) UnmarshalJSON(data []byte) error {
if m == nil {
return errors.New("ScopeExpressionTemplate: UnmarshalJSON on nil pointer")
}
m.RawMessage = append((m.RawMessage)[0:0], data...)
var tempObj interface{}
err := json.Unmarshal(m.RawMessage, &tempObj)
if err != nil {
panic("Internal error: " + err.Error())
}
switch t := tempObj.(type) {
case string:
m.Type = "RequiredScope"
m.RequiredScope = new(RequiredScope)
*(m.RequiredScope) = RequiredScope(t)
case map[string]interface{}:
j, err := json.Marshal(t)
if err != nil {
panic("Internal error: " + err.Error())
}
if _, exists := t["AnyOf"]; exists {
m.Type = "AnyOf"
m.AnyOf = new(Disjunction)
err = json.Unmarshal(j, m.AnyOf)
}
if _, exists := t["AllOf"]; exists {
m.Type = "AllOf"
m.AllOf = new(Conjunction)
err = json.Unmarshal(j, m.AllOf)
}
if _, exists := t["if"]; exists {
m.Type = "IfThen"
m.IfThen = new(Conditional)
err = json.Unmarshal(j, m.IfThen)
}
if _, exists := t["for"]; exists {
m.Type = "ForEachIn"
m.ForEachIn = new(ForAll)
err = json.Unmarshal(j, m.ForEachIn)
}
if err != nil {
panic("Internal error: " + err.Error())
}
// for old style scopesets [][]string (normal disjunctive form)
case []interface{}:
m.Type = "AnyOf"
m.AnyOf = &Disjunction{
AnyOf: make([]ScopeExpressionTemplate, len(t)),
}
for i, j := range t {
allOf := j.([]interface{})
m.AnyOf.AnyOf[i] = ScopeExpressionTemplate{
Type: "AllOf",
AllOf: &Conjunction{
AllOf: make([]ScopeExpressionTemplate, len(allOf)),
},
}
for k, l := range allOf {
rs := RequiredScope(l.(string))
m.AnyOf.AnyOf[i].AllOf.AllOf[k] = ScopeExpressionTemplate{
Type: "RequiredScope",
RequiredScope: &rs,
}
}
}
default:
panic(fmt.Sprintf("Internal error: unrecognised type %T for json: %v", t, string(data)))
}
return nil
}
// See https://schemas.taskcluster.net/base/v1/api-reference.json#/definitions/scopeExpressionTemplate
type ScopeExpressionTemplate struct {
RawMessage json.RawMessage
// One of:
// * "AllOf"
// * "AnyOf"
// * "ForEachIn"
// * "IfThen"
// * "RequiredScope"
Type string
AllOf *Conjunction
AnyOf *Disjunction
ForEachIn *ForAll
IfThen *Conditional
RequiredScope *RequiredScope
}