httpwire

package module
v1.0.0-dev.7 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 20, 2026 License: Apache-2.0 Imports: 37 Imported by: 0

README

httpwire

Go Reference Go version npm JSR

httpwire declares your Go app's JSON API once, as a table of rows, and binds typed handlers to it, with a matching TypeScript package that decodes the same wire in the browser.

The Go module depends on this repository's httpserver and textsafe, which use only the standard library. Both halves are licensed under Apache-2.0.

Why use it

httpwire is built for a Go server whose browser client is generated from the same table, where any disagreement between the two must fail in a test.

  • New checks the table against its handlers and the committed OpenAPI document at start, listing every refusal at once.
  • Every refusal is one error envelope whose code is in the row's declared union, at the catalog's status.
  • A request is guarded before it is decoded, and decoded strictly: unknown fields, a body not sent as application/json and a value outside its schema are refused before the handler runs.
  • Idempotency-Key replay, If-Match tags, sealed list cursors that page both ways, and quiescing for a file replace are built in.
  • httpwiretest.Contract holds every answer to the document.

Consider huma if you want the OpenAPI document generated from your handlers at run time across several routers.

Install

go get github.com/cplieger/go/httpwire@latest
npx jsr add @cplieger/httpwire  # or: npm i @cplieger/httpwire

Usage

table := &httpwire.Table{
	Prefix:  "/api",
	Catalog: httpwire.NewCatalog(),
	Endpoints: []httpwire.Endpoint{{
		Name: "items.get", Method: http.MethodGet, Path: "/api/items/{id}",
		Summary: "Read an item", Description: "Reads one item.",
		Params: reflect.TypeFor[itemRef](), Response: reflect.TypeFor[item](),
		Access: httpwire.Access{Class: httpwire.Public},
	}},
}
get := func(_ context.Context, c httpwire.Call[itemRef, httpwire.None, httpwire.None]) (item, error) {
	return item{ID: string(c.Params.ID), Name: "first"}, nil
}
api, err := httpwire.New(table, []httpwire.Binding{httpwire.Bind("items.get", get)},
	httpwire.WithSchema(openapiJSON))

ExampleNew in example_test.go runs this with its document, and go test keeps it true. The document is the one wiregen writes from the same table, committed beside it. A row that is not Public also needs WithGuard, WithCredential and WithCursorOwner, and New names each missing option.

API

  • Table, Endpoint, Access, Kind, Mount, Owner and Derive declare the API. Bind, BindRaw, BindStream, Call, None, Status and Answer bind handlers.
  • New and its With* options build an API, which serves the table and quiesces through Quiesce.
  • Catalog, Error, FieldError, Upstream, Envelope, DecodeEnvelope and Union describe refusals.
  • Page, Cursor, Limit, List, Seal, Open, Tag, OpenToken, Idempotency and IdempotencyStore serve pages, handles, tags and replays.
  • ParseSchema, WireVersion and the Pattern* constants read the document.
  • httpwiretest holds Contract, WithSameShape and Sentinels.
  • The TypeScript package decodes envelopes, pages and tags, and its ./testing entry holds the fakes and fixtures; web/README.md documents it.

The full reference is on pkg.go.dev and JSR.

Every row runs in one order

A write first meets httpserver.CrossOrigin. Then every row meets the client version floor, maintenance, the store outage, the guard, the key rate and the held-request cap, in that order, and only then is the request decoded: path, query, the body's media type, the body, If-Match, Idempotency-Key and the cursor. A write naming another Wire-Version answers wire_mismatch before decoding. So a refused principal is never decoded, and an idempotency key is never looked up for a caller the guard has not admitted. A bad path value answers not_found, since it names no resource.

A handler's error answers through the row's union: an *Error whose code the union holds, else the first owner sentinel it wraps, else internal_error, logged. The binder covers the order, idempotency, the spool for keyed uploads, person-only actions and maintenance.

The wire both halves agree on

Every answer carries Wire-Version, the first 16 hex characters of the SHA-256 of the document's normal form, and the request's X-Request-Id. Refusals are one envelope (code, message, remediation, request_id, optional reason, fields, retry_after_ms and upstream), decoded by the same rules in Go and TypeScript. A List row's page carries offset, total and cursors sealed under AES-256-GCM, bound to the row, the query and the owner, that open for 24 hours. The wire lists the headers, the envelope bounds, the page rules, the tag form and the schema keywords ParseSchema accepts.

Documentation

  • The binder describes how a row is admitted, decoded and answered, for anyone writing handlers or a guard.
  • The wire describes the headers, envelope, pages, tags and document rules, for anyone writing a client.
  • Testing an API covers httpwiretest and the TypeScript fixtures, for anyone writing handler tests.
  • web/README.md documents the TypeScript package.

Contributing

Issues and pull requests are welcome. The shared contributing rules apply.

Disclaimer

This project is built with care and follows security best practices, but it is intended for personal / self-hosted use. No guarantees of fitness for production environments. Use at your own risk.

This project was built with AI assistance. The human maintainer defines architecture, supervises implementation, and makes all final decisions.

License

Apache-2.0. See LICENSE.

Documentation

Overview

Package httpwire declares a JSON API once, as a table of Endpoint rows, and binds typed handlers to it: decoding, the error envelope and its code catalog, Idempotency-Key replay, list pages and the wire version.

