diff --git a/.golangci.yml b/.golangci.yml index b25c08c1..198db5d2 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -549,6 +549,7 @@ linters: files: - "$test" - "!**/client/http/*_test.go" + - "!**/cmd/internal/testacc/*_test.go" list-mode: strict allow: - $gostd @@ -567,6 +568,21 @@ linters: - github.com/spf13/pflag - github.com/stretchr/testify + # The API docs scenario breaks the connection to meshStack, as the tests of client/http do. + tests-testacc: + files: + - "**/cmd/internal/testacc/*_test.go" + list-mode: strict + allow: + - $gostd + - encoding/json/jsontext + - github.com/meshcloud/meshstack-cli + - github.com/spf13/cobra + - github.com/stretchr/testify + - github.com/Shopify/toxiproxy/v2 + # toxiproxy.NewServer takes a zerolog.Logger, and zerolog.Nop() is the only use + - github.com/rs/zerolog + # client/http breaks connections on purpose, which toxiproxy does in process. tests-client-http: files: diff --git a/client/openapi/doc.go b/client/openapi/doc.go index d693587e..5b4e64e9 100644 --- a/client/openapi/doc.go +++ b/client/openapi/doc.go @@ -42,7 +42,7 @@ type Body struct { // Field is a property anywhere in a body. Its Path joins the property names from the top with dots, // and writes the items of an array as [], as in spec.parentBuildingBlockRefs[].uuid, and the values -// of a map as the name *, as the API docs do. +// of a map as {}, as in spec.inputs{}.value. type Field struct { Path string Type string @@ -59,14 +59,18 @@ func (f Field) Depth() int { } type schema struct { - Ref string `json:"$ref"` - Type string `json:"type"` - Format string `json:"format"` - Description string `json:"description"` - Required []string `json:"required"` - Properties object `json:"properties"` - Items jsontext.Value `json:"items"` - resolvedRef string + Ref string `json:"$ref"` + Type string `json:"type"` + Format string `json:"format"` + Description string `json:"description"` + Required []string `json:"required"` + Properties object `json:"properties"` + Items jsontext.Value `json:"items"` + AdditionalProperties jsontext.Value `json:"additionalProperties"` + AllOf []jsontext.Value `json:"allOf"` + OneOf []jsontext.Value `json:"oneOf"` + AnyOf []jsontext.Value `json:"anyOf"` + resolvedRef string } // Doc reads the operation of a Spec, or of a selection of it, which keeps every component. @@ -75,12 +79,13 @@ func (s Spec) Doc(operation Operation) (OperationDoc, error) { Summary string `json:"summary"` Description string `json:"description"` Parameters []struct { - Name string `json:"name"` - In string `json:"in"` - Required bool `json:"required"` - Description string `json:"description"` - Schema schema `json:"schema"` - PathKey string `json:"x-meshstack-path-key"` + Name string `json:"name"` + In string `json:"in"` + Required bool `json:"required"` + Description string `json:"description"` + Schema jsontext.Value `json:"schema"` + PathKey string `json:"x-meshstack-path-key"` + PathKeyByVersion map[string]string `json:"x-meshstack-path-key-by-version"` } `json:"parameters"` RequestBody struct { Content object `json:"content"` @@ -92,13 +97,17 @@ func (s Spec) Doc(operation Operation) (OperationDoc, error) { } doc := OperationDoc{Summary: parsed.Summary, Description: parsed.Description} for _, parameter := range parsed.Parameters { + typeName, err := s.typeName(parameter.Schema, nil) + if err != nil { + return doc, fmt.Errorf("parameter %s: %w", parameter.Name, err) + } doc.Parameters = append(doc.Parameters, Parameter{ Name: parameter.Name, In: parameter.In, Required: parameter.Required, - Type: parameter.Schema.typeName(nil), + Type: typeName, Description: parameter.Description, - PathKey: parameter.PathKey, + PathKey: cmp.Or(parameter.PathKeyByVersion[operation.LatestApiVersion().String()], parameter.PathKey), }) } var err error @@ -152,15 +161,22 @@ func (s Spec) fields(path string, raw jsontext.Value, refs []string) ([]Field, e if resolved.Items != nil { return s.fields(path+"[]", resolved.Items, refs) } + if values := resolved.mapValues(); values != nil { + return s.fields(path+"{}", values, refs) + } var fields []Field for _, property := range resolved.Properties { child, _, err := s.resolve(property.value, refs) if err != nil { return nil, err } + typeName, err := s.typeName(property.value, refs) + if err != nil { + return nil, err + } field := Field{ Path: strings.TrimPrefix(path+"."+property.name, "."), - Type: child.typeName(s.itemsOf(child, refs)), + Type: typeName, Required: slices.Contains(resolved.Required, property.name), Description: child.Description, } @@ -173,51 +189,86 @@ func (s Spec) fields(path string, raw jsontext.Value, refs []string) ([]Field, e return fields, nil } -// resolve follows $ref into the components. A schema it cannot follow keeps its Ref. +// resolve also follows an allOf of one schema, in which the API docs wrap a $ref to describe it. func (s Spec) resolve(raw jsontext.Value, refs []string) (schema, []string, error) { var resolved schema if err := json.Unmarshal(raw, &resolved); err != nil { return resolved, refs, err } - resolvedRef := resolved.Ref - for resolved.Ref != "" && !slices.Contains(refs, resolved.Ref) { - i := slices.IndexFunc(s.components, func(c component) bool { return c.ref() == resolved.Ref }) - if i < 0 { + var resolvedRef string + for { + var next jsontext.Value + switch { + case resolved.Ref != "" && !slices.Contains(refs, resolved.Ref): + i := slices.IndexFunc(s.components, func(c component) bool { return c.ref() == resolved.Ref }) + if i < 0 { + return resolved, refs, nil + } + refs = append(slices.Clip(refs), resolved.Ref) + resolvedRef = resolved.Ref + next = s.components[i].value + case resolved.Ref == "" && len(resolved.AllOf) == 1: + next = resolved.AllOf[0] + default: + resolved.resolvedRef = resolvedRef return resolved, refs, nil } - refs = append(slices.Clip(refs), resolved.Ref) description := resolved.Description resolved = schema{} - if err := json.Unmarshal(s.components[i].value, &resolved); err != nil { + if err := json.Unmarshal(next, &resolved); err != nil { return resolved, refs, err } resolved.Description = cmp.Or(description, resolved.Description) } - resolved.resolvedRef = resolvedRef - return resolved, refs, nil } -func (s Spec) itemsOf(array schema, refs []string) *schema { - if array.Items == nil { - return nil +func (s Spec) typeName(raw jsontext.Value, refs []string) (string, error) { + if raw == nil { + return "", nil } - items, _, err := s.resolve(array.Items, refs) + resolved, refs, err := s.resolve(raw, refs) if err != nil { - return nil + return "", err } - return &items + if variants := slices.Concat(resolved.OneOf, resolved.AnyOf); len(variants) > 0 && resolved.name() == "" { + names := make([]string, len(variants)) + for i, variant := range variants { + if names[i], err = s.typeName(variant, refs); err != nil { + return "", err + } + } + return "one of " + strings.Join(names, ", "), nil + } + if values := resolved.mapValues(); values != nil { + var valueType string + valueType, err = s.typeName(values, refs) + return "map of " + cmp.Or(valueType, "any"), err + } + if resolved.Items == nil { + return resolved.name(), nil + } + items, err := s.typeName(resolved.Items, refs) + return strings.TrimSpace(resolved.name() + " of " + items), err } -func (s schema) typeName(items *schema) string { +func (s schema) name() string { name := s.Type - if _, component, isRef := strings.CutLast(cmp.Or(s.Ref, s.resolvedRef), "/"); isRef { + if _, component, isRef := strings.CutLast(cmp.Or(s.Ref, s.resolvedRef), "/"); isRef && (s.Ref != "" || s.Type == "" || s.Type == "object") { name = component } if s.Format != "" { name += " (" + s.Format + ")" } - if items != nil { - return strings.TrimSpace(name + " of " + items.typeName(nil)) - } return name } + +func (s schema) mapValues() jsontext.Value { + switch s.AdditionalProperties.Kind() { + case jsontext.KindTrue: + return jsontext.Value("{}") + case jsontext.KindBeginObject: + return s.AdditionalProperties + default: + return nil + } +} diff --git a/client/openapi/media_type.go b/client/openapi/media_type.go index 282bb966..0e5d3b16 100644 --- a/client/openapi/media_type.go +++ b/client/openapi/media_type.go @@ -51,7 +51,7 @@ func ParseMediaType(name string) MediaType { // WithKindAndApiVersion adds the kind and apiVersion a meshObject body lacks, in front, as the // meshObject API writes them. func (m MediaType) WithKindAndApiVersion(body jsontext.Value) (jsontext.Value, error) { - if m.Kind == "" || body.Kind() != '{' { + if m.Kind == "" || body.Kind() != jsontext.KindBeginObject { return body, nil } var members object diff --git a/client/openapi/object.go b/client/openapi/object.go index a6732ff2..d5f199da 100644 --- a/client/openapi/object.go +++ b/client/openapi/object.go @@ -18,11 +18,11 @@ type member struct { func (o *object) UnmarshalJSONFrom(dec *jsontext.Decoder) error { if token, err := dec.ReadToken(); err != nil { return err - } else if token.Kind() != '{' { + } else if token.Kind() != jsontext.KindBeginObject { return fmt.Errorf("expected an object, got %s", token.Kind()) } *o = (*o)[:0] - for dec.PeekKind() != '}' { + for dec.PeekKind() != jsontext.KindEndObject { token, err := dec.ReadToken() if err != nil { return err diff --git a/client/openapi/spec.go b/client/openapi/spec.go index 34ac5012..e64c1247 100644 --- a/client/openapi/spec.go +++ b/client/openapi/spec.go @@ -32,7 +32,7 @@ type Operation struct { // Action names the operation within its kind, as a command of the CLI would: list, show, // create, update, delete, or the path below the kind's object, such as trigger-run. Action string - // MediaTypes are those of the request body and of every response, each once. + // An error response carries application/json whatever the operation serves. MediaTypes []MediaType raw jsontext.Value @@ -108,8 +108,10 @@ func parseOperation(method, pathTemplate string, raw jsontext.Value) (Operation, return Operation{}, err } names := slices.Collect(maps.Keys(parsed.RequestBody.Content)) - for _, response := range parsed.Responses { - names = slices.AppendSeq(names, maps.Keys(response.Content)) + for status, response := range parsed.Responses { + if strings.HasPrefix(status, "2") { + names = slices.AppendSeq(names, maps.Keys(response.Content)) + } } slices.Sort(names) operation := Operation{Method: method, PathTemplate: PathTemplate(pathTemplate), raw: raw} @@ -139,8 +141,6 @@ func (o Operation) LatestApiVersion() ApiVersion { return versions[len(versions)-1] } -// LatestMediaType is the one of the latest version, or for an operation of no version the first, -// such as application/json. It is the one to accept, and to send a body in. func (o Operation) LatestMediaType() (MediaType, bool) { if mediaType, ok := o.MediaType(o.LatestApiVersion()); ok { return mediaType, true @@ -188,31 +188,12 @@ func (s Spec) Select(selector Selector) (Spec, error) { if selector.IsZero() { return s, nil } - matched := slices.DeleteFunc(slices.Clone(s.Operations), func(operation Operation) bool { - return !selector.matches(operation) - }) - // The templates of one method that match a path, or of one action of a kind, are versions of one - // operation, because meshStack names a path parameter differently in different versions: - // meshtenants/{tenantIdentifier} in v3 and meshtenants/{uuid} in v4. - operationKey := func(operation Operation) string { - switch { - case selector.Path != "": - return operation.Method - case operation.Kind != "": - return operation.Kind + " " + operation.Method + " " + operation.Action - default: - return operation.Method + " " + string(operation.PathTemplate) - } - } - selected := Spec{components: s.components} - for _, operations := range groupBy(matched, operationKey) { - operations = mostLiteral(operations) - var offered ApiVersions - for _, operation := range operations { - offered = append(offered, operation.ApiVersions()...) + for _, operation := range s.Operations { + if !selector.matches(operation) { + continue } - offered = offered.SortedUnique() + offered := operation.ApiVersions() version := selector.ApiVersion if len(offered) > 0 { if version.IsZero() { @@ -222,45 +203,18 @@ func (s Spec) Select(selector Selector) (Spec, error) { if selector.Path == "" { continue } - return Spec{}, fmt.Errorf("%s %s offers %s, not %s", operations[0].Method, selector.Path, offered, version) + return Spec{}, fmt.Errorf("%s %s offers %s, not %s", operation.Method, selector.Path, offered, version) } - operations = slices.DeleteFunc(operations, func(operation Operation) bool { - return !slices.Contains(operation.ApiVersions(), version) - }) } - for _, operation := range operations { - narrowed, err := operation.withVersion(version) - if err != nil { - return Spec{}, err - } - selected.Operations = append(selected.Operations, narrowed) + narrowed, err := operation.withVersion(version) + if err != nil { + return Spec{}, err } + selected.Operations = append(selected.Operations, narrowed) } return selected, nil } -// mostLiteral keeps the templates that have a literal segment where the others have a parameter. -func mostLiteral(operations []Operation) []Operation { - // The templates all match one path, so they agree on every literal segment, and a parameter - // written as "" sorts below it. - literals := func(operation Operation) []segment { - literal := operation.PathTemplate.segments() - for i, segment := range literal { - if segment.isParameter() { - literal[i] = "" - } - } - return literal - } - compare := func(a, b Operation) int { - return slices.Compare(literals(a), literals(b)) - } - most := slices.MaxFunc(operations, compare) - return slices.DeleteFunc(operations, func(operation Operation) bool { - return compare(operation, most) < 0 - }) -} - func (o Operation) withVersion(version ApiVersion) (Operation, error) { if version.IsZero() { return o, nil @@ -413,7 +367,7 @@ func (s Spec) inline(value jsontext.Value) (jsontext.Value, error) { var ref struct { Ref string `json:"$ref"` } - if value.Kind() != '{' { + if value.Kind() != jsontext.KindBeginObject { return value, nil } if err := json.Unmarshal(value, &ref); err != nil { diff --git a/client/openapi/spec_test.go b/client/openapi/spec_test.go index c4af9cb4..bc4a200e 100644 --- a/client/openapi/spec_test.go +++ b/client/openapi/spec_test.go @@ -13,22 +13,17 @@ import ( "github.com/meshcloud/meshstack-cli/internal/json" ) +const ( + runV1 = "application/vnd.meshcloud.api.meshbuildingblockrun.v1.hal+json" + tenantV3 = "application/vnd.meshcloud.api.meshtenant.v3.hal+json" + tenantV4 = "application/vnd.meshcloud.api.meshtenant.v4.hal+json" +) + func TestSpec(t *testing.T) { - document, spec := parseTestSpec(t) - selectOperations := func(t *testing.T, selector openapi.Selector) []string { - t.Helper() - selected, err := spec.Select(selector) - require.NoError(t, err) - var operations []string - for _, operation := range selected.Operations { - var mediaTypes []string - for _, mediaType := range operation.MediaTypes { - mediaTypes = append(mediaTypes, mediaType.Name) - } - operations = append(operations, operation.Method+" "+string(operation.PathTemplate)+" "+jsonString(t, mediaTypes)) - } - return operations - } + document, err := os.ReadFile("testdata/spec.json") + require.NoError(t, err) + spec := parseSpec(t, document) + selectOperations := selectOperationsOf(spec) t.Run("marshals to the document as it came without a selector", func(t *testing.T) { selected, err := spec.Select(openapi.Selector{}) @@ -42,45 +37,34 @@ func TestSpec(t *testing.T) { t.Run("selects the latest version of a path, preview included, unless a version is named", func(t *testing.T) { assert.Equal(t, []string{ - `POST /api/meshobjects/meshbuildingblocks ["application/json","application/vnd.meshcloud.api.meshbuildingblock.v2-preview.hal+json"]`, + `POST /api/meshobjects/meshbuildingblocks ["application/vnd.meshcloud.api.meshbuildingblock.v2-preview.hal+json"]`, }, selectOperations(t, openapi.Selector{Method: "post", Path: "/api/meshobjects/meshbuildingblocks"})) assert.Equal(t, []string{ - `POST /api/meshobjects/meshbuildingblocks ["application/json","application/vnd.meshcloud.api.meshbuildingblock.v1.hal+json"]`, + `POST /api/meshobjects/meshbuildingblocks ["application/vnd.meshcloud.api.meshbuildingblock.v1.hal+json"]`, }, selectOperations(t, openapi.Selector{Method: "POST", Path: "/api/meshobjects/meshbuildingblocks", ApiVersion: openapi.MustParseApiVersion("v1")})) }) - t.Run("treats two templates of one path as versions of one operation", func(t *testing.T) { + t.Run("keeps the media types of one version of an operation that offers several, and fails for another version", func(t *testing.T) { assert.Equal(t, []string{ - `GET /api/meshobjects/meshtenants/{uuid} ["application/vnd.meshcloud.api.meshtenant.v4.hal+json"]`, + `GET /api/meshobjects/meshtenants/{tenant} ["` + tenantV4 + `"]`, }, selectOperations(t, openapi.Selector{Method: "GET", Path: "/api/meshobjects/meshtenants/abc"})) assert.Equal(t, []string{ - `GET /api/meshobjects/meshtenants/{tenantIdentifier} ["application/vnd.meshcloud.api.meshtenant.v3.hal+json"]`, + `GET /api/meshobjects/meshtenants/{tenant} ["` + tenantV3 + `"]`, }, selectOperations(t, openapi.Selector{Method: "GET", Path: "/api/meshobjects/meshtenants/abc", ApiVersion: openapi.MustParseApiVersion("v3")})) _, err := spec.Select(openapi.Selector{Method: "GET", Path: "/api/meshobjects/meshtenants/abc", ApiVersion: openapi.MustParseApiVersion("v5")}) assert.EqualError(t, err, "GET /api/meshobjects/meshtenants/abc offers v3, v4, not v5") }) - t.Run("prefers a literal segment over a parameter of the same method", func(t *testing.T) { - assert.Equal(t, []string{ - `POST /api/meshobjects/meshbuildingblockruns/{blockRunUuid}/status ["application/json"]`, - }, selectOperations(t, openapi.Selector{Method: "POST", Path: "/api/meshobjects/meshbuildingblockruns/abc/status"})) - assert.Equal(t, []string{ - `POST /api/meshobjects/meshbuildingblockruns/create ["application/vnd.meshcloud.api.meshbuildingblockrun.v1.hal+json"]`, - `GET /api/meshobjects/meshbuildingblockruns/{blockRunUuid} ["application/vnd.meshcloud.api.meshbuildingblockrun.v1.hal+json"]`, - }, selectOperations(t, openapi.Selector{Path: "/api/meshobjects/meshbuildingblockruns/create"}), - "a GET of .../create reaches the run with the uuid create") - }) - t.Run("selects the latest version of each action of a kind for a method", func(t *testing.T) { assert.Equal(t, []string{ - `GET /api/meshobjects/meshbuildingblockruns/{blockRunUuid} ["application/vnd.meshcloud.api.meshbuildingblockrun.v1.hal+json"]`, - `GET /api/meshobjects/meshbuildingblockruns/{blockRunUuid}/plan-artifact ["application/octet-stream"]`, - `GET /api/meshobjects/meshtenants/{uuid} ["application/vnd.meshcloud.api.meshtenant.v4.hal+json"]`, + `GET /api/meshobjects/meshbuildingblockruns/{buildingBlockRun} ["` + runV1 + `"]`, + `GET /api/meshobjects/meshbuildingblockruns/{buildingBlockRun}/plan-artifact ["application/octet-stream"]`, + `GET /api/meshobjects/meshtenants/{tenant} ["` + tenantV4 + `"]`, }, selectOperations(t, openapi.Selector{Method: "GET"})) }) - t.Run("accepts the media type of the latest version, or the first of no version", func(t *testing.T) { + t.Run("accepts the media type of the latest version, or the first of no version, and never that of an error response", func(t *testing.T) { selected, err := spec.Select(openapi.Selector{Path: "/api/meshobjects/meshbuildingblocks"}) require.NoError(t, err) latest, ok := selected.Operations[0].LatestMediaType() @@ -88,94 +72,192 @@ func TestSpec(t *testing.T) { assert.Equal(t, "application/vnd.meshcloud.api.meshbuildingblock.v2-preview.hal+json", latest.Name) assert.Equal(t, "v2-preview", selected.Operations[0].LatestApiVersion().String()) - selected, err = spec.Select(openapi.Selector{Path: "/api/meshobjects/meshbuildingblockruns/abc/status"}) + selected, err = spec.Select(openapi.Selector{Method: "GET", Path: "/api/meshobjects/meshbuildingblockruns/abc/plan-artifact"}) require.NoError(t, err) latest, ok = selected.Operations[0].LatestMediaType() require.True(t, ok) - assert.Equal(t, "application/json", latest.Name) + assert.Equal(t, "application/octet-stream", latest.Name) assert.Empty(t, selected.Operations[0].LatestApiVersion().String()) + + selected, err = spec.Select(openapi.Selector{Method: "DELETE", Path: "/api/meshobjects/meshtenants/abc"}) + require.NoError(t, err) + _, ok = selected.Operations[0].LatestMediaType() + assert.False(t, ok) }) - t.Run("selects every method of a path, and nothing of an unknown path", func(t *testing.T) { + t.Run("selects every operation whose template matches a path, of any method, and nothing of an unknown path", func(t *testing.T) { assert.Equal(t, []string{ - `GET /api/meshobjects/meshtenants/{uuid} ["application/vnd.meshcloud.api.meshtenant.v4.hal+json"]`, - `DELETE /api/meshobjects/meshtenants/{uuid} []`, + `GET /api/meshobjects/meshtenants/{tenant} ["` + tenantV4 + `"]`, + `DELETE /api/meshobjects/meshtenants/{tenant} []`, }, selectOperations(t, openapi.Selector{Path: "/api/meshobjects/meshtenants/abc/"})) + assert.Equal(t, []string{ + `POST /api/meshobjects/meshbuildingblockruns/create ["` + runV1 + `"]`, + `GET /api/meshobjects/meshbuildingblockruns/{buildingBlockRun} ["` + runV1 + `"]`, + }, selectOperations(t, openapi.Selector{Path: "/api/meshobjects/meshbuildingblockruns/create"}), + "a GET of .../create reaches the run with the uuid create") assert.Empty(t, selectOperations(t, openapi.Selector{Path: "/api/meshobjects/meshunknowns"})) }) t.Run("names the operations of a kind below its path as the commands of the CLI do", func(t *testing.T) { assert.Equal(t, []string{"meshBuildingBlock", "meshBuildingBlockRun", "meshTenant"}, spec.Kinds()) - assert.Equal(t, []string{"create", "show", "status", "plan-artifact"}, spec.Actions("meshBuildingBlockRun"), - "POST .../create is below the path of the kind, which GET .../{blockRunUuid} shows") + assert.Equal(t, []string{"create", "show", "abort", "plan-artifact", "plan-artifact-update"}, spec.Actions("meshBuildingBlockRun"), + "POST .../create is below the path of the kind, which GET .../{buildingBlockRun} shows") assert.Equal(t, []string{ - `GET /api/meshobjects/meshtenants/{uuid} ["application/vnd.meshcloud.api.meshtenant.v4.hal+json"]`, - `DELETE /api/meshobjects/meshtenants/{uuid} []`, + `GET /api/meshobjects/meshtenants/{tenant} ["` + tenantV4 + `"]`, + `DELETE /api/meshobjects/meshtenants/{tenant} []`, }, selectOperations(t, openapi.Selector{Kind: "meshtenant"}), "the latest version of each action") assert.Equal(t, []string{ - `POST /api/meshobjects/meshbuildingblockruns/{blockRunUuid}/status ["application/json"]`, - }, selectOperations(t, openapi.Selector{Kind: "meshBuildingBlockRun", Action: "status"})) + `POST /api/meshobjects/meshbuildingblockruns/{buildingBlockRun}/abort ["` + runV1 + `"]`, + }, selectOperations(t, openapi.Selector{Kind: "meshBuildingBlockRun", Action: "abort"})) + assert.Equal(t, []string{ + `PUT /api/meshobjects/meshbuildingblockruns/{buildingBlockRun}/plan-artifact ["application/octet-stream"]`, + }, selectOperations(t, openapi.Selector{Kind: "meshBuildingBlockRun", Action: "plan-artifact-update"})) + }) + + t.Run("reads the parameters of an operation and of its path, following a $ref, with the path key of the selected version", func(t *testing.T) { + parameters := func(selector openapi.Selector) []openapi.Parameter { + selected, err := spec.Select(selector) + require.NoError(t, err) + require.Len(t, selected.Operations, 1) + doc, err := selected.Doc(selected.Operations[0]) + require.NoError(t, err) + return doc.Parameters + } + assert.Equal(t, []openapi.Parameter{ + {Name: "buildingBlockRun", In: "path", Required: true, Type: "string (uuid)", Description: "The UUID of the meshBuildingBlockRun.", PathKey: "metadata.uuid"}, + }, parameters(openapi.Selector{Method: "GET", Path: "/api/meshobjects/meshbuildingblockruns/abc/plan-artifact"})) + assert.Equal(t, []openapi.Parameter{ + {Name: "tenant", In: "path", Required: true, Type: "string", Description: "DELETE takes the UUID or the full tenant identifier.", PathKey: "metadata.uuid"}, + {Name: "purge", In: "query", Type: "boolean", Description: "Removes the meshTenant from meshStack at once."}, + }, parameters(openapi.Selector{Method: "DELETE", Path: "/api/meshobjects/meshtenants/abc"})) + assert.Equal(t, "metadata.uuid", parameters(openapi.Selector{Method: "GET", Path: "/api/meshobjects/meshtenants/abc"})[0].PathKey) + assert.Equal(t, "metadata.tenantIdentifier", + parameters(openapi.Selector{Method: "GET", Path: "/api/meshobjects/meshtenants/abc", ApiVersion: openapi.MustParseApiVersion("v3")})[0].PathKey) }) selected, selectErr := spec.Select(openapi.Selector{Method: "POST", Path: "/api/meshobjects/meshbuildingblocks", ApiVersion: openapi.MustParseApiVersion("v1")}) require.NoError(t, selectErr) - t.Run("marshals a selection to its operations and the components they reference", func(t *testing.T) { + t.Run("marshals a selection to its operations, with each $ref response in place, and the components they reference", func(t *testing.T) { out, err := json.Marshal(selected) require.NoError(t, err) assert.JSONEq(t, `{ "paths": { "/api/meshobjects/meshbuildingblocks": { "post": { - "summary": "Create a building block", - "description": "Creates a building block.", + "tags": ["Building Blocks"], + "summary": "Create building block", + "description": "Create a new meshBuildingBlock with inputs and parent building block relationships", "operationId": "meshBuildingBlockPost", - "parameters": [{"name": "Accept", "in": "header", "required": true, "schema": {"type": "string"}}], - "requestBody": {"content": {"application/vnd.meshcloud.api.meshbuildingblock.v1.hal+json": {"schema": {"$ref": "#/components/schemas/blockV1"}}}}, + "requestBody": { + "content": { + "application/vnd.meshcloud.api.meshbuildingblock.v1.hal+json": { + "schema": {"$ref": "#/components/schemas/MeshBuildingBlockV1Request"}, + "x-meshstack-lifecycle": {"meshObject": "meshBuildingBlock.v1", "state": "GA", "notice": "v2 also supports building blocks on workspace level."} + } + }, + "required": true + }, "responses": { - "201": {"description": "201", "content": {"application/vnd.meshcloud.api.meshbuildingblock.v1.hal+json": {"schema": {"$ref": "#/components/schemas/blockV1"}}}}, - "400": {"description": "400", "content": {"application/json": {"schema": {"type": "object"}}}} - } + "201": { + "description": "Building block created", + "content": {"application/vnd.meshcloud.api.meshbuildingblock.v1.hal+json": {"x-meshstack-lifecycle": {"meshObject": "meshBuildingBlock.v1", "state": "GA"}}} + }, + "400": { + "description": "The request is invalid. The message names the invalid part.", + "content": {"application/json": {"schema": {"$ref": "#/components/schemas/CustomErrorMessage"}}} + } + }, + "x-position": 8 } } }, "components": { "schemas": { - "blockV1": {"type": "object", "properties": {"spec": {"$ref": "#/components/schemas/specV1"}}}, - "specV1": { + "CustomErrorMessage": { + "required": ["errorCode", "message"], + "type": "object", + "properties": {"errorCode": {"type": "string"}, "message": {"type": "string", "description": "A message that describes the error."}}, + "description": "The body of every error response." + }, + "MeshBuildingBlockIOV1": { + "required": ["key"], "type": "object", - "required": ["name"], "properties": { - "name": {"type": "string", "description": "The name."}, - "tags": {"type": "array", "items": {"$ref": "#/components/schemas/tagV1"}}, - "parent": {"$ref": "#/components/schemas/specV1"} + "key": {"type": "string", "description": "The key of the input as set on the related Building Block Definition."}, + "value": {"description": "The value, which is set on this input.", "nullable": true, "oneOf": [{"type": "string"}, {"$ref": "#/components/schemas/integer_int64"}, {"type": "boolean"}, {"$ref": "#/components/schemas/array_string_0"}]} } }, - "tagV1": {"type": "object", "properties": {"key": {"type": "string", "format": "uuid"}}} + "MeshBuildingBlockSpecV1": { + "required": ["displayName", "parentBuildingBlocks"], + "type": "object", + "properties": { + "displayName": {"type": "string", "description": "The display name of the Building Block."}, + "parentBuildingBlocks": {"description": "The parent building blocks.", "allOf": [{"$ref": "#/components/schemas/array_MeshParentBuildingBlock"}]}, + "inputs": {"description": "List of inputs, which are set on the Building Block.", "allOf": [{"$ref": "#/components/schemas/array_MeshBuildingBlockIOV1"}]} + } + }, + "MeshBuildingBlockV1Request": { + "required": ["kind", "spec"], + "type": "object", + "properties": { + "kind": {"type": "string", "enum": ["meshBuildingBlock"]}, + "apiVersion": {"type": "string", "enum": ["v1"]}, + "spec": {"description": "All fields in this section describe the Building Block.", "allOf": [{"$ref": "#/components/schemas/MeshBuildingBlockSpecV1"}]} + } + }, + "MeshParentBuildingBlock": { + "required": ["buildingBlockUuid"], + "type": "object", + "properties": {"buildingBlockUuid": {"description": "The UUID of the parent Building Block.", "allOf": [{"$ref": "#/components/schemas/string_uuid"}]}} + }, + "array_MeshBuildingBlockIOV1": {"type": "array", "items": {"$ref": "#/components/schemas/MeshBuildingBlockIOV1"}}, + "array_MeshParentBuildingBlock": {"type": "array", "items": {"$ref": "#/components/schemas/MeshParentBuildingBlock"}}, + "array_string_0": {"type": "array", "items": {"type": "string"}}, + "integer_int64": {"type": "integer", "format": "int64"}, + "string_uuid": {"type": "string", "format": "uuid"} } } }`, string(out)) }) - t.Run("reads an operation's parameters and the fields of its bodies, naming a referenced schema, up to a schema that contains itself", func(t *testing.T) { + t.Run("reads the fields of an operation's bodies, naming a referenced schema and each variant of a oneOf", func(t *testing.T) { doc, err := selected.Doc(selected.Operations[0]) require.NoError(t, err) - assert.Equal(t, "Create a building block", doc.Summary) - assert.Equal(t, []openapi.Parameter{{Name: "Accept", In: "header", Required: true, Type: "string"}}, doc.Parameters) - fields := []openapi.Field{ - {Path: "spec", Type: "specV1"}, - {Path: "spec.name", Type: "string", Required: true, Description: "The name."}, - {Path: "spec.tags", Type: "array of tagV1"}, - {Path: "spec.tags[].key", Type: "string (uuid)"}, - {Path: "spec.parent", Type: "specV1"}, - } - assert.Equal(t, []openapi.Body{{MediaType: "application/vnd.meshcloud.api.meshbuildingblock.v1.hal+json", Fields: fields}}, doc.RequestBodies) + assert.Equal(t, "Create building block", doc.Summary) + assert.Empty(t, doc.Parameters) + assert.Equal(t, []openapi.Body{{MediaType: "application/vnd.meshcloud.api.meshbuildingblock.v1.hal+json", Fields: []openapi.Field{ + {Path: "kind", Type: "string", Required: true}, + {Path: "apiVersion", Type: "string"}, + {Path: "spec", Type: "MeshBuildingBlockSpecV1", Required: true, Description: "All fields in this section describe the Building Block."}, + {Path: "spec.displayName", Type: "string", Required: true, Description: "The display name of the Building Block."}, + {Path: "spec.parentBuildingBlocks", Type: "array of MeshParentBuildingBlock", Required: true, Description: "The parent building blocks."}, + {Path: "spec.parentBuildingBlocks[].buildingBlockUuid", Type: "string (uuid)", Required: true, Description: "The UUID of the parent Building Block."}, + {Path: "spec.inputs", Type: "array of MeshBuildingBlockIOV1", Description: "List of inputs, which are set on the Building Block."}, + {Path: "spec.inputs[].key", Type: "string", Required: true, Description: "The key of the input as set on the related Building Block Definition."}, + {Path: "spec.inputs[].value", Type: "one of string, integer (int64), boolean, array of string", Description: "The value, which is set on this input."}, + }}}, doc.RequestBodies) assert.Equal(t, []openapi.Response{ - {Status: "201", Description: "201", Bodies: []openapi.Body{{MediaType: "application/vnd.meshcloud.api.meshbuildingblock.v1.hal+json", Fields: fields}}}, - {Status: "400", Description: "400", Bodies: []openapi.Body{{MediaType: "application/json"}}}, + {Status: "201", Description: "Building block created", Bodies: []openapi.Body{{MediaType: "application/vnd.meshcloud.api.meshbuildingblock.v1.hal+json"}}}, + {Status: "400", Description: "The request is invalid. The message names the invalid part.", Bodies: []openapi.Body{{MediaType: "application/json", Fields: []openapi.Field{ + {Path: "errorCode", Type: "string", Required: true}, + {Path: "message", Type: "string", Required: true, Description: "A message that describes the error."}, + }}}}, }, doc.Responses) }) + t.Run("reads the fields of a map's values below the map", func(t *testing.T) { + v2Preview, err := spec.Select(openapi.Selector{Method: "POST", Path: "/api/meshobjects/meshbuildingblocks"}) + require.NoError(t, err) + doc, err := v2Preview.Doc(v2Preview.Operations[0]) + require.NoError(t, err) + assert.Equal(t, []openapi.Field{ + {Path: "spec.inputs", Type: "map of MeshBuildingBlockInput", Required: true, Description: "Map of input keys to their input data."}, + {Path: "spec.inputs{}.value", Type: "one of string, integer (int64), boolean, array of string", Description: "The value of this input."}, + {Path: "spec.inputs{}.isOptional", Type: "boolean", Required: true, Description: "Whether the Building Block Definition allows this input to be left unset."}, + }, doc.RequestBodies[0].Fields[3:]) + }) + t.Run("adds the kind and apiVersion a body lacks, with the kind in camel case", func(t *testing.T) { mediaType, ok := selected.Operations[0].MediaType(openapi.MustParseApiVersion("v1")) require.True(t, ok) @@ -189,6 +271,29 @@ func TestSpec(t *testing.T) { }) } +func TestDocOfASchemaThatContainsItself(t *testing.T) { + spec := parseSpec(t, []byte(`{ + "openapi": "3.0.1", + "paths": { + "/api/nodes": { + "get": {"responses": {"200": {"description": "200", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/node"}}}}}} + } + }, + "components": { + "schemas": { + "node": {"type": "object", "properties": {"name": {"type": "string"}, "parent": {"allOf": [{"$ref": "#/components/schemas/node"}]}, "children": {"type": "object", "additionalProperties": {"$ref": "#/components/schemas/node"}}}} + } + } + }`)) + doc, err := spec.Doc(spec.Operations[0]) + require.NoError(t, err) + assert.Equal(t, []openapi.Response{{Status: "200", Description: "200", Bodies: []openapi.Body{{MediaType: "application/json", Fields: []openapi.Field{ + {Path: "name", Type: "string"}, + {Path: "parent", Type: "node"}, + {Path: "children", Type: "map of node"}, + }}}}}, doc.Responses) +} + func TestApiVersion(t *testing.T) { versions := []string{"v1", "v2-preview", "v2", "v10"} for i := range len(versions) - 1 { @@ -200,13 +305,28 @@ func TestApiVersion(t *testing.T) { } } -func parseTestSpec(t *testing.T) ([]byte, openapi.Spec) { +func parseSpec(t *testing.T, document []byte) openapi.Spec { t.Helper() - document, err := os.ReadFile("testdata/spec.json") - require.NoError(t, err) spec, err := openapi.Parse(bytes.NewReader(document)) require.NoError(t, err) - return document, spec + return spec +} + +func selectOperationsOf(spec openapi.Spec) func(t *testing.T, selector openapi.Selector) []string { + return func(t *testing.T, selector openapi.Selector) []string { + t.Helper() + selected, err := spec.Select(selector) + require.NoError(t, err) + var operations []string + for _, operation := range selected.Operations { + var mediaTypes []string + for _, mediaType := range operation.MediaTypes { + mediaTypes = append(mediaTypes, mediaType.Name) + } + operations = append(operations, operation.Method+" "+string(operation.PathTemplate)+" "+jsonString(t, mediaTypes)) + } + return operations + } } func jsonString(t *testing.T, value any) string { diff --git a/client/openapi/testdata/spec.json b/client/openapi/testdata/spec.json index ff85c116..2e7ebc5f 100644 --- a/client/openapi/testdata/spec.json +++ b/client/openapi/testdata/spec.json @@ -1,91 +1,230 @@ { "openapi": "3.0.1", + "info": {"title": "meshStack API documentation", "version": "1.0.0"}, + "x-meshstack-retired-endpoints": [ + {"method": "GET", "path": "/api/meshobjects/meshcustomers", "mediaType": "application/vnd.meshcloud.api.meshcustomer.v1.hal+json", "meshObject": "meshCustomer.v1", "state": "Retired", "retiredAfter": "2025-03-01", "notice": "Use `meshWorkspace`."} + ], + "x-meshstack-retired-meshobjects": [ + {"meshObject": "meshCustomer.v1", "state": "Retired", "retiredAfter": "2025-03-01", "notice": "Use `meshWorkspace`."} + ], "paths": { - "/api/meshobjects/meshbuildingblocks": { - "post": { - "summary": "Create a building block", - "description": "Creates a building block.", - "operationId": "meshBuildingBlockPost", - "parameters": [{"name": "Accept", "in": "header", "required": true, "schema": {"type": "string"}}], - "requestBody": { - "content": { - "application/vnd.meshcloud.api.meshbuildingblock.v1.hal+json": {"schema": {"$ref": "#/components/schemas/blockV1"}}, - "application/vnd.meshcloud.api.meshbuildingblock.v2-preview.hal+json": {"schema": {"$ref": "#/components/schemas/blockV2"}} - } - }, - "responses": { - "201": { - "description": "201", - "content": { - "application/vnd.meshcloud.api.meshbuildingblock.v1.hal+json": {"schema": {"$ref": "#/components/schemas/blockV1"}}, - "application/vnd.meshcloud.api.meshbuildingblock.v2-preview.hal+json": {"schema": {"$ref": "#/components/schemas/blockV2"}} - } - }, - "400": {"description": "400", "content": {"application/json": {"schema": {"type": "object"}}}} - } - } - }, "/api/meshobjects/meshbuildingblockruns/create": { "post": { + "tags": ["Building Block Runs"], + "summary": "Fetch a pending building block run", "operationId": "meshBuildingBlockRunCreate", - "responses": {"201": {"description": "201", "content": {"application/vnd.meshcloud.api.meshbuildingblockrun.v1.hal+json": {}}}} + "parameters": [{"name": "forRunnerUuid", "in": "query", "required": true, "schema": {"$ref": "#/components/schemas/string_uuid"}}], + "responses": { + "201": { + "description": "The pending building block run, now assigned to the runner", + "content": {"application/vnd.meshcloud.api.meshbuildingblockrun.v1.hal+json": {"x-meshstack-lifecycle": {"meshObject": "meshBuildingBlockRun.v1", "state": "GA"}}} + } + }, + "x-position": 25 } }, - "/api/meshobjects/meshbuildingblockruns/{blockRunUuid}": { + "/api/meshobjects/meshbuildingblockruns/{buildingBlockRun}": { "get": { - "operationId": "meshBuildingBlockRun", - "responses": {"200": {"description": "200", "content": {"application/vnd.meshcloud.api.meshbuildingblockrun.v1.hal+json": {}}}} + "tags": ["Building Block Runs"], + "summary": "Get building block run", + "operationId": "meshBuildingBlockRunGet", + "parameters": [{"$ref": "#/components/parameters/buildingBlockRun_0"}], + "responses": { + "200": { + "description": "The building block run", + "content": {"application/vnd.meshcloud.api.meshbuildingblockrun.v1.hal+json": {"x-meshstack-lifecycle": {"meshObject": "meshBuildingBlockRun.v1", "state": "GA"}}} + } + }, + "x-position": 24 } }, - "/api/meshobjects/meshbuildingblockruns/{blockRunUuid}/status": { + "/api/meshobjects/meshbuildingblockruns/{buildingBlockRun}/abort": { "post": { - "operationId": "meshBuildingBlockRunStatus", - "responses": {"200": {"description": "200", "content": {"application/json": {}}}} + "tags": ["Building Block Runs"], + "summary": "Abort building block run", + "operationId": "meshBuildingBlockRunAbort", + "parameters": [{"$ref": "#/components/parameters/buildingBlockRun_0"}], + "responses": { + "202": { + "description": "Abort accepted", + "content": {"application/vnd.meshcloud.api.meshbuildingblockrun.v1.hal+json": {"x-meshstack-lifecycle": {"meshObject": "meshBuildingBlockRun.v1", "state": "GA"}}} + } + }, + "x-position": 26 } }, - "/api/meshobjects/meshbuildingblockruns/{blockRunUuid}/plan-artifact": { + "/api/meshobjects/meshbuildingblockruns/{buildingBlockRun}/plan-artifact": { + "parameters": [{"$ref": "#/components/parameters/buildingBlockRun_0"}], "get": { - "operationId": "meshBuildingBlockRunPlanArtifact", - "responses": {"200": {"description": "200", "content": {"application/octet-stream": {}}}} + "tags": ["Building Block Runs"], + "summary": "Download plan artifact of building block run (deprecated)", + "operationId": "meshBuildingBlockRunDownloadPlanArtifact", + "responses": { + "200": { + "description": "The predecessor artifact of the building block run", + "content": {"application/octet-stream": {"schema": {"$ref": "#/components/schemas/string_binary"}, "x-meshstack-lifecycle": {"state": "Deprecated", "retiredAfter": "2027-01-01"}}} + }, + "400": {"$ref": "#/components/responses/BadRequest"} + }, + "deprecated": true, + "x-position": 31 + }, + "put": { + "tags": ["Building Block Runs"], + "summary": "Upload plan artifact of building block run (deprecated)", + "operationId": "meshBuildingBlockRunUploadPlanArtifact", + "requestBody": {"content": {"application/octet-stream": {"schema": {"$ref": "#/components/schemas/string_binary"}}}, "required": true}, + "responses": {"204": {"description": "No Content"}}, + "deprecated": true, + "x-position": 32 } }, - "/api/meshobjects/meshbuildingblockruns/{blockRunUuid}/{part}": { + "/api/meshobjects/meshbuildingblocks": { "post": { - "operationId": "meshBuildingBlockRunPart", - "responses": {"200": {"description": "200"}} + "tags": ["Building Blocks"], + "summary": "Create building block", + "description": "Create a new meshBuildingBlock with inputs and parent building block relationships", + "operationId": "meshBuildingBlockPost", + "requestBody": { + "content": { + "application/vnd.meshcloud.api.meshbuildingblock.v2-preview.hal+json": { + "schema": {"$ref": "#/components/schemas/MeshBuildingBlockV2Request"}, + "examples": {"meshWorkspace": {"$ref": "#/components/examples/MeshBuildingBlockV2Request-meshWorkspace"}}, + "x-meshstack-lifecycle": {"meshObject": "meshBuildingBlock.v2-preview", "state": "Preview"} + }, + "application/vnd.meshcloud.api.meshbuildingblock.v1.hal+json": { + "schema": {"$ref": "#/components/schemas/MeshBuildingBlockV1Request"}, + "x-meshstack-lifecycle": {"meshObject": "meshBuildingBlock.v1", "state": "GA", "notice": "v2 also supports building blocks on workspace level."} + } + }, + "required": true + }, + "responses": { + "201": { + "description": "Building block created", + "content": { + "application/vnd.meshcloud.api.meshbuildingblock.v2-preview.hal+json": {"x-meshstack-lifecycle": {"meshObject": "meshBuildingBlock.v2-preview", "state": "Preview"}}, + "application/vnd.meshcloud.api.meshbuildingblock.v1.hal+json": {"x-meshstack-lifecycle": {"meshObject": "meshBuildingBlock.v1", "state": "GA"}} + } + }, + "400": {"$ref": "#/components/responses/BadRequest"} + }, + "x-position": 8 } }, - "/api/meshobjects/meshtenants/{tenantIdentifier}": { + "/api/meshobjects/meshtenants/{tenant}": { "get": { - "operationId": "meshTenantV3", - "responses": {"200": {"description": "200", "content": {"application/vnd.meshcloud.api.meshtenant.v3.hal+json": {}}}} - } - }, - "/api/meshobjects/meshtenants/{uuid}": { - "delete": { - "operationId": "meshTenantDeleteV4", - "responses": {"202": {"description": "202"}} + "tags": ["Tenants"], + "summary": "Get tenant", + "operationId": "meshTenantGet", + "parameters": [{"name": "tenant", "in": "path", "required": true, "schema": {"type": "string"}, "x-meshstack-path-key": "metadata.uuid", "x-meshstack-path-key-by-version": {"v3": "metadata.tenantIdentifier"}}], + "responses": { + "200": { + "description": "The tenant", + "content": { + "application/vnd.meshcloud.api.meshtenant.v4.hal+json": {"x-meshstack-lifecycle": {"meshObject": "meshTenant.v4", "state": "GA"}}, + "application/vnd.meshcloud.api.meshtenant.v3.hal+json": {"x-meshstack-lifecycle": {"meshObject": "meshTenant.v3", "state": "Outdated", "latest": "meshTenant.v4"}} + } + } + }, + "x-position": 110 }, - "get": { - "operationId": "meshTenantV4", - "responses": {"200": {"description": "200", "content": {"application/vnd.meshcloud.api.meshtenant.v4.hal+json": {}}}} + "delete": { + "tags": ["Tenants"], + "summary": "Delete tenant", + "operationId": "meshTenantDelete", + "parameters": [ + {"name": "tenant", "in": "path", "description": "DELETE takes the UUID or the full tenant identifier.", "required": true, "schema": {"type": "string"}, "x-meshstack-path-key": "metadata.uuid"}, + {"name": "purge", "in": "query", "description": "Removes the meshTenant from meshStack at once.", "required": false, "schema": {"type": "boolean"}} + ], + "responses": { + "202": {"description": "Deletion of tenant started"}, + "400": {"$ref": "#/components/responses/BadRequest"} + }, + "x-position": 112 } } }, "components": { "schemas": { - "blockV1": {"type": "object", "properties": {"spec": {"$ref": "#/components/schemas/specV1"}}}, - "specV1": { + "CustomErrorMessage": { + "required": ["errorCode", "message"], + "type": "object", + "properties": {"errorCode": {"type": "string"}, "message": {"type": "string", "description": "A message that describes the error."}}, + "description": "The body of every error response." + }, + "MeshBuildingBlockIOV1": { + "required": ["key"], + "type": "object", + "properties": { + "key": {"type": "string", "description": "The key of the input as set on the related Building Block Definition."}, + "value": {"description": "The value, which is set on this input.", "nullable": true, "oneOf": [{"type": "string"}, {"$ref": "#/components/schemas/integer_int64"}, {"type": "boolean"}, {"$ref": "#/components/schemas/array_string_0"}]} + } + }, + "MeshBuildingBlockSpecV1": { + "required": ["displayName", "parentBuildingBlocks"], "type": "object", - "required": ["name"], "properties": { - "name": {"type": "string", "description": "The name."}, - "tags": {"type": "array", "items": {"$ref": "#/components/schemas/tagV1"}}, - "parent": {"$ref": "#/components/schemas/specV1"} + "displayName": {"type": "string", "description": "The display name of the Building Block."}, + "parentBuildingBlocks": {"description": "The parent building blocks.", "allOf": [{"$ref": "#/components/schemas/array_MeshParentBuildingBlock"}]}, + "inputs": {"description": "List of inputs, which are set on the Building Block.", "allOf": [{"$ref": "#/components/schemas/array_MeshBuildingBlockIOV1"}]} } }, - "tagV1": {"type": "object", "properties": {"key": {"type": "string", "format": "uuid"}}}, - "blockV2": {"type": "object"} + "MeshBuildingBlockV1Request": { + "required": ["kind", "spec"], + "type": "object", + "properties": { + "kind": {"type": "string", "enum": ["meshBuildingBlock"]}, + "apiVersion": {"type": "string", "enum": ["v1"]}, + "spec": {"description": "All fields in this section describe the Building Block.", "allOf": [{"$ref": "#/components/schemas/MeshBuildingBlockSpecV1"}]} + } + }, + "MeshBuildingBlockV2Request": { + "required": ["kind", "spec"], + "type": "object", + "properties": { + "kind": {"type": "string", "enum": ["meshBuildingBlock"]}, + "apiVersion": {"type": "string", "enum": ["v2-preview"]}, + "spec": {"description": "All fields in this section describe the Building Block.", "allOf": [{"$ref": "#/components/schemas/MeshBuildingBlockSpecV2"}]} + } + }, + "MeshBuildingBlockSpecV2": { + "required": ["inputs"], + "type": "object", + "properties": {"inputs": {"description": "Map of input keys to their input data.", "allOf": [{"$ref": "#/components/schemas/MapOfMeshBuildingBlockInput"}]}} + }, + "MapOfMeshBuildingBlockInput": {"type": "object", "additionalProperties": {"$ref": "#/components/schemas/MeshBuildingBlockInput"}}, + "MeshBuildingBlockInput": { + "required": ["isOptional"], + "type": "object", + "properties": { + "value": {"description": "The value of this input.", "nullable": true, "oneOf": [{"type": "string"}, {"$ref": "#/components/schemas/integer_int64"}, {"type": "boolean"}, {"$ref": "#/components/schemas/array_string_0"}]}, + "isOptional": {"type": "boolean", "description": "Whether the Building Block Definition allows this input to be left unset.", "readOnly": true} + } + }, + "MeshParentBuildingBlock": { + "required": ["buildingBlockUuid"], + "type": "object", + "properties": {"buildingBlockUuid": {"description": "The UUID of the parent Building Block.", "allOf": [{"$ref": "#/components/schemas/string_uuid"}]}} + }, + "array_MeshBuildingBlockIOV1": {"type": "array", "items": {"$ref": "#/components/schemas/MeshBuildingBlockIOV1"}}, + "array_MeshParentBuildingBlock": {"type": "array", "items": {"$ref": "#/components/schemas/MeshParentBuildingBlock"}}, + "array_string_0": {"type": "array", "items": {"type": "string"}}, + "integer_int64": {"type": "integer", "format": "int64"}, + "string_binary": {"type": "string", "format": "binary"}, + "string_uuid": {"type": "string", "format": "uuid"} + }, + "responses": { + "BadRequest": { + "description": "The request is invalid. The message names the invalid part.", + "content": {"application/json": {"schema": {"$ref": "#/components/schemas/CustomErrorMessage"}}} + } + }, + "parameters": { + "buildingBlockRun_0": {"name": "buildingBlockRun", "in": "path", "description": "The UUID of the meshBuildingBlockRun.", "required": true, "schema": {"type": "string", "format": "uuid"}, "x-meshstack-path-key": "metadata.uuid"} + }, + "examples": { + "MeshBuildingBlockV2Request-meshWorkspace": {"summary": "`spec.targetRef.kind` is `meshWorkspace`.", "value": {"kind": "meshBuildingBlock", "apiVersion": "v2-preview"}} } } } diff --git a/cmd/api/api.go b/cmd/api/api.go index 569ca21e..e8a7c339 100644 --- a/cmd/api/api.go +++ b/cmd/api/api.go @@ -51,8 +51,7 @@ To see what the API docs say about the request, run the same command line with ' return err } ctx := cmd.Context() - // Resolved before the API docs, whose first download takes a while, so that a missing - // login fails at once. + // Resolved first, so that a missing login fails before the API docs download. meshStack, err := internal.ResolveClient(ctx, internal.WithSettingSources(r.originAsEndpoint())) if err != nil { return err @@ -60,8 +59,7 @@ To see what the API docs say about the request, run the same command line with ' if r.target.IsAbs() && !strings.EqualFold(r.origin(), meshStack.Endpoint.String()) { return fmt.Errorf("%s is not at the endpoint %s of this command; leave out --%s", r.target.Redacted(), meshStack.Endpoint, internal.EndpointFlag.Name) } - spec, wait, err := flags.loadApiDocs(cmd, meshStack.Endpoint) - defer wait() + spec, err := flags.loadApiDocs(cmd, meshStack.Endpoint) if err != nil { slog.WarnContext(ctx, fmt.Sprintf("Sending the request unchanged, because the API docs are not available: %s. "+ "Run %s to see why.", err, docsCommand(cmd, args))) diff --git a/cmd/api/api_test.go b/cmd/api/api_test.go index 2962087d..7d57fbb1 100644 --- a/cmd/api/api_test.go +++ b/cmd/api/api_test.go @@ -6,7 +6,9 @@ import ( "io" gohttp "net/http" "os" + "path/filepath" "strings" + "sync/atomic" "testing" "github.com/spf13/cobra" @@ -29,12 +31,10 @@ const ( ) func TestApi(t *testing.T) { - meshStack := newFakeMeshStack(t) - testlogin.LoggedInTo(t, meshStack.URL) apiDocs, err := os.ReadFile(apiDocsFile) require.NoError(t, err) - docs := fakemeshstack.Start(t, fakemeshstack.Options{ApiDocs: apiDocs}) - t.Setenv("MESHSTACK_API_DOCS_URL", docs.URL+fakemeshstack.ApiDocsPath) + meshStack := newFakeMeshStack(t, apiDocs) + testlogin.LoggedInTo(t, meshStack.URL) postBlock := func(t *testing.T, body string, args ...string) (recordedRequest, error) { t.Helper() _, err := meshStack.run(t, api.New(), body, append([]string{"-X", "POST", "/api/meshobjects/meshbuildingblocks", "--request-json", "-"}, args...)...) @@ -66,12 +66,12 @@ func TestApi(t *testing.T) { t.Run("fails without a login before it downloads the API docs", func(t *testing.T) { t.Setenv(config.DirectorySetting.EnvKey(), t.TempDir()) t.Setenv(auth.ApiTokenSetting.EnvKey(), "") - docs.TakeRequests() + docsRequests := meshStack.docsRequests.Load() _, err := meshStack.run(t, api.New(), "", "/api/meshobjects/meshbuildingblocks") require.ErrorContains(t, err, "no credential for the endpoint") - assert.Empty(t, docs.TakeRequests()) + assert.Equal(t, docsRequests, meshStack.docsRequests.Load()) assert.Empty(t, meshStack.requests) }) @@ -141,17 +141,12 @@ func TestApi(t *testing.T) { } }) - t.Run("points to api-docs on a 404 only for a path the API docs do not list", func(t *testing.T) { - for path, wantError := range map[string]string{ - "/api/x": "meshStack answered HTTP 404: gone (errorCode NotFound). Run meshstack api-docs /api/x -X GET -H 'Accept: application/json' to see what the API expects", - "/api/meshobjects/meshtenants/0c9ef6d1-5c5d-4b0c-9a4b-1e0e3c1f2a3b": "meshStack answered HTTP 404: gone (errorCode NotFound)", - } { - meshStack.answer(gohttp.StatusNotFound, `{"errorCode":"NotFound","message":"gone"}`) + t.Run("points to api-docs on a 404 for a path the API docs do not list", func(t *testing.T) { + meshStack.answer(gohttp.StatusNotFound, `{"errorCode":"NotFound","message":"gone"}`) - _, err := meshStack.run(t, api.New(), "", path, "-H", "Accept: application/json") + _, err := meshStack.run(t, api.New(), "", "/api/x", "-H", "Accept: application/json") - require.EqualError(t, err, wantError) - } + require.EqualError(t, err, "meshStack answered HTTP 404: gone (errorCode NotFound). Run meshstack api-docs /api/x -X GET -H 'Accept: application/json' to see what the API expects") }) t.Run("adds the clientVersionHint of a failed answer to the error", func(t *testing.T) { @@ -198,7 +193,7 @@ func TestApi(t *testing.T) { require.NoError(t, err) assert.Contains(t, stdout, "| POST | `/api/meshobjects/meshbuildingblocks` | v1, v2-preview |") - assert.Contains(t, stdout, "| GET, DELETE | `/api/meshobjects/meshtenants/{uuid}` | v4 |") + assert.Contains(t, stdout, "| GET, DELETE | `/api/meshobjects/meshtenants/{tenant}` | v3, v4 |") stdout, err = meshStack.run(t, api.NewDocs(), "", "-o", "json") @@ -210,7 +205,7 @@ func TestApi(t *testing.T) { stdout, err := meshStack.run(t, api.NewDocs(), "", "-X", "DELETE") require.NoError(t, err) - assert.Equal(t, "| Methods | Path | API versions |\n|---|---|---|\n| DELETE | `/api/meshobjects/meshtenants/{uuid}` | |\n", stdout) + assert.Equal(t, "| Methods | Path | API versions |\n|---|---|---|\n| DELETE | `/api/meshobjects/meshtenants/{tenant}` | |\n", stdout) _, err = meshStack.run(t, api.NewDocs(), "", "-X", "PATCH") @@ -235,7 +230,8 @@ func TestApi(t *testing.T) { require.NoError(t, err) assert.Contains(t, stdout, "# meshBuildingBlock\n\n## create: `POST /api/meshobjects/meshbuildingblocks`\n\n"+ - "API version "+request.wantVersion+"\n\n**Create a building block**\n\nCreates a building block.\n\n### Parameters", request.args) + "API version "+request.wantVersion+"\n\n**Create building block**\n\n"+ + "Create a new meshBuildingBlock with inputs and parent building block relationships\n\n### Request body", request.args) assert.Contains(t, stdout, "### Request body `application/vnd.meshcloud.api.meshbuildingblock."+request.wantVersion+".hal+json`", request.args) } }) @@ -245,14 +241,23 @@ func TestApi(t *testing.T) { require.NoError(t, err) assert.Equal(t, "# meshTenant\n\n"+ - "## show: `GET /api/meshobjects/meshtenants/{uuid}`\n\nAPI version v4\n\n"+ + "## show: `GET /api/meshobjects/meshtenants/{tenant}`\n\nAPI version v4\n\n**Get tenant**\n\n"+ + "### Parameters\n\n| Name | In | Type | Required | Description |\n|---|---|---|---|---|\n"+ + "| `tenant` | path | string | yes | |\n\n"+ "### Response 200 `application/vnd.meshcloud.api.meshtenant.v4.hal+json`\n\n"+ - "## delete: `DELETE /api/meshobjects/meshtenants/{uuid}`\n\nNo API version\n\n### Response 202\n", stdout) + "## delete: `DELETE /api/meshobjects/meshtenants/{tenant}`\n\nNo API version\n\n**Delete tenant**\n\n"+ + "### Parameters\n\n| Name | In | Type | Required | Description |\n|---|---|---|---|---|\n"+ + "| `tenant` | path | string | yes | DELETE takes the UUID or the full tenant identifier. |\n"+ + "| `purge` | query | boolean | | Removes the meshTenant from meshStack at once. |\n\n"+ + "### Response 202\n\n"+ + "### Response 400 `application/json`\n\n| Field | Type | Required | Description |\n|---|---|---|---|\n"+ + "| `errorCode` | string | yes | |\n| `message` | string | yes | A message that describes the error. |\n", stdout) stdout, err = meshStack.run(t, api.NewDocs(), "", "-X", "GET", "/api/meshobjects/meshtenants/abc", "--api-version", "v3") require.NoError(t, err) - assert.Contains(t, stdout, "## show: `GET /api/meshobjects/meshtenants/{tenantIdentifier}`\n\nAPI version v3\n") + assert.Contains(t, stdout, "## show: `GET /api/meshobjects/meshtenants/{tenant}`\n\nAPI version v3\n") + assert.Contains(t, stdout, "### Response 200 `application/vnd.meshcloud.api.meshtenant.v3.hal+json`\n") assert.NotContains(t, stdout, "DELETE") }) @@ -260,9 +265,13 @@ func TestApi(t *testing.T) { stdout, err := meshStack.run(t, api.NewDocs(), "", "/api/meshobjects/meshtenants/abc", "-X", "GET", "-o", "json") require.NoError(t, err) - assert.JSONEq(t, `{"paths": {"/api/meshobjects/meshtenants/{uuid}": {"get": { - "operationId": "meshTenantV4", - "responses": {"200": {"description": "200", "content": {"application/vnd.meshcloud.api.meshtenant.v4.hal+json": {}}}} + assert.JSONEq(t, `{"paths": {"/api/meshobjects/meshtenants/{tenant}": {"get": { + "tags": ["Tenants"], + "summary": "Get tenant", + "operationId": "meshTenantGet", + "parameters": [{"name": "tenant", "in": "path", "required": true, "schema": {"type": "string"}, "x-meshstack-path-key": "metadata.uuid", "x-meshstack-path-key-by-version": {"v3": "metadata.tenantIdentifier"}}], + "responses": {"200": {"description": "The tenant", "content": {"application/vnd.meshcloud.api.meshtenant.v4.hal+json": {"x-meshstack-lifecycle": {"meshObject": "meshTenant.v4", "state": "GA"}}}}}, + "x-position": 110 }}}}`, stdout) _, err = meshStack.run(t, api.NewDocs(), "", "/api/meshobjects/meshunknowns") @@ -274,17 +283,36 @@ func TestApi(t *testing.T) { stdout, err := meshStack.run(t, api.NewDocs(), "", "--describe", "bb") require.NoError(t, err) - assert.Contains(t, stdout, "# meshBuildingBlock\n\n## create: `POST /api/meshobjects/meshbuildingblocks`\n\nAPI version v2-preview\n\n**Create a building block**\n\nCreates a building block.\n\n### Parameters") + assert.Contains(t, stdout, "# meshBuildingBlock\n\n## create: `POST /api/meshobjects/meshbuildingblocks`\n\nAPI version v2-preview\n\n**Create building block**\n\n"+ + "Create a new meshBuildingBlock with inputs and parent building block relationships\n\n### Request body `"+blockV2Preview+"`") assert.Contains(t, stdout, "### Response 201 `"+blockV2Preview+"`") assert.Contains(t, stdout, "### Response 400 `application/json`") stdout, err = meshStack.run(t, api.NewDocs(), "", "--describe", "tenant.delete", "-o", "json") require.NoError(t, err) - assert.JSONEq(t, `{"paths": {"/api/meshobjects/meshtenants/{uuid}": {"delete": { - "operationId": "meshTenantDeleteV4", - "responses": {"202": {"description": "202"}} - }}}}`, stdout) + assert.JSONEq(t, `{ + "paths": {"/api/meshobjects/meshtenants/{tenant}": {"delete": { + "tags": ["Tenants"], + "summary": "Delete tenant", + "operationId": "meshTenantDelete", + "parameters": [ + {"name": "tenant", "in": "path", "description": "DELETE takes the UUID or the full tenant identifier.", "required": true, "schema": {"type": "string"}, "x-meshstack-path-key": "metadata.uuid"}, + {"name": "purge", "in": "query", "description": "Removes the meshTenant from meshStack at once.", "required": false, "schema": {"type": "boolean"}} + ], + "responses": { + "202": {"description": "Deletion of tenant started"}, + "400": {"description": "The request is invalid. The message names the invalid part.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/CustomErrorMessage"}}}} + }, + "x-position": 112 + }}}, + "components": {"schemas": {"CustomErrorMessage": { + "required": ["errorCode", "message"], + "type": "object", + "properties": {"errorCode": {"type": "string"}, "message": {"type": "string", "description": "A message that describes the error."}}, + "description": "The body of every error response." + }}} + }`, stdout) }) t.Run("api-docs --describe takes a kind of the API docs, and neither a path nor a request", func(t *testing.T) { @@ -303,6 +331,7 @@ func TestApi(t *testing.T) { t.Run("without a writable config directory, api sends the request as given and api-docs fails", func(t *testing.T) { dir := os.Getenv(config.DirectorySetting.EnvKey()) + require.NoError(t, os.RemoveAll(filepath.Join(dir, "api-docs")), "the earlier steps stored the API docs") //nolint:gosec // G703: the config directory of this test // G302 counts a directory's x bit, without which nothing can enter it. require.NoError(t, os.Chmod(dir, 0o500)) //nolint:gosec // G302: see above t.Cleanup(func() { _ = os.Chmod(dir, 0o700) }) //nolint:gosec // G302: see above @@ -332,12 +361,18 @@ type recordedRequest struct { type fakeMeshStack struct { *fakemeshstack.Server - requests []recordedRequest + requests []recordedRequest + docsRequests atomic.Int32 } -func newFakeMeshStack(t *testing.T) *fakeMeshStack { +func newFakeMeshStack(t *testing.T, apiDocs []byte) *fakeMeshStack { t.Helper() meshStack := &fakeMeshStack{Server: fakemeshstack.Start(t, fakemeshstack.Options{})} + serveApiDocs := fakemeshstack.ServeApiDocs(apiDocs) + meshStack.Route("GET "+fakemeshstack.ApiDocsPath, func(w gohttp.ResponseWriter, r *gohttp.Request) { + meshStack.docsRequests.Add(1) + serveApiDocs(w, r) + }) meshStack.answer(gohttp.StatusOK, `{}`) return meshStack } @@ -362,6 +397,9 @@ func (f *fakeMeshStack) run(t *testing.T, cmd *cobra.Command, stdin string, args err := cmd.ExecuteContext(t.Context()) f.requests = nil for _, r := range f.TakeRequests() { + if r.URL.Path == fakemeshstack.ApiDocsPath { + continue + } f.requests = append(f.requests, recordedRequest{ method: r.Method, pathAndQuery: r.URL.RequestURI(), diff --git a/cmd/api/docs.go b/cmd/api/docs.go index 227531b9..20aece6d 100644 --- a/cmd/api/docs.go +++ b/cmd/api/docs.go @@ -46,9 +46,7 @@ Give the request as you would give it to 'meshstack api': a path or a URL, with --%[6]s %[7]s prints the matching part of the OpenAPI document as JSON. -The command downloads the API docs from your meshStack, so they list only what your meshStack offers. If no endpoint is set, or if your meshStack is too old to serve its API docs, the command uses the API docs of the latest release on docs.meshcloud.io. - ---%[8]s uses the API docs of meshStack's development version instead.`, +The command downloads the API docs from the endpoint, which needs no login for them, and keeps them in the config directory until the endpoint has newer ones. If no endpoint is set, the command uses the API docs of the latest release on docs.meshcloud.io. It also uses them, with a warning, if the endpoint has no API docs, or if it cannot be reached and no API docs of it are kept. --%[8]s uses the API docs of meshStack's development version instead.`, methodFlagName, headerFlagName, requestJsonFlagName, apiVersionFlagName, describeFlagName, internal.OutputFlagName, internal.OutputJson, devFlagName), Example: ` meshstack api-docs @@ -80,8 +78,7 @@ The command downloads the API docs from your meshStack, so they list only what y if err != nil { return err } - spec, wait, err := flags.loadApiDocs(cmd, endpoint) - defer wait() + spec, err := flags.loadApiDocs(cmd, endpoint) if err != nil { return err } diff --git a/cmd/api/request.go b/cmd/api/request.go index 79ab2c84..060562ea 100644 --- a/cmd/api/request.go +++ b/cmd/api/request.go @@ -43,7 +43,7 @@ func (f *requestFlags) register(cmd *cobra.Command, defaultMethod, methodUsage s cmd.Flags().StringArrayVarP(&f.headers, headerFlagName, "H", nil, "add a request header, as 'key: value'") f.requestJson.Register(cmd.Flags(), requestJsonFlagName, "JSON file to send as the request body, or - for stdin") cmd.Flags().StringVar(&f.apiVersion, apiVersionFlagName, "", "version of the meshObject API, such as v1 or v2-preview, instead of the latest") - cmd.Flags().BoolVar(&f.dev, devFlagName, false, "use the API docs of meshStack's development version") + cmd.Flags().BoolVar(&f.dev, devFlagName, false, "if the endpoint has no API docs, use those of meshStack's development version") } type request struct { @@ -110,7 +110,7 @@ func (f *requestFlags) selector(r request) (openapi.Selector, error) { if f.apiVersion != "" { given = append(given, f.apiVersion) } - if r.body.Kind() == '{' { + if r.body.Kind() == jsontext.KindBeginObject { var body struct { ApiVersion string `json:"apiVersion"` } @@ -133,7 +133,7 @@ func (f *requestFlags) selector(r request) (openapi.Selector, error) { return selector, nil } -func (f *requestFlags) loadApiDocs(cmd *cobra.Command, endpoint xurl.URL) (openapi.Spec, func(), error) { +func (f *requestFlags) loadApiDocs(cmd *cobra.Command, endpoint xurl.URL) (openapi.Spec, error) { return apidocs.Load(cmd.Context(), apidocs.Options{ Sources: internal.SettingSources(), Client: internal.ResolveClientOptions().HttpClient(), diff --git a/cmd/internal/testacc/api_docs_test.go b/cmd/internal/testacc/api_docs_test.go index d34b2f06..f3f00006 100644 --- a/cmd/internal/testacc/api_docs_test.go +++ b/cmd/internal/testacc/api_docs_test.go @@ -1,31 +1,94 @@ package testacc import ( + "bytes" + "crypto/sha256" + "encoding/hex" + "io" gohttp "net/http" + "net/url" + "os" + "path/filepath" "regexp" "slices" "strings" "testing" + "github.com/Shopify/toxiproxy/v2" + "github.com/rs/zerolog" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/meshcloud/meshstack-cli/client/openapi" + "github.com/meshcloud/meshstack-cli/cmd/internal" + "github.com/meshcloud/meshstack-cli/internal/json" ) var pathParameterRe = regexp.MustCompile(`\{([^}]+)}`) +const fallbackWarning = "which may not match it" + func TestAccApiDocs(t *testing.T) { - requireLocalStack(t) - spec := devApiDocs(t) - require.NotEmpty(t, spec.Operations) + endpoint := requireLocalStack(t) + proxy := newEndpointProxy(t, endpoint) + c := newCLI(t, proxy.endpoint) + var spec openapi.Spec + + t.Run("with the endpoint unreachable and nothing stored, api-docs reads the published docs of develop", func(t *testing.T) { + proxy.breakConnections(t) + defer proxy.heal(t) + + output, err := c.run("", "api-docs", "--dev") + + require.NoErrorf(t, err, "output:\n%s", output) + assert.Contains(t, output, "https://docs.dev.meshcloud.io/api/meshstack-openapi-docs.json, "+fallbackWarning) + assert.Empty(t, c.storedApiDocs(t), "the published docs are not stored") + }) + + t.Run("api-docs stores the docs of the endpoint under their hash, and asks for newer ones with their ETag", func(t *testing.T) { + output, err := c.run("", "api-docs") + + require.NoErrorf(t, err, "output:\n%s", output) + assert.NotContains(t, output, "level=WARN") + document := servedApiDocs(t, endpoint) + spec, err = openapi.Parse(bytes.NewReader(document)) + require.NoError(t, err) + hash := sha256.Sum256(document) + assert.Equal(t, []string{hex.EncodeToString(hash[:]) + ".json"}, c.storedApiDocs(t)) + index := c.apiDocsIndex(t) + assert.Equal(t, proxy.endpoint, index.Endpoint) + assert.Equal(t, hex.EncodeToString(hash[:]), index.Document) + require.NotEmptyf(t, index.ETag, "%s/api/openapi sends no ETag, so every run downloads the docs again; "+ + "meshfed-release 3a2224431fa adds it", endpoint) + + // A 304 fits into the limit, and the document does not. + proxy.addToxic(t, "limit_data", "downstream", map[string]any{"bytes": 8192}) + defer proxy.heal(t) + output, err = c.run("", "api-docs") + + require.NoErrorf(t, err, "output:\n%s", output) + assert.NotContains(t, output, "level=WARN", "the stored docs are up to date") + }) - t.Run("every operation documents the parameters of its path", func(t *testing.T) { + t.Run("with the endpoint unreachable, api-docs reads the docs stored of it", func(t *testing.T) { + proxy.breakConnections(t) + defer proxy.heal(t) + + output, err := c.run("", "api-docs") + + require.NoErrorf(t, err, "output:\n%s", output) + assert.Contains(t, output, "so this command reads the ones stored before") + assert.NotContains(t, output, fallbackWarning) + }) + + t.Run("every operation has a doc whose fields and parameters have a type, and documents the parameters of its path", func(t *testing.T) { + require.NotEmpty(t, spec.Operations) for _, operation := range spec.Operations { doc, err := spec.Doc(operation) - require.NoError(t, err) + require.NoErrorf(t, err, "%s %s", operation.Method, operation.PathTemplate) var documented []string for _, parameter := range doc.Parameters { + assert.NotEmptyf(t, parameter.Type, "%s %s: parameter %s", operation.Method, operation.PathTemplate, parameter.Name) if parameter.In == "path" { documented = append(documented, parameter.Name) } @@ -33,6 +96,11 @@ func TestAccApiDocs(t *testing.T) { for _, match := range pathParameterRe.FindAllStringSubmatch(string(operation.PathTemplate), -1) { assert.Containsf(t, documented, match[1], "%s %s", operation.Method, operation.PathTemplate) } + for _, body := range slices.Concat(doc.RequestBodies, responseBodies(doc)) { + for _, field := range body.Fields { + assert.NotRegexpf(t, `^$| of$`, field.Type, "%s %s: %s field %s", operation.Method, operation.PathTemplate, body.MediaType, field.Path) + } + } } }) @@ -45,4 +113,95 @@ func TestAccApiDocs(t *testing.T) { assert.Falsef(t, operation.LatestApiVersion().IsZero(), "%s %s", operation.Method, operation.PathTemplate) } }) + + t.Run("api-docs describes every kind", func(t *testing.T) { + kinds := spec.Kinds() + require.NotEmpty(t, kinds) + for _, kind := range kinds { + output, err := c.run("", "api-docs", "--describe", string(internal.KindCommandOf(kind))) + require.NoErrorf(t, err, "%s, output:\n%s", kind, output) + } + }) +} + +func responseBodies(doc openapi.OperationDoc) []openapi.Body { + var bodies []openapi.Body + for _, response := range doc.Responses { + bodies = append(bodies, response.Bodies...) + } + return bodies +} + +func servedApiDocs(t *testing.T, endpoint string) []byte { + t.Helper() + req, err := gohttp.NewRequestWithContext(t.Context(), gohttp.MethodGet, endpoint+"/api/openapi", nil) + require.NoError(t, err) + resp, err := gohttp.DefaultClient.Do(req) + require.NoError(t, err) + defer func() { _ = resp.Body.Close() }() + require.Equal(t, gohttp.StatusOK, resp.StatusCode) + document, err := io.ReadAll(resp.Body) + require.NoError(t, err) + return document +} + +func (c *cli) storedApiDocs(t *testing.T) []string { + t.Helper() + documents, err := filepath.Glob(filepath.Join(c.configDir, "api-docs", "*.json")) + require.NoError(t, err) + for i, document := range documents { + documents[i] = filepath.Base(document) + } + return documents +} + +type apiDocsIndex struct { + Endpoint string `json:"endpoint"` + Document string `json:"document"` + ETag string `json:"etag"` +} + +func (c *cli) apiDocsIndex(t *testing.T) apiDocsIndex { + t.Helper() + indexes, err := filepath.Glob(filepath.Join(c.configDir, "api-docs", "endpoints", "*.json")) + require.NoError(t, err) + require.Len(t, indexes, 1) + content, err := os.ReadFile(indexes[0]) + require.NoError(t, err) + var index apiDocsIndex + require.NoError(t, json.Unmarshal(content, &index)) + return index +} + +type endpointProxy struct { + proxy *toxiproxy.Proxy + endpoint string +} + +func newEndpointProxy(t *testing.T, endpoint string) endpointProxy { + t.Helper() + upstream, err := url.Parse(endpoint) + require.NoError(t, err) + proxy := toxiproxy.NewProxy(toxiproxy.NewServer(toxiproxy.NewMetricsContainer(nil), zerolog.Nop()), t.Name(), "127.0.0.1:0", upstream.Host) + require.NoError(t, proxy.Start()) + t.Cleanup(proxy.Stop) + return endpointProxy{proxy: proxy, endpoint: "http://" + proxy.Listen} +} + +func (p endpointProxy) addToxic(t *testing.T, toxicType, stream string, attributes map[string]any) { + t.Helper() + toxic, err := json.Marshal(map[string]any{"type": toxicType, "stream": stream, "attributes": attributes}) + require.NoError(t, err) + _, err = p.proxy.Toxics.AddToxicJson(bytes.NewReader(toxic)) + require.NoError(t, err) +} + +func (p endpointProxy) breakConnections(t *testing.T) { + t.Helper() + p.addToxic(t, "reset_peer", "upstream", map[string]any{"timeout": 0}) +} + +func (p endpointProxy) heal(t *testing.T) { + t.Helper() + p.proxy.Toxics.ResetToxics(t.Context()) } diff --git a/cmd/internal/testacc/api_get_test.go b/cmd/internal/testacc/api_get_test.go index 7834d253..5e76392c 100644 --- a/cmd/internal/testacc/api_get_test.go +++ b/cmd/internal/testacc/api_get_test.go @@ -6,6 +6,7 @@ import ( "encoding/json/jsontext" "errors" "fmt" + "log/slog" gohttp "net/http" "net/url" "regexp" @@ -20,9 +21,11 @@ import ( "github.com/meshcloud/meshstack-cli/client" "github.com/meshcloud/meshstack-cli/client/http" "github.com/meshcloud/meshstack-cli/client/openapi" + "github.com/meshcloud/meshstack-cli/client/types/xurl" "github.com/meshcloud/meshstack-cli/cmd/internal" "github.com/meshcloud/meshstack-cli/internal/apidocs" "github.com/meshcloud/meshstack-cli/internal/json" + "github.com/meshcloud/meshstack-cli/internal/logs" "github.com/meshcloud/meshstack-cli/pkg/auth" ) @@ -35,6 +38,9 @@ var getExceptions = map[openapi.PathTemplate]getException{ "/api/meshobjects/meshbuildingblockruns": { query: map[string]objectField{"buildingBlockUuid": {"meshBuildingBlock", "uuid"}}, }, + "/api/meshobjects/meshbuildingblockruns/{buildingBlockRun}/artifact": { + skip: "answers 403 to a user login; the building block runner's acceptance tests cover it", + }, "/api/meshobjects/meshbuildingblockruns/{buildingBlockRun}/plan-artifact": { skip: "the API docs say it is in development, and answers 404 in normal operation", }, @@ -54,7 +60,7 @@ type objectField struct { func everyGetOperationAnswers(c *cli) func(*testing.T) { return func(t *testing.T) { - spec := devApiDocs(t) + spec := c.apiDocsOf(t) objects := firstObjects{spec: spec, meshStack: c.client(t)} gets, err := spec.Select(openapi.Selector{Method: gohttp.MethodGet}) require.NoError(t, err) @@ -98,17 +104,18 @@ func organizationAdmin(t *testing.T, logins []devLogin) organizationAdminLogin { return organizationAdminLogin{} } -func devApiDocs(t *testing.T) openapi.Spec { +func (c *cli) apiDocsOf(t *testing.T) openapi.Spec { t.Helper() t.Setenv(envConfigDir, t.TempDir()) - spec, wait, err := apidocs.Load(t.Context(), apidocs.Options{ - Sources: internal.SettingSources(), - Client: internal.ResolveClientOptions().HttpClient(), - Version: internal.Version, - Dev: true, + captured := logs.Capture(t) + spec, err := apidocs.Load(t.Context(), apidocs.Options{ + Sources: internal.SettingSources(), + Client: internal.ResolveClientOptions().HttpClient(), + Endpoint: xurl.MustParsef("%s", c.endpoint), + Version: internal.Version, }) - wait() require.NoError(t, err) + require.Empty(t, captured.Lines(slog.LevelWarn)) return spec } diff --git a/cmd/internal/testacc/api_test.go b/cmd/internal/testacc/api_test.go index 0c4f3803..b3b77575 100644 --- a/cmd/internal/testacc/api_test.go +++ b/cmd/internal/testacc/api_test.go @@ -26,6 +26,16 @@ func apiAsksForJson(c *cli) func(*testing.T) { } } +// The API docs list no version for a delete, so request.negotiate sends no Accept and Content-Type. +func apiDeletesWithNoMediaType(c *cli) func(*testing.T) { + return func(t *testing.T) { + output, err := c.run("", "api", "-X", "DELETE", "/api/meshobjects/meshtenants/00000000-0000-4000-8000-000000000000") + + require.ErrorContainsf(t, err, "meshStack answered HTTP 404", "a tenant that does not exist is not found, rather than refused for its headers, output:\n%s", output) + assert.NotContains(t, err.Error(), "api-docs", "a 404 on a path the API docs list has no hint to them") + } +} + func apiFollowsASelfLink(c *cli) func(*testing.T) { return func(t *testing.T) { var href string diff --git a/cmd/internal/testacc/login_test.go b/cmd/internal/testacc/login_test.go index a4709171..77a5bb67 100644 --- a/cmd/internal/testacc/login_test.go +++ b/cmd/internal/testacc/login_test.go @@ -269,6 +269,7 @@ func TestAccApiKeyLogin(t *testing.T) { t.Run("every list command answers", everyListCommandAnswers(c)) t.Run("every GET operation answers the API key", everyGetOperationAnswers(c)) t.Run("a meshObject endpoint refuses JSON, and api sends --request-json in its media type", apiAsksForJson(c)) + t.Run("a meshObject endpoint takes a DELETE without a media type", apiDeletesWithNoMediaType(c)) t.Run("api picks the profile for the self link of a list answer by its URL alone, with no endpoint in the environment", apiFollowsASelfLink(c)) t.Run("a wait ends once the run has ended", waitEndsTheRun(c)) t.Run("trigger-run names the run it started", triggerRunNamesTheRunItStarted(c)) diff --git a/cmd/internal/testacc/testacc_test.go b/cmd/internal/testacc/testacc_test.go index fe10c03e..101746b7 100644 --- a/cmd/internal/testacc/testacc_test.go +++ b/cmd/internal/testacc/testacc_test.go @@ -146,7 +146,7 @@ func (c *cli) environ() []string { // no test can import, and adds only persistent flags, which this suite sets through the environment. func newRootCommand() *cobra.Command { root := &cobra.Command{Use: "meshstack", SilenceUsage: true} - root.AddCommand(api.New(), auth.New(), auth.NewLoginShortcut(), + root.AddCommand(api.New(), api.NewDocs(), auth.New(), auth.NewLoginShortcut(), buildingblock.New(), buildingblockdefinition.New(), buildingblockdefinitionversion.New(), buildingblockrun.New(), eventlog.New(), profile.New(), workspace.New()) return root diff --git a/docs/demo/fakemeshstack/meshstack.go b/docs/demo/fakemeshstack/meshstack.go index 4515d041..93bcce8f 100644 --- a/docs/demo/fakemeshstack/meshstack.go +++ b/docs/demo/fakemeshstack/meshstack.go @@ -28,6 +28,7 @@ func (i installation) meshStack() *fakemeshstack.Server { Issuer: "https://" + i.sso + "/realms/meshfed", Workspaces: workspaces(), BuildingBlocks: buildingBlocks(), + ApiDocs: apiDocs, }) } @@ -37,8 +38,6 @@ func (i installation) meshStack() *fakemeshstack.Server { //go:embed api-docs.json var apiDocs []byte -const docsHost = "docs.meshstack.example.com" - func workspaces() (objects []any) { for _, workspace := range [][2]string{ {"platform-team", "Platform Team"}, diff --git a/docs/demo/fakemeshstack/server.go b/docs/demo/fakemeshstack/server.go index cc697d3f..e2a587f9 100644 --- a/docs/demo/fakemeshstack/server.go +++ b/docs/demo/fakemeshstack/server.go @@ -16,13 +16,13 @@ import ( "log" "net" gohttp "net/http" + "net/url" "os" "path/filepath" "slices" "time" "github.com/meshcloud/meshstack-cli/internal/json" - "github.com/meshcloud/meshstack-cli/internal/testutil/fakemeshstack" ) // lifetime ends a server that the tape failed to stop. @@ -52,7 +52,6 @@ func serve(dir string) error { mux.Handle(i.api+"/", meshStack) mux.Handle(i.sso+"/", meshStack) } - mux.Handle(docsHost+"/", fakemeshstack.New(fakemeshstack.Options{ApiDocs: apiDocs})) failed := make(chan error, 2) go func() { server := &gohttp.Server{ @@ -82,7 +81,7 @@ func hostNames() (hosts []string) { for _, i := range installations { hosts = append(hosts, i.api, i.sso) } - return append(hosts, docsHost) + return hosts } // tunnel is an HTTPS proxy for the installations' host names only. Refusing every other host, @@ -184,8 +183,8 @@ func writeDemoConfig(dir string, certPEM []byte, proxyAddr string) error { return err } - env := fmt.Sprintf("export MESHSTACK_CONFIG_DIR=%q\nexport HTTPS_PROXY=%q\nexport SSL_CERT_FILE=%q\nexport MESHSTACK_API_DOCS_URL=%q\n", - configDir, "http://"+proxyAddr, caFile, "https://"+docsHost+fakemeshstack.ApiDocsPath) + env := fmt.Sprintf("export MESHSTACK_CONFIG_DIR=%q\nexport HTTPS_PROXY=%q\nexport SSL_CERT_FILE=%q\n", + configDir, (&url.URL{Scheme: "http", Host: proxyAddr}).String(), caFile) if err := os.WriteFile(filepath.Join(dir, "env.tmp"), []byte(env), 0o600); err != nil { return err } diff --git a/internal/apidocs/apidocs.go b/internal/apidocs/apidocs.go index 6be387dd..c3be9d21 100644 --- a/internal/apidocs/apidocs.go +++ b/internal/apidocs/apidocs.go @@ -1,18 +1,14 @@ -// Package apidocs loads the OpenAPI document of the meshStack API into the config directory, and -// keeps it there up to date. package apidocs import ( "bytes" "context" - "crypto/sha256" - "encoding/hex" "errors" "fmt" "log/slog" - gourl "net/url" + gohttp "net/http" "os" - "strings" + "time" "github.com/meshcloud/meshstack-cli/client/http" "github.com/meshcloud/meshstack-cli/client/openapi" @@ -27,98 +23,77 @@ var ( devUrl = xurl.MustParsef("https://docs.dev.meshcloud.io/api/meshstack-openapi-docs.json") ) -// urlEnv names the document of the fake meshStack that the tests and the demo serve, or as a file:// -// URL the one the acceptance suite generates from the meshStack it runs against. It is no -// setting.Setting, and no help names it, so that nobody else comes to rely on it. -const urlEnv = "MESHSTACK_API_DOCS_URL" +// requestTimeout is short, because the stored or the published docs can stand in. +const requestTimeout = 15 * time.Second type Options struct { setting.Sources Client http.Client Endpoint xurl.URL - // Version is the CLI's. A build of no release reads the docs of develop, as Dev does. + // Dev and a Version of no release fall back to the published docs of develop. Version string Dev bool } -// ErrNoConfigDir is returned rather than a document downloaded for nothing, because 4.7MB per -// command is too much to fetch again and again. var ErrNoConfigDir = errors.New("no writable config directory to keep the API docs in") -// Load returns a wait that the caller runs when the command has done its work, so that a slow -// download can finish. -func Load(ctx context.Context, opts Options) (spec openapi.Spec, wait func(), err error) { - wait = func() {} - customEnv := os.Getenv(urlEnv) - if path, isFile := strings.CutPrefix(customEnv, "file://"); isFile { - document, readErr := os.ReadFile(path) //nolint:gosec // G304: the path is the one the acceptance suite sets - if readErr != nil { - return spec, wait, fmt.Errorf("%s: %w", urlEnv, readErr) - } - if spec, err = openapi.Parse(bytes.NewReader(document)); err != nil { - return spec, wait, fmt.Errorf("%s: %w", path, err) - } - return spec, wait, nil +func Load(ctx context.Context, opts Options) (openapi.Spec, error) { + if opts.Endpoint.URL == nil { + return opts.loadPublished(ctx, nil) } dir, err := opts.ResolveSetting(ctx, config.DirectorySetting) if err != nil { - return spec, wait, err + return openapi.Spec{}, err } - if mkdirErr := os.MkdirAll(string(dir), 0o700); mkdirErr != nil || !writable(dir) { - return spec, wait, fmt.Errorf("%w: %s is not writable, set %s to a directory that is", + s := store{dir: dir.Join("api-docs")} + if mkdirErr := os.MkdirAll(s.indexDir(), 0o700); mkdirErr != nil || !writable(s.indexDir()) { + return openapi.Spec{}, fmt.Errorf("%w: %s is not writable, set %s to a directory that is", ErrNoConfigDir, dir, config.DirectorySetting.EnvKey()) } - if customEnv != "" { - var custom xurl.URL - if err = custom.UnmarshalText([]byte(customEnv)); err != nil { - return spec, wait, fmt.Errorf("%s: %w", urlEnv, err) - } - return opts.download(ctx, custom.URL, dir.Join(fmt.Sprintf("api-docs-custom-%s.json", urlHash(custom.URL)))) - } - if opts.Endpoint.URL != nil && !opts.Dev { - served := opts.Endpoint.JoinPath("api", "openapi") - spec, wait, err = opts.download(ctx, served, dir.Join(fmt.Sprintf("api-docs-%s.json", urlHash(served)))) - if httpErr, ok := errors.AsType[http.Error](err); !ok || (!httpErr.IsUnauthorized() && !httpErr.IsNotFound()) { - return spec, wait, err - } - slog.DebugContext(ctx, fmt.Sprintf("%s serves no API docs at /api/openapi, reading those of the docs site", opts.Endpoint)) + spec, err := s.load(ctx, opts.Client, opts.Endpoint) + if _, ok := errors.AsType[fallbackError](err); ok { + return opts.loadPublished(ctx, err) } + return spec, err +} - url, path := releasedUrl, dir.Join("api-docs.json") +func (opts Options) loadPublished(ctx context.Context, why error) (openapi.Spec, error) { + url := releasedUrl if cliVersion, parseErr := version.Parse(opts.Version); opts.Dev || parseErr != nil || !cliVersion.IsRelease() { - url, path = devUrl, dir.Join("api-docs-dev.json") + url = devUrl + } + if why != nil { + slog.WarnContext(ctx, fmt.Sprintf("%s, so this command reads the API docs from %s, which may not match it", why, url)) + } + document, _, err := download(ctx, opts.Client, url) + if err != nil { + return openapi.Spec{}, fmt.Errorf("cannot download the API docs from %s: %w", url, err) } - return opts.download(ctx, url.URL, path) + return parse(url, document) } -func urlHash(url *gourl.URL) string { - sum := sha256.Sum256([]byte(url.String())) - return hex.EncodeToString(sum[:6]) +func download(ctx context.Context, client http.Client, url xurl.URL, options ...http.RequestOption) ([]byte, gohttp.Header, error) { + ctx, cancel := context.WithTimeout(ctx, requestTimeout) + defer cancel() + var header gohttp.Header + // No option sets an Accept-Encoding, so that net/http asks for gzip and decompresses the answer. + document, err := http.ReadAllBody(client.DoRequest(ctx, http.MethodGet, url.URL, + append(options, http.Retryable(0), http.WithCapturedResponseHeader(&header))...)) + return document, header, err } -func (opts Options) download(ctx context.Context, url *gourl.URL, path string) (spec openapi.Spec, wait func(), err error) { - wait = func() {} - document, err := http.ReadAllBody(opts.Client.DoRequest(ctx, http.MethodGet, url)) +func parse(url xurl.URL, document []byte) (openapi.Spec, error) { + spec, err := openapi.Parse(bytes.NewReader(document)) if err != nil { - return spec, wait, fmt.Errorf("cannot download the API docs from %s: %w", url, err) + return spec, fmt.Errorf("the API docs from %s: %w", url, err) } - if err = os.WriteFile(path, document, 0o600); err != nil { //nolint:gosec // G703: the path is the config directory's, joined above - return spec, wait, err - } - spec, err = openapi.Parse(bytes.NewReader(document)) - if err != nil { - return spec, wait, fmt.Errorf("%s: %w", path, err) - } - return spec, wait, nil + return spec, nil } -func writable(dir config.Directory) bool { - if !dir.Exists() { - return false - } - probe, err := os.CreateTemp(string(dir), ".writable-*") +func writable(dir string) bool { + probe, err := os.CreateTemp(dir, ".writable-*") if err != nil { return false } diff --git a/internal/apidocs/apidocs_test.go b/internal/apidocs/apidocs_test.go deleted file mode 100644 index 586bca45..00000000 --- a/internal/apidocs/apidocs_test.go +++ /dev/null @@ -1,84 +0,0 @@ -package apidocs - -import ( - gohttp "net/http" - "os" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/meshcloud/meshstack-cli/client/http" - "github.com/meshcloud/meshstack-cli/client/types/xurl" - "github.com/meshcloud/meshstack-cli/internal/config" - "github.com/meshcloud/meshstack-cli/internal/testutil/fakemeshstack" -) - -func TestLoad(t *testing.T) { - apiDocs, err := os.ReadFile("../../client/openapi/testdata/spec.json") - require.NoError(t, err) - meshStack := fakemeshstack.Start(t, fakemeshstack.Options{ApiDocs: apiDocs}) - docsSite := fakemeshstack.Start(t, fakemeshstack.Options{ApiDocs: apiDocs}) - docsOfDevelop := devUrl - devUrl = xurl.MustParsef("%s%s", docsSite.URL, fakemeshstack.ApiDocsPath) - t.Cleanup(func() { devUrl = docsOfDevelop }) - t.Setenv(urlEnv, "") - - load := func(t *testing.T, dev bool) error { - t.Helper() - t.Setenv(config.DirectorySetting.EnvKey(), t.TempDir()) - _, wait, err := Load(t.Context(), Options{ - Client: http.NewClient(fakemeshstack.UserAgent), - Endpoint: xurl.MustParsef("%s", meshStack.URL), - Dev: dev, - }) - wait() - return err - } - answer := func(status int) { - meshStack.Route("GET "+fakemeshstack.MeshStackApiDocsPath, func(w gohttp.ResponseWriter, _ *gohttp.Request) { - w.WriteHeader(status) - }) - } - paths := func(s *fakemeshstack.Server) (paths []string) { - for _, request := range s.TakeRequests() { - paths = append(paths, request.URL.Path) - } - return paths - } - - t.Run("reads the API docs of the meshStack it acts against", func(t *testing.T) { - require.NoError(t, load(t, false)) - - assert.Equal(t, []string{fakemeshstack.MeshStackApiDocsPath}, paths(meshStack)) - assert.Empty(t, paths(docsSite)) - }) - - t.Run("reads those of the docs site where the meshStack is older than its API docs", func(t *testing.T) { - for _, status := range []int{gohttp.StatusUnauthorized, gohttp.StatusNotFound} { - answer(status) - - require.NoError(t, load(t, false)) - - assert.Equal(t, []string{fakemeshstack.MeshStackApiDocsPath}, paths(meshStack)) - assert.Equal(t, []string{fakemeshstack.ApiDocsPath}, paths(docsSite)) - } - }) - - t.Run("fails where the meshStack refuses its API docs otherwise", func(t *testing.T) { - answer(gohttp.StatusForbidden) - - require.ErrorContains(t, load(t, false), "403") - - assert.Empty(t, paths(docsSite)) - }) - - t.Run("reads those of the docs site with --dev, without asking the meshStack", func(t *testing.T) { - meshStack.TakeRequests() - - require.NoError(t, load(t, true)) - - assert.Empty(t, paths(meshStack)) - assert.Equal(t, []string{fakemeshstack.ApiDocsPath}, paths(docsSite)) - }) -} diff --git a/internal/apidocs/store.go b/internal/apidocs/store.go new file mode 100644 index 00000000..92a4da2a --- /dev/null +++ b/internal/apidocs/store.go @@ -0,0 +1,151 @@ +package apidocs + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "log/slog" + gohttp "net/http" + "os" + "path/filepath" + "strings" + + "github.com/meshcloud/meshstack-cli/client/http" + "github.com/meshcloud/meshstack-cli/client/openapi" + "github.com/meshcloud/meshstack-cli/client/types/xurl" + "github.com/meshcloud/meshstack-cli/internal/json" +) + +type fallbackError struct { + error +} + +type store struct { + dir string +} + +type endpointIndex struct { + Endpoint string `json:"endpoint"` + Document string `json:"document"` + ETag string `json:"etag,omitzero"` +} + +func (s store) indexDir() string { + return filepath.Join(s.dir, "endpoints") +} + +func (s store) indexPath(endpoint xurl.URL) string { + hash := sha256.Sum256([]byte(endpoint.String())) + return filepath.Join(s.indexDir(), hex.EncodeToString(hash[:8])+".json") +} + +func (s store) documentPath(hash string) string { + return filepath.Join(s.dir, hash+".json") +} + +func (s store) load(ctx context.Context, client http.Client, endpoint xurl.URL) (openapi.Spec, error) { + url := xurl.URL{URL: endpoint.JoinPath("api", "openapi")} + indexPath := s.indexPath(endpoint) + stored, storedDocument := s.read(ctx, indexPath) + var options []http.RequestOption + if storedDocument != nil && stored.ETag != "" { + options = append(options, http.WithHeader("If-None-Match", stored.ETag)) + } + + document, header, err := download(ctx, client, url, options...) + httpErr, isHttpErr := errors.AsType[http.Error](err) + switch { + case isHttpErr && httpErr.StatusCode == gohttp.StatusNotModified: + slog.DebugContext(ctx, fmt.Sprintf("The API docs of %s are up to date", endpoint)) + return parse(url, storedDocument) + // A meshStack from before /api/openapi answers 401. + case isHttpErr && (httpErr.StatusCode == gohttp.StatusUnauthorized || httpErr.StatusCode == gohttp.StatusNotFound): + return openapi.Spec{}, fallbackError{fmt.Errorf("%s serves no API docs", endpoint)} + case err != nil && storedDocument != nil: + slog.WarnContext(ctx, fmt.Sprintf("Cannot load the API docs from %s, so this command reads the ones stored before: %s", url, err)) + return parse(url, storedDocument) + case err != nil: + return openapi.Spec{}, fallbackError{fmt.Errorf("cannot load the API docs from %s: %w", url, err)} + } + + spec, err := parse(url, document) + if err != nil { + return spec, err + } + hash := sha256.Sum256(document) + index := endpointIndex{Endpoint: endpoint.String(), Document: hex.EncodeToString(hash[:]), ETag: header.Get("ETag")} + if storeErr := s.put(ctx, indexPath, index, document, stored.Document); storeErr != nil { + slog.WarnContext(ctx, fmt.Sprintf("Cannot store the API docs of %s: %s", endpoint, storeErr)) + } + return spec, nil +} + +func (s store) read(ctx context.Context, indexPath string) (endpointIndex, []byte) { + var index endpointIndex + if err := json.UnmarshalFrom(ctx, indexPath, &index); err != nil { + return endpointIndex{}, nil + } + document, err := os.ReadFile(s.documentPath(index.Document)) + if hash := sha256.Sum256(document); err != nil || hex.EncodeToString(hash[:]) != index.Document { + return index, nil + } + return index, document +} + +func (s store) put(ctx context.Context, indexPath string, index endpointIndex, document []byte, previous string) error { + if err := writeFile(s.documentPath(index.Document), document); err != nil { + return err + } + if err := json.MarshalTo(ctx, indexPath, index); err != nil { + return err + } + if previous == "" || previous == index.Document { + return nil + } + return s.removeUnreferenced(ctx) +} + +func (s store) removeUnreferenced(ctx context.Context) error { + indexes, err := filepath.Glob(filepath.Join(s.indexDir(), "*.json")) + if err != nil { + return err + } + referenced := map[string]bool{} + for _, path := range indexes { + var index endpointIndex + if readErr := json.UnmarshalFrom(ctx, path, &index); readErr != nil { + return readErr + } + referenced[index.Document] = true + } + documents, err := filepath.Glob(s.documentPath("*")) + if err != nil { + return err + } + var errs []error + for _, path := range documents { + if !referenced[strings.TrimSuffix(filepath.Base(path), ".json")] { + errs = append(errs, os.Remove(path)) + } + } + return errors.Join(errs...) +} + +func writeFile(path string, content []byte) (err error) { + tmp, err := os.CreateTemp(filepath.Dir(path), filepath.Base(path)+".*.tmp") + if err != nil { + return err + } + defer func() { + if err != nil { + _ = os.Remove(tmp.Name()) + } + }() + _, writeErr := tmp.Write(content) + if err = errors.Join(writeErr, tmp.Close()); err != nil { + return err + } + return os.Rename(tmp.Name(), path) +} diff --git a/internal/testutil/fakemeshstack/fakemeshstack.go b/internal/testutil/fakemeshstack/fakemeshstack.go index 3c67471e..e7278e1c 100644 --- a/internal/testutil/fakemeshstack/fakemeshstack.go +++ b/internal/testutil/fakemeshstack/fakemeshstack.go @@ -12,6 +12,8 @@ package fakemeshstack import ( "bytes" "cmp" + "crypto/sha256" + "fmt" "io" gohttp "net/http" "net/http/httptest" @@ -38,9 +40,8 @@ const Token = "eyJhbGciOiJub25lIn0.eyJleHAiOjQxMDI0NDQ4MDB9." //nolint:gosec // var UserAgent = http.UserAgent{GitHubRepo: "meshcloud/fakemeshstack", Version: "test"} const ( - ApiDocsPath = "/api/meshstack-openapi-docs.json" - MeshStackApiDocsPath = "/api/openapi" - defaultPageSize = 50 + ApiDocsPath = "/api/openapi" + defaultPageSize = 50 ) type Options struct { @@ -63,9 +64,7 @@ type Options struct { PageSize int TfStates map[TfState][]byte - // ApiDocs is served at ApiDocsPath and MeshStackApiDocsPath as last modified when New was called, - // so a conditional GET gets a 304. - ApiDocs []byte + ApiDocs []byte } type ApiKey struct { @@ -144,13 +143,7 @@ func New(options Options) *Server { } s.routes.HandleFunc("/api/terraform/state/workspace/{workspace}/buildingBlock/{uuid}", s.authorized(s.tfState)) if options.ApiDocs != nil { - modified := time.Now() - for _, path := range []string{ApiDocsPath, MeshStackApiDocsPath} { - s.routes.HandleFunc("GET "+path, func(w gohttp.ResponseWriter, r *gohttp.Request) { - w.Header().Set("Content-Type", "application/json") - gohttp.ServeContent(w, r, "", modified, bytes.NewReader(options.ApiDocs)) - }) - } + s.routes.HandleFunc("GET "+ApiDocsPath, ServeApiDocs(options.ApiDocs)) } if options.Issuer != "" { s.registerKeycloak() @@ -158,6 +151,15 @@ func New(options Options) *Server { return s } +func ServeApiDocs(document []byte) gohttp.HandlerFunc { + etag := fmt.Sprintf(`"%x"`, sha256.Sum256(document)) + return func(w gohttp.ResponseWriter, r *gohttp.Request) { + w.Header().Set("Content-Type", "application/json") + w.Header().Set("ETag", etag) + gohttp.ServeContent(w, r, "", time.Time{}, bytes.NewReader(document)) + } +} + func Start(t *testing.T, options Options) *Server { t.Helper() s := New(options) diff --git a/skills/meshstack-cli/SKILL.md b/skills/meshstack-cli/SKILL.md index bcd01263..ae65d3d6 100644 --- a/skills/meshstack-cli/SKILL.md +++ b/skills/meshstack-cli/SKILL.md @@ -405,7 +405,10 @@ where `MESHSTACK_ENDPOINT` names another one. For a meshObject endpoint it picks command keeps working when a preview version becomes GA. An answer outside 2xx still prints its body, but the command fails. -Do not read the OpenAPI document yourself — it is several MB. Ask `api-docs`: +Do not read the OpenAPI document yourself — it is about 1 MB. Ask `api-docs`, which reads the +document the endpoint serves at `/api/openapi`, so it describes the API of that meshStack. It needs +no login. A meshStack that serves none gets the published docs, with a warning that they may not +match it: ```sh meshstack api-docs --describe bb # every operation of a kind, latest version