diff --git a/README.md b/README.md index 4baebdf1..04651e9c 100644 --- a/README.md +++ b/README.md @@ -136,6 +136,9 @@ How the specification maps onto Go: members the specification does not know. Only if that fails too does the call fail, so a response that merely holds more than the specification says still reaches the caller. + A response holding a value of an enum the specification does not list, which + decodes, is recorded too: each type holding an enum has an `unknownEnum` + method, which the client calls on what it decoded, in debug mode only. Nothing the specification leaves open decodes into `any` then: the empty schema, an array without `items`, a free-form object and `not` alone become `struct{}`, so any value in them is recorded, and any but an object fails. diff --git a/ir/document.go b/ir/document.go index 6897c46e..7d11f933 100644 --- a/ir/document.go +++ b/ir/document.go @@ -81,6 +81,10 @@ func FromDocument(doc *openapi.Document, packageName, userAgent string, producti return nil, fmt.Errorf("paths: %w", err) } + if debug { + markUnknownEnums(schemas) + } + hasURL, hasDuration, hasDate, hasDateTimeOrInt := needsSpecialImports(schemas, operations) encodings, err := markEncodings(schemas) diff --git a/ir/ir.go b/ir/ir.go index 612b6de3..9bf6e9cd 100644 --- a/ir/ir.go +++ b/ir/ir.go @@ -12,7 +12,9 @@ import ( // Document is the top-level IR type passed to templates. type Document struct { // If enabled, debug mode will record responses that failed to unmarshal. - Debug bool `json:"debug,omitzero"` + Debug bool `json:"debug,omitzero"` + // enums tells what each type holds of an enum, see [Document.UnknownEnum]. + enums *enums Title string `json:"title,omitzero"` Production bool `json:"production,omitzero"` PackageName string `json:"packageName,omitzero"` @@ -253,6 +255,9 @@ type Schema struct { // response leaves out. ReadOnly []string `json:"readOnly,omitempty"` WriteOnly []string `json:"writeOnly,omitempty"` + // UnknownEnum is set in debug mode for a type that holds an enum: the body of its unknownEnum method, an + // expression of its receiver v, true if an enum it holds has a value the specification does not list. + UnknownEnum string `json:"unknownEnum,omitzero"` } // AllOfUnion is the union part of an allOf. diff --git a/ir/unknown_enum.go b/ir/unknown_enum.go new file mode 100644 index 00000000..3773d3a1 --- /dev/null +++ b/ir/unknown_enum.go @@ -0,0 +1,258 @@ +package ir + +import ( + "strconv" + "strings" +) + +// enums tells what a Go type of the document holds of an enum, so that debug mode can record a response holding a +// value the specification does not list: it decodes, since an enum is a plain string or number, but is news. +type enums struct { + byName map[string]*Schema + zero map[string]string // the zero value of each enum type, which an optional member holds while left out + holds map[string]bool // whether a named type holds an enum, as found so far +} + +func newEnums(schemas []Schema) *enums { + e := &enums{byName: make(map[string]*Schema, len(schemas)), zero: map[string]string{}, holds: map[string]bool{}} + + for i := range schemas { + s := &schemas[i] + e.byName[s.Name] = s + + if s.Kind == SchemaKindEnum { + e.zero[s.Name] = zeroOf(s.Type) + } + + if s.Tagged != nil && len(s.Tagged.Enum) > 0 { + e.zero[s.Tagged.Type] = `""` + } + } + + return e +} + +func zeroOf(typ string) string { + if typ == "string" { + return `""` + } + + return "0" +} + +// markUnknownEnums gives each schema that holds an enum, if not through a type alias, its UnknownEnum. +func markUnknownEnums(schemas []Schema) { + e := newEnums(schemas) + + for i := range schemas { + if s := &schemas[i]; !s.IsTypeAlias && e.holdsEnum(s.Name) { + s.UnknownEnum = e.method(s) + } + } +} + +// holdsEnum reports whether a value of the Go type typ may hold an enum. +func (e *enums) holdsEnum(typ string) bool { + if elem, ok := strings.CutPrefix(typ, "*"); ok { + return e.holdsEnum(elem) + } + + if elem, ok := strings.CutPrefix(typ, "[]"); ok { + return e.holdsEnum(elem) + } + + if key, value, ok := mapTypes(typ); ok { + return e.holdsEnum(key) || e.holdsEnum(value) + } + + if _, ok := e.zero[typ]; ok { + return true + } + + s := e.byName[typ] + if s == nil { + return false + } + + if holds, ok := e.holds[typ]; ok { + return holds + } + + e.holds[typ] = false // a type that refers to itself holds an enum only if another of its members does + + holds := false + + switch s.Kind { + case SchemaKindAlias: + holds = e.holdsEnum(s.Type) + case SchemaKindMap: + holds = e.holdsEnum(s.MapKey) || e.holdsEnum(s.MapValue) + case SchemaKindUnion: + for _, v := range s.UnionVariants { + holds = holds || e.holdsEnum(v.Type) + } + default: + for _, f := range s.Fields { + holds = holds || e.holdsEnum(f.Type) + } + } + + e.holds[typ] = holds + + return holds +} + +// method is the body of the unknownEnum method of the schema s, which holds an enum: an expression of its receiver, +// v, true if any enum v holds has a value the enum does not list. +func (e *enums) method(s *Schema) string { + var checks []string + + add := func(expr, typ string, optional bool) { + if c := e.check(expr, typ, optional, 0); c != "" { + checks = append(checks, c) + } + } + + switch s.Kind { + case SchemaKindAlias: + if e.byName[s.Type] != nil || e.zero[s.Type] != "" { + add(convert(s.Type, "v"), s.Type, false) // a new type of another, which has its methods + } else { + add("v", s.Type, false) + } + case SchemaKindMap: + add("v", "map["+s.MapKey+"]"+s.MapValue, false) + case SchemaKindUnion: + for _, u := range s.UnionVariants { + if u.Zero != "" { + add("v."+u.FieldName, u.Type, true) + } else { + add("v."+u.FieldName, "*"+u.Type, false) + } + } + case SchemaKindTuple: + for _, f := range s.Fields { + add("v."+f.Name, f.Type, false) + } + default: + for _, f := range s.Fields { + name := f.Name + if f.Embedded { + name = strings.TrimPrefix(f.Type, "*") + } + + add("v."+name, f.Type, !f.Required) + } + } + + return strings.Join(checks, " ||\n") +} + +// convert is expr, a value of a new type of typ, as one of typ, whose methods it then has. +func convert(typ, expr string) string { + if strings.HasPrefix(typ, "*") || strings.HasPrefix(typ, "[]") || strings.HasPrefix(typ, "map[") { + return "(" + typ + ")(" + expr + ")" + } + + return typ + "(" + expr + ")" +} + +// check is an expression true if expr, of the Go type typ, holds a value of an enum the enum does not list, or "" +// if typ holds no enum. Where optional, the zero value of an enum is one left out, and fine. depth names the +// variables of nested loops. +func (e *enums) check(expr, typ string, optional bool, depth int) string { + if !e.holdsEnum(typ) { + return "" + } + + if elem, ok := strings.CutPrefix(typ, "*"); ok { + inner := expr + if strings.HasPrefix(elem, "[]") || strings.HasPrefix(elem, "map[") { + inner = "(*" + expr + ")" + } + + return expr + " != nil && " + e.check(inner, elem, false, depth) + } + + x := "x" + if depth > 0 { + x += strconv.Itoa(depth + 1) + } + + if elem, ok := strings.CutPrefix(typ, "[]"); ok { + return "slices.ContainsFunc(" + expr + ", func(" + x + " " + elem + ") bool { return " + + e.check(x, elem, false, depth+1) + " })" + } + + if key, value, ok := mapTypes(typ); ok { + k, v := "_", "_" + + var checks []string + + if c := e.check("k"+x[1:], key, false, depth+1); c != "" { + k = "k" + x[1:] + + checks = append(checks, c) + } + + if c := e.check(x, value, false, depth+1); c != "" { + v = x + + checks = append(checks, c) + } + + vars := k + ", " + v + if v == "_" { + vars = k + } + + return "func() bool {\nfor " + vars + " := range " + expr + " {\nif " + strings.Join(checks, " || ") + + " {\nreturn true\n}\n}\n\nreturn false\n}()" + } + + if zero, ok := e.zero[typ]; ok { + if optional { + return expr + " != " + zero + " && !" + expr + ".Valid()" + } + + return "!" + expr + ".Valid()" + } + + if s := e.byName[typ]; s.IsTypeAlias { + return e.check(expr, s.Type, optional, depth) + } + + return expr + ".unknownEnum()" +} + +// mapTypes is the key and value types of typ, if it is a map type. +func mapTypes(typ string) (key, value string, ok bool) { + rest, ok := strings.CutPrefix(typ, "map[") + if !ok { + return "", "", false + } + + depth := 1 + for i, r := range rest { + switch r { + case '[': + depth++ + case ']': + if depth--; depth == 0 { + return rest[:i], rest[i+1:], true + } + } + } + + return "", "", false +} + +// UnknownEnum is, for the decoded value expr of the Go type typ, an expression true if it holds a value of an enum +// the enum does not list, or "" if it can hold none: a response debug mode records. +func (d *Document) UnknownEnum(expr, typ string) string { + if d.enums == nil { + d.enums = newEnums(d.Schemas) + } + + return d.enums.check(expr, typ, false, 0) +} diff --git a/ir/unknown_enum_internal_test.go b/ir/unknown_enum_internal_test.go new file mode 100644 index 00000000..ed6cdaa3 --- /dev/null +++ b/ir/unknown_enum_internal_test.go @@ -0,0 +1,38 @@ +package ir + +import "testing" + +func TestEnumsCheck(t *testing.T) { + t.Parallel() + + e := newEnums([]Schema{ + {Name: "Status", Kind: SchemaKindEnum, Type: "string"}, + {Name: "Level", Kind: SchemaKindEnum, Type: "int"}, + {Name: "Item", Kind: SchemaKindStruct, Fields: []Field{{Name: "Status", Type: "Status"}}}, + {Name: "Items", Kind: SchemaKindAlias, Type: "[]Item"}, + {Name: "Same", Kind: SchemaKindAlias, Type: "Items", IsTypeAlias: true}, + {Name: "Node", Kind: SchemaKindStruct, Fields: []Field{{Name: "Next", Type: "*Node"}, {Name: "Name", Type: "string"}}}, + }) + + for _, tc := range []struct { + typ string + optional bool + want string + }{ + {"string", false, ""}, + {"Node", false, ""}, // refers to itself, but holds no enum + {"Status", false, "!v.Valid()"}, + {"Level", true, "v != 0 && !v.Valid()"}, + {"*Item", false, "v != nil && v.unknownEnum()"}, + {"*[]Status", false, "v != nil && slices.ContainsFunc((*v), func(x Status) bool { return !x.Valid() })"}, + {"[][]Status", false, "slices.ContainsFunc(v, func(x []Status) bool { return " + + "slices.ContainsFunc(x, func(x2 Status) bool { return !x2.Valid() }) })"}, + {"map[Status]string", false, "func() bool {\nfor k := range v {\nif !k.Valid() {\nreturn true\n}\n}\n\nreturn false\n}()"}, + {"map[string][]Item", false, "func() bool {\nfor _, x := range v {\nif slices.ContainsFunc(x, func(x2 Item) bool { return x2.unknownEnum() }) {\nreturn true\n}\n}\n\nreturn false\n}()"}, + {"Same", false, "v.unknownEnum()"}, + } { + if got := e.check("v", tc.typ, tc.optional, 0); got != tc.want { + t.Errorf("check(%s) =\n%s\nwant\n%s", tc.typ, got, tc.want) + } + } +} diff --git a/render/templates/client.gen.go.tmpl b/render/templates/client.gen.go.tmpl index 465c5bab..b55c81a7 100644 --- a/render/templates/client.gen.go.tmpl +++ b/render/templates/client.gen.go.tmpl @@ -382,6 +382,15 @@ func (c *Client) {{.Name}}(ctx context.Context{{range .PathParams}}, {{.GoName}} {{- end }} } + {{ if $.Debug }}{{ with $.UnknownEnum "out" (print $out) -}} + // a value of an enum the specification does not list decodes, but is news + if ia != nil && ({{ . }}) { + if err := c.keep(ia); err != nil { + return {{if $op.SuccessReturn}}nil, {{end}}fmt.Errorf("recording the call: %w", err) + } + } + + {{ end }}{{ end -}} {{ if and .IsSuccess $op.SuccessReturn -}} return {{ if not $op.SuccessReturn.NilByItself }}&{{ end }}out, nil {{ else if .IsSuccess -}} diff --git a/render/templates/types.gen.go.tmpl b/render/templates/types.gen.go.tmpl index e2b1642b..814aacb4 100644 --- a/render/templates/types.gen.go.tmpl +++ b/render/templates/types.gen.go.tmpl @@ -581,6 +581,14 @@ func (a {{$typeName}}) MarshalJSONTo(enc *jsontext.Encoder) error { {{ else }} // TODO: unimplemented schema kind {{ .Kind }} {{- end }} +{{- if .UnknownEnum }} + +// unknownEnum reports whether v holds a value of an enum the specification does not list, a response debug mode +// records. +func (v {{ if not (or (eq .Kind 2) (eq .Kind 4)) }}*{{ end }}{{ .Name }}) unknownEnum() bool { + return {{ .UnknownEnum }} +} +{{- end }} {{end}} {{- if .NeedsJSONHelpers }} diff --git a/testdata/debug/api/openapi.json b/testdata/debug/api/openapi.json index 1ed29910..14c1adec 100644 --- a/testdata/debug/api/openapi.json +++ b/testdata/debug/api/openapi.json @@ -7,6 +7,9 @@ "200": {"description": "ok", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Item"}}}}, "404": {"description": "An error debug mode decodes leniently too.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Problem"}}}} }}}, + "/items": {"get": {"operationId": "listItems", "responses": { + "200": {"description": "ok", "content": {"application/json": {"schema": {"type": "array", "items": {"$ref": "#/components/schemas/Item"}}}}} + }}}, "/block": {"get": {"operationId": "getBlock", "responses": { "200": {"description": "ok", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Block"}}}} }}}, @@ -22,14 +25,19 @@ "schemas": { "Problem": {"type": "object", "required": ["message"], "properties": {"message": {"type": "string"}}}, "Item": {"type": "object", "required": ["id"], "properties": {"id": {"type": "string"}, - "updated": {"description": "Every date here is an integer, so one marshaler writes them all.", "type": "integer", "format": "date"}}}, + "updated": {"description": "Every date here is an integer, so one marshaler writes them all.", "type": "integer", "format": "date"}, + "status": {"$ref": "#/components/schemas/Status"}, + "events": {"type": "array", "items": {"$ref": "#/components/schemas/Event"}}, + "labels": {"type": "object", "additionalProperties": {"$ref": "#/components/schemas/Status"}}}}, + "Status": {"description": "A value the specification does not list decodes, and debug mode records it.", "type": "string", "enum": ["active", "archived"]}, + "Event": {"type": "object", "required": ["kind"], "properties": {"kind": {"type": "string", "enum": ["created", "deleted"]}}}, "Block": {"oneOf": [{"$ref": "#/components/schemas/Paragraph"}, {"$ref": "#/components/schemas/Divider"}]}, "Paragraph": {"type": "object", "required": ["type", "paragraph"], "properties": { "type": {"type": "string", "const": "paragraph"}, "paragraph": {"$ref": "#/components/schemas/Text"}}}, "Divider": {"type": "object", "required": ["type"], "properties": {"type": {"type": "string", "const": "divider"}}}, "Text": {"type": "object", "required": ["text"], "properties": {"text": {"type": "string"}}}, "Pet": {"oneOf": [{"$ref": "#/components/schemas/Cat"}, {"$ref": "#/components/schemas/Dog"}]}, - "Cat": {"type": "object", "required": ["meow"], "properties": {"meow": {"type": "boolean"}}}, + "Cat": {"type": "object", "required": ["meow"], "properties": {"meow": {"type": "boolean"}, "mood": {"type": "string", "enum": ["calm", "grumpy"]}}}, "Dog": {"type": "object", "required": ["bark"], "properties": {"bark": {"type": "boolean"}}} }} } diff --git a/testdata/debug/pkg/debug/api.js b/testdata/debug/pkg/debug/api.js index dea3447f..0980dc53 100644 --- a/testdata/debug/pkg/debug/api.js +++ b/testdata/debug/pkg/debug/api.js @@ -10,6 +10,7 @@ * Usage: * import './api.js'; // or * const result = await window.API.getItem(); + * const result = await window.API.listItems(); * const result = await window.API.getBlock(); * const result = await window.API.getPet(); * window.API.ping(); @@ -90,6 +91,10 @@ window.API = { getItem: () => apiFetch("/item", { operationId: "GetItem", }), + // GET /items + listItems: () => apiFetch("/items", { + operationId: "ListItems", + }), // GET /block getBlock: () => apiFetch("/block", { operationId: "GetBlock", diff --git a/testdata/debug/pkg/debug/client.gen.go b/testdata/debug/pkg/debug/client.gen.go index e2bfd87d..d19a74eb 100644 --- a/testdata/debug/pkg/debug/client.gen.go +++ b/testdata/debug/pkg/debug/client.gen.go @@ -13,6 +13,7 @@ import ( "net/http" "net/url" "os" + "slices" "strings" "github.com/MarkRosemaker/cassette" @@ -149,6 +150,13 @@ func (c *Client) GetItem(ctx context.Context) (*Item, error) { } } + // a value of an enum the specification does not list decodes, but is news + if ia != nil && out.unknownEnum() { + if err := c.keep(ia); err != nil { + return nil, fmt.Errorf("recording the call: %w", err) + } + } + return &out, nil default: return nil, c.failed(ia, api.NewErrUnknownContentType(rsp)) @@ -173,6 +181,56 @@ func (c *Client) GetItem(ctx context.Context) (*Item, error) { } } +// GET /items +func (c *Client) ListItems(ctx context.Context) ([]Item, error) { + u := c.baseURL.JoinPath("items") + req := (&http.Request{ + Header: http.Header{ + "Authorization": []string{c.bearer}, + "User-Agent": []string{c.userAgent}, + }, + Host: u.Host, + Method: http.MethodGet, + Proto: "HTTP/1.1", + ProtoMajor: 1, + ProtoMinor: 1, + URL: u, + }).WithContext(ctx) + + rsp, ia, err := c.do(req) + if err != nil { + return nil, err + } + defer rsp.Body.Close() + + switch rsp.StatusCode { + case http.StatusOK: + // ok + switch mt, _, _ := strings.Cut(rsp.Header.Get("Content-Type"), ";"); mt { + case "application/json": + var out []Item + if err := json.UnmarshalRead(rsp.Body, &out, jsonOpts); err != nil { + if err := api.DecodeLenient(rsp, err, ia, cmp.Or(c.debugFile, defaultDebugFile), &out, jsonOpts); err != nil { + return nil, err + } + } + + // a value of an enum the specification does not list decodes, but is news + if ia != nil && slices.ContainsFunc(out, func(x Item) bool { return x.unknownEnum() }) { + if err := c.keep(ia); err != nil { + return nil, fmt.Errorf("recording the call: %w", err) + } + } + + return out, nil + default: + return nil, c.failed(ia, api.NewErrUnknownContentType(rsp)) + } + default: + return nil, c.failed(ia, api.NewErrUnknownStatusCode(rsp)) + } +} + // GET /block func (c *Client) GetBlock(ctx context.Context) (*Block, error) { u := c.baseURL.JoinPath("block") @@ -207,6 +265,13 @@ func (c *Client) GetBlock(ctx context.Context) (*Block, error) { } } + // a value of an enum the specification does not list decodes, but is news + if ia != nil && out.unknownEnum() { + if err := c.keep(ia); err != nil { + return nil, fmt.Errorf("recording the call: %w", err) + } + } + return &out, nil default: return nil, c.failed(ia, api.NewErrUnknownContentType(rsp)) @@ -250,6 +315,13 @@ func (c *Client) GetPet(ctx context.Context) (*Pet, error) { } } + // a value of an enum the specification does not list decodes, but is news + if ia != nil && out.unknownEnum() { + if err := c.keep(ia); err != nil { + return nil, fmt.Errorf("recording the call: %w", err) + } + } + return &out, nil default: return nil, c.failed(ia, api.NewErrUnknownContentType(rsp)) diff --git a/testdata/debug/pkg/debug/client.gen_test.go b/testdata/debug/pkg/debug/client.gen_test.go index dab5a814..14190f93 100644 --- a/testdata/debug/pkg/debug/client.gen_test.go +++ b/testdata/debug/pkg/debug/client.gen_test.go @@ -249,6 +249,142 @@ func TestClient_Error(t *testing.T) { }) }) + t.Run("ListItems", func(t *testing.T) { + t.Setenv("DEBUG_TOKEN", "**************************************************") + + t.Run("transport error", func(t *testing.T) { + c, err := NewClient(WithHTTPClient(&http.Client{Transport: apitest.RoundTripFunc( + func(*http.Request) (*http.Response, error) { return nil, io.EOF }, + )})) + if err != nil { + t.Fatal(err) + } + + if _, err := c.ListItems(t.Context()); err == nil { + t.Fatal("expected error") + } else if !errors.Is(err, io.EOF) { + t.Fatalf("want: %v, got: %v", io.EOF, err) + } + }) + + t.Run("unknown status code", func(t *testing.T) { + srv := apitest.NewServer(t, http.StatusTeapot) + + baseURL, err := url.Parse(srv.URL) + if err != nil { + t.Fatal(err) + } + + c, err := NewClient(WithBaseURL(baseURL)) + if err != nil { + t.Fatal(err) + } + + if _, err := c.ListItems(t.Context()); err == nil { + t.Fatal("expected error") + } else if apiErr, ok := errors.AsType[*api.Error](err); !ok { + t.Fatalf("got: %T, want: *api.Error", err) + } else if apiErr.Err != api.ErrUnknownStatusCode { + t.Fatalf("got: %v, want: %v", apiErr.Err, api.ErrUnknownStatusCode) + } else if apiErr.Response.StatusCode != http.StatusTeapot { + t.Fatalf("got: %v, want: %v", apiErr.Response.StatusCode, http.StatusTeapot) + } + }) + + t.Run("unknown content type", func(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "foo") + w.WriteHeader(http.StatusOK) + })) + t.Cleanup(srv.Close) + + baseURL, err := url.Parse(srv.URL) + if err != nil { + t.Fatal(err) + } + + c, err := NewClient(WithBaseURL(baseURL)) + if err != nil { + t.Fatal(err) + } + + if _, err := c.ListItems(t.Context()); err == nil { + t.Fatal("expected error") + } else if !errors.Is(err, api.ErrUnknownContentType) { + t.Fatalf("want: %v, got: %v", api.ErrUnknownContentType, err) + } + }) + + t.Run("decoding error", func(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte("invalid json")) + })) + t.Cleanup(srv.Close) + + baseURL, err := url.Parse(srv.URL) + if err != nil { + t.Fatal(err) + } + + c, err := NewClient(WithBaseURL(baseURL)) + if err != nil { + t.Fatal(err) + } + + if _, err := c.ListItems(t.Context()); err == nil { + t.Fatal("expected error") + } else if decErr, ok := errors.AsType[*api.DecodingError](err); !ok { + t.Fatalf("got: %T, want: *api.DecodingError", err) + } else if _, ok := errors.AsType[*jsontext.SyntacticError](decErr.Err); !ok { + t.Fatalf("got: %T, want: *jsontext.SyntacticError", decErr.Err) + } + }) + + t.Run("debug mode keeps a body it cannot decode", func(t *testing.T) { + file := filepath.Join(t.TempDir(), "interactions.json") + + c, err := NewClient(WithBaseURL(apitest.BodyServer(t, http.StatusOK, "application/json", []byte("invalid json"))), WithDebugFile(file)) + if err != nil { + t.Fatal(err) + } + + if _, err := c.ListItems(t.Context()); err == nil { + t.Fatal("expected error") + } else if _, ok := errors.AsType[*api.DecodingError](err); !ok { + t.Fatalf("got: %T, want: *api.DecodingError", err) + } + + if ias, err := cassette.InteractionsReadFile(file); err != nil { + t.Fatal(err) + } else if len(ias) != 1 { + t.Fatalf("the debug file holds %d calls, want the one that failed to decode", len(ias)) + } + }) + + t.Run("debug mode reports a debug file it cannot write", func(t *testing.T) { + // a file where the debug file's directory would be + blocker := filepath.Join(t.TempDir(), "file") + if err := os.WriteFile(blocker, nil, 0o600); err != nil { + t.Fatal(err) + } + + c, err := NewClient(WithBaseURL(apitest.BodyServer(t, http.StatusOK, "application/json", []byte("invalid json"))), WithDebugFile(filepath.Join(blocker, "interactions.json"))) + if err != nil { + t.Fatal(err) + } + + if _, err := c.ListItems(t.Context()); err == nil { + t.Fatal("expected error") + } else if _, ok := errors.AsType[*api.DecodingError](err); !ok { + t.Fatalf("got: %T, want the *api.DecodingError", err) + } else if _, ok := errors.AsType[*fs.PathError](err); !ok { + t.Fatalf("got: %v, want the failure to write the debug file beside it", err) + } + }) + }) + t.Run("GetBlock", func(t *testing.T) { t.Setenv("DEBUG_TOKEN", "**************************************************") diff --git a/testdata/debug/pkg/debug/debug_test.go b/testdata/debug/pkg/debug/debug_test.go index 3ab25d24..8a1f6a96 100644 --- a/testdata/debug/pkg/debug/debug_test.go +++ b/testdata/debug/pkg/debug/debug_test.go @@ -277,3 +277,59 @@ func TestDebug_Recording(t *testing.T) { } }) } + +func TestDebug_UnknownEnum(t *testing.T) { + item := func(c *Client) (any, error) { return c.GetItem(t.Context()) } + + for _, tc := range []struct { + name, body string + call func(*Client) (any, error) + unknown bool + // an untagged union picks its alternative by the values its enums list, so it fails strictly + strictFails bool + }{ + {"known", `{"id":"a","status":"active","events":[{"kind":"created"}],"labels":{"x":"archived"}}`, item, false, false}, + {"optional left out", `{"id":"a"}`, item, false, false}, + {"member", `{"id":"a","status":"deleted"}`, item, true, false}, + {"in a list", `{"id":"a","events":[{"kind":"created"},{"kind":"moved"}]}`, item, true, false}, + {"in a map", `{"id":"a","labels":{"x":"active","y":"pinned"}}`, item, true, false}, + {"in a list answered", `[{"id":"a"},{"id":"b","status":"deleted"}]`, + func(c *Client) (any, error) { return c.ListItems(t.Context()) }, true, false}, + {"in an alternative of a union", `{"meow":true,"mood":"sleepy"}`, + func(c *Client) (any, error) { return c.GetPet(t.Context()) }, true, true}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Chdir(t.TempDir()) + + // without debug mode, the value is decoded as it is + strict, err := NewClient(WithBaseURL(serve(t, tc.body)), WithBearer("token")) + if err != nil { + t.Fatal(err) + } + + if _, err := tc.call(strict); (err != nil) != tc.strictFails { + t.Fatalf("without debug: %v", err) + } + + if ias := recorded(t); len(ias) != 0 { + t.Fatalf("without debug, %d interactions recorded", len(ias)) + } + + c, err := NewClient(WithBaseURL(serve(t, tc.body)), WithBearer("token"), WithDebug) + if err != nil { + t.Fatal(err) + } + + if _, err := tc.call(c); err != nil { + t.Fatalf("with debug: %v", err) + } + + switch ias := recorded(t); { + case !tc.unknown && len(ias) != 0: + t.Errorf("recorded %d interactions, want none", len(ias)) + case tc.unknown && (len(ias) != 1 || !sameJSON(t, ias[0].Response.Body, tc.body)): + t.Errorf("recorded %+v, want the one response", ias) + } + }) + } +} diff --git a/testdata/debug/pkg/debug/ir.json b/testdata/debug/pkg/debug/ir.json index 85c36b90..bf137431 100644 --- a/testdata/debug/pkg/debug/ir.json +++ b/testdata/debug/pkg/debug/ir.json @@ -42,6 +42,32 @@ "name": "Item" } }, + { + "auth": "bearer", + "name": "ListItems", + "method": "GET", + "pathTemplate": "/items", + "joinPathArgs": [ + "\"items\"" + ], + "responses": [ + { + "statusCode": "200", + "goConstant": "http.StatusOK", + "description": "ok", + "contentType": "application/json", + "goType": { + "name": "Item", + "isSlice": true + }, + "isSuccess": true + } + ], + "successReturn": { + "name": "Item", + "isSlice": true + } + }, { "auth": "bearer", "name": "GetBlock", @@ -170,7 +196,8 @@ "zero": "nil" } ] - } + }, + "unknownEnum": "!v.Type.Valid()" }, { "name": "Cat", @@ -182,6 +209,31 @@ "type": "bool", "jsonTag": "json:\"meow\"", "required": true + }, + { + "name": "Mood", + "jsonName": "mood", + "type": "CatMood", + "jsonTag": "json:\"mood,omitzero\"" + } + ], + "unknownEnum": "v.Mood != \"\" && !v.Mood.Valid()" + }, + { + "name": "CatMood", + "description": "CatMood defines a model", + "kind": 1, + "type": "string", + "enumValues": [ + { + "goName": "CatMoodCalm", + "value": "calm", + "literal": "\"calm\"" + }, + { + "goName": "CatMoodGrumpy", + "value": "grumpy", + "literal": "\"grumpy\"" } ] }, @@ -198,6 +250,38 @@ } ] }, + { + "name": "Event", + "description": "Event defines a model", + "fields": [ + { + "name": "Kind", + "jsonName": "kind", + "type": "EventKind", + "jsonTag": "json:\"kind\"", + "required": true + } + ], + "unknownEnum": "!v.Kind.Valid()" + }, + { + "name": "EventKind", + "description": "EventKind defines a model", + "kind": 1, + "type": "string", + "enumValues": [ + { + "goName": "EventKindCreated", + "value": "created", + "literal": "\"created\"" + }, + { + "goName": "EventKindDeleted", + "value": "deleted", + "literal": "\"deleted\"" + } + ] + }, { "name": "Item", "description": "Item defines a model", @@ -216,8 +300,28 @@ "jsonTag": "json:\"updated,omitzero\"", "description": "Every date here is an integer, so one marshaler writes them all.", "isUnix": true + }, + { + "name": "Status", + "jsonName": "status", + "type": "Status", + "jsonTag": "json:\"status,omitzero\"", + "description": "A value the specification does not list decodes, and debug mode records it." + }, + { + "name": "Events", + "jsonName": "events", + "type": "[]Event", + "jsonTag": "json:\"events,omitzero\"" + }, + { + "name": "Labels", + "jsonName": "labels", + "type": "map[string]Status", + "jsonTag": "json:\"labels,omitzero\"" } - ] + ], + "unknownEnum": "v.Status != \"\" && !v.Status.Valid() ||\nslices.ContainsFunc(v.Events, func(x Event) bool { return x.unknownEnum() }) ||\nfunc() bool {\nfor _, x := range v.Labels {\nif !x.Valid() {\nreturn true\n}\n}\n\nreturn false\n}()" }, { "name": "Pet", @@ -228,12 +332,22 @@ "fieldName": "Cat", "type": "Cat", "members": [ - "meow" + "meow", + "mood" ], "required": [ "meow" ], - "object": true + "object": true, + "enums": [ + { + "name": "mood", + "values": [ + "\"calm\"", + "\"grumpy\"" + ] + } + ] }, { "fieldName": "Dog", @@ -252,12 +366,22 @@ "fieldName": "Cat", "type": "Cat", "members": [ - "meow" + "meow", + "mood" ], "required": [ "meow" ], - "object": true + "object": true, + "enums": [ + { + "name": "mood", + "values": [ + "\"calm\"", + "\"grumpy\"" + ] + } + ] }, { "fieldName": "Dog", @@ -271,7 +395,8 @@ "object": true } ], - "isOneOf": true + "isOneOf": true, + "unknownEnum": "v.Cat != nil && v.Cat.unknownEnum()" }, { "name": "Problem", @@ -286,6 +411,24 @@ } ] }, + { + "name": "Status", + "description": "A value the specification does not list decodes, and debug mode records it.", + "kind": 1, + "type": "string", + "enumValues": [ + { + "goName": "StatusActive", + "value": "active", + "literal": "\"active\"" + }, + { + "goName": "StatusArchived", + "value": "archived", + "literal": "\"archived\"" + } + ] + }, { "name": "Text", "description": "Text defines a model", diff --git a/testdata/debug/pkg/debug/server.gen.go b/testdata/debug/pkg/debug/server.gen.go index 22a6f5e9..211e54d9 100644 --- a/testdata/debug/pkg/debug/server.gen.go +++ b/testdata/debug/pkg/debug/server.gen.go @@ -17,6 +17,7 @@ import ( // Service defines the operations the server must implement. type Service interface { GetItem(ctx context.Context) (*Item, error) + ListItems(ctx context.Context) ([]Item, error) GetBlock(ctx context.Context) (*Block, error) GetPet(ctx context.Context) (*Pet, error) Ping(ctx context.Context) error @@ -67,6 +68,48 @@ func RegisterService(svc Service, mux *http.ServeMux, pathPrefix string) { }) } + { + path := fmt.Sprintf("%s%s", pathPrefix, "/items") + l := slog.Default().With(slog.String("method", "GET"), slog.String("path", path), slog.String("function", "ListItems")) + + mux.HandleFunc(fmt.Sprintf("GET %s", path), func(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + l.DebugContext(ctx, "called") + + res, err := svc.ListItems(ctx) + if err != nil { + sErr, ok := errors.AsType[*server.Error](err) + if !ok { + l.ErrorContext(ctx, "Internal Server Error", slog.String("error", err.Error())) + http.Error(w, "Internal Server Error", http.StatusInternalServerError) + return + } + + l.DebugContext(ctx, "graceful error", slog.String("error", err.Error())) + + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(sErr.Code) + + if err := json.MarshalWrite(w, err); err != nil { + l.ErrorContext(ctx, "marshal error", slog.String("error", err.Error())) + http.Error(w, "Internal Server Error", http.StatusInternalServerError) + } + return + } + + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + + if err := json.MarshalWrite(w, res, jsonOpts); err != nil { + l.ErrorContext(ctx, "marshal error", slog.String("error", err.Error())) + http.Error(w, "Internal Server Error", http.StatusInternalServerError) + return + } + + l.DebugContext(ctx, "success") + }) + } + { path := fmt.Sprintf("%s%s", pathPrefix, "/block") l := slog.Default().With(slog.String("method", "GET"), slog.String("path", path), slog.String("function", "GetBlock")) diff --git a/testdata/debug/pkg/debug/types.gen.go b/testdata/debug/pkg/debug/types.gen.go index d9286f89..199b6c0b 100644 --- a/testdata/debug/pkg/debug/types.gen.go +++ b/testdata/debug/pkg/debug/types.gen.go @@ -8,6 +8,7 @@ import ( "encoding/json/jsontext" "encoding/json/v2" "fmt" + "slices" "cloud.google.com/go/civil" "github.com/MarkRosemaker/jsonutil" @@ -114,9 +115,40 @@ func (v *Block) MarshalJSONTo(enc *jsontext.Encoder) error { return json.MarshalEncode(enc, (*plain)(&out), jsonOptsTo(enc)) } +// unknownEnum reports whether v holds a value of an enum the specification does not list, a response debug mode +// records. +func (v *Block) unknownEnum() bool { + return !v.Type.Valid() +} + // Cat defines a model type Cat struct { - Meow bool `json:"meow"` + Meow bool `json:"meow"` + Mood CatMood `json:"mood,omitzero"` +} + +// unknownEnum reports whether v holds a value of an enum the specification does not list, a response debug mode +// records. +func (v *Cat) unknownEnum() bool { + return v.Mood != "" && !v.Mood.Valid() +} + +// CatMood defines a model +type CatMood string + +const ( + CatMoodCalm CatMood = "calm" + CatMoodGrumpy CatMood = "grumpy" +) + +// Valid indicates whether the value is a known member of the CatMood enum. +func (e CatMood) Valid() bool { + switch e { + case CatMoodCalm, CatMoodGrumpy: + return true + default: + return false + } } // Dog defines a model @@ -124,11 +156,60 @@ type Dog struct { Bark bool `json:"bark"` } +// Event defines a model +type Event struct { + Kind EventKind `json:"kind"` +} + +// unknownEnum reports whether v holds a value of an enum the specification does not list, a response debug mode +// records. +func (v *Event) unknownEnum() bool { + return !v.Kind.Valid() +} + +// EventKind defines a model +type EventKind string + +const ( + EventKindCreated EventKind = "created" + EventKindDeleted EventKind = "deleted" +) + +// Valid indicates whether the value is a known member of the EventKind enum. +func (e EventKind) Valid() bool { + switch e { + case EventKindCreated, EventKindDeleted: + return true + default: + return false + } +} + // Item defines a model type Item struct { ID string `json:"id"` // Every date here is an integer, so one marshaler writes them all. Updated civil.Date `json:"updated,omitzero"` + // A value the specification does not list decodes, and debug mode records it. + Status Status `json:"status,omitzero"` + Events []Event `json:"events,omitzero"` + Labels map[string]Status `json:"labels,omitzero"` +} + +// unknownEnum reports whether v holds a value of an enum the specification does not list, a response debug mode +// records. +func (v *Item) unknownEnum() bool { + return v.Status != "" && !v.Status.Valid() || + slices.ContainsFunc(v.Events, func(x Event) bool { return x.unknownEnum() }) || + func() bool { + for _, x := range v.Labels { + if !x.Valid() { + return true + } + } + + return false + }() } // Pet defines a model @@ -157,30 +238,38 @@ func (v *Pet) UnmarshalJSONFrom(dec *jsontext.Decoder) error { var matched int - // leniently, more than one may match, and the first does - if strict || matched == 0 { - // decoding checks neither the members the alternative requires nor those it pins to one value - required, nullable, pinned := []string{"meow"}, map[string]bool{}, map[string]string{} - if union.Fits(raw, required, nullable, pinned) { - var vv Cat - if err := json.Unmarshal(raw, &vv, opts); err == nil { - v.Cat = &vv - matched++ + // a member outside its enum rules an alternative out; leniently, only while another fits + for _, enums := range union.EnumPasses(strict) { + + // leniently, more than one may match, and the first does + if strict || matched == 0 { + // decoding checks neither the members the alternative requires nor those it pins to one value + required, nullable, pinned := []string{"meow"}, map[string]bool{}, map[string]string{} + if union.Fits(raw, required, nullable, pinned) && (!enums || union.EnumsFit(raw, map[string][]string{"mood": {"\"calm\"", "\"grumpy\""}})) { + var vv Cat + if err := json.Unmarshal(raw, &vv, opts); err == nil { + v.Cat = &vv + matched++ + } } } - } - // leniently, more than one may match, and the first does - if strict || matched == 0 { - // decoding checks neither the members the alternative requires nor those it pins to one value - required, nullable, pinned := []string{"bark"}, map[string]bool{}, map[string]string{} - if union.Fits(raw, required, nullable, pinned) { - var vv Dog - if err := json.Unmarshal(raw, &vv, opts); err == nil { - v.Dog = &vv - matched++ + // leniently, more than one may match, and the first does + if strict || matched == 0 { + // decoding checks neither the members the alternative requires nor those it pins to one value + required, nullable, pinned := []string{"bark"}, map[string]bool{}, map[string]string{} + if union.Fits(raw, required, nullable, pinned) { + var vv Dog + if err := json.Unmarshal(raw, &vv, opts); err == nil { + v.Dog = &vv + matched++ + } } } + + if matched > 0 { + break + } } if matched != 1 { @@ -203,11 +292,35 @@ func (v *Pet) MarshalJSONTo(enc *jsontext.Encoder) error { return enc.WriteToken(jsontext.Null) } +// unknownEnum reports whether v holds a value of an enum the specification does not list, a response debug mode +// records. +func (v *Pet) unknownEnum() bool { + return v.Cat != nil && v.Cat.unknownEnum() +} + // Problem defines a model type Problem struct { Message string `json:"message"` } +// A value the specification does not list decodes, and debug mode records it. +type Status string + +const ( + StatusActive Status = "active" + StatusArchived Status = "archived" +) + +// Valid indicates whether the value is a known member of the Status enum. +func (e Status) Valid() bool { + switch e { + case StatusActive, StatusArchived: + return true + default: + return false + } +} + // Text defines a model type Text struct { Text string `json:"text"` diff --git a/testdata/debug/pkg/debug/types.gen_test.go b/testdata/debug/pkg/debug/types.gen_test.go index 441e6b2f..d6f2b9d8 100644 --- a/testdata/debug/pkg/debug/types.gen_test.go +++ b/testdata/debug/pkg/debug/types.gen_test.go @@ -21,13 +21,43 @@ func TestEnums_Valid(t *testing.T) { if BlockType("not a member").Valid() { t.Errorf("BlockType(%v): valid, though no member", "not a member") } + + for _, v := range []CatMood{CatMoodCalm, CatMoodGrumpy} { + if !v.Valid() { + t.Errorf("CatMood %v: not valid", v) + } + } + + if CatMood("not a member").Valid() { + t.Errorf("CatMood(%v): valid, though no member", "not a member") + } + + for _, v := range []EventKind{EventKindCreated, EventKindDeleted} { + if !v.Valid() { + t.Errorf("EventKind %v: not valid", v) + } + } + + if EventKind("not a member").Valid() { + t.Errorf("EventKind(%v): valid, though no member", "not a member") + } + + for _, v := range []Status{StatusActive, StatusArchived} { + if !v.Valid() { + t.Errorf("Status %v: not valid", v) + } + } + + if Status("not a member").Valid() { + t.Errorf("Status(%v): valid, though no member", "not a member") + } } // TestUnions_RoundTrip sets each variant of each union in turn, encodes it and decodes it strictly: the union must // choose the same variant again, and encode as before. func TestUnions_RoundTrip(t *testing.T) { t.Run("Pet/Cat", func(t *testing.T) { - v := Cat{} + v := Cat{Mood: "calm"} apitest.RoundTrip(t, Pet{Cat: &v}, func(u Pet) bool { return u.Cat != nil }, jsonOpts) })