Index

Examples

Constants

View Source
const (
	// PatternJSONString is the JSON text of a ,string string or enum.
	PatternJSONString = `^"(?:[^"\\\x00-\x1F]|\\(?:["\\/bfnrt]|u[0-9a-fA-F]{4}))*"$`
	// PatternJSONNumber is the JSON text of a ,string float.
	PatternJSONNumber = `^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$`
	// PatternJSONInt is a ,string signed integer, and a signed integer map key.
	PatternJSONInt = `^-?(?:0|[1-9][0-9]*)$`
	// PatternJSONUint is a ,string unsigned integer, and an unsigned integer
	// map key.
	PatternJSONUint = `^(?:0|[1-9][0-9]*)$`
	// PatternJSONBool is the JSON text of a ,string boolean.
	PatternJSONBool = `^(?:true|false)$`
	// PatternHeader is a declared header's value: printable ASCII.
	PatternHeader = `^[\x20-\x7E]*$`
)

The only pattern keywords a document may carry: wiregen writes them from these constants, and the TS half matches each under ECMA-262's u flag, so both engines give one verdict (the shared corpus at web/testdata/wirepatterns.json holds them to it).

View Source
const (
	PersonSignInMethods   = "sign_in_methods"
	PersonTrustedProxies  = "trusted_proxies"
	PersonKeyRotate       = "key_rotate"
	PersonAdminAccount    = "admin_account"
	PersonSecretRetarget  = "secret_retarget"
	PersonAccountsArchive = "accounts_archive"
)

The person-only actions: reachable by no API key, only by a person's session or the admin-socket principal. The first three are a whole row's purpose, so their row is PersonOnly; the last three are decided inside a row through RequirePerson.

Variables

View Source
var (
	// ErrPositionTooLong is SealNext's, SealPrev's and Seal's answer for a
	// position or payload over 1,024 bytes; a handler returning it answers
	// internal_error.
	ErrPositionTooLong = errors.New("httpwire: a sealed position or payload is at most 1,024 bytes")
	// ErrSealed is Open's answer for a value that does not open: tampered,
	// sealed under another key, purpose or credential, past its age, or
	// opened outside a request the binder serves or on a Public row.
	ErrSealed = errors.New("httpwire: the sealed value does not open")
)

Functions

func CredentialOf

func CredentialOf(ctx context.Context) string

CredentialOf answers WithCredential's answer for the request ctx belongs to; "" on a Public row and outside a request the binder serves.

func CursorOwnerOf

func CursorOwnerOf(ctx context.Context) string

CursorOwnerOf answers WithCursorOwner's answer for the request ctx belongs to; "" on a Public row and outside a request the binder serves.

func IsWirePattern

func IsWirePattern(p string) bool

IsWirePattern reports whether p is one of the six Pattern constants.

func Open

func Open(ctx context.Context, purpose, sealed string, maxAge time.Duration) ([]byte, error)

Open answers the payload Seal sealed for purpose and this request's credential no longer than maxAge ago, else ErrSealed.

func OpenToken

func OpenToken(epoch [16]byte) [8]byte

OpenToken answers the first 8 bytes of SHA-256("httpwire tag\x00" || epoch), so a tag never carries the raw epoch of the open it names.

func RequirePerson

func RequirePerson(ctx context.Context, action string) error

RequirePerson answers nil when the request ctx belongs to is a person's, as the API's Guard.Person decides: a session that authenticated recently or the admin-socket principal. Else it answers an *Error to return, or to write through the catalog on a Raw row: person_required with the action as its Reason for a key, or the guard's step-up refusal. action is one of the in-row actions its row lists in PersonActions; any other, a guard answer off the row's union, or a ctx outside a request the binder serves is internal_error, logged at ERROR.

func Seal

func Seal(ctx context.Context, purpose string, payload []byte) (string, error)

Seal seals payload, at most 1,024 bytes, under the API's cursor key, bound to purpose and CredentialOf(ctx), so only that credential opens it. It refuses a Public row, where a handle would come back from anyone.

func Union

func Union(t *Table, ep *Endpoint, guardCodes func(Access) []string) []string

Union is a row's error union, deduplicated in a fixed order: the row's own codes and its owners', the codes its features bring, the guard's codes for its Access, and the codes every row may answer. A mount row, found in t by name, carries its own codes and the binder's wrap's instead. Derive fills Errors with it, so the binder and the client generator read one derivation.

func WireVersion

func WireVersion(doc []byte) string

WireVersion answers the wire version of an OpenAPI 3.1 document: the first 16 lowercase hex characters of the SHA-256 of its normal form. The normal form drops what changes no wire: summary and description where each is a keyword of an OpenAPI object (never a member name inside a map such as properties), the top-level info object, and each x-error-codes entry's remediation in a response; the rest is written with sorted keys and no whitespace. It answers "" when doc is not one JSON object.

Types

type API

type API struct {
	// contains filtered or unexported fields
}

API serves one checked table under its Prefix. It is safe for concurrent use.

func New

func New(t *Table, bs []Binding, opts ...Option) (*API, error)

New checks t against its bindings and options and builds its API. Its error lists every refusal at once, Derive's among them, so an app fails at start and never at a request.

Example

