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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/codegen-drift.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ on:
- internal/api/**
- specs/**
- tools/codegen/**
- tools/swagger2openapi/**
- tools/specconv/**
schedule:
- cron: "17 6 * * 1"
workflow_dispatch:
Expand Down
10 changes: 10 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,16 @@ this file collects what users and scripts need to know.

## Unreleased

### Development

- `make codegen` reads OpenAPI 3.0 and 3.1 service documents (huma) as
well as Swagger 2.0 (swag). The converter, renamed from
`tools/swagger2openapi` to `tools/specconv`, brings OpenAPI 3.1 down to
the 3.0 that the pinned oapi-codegen reads (nullable types, exclusive
bounds, `const`, schema `examples`, huma's read-only `$schema` field)
and applies the same clean-ups and excluded tags to both. The generated
specs and clients of every existing service are unchanged.

## 0.29.0 (2026-11-26)

### New
Expand Down
6 changes: 4 additions & 2 deletions docs/DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -678,8 +678,10 @@ the registry entries that have a `package`:
1. reads `apps/<app>/docs/<file>` from the backend checkout (`MONO`,
default `../backend-mono`) or from any directory with the same layout,
such as a published spec archive;
2. converts Swagger 2.0 to OpenAPI 3 with
[`tools/swagger2openapi`](../tools/swagger2openapi/main.go), dropping
2. converts the document to OpenAPI 3.0 with
[`tools/specconv`](../tools/specconv/main.go): Swagger 2.0 (swag) is
converted, OpenAPI 3.1 (huma) is brought down to 3.0
([`downlevel.go`](../tools/specconv/downlevel.go)), dropping
operations whose tags are listed under `output-options.exclude-tags` in
the package's `oapi-codegen.yaml`, and the schemas only they used, so
admin and webhook routes never appear in this public repository;
Expand Down
6 changes: 3 additions & 3 deletions tools/codegen/main.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// codegen regenerates the typed API clients listed in
// internal/registry/services.yaml: for every service with a `package`, it
// converts the Swagger 2.0 spec from the backend monorepo to OpenAPI 3
// (specs/<package>.openapi.json) and runs a pinned oapi-codegen with
// converts the service's API document from the backend monorepo (Swagger
// 2.0 or OpenAPI 3.0/3.1) to OpenAPI 3.0 (specs/<package>.openapi.json) and runs a pinned oapi-codegen with
// internal/api/<package>/oapi-codegen.yaml.
//
// Usage: go run ./tools/codegen -mono ../backend-mono [-only snapdb,langsync]
Expand Down Expand Up @@ -76,7 +76,7 @@ func generate(mono string, s registry.Service) error {
return err
}
var converted bytes.Buffer
conv := exec.Command("go", "run", "./tools/swagger2openapi", "-exclude-tags", strings.Join(excluded, ","), spec) // #nosec G204 -- paths from the embedded manifest
conv := exec.Command("go", "run", "./tools/specconv", "-exclude-tags", strings.Join(excluded, ","), spec) // #nosec G204 -- paths from the embedded manifest
conv.Stdout, conv.Stderr = &converted, os.Stderr
if err := conv.Run(); err != nil {
return fmt.Errorf("convert: %w", err)
Expand Down
105 changes: 105 additions & 0 deletions tools/specconv/downlevel.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
package main

import (
"encoding/json"
"slices"
)

// downlevel rewrites an OpenAPI 3.1 document as OpenAPI 3.0, the version
// the pinned oapi-codegen reads. A 3.0 document passes through unchanged
// except for the "$schema" clean-up, which applies to both.
//
// 3.1 schemas are JSON Schema 2020-12. The constructs services emit that
// 3.0 has no syntax for are rewritten to their 3.0 equivalent:
//
// - "type": ["string", "null"] becomes "type": "string" with
// "nullable": true (a list of several non-null types can't be said in
// 3.0, so the type is left out and the field is untyped);
// - a numeric "exclusiveMinimum"/"exclusiveMaximum" becomes
// "minimum"/"maximum" plus the boolean form;
// - "const" becomes a one-value "enum";
// - a schema's "examples" list becomes "example" (its first entry);
// the "examples" map of a media type or parameter is a 3.0 construct
// and is left alone;
// - the read-only "$schema" property huma adds to every object, which is
// no field a client sends or reads, is dropped (with its "required"
// entry);
// - the 3.1-only top-level "webhooks" and "jsonSchemaDialect" are
// dropped: they describe nothing a client calls.
func downlevel(raw []byte) ([]byte, error) {
var doc map[string]any
if err := json.Unmarshal(raw, &doc); err != nil {
return nil, err
}
doc["openapi"] = "3.0.3"
delete(doc, "webhooks")
delete(doc, "jsonSchemaDialect")
walk(doc)
return json.Marshal(doc)
}

func walk(v any) {
switch t := v.(type) {
case map[string]any:
downlevelSchema(t)
for _, child := range t {
walk(child)
}
case []any:
for _, child := range t {
walk(child)
}
}
}

// downlevelSchema rewrites one node if it uses 3.1-only schema syntax.
// Nodes that aren't schemas are untouched: every rule keys on a field
// whose 3.1 form can't appear outside a schema.
func downlevelSchema(s map[string]any) {
if types, ok := s["type"].([]any); ok {
var nonNull []any
for _, x := range types {
if x != "null" {
nonNull = append(nonNull, x)
}
}
switch {
case len(nonNull) == 1:
s["type"] = nonNull[0]
default:
delete(s, "type")
}
if len(nonNull) < len(types) {
s["nullable"] = true
}
}
for _, k := range [][2]string{{"exclusiveMinimum", "minimum"}, {"exclusiveMaximum", "maximum"}} {
if n, ok := s[k[0]].(float64); ok {
s[k[1]] = n
s[k[0]] = true
}
}
if c, ok := s["const"]; ok {
s["enum"] = []any{c}
delete(s, "const")
}
if ex, ok := s["examples"].([]any); ok {
if len(ex) > 0 {
s["example"] = ex[0]
}
delete(s, "examples")
}
if props, ok := s["properties"].(map[string]any); ok {
if p, ok := props["$schema"].(map[string]any); ok && p["readOnly"] == true {
delete(props, "$schema")
if req, ok := s["required"].([]any); ok {
req = slices.DeleteFunc(req, func(x any) bool { return x == "$schema" })
if len(req) == 0 {
delete(s, "required")
} else {
s["required"] = req
}
}
}
}
}
File renamed without changes.
51 changes: 42 additions & 9 deletions tools/swagger2openapi/main.go → tools/specconv/main.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
// swagger2openapi reads a Swagger 2.0 JSON document and writes the equivalent
// OpenAPI 3.0 JSON to stdout. This is a glue tool: the Norcube backend
// services emit Swagger 2.0 via `swag`, but oapi-codegen only ingests
// OpenAPI 3.x, so we run every spec through this converter before codegen.
// specconv reads a service's API document and writes the OpenAPI 3.0 JSON
// that the pinned oapi-codegen generates clients from, on stdout.
//
// It accepts both formats the Norcube services publish: Swagger 2.0 (swag)
// is converted to OpenAPI 3.0, and OpenAPI 3.1 (huma) is brought down to
// 3.0 (downlevel.go), so every client is generated from the same input
// format. The same clean-ups apply to both, then the excluded tags are
// removed.
package main

import (
Expand All @@ -22,7 +26,7 @@ func main() {
excludeTags := flag.String("exclude-tags", "", "comma-separated tags whose operations are left out (with the schemas only they use)")
flag.Parse()
if flag.NArg() != 1 {
fmt.Fprintln(os.Stderr, "usage: swagger2openapi [-exclude-tags a,b] <swagger-2.0.json>")
fmt.Fprintln(os.Stderr, "usage: specconv [-exclude-tags a,b] <swagger-2.0-or-openapi-3.x.json>")
os.Exit(2)
}

Expand All @@ -33,10 +37,7 @@ func main() {
raw, err := io.ReadAll(in)
must(err)

var v2 openapi2.T
must(json.Unmarshal(raw, &v2))

v3, err := openapi2conv.ToV3(&v2)
v3, err := toOpenAPI30(raw)
must(err)

normalizeFiberPathParams(v3)
Expand All @@ -54,6 +55,38 @@ func main() {
must(err)
}

// toOpenAPI30 reads a Swagger 2.0, OpenAPI 3.0 or OpenAPI 3.1 document as
// OpenAPI 3.0.
func toOpenAPI30(raw []byte) (*openapi3.T, error) {
var head struct {
Swagger string `json:"swagger"`
OpenAPI string `json:"openapi"`
}
if err := json.Unmarshal(raw, &head); err != nil {
return nil, err
}
switch {
case head.Swagger == "2.0":
var v2 openapi2.T
if err := json.Unmarshal(raw, &v2); err != nil {
return nil, err
}
return openapi2conv.ToV3(&v2)
case strings.HasPrefix(head.OpenAPI, "3.0."), strings.HasPrefix(head.OpenAPI, "3.1."):
down, err := downlevel(raw)
if err != nil {
return nil, err
}
// The loader resolves internal references (written back as $ref);
// a service document has no business pointing at external files.
loader := openapi3.NewLoader()
loader.IsExternalRefsAllowed = false
return loader.LoadFromData(down)
default:
return nil, fmt.Errorf("not a Swagger 2.0 or OpenAPI 3.0/3.1 document (swagger: %q, openapi: %q)", head.Swagger, head.OpenAPI)
}
}

func must(err error) {
if err != nil {
fmt.Fprintln(os.Stderr, "error:", err)
Expand Down
130 changes: 130 additions & 0 deletions tools/specconv/specconv_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
package main

import (
"context"
"encoding/json"
"testing"
)

// A small service document as huma writes it (OpenAPI 3.1).
const humaDoc = `{
"openapi": "3.1.0",
"info": {"title": "Example", "version": "1.0.0"},
"jsonSchemaDialect": "https://spec.openapis.org/oas/3.1/dialect/base",
"paths": {
"/widgets/{id}": {
"get": {
"operationId": "getWidget",
"parameters": [{"name": "id", "in": "path", "required": true, "schema": {"type": "string", "format": "uuid"}}],
"responses": {
"200": {"description": "OK", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Widget"}}}},
"default": {"description": "Error", "content": {"application/problem+json": {"schema": {"$ref": "#/components/schemas/ErrorModel"}}}}
},
"security": [{"bearer": []}]
}
}
},
"components": {
"securitySchemes": {"bearer": {"type": "http", "scheme": "bearer"}},
"schemas": {
"Widget": {
"type": "object", "additionalProperties": false,
"required": ["$schema", "id", "kind"],
"properties": {
"$schema": {"type": "string", "format": "uri", "readOnly": true},
"id": {"type": "string", "examples": ["w-1"]},
"kind": {"const": "widget"},
"note": {"type": ["string", "null"]},
"score": {"type": "number", "exclusiveMinimum": 0, "exclusiveMaximum": 10}
}
},
"ErrorModel": {"type": "object", "properties": {"title": {"type": "string"}}}
}
}
}`

func TestOpenAPI31IsBroughtDownTo30(t *testing.T) {
v3, err := toOpenAPI30([]byte(humaDoc))
if err != nil {
t.Fatal(err)
}
stripOperationSecurity(v3)
ensurePathParameters(v3)

if v3.OpenAPI != "3.0.3" {
t.Errorf("openapi = %q, want 3.0.3", v3.OpenAPI)
}
// The result must be a valid 3.0 document: what oapi-codegen reads.
if err := v3.Validate(context.Background()); err != nil {
t.Fatalf("not a valid OpenAPI 3.0 document: %v", err)
}

w := v3.Components.Schemas["Widget"].Value
if _, ok := w.Properties["$schema"]; ok {
t.Error("huma's read-only $schema property was kept")
}
if len(w.Required) != 2 {
t.Errorf("required = %v, want [id kind]", w.Required)
}
if note := w.Properties["note"].Value; !note.Type.Is("string") || !note.Nullable {
t.Errorf("note: type %v nullable %v, want string, nullable", note.Type, note.Nullable)
}
if kind := w.Properties["kind"].Value; len(kind.Enum) != 1 || kind.Enum[0] != "widget" {
t.Errorf("kind enum = %v, want [widget]", kind.Enum)
}
if id := w.Properties["id"].Value; id.Example != "w-1" {
t.Errorf("id example = %v, want w-1", id.Example)
}
score := w.Properties["score"].Value
// 3.0 form: the bound in minimum/maximum, exclusiveness as a boolean.
if score.Min == nil || *score.Min != 0 || score.ExclusiveMin.Bool == nil || !*score.ExclusiveMin.Bool || score.ExclusiveMin.Value != nil ||
score.Max == nil || *score.Max != 10 || score.ExclusiveMax.Bool == nil || !*score.ExclusiveMax.Bool || score.ExclusiveMax.Value != nil {
t.Errorf("score bounds: min %v excl %+v, max %v excl %+v", score.Min, score.ExclusiveMin, score.Max, score.ExclusiveMax)
}
}

func TestSwagger20StillConverts(t *testing.T) {
doc := `{"swagger": "2.0", "info": {"title": "E", "version": "1"}, "basePath": "/app/v1",
"paths": {"/things/:id": {"get": {"operationId": "getThing", "produces": ["application/json"],
"parameters": [{"name": "id", "in": "path", "required": true, "type": "string"}],
"responses": {"200": {"description": "OK", "schema": {"$ref": "#/definitions/Thing"}}}}}},
"definitions": {"Thing": {"type": "object", "properties": {"id": {"type": "string"}}}}}`
v3, err := toOpenAPI30([]byte(doc))
if err != nil {
t.Fatal(err)
}
normalizeFiberPathParams(v3)
if v3.Paths.Value("/things/{id}") == nil {
t.Errorf("Fiber path not normalized; paths: %v", v3.Paths.InMatchingOrder())
}
if err := v3.Validate(context.Background()); err != nil {
t.Fatalf("not a valid OpenAPI 3.0 document: %v", err)
}
}

func TestRefusesUnknownDocuments(t *testing.T) {
for _, doc := range []string{`{"openapi": "2.5.0"}`, `{"paths": {}}`, `not json`} {
if _, err := toOpenAPI30([]byte(doc)); err == nil {
t.Errorf("%s was accepted", doc)
}
}
}

// Media-type "examples" maps are 3.0 constructs and survive.
func TestMediaExamplesMapIsKept(t *testing.T) {
doc := `{"openapi": "3.1.0", "info": {"title": "E", "version": "1"}, "paths": {"/a": {"get": {"operationId": "a",
"responses": {"200": {"description": "OK", "content": {"application/json": {
"schema": {"type": "string"}, "examples": {"one": {"value": "x"}}}}}}}}}}`
out, err := downlevel([]byte(doc))
if err != nil {
t.Fatal(err)
}
var v map[string]any
if err := json.Unmarshal(out, &v); err != nil {
t.Fatal(err)
}
media := v["paths"].(map[string]any)["/a"].(map[string]any)["get"].(map[string]any)["responses"].(map[string]any)["200"].(map[string]any)["content"].(map[string]any)["application/json"].(map[string]any)
if _, ok := media["examples"].(map[string]any); !ok {
t.Errorf("media examples map was changed: %v", media["examples"])
}
}
Loading