From 51d1d5b2507569c54ec2da26552f9a336a4d10a9 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 02:53:53 +0000 Subject: [PATCH 1/2] feat: an operation whose list is paged by cursor gets Pages and All iterators An operation whose list holds items, the cursor of the next page and, if it says so, whether there is one, and which takes a cursor of the same type as a query parameter or a member of the body, also gets XPages and XAll, built on go-api-libs/api's paging: each yields what it fetches a page at a time, stops when the loop breaks, and yields the first error. Such a list is found by the names lists and cursors commonly have, or by its x-pagination, which names them, fails the run where they do not fit, or, as false, leaves the operation without iterators. The caller's parameters and body are copied, not changed. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019QCb1AfnATvpBQCH3PrX7Y --- README.md | 13 + README/features.md | 13 + golden_test.go | 1 + ir/document.go | 4 + ir/ir.go | 5 + ir/operation.go | 6 + ir/pagination.go | 293 ++++++++++++++++++ ir/pagination_internal_test.go | 88 ++++++ render/imports.go | 2 + render/templates/client.gen.go.tmpl | 26 ++ testdata/golden/api/openapi.json | 61 ++++ testdata/golden/pkg/golden/api.js | 17 + testdata/golden/pkg/golden/client.gen.go | 148 +++++++++ testdata/golden/pkg/golden/client.gen_test.go | 236 ++++++++++++++ testdata/golden/pkg/golden/ir.json | 154 +++++++++ testdata/golden/pkg/golden/paging_test.go | 115 +++++++ testdata/golden/pkg/golden/server.gen.go | 127 ++++++++ testdata/golden/pkg/golden/types.gen.go | 25 ++ 18 files changed, 1334 insertions(+) create mode 100644 ir/pagination.go create mode 100644 ir/pagination_internal_test.go create mode 100644 testdata/golden/pkg/golden/paging_test.go diff --git a/README.md b/README.md index 97dd7420..4baebdf1 100644 --- a/README.md +++ b/README.md @@ -234,6 +234,19 @@ How the specification maps onto Go: not JSON is returned as `[]byte`. The server copies a returned reader into the response, and the JavaScript client returns such a body as a `Blob`, or text as a string. +- **Paging** — an operation whose list is paged through by cursor also gets + `XPages`, which yields each page, and `XAll`, which yields every item, each + fetching the next page as the one before is used up, and stopping when the + loop breaks and at the first error, which it yields. Such a list is found + by its members: a list of items (`results`, `data`, `items`), the cursor of + the next page (`next_cursor`, `next_page_token`, ...) and, if there is one, + whether there is a next page (`has_more`), where there is none once the + cursor is zero; and by a cursor of the same type the operation takes, as a + query parameter or a member of the body (`start_cursor`, `cursor`, + `page_token`, ...). An operation's `x-pagination` names those an API calls + otherwise, by their JSON names (`cursor`, `next`, `more`, `items`), and fails + the run where they do not fit; `"x-pagination": false` leaves an operation + without iterators. The caller's parameters and body are copied, not changed. - **Error responses** — an error body's type is returned wrapped in `api.Error`, so it needs an `Error() string` method. The generator does not write one, since a good message depends on the API: add it by hand beside the diff --git a/README/features.md b/README/features.md index 9f55b8db..62fd4e03 100644 --- a/README/features.md +++ b/README/features.md @@ -189,6 +189,19 @@ How the specification maps onto Go: not JSON is returned as `[]byte`. The server copies a returned reader into the response, and the JavaScript client returns such a body as a `Blob`, or text as a string. +- **Paging** — an operation whose list is paged through by cursor also gets + `XPages`, which yields each page, and `XAll`, which yields every item, each + fetching the next page as the one before is used up, and stopping when the + loop breaks and at the first error, which it yields. Such a list is found + by its members: a list of items (`results`, `data`, `items`), the cursor of + the next page (`next_cursor`, `next_page_token`, ...) and, if there is one, + whether there is a next page (`has_more`), where there is none once the + cursor is zero; and by a cursor of the same type the operation takes, as a + query parameter or a member of the body (`start_cursor`, `cursor`, + `page_token`, ...). An operation's `x-pagination` names those an API calls + otherwise, by their JSON names (`cursor`, `next`, `more`, `items`), and fails + the run where they do not fit; `"x-pagination": false` leaves an operation + without iterators. The caller's parameters and body are copied, not changed. - **Error responses** — an error body's type is returned wrapped in `api.Error`, so it needs an `Error() string` method. The generator does not write one, since a good message depends on the API: add it by hand beside the diff --git a/golden_test.go b/golden_test.go index 75cba00f..d758d159 100644 --- a/golden_test.go +++ b/golden_test.go @@ -13,6 +13,7 @@ import ( _ "github.com/MarkRosemaker/cassette" _ "github.com/go-api-libs/api" _ "github.com/go-api-libs/api/apitest" + _ "github.com/go-api-libs/api/paging" _ "github.com/go-api-libs/api/server" _ "github.com/go-api-libs/api/union" ) diff --git a/ir/document.go b/ir/document.go index 59de962f..6897c46e 100644 --- a/ir/document.go +++ b/ir/document.go @@ -77,6 +77,10 @@ func FromDocument(doc *openapi.Document, packageName, userAgent string, producti return nil, fmt.Errorf("paths: %w", err) } + if err := paginate(operations, schemas); err != nil { + return nil, fmt.Errorf("paths: %w", err) + } + hasURL, hasDuration, hasDate, hasDateTimeOrInt := needsSpecialImports(schemas, operations) encodings, err := markEncodings(schemas) diff --git a/ir/ir.go b/ir/ir.go index 2cb222fc..612b6de3 100644 --- a/ir/ir.go +++ b/ir/ir.go @@ -127,6 +127,11 @@ type Operation struct { // StreamSuccess is true when the operation's success response is not text (see Response.IsStream), so // SuccessReturn is io.ReadCloser and the method leaves the response body open for the caller. StreamSuccess bool `json:"streamSuccess,omitzero"` + // Pagination is how the operation's list is paged through by cursor, if it is: the client then has an iterator + // of its pages and one of their items. + Pagination *Pagination `json:"pagination,omitempty"` + + pagination paginationExt // what the operation's x-pagination says } func (op Operation) ParamsInStruct() Params { diff --git a/ir/operation.go b/ir/operation.go index dd1f8d56..6076fbd6 100644 --- a/ir/operation.go +++ b/ir/operation.go @@ -105,6 +105,11 @@ func FromOperation( return nil, fmt.Errorf("responses: %w", err) } + pagination, err := readPaginationExt(op.Extensions) + if err != nil { + return nil, err + } + return &Operation{ Name: name, Description: op.Description, @@ -125,6 +130,7 @@ func FromOperation( RawBytesSuccess: rawBytesSuccess, StreamSuccess: streamSuccess, EmptySuccess: emptySuccess, + pagination: pagination, }, nil } diff --git a/ir/pagination.go b/ir/pagination.go new file mode 100644 index 00000000..5c675685 --- /dev/null +++ b/ir/pagination.go @@ -0,0 +1,293 @@ +package ir + +import ( + "encoding/json/jsontext" + "encoding/json/v2" + "fmt" + "slices" + "strings" +) + +// Pagination is how an operation's list is paged through by cursor: the client sends the cursor of the page it wants, +// none for the first, and the list says the cursor of the next, and whether there is one. The client gets an +// iterator of the pages and one of their items. +type Pagination struct { + // CursorType is the Go type of the cursor, which the list's NextField holds. + CursorType string `json:"cursorType,omitzero"` + // Prepare is the Go statements that put the cursor, as cursor, into the request, copying what the caller passed + // rather than changing it; Args is the arguments the operation is then called with, after its context. + Prepare string `json:"prepare,omitzero"` + Args string `json:"args,omitzero"` + // NextField and MoreField are the fields of the list holding the cursor of the next page and whether there is + // one; without the latter, there is one if the cursor is not zero. + NextField string `json:"nextField,omitzero"` + MoreField string `json:"moreField,omitzero"` + // ItemsField is the field of the list holding its items, each of ItemType. + ItemsField string `json:"itemsField,omitzero"` + ItemType string `json:"itemType,omitzero"` +} + +// The names a list's members and the cursor a request sends are found by, where x-pagination names none. +var ( + cursorNames = []string{"start_cursor", "cursor", "page_token", "pageToken"} + nextNames = []string{"next_cursor", "nextCursor", "next_page_token", "nextPageToken"} + moreNames = []string{"has_more", "hasMore", "has_next_page"} + itemsNames = []string{"results", "data", "items"} +) + +// paginationExt is what an operation's x-pagination says: the JSON names of the cursor the request sends and of the +// list's members, any of which may be left to be found, or that the operation is not paged through, as false. +type paginationExt struct { + set, off bool + Cursor, Next, More, Items string +} + +// readPaginationExt reads the x-pagination of an operation's extensions. +func readPaginationExt(ext jsontext.Value) (paginationExt, error) { + if len(ext) == 0 { + return paginationExt{}, nil + } + + var all map[string]jsontext.Value + if err := json.Unmarshal(ext, &all); err != nil { + return paginationExt{}, err + } + + raw, ok := all["x-pagination"] + if !ok { + return paginationExt{}, nil + } + + if string(raw) == "false" { + return paginationExt{set: true, off: true}, nil + } + + var p struct { + Cursor string `json:"cursor"` + Next string `json:"next"` + More string `json:"more"` + Items string `json:"items"` + } + if err := json.Unmarshal(raw, &p, json.RejectUnknownMembers(true)); err != nil { + return paginationExt{}, fmt.Errorf("x-pagination: %w", err) + } + + return paginationExt{set: true, Cursor: p.Cursor, Next: p.Next, More: p.More, Items: p.Items}, nil +} + +// paginate gives each operation whose list is paged through by cursor its Pagination: what its x-pagination names, +// or else what is found by the names lists and cursors commonly have. One x-pagination names but does not fit fails. +func paginate(ops []Operation, schemas []Schema) error { + byName := make(map[string]*Schema, len(schemas)) + for i := range schemas { + byName[schemas[i].Name] = &schemas[i] + } + + taken := map[string]bool{} + for _, op := range ops { + taken[op.Name] = true + } + + for i := range ops { + op := &ops[i] + if op.pagination.off { + continue + } + + p, err := pagination(op, byName) + if err == nil && (taken[op.Name+"Pages"] || taken[op.Name+"All"]) { + err = fmt.Errorf("%sPages or %sAll is the name of an operation", op.Name, op.Name) + } + + switch { + case err == nil: + op.Pagination = p + case op.pagination.set: + return fmt.Errorf("%s: x-pagination: %w", op.Name, err) + } + } + + return nil +} + +// pagination is how op's list is paged through, or why it cannot be. +func pagination(op *Operation, byName map[string]*Schema) (*Pagination, error) { + ext := op.pagination + + if op.SuccessReturn == nil || op.RawBytesSuccess || op.StreamSuccess { + return nil, fmt.Errorf("it answers with no list") + } + + list := byName[op.SuccessReturn.Name] + if list == nil || list.Kind != SchemaKindStruct { + return nil, fmt.Errorf("it answers with no object") + } + + items := fieldOf(list, ext.Items, itemsNames) + if items == nil || !strings.HasPrefix(items.Type, "[]") { + return nil, fmt.Errorf("%s has no list of items", list.Name) + } + + next := fieldOf(list, ext.Next, nextNames) + if next == nil || strings.HasPrefix(next.Type, "*") { + return nil, fmt.Errorf("%s has no cursor of the next page", list.Name) + } + + more := fieldOf(list, ext.More, moreNames) + if more != nil && more.Type != "bool" { + return nil, fmt.Errorf("%s.%s is no bool", list.Name, more.Name) + } + + p := &Pagination{ + CursorType: next.Type, NextField: next.Name, ItemsField: items.Name, ItemType: strings.TrimPrefix(items.Type, "[]"), + } + if more != nil { + p.MoreField = more.Name + } + + // the cursor is a query parameter or a member of the body + cursorNames := cursorNames + if ext.Cursor != "" { + cursorNames = []string{ext.Cursor} + } + + set := func(holder, field, typ string) error { + switch typ { + case next.Type, aliasOf(byName, next.Type): + p.Prepare = holder + "." + field + " = cursor" + case "*" + next.Type: + p.Prepare = holder + "." + field + " = &cursor" + default: + return fmt.Errorf("the cursor it takes is a %s, the one its list gives a %s", typ, next.Type) + } + + return nil + } + + args := op.CallArgs() + p.Args = args + + if i := slices.IndexFunc(op.QueryParams, func(q Param) bool { return slices.Contains(cursorNames, q.JSONName) }); i >= 0 { + q := op.QueryParams[i] + + if op.ParamsInStruct().Required() { + return p, set("params", q.FieldName, q.Type) + } + + if err := set("p", q.FieldName, q.Type); err != nil { + return nil, err + } + + p.Prepare = "var p " + op.ParamStructName + "\nif params != nil {\np = *params\n}\n" + p.Prepare + p.Args = strings.Replace(args, ", params", ", &p", 1) + + return p, nil + } + + if op.RequestBody != nil { + body := byName[strings.TrimPrefix(op.RequestBody.TypeName, "*")] + if f := fieldOf(body, ext.Cursor, cursorNames); body != nil && f != nil { + if op.RequestBody.Required { + return p, set("body", f.Name, f.Type) + } + + if err := set("b", f.Name, f.Type); err != nil { + return nil, err + } + + p.Prepare = "var b " + op.RequestBody.TypeName + "\nif body != nil {\nb = *body\n}\n" + p.Prepare + p.Args = strings.Replace(args, ", body", ", &b", 1) + + return p, nil + } + } + + return nil, fmt.Errorf("it takes no cursor") +} + +// fieldOf is the field of s whose JSON name is name, or, where name is empty, the first of names; nil for none. +func fieldOf(s *Schema, name string, names []string) *Field { + if s == nil { + return nil + } + + if name != "" { + names = []string{name} + } + + for _, n := range names { + if i := slices.IndexFunc(s.Fields, func(f Field) bool { return f.JSONName == n }); i >= 0 { + return &s.Fields[i] + } + } + + return nil +} + +// aliasOf is the type the schema named name is an alias of, or "" if it is none. +func aliasOf(byName map[string]*Schema, name string) string { + if s := byName[name]; s != nil && s.IsTypeAlias { + return s.Type + } + + return "" +} + +// Zero is the zero value of the cursor, which a list without a MoreField ends with. +func (p Pagination) Zero() string { + if p.CursorType == "string" { + return `""` + } + + return "*new(" + p.CursorType + ")" +} + +// ArgsDecl is the parameters of the operation's method after its context, as declared. +func (op Operation) ArgsDecl() string { + var b strings.Builder + + for _, p := range op.PathParams { + b.WriteString(", " + p.GoName + " " + p.Type) + } + + if op.ParamsInStruct() != nil { + b.WriteString(", params ") + + if !op.ParamsInStruct().Required() { + b.WriteString("*") + } + + b.WriteString(op.ParamStructName) + } + + if op.RequestBody != nil { + b.WriteString(", body ") + + if !op.RequestBody.Required { + b.WriteString("*") + } + + b.WriteString(op.RequestBody.TypeName) + } + + return b.String() +} + +// CallArgs is the arguments the operation's method is called with after its context, as ArgsDecl names them. +func (op Operation) CallArgs() string { + var b strings.Builder + + for _, p := range op.PathParams { + b.WriteString(", " + p.GoName) + } + + if op.ParamsInStruct() != nil { + b.WriteString(", params") + } + + if op.RequestBody != nil { + b.WriteString(", body") + } + + return b.String() +} diff --git a/ir/pagination_internal_test.go b/ir/pagination_internal_test.go new file mode 100644 index 00000000..c33ddef0 --- /dev/null +++ b/ir/pagination_internal_test.go @@ -0,0 +1,88 @@ +package ir + +import ( + "encoding/json/jsontext" + "strings" + "testing" +) + +func TestReadPaginationExt(t *testing.T) { + t.Parallel() + + for _, tc := range []struct { + ext string + want paginationExt + wantErr bool + }{ + {"", paginationExt{}, false}, + {`{"x-other":1}`, paginationExt{}, false}, + {`{"x-pagination":false}`, paginationExt{set: true, off: true}, false}, + {`{"x-pagination":{"cursor":"after","items":"entries"}}`, paginationExt{set: true, Cursor: "after", Items: "entries"}, false}, + {`{"x-pagination":{"cursr":"after"}}`, paginationExt{}, true}, + } { + got, err := readPaginationExt(jsontext.Value(tc.ext)) + if (err != nil) != tc.wantErr || got != tc.want { + t.Errorf("%s: got %+v, %v; want %+v, error %v", tc.ext, got, err, tc.want, tc.wantErr) + } + } +} + +// listOp is an operation that takes a cursor of the type as a query parameter and answers with a list L, whose next +// cursor is a string. +func listOp(cursorType string, ext paginationExt) Operation { + return Operation{ + Name: "ListThings", + ParamStructName: "ListThingsParams", + QueryParams: Params{{JSONName: "start_cursor", FieldName: "StartCursor", Type: cursorType}}, + SuccessReturn: &GoType{Name: "L"}, + pagination: ext, + } +} + +var listSchemas = []Schema{{Name: "L", Kind: SchemaKindStruct, Fields: []Field{ + {Name: "Results", JSONName: "results", Type: "[]Thing"}, + {Name: "NextCursor", JSONName: "next_cursor", Type: "string"}, + {Name: "HasMore", JSONName: "has_more", Type: "bool"}, +}}} + +func TestPaginate(t *testing.T) { + t.Parallel() + + ops := []Operation{listOp("string", paginationExt{})} + if err := paginate(ops, listSchemas); err != nil { + t.Fatal(err) + } + + p := ops[0].Pagination + if p == nil { + t.Fatal("a list of results, a next cursor and has_more is not paged through") + } + + if want := (Pagination{ + CursorType: "string", NextField: "NextCursor", MoreField: "HasMore", ItemsField: "Results", ItemType: "Thing", + Prepare: "var p ListThingsParams\nif params != nil {\np = *params\n}\np.StartCursor = cursor", Args: ", &p", + }); *p != want { + t.Errorf("got %+v\nwant %+v", *p, want) + } + + // a cursor of another type than the list's is no cursor of the list, unless x-pagination says it is + ops = []Operation{listOp("int", paginationExt{})} + if err := paginate(ops, listSchemas); err != nil || ops[0].Pagination != nil { + t.Errorf("a cursor of another type: got %+v, %v; want none", ops[0].Pagination, err) + } + + ops = []Operation{listOp("int", paginationExt{set: true})} + if err := paginate(ops, listSchemas); err == nil || !strings.Contains(err.Error(), "ListThings: x-pagination") { + t.Errorf("x-pagination on a cursor of another type: got %v, want its error", err) + } + + ops = []Operation{listOp("string", paginationExt{set: true, off: true})} + if err := paginate(ops, listSchemas); err != nil || ops[0].Pagination != nil { + t.Errorf("x-pagination false: got %+v, %v; want none", ops[0].Pagination, err) + } + + ops = []Operation{listOp("string", paginationExt{}), {Name: "ListThingsAll"}} + if err := paginate(ops, listSchemas); err != nil || ops[0].Pagination != nil { + t.Errorf("a name taken: got %+v, %v; want none", ops[0].Pagination, err) + } +} diff --git a/render/imports.go b/render/imports.go index 9fcec519..45023454 100644 --- a/render/imports.go +++ b/render/imports.go @@ -24,6 +24,7 @@ var importPaths = map[string]string{ "http": "net/http", "httptest": "net/http/httptest", "io": "io", + "iter": "iter", "json": "encoding/json/v2", "jsontext": "encoding/json/jsontext", "maps": "maps", @@ -43,6 +44,7 @@ var importPaths = map[string]string{ "cassette": "github.com/MarkRosemaker/cassette", "civil": "cloud.google.com/go/civil", "jsonutil": "github.com/MarkRosemaker/jsonutil", + "paging": "github.com/go-api-libs/api/paging", "server": "github.com/go-api-libs/api/server", "types": "github.com/go-api-libs/types", "union": "github.com/go-api-libs/api/union", diff --git a/render/templates/client.gen.go.tmpl b/render/templates/client.gen.go.tmpl index 3dbeb597..465c5bab 100644 --- a/render/templates/client.gen.go.tmpl +++ b/render/templates/client.gen.go.tmpl @@ -423,6 +423,32 @@ func (c *Client) {{.Name}}(ctx context.Context{{range .PathParams}}, {{.GoName}} {{ end -}} } } +{{- with .Pagination }} + +// {{ $op.Name }}Pages yields each page of what {{ $op.Name }} lists, fetching the next as the one before is used up. +// It stops when the loop breaks, and at the first error, which it yields. +func (c *Client) {{ $op.Name }}Pages(ctx context.Context{{ $op.ArgsDecl }}) iter.Seq2[{{ $op.SuccessReturn.Nilable }}, error] { + return paging.Pages(func(cursor {{ .CursorType }}) ({{ $op.SuccessReturn.Nilable }}, error) { + {{ .Prepare }} + + return c.{{ $op.Name }}(ctx{{ .Args }}) + }, func(l {{ $op.SuccessReturn.Nilable }}) ({{ .CursorType }}, bool) { + {{- if .MoreField }} + return l.{{ .NextField }}, l.{{ .MoreField }} + {{- else }} + return l.{{ .NextField }}, l.{{ .NextField }} != {{ .Zero }} + {{- end }} + }) +} + +// {{ $op.Name }}All yields every item of what {{ $op.Name }} lists, fetching a page at a time. It stops when the loop +// breaks, and at the first error, which it yields. +func (c *Client) {{ $op.Name }}All(ctx context.Context{{ $op.ArgsDecl }}) iter.Seq2[{{ .ItemType }}, error] { + return paging.Items(c.{{ $op.Name }}Pages(ctx{{ $op.CallArgs }}), func(l {{ $op.SuccessReturn.Nilable }}) []{{ .ItemType }} { + return l.{{ .ItemsField }} + }) +} +{{- end }} {{end}} {{- if .EscapesQuery }} diff --git a/testdata/golden/api/openapi.json b/testdata/golden/api/openapi.json index c51fb238..da8c2738 100644 --- a/testdata/golden/api/openapi.json +++ b/testdata/golden/api/openapi.json @@ -230,7 +230,68 @@ ] } }, + "/entries/query": { + "post": { + "operationId": "queryEntries", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "kind": { "type": "string" }, + "cursor": { "type": "string" } + } + } + } + } + }, + "responses": { + "200": { + "description": "a page of the entries of the kind, and the cursor of the next, empty after the last", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": ["items", "next_page_token"], + "properties": { + "items": { "type": "array", "items": { "$ref": "#/components/schemas/Entry" } }, + "next_page_token": { "type": "string" } + } + } + } + } + } + } + } + }, "/entries": { + "get": { + "operationId": "listEntries", + "parameters": [ + { "name": "start_cursor", "in": "query", "schema": { "type": "string", "format": "uuid" } }, + { "name": "page_size", "in": "query", "schema": { "type": "integer", "maximum": 100 } } + ], + "responses": { + "200": { + "description": "a page of the entries", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": ["results", "next_cursor", "has_more"], + "properties": { + "results": { "type": "array", "items": { "$ref": "#/components/schemas/Entry" } }, + "next_cursor": { "oneOf": [{ "type": "string", "format": "uuid" }, { "type": "null" }] }, + "has_more": { "type": "boolean" } + } + } + } + } + } + } + }, "post": { "operationId": "createEntry", "requestBody": { diff --git a/testdata/golden/pkg/golden/api.js b/testdata/golden/pkg/golden/api.js index 41d84f3f..05d54ae0 100644 --- a/testdata/golden/pkg/golden/api.js +++ b/testdata/golden/pkg/golden/api.js @@ -14,6 +14,8 @@ * const result = await window.API.getTrial(id); * const result = await window.API.updateUser(id); * window.API.patchUser(id); + * const result = await window.API.queryEntries(); + * const result = await window.API.listEntries(); * const result = await window.API.createEntry(); * const result = await window.API.getValue(id); * const result = await window.API.getBlock(id); @@ -136,6 +138,21 @@ window.API = { body: JSON.stringify(body), operationId: "PatchUser", }), + // POST /entries/query + queryEntries: (body) => apiFetch("/entries/query", { + method: "POST", + body: JSON.stringify(body), + operationId: "QueryEntries", + }), + // GET /entries + listEntries: (params = {}) => { + const q = new URLSearchParams(); + if (params.startCursor != null) q.set("start_cursor", String(params.startCursor)); + if (params.pageSize != null) q.set("page_size", String(params.pageSize)); + return apiFetch(`/entries?${q}`, { + operationId: "ListEntries", + }); + }, // POST /entries createEntry: (body) => apiFetch("/entries", { method: "POST", diff --git a/testdata/golden/pkg/golden/client.gen.go b/testdata/golden/pkg/golden/client.gen.go index ec6576f4..dfae5183 100644 --- a/testdata/golden/pkg/golden/client.gen.go +++ b/testdata/golden/pkg/golden/client.gen.go @@ -9,6 +9,7 @@ import ( "encoding/json/v2" "fmt" "io" + "iter" "maps" "net/http" "net/url" @@ -16,9 +17,11 @@ import ( "strconv" "strings" "time" + "uuid" "cloud.google.com/go/civil" "github.com/go-api-libs/api" + "github.com/go-api-libs/api/paging" ) const defaultUserAgent = "Golden" @@ -349,6 +352,151 @@ func (c *Client) PatchUser(ctx context.Context, id string, body *User) error { } } +// POST /entries/query +func (c *Client) QueryEntries(ctx context.Context, body QueryEntries) (*QueryEntriesOk, error) { + u := c.baseURL.JoinPath("entries", "query") + pr, pw := io.Pipe() + req := (&http.Request{ + Header: http.Header{ + "User-Agent": []string{c.userAgent}, + "Content-Type": []string{"application/json"}, + }, + Host: u.Host, + Method: http.MethodPost, + Proto: "HTTP/1.1", + ProtoMajor: 1, + ProtoMinor: 1, + URL: u, + Body: pr, + ContentLength: -1, + }).WithContext(ctx) + + go func() { pw.CloseWithError(json.MarshalWrite(pw, body, jsonOptsRequest)) }() + defer pr.Close() + + rsp, err := c.cli.Do(req) + if err != nil { + return nil, err + } + defer rsp.Body.Close() + + switch rsp.StatusCode { + case http.StatusOK: + // a page of the entries of the kind, and the cursor of the next, empty after the last + switch mt, _, _ := strings.Cut(rsp.Header.Get("Content-Type"), ";"); mt { + case "application/json": + var out QueryEntriesOk + if err := json.UnmarshalRead(rsp.Body, &out, jsonOpts); err != nil { + return nil, api.WrapDecodingError(rsp, err) + } + + return &out, nil + default: + return nil, api.NewErrUnknownContentType(rsp) + } + default: + return nil, api.NewErrUnknownStatusCode(rsp) + } +} + +// QueryEntriesPages yields each page of what QueryEntries lists, fetching the next as the one before is used up. +// It stops when the loop breaks, and at the first error, which it yields. +func (c *Client) QueryEntriesPages(ctx context.Context, body QueryEntries) iter.Seq2[*QueryEntriesOk, error] { + return paging.Pages(func(cursor string) (*QueryEntriesOk, error) { + body.Cursor = cursor + + return c.QueryEntries(ctx, body) + }, func(l *QueryEntriesOk) (string, bool) { + return l.NextPageToken, l.NextPageToken != "" + }) +} + +// QueryEntriesAll yields every item of what QueryEntries lists, fetching a page at a time. It stops when the loop +// breaks, and at the first error, which it yields. +func (c *Client) QueryEntriesAll(ctx context.Context, body QueryEntries) iter.Seq2[Entry, error] { + return paging.Items(c.QueryEntriesPages(ctx, body), func(l *QueryEntriesOk) []Entry { + return l.Items + }) +} + +// GET /entries +func (c *Client) ListEntries(ctx context.Context, params *ListEntriesParams) (*ListEntriesOk, error) { + u := c.baseURL.JoinPath("entries") + if params != nil { + q := make(url.Values, 2) + + if params.StartCursor != uuid.Nil() { + q["start_cursor"] = []string{params.StartCursor.String()} + } + + if params.PageSize != 0 { + q["page_size"] = []string{strconv.Itoa(params.PageSize)} + } + + u.RawQuery = q.Encode() + } + + req := (&http.Request{ + Header: http.Header{ + "User-Agent": []string{c.userAgent}, + }, + Host: u.Host, + Method: http.MethodGet, + Proto: "HTTP/1.1", + ProtoMajor: 1, + ProtoMinor: 1, + URL: u, + }).WithContext(ctx) + + rsp, err := c.cli.Do(req) + if err != nil { + return nil, err + } + defer rsp.Body.Close() + + switch rsp.StatusCode { + case http.StatusOK: + // a page of the entries + switch mt, _, _ := strings.Cut(rsp.Header.Get("Content-Type"), ";"); mt { + case "application/json": + var out ListEntriesOk + if err := json.UnmarshalRead(rsp.Body, &out, jsonOpts); err != nil { + return nil, api.WrapDecodingError(rsp, err) + } + + return &out, nil + default: + return nil, api.NewErrUnknownContentType(rsp) + } + default: + return nil, api.NewErrUnknownStatusCode(rsp) + } +} + +// ListEntriesPages yields each page of what ListEntries lists, fetching the next as the one before is used up. +// It stops when the loop breaks, and at the first error, which it yields. +func (c *Client) ListEntriesPages(ctx context.Context, params *ListEntriesParams) iter.Seq2[*ListEntriesOk, error] { + return paging.Pages(func(cursor uuid.UUID) (*ListEntriesOk, error) { + var p ListEntriesParams + if params != nil { + p = *params + } + p.StartCursor = cursor + + return c.ListEntries(ctx, &p) + }, func(l *ListEntriesOk) (uuid.UUID, bool) { + return l.NextCursor, l.HasMore + }) +} + +// ListEntriesAll yields every item of what ListEntries lists, fetching a page at a time. It stops when the loop +// breaks, and at the first error, which it yields. +func (c *Client) ListEntriesAll(ctx context.Context, params *ListEntriesParams) iter.Seq2[Entry, error] { + return paging.Items(c.ListEntriesPages(ctx, params), func(l *ListEntriesOk) []Entry { + return l.Results + }) +} + // Body: The entry to create, without its id. // // Returns: The entry created, with its id. diff --git a/testdata/golden/pkg/golden/client.gen_test.go b/testdata/golden/pkg/golden/client.gen_test.go index 92b0bbb1..72126b74 100644 --- a/testdata/golden/pkg/golden/client.gen_test.go +++ b/testdata/golden/pkg/golden/client.gen_test.go @@ -750,6 +750,216 @@ func TestClient_Error(t *testing.T) { }) }) + t.Run("QueryEntries", func(t *testing.T) { + 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.QueryEntries(t.Context(), QueryEntries{}); 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.QueryEntries(t.Context(), QueryEntries{}); 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.QueryEntries(t.Context(), QueryEntries{}); 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.QueryEntries(t.Context(), QueryEntries{}); 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("unknown member", func(t *testing.T) { + c, err := NewClient(WithBaseURL(apitest.BodyServer(t, http.StatusOK, "application/json", apitest.WithUnknownMember(t, QueryEntriesOk{}, jsonOpts)))) + if err != nil { + t.Fatal(err) + } + + if _, err := c.QueryEntries(t.Context(), QueryEntries{}); err == nil { + t.Fatal("the package's own type accepted a member it does not declare") + } else if _, ok := errors.AsType[*api.DecodingError](err); !ok { + t.Fatalf("got: %T, want: *api.DecodingError", err) + } + }) + }) + + t.Run("ListEntries", func(t *testing.T) { + 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.ListEntries(t.Context(), nil); 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.ListEntries(t.Context(), nil); 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.ListEntries(t.Context(), nil); 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.ListEntries(t.Context(), nil); 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("unknown member", func(t *testing.T) { + c, err := NewClient(WithBaseURL(apitest.BodyServer(t, http.StatusOK, "application/json", apitest.WithUnknownMember(t, ListEntriesOk{}, jsonOpts)))) + if err != nil { + t.Fatal(err) + } + + if _, err := c.ListEntries(t.Context(), nil); err == nil { + t.Fatal("the package's own type accepted a member it does not declare") + } else if _, ok := errors.AsType[*api.DecodingError](err); !ok { + t.Fatalf("got: %T, want: *api.DecodingError", err) + } + }) + }) + t.Run("CreateEntry", func(t *testing.T) { t.Run("transport error", func(t *testing.T) { c, err := NewClient(WithHTTPClient(&http.Client{Transport: apitest.RoundTripFunc( @@ -1961,6 +2171,32 @@ func TestClient_Error(t *testing.T) { // TestClient_Params sets every parameter it can to a value other than its zero value, and finds each in the request, // under its name and written as the client must write it. func TestClient_Params(t *testing.T) { + t.Run("ListEntries", func(t *testing.T) { + var got *http.Request + + c, err := NewClient(WithHTTPClient(&http.Client{Transport: apitest.RoundTripFunc( + func(r *http.Request) (*http.Response, error) { + got = r + + return &http.Response{StatusCode: http.StatusTeapot, Header: http.Header{}, Body: http.NoBody, Request: r}, nil + }, + )})) + if err != nil { + t.Fatal(err) + } + + _, _ = c.ListEntries(t.Context(), &ListEntriesParams{ + PageSize: 2, + }) + + if got == nil { + t.Fatal("no request was sent") + } + + if v := got.URL.Query().Get("page_size"); v != "2" { + t.Errorf("query %s: got %q, want %q", "page_size", v, "2") + } + }) t.Run("ListReports", func(t *testing.T) { var got *http.Request diff --git a/testdata/golden/pkg/golden/ir.json b/testdata/golden/pkg/golden/ir.json index 43a1201f..545467a0 100644 --- a/testdata/golden/pkg/golden/ir.json +++ b/testdata/golden/pkg/golden/ir.json @@ -248,6 +248,95 @@ } ] }, + { + "name": "QueryEntries", + "method": "POST", + "pathTemplate": "/entries/query", + "joinPathArgs": [ + "\"entries\"", + "\"query\"" + ], + "requestBody": { + "typeName": "QueryEntries", + "contentType": "application/json", + "required": true + }, + "responses": [ + { + "statusCode": "200", + "goConstant": "http.StatusOK", + "description": "a page of the entries of the kind, and the cursor of the next, empty after the last", + "contentType": "application/json", + "goType": { + "name": "QueryEntriesOk" + }, + "isSuccess": true + } + ], + "successReturn": { + "name": "QueryEntriesOk" + }, + "pagination": { + "cursorType": "string", + "prepare": "body.Cursor = cursor", + "args": ", body", + "nextField": "NextPageToken", + "itemsField": "Items", + "itemType": "Entry" + } + }, + { + "name": "ListEntries", + "method": "GET", + "pathTemplate": "/entries", + "joinPathArgs": [ + "\"entries\"" + ], + "queryParams": [ + { + "varName": "params.StartCursor", + "goName": "startCursor", + "fieldName": "StartCursor", + "jsonName": "start_cursor", + "type": "uuid.UUID", + "parseExpr": "uuid.Parse(%s)" + }, + { + "varName": "params.PageSize", + "goName": "pageSize", + "fieldName": "PageSize", + "jsonName": "page_size", + "type": "int", + "parseExpr": "strconv.Atoi(%s)" + } + ], + "hasParams": true, + "paramStructName": "ListEntriesParams", + "responses": [ + { + "statusCode": "200", + "goConstant": "http.StatusOK", + "description": "a page of the entries", + "contentType": "application/json", + "goType": { + "name": "ListEntriesOk" + }, + "isSuccess": true + } + ], + "successReturn": { + "name": "ListEntriesOk" + }, + "pagination": { + "cursorType": "uuid.UUID", + "prepare": "var p ListEntriesParams\nif params != nil {\np = *params\n}\np.StartCursor = cursor", + "args": ", &p", + "nextField": "NextCursor", + "moreField": "HasMore", + "itemsField": "Results", + "itemType": "Entry" + } + }, { "name": "CreateEntry", "method": "POST", @@ -2557,6 +2646,33 @@ } ] }, + { + "name": "ListEntriesOk", + "description": "ListEntriesOk defines a model", + "fields": [ + { + "name": "Results", + "jsonName": "results", + "type": "[]Entry", + "jsonTag": "json:\"results\"", + "required": true + }, + { + "name": "NextCursor", + "jsonName": "next_cursor", + "type": "uuid.UUID", + "jsonTag": "json:\"next_cursor\"", + "required": true + }, + { + "name": "HasMore", + "jsonName": "has_more", + "type": "bool", + "jsonTag": "json:\"has_more\"", + "required": true + } + ] + }, { "name": "ListPeopleOk", "description": "ListPeopleOk defines a model", @@ -4094,6 +4210,44 @@ ] } }, + { + "name": "QueryEntries", + "description": "QueryEntries defines a model", + "fields": [ + { + "name": "Kind", + "jsonName": "kind", + "type": "string", + "jsonTag": "json:\"kind,omitzero\"" + }, + { + "name": "Cursor", + "jsonName": "cursor", + "type": "string", + "jsonTag": "json:\"cursor,omitzero\"" + } + ] + }, + { + "name": "QueryEntriesOk", + "description": "QueryEntriesOk defines a model", + "fields": [ + { + "name": "Items", + "jsonName": "items", + "type": "[]Entry", + "jsonTag": "json:\"items\"", + "required": true + }, + { + "name": "NextPageToken", + "jsonName": "next_page_token", + "type": "string", + "jsonTag": "json:\"next_page_token\"", + "required": true + } + ] + }, { "name": "Record", "description": "Record defines a model", diff --git a/testdata/golden/pkg/golden/paging_test.go b/testdata/golden/pkg/golden/paging_test.go new file mode 100644 index 00000000..a02f56e0 --- /dev/null +++ b/testdata/golden/pkg/golden/paging_test.go @@ -0,0 +1,115 @@ +// This file is written by hand, not by the generator. +// +// It pages through the lists the generator found to be paged by cursor: one by a query parameter and has_more, one +// by a member of the body and a cursor that is empty after the last page. + +package golden + +import ( + "encoding/json/v2" + "net/http" + "net/http/httptest" + "net/url" + "slices" + "testing" + "uuid" +) + +// serve is a client of a server that answers with handle. +func serve(t *testing.T, handle http.HandlerFunc) *Client { + t.Helper() + + srv := httptest.NewServer(handle) + t.Cleanup(srv.Close) + + u, err := url.Parse(srv.URL) + if err != nil { + t.Fatal(err) + } + + c, err := NewClient(WithBaseURL(u)) + if err != nil { + t.Fatal(err) + } + + return c +} + +// notes is what the entries hold, in order. +func notes(t *testing.T, entries func(yield func(Entry, error) bool)) []string { + t.Helper() + + var got []string + + for e, err := range entries { + if err != nil { + t.Fatal(err) + } + + got = append(got, e.Note.Note) + } + + return got +} + +func TestListEntriesAll(t *testing.T) { + next := uuid.New() + + var cursors []string + + c := serve(t, func(w http.ResponseWriter, r *http.Request) { + cursor := r.URL.Query().Get("start_cursor") + cursors = append(cursors, cursor) + + w.Header().Set("Content-Type", "application/json") + + if cursor == "" { + _, _ = w.Write([]byte(`{"results":[{"note":"a"},{"note":"b"}],"next_cursor":"` + next.String() + `","has_more":true}`)) + } else { + _, _ = w.Write([]byte(`{"results":[{"note":"c"}],"next_cursor":null,"has_more":false}`)) + } + }) + + params := &ListEntriesParams{PageSize: 2} + + if got := notes(t, c.ListEntriesAll(t.Context(), params)); !slices.Equal(got, []string{"a", "b", "c"}) { + t.Errorf("got %v, want a, b, c", got) + } + + if !slices.Equal(cursors, []string{"", next.String()}) { + t.Errorf("sent cursors %q, want none, then %s", cursors, next) + } + + if params.StartCursor != uuid.Nil() { + t.Error("paging changed the caller's params") + } +} + +func TestQueryEntriesAll(t *testing.T) { + var sent []QueryEntries + + c := serve(t, func(w http.ResponseWriter, r *http.Request) { + var body QueryEntries + if err := json.UnmarshalRead(r.Body, &body); err != nil { + t.Error(err) + } + + sent = append(sent, body) + + w.Header().Set("Content-Type", "application/json") + + if body.Cursor == "" { + _, _ = w.Write([]byte(`{"items":[{"note":"a"}],"next_page_token":"t2"}`)) + } else { + _, _ = w.Write([]byte(`{"items":[{"note":"b"}],"next_page_token":""}`)) + } + }) + + if got := notes(t, c.QueryEntriesAll(t.Context(), QueryEntries{Kind: "todo"})); !slices.Equal(got, []string{"a", "b"}) { + t.Errorf("got %v, want a, b", got) + } + + if want := []QueryEntries{{Kind: "todo"}, {Kind: "todo", Cursor: "t2"}}; !slices.Equal(sent, want) { + t.Errorf("sent %v, want %v", sent, want) + } +} diff --git a/testdata/golden/pkg/golden/server.gen.go b/testdata/golden/pkg/golden/server.gen.go index f18f64dc..ab2f0080 100644 --- a/testdata/golden/pkg/golden/server.gen.go +++ b/testdata/golden/pkg/golden/server.gen.go @@ -15,6 +15,7 @@ import ( "strconv" "strings" "time" + "uuid" "cloud.google.com/go/civil" "github.com/go-api-libs/api/server" @@ -27,6 +28,8 @@ type Service interface { GetTrial(ctx context.Context, id string) (*Trial, error) UpdateUser(ctx context.Context, id string, body User) (*User, error) PatchUser(ctx context.Context, id string, body *User) error + QueryEntries(ctx context.Context, body QueryEntries) (*QueryEntriesOk, error) + ListEntries(ctx context.Context, params *ListEntriesParams) (*ListEntriesOk, error) CreateEntry(ctx context.Context, body Entry) (*Entry, error) GetValue(ctx context.Context, id string) (*Value, error) GetBlock(ctx context.Context, id string) (*Block, error) @@ -281,6 +284,106 @@ func RegisterService(svc Service, mux *http.ServeMux, pathPrefix string) { }) } + { + path := fmt.Sprintf("%s%s", pathPrefix, "/entries/query") + l := slog.Default().With(slog.String("method", "POST"), slog.String("path", path), slog.String("function", "QueryEntries")) + + mux.HandleFunc(fmt.Sprintf("POST %s", path), func(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + l.DebugContext(ctx, "called") + + var body QueryEntries + if err := json.UnmarshalRead(r.Body, &body, jsonOpts); err != nil { + msg := err.Error() + l.DebugContext(ctx, "Bad Request", slog.String("msg", msg)) + http.Error(w, msg, http.StatusBadRequest) + return + } + + res, err := svc.QueryEntries(ctx, body) + 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, jsonOptsResponse); 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, "/entries") + l := slog.Default().With(slog.String("method", "GET"), slog.String("path", path), slog.String("function", "ListEntries")) + + mux.HandleFunc(fmt.Sprintf("GET %s", path), func(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + l.DebugContext(ctx, "called") + + params, err := parseListEntriesArgs(r) + if err != nil { + msg := err.Error() + l.DebugContext(ctx, "Bad Request", slog.String("msg", msg)) + http.Error(w, msg, http.StatusBadRequest) + return + } + + res, err := svc.ListEntries(ctx, ¶ms) + 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, jsonOptsResponse); 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, "/entries") l := slog.Default().With(slog.String("method", "POST"), slog.String("path", path), slog.String("function", "CreateEntry")) @@ -946,6 +1049,30 @@ func RegisterService(svc Service, mux *http.ServeMux, pathPrefix string) { } } +// parseListEntriesArgs reads the path and query parameters of ListEntries from req. +func parseListEntriesArgs(req *http.Request) (params ListEntriesParams, err error) { + query := req.URL.Query() + + if s := query.Get("start_cursor"); s != "" { + v, err := uuid.Parse(s) + if err != nil { + return params, fmt.Errorf("invalid start_cursor: %w", err) + } + + params.StartCursor = v + } + + if s := query.Get("page_size"); s != "" { + v, err := strconv.Atoi(s) + if err != nil { + return params, fmt.Errorf("invalid page_size: %w", err) + } + + params.PageSize = v + } + return params, nil +} + // parseListReportsArgs reads the path and query parameters of ListReports from req. func parseListReportsArgs(req *http.Request) (params ListReportsParams, err error) { query := req.URL.Query() diff --git a/testdata/golden/pkg/golden/types.gen.go b/testdata/golden/pkg/golden/types.gen.go index c5365444..422feeb1 100644 --- a/testdata/golden/pkg/golden/types.gen.go +++ b/testdata/golden/pkg/golden/types.gen.go @@ -99,6 +99,12 @@ var jsonOptsResponse = json.JoinOptions(jsonOpts, json.WithMarshalers(json.JoinM }), ))) +// ListEntriesParams holds the query parameters for ListEntries. +type ListEntriesParams struct { + StartCursor uuid.UUID + PageSize int +} + // ListReportsParams holds the query parameters for ListReports. type ListReportsParams struct { Since time.Time @@ -1174,6 +1180,13 @@ type Link struct { URL string `json:"url"` } +// ListEntriesOk defines a model +type ListEntriesOk struct { + Results []Entry `json:"results"` + NextCursor uuid.UUID `json:"next_cursor"` + HasMore bool `json:"has_more"` +} + // ListPeopleOk defines a model type ListPeopleOk struct { Results []PeopleArrayBasedPropertyValueResponsePeopleItem `json:"results,omitzero"` @@ -2494,6 +2507,18 @@ func (v *PropertyValue) MarshalJSONTo(enc *jsontext.Encoder) error { return json.MarshalEncode(enc, (*plain)(&out), jsonOptsTo(enc)) } +// QueryEntries defines a model +type QueryEntries struct { + Kind string `json:"kind,omitzero"` + Cursor string `json:"cursor,omitzero"` +} + +// QueryEntriesOk defines a model +type QueryEntriesOk struct { + Items []Entry `json:"items"` + NextPageToken string `json:"next_page_token"` +} + // Record defines a model type Record struct { Meta From f23cc556370bb567ec62a5420a7dbcabec145d03 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 03:02:29 +0000 Subject: [PATCH 2/2] chore: bump go-api-libs/api, whose paging the iterators rest on Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019QCb1AfnATvpBQCH3PrX7Y --- go.mod | 2 +- go.sum | 4 +- vendor/github.com/go-api-libs/api/AGENTS.md | 3 + vendor/github.com/go-api-libs/api/README.md | 9 ++- .../github.com/go-api-libs/api/devtool.json | 4 +- .../go-api-libs/api/paging/paging.go | 57 +++++++++++++++++++ vendor/modules.txt | 3 +- 7 files changed, 75 insertions(+), 7 deletions(-) create mode 100644 vendor/github.com/go-api-libs/api/paging/paging.go diff --git a/go.mod b/go.mod index bdff6847..1240b95e 100644 --- a/go.mod +++ b/go.mod @@ -11,7 +11,7 @@ require ( github.com/MarkRosemaker/openapi-flatten v0.0.0-20261114135009-b46b792b06be github.com/MarkRosemaker/ordmap v0.0.0-20261114134829-166766214acc github.com/ettle/strcase v0.2.0 - github.com/go-api-libs/api v0.0.0-20261113130130-277524695333 + github.com/go-api-libs/api v0.0.0-20261115030148-02c29b673d3a github.com/spf13/afero v1.15.0 mvdan.cc/gofumpt v0.12.0 ) diff --git a/go.sum b/go.sum index ed833e33..60016d4b 100644 --- a/go.sum +++ b/go.sum @@ -30,8 +30,8 @@ github.com/MarkRosemaker/yaml2json v0.0.0-20261114134758-35f07119f480 h1:+NUgW7j github.com/MarkRosemaker/yaml2json v0.0.0-20261114134758-35f07119f480/go.mod h1:DxNA9SDFrzw+RHsnxjIxjUzHy0I4+3hZg7R13u3SBvE= github.com/ettle/strcase v0.2.0 h1:fGNiVF21fHXpX1niBgk0aROov1LagYsOwV/xqKDKR/Q= github.com/ettle/strcase v0.2.0/go.mod h1:DajmHElDSaX76ITe3/VHVyMin4LWSJN5Z909Wp+ED1A= -github.com/go-api-libs/api v0.0.0-20261113130130-277524695333 h1:jHic3tOf6/vtJHZKB5niLbzXcXwl1kcIq1424Wc9xJc= -github.com/go-api-libs/api v0.0.0-20261113130130-277524695333/go.mod h1:nJuMPHY4qEhbWBvTdDFOPK+LC3Uo8RM9kPhIQfzXv4s= +github.com/go-api-libs/api v0.0.0-20261115030148-02c29b673d3a h1:Thu2LNeFzxiWHfVKhRmIu16/N7Rf6vUo5jghCroFc+k= +github.com/go-api-libs/api v0.0.0-20261115030148-02c29b673d3a/go.mod h1:rzjWUX+9lLTr+YF9mMw1rvNNDcnYpEHPGl7OA9qj9ZQ= github.com/go-api-libs/types v0.0.0-20261114134757-0dc6e4300b30 h1:p1IOp1ya/fErQ3tUwXdprKG8vPRzmHVgiJsmRVRmbt0= github.com/go-api-libs/types v0.0.0-20261114134757-0dc6e4300b30/go.mod h1:z0z6qkZc45AvoRnluq7PkVSlSSF25sT0diJ+vrubYfA= github.com/go-quicktest/qt v1.102.0 h1:HSQxCeh5YZH3EL3W39ixjtyaEhcWSXQHtHnMBzSs474= diff --git a/vendor/github.com/go-api-libs/api/AGENTS.md b/vendor/github.com/go-api-libs/api/AGENTS.md index a004623e..c8bd7f8e 100644 --- a/vendor/github.com/go-api-libs/api/AGENTS.md +++ b/vendor/github.com/go-api-libs/api/AGENTS.md @@ -98,6 +98,9 @@ generated. Your own rules go below that block, where they win — in a - Comments are one line, and only where the code would otherwise puzzle a reader. Never a restatement of what it already says. +- Fail at startup when something required is missing, such as an + environment variable, rather than fall back to a default. +- Keep one way to do each thing. - Linters, scanners and generators are installed at their latest by `make tools`, and `devtool.json` pins the versions installed. A run moves a pin up, never back. Do not vendor one or add it to `go.mod` to run it. diff --git a/vendor/github.com/go-api-libs/api/README.md b/vendor/github.com/go-api-libs/api/README.md index f7085da5..206f95ab 100644 --- a/vendor/github.com/go-api-libs/api/README.md +++ b/vendor/github.com/go-api-libs/api/README.md @@ -1,5 +1,5 @@ -[![Go Reference](https://pkg.go.dev/badge/github.com/go-api-libs/api.svg)](https://pkg.go.dev/github.com/go-api-libs/api) ![Code Coverage](https://img.shields.io/badge/coverage-89%25-green) [![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](LICENSE) +[![Go Reference](https://pkg.go.dev/badge/github.com/go-api-libs/api.svg)](https://pkg.go.dev/github.com/go-api-libs/api) ![Code Coverage](https://img.shields.io/badge/coverage-90%25-brightgreen) [![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](LICENSE) ![Code Coverage](https://img.shields.io/badge/coverage-100%25-brightgreen) @@ -15,6 +15,13 @@ It is utilized by all API libraries within the [go-api-libs](https://github.com/ - **Status Code Handling**: Handle and identify errors based on HTTP status codes. - **Content Type Handling**: Handle errors based on content type mismatches. +For the code openapi-codegen generates, it also holds: + +- **`union`**: decoding and encoding unions and tagged structs. +- **`apitest`**: replaying recorded interactions in generated tests. +- **`paging`**: `paging.Pages` and `paging.Items` yield what an API lists a page at a time, fetching each page as the one + before is used up, and stopping when the loop breaks or at the first error. + ## Usage To install the library, run: diff --git a/vendor/github.com/go-api-libs/api/devtool.json b/vendor/github.com/go-api-libs/api/devtool.json index 0da670bd..a26fdd18 100644 --- a/vendor/github.com/go-api-libs/api/devtool.json +++ b/vendor/github.com/go-api-libs/api/devtool.json @@ -1,6 +1,6 @@ { - "coverage": 89.8, - "devtoolVersion": "v0.0.0-20261112195051-ee9871757373", + "coverage": 90.5, + "devtoolVersion": "v0.0.0-20261114134623-f0f0252835dc", "kind": "apilib", "tools": { "golangci-lint": "v2.15.0", diff --git a/vendor/github.com/go-api-libs/api/paging/paging.go b/vendor/github.com/go-api-libs/api/paging/paging.go new file mode 100644 index 00000000..23a8ad6e --- /dev/null +++ b/vendor/github.com/go-api-libs/api/paging/paging.go @@ -0,0 +1,57 @@ +// Package paging yields what an API lists a page at a time, fetching each page as the one before is used up. +package paging + +import "iter" + +// Pages yields each page of a list, which fetch returns given its cursor, the zero cursor for the first, and next +// tells the cursor of the page after, and whether there is one. It stops when the loop breaks, and at the first +// error, which it yields. +func Pages[P any, C comparable](fetch func(cursor C) (P, error), next func(P) (C, bool)) iter.Seq2[P, error] { + return func(yield func(P, error) bool) { + var cursor C + + for { + p, err := fetch(cursor) + if err != nil { + var zero P + + yield(zero, err) + + return + } + + if !yield(p, nil) { + return + } + + c, more := next(p) + if !more { + return + } + + cursor = c + } + } +} + +// Items yields the items of each of pages, which items tells. It stops when the loop breaks, and at the first error, +// which it yields. +func Items[P, T any](pages iter.Seq2[P, error], items func(P) []T) iter.Seq2[T, error] { + return func(yield func(T, error) bool) { + for p, err := range pages { + if err != nil { + var zero T + + yield(zero, err) + + return + } + + for _, item := range items(p) { + if !yield(item, nil) { + return + } + } + } + } +} diff --git a/vendor/modules.txt b/vendor/modules.txt index 80d660d6..8e4574f5 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -40,10 +40,11 @@ github.com/MarkRosemaker/yaml2json # github.com/ettle/strcase v0.2.0 ## explicit; go 1.12 github.com/ettle/strcase -# github.com/go-api-libs/api v0.0.0-20261113130130-277524695333 +# github.com/go-api-libs/api v0.0.0-20261115030148-02c29b673d3a ## explicit; go 1.27 github.com/go-api-libs/api github.com/go-api-libs/api/apitest +github.com/go-api-libs/api/paging github.com/go-api-libs/api/server github.com/go-api-libs/api/union # github.com/go-api-libs/types v0.0.0-20261114134757-0dc6e4300b30