A table row and its typed handler: the binder decodes the path value into its type, and a value outside its bounds names no resource, so it answers not_found without running the handler.

package main

import (
	"context"
	"fmt"
	"net/http"
	"net/http/httptest"
	"reflect"
	"strings"

	"github.com/cplieger/go/httpwire"
)

// exampleID is a path value of at most 32 bytes.
type exampleID string

func (exampleID) MaxBytes() int { return 32 }

type exampleRef struct {
	ID exampleID `json:"id"`
}

type exampleItem struct {
	ID   string `json:"id"`
	Name string `json:"name"`
}

// itemDoc is the OpenAPI document wiregen writes for the table below; an app
// commits it and embeds it.
const itemDoc = `{
  "openapi": "3.1.0",
  "info": {"title": "items", "version": "1"},
  "paths": {
    "/api/items/{id}": {
      "get": {
        "operationId": "items.get",
        "summary": "Read an item",
        "parameters": [
          {"in": "path", "name": "id", "required": true, "schema": {"type": "string", "minLength": 1, "maxLength": 32}}
        ],
        "responses": {
          "200": {
            "description": "OK",
            "content": {"application/json": {"schema": {
              "type": "object",
              "properties": {"id": {"type": "string"}, "name": {"type": "string"}},
              "required": ["id", "name"]
            }}}
          }
        }
      }
    }
  }
}`

// A table row and its typed handler: the binder decodes the path value into
// its type, and a value outside its bounds names no resource, so it answers
// not_found without running the handler.
func main() {
	table := &httpwire.Table{
		Prefix:  "/api",
		Catalog: httpwire.NewCatalog(),
		Endpoints: []httpwire.Endpoint{{
			Name: "items.get", Method: http.MethodGet, Path: "/api/items/{id}",
			Summary: "Read an item", Description: "Reads one item.",
			Params: reflect.TypeFor[exampleRef](), Response: reflect.TypeFor[exampleItem](),
			Access: httpwire.Access{Class: httpwire.Public},
		}},
	}
	get := func(_ context.Context, c httpwire.Call[exampleRef, httpwire.None, httpwire.None]) (exampleItem, error) {
		return exampleItem{ID: string(c.Params.ID), Name: "first"}, nil
	}
	api, err := httpwire.New(table, []httpwire.Binding{httpwire.Bind("items.get", get)},
		httpwire.WithSchema([]byte(itemDoc)))
	if err != nil {
		fmt.Println(err)
		return
	}

	for _, target := range []string{"/api/items/a1", "/api/items/" + strings.Repeat("x", 33)} {
		rec := httptest.NewRecorder()
		api.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, target, http.NoBody))
		env, _ := httpwire.DecodeEnvelope(rec.Body.Bytes())
		fmt.Println(rec.Code, env.Code, rec.Header().Get("Wire-Version") != "")
	}
}
Output:
200  true
404 not_found true

func (*API) Quiesce

func (a *API) Quiesce(ctx context.Context, q Quiet) (resume func(), err error)

Quiesce starts refusing or holding at once, then returns when every request of that level already in flight (writes for QuietWrites, every request but an open stream for QuietAll) has returned; one still running 10 s into QuietAll has its context cancelled. It returns ctx's error, holding nothing, when ctx ends first. The request ctx descends from, detached or not, is never waited for. A QuietAll taken under a QuietWrites returns to it at its own resume.

func (*API) ServeHTTP

func (a *API) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP answers a row, or method_not_allowed with Allow when the path is a row's under another method, or not_found. Every answer carries Wire-Version and the request's X-Request-Id.

func (*API) Table

func (a *API) Table() *Table

Table answers a copy of the checked table, each row's Errors filled.

type Access

type Access struct {
	// Scope is the key scope: required on Scoped, optional on Key and on a
	// PersonOnly Session row, refused on every other class.
	Scope string
	Class Class
	// RecentAuth asks a session to have authenticated recently (a step-up).
	RecentAuth bool
	// PersonOnly refuses every API key whatever its scopes; valid only on a
	// Session row.
	PersonOnly bool
	HTTPS      bool // admit only a secure request
	Passive    bool // not session activity
}

Access says who a row admits. Its classes are the guard's.

type Binding

type Binding struct {
	// contains filtered or unexported fields
}

Binding pairs a row, by name, with its handler. New checks it against the row.

func Bind

func Bind[P, Q, B, R any](name string, h Handler[P, Q, B, R]) Binding

Bind binds a JSON row: P, Q and B are its Params, Query and Request types (None where it has none), and R its Response type, None when it has none, or Status[T] when it declares Successes.

func BindRaw

func BindRaw(name string, h http.Handler) Binding

BindRaw binds a Raw or Redirect row to a handler that writes its own answer.

func BindStream

func BindStream(name string, h http.Handler) Binding

BindStream binds a Stream row to a handler that writes the event stream.

type Call

type Call[P, Q, B any] struct {
	Params P
	Query  Q
	Body   B

	// Position is the position a List row's cursor sealed; nil on the first
	// page. See SealNext and SealPrev.
	Position []byte
	// IfMatch is the tag an IfMatch row's If-Match named; the zero Tag on
	// any other row.
	IfMatch Tag
	// Limit is a List row's page size.
	Limit int
	// Backward marks a List row's prev_cursor: answer the Limit rows ending
	// just before Position, in list order.
	Backward bool
	// contains filtered or unexported fields
}

