Generate the OpenAPI document from a route table
Security / Vulnerability check (push) Successful in 38s
Test / Lint and test (push) Successful in 1m53s

The server registers its routes from one table in server/routes.go, and
tools/genopenapi (run by go generate) writes docs/swagger.json, an
OpenAPI 3.1 document, from the same table and the Go types it names.
Schemas are reflected with invopop/jsonschema: descriptions from the
first paragraph of the doc comments, enums and limits from jsonschema
tags. Request schemas are strict, as the decoder is; response schemas
allow fields added later. The daemon serves the embedded document at
GET /openapi.json without a token, internal/app passes it to the server
in its config, and release archives and the Docker build include it.

Tests keep it honest: a golden test and a CI step fail when the
document is stale, every registered route must be in the table, and the
tags are held to validation, to the Go constants and to the values the
handlers send. receipt.Element and printqueue.Status gain field doc
comments for the descriptions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
57_WolveandClaude Opus 5.5 committed 2026-11-30 09:30:42 -06:00
1 parent 9f7c5db923
commit bdd337e2dc
31 files changed
+3153 -128

No files matched your search

+355
View File
@@ -0,0 +1,355 @@
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"reflect"
"sort"
"strconv"
"strings"
"unicode"
"unicode/utf8"
"github.com/invopop/jsonschema"
"uberbringer/internal/app/uberbringer/server"
"uberbringer/internal/pkg/printqueue"
"uberbringer/internal/pkg/receipt"
)
const (
componentsPrefix = "#/components/schemas/"
defsPrefix = "#/$defs/"
securityScheme = "bearerAuth"
mediaJSON = "application/json"
// codesExtension lists the error codes a status stands for.
codesExtension = "x-uberbringer-codes"
)
// jobIDPattern matches a job_ TypeID: a UUIDv7 in Crockford base32 after the
// prefix.
const jobIDPattern = "^job_[0-7][0-9a-hjkmnp-tv-z]{25}$"
// Generate returns docs/swagger.json for the route table. root is the
// repository root, whose sources hold the doc comments.
func Generate(root string) ([]byte, error) {
c, err := extractComments(root, server.Route{}, receipt.Job{}, printqueue.Status{})
if err != nil {
return nil, err
}
g := &generator{
requests: newSchemaReflector(c, true),
responses: newSchemaReflector(c, false),
schemas: make(map[string]any),
}
if _, err := g.schemaRef(g.responses, server.ErrorBody()); err != nil {
return nil, err
}
paths := make(map[string]any)
tags := make(map[string]bool)
for _, r := range server.Routes() {
op, err := g.operation(r)
if err != nil {
return nil, fmt.Errorf("%s %s: %w", r.Method, r.Path, err)
}
item, _ := paths[r.Path].(map[string]any)
if item == nil {
item = make(map[string]any)
paths[r.Path] = item
}
item[strings.ToLower(r.Method)] = op
tags[r.Tag] = true
}
var serverErrors []string
for _, e := range server.ServerErrors() {
serverErrors = append(serverErrors, strconv.Itoa(e.Status)+" "+e.Code)
}
doc := map[string]any{
"openapi": "3.1.0",
"info": map[string]any{
"title": "Überbringer HTTP API",
"version": "v1",
"description": "Takes print jobs as JSON and prints them on an Epson ESC/POS receipt printer. " +
"Every error is JSON with a stable code. Each operation lists the codes it and its " +
"middleware answer with; the HTTP server itself can also refuse any request with " +
strings.Join(serverErrors, ", ") + ". Responses from /healthz and every /api/v1 route " +
"carry Cache-Control: no-store. Generated from the route table; do not edit.",
"license": map[string]any{"name": "EUPL-1.2", "identifier": "EUPL-1.2"},
},
"tags": sortedTags(tags),
"paths": paths,
"components": map[string]any{
"schemas": g.schemas,
"securitySchemes": map[string]any{
securityScheme: map[string]any{
"type": "http",
"scheme": "bearer",
"bearerFormat": "JWT",
"description": "An HS256 token signed with api.secret, as `uberbringer token` issues them.",
},
},
},
}
var buf bytes.Buffer
enc := json.NewEncoder(&buf)
enc.SetEscapeHTML(false)
enc.SetIndent("", " ")
if err := enc.Encode(doc); err != nil {
return nil, fmt.Errorf("encoding the document: %w", err)
}
return buf.Bytes(), nil
}
// newSchemaReflector reflects types into JSON Schema 2020-12, the dialect of
// OpenAPI 3.1. A request schema is strict, as the server decodes requests:
// an unknown field is an error, and a field is required only when its
// jsonschema tag says so. A response schema allows additional properties,
// so a field added later does not break a client validating against an
// older document, and requires the fields that are always sent.
func newSchemaReflector(c comments, request bool) *jsonschema.Reflector {
return &jsonschema.Reflector{
Anonymous: true,
AllowAdditionalProperties: !request,
RequiredFromJSONSchemaTags: request,
Namer: schemaName,
Mapper: mapType(c),
LookupComment: c.lookup,
}
}
type generator struct {
requests, responses *jsonschema.Reflector
schemas map[string]any
}
func (g *generator) operation(r server.Route) (map[string]any, error) {
op := map[string]any{
"operationId": r.OperationID,
"summary": r.Summary,
"tags": []string{r.Tag},
}
if r.Description != "" {
op["description"] = r.Description
}
if r.Auth {
op["security"] = []any{map[string]any{securityScheme: []string{}}}
} else {
op["security"] = []any{}
}
if len(r.Params) > 0 {
params := make([]any, len(r.Params))
for i, p := range r.Params {
params[i] = map[string]any{
"name": p.Name,
"in": p.In,
"required": p.Required || p.In == "path",
"description": p.Description,
"schema": map[string]any{"type": "string"},
}
}
op["parameters"] = params
}
if r.Request != nil {
ref, err := g.schemaRef(g.requests, r.Request)
if err != nil {
return nil, err
}
op["requestBody"] = map[string]any{
"required": true,
"content": map[string]any{mediaJSON: map[string]any{"schema": ref}},
}
}
responses, err := g.routeResponses(r)
if err != nil {
return nil, err
}
op["responses"] = responses
return op, nil
}
func (g *generator) routeResponses(r server.Route) (map[string]any, error) {
responses := make(map[string]any)
for _, resp := range r.Responses {
doc := map[string]any{"description": resp.Description}
if len(resp.Content) > 0 {
content := make(map[string]any, len(resp.Content))
for _, c := range resp.Content {
schema, err := g.bodySchema(c.Body)
if err != nil {
return nil, err
}
content[c.MediaType] = map[string]any{"schema": schema}
}
doc["content"] = content
}
if len(resp.Headers) > 0 {
headers := make(map[string]any, len(resp.Headers))
for _, h := range resp.Headers {
schema := map[string]any{"type": "string"}
if h.Integer {
schema = map[string]any{"type": "integer", "minimum": 1}
}
headers[h.Name] = map[string]any{"description": h.Description, "schema": schema}
}
doc["headers"] = headers
}
responses[strconv.Itoa(resp.Status)] = doc
}
byStatus := make(map[int][]server.ErrorDoc)
for _, e := range r.DocumentedErrors() {
byStatus[e.Status] = append(byStatus[e.Status], e)
}
for status, codes := range byStatus {
key := strconv.Itoa(status)
if _, taken := responses[key]; taken {
return nil, fmt.Errorf("status %d is both a response and an error", status)
}
names := make([]string, len(codes))
titles := make([]string, len(codes))
for i, c := range codes {
names[i] = c.Code
titles[i] = c.Code + ": " + c.Message
}
resp := map[string]any{
"description": http.StatusText(status) + ". " + strings.Join(titles, "; ") + ".",
codesExtension: names,
"content": map[string]any{mediaJSON: map[string]any{
"schema": map[string]any{"$ref": componentsPrefix + "ErrorResponse"},
}},
}
if headers := errorHeaders(status); headers != nil {
resp["headers"] = headers
}
responses[key] = resp
}
return responses, nil
}
// bodySchema is the schema of a response body: a string for a text body,
// otherwise a reference to the reflected type.
func (g *generator) bodySchema(body any) (map[string]any, error) {
if _, ok := body.(string); ok {
return map[string]any{"type": "string"}, nil
}
return g.schemaRef(g.responses, body)
}
// errorHeaders documents the headers an error status carries besides its
// body, or nil for none.
func errorHeaders(status int) map[string]any {
switch status {
case http.StatusUnauthorized:
return map[string]any{"WWW-Authenticate": map[string]any{
"description": `The challenge: Bearer realm="uberbringer", with error="invalid_token" when a ` +
"token was sent but is not valid.",
"schema": map[string]any{"type": "string"},
}}
case http.StatusTooManyRequests:
return map[string]any{"Retry-After": map[string]any{
"description": "How many seconds to wait before the client's next request is let through.",
"schema": map[string]any{"type": "integer", "minimum": 1},
}}
case http.StatusServiceUnavailable:
return map[string]any{"Retry-After": map[string]any{
"description": "Sent with queue_full: how many seconds to wait before trying again.",
"schema": map[string]any{"type": "integer", "minimum": 1},
}}
}
return nil
}
// schemaRef reflects v's type into the components and returns a reference
// to it.
func (g *generator) schemaRef(r *jsonschema.Reflector, v any) (map[string]any, error) {
s := r.Reflect(v)
raw, err := json.Marshal(s)
if err != nil {
return nil, fmt.Errorf("reflecting %T: %w", v, err)
}
var root map[string]any
if err := json.Unmarshal(raw, &root); err != nil {
return nil, fmt.Errorf("reflecting %T: %w", v, err)
}
defs, _ := root["$defs"].(map[string]any)
for name, def := range defs {
def = rewriteRefs(def)
if existing, ok := g.schemas[name]; ok && !reflect.DeepEqual(existing, def) {
return nil, fmt.Errorf("two different schemas are both named %q", name)
}
g.schemas[name] = def
}
ref, ok := root["$ref"].(string)
if !ok {
return nil, fmt.Errorf("%T did not reflect to a named schema", v)
}
return map[string]any{"$ref": strings.Replace(ref, defsPrefix, componentsPrefix, 1)}, nil
}
// rewriteRefs points every $ref at the components instead of $defs.
func rewriteRefs(node any) any {
switch n := node.(type) {
case map[string]any:
for k, v := range n {
if s, ok := v.(string); ok && k == "$ref" {
n[k] = strings.Replace(s, defsPrefix, componentsPrefix, 1)
continue
}
n[k] = rewriteRefs(v)
}
case []any:
for i, v := range n {
n[i] = rewriteRefs(v)
}
}
return node
}
// schemaName names a component after its Go type, with a capital letter
// since several of the server's types are unexported. A job's status is
// JobStatus, as Status alone says too little.
func schemaName(t reflect.Type) string {
if t == reflect.TypeFor[printqueue.Status]() {
return "JobStatus"
}
name := t.Name()
if name == "" {
return ""
}
r, size := utf8.DecodeRuneInString(name)
return string(unicode.ToUpper(r)) + name[size:]
}
// mapType gives a job ID its JSON form, a string, in place of the Go struct
// behind it.
func mapType(c comments) func(reflect.Type) *jsonschema.Schema {
return func(t reflect.Type) *jsonschema.Schema {
if t != reflect.TypeFor[printqueue.JobID]() {
return nil
}
return &jsonschema.Schema{
Type: "string",
Pattern: jobIDPattern,
Description: c.lookup(t, ""),
Examples: []any{"job_01kbx4n6m3ex8tq0wq3r5vrzq1"},
}
}
}
func sortedTags(tags map[string]bool) []any {
names := make([]string, 0, len(tags))
for name := range tags {
names = append(names, name)
}
sort.Strings(names)
out := make([]any, len(names))
for i, name := range names {
out[i] = map[string]any{"name": name}
}
return out
}