Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -549,6 +549,7 @@ linters:
files:
- "$test"
- "!**/client/http/*_test.go"
- "!**/cmd/internal/testacc/*_test.go"
list-mode: strict
allow:
- $gostd
Expand All @@ -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:
Expand Down
127 changes: 89 additions & 38 deletions client/openapi/doc.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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.
Expand All @@ -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"`
Expand All @@ -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
Expand Down Expand Up @@ -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,
}
Expand All @@ -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
}
}
2 changes: 1 addition & 1 deletion client/openapi/media_type.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions client/openapi/object.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
76 changes: 15 additions & 61 deletions client/openapi/spec.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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}
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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() {
Expand All @@ -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
Expand Down Expand Up @@ -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 {
Expand Down
Loading
Loading