Call is what a bound handler receives: the request's decoded parts.

func (Call[P, Q, B]) SealNext

func (c Call[P, Q, B]) SealNext(pos []byte) (string, error)

SealNext answers the next_cursor resuming after pos, the page's last item: a request with it has Position pos and Backward false. It is bound to this row, this query (Page aside) and WithCursorOwner's owner, and answers ErrPositionTooLong for a pos over 1,024 bytes.

func (Call[P, Q, B]) SealPrev

func (c Call[P, Q, B]) SealPrev(pos []byte) (string, error)

SealPrev answers the prev_cursor ending before pos, the page's first item: a request with it has Position pos and Backward true, and answers the Limit rows before pos in list order, or the first page when fewer precede it. It is bound as SealNext's is.

type Catalog

type Catalog struct {
	// contains filtered or unexported fields
}

Catalog is the one code table of an app's listeners: every code any layer answers, with its status and remediation. It is safe for concurrent use.

func NewCatalog

func NewCatalog() *Catalog

NewCatalog returns a catalog holding httpwire's own codes and every code of httpserver.CodeSpecs.

func (*Catalog) Add

func (c *Catalog) Add(code string, s httpserver.CodeSpec) error

Add adds an app's own code. It refuses a code already in the catalog, a code outside the grammar, a status outside 400 to 599, and a remediation that is empty, over 4 KiB or more than one line of valid UTF-8.

func (*Catalog) AddOwned

func (c *Catalog) AddOwned(specs map[httpserver.ErrorCode]httpserver.CodeSpec) error

AddOwned adds the codes another module answers itself, under Add's rules. A code already present with the identical spec is skipped, so a module may add its codes twice; one present with another spec is refused. A refusal adds none of specs.

func (*Catalog) Lookup

func (c *Catalog) Lookup(code string) (httpserver.CodeSpec, bool)

Lookup returns code's status and remediation.

func (*Catalog) Responder

func (c *Catalog) Responder() httpserver.ErrorResponder

Responder adapts WriteError to httpserver's ErrorResponder, for the listener's own writers (host policy, SPA, not found): the catalog's status replaces the one the caller passes, and a code missing from the catalog answers internal_error.

func (*Catalog) SetRemediation

func (c *Catalog) SetRemediation(code, remediation string) error

SetRemediation replaces the remediation of a code already in the catalog, keeping its status: the app's words for a library's code. It refuses an unknown code and a remediation Add would refuse.

func (*Catalog) WriteError

func (c *Catalog) WriteError(w http.ResponseWriter, r *http.Request, e *Error)

WriteError answers e as the error envelope, at its code's catalog status and with its remediation. It keeps every header the caller set, setting only Content-Type, X-Request-Id and, when e carries one, Retry-After. The body always decodes with DecodeEnvelope: text is capped to the envelope's bounds, and internal_error carries the message "internal error" and nothing else. A code missing from the catalog, a reason outside the grammar and an upstream service outside it are wiring bugs: each is logged at ERROR and answered as internal_error, or left out. r may be nil.

type Class

type Class uint8

Class is a row's admission class. The zero Class is refused.

const (
	Public Class = iota + 1
	Session
	Key
	Scoped
)

The admission classes.

type ClientFloor

type ClientFloor struct {
	// Below reports whether a client version is under the floor.
	Below func(version string) bool
	// Message is the one line naming this server's version and the client
	// release to install.
	Message func(version string) string
}

ClientFloor refuses an installed client below this server's floor, read from the table's ClientHeader.

type Cursor

type Cursor string

Cursor is a page cursor as the query carries it: opaque, at most 1,416 bytes, absent on the first page. Any cursor that does not open for this row, query and owner answers cursor_invalid.

func (Cursor) MaxBytes

func (Cursor) MaxBytes() int

MaxBytes is base64url of the 12-byte nonce, the format, direction and issue-time header, the longest position and the 16-byte tag: 12 + 1 + 1 + 8 + 1,024 + 16 bytes.

type Endpoint

type Endpoint struct {
	Params, Query, Request, Response reflect.Type // nil is none

	// Reasons maps a code of the row's union to the reasons it may carry.
	Reasons map[string]ReasonSet

	// Name is "<area>.<verb>", unique in the table: the operation id and the
	// generated client function's name.
	Name string
	// Method is GET, POST, PUT, PATCH or DELETE; a GET row also answers HEAD.
	Method string
	// Path is a ServeMux pattern under the table's Prefix: literal segments
	// and whole-segment {name} wildcards.
	Path        string
	Summary     string
	Description string
	// ContentType is a Raw row's 2xx media type, required there and only there.
	ContentType string
	// Result names the read row that returns a Keyed row's result, for an
	// answer too large to replay.
	Result string

	// Successes are the success statuses the row answers besides Status. A
	// JSON row's are a 2xx other than 205 with a Response or a 204 with none;
	// a Raw or Stream row's only a 204 with none; a Redirect row's other
	// redirect statuses with none.
	Successes []Success
	// Codes are the codes the handler answers itself.
	Codes []string
	// Owners are the owner code sets mapError tries, in order.
	Owners []*Owner
	// Changes names the feed kinds this read serves; empty on a write.
	Changes []string
	// Events are a Stream row's events.
	Events []Event
	// PersonActions are the person-only actions decided inside the row.
	PersonActions []string
	// Errors is the row's error union, filled by Derive; a value set by hand
	// is replaced.
	Errors []string

	Access Access
	// Status is the primary success status. Zero is 200, 204 for a JSON row
	// with no Response, and 302 for a Redirect.
	Status int
	// MaxBody is the request body cap when not the table's; zero is the
	// table's.
	MaxBody int
	// Window is a Keyed row's idempotency window, 1 minute to 7 days; zero
	// is the table's.
	Window time.Duration
	// MaxKept is a Keyed row's answers kept per credential; zero is no count
	// bound.
	MaxKept int
	Kind    Kind

	Keyed   bool // takes an Idempotency-Key
	IfMatch bool // takes If-Match naming the Tag it was read at
	List    bool // a list read: takes Page, answers List[T]
	// Personal marks a read whose rows differ per principal within one shape;
	// it names a kind only in a OnePerson table.
	Personal bool
	// Held marks a JSON row that holds the request open, counted by the
	// held-request cap.
	Held bool
	// ShownOnce marks an answer carrying a secret shown once; such a row is
	// never Keyed.
	ShownOnce bool
	// DuringOutage keeps the row served while a store file cannot open.
	DuringOutage bool
}

Endpoint is one route of an app's JSON API. The binder, the guard, the client generator and the change feed all read it; none adds a field of its own beside it.

type Envelope

type Envelope struct {
	Code        string       `json:"code"`
	Message     string       `json:"message"`
	Remediation string       `json:"remediation"`
	Reason      string       `json:"reason,omitempty"`
	Fields      []FieldError `json:"fields,omitempty"`
	// RetryAfterMS is the wait before a retry, in milliseconds; 0 is none.
	RetryAfterMS int64     `json:"retry_after_ms,omitempty"`
	Upstream     *Upstream `json:"upstream,omitempty"`
	RequestID    string    `json:"request_id"`
}

Envelope is the decoded error body every listener of an app answers.

func DecodeEnvelope

func DecodeEnvelope(body []byte) (Envelope, error)

DecodeEnvelope decodes an error body by the rules the TypeScript decodeEnvelope holds too: code, message, remediation and request_id present and strings; code, reason and upstream.service in the code grammar; reason at most 64 bytes, fields at most 100 entries, upstream.message at most 512 bytes and every other string at most 4 KiB; retry_after_ms an integer from 0 to 2^53 - 1 and upstream.status one from 100 to 599. A member present as null breaks its rule, and an unknown member is ignored.

type Error

type Error struct {
	// Upstream is what another service said; the writer cleans and caps it.
	Upstream *Upstream
	Code     string
	Message  string
	// Reason is optional machine detail: the code grammar, at most 64 bytes.
	Reason string

	// Fields names the refused parts of the request; at most 100 are written.
	Fields     []FieldError
	RetryAfter time.Duration
	// contains filtered or unexported fields
}

Error is a handler's own refusal. Its Code must be in the row's error union; the catalog supplies the status and the remediation.

func (*Error) Error

func (e *Error) Error() string

type Event

type Event struct {
	Data reflect.Type // the JSON data type
	// Name is the SSE event name, in the code grammar.
	Name string
	// Readers, on an app event the feed publishes, says who receives it;
	// zero on the feed's own events.
	Readers Access
}

Event is one event a Stream row sends.

type FeedKind

type FeedKind struct {
	// Name is in the code grammar, at most 32 bytes, unique across sources.
	Name   string
	Source string
}

FeedKind is one change kind and the source it belongs to.

type FeedSource

type FeedSource struct {
	// Name is ^[a-z][a-z0-9_]{0,31}$, a key of the Feed-Position dictionary.
	Name string
	// Log says a store log is behind it, so a reader can catch up.
	Log bool
}

FeedSource is one source of the change feed: a store with its own epoch and revisions, or an in-memory set of parts.

type FieldError

type FieldError struct {
	Path    string `json:"path"`
	Code    string `json:"code"`
	Message string `json:"message"`
}

FieldError names one refused part of a request: Path is the JSON path ("items[1].key") or the query key, Code the field code.

type Guard

type Guard interface {
	// Wrap guards one row's handler; it runs before any decoding.
	Wrap(ep *Endpoint, next http.Handler) http.Handler
	// Codes are the codes Wrap may answer for a row with this Access.
	Codes(a Access) []string
	// Shape is the request's principal shape, answered without refusing:
	// the admitted principal, else a passive authentication, else anonymous.
	Shape(r *http.Request) Shape
	// Shapes are every shape the guard can admit.
	Shapes() []Shape
	// Admits reports whether a principal of shape s passes a row with this
	// Access with no step-up: false on every RecentAuth row, and false for
	// a key shape on a PersonOnly row.
	Admits(s Shape, a Access) bool
	// Person answers nil for a session that authenticated recently or the
	// admin-socket principal, else the *Error to return.
	Person(ctx context.Context) error
}

Guard decides who reaches each row, from the row's Access.

type Handler

type Handler[P, Q, B, R any] func(context.Context, Call[P, Q, B]) (R, error)

Handler is a JSON row's handler. Its error is answered through the row's union: an *Error whose code the union holds, else the first owner sentinel it wraps, else internal_error.

type IdempotencyEvent

type IdempotencyEvent struct {
	Row     string
	Outcome IdempotencyOutcome
}

IdempotencyEvent is one outcome on one row, for the app's counters.

type IdempotencyKey

type IdempotencyKey struct {
	Credential string
	Row        string
	Key        string
}

IdempotencyKey is the slot a kept answer is held under: the key one credential sent on one row.

func Idempotency

func Idempotency(ctx context.Context) (k IdempotencyKey, fingerprint [32]byte, ok bool)

Idempotency answers, inside a Keyed row's handler, the slot its answer is kept under and the request's fingerprint, so a store can write the key in the work's own transaction. ok is false anywhere else.

type IdempotencyOptions

type IdempotencyOptions struct {
	// Store keeps settled answers; nil is the in-memory store.
	Store IdempotencyStore
	// Observer is told of each outcome other than a first run.
	Observer func(IdempotencyEvent)
	// MaxAnswer is the largest body kept: 64 KiB when zero, else 1 KiB to
	// 1 MiB. A larger answer is sent whole and kept as Oversize.
	MaxAnswer int
	// MaxBytes bounds the in-memory store's kept bodies: 64 MiB when zero,
	// else 1 MiB to 1 GiB. A body that would pass it is kept as Oversize.
	MaxBytes int
	// MaxBytesPerCredential bounds one credential's kept bodies in memory:
	// MaxBytes / 8 when zero, raised to MaxAnswer, else MaxAnswer to
	// MaxBytes. A credential at it gets idempotency_store_full.
	MaxBytesPerCredential int
	// MaxPerCredential bounds one credential's kept answers and runs in
	// flight in memory: 1,000 when zero, else 1 to 10,000.
	MaxPerCredential int
}

IdempotencyOptions configures every Keyed row. Each zero value is its default; New refuses a value outside its bound.

type IdempotencyOutcome

type IdempotencyOutcome string

IdempotencyOutcome is what a keyed request met instead of a first run.

const (
	OutcomeReplayed IdempotencyOutcome = "replayed" // a kept answer was written again
	OutcomeJoined   IdempotencyOutcome = "joined"   // the request waited for the run in flight and wrote its answer
	OutcomeReused   IdempotencyOutcome = "reused"   // the key was held for another request
	OutcomeOversize IdempotencyOutcome = "oversize" // the kept answer had no body: idempotency_answer_too_large
)

The outcomes an Observer is told of.

type IdempotencyStore

type IdempotencyStore interface {
	Load(ctx context.Context, k IdempotencyKey) (KeptAnswer, bool, error)
	Save(ctx context.Context, k IdempotencyKey, a KeptAnswer) error
}

IdempotencyStore keeps settled answers; a request in flight is joined in memory. A store that writes the key in the work's transaction reads it with Idempotency in the handler, answers it from Load, and makes Save a no-op. A Load error answers internal_error. A Save error is logged and the answer kept in this process's memory until Expires. That memory admits a new key by the default bounds over the answers it holds, not the runs in flight, so runs whose saves all fail can pass those bounds by their number; no kept answer is dropped to hold them.

type KeptAnswer

type KeptAnswer struct {
	Expires     time.Time
	ContentType string
	// Body is nil when Oversize.
	Body []byte
	// RetryAfter is a kept refusal's; zero on a success.
	RetryAfter time.Duration
	// Status is the status the first run answered, a declared success or
	// a refusal.
	Status      int
	Fingerprint [32]byte
	// Oversize marks an answer kept without its body: its resend answers
	// idempotency_answer_too_large and never runs the handler.
	Oversize bool
}

KeptAnswer is a Keyed row's settled answer, which a resend with the same key and fingerprint is answered with until Expires.

type Kind

type Kind uint8

Kind is what a row answers on success.

const (
	// JSON answers Response as JSON, or nothing with no Response.
	JSON Kind = iota
	// Raw answers a body of the row's ContentType the handler writes itself.
	Raw
	// Stream answers text/event-stream.
	Stream
	// Redirect answers a 3xx whose Location the handler builds from server
	// values only.
	Redirect
)

The row kinds.

type Limit

type Limit int

Limit is a page size, 1 to 200; absent is 50.

func (Limit) Range

func (Limit) Range() (lo, hi int64)

Range is the bound the decode holds a limit to and wiregen describes.

type List

type List[T any] struct {
	Items      []T    `json:"items"`
	NextCursor string `json:"next_cursor,omitempty"`
	PrevCursor string `json:"prev_cursor,omitempty"`
	// Offset is the count of items before this page's first, read with Total.
	Offset int64 `json:"offset"`
	// Total is the count of items matching the query at this read.
	Total int64 `json:"total"`
}

List is a List row's Response, or embedded in it beside the app's own fields. The binder writes a nil Items as [] and answers internal_error, writing nothing, unless 0 <= Offset <= Total <= 999,999,999,999,999, Offset+len(Items) <= Total, PrevCursor is absent exactly when Offset is 0, and NextCursor is absent exactly when the page ends at Total.

type Mount

type Mount struct {
	Handler http.Handler
	Rows    []Endpoint
}

Mount is a handler serving its own rows: they are in the table for the client generator, the document and the unions, and the handler decodes and guards them itself.

type None

type None struct{}

None is a row's type where it declares none: a P, Q or B the row has no Params, Query or Request for, and the R of a row with no Response (a 204).

type Option

type Option func(*options)

Option configures New. When an option is given twice, the last one wins.

func WithClientFloor

func WithClientFloor(f ClientFloor) Option

WithClientFloor turns on the client version floor. New requires it exactly when the table names a ClientHeader, with both functions set.

func WithCredential

func WithCredential(fn func(*http.Request) string) Option

WithCredential names the session or key a request came with, which idempotency keys, sealed handles and the held-request cap are scoped to. New requires it when a row's class is not Public.

func WithCursorKey

func WithCursorKey(key [32]byte) Option

WithCursorKey sets the key list cursors and Seal's handles are sealed under. Without it, New draws one at random, so cursors stop opening at a restart and a client reads the list again from its first page.

func WithCursorOwner

func WithCursorOwner(fn func(*http.Request) string) Option

WithCursorOwner names the owner a list cursor is bound to: one answer for every session of one person. New requires it when a row's class is not Public.

func WithFeed

func WithFeed(f interface {
	Position(r *http.Request, kinds []string) string
},
) Option

WithFeed sets the change feed whose position seeds Feed-Position on every 2xx of a row with Changes. New requires it for such a row.

func WithGuard

func WithGuard(g Guard) Option

WithGuard sets the guard that admits each row's principal; nil is none, and New then refuses every row whose class is not Public.

func WithHold

func WithHold(fn func(next http.Handler) http.Handler) Option

WithHold wraps every Held row's handler and every Keyed row's join waiter, counting each against the held-request cap. New requires it for a Held or Keyed row.

func WithIdempotency

func WithIdempotency(o IdempotencyOptions) Option

WithIdempotency configures the Keyed rows; without it each default holds.

func WithKeyRate

func WithKeyRate(l *httpserver.KeyedRateLimiter, key func(*http.Request) (string, bool)) Option

WithKeyRate takes one token from l per admitted request whose principal key answers as an API key. New requires it when a row's class admits a key, and refuses it with a nil l or key.

func WithLogger

func WithLogger(l *slog.Logger) Option

WithLogger names where the binder's lines go. Without it, each line goes to slog.Default() as it is when the line is written.

func WithOutage

func WithOutage(fn func() string) Option

WithOutage reports, per request, which file cannot open: "accounts", "store" or "" when both are open. While it names one, every row not marked DuringOutage answers accounts_unavailable or store_unavailable before its guard runs; a mount is refused only while the accounts file is out. Any other answer is a wiring bug, answered internal_error. nil is no outage.

func WithSchema

func WithSchema(doc []byte) Option

WithSchema hands New the table's committed OpenAPI document, which every request is checked against, httpwiretest.Contract checks answers against, and which gives the wire version. New requires it.

func WithSpoolDir

func WithSpoolDir(dir string) Option

WithSpoolDir names the private directory a Keyed Raw row's body is spooled in; New requires it for such a row. New removes the regular files in dir named httpwire-spool-*, which a crash left, and nothing else; it refuses a dir it cannot read.

type Owner

type Owner struct {
	// Sentinels holds every exported Err* variable the owner package
	// declares, by name; httpwiretest.Sentinels holds it to the source.
	Sentinels map[string]error
	// Outside names a sentinel that is handled inside the package, with why.
	Outside map[string]string
	Name    string
	// Codes is matched in order, with errors.Is: the first match answers.
	Codes []OwnerCode
}

Owner is the error-code table of a package whose sentinels a handler may return: each sentinel answers its code, or is named in Outside with the reason it never reaches the wire.

type OwnerCode

type OwnerCode struct {
	Err  error
	Code string
}

OwnerCode maps one sentinel to the code it answers.

type Page

type Page struct {
	Cursor Cursor `json:"cursor,omitempty"`
	Limit  Limit  `json:"limit,omitempty"`
}

Page is embedded in a List row's Query type.

type Quiescer

type Quiescer interface {
	Quiesce(ctx context.Context, q Quiet) (resume func(), err error)
}

Quiescer is quieted while a database file it reads is replaced. It returns from Quiesce(ctx, QuietAll) only once it will commit nothing derived from the old file after the reopen: its requests and its own writers held, and a job runner's running jobs cancelled or finished, each job writing only through the pin it took at its start. resume is idempotent.

type Quiet

type Quiet int

Quiet is how far Quiesce quiets an API.

const (
	// QuietWrites answers maintenance on every write row, a mount's
	// included, and every Stream row.
	QuietWrites Quiet = iota + 1
	// QuietAll also holds every other row: a request waits for resume, at
	// most 5 s, then answers maintenance.
	QuietAll
)

type ReasonSet

type ReasonSet struct {
	Listed []string
	Open   bool
}

ReasonSet is the reasons one code may carry on a row. Open marks a set the row cannot close (a field name or an upstream code rides in the reason): Listed holds the known ones, and a client must accept any other.

type Schema

type Schema struct {
	// contains filtered or unexported fields
}

Schema is a parsed OpenAPI 3.1 document: the request and response schemas of each operation, by operationId. A nil *Schema declares no operation.

func ParseSchema

func ParseSchema(doc []byte) (*Schema, error)

ParseSchema parses the OpenAPI 3.1 document wiregen writes. It refuses a schema keyword outside the closed set the validator reads (the README lists it), a pattern IsWirePattern rejects, an unresolved $ref, a $ref cycle with no object between, and an OpenAPI member wiregen never writes, naming each in the joined error. An object schema with properties and no additionalProperties admits no other member, as the decode refuses unknown fields.

func (*Schema) CheckBody

func (s *Schema) CheckBody(operation string, status int, body []byte) []FieldError

CheckBody validates one JSON value against an operation's request body (status 0) or the response for status, numbers read exactly (an integer as int64 or uint64, never through float64). It answers one entry per failing path ("" for the value itself), with the field code of the one map. An operation, status or body the document does not declare answers one entry at "" with code unknown.

func (*Schema) CheckParam

func (s *Schema) CheckParam(operation, in, name string, value any) *FieldError

CheckParam validates one parameter value against its schema: in is "query", "path" or "header", value a string, int64, uint64 or bool (the number or boolean a query value parsed to). The entry's Path is name.

type Shape

type Shape struct {
	// Scopes are sorted.
	Scopes    []string
	Principal ShapeKind
}

Shape is a principal's kind and the scopes it holds: the unit every principal of one view shares.

type ShapeKind

type ShapeKind uint8

ShapeKind is a principal's kind.

const (
	ShapeAnonymous ShapeKind = iota + 1
	ShapeSession
	ShapeKey
)

The principal kinds.

type Status

type Status[T any] struct {
	// Body is written as JSON when Code declares a body, and never on a
	// bodiless status.
	Body T
	// Code is the row's Status or one of its Successes; zero is the row's
	// Status. Any other code is answered internal_error.
	Code int
}

Status is the answer of a JSON row that declares Successes: one of the row's declared success statuses and its body.

func Answer

func Answer[T any](code int, body T) Status[T]

Answer is the status and body a handler of a row with Successes returns.

type Success

type Success struct {
	Response reflect.Type // nil is none (a 204)
	Status   int
}

Success is one success status a row answers besides its primary one.

type Table

type Table struct {
	Catalog *Catalog
	// Prefix starts every row's path: "/api", "/v1".
	Prefix string
	// ClientHeader is the header a client version floor reads; "" is no
	// floor.
	ClientHeader string
	Endpoints    []Endpoint
	// Sources are the change feed's sources.
	Sources []FeedSource
	// Kinds are every change kind with its source; empty with no feed.
	Kinds []FeedKind
	// Mounts are rows served and guarded by a handler outside the binder.
	Mounts []Mount
	// MaxBody is the request body cap; zero is 64 KiB.
	MaxBody int
	// Window is how long a Keyed row with no Window of its own keeps an
	// answer: 10 minutes when zero, else 1 minute to 7 days. Derive copies
	// it onto each such row, so the document publishes every row's window.
	Window time.Duration
	// OnePerson says only one person can sign in, so a Personal read may
	// name kinds.
	OnePerson bool
}

Table is an app's API: its rows, owners, feed kinds and mounts.

func Derive

func Derive(t *Table, guardCodes func(Access) []string) (*Table, error)

Derive runs every table check that needs no binding and returns a copy of t with each row's Errors filled and MaxBody defaulted. Its error lists every refusal at once, each naming its row, owner, source or kind. guardCodes answers the guard's codes for an Access; nil is no guard.

type Tag

type Tag struct {
	// Open is the token of what the revision lives in: a store file's open
	// (OpenToken of its epoch, read inside the transaction that reads or
	// checks the revision), or the first 8 bytes of a shared file's SHA-256.
	Open [8]byte
	Rev  uint64
}

Tag is an IfMatch row's entity tag: a revision bound to what it lives in, so a revision an older file puts back never matches a tag read before.

func (Tag) MarshalText

func (t Tag) MarshalText() ([]byte, error)

MarshalText answers String's text.

func (Tag) String

func (t Tag) String() string

String answers "<16 lowercase hex>.<canonical decimal>": the value inside If-Match's quotes, and a read answer's tag field.

func (*Tag) UnmarshalText

func (t *Tag) UnmarshalText(b []byte) error

UnmarshalText takes exactly String's form: 16 lowercase hex characters, ".", and a decimal with no sign or leading zero of at most 2^64-1. On an error t is left unchanged.

type Upstream

type Upstream struct {
	// Service names the other service in the code grammar ("sonarr").
	Service string `json:"service"`
	// Status is the service's HTTP status; 0, or a value outside 100 to 599,
	// is not written.
	Status int `json:"status,omitempty"`
	// Message is the service's own text, written as one line of at most 512
	// bytes.
	Message string `json:"message"`
}

Upstream is another service's answer when the app's call to it failed. It is untrusted text: no code or remediation depends on it.

Directories

Path Synopsis
Package httpwiretest checks an app's httpwire API from its handler tests: every answer against the row's declared shapes in the document the API runs with, and each owner package's sentinels against its code table.
Package httpwiretest checks an app's httpwire API from its handler tests: every answer against the row's declared shapes in the document the API runs with, and each owner package's sentinels against its code table.
internal
wirelink
Package wirelink hands package httpwiretest what an httpwire API was built with, which httpwire keeps off its exported API.
Package wirelink hands package httpwiretest what an httpwire API was built with, which httpwire keeps off its exported API.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL