fuge

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 28, 2026 License: Apache-2.0 Imports: 24 Imported by: 0

README

fuge

A typed RPC layer for Centrifuge WebSocket connections, documented as it's built. Register a typed Go function and it becomes both a live RPC method and an entry in a generated AsyncAPI 3.1 document — the way huma binds an HTTP handler and documents it as OpenAPI in one call.

api := fuge.New(fuge.DefaultConfig("Platform RPC", "1.0.0"))

fuge.Register(api, fuge.Operation{
    OperationID: "create-country",
    Method:      "country.create",
    Summary:     "Create a new country",
}, func(ctx context.Context, req *CreateCountryRequest) (*Country, error) {
    return &Country{ID: 1, Name: req.Name}, nil
})

node.OnConnect(func(c *centrifuge.Client) { api.Attach(node, c) })
api.ServeDocs(mux) // /asyncapi.json, /asyncapi.yaml and the interactive /asyncdocs/ UI
Authorizing calls and channel access

RPC methods are gated with an OpMiddleware (api.UseMiddleware), which sees the operation and its extensions. Channels have the equivalent: a ChannelGate (api.UseChannelGate) that runs before every client subscribe and publish, and sees the channel's extensions:

api.UseChannelGate(func(ctx context.Context, ch *fuge.ChannelInfo, action fuge.ChannelAction,
    params fuge.Params, info fuge.SubscribeInfo) error {
    ext := ch.Extensions // documents subscribing
    if action == fuge.ChannelPublish {
        ext = ch.PublishExtensions // documents client publishing (AllowPublish)
    }
    return checkPermissions(ctx, ext) // e.g. read ext["x-permissions"]
})

Declaring a requirement as an extension on the operation or channel means the same value is shown in the AsyncAPI document and enforced by the gate. Return centrifuge.ErrorPermissionDenied to refuse; per-channel rules that depend on the parameters (does this room belong to this user?) still go in ChannelHandle.OnSubscribe, which runs after the gates.

Security

fuge supports the token-based schemes a browser WebSocket can carry; New panics on anything else:

Scheme Delivered as
http + bearer Centrifuge connect token
oauth2 (all four flows) access token → connect token
openIdConnect access token → connect token
httpApiKey, in: query / cookie URL query parameter / cookie

(Header-based keys, HTTP basic and the other AsyncAPI types can't be sent by a browser WebSocket, so they aren't offered.) The docs UI has an Authorize panel for these: it runs authorization code + PKCE, implicit, password and client-credentials flows and OpenID Connect discovery, pre-filled from the document, with every field editable. Tune the defaults with x-fuge-* extensions:

cfg.SecuritySchemes["oauth"] = fuge.SecurityScheme{
    Type:  fuge.SecurityTypeOAuth2,
    Flows: &fuge.OAuthFlows{AuthorizationCode: &fuge.OAuthFlow{
        AuthorizationURL: "https://idp.example.com/auth",
        TokenURL:         "https://idp.example.com/token",
        AvailableScopes:  map[string]string{"openid": "OIDC"},
    }},
    Extensions: fuge.OAuthExtensions(fuge.OAuthOptions{
        ClientID:        "web",
        DefaultScopes:   []string{"openid"},
        UsePKCE:         "S256", // or "plain", "none"
        AuthorizeParams: map[string]string{"audience": "api"},
    }),
}

OAuthOptions also covers RedirectURI (default: the docs page), TokenName, CredentialsLocation ("body"/"header") and TokenParams. The docs page's CSP automatically allows the token/discovery endpoints' origins; add others (e.g. endpoints an OIDC discovery document points at) with DocsOptions.ConnectSrc. The identity provider must allow CORS from the docs origin for the token endpoint, and the redirect URI must be registered with it.

Serving the docs

api.ServeDocs(m) mounts the document and the interactive reference (rendered operations plus a "Try it" client) on anything with Handle(pattern, http.Handler) — *http.ServeMux, chi. The paths come from Config and default to:

Config field Default
DocsPath /asyncdocs
JSONPath /asyncapi.json
YAMLPath /asyncapi.yaml

Set one and everything follows (routes, the UI's spec links). Use api.DocsRoute(), api.JsonRoute() and api.YamlRoute() wherever you need the URL. cfg.Docs (DocsOptions) sets the page title and default websocket URL.

For routers with a different Handle signature (gorilla/mux), loop over the routes:

for _, r := range api.Routes() { // or api.SpecRoutes() / api.DocsRoutes()
    if r.Subtree {
        router.PathPrefix(r.Path + "/").Handler(r.Handler)
    } else {
        router.Handle(r.Path, r.Handler)
    }
}

api.DocsHandler(prefix, DocsOptions{...}) is the lower-level handler if you want to place the UI yourself (SpecURL points it at a document hosted elsewhere).

See example/main.go for a complete, runnable version of the above.

Why

Centrifuge gives you a WebSocket connection and an RPC event; it doesn't give you routing, typed request/response handling, or any way to describe your RPC surface to the outside world. fuge adds all three:

  • Typed handlers. Write func(ctx, *Req) (*Res, error); fuge decodes, validates (if Req implements Validate() error), calls your function, and encodes the result.
  • Real errors. A returned error is mapped to an internal error and logged without leaking details, unless it's a *fuge.Error (see ErrNotFound, ErrConflict, ErrValidation, ErrTimeout, or build your own with NewError) or a *centrifuge.Error, in which case its code, message and Temporary flag go straight to the client. WithErrorMapper translates domain errors — a database's "not found", say — without every handler needing to know about the wire format.
  • A generated AsyncAPI document. Every Register'd operation appears in api.JSON() / api.DocHandler(): its request and response schemas (reflected from your Go types), its possible error codes, its security requirements, and any x- extensions you attach. Validation against the official AsyncAPI 3.1 meta-schema is opt-in (see Dependencies).

The three layers

Most applications only ever touch the first one.

Layer Use for Key names
Documented RPC Anything client-facing, request/reply Register, Operation, Group, UseMiddleware, OpMiddleware
Documented channels Real pub/sub — broadcast, subscribe, publish RegisterChannel, Channel, AllowPublish, OnSubscribe
Raw Internal/undocumented methods Handle, RouteGroup, Use, Middleware
Router Rarely touched directly Router, NewRouter, Attach, Call

API (built by New) embeds a Router directly — there's no separate router to construct or wire up. Register and Handle both end up dispatching through the same Router, so router-level Use middleware (timeouts, logging, auth) applies to everything either way; UseMiddleware is the documented-only layer that can additionally read the Operation being called (OperationFrom(ctx)), e.g. to check op.Security.

Security and extensions

cfg := fuge.DefaultConfig("Platform RPC", "1.0.0")
cfg.SecuritySchemes["bearer"] = fuge.SecurityScheme{
    Type: "http", Scheme: "bearer", BearerFormat: "JWT",
}

fuge.Register(api, fuge.Operation{
    Method:     "country.create",
    Security:   []map[string][]string{{"bearer": {}}},
    Errors:     []uint32{403},
    Extensions: map[string]any{"x-permissions": []string{"location.create"}},
}, createCountry)

Security is a list of alternative requirements — each map is one set of schemes that together satisfy the operation (an "AND"); the list itself is the "OR". AsyncAPI 3 can't express an "AND" inside one requirement (unlike OpenAPI's security model), so a map with more than one entry panics at registration rather than silently producing an invalid document.

Groups

billing := api.Group("billing", "Billing")           // documented, prefixes method + tags
invoices := billing.Group("invoice", "Invoices")
fuge.Register(invoices, fuge.Operation{Method: "create"}, createInvoice)
// wire method: "billing.invoice.create", tags: ["Billing", "Invoices"]

RouteGroup (on Router or API.RouteGroup) does the same for raw, undocumented methods — it prefixes the wire name but never touches the document.

Channels: real pub/sub, not RPC

Register'd methods live on synthetic rpc.<method> channels — a documentation device, unrelated to Centrifuge's actual channel/subscribe mechanism. For a real channel — one clients subscribe to, that the server (or another client, or another service acting as one) publishes into — use RegisterChannel:

notif := fuge.RegisterChannel[Notification](api, fuge.Channel{
    ID: "user-notifications", Pattern: "user:{userId}:notifications",
})
notif.OnSubscribe(func(ctx context.Context, params fuge.Params, info fuge.SubscribeInfo) error {
    if params["userId"] != info.UserID {
        return centrifuge.ErrorPermissionDenied
    }
    return nil
})
notif.Publish(node, fuge.Params{"userId": user.ID}, Notification{Text: "..."})

Pattern may contain {name} placeholders — Params is what you get back in OnSubscribe/AllowPublish (extracted from the real address a client used) and what you supply to Publish (rendered back into a real address). A placeholder matches one or more characters that aren't :, matching Centrifuge's usual convention of : as a namespace separator.

Centrifuge itself has no notion of "declared" channels — by default any client can subscribe to any string. API.Attach closes that gap: a subscribe to an address matching no RegisterChannel'd pattern is rejected with centrifuge.ErrorUnknownChannel before OnSubscribe ever runs.

Publish, by contrast, is refused by Centrifuge unless explicitly allowed. AllowPublish opts a channel into it, and lets the publish shape differ from the broadcast shape — what a publisher sends isn't always what subscribers should receive:

fuge.AllowPublish(chatRoom, func(ctx context.Context, params fuge.Params, in *ChatInput) (*ChatMessage, error) {
    return &ChatMessage{RoomID: params["roomId"], Author: fuge.InfoFrom(ctx).UserID, Text: in.Text}, nil
})

in is decoded and Validate()'d exactly like an RPC request. Returning (nil, nil) accepts the publish without broadcasting anything. Every operation fuge generates — RPC, broadcast, or publish — carries x-fuge-operation-kind ("rpc" / "broadcast" / "publish"), so a document consumer never has to guess intent from channel naming.

Testing

go test -race ./...

The suite covers routing (groups, middleware ordering, timeouts, panic recovery, bounded concurrency), the AsyncAPI document model (security schemes, x- extensions, schema reflection, meta-schema validation (validate package) for both success and failure cases), channels (address-pattern matching and rendering, RegisterChannel/AllowPublish document shape, and end-to-end subscribe/publish dispatch — including that a rejected or transformed publish never lets a client's raw bytes leak to subscribers), and the RPC layers together (a Register'd, Group-nested operation reachable under its full prefixed name, documented under that same name, with its Timeout actually reaching the router).

Install

go get github.com/julaw-energy/fuge

Requires Go 1.26+.

Dependencies

Direct, for package fuge:

Module Why
github.com/centrifugal/centrifuge The transport fuge wraps (Node, Client, RPC and pub/sub events). Required.
github.com/swaggest/jsonschema-go Go type → JSON Schema for request/response payloads.
go.yaml.in/yaml/v3 Block-style YAML rendering of the document.

Logging uses the standard library's log/slog behind the small Logger interface (WithLogger). Centrifuge brings its own transitive dependencies (protobuf, redis client, prometheus, ...); fuge adds none of them itself.

Optional: meta-schema validation

Package github.com/julaw-energy/fuge/validate checks the generated document against the official AsyncAPI 3.1 meta-schema. It embeds the schema (about 400 KB) and depends on santhosh-tekuri/jsonschema/v6, so it is a separate package: programs that don't import it don't link either. Opt in per API:

cfg := fuge.DefaultConfig("Platform RPC", "1.0.0")
cfg.Validator = validate.Bytes // api.JSON() now fails on a non-conforming document

Config.Validator is any func([]byte) error, so you can plug in your own check.

Status

Pre-1.0: the API may still change. It is a merge of three previously separate pieces (an RPC router, a huma-style registration layer, and a fork of mitresthen/asyncapi3 extended with security schemes, x- extensions, and AsyncAPI 3.1 support) into one package.

License

Apache License, Version 2.0 — see LICENSE. Some files are derived from mitresthen/asyncapi3 (also Apache-2.0); see NOTICE for which ones and what changed.

Documentation

Overview

Package fuge Package asyncapi3 emits AsyncAPI 3.1.0 documents from Go code.

Declare servers, channels, and operations as Go values, reflect payload schemas from the structs that cross the wire with SchemaFromType, and marshal the Document to JSON or YAML.

Marshalled output is deterministic — maps marshal key-sorted and struct field order is fixed — so regenerating an unchanged document is byte-identical. That property is what makes a committed document gateable in CI; see Check.

The document model is a curated subset of the specification. Spec objects and protocol bindings it does not model yet attach as raw JSON through the Bindings fields, so an unmodelled binding never blocks you.

Package fuge is a typed RPC layer for Centrifuge WebSocket connections, documented as it's built. Register a typed Go function and it becomes both a live RPC method and an entry in the generated AsyncAPI 3.1 document — the way huma binds an HTTP handler and documents it as OpenAPI in one call.

The package works at three layers, and most applications only ever touch the top one:

  • Register / Operation / Group: bind a typed handler and describe it (summary, tags, security, error codes, "x-" extensions). This is what builds the AsyncAPI document, and it's the primary, recommended way to add a method.
  • Handle / RouteGroup (on API or Router): register a raw, undocumented method directly — an escape hatch for internal methods that shouldn't appear in the public document.
  • Router: the underlying dispatcher (middleware, timeouts, panic recovery, bounded concurrency, Centrifuge wiring). API embeds one; most applications never construct a Router directly.

Getting started

api := fuge.New(fuge.DefaultConfig("Platform RPC", "1.0.0"))

fuge.Register(api, fuge.Operation{
    OperationID: "create-country",
    Method:      "country.create",
    Summary:     "Create a new country",
}, func(ctx context.Context, req *CreateCountryRequest) (*Country, error) {
    return &Country{ID: 1, Name: req.Name}, nil
})

node.OnConnect(func(c *centrifuge.Client) { api.Attach(node, c) })
api.ServeDocs(mux) // /asyncapi.json, /asyncapi.yaml, interactive /asyncdocs/ (paths: Config.DocsPath etc.)

Errors

A handler can return a plain error (mapped to an internal error and logged, never leaking details to the client), a *fuge.Error built with NewError or one of ErrNotFound / ErrConflict / ErrValidation / ErrTimeout (mapped to its Code/Message/Temporary), or a *centrifuge.Error directly. WithErrorMapper translates domain errors (e.g. a database's "not found") without every handler needing to know about them.

Documenting a method

Operation mirrors huma.Operation. Security is a list of alternative requirements — each map is one set of schemes that together satisfy the operation (an "AND"); the list itself is the "OR". AsyncAPI 3 cannot express an "AND" inside one requirement (unlike OpenAPI), so a map with more than one entry panics at registration. Extensions are "x-" keys merged onto the operation. Errors are extra Centrifuge error codes the operation may return, beyond the internal/bad-request/validation codes added automatically.

Channels: real Centrifuge pub/sub, not RPC

Register documents a synthetic "rpc.<method>" channel purely so every RPC method has somewhere to hang its schemas in the document; it has nothing to do with Centrifuge's actual channel/subscribe mechanism. For a real channel — one clients subscribe to, that the server (or another client, or another service acting as one) publishes into — use RegisterChannel:

notif := fuge.RegisterChannel[Notification](api, fuge.Channel{
    ID: "user-notifications", Pattern: "user:{userId}:notifications",
})
notif.OnSubscribe(func(ctx context.Context, params fuge.Params, info fuge.SubscribeInfo) error {
    if params["userId"] != info.UserID {
        return centrifuge.ErrorPermissionDenied
    }
    return nil
})
notif.Publish(node, fuge.Params{"userId": user.ID}, Notification{Text: "..."})

Centrifuge itself has no notion of "declared" channels — by default any client can subscribe to any string. API.Attach closes that gap: a subscribe to an address matching no RegisterChannel'd pattern is rejected with centrifuge.ErrorUnknownChannel before OnSubscribe ever runs.

Publish, similarly, is refused by Centrifuge unless explicitly allowed. AllowPublish opts a channel into it, and lets the publish shape differ from the broadcast shape — what a publisher sends isn't always what subscribers should receive:

fuge.AllowPublish(chatRoom, func(ctx context.Context, params fuge.Params, in *ChatInput) (*ChatMessage, error) {
    return &ChatMessage{RoomID: params["roomId"], Author: fuge.InfoFrom(ctx).UserID, Text: in.Text}, nil
})

in is decoded and Validate()'d like an RPC request. Returning (nil, nil) accepts the publish without broadcasting anything.

Every operation fuge generates — RPC, broadcast, or publish — carries "x-fuge-operation-kind" ("rpc" / "broadcast" / "publish"), so a document consumer (a renderer, a future client generator) never has to guess intent from channel naming.

Index

Constants

View Source
const (
	ActionSend    = "send"
	ActionReceive = "receive"
)

SpecOperation actions, as defined by the specification: an application either sends a message to a channel or receives one from it. Both are expressed from the point of view of the application described by the document.

View Source
const (
	CodeTimeout    uint32 = 408
	CodeNotFound   uint32 = 404
	CodeConflict   uint32 = 409
	CodeValidation uint32 = 422
)

Application error codes. Centrifuge reserves the low ranges for itself, so keep custom codes >= 400.

View Source
const (
	SecurityTypeHTTP          = "http"
	SecurityTypeHTTPAPIKey    = "httpApiKey"
	SecurityTypeOAuth2        = "oauth2"
	SecurityTypeOpenIDConnect = "openIdConnect"
)

Security scheme types fuge supports.

View Source
const (
	ExtClientID            = "x-fuge-client-id"
	ExtRedirectURI         = "x-fuge-redirect-uri"
	ExtUsePKCE             = "x-fuge-use-pkce"
	ExtDefaultScopes       = "x-fuge-default-scopes"
	ExtTokenName           = "x-fuge-token-name"
	ExtCredentialsLocation = "x-fuge-credentials-location"
	ExtAuthorizeParams     = "x-fuge-authorize-params"
	ExtTokenParams         = "x-fuge-token-params"
)

Keys of the "x-fuge-*" extensions the docs UI reads from an oauth2 or openIdConnect SecurityScheme to pre-fill its authorization panel. Build them with OAuthExtensions.

View Source
const Version = "3.1.0"

Version is the AsyncAPI specification version this package emits: 3.1.0, the only version NewDocument emits.

Variables

View Source
var (
	ErrNotFound   = NewError(CodeNotFound, "not found")
	ErrConflict   = NewError(CodeConflict, "conflict")
	ErrValidation = NewError(CodeValidation, "validation failed")
	ErrTimeout    = &Error{Code: CodeTimeout, Message: "request timed out", Temporary: true}
)

Functions

func AllowPublish

func AllowPublish[T, Req any](ch *ChannelHandle[T], fn func(ctx context.Context, params Params, req *Req) (*T, error))

AllowPublish lets clients (including other services acting as ordinary Centrifuge clients) publish directly into ch, documenting a second, "receive" operation on the same channel. Req is what a publisher must send — decoded and Validate()'d exactly like an RPC request — and is deliberately allowed to differ from T, what subscribers receive: fn is the seam between them. Returning (nil, nil) accepts the publish without broadcasting anything.

func Check

func Check(generated []byte, path string) error

Check compares freshly generated document bytes against the committed artifact at path, so contract-drift gating runs as one tested code path locally and in CI instead of shell logic in a workflow.

func MergeSchemas

func MergeSchemas(dst, src map[string]json.RawMessage) error

MergeSchemas folds src into dst, failing on same-name definitions with different content — a silent overwrite would corrupt one of the schemas.

func Register

func Register[Req, Res any](r Registrar, op Operation, fn func(ctx context.Context, req *Req) (*Res, error))

Register binds a typed handler and documents it, mirroring huma.Register.

fuge.Register(api, fuge.Operation{
    OperationID: "create-country",
    Method:      "country.create",
    Summary:     "Create a new country",
}, createCountry) // func(ctx, *CreateCountryRequest) (*Country, error)

Req and Res are inferred from the handler. Use struct{} for "no payload". Returning a nil *Res replies with no data. Misconfiguration (duplicate names, unknown security scheme, conflicting schemas) panics at startup.

func SchemaFromType

func SchemaFromType(v any, opts ...ReflectOption) (json.RawMessage, map[string]json.RawMessage, error)

SchemaFromType reflects v into a JSON Schema, returning the payload schema for the value itself — a "$ref" into "#/components/schemas/" — and the definitions it references, ready to assign to Components.Schemas.

Property names come from json struct tags. Schema keywords are read from the tags jsonschema-go understands, including required:"true", so the wire contract is declared on the struct rather than restated here.

Types

type API

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

API is the single object an application holds: it dispatches RPC calls (embedding a *Router) and, in the same step, documents every call Register binds as AsyncAPI. There is no separate router type to wire up — New builds both together.

func New

func New(cfg Config, opts ...Option) *API

New builds the API: a Router (configured by opts, see WithDefaultTimeout, WithMaxInflight, WithErrorMapper, WithLogger) plus the AsyncAPI document described by cfg. Use DefaultConfig to build cfg.

func (*API) Attach

func (a *API) Attach(node *centrifuge.Node, c *centrifuge.Client)

Attach wires the API into a Centrifuge connection: Register'd RPC methods (via Router.Attach), plus subscribe/publish dispatch for every channel registered with RegisterChannel. node is required to actually publish a transformed message when a channel has AllowPublish set (see channels.go); call this from node.OnConnect, where both are already in scope together:

node.OnConnect(func(c *centrifuge.Client) { api.Attach(node, c) })

A subscribe to an address matching no registered channel is rejected with centrifuge.ErrorUnknownChannel — Centrifuge itself has no such restriction by default (see RegisterChannel's doc comment), so this is what makes "channels must be declared on the backend" actually true.

func (*API) Call

func (a *API) Call(ctx context.Context, method string, data []byte) ([]byte, error)

Call runs a registered method in-process, documented or not — see Router.Call.

func (*API) DocsHandler

func (a *API) DocsHandler(prefix string, opts ...DocsOptions) http.Handler

DocsHandler serves an interactive AsyncAPI reference: the rendered operations and schemas plus a "Try it" client that connects to the websocket, calls RPC methods and subscribes to channels. It is self-contained (no CDN, no build step) and also serves the generated document at <prefix>/asyncapi.json and <prefix>/asyncapi.yaml.

prefix is the path the handler is mounted at, without a trailing slash (e.g. "/asyncdocs"). Mount it for both the prefix and everything below it:

h := api.DocsHandler("/asyncdocs")
mux.Handle("/asyncdocs/", h) // net/http also redirects "/asyncdocs"

or with gorilla/mux: router.Handle("/asyncdocs", h) and router.PathPrefix("/asyncdocs/").Handler(h).

Like the document handlers, the document is generated on first request, so register all operations before serving.

func (*API) DocsRoute

func (a *API) DocsRoute() string

DocsRoute, JsonRoute and YamlRoute return the configured mount paths (Config.DocsPath, JSONPath, YAMLPath; defaults "/asyncdocs", "/asyncapi.json", "/asyncapi.yaml"). Use them wherever you need the URL, so changing the config is the only edit.

func (*API) DocsRoutes

func (a *API) DocsRoutes() []Route

DocsRoutes returns the routes serving the interactive reference: DocsRoute exactly and below. It loads the document from JsonRoute/YamlRoute, so mount SpecRoutes too (Routes returns both).

func (*API) Document

func (a *API) Document() *Document

Document exposes the underlying model (like huma's api.OpenAPI()). Security and "x-" extensions are already applied by the time Register returns — Document reflects the fully-formed operation immediately.

func (*API) Group

func (a *API) Group(prefix string, tags ...string) *Group

func (*API) Handle

func (a *API) Handle(method string, h Handler, opts ...RouteOption)

Handle registers a raw, undocumented method directly on the Router — for anything that should not appear in the AsyncAPI document. Prefer Register for anything client-facing.

func (*API) JSON

func (a *API) JSON() ([]byte, error)

JSON renders the document and, if Config.Validator is set, runs it over the result. Security, extensions and security schemes are already part of a.doc by the time this runs — Register sets them directly on native fields — so there is no patch step here anymore; this is just marshal and, optionally, validate. Field order is whatever Document's own MarshalJSON produces (declared fields in their struct order, then any "x-" extensions sorted after them), so output is still deterministic.

func (*API) JsonDocHandler

func (a *API) JsonDocHandler() http.Handler

func (*API) JsonRoute

func (a *API) JsonRoute() string

func (*API) RouteGroup

func (a *API) RouteGroup(prefix string, mw ...Middleware) *RouteGroup

RouteGroup groups raw, undocumented methods under a prefix — see Router.RouteGroup. For documented operations, use Group instead.

func (*API) Router

func (a *API) Router() *Router

Router exposes the underlying dispatcher, for raw/undocumented registration (see Handle and RouteGroup) or anything else Router offers that API does not forward directly.

func (*API) Routes

func (a *API) Routes() []Route

Routes returns SpecRoutes and DocsRoutes.

func (*API) ServeDocs

func (a *API) ServeDocs(m Mux)

ServeDocs mounts the document and the interactive reference on m at the configured paths — the one-liner for the common case:

api.ServeDocs(http.DefaultServeMux) // /asyncapi.json, /asyncapi.yaml, /asyncdocs/

func (*API) ServeSpec

func (a *API) ServeSpec(m Mux)

ServeSpec mounts only the document (JsonRoute, YamlRoute) on m.

func (*API) SpecRoutes

func (a *API) SpecRoutes() []Route

SpecRoutes returns the routes serving the document: JsonRoute and YamlRoute.

func (*API) Use

func (a *API) Use(mw ...Middleware)

Use adds router-level middleware (see Router.Use), applied to every call — documented Register operations included, since they dispatch through the same Router underneath. For middleware that should see the Operation being called (e.g. to read op.Security), use UseMiddleware instead.

func (*API) UseChannelGate

func (a *API) UseChannelGate(g ...ChannelGate)

UseChannelGate adds gates that authorize every client subscribe and publish before the channel's own handlers run; see ChannelGate. Unlike UseMiddleware it may be called at any time.

func (*API) UseMiddleware

func (a *API) UseMiddleware(mw ...OpMiddleware)

UseMiddleware adds middleware applied to every Register'd operation. It must be called before the first Register, otherwise earlier operations would silently miss it.

func (*API) YamlDocHandler

func (a *API) YamlDocHandler() http.Handler

func (*API) YamlRoute

func (a *API) YamlRoute() string

type CallInfo

type CallInfo struct {
	Method    string
	RequestID string
	ClientID  string
	UserID    string
	Received  time.Time
	// Client is nil for in-process calls made via Router.Call.
	Client *centrifuge.Client
}

CallInfo is attached to the context of every call.

func InfoFrom

func InfoFrom(ctx context.Context) (CallInfo, bool)

InfoFrom returns the call metadata for the current request.

type Channel

type Channel struct {
	// ID names this channel in the document (as Operation.OperationID does
	// for RPC) and is used to derive its message and operation names.
	ID string
	// Pattern is the channel address, with optional {name} placeholders.
	Pattern     string
	Summary     string
	Description string
	Tags        []string
	// Security gates who may subscribe at the scheme level — see
	// ChannelHandle.OnSubscribe for authorization beyond that (e.g. "does
	// this specific room belong to this specific caller").
	Security   []map[string][]string
	Extensions map[string]any
	// PublishExtensions are the "x-" extensions on the operation that
	// documents client publishing (see AllowPublish), e.g. the permissions a
	// publisher needs. Channel gates see them as ChannelInfo.PublishExtensions.
	PublishExtensions map[string]any
}

Channel describes one addressable, real Centrifuge channel — as opposed to the synthetic "rpc.<method>" channels Register creates for RPC methods. Pattern may contain {name} placeholders (e.g. "chat:{roomId}"), matching AsyncAPI's own channel-parameter convention; a placeholder matches one or more characters that are not ':', matching Centrifuge's usual convention of ':' as a namespace separator in channel names.

type ChannelAction

type ChannelAction string

ChannelAction is what a client is attempting on a channel.

const (
	ChannelSubscribe ChannelAction = "subscribe"
	ChannelPublish   ChannelAction = "publish"
)

type ChannelGate

type ChannelGate func(ctx context.Context, ch *ChannelInfo, action ChannelAction, params Params, info SubscribeInfo) error

ChannelGate authorizes a client's action on a channel before it happens, the channel counterpart of OpMiddleware: it sees the channel's extensions, so a requirement documented there (say "x-permissions") can be enforced in one place instead of in every channel's OnSubscribe. ctx is the connection's context. Returning an error rejects the action; a *fuge.Error or *centrifuge.Error reaches the client as is (e.g. centrifuge.ErrorPermissionDenied). Gates run in registration order, before the channel's own OnSubscribe.

type ChannelHandle

type ChannelHandle[T any] struct {
	// contains filtered or unexported fields
}

ChannelHandle is returned by RegisterChannel: the typed handle used to publish to this channel, gate subscriptions, and (via AllowPublish) accept client-initiated publishes.

func RegisterChannel

func RegisterChannel[T any](api *API, ch Channel) *ChannelHandle[T]

RegisterChannel documents ch as a real (non-RPC) channel with a "send" operation — the server publishing to it — and returns a handle for publishing typed messages of type T. Combine with AllowPublish if clients (including other services acting as ordinary clients) should be able to publish into it directly.

func (*ChannelHandle[T]) OnSubscribe

func (ch *ChannelHandle[T]) OnSubscribe(fn func(ctx context.Context, params Params, info SubscribeInfo) error) *ChannelHandle[T]

OnSubscribe gates who may subscribe to this channel, beyond the coarse Security requirement — e.g. checking that params["userId"] matches the authenticated caller. Returning an error rejects the subscription. Returns ch so it chains at the call site: RegisterChannel(...).OnSubscribe(...).

func (*ChannelHandle[T]) Publish

func (ch *ChannelHandle[T]) Publish(node *centrifuge.Node, params Params, msg T) error

Publish sends msg to the channel identified by params (e.g. {"roomId": "room-42"} for a channel registered as "chat:{roomId}"), via node.Publish. The type used here is exactly the type RegisterChannel documented for this channel — there is no other way to publish to it.

type ChannelInfo

type ChannelInfo struct {
	ID       string
	Pattern  string
	Security []map[string][]string
	// Extensions are Channel.Extensions: they document subscribing, and are
	// what a gate reads to authorize ChannelSubscribe.
	Extensions map[string]any
	// PublishExtensions are Channel.PublishExtensions, for ChannelPublish.
	PublishExtensions map[string]any
}

ChannelInfo describes a registered channel to a ChannelGate. It is shared and must not be modified.

type Codec

type Codec interface {
	Unmarshal(data []byte, v any) error
	Marshal(v any) ([]byte, error)
}

Codec converts between wire bytes and Go values. Swap it to use msgpack, protobuf, etc. — pass it via Config.Codec.

var JSON Codec = jsonCodec{}

JSON is the default codec. If you swap the codec, also set Config.DefaultContentType so the document stays truthful.

type Components

type Components struct {
	Schemas         map[string]json.RawMessage `json:"schemas,omitempty"`
	Messages        map[string]Message         `json:"messages,omitempty"`
	Parameters      map[string]Parameter       `json:"parameters,omitempty"`
	Servers         map[string]Server          `json:"servers,omitempty"`
	Channels        map[string]SpecChannel     `json:"channels,omitempty"`
	SecuritySchemes map[string]SecurityScheme  `json:"securitySchemes,omitempty"`

	// Extensions holds "x-" values on this object. See [Extensions].
	Extensions Extensions `json:"-"`
}

Components holds reusable definitions referenced from elsewhere in the document. Schemas is where SchemaFromType definitions belong; entries are referenced as "#/components/schemas/Name".

func (Components) MarshalJSON

func (c Components) MarshalJSON() ([]byte, error)

func (*Components) UnmarshalJSON

func (c *Components) UnmarshalJSON(data []byte) error

type Config

type Config struct {
	*Document

	// SecuritySchemes populate components.securitySchemes.
	SecuritySchemes map[string]SecurityScheme
	// Codec defaults to JSON.
	Codec Codec
	// ReflectOptions are passed to SchemaFromType, e.g. RequireAll().
	ReflectOptions []ReflectOption

	// DocsPath, JSONPath and YAMLPath are where ServeDocs/Routes mount the
	// interactive reference and the generated document. Empty values default
	// to "/asyncdocs", "/asyncapi.json" and "/asyncapi.yaml"; set one and
	// everything derived from it (the routes, the UI's spec links) follows.
	DocsPath, JSONPath, YAMLPath string
	// Validator, when set, is run on the generated JSON document before it is
	// served; its error fails API.JSON. Nil (the default) skips validation.
	// validate.Bytes (package fuge/validate) checks against the official
	// AsyncAPI meta-schema.
	Validator func(document []byte) error
	// Docs customizes the interactive reference (title, default websocket URL).
	// Its SpecURL/SpecYAMLURL are managed by ServeDocs and ignored there.
	Docs DocsOptions
}

Config mirrors huma.Config: it embeds the document so cfg.Info, cfg.Servers, cfg.Components... are edited directly.

func DefaultConfig

func DefaultConfig(title, version string) Config

DefaultConfig returns a Config with JSON as the content type and codec.

type Contact

type Contact struct {
	Name  string `json:"name,omitempty"`
	URL   string `json:"url,omitempty"`
	Email string `json:"email,omitempty"`
}

Contact identifies who to reach about the API.

type DocsOptions

type DocsOptions struct {
	// Title is the browser tab title. Defaults to "<info.title> Reference".
	Title string
	// WebSocketURL pre-fills the connection bar of the "Try it" client, e.g.
	// "wss://api.example.com/connection/websocket". When empty the UI derives
	// it from the page's own origin and the document's first server pathname.
	// A URL the user typed in earlier (kept in their browser) takes precedence.
	WebSocketURL string
	// SpecURL makes the UI load the AsyncAPI document from this URL instead of
	// the copy this handler serves: a path ("/asyncapi.json") or an absolute
	// http(s) URL, whose origin is then allowed by the page's CSP (the server
	// must permit cross-origin reads, e.g. CORS). The YAML link is derived by
	// swapping a ".json" suffix for ".yaml", and hidden when there is none.
	// Any other scheme panics at construction, like a bad http.ServeMux pattern.
	SpecURL string
	// SpecYAMLURL is the YAML counterpart of SpecURL. When empty it is derived
	// from SpecURL as described there. Ignored without SpecURL.
	SpecYAMLURL string
	// ConnectSrc lists extra origins ("https://idp.example.com") the page may
	// fetch from. Origins of the security schemes' token and discovery URLs
	// and of SpecURL are added automatically; list others here, e.g. the
	// authorization/token endpoints an openIdConnect discovery document
	// points at when they live on a different host.
	ConnectSrc []string
}

DocsOptions customizes API.DocsHandler. The zero value is valid.

type Document

type Document struct {
	AsyncAPI           string                   `json:"asyncapi"`
	ID                 string                   `json:"id,omitempty"`
	Info               Info                     `json:"info"`
	DefaultContentType string                   `json:"defaultContentType,omitempty"`
	Servers            map[string]Server        `json:"servers,omitempty"`
	Channels           map[string]SpecChannel   `json:"channels,omitempty"`
	Operations         map[string]SpecOperation `json:"operations,omitempty"`
	Components         *Components              `json:"components,omitempty"`

	// Extensions holds "x-" values on the document root. See [Extensions].
	Extensions Extensions `json:"-"`
}

Document is the root of an AsyncAPI document. Build one with NewDocument so the specification version is set correctly.

func NewDocument

func NewDocument(title, version string) *Document

NewDocument returns a Document for AsyncAPI 3.1.0 with its required info fields populated.

func (Document) MarshalJSON

func (d Document) MarshalJSON() ([]byte, error)

func (*Document) UnmarshalJSON

func (d *Document) UnmarshalJSON(data []byte) error

type Error

type Error struct {
	Code      uint32
	Message   string
	Temporary bool
	// contains filtered or unexported fields
}

Error is a client-visible RPC error. Only Code, Message, and Temporary are sent over the wire; the wrapped cause stays server-side (logs only).

func NewError

func NewError(code uint32, message string) *Error

func (*Error) Error

func (e *Error) Error() string

func (*Error) Is

func (e *Error) Is(target error) bool

Is makes errors.Is(err, ErrNotFound) work for any error with the same code, including copies produced by WithMessage / Wrap.

func (*Error) Unwrap

func (e *Error) Unwrap() error

func (*Error) WithMessage

func (e *Error) WithMessage(msg string) *Error

WithMessage returns a copy with a different client-visible message.

func (*Error) Wrap

func (e *Error) Wrap(cause error) *Error

Wrap returns a copy that carries a server-side cause (never sent to clients).

type ErrorMapper

type ErrorMapper func(err error) (*Error, bool)

ErrorMapper lets you translate domain errors (pgx.ErrNoRows, your own sentinel errors...) into client-visible errors. Return ok=false to fall through to the default handling.

type Extensions

type Extensions map[string]any

Extensions holds "x-" specification extensions: implementation-defined values the specification permits on almost every object, alongside that object's own fields (e.g. a channel, an operation, a security scheme).

Keys must start with "x-". MarshalJSON reports an error otherwise, since a malformed key would silently produce a document that fails meta-schema validation (fuge/validate).

func OAuthExtensions

func OAuthExtensions(o OAuthOptions) Extensions

OAuthExtensions returns the "x-fuge-*" extensions for o, ready to assign to SecurityScheme.Extensions. Zero fields are omitted.

type ExternalDocs

type ExternalDocs struct {
	Description string `json:"description,omitempty"`
	URL         string `json:"url"`
}

ExternalDocs points at documentation held outside the document.

type Group

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

Group prefixes method names and tags for the operations registered on it. Unlike RouteGroup, the prefix is visible to the documentation.

func (*Group) Group

func (g *Group) Group(prefix string, tags ...string) *Group

type Handler

type Handler func(ctx context.Context, req Request) (Response, error)

type Info

type Info struct {
	Title          string        `json:"title"`
	Version        string        `json:"version"`
	Description    string        `json:"description,omitempty"`
	TermsOfService string        `json:"termsOfService,omitempty"`
	Contact        *Contact      `json:"contact,omitempty"`
	License        *License      `json:"license,omitempty"`
	Tags           []Tag         `json:"tags,omitempty"`
	ExternalDocs   *ExternalDocs `json:"externalDocs,omitempty"`

	// Extensions holds "x-" values on this object. See [Extensions].
	Extensions Extensions `json:"-"`
}

Info carries metadata about the API. Title and Version are required by the specification.

func (Info) MarshalJSON

func (i Info) MarshalJSON() ([]byte, error)

func (*Info) UnmarshalJSON

func (i *Info) UnmarshalJSON(data []byte) error

type License

type License struct {
	Name string `json:"name"`
	URL  string `json:"url,omitempty"`
}

License names the license the API is published under.

type Logger

type Logger interface {
	Info(msg string, args ...any)
	Warn(msg string, args ...any)
	Error(msg string, args ...any)
}

Logger is the subset of *slog.Logger the router needs.

type Message

type Message struct {
	Ref         string          `json:"$ref,omitempty"`
	Name        string          `json:"name,omitempty"`
	Title       string          `json:"title,omitempty"`
	Summary     string          `json:"summary,omitempty"`
	Description string          `json:"description,omitempty"`
	ContentType string          `json:"contentType,omitempty"`
	Headers     json.RawMessage `json:"headers,omitempty"`
	Payload     json.RawMessage `json:"payload,omitempty"`
	Examples    json.RawMessage `json:"examples,omitempty"`
	Tags        []Tag           `json:"tags,omitempty"`
	Bindings    json.RawMessage `json:"bindings,omitempty"`

	// Extensions holds "x-" values on this object. See [Extensions].
	Extensions Extensions `json:"-"`
}

Message describes one kind of message on a channel. Set Ref alone to reference a message defined under Components; otherwise Payload carries the schema, typically produced by SchemaFromType.

func (Message) MarshalJSON

func (m Message) MarshalJSON() ([]byte, error)

func (*Message) UnmarshalJSON

func (m *Message) UnmarshalJSON(data []byte) error

type Middleware

type Middleware func(Handler) Handler

Middleware wraps a Handler. Middleware attached first runs first (outermost).

func Logging

func Logging(l Logger) Middleware

Logging logs one line per call with duration and outcome.

func Observe

func Observe(fn func(info CallInfo, d time.Duration, err error)) Middleware

Observe is the hook for metrics/tracing: called after every call.

func RequireUser

func RequireUser() Middleware

RequireUser rejects calls from anonymous connections.

type Mux

type Mux interface {
	Handle(pattern string, h http.Handler)
}

Mux is the part of a router ServeDocs needs. *http.ServeMux and chi's routers satisfy it; for routers whose Handle has a different signature (gorilla/mux) loop over API.Routes instead.

type OAuthFlow

type OAuthFlow struct {
	AuthorizationURL string            `json:"authorizationUrl,omitempty"`
	TokenURL         string            `json:"tokenUrl,omitempty"`
	RefreshURL       string            `json:"refreshUrl,omitempty"`
	AvailableScopes  map[string]string `json:"availableScopes"`
}

OAuthFlow configures one OAuth2 flow. AuthorizationURL is required for Implicit and AuthorizationCode; TokenURL is required for Password, ClientCredentials and AuthorizationCode. AvailableScopes is always required — pass an empty, non-nil map if the flow grants no scopes, since a nil map marshals as JSON null and fails validation against the specification's meta-schema.

type OAuthFlows

type OAuthFlows struct {
	Implicit          *OAuthFlow `json:"implicit,omitempty"`
	Password          *OAuthFlow `json:"password,omitempty"`
	ClientCredentials *OAuthFlow `json:"clientCredentials,omitempty"`
	AuthorizationCode *OAuthFlow `json:"authorizationCode,omitempty"`
}

OAuthFlows configures the OAuth2 flows an "oauth2" SecurityScheme supports. At least one flow must be set.

type OAuthOptions

type OAuthOptions struct {
	// ClientID is the public client identifier.
	ClientID string
	// RedirectURI the identity provider sends the user back to. Defaults to
	// the docs page itself, which relays the result to the opener.
	RedirectURI string
	// UsePKCE for the authorization-code flow: "S256" (default), "plain" or "none".
	UsePKCE string
	// DefaultScopes are pre-selected.
	DefaultScopes []string
	// TokenName is the field holding the token in the token response
	// (default "access_token").
	TokenName string
	// CredentialsLocation says where client credentials go on token requests:
	// "body" (default) or "header" (HTTP Basic).
	CredentialsLocation string
	// AuthorizeParams are extra query parameters on the authorization request
	// (e.g. {"audience": "api", "prompt": "login"}).
	AuthorizeParams map[string]string
	// TokenParams are extra form fields on the token request.
	TokenParams map[string]string
}

OAuthOptions are the defaults the docs UI pre-fills for an oauth2 or openIdConnect scheme. Every field is optional, and the person using the UI can change any of them before authorizing.

type OpHandler

type OpHandler func(ctx context.Context, data []byte) ([]byte, error)

OpHandler is the raw, codec-level handler an Operation is bound to.

type OpMiddleware

type OpMiddleware func(op *Operation, next OpHandler) OpHandler

OpMiddleware wraps an OpHandler and can inspect the operation being called, which is what lets a security middleware read op.Security or op.Extensions.

type Operation

type Operation struct {
	// OperationID is the stable identifier in the document. Defaults to Method.
	OperationID string
	// Method is the wire name the client passes to client.rpc(). Required.
	Method      string
	Summary     string
	Description string
	Tags        []string

	// Security lists acceptable schemes, drop-in compatible with huma's type:
	// each map is one alternative (OR). A map holding more than one scheme
	// (AND) cannot be expressed in AsyncAPI 3 and panics at registration.
	// Scopes are ignored: AsyncAPI 3 carries them on the scheme itself.
	Security []map[string][]string

	// Errors are extra Centrifuge error codes this method may return. Internal
	// error (100) is always documented; bad request (107) is added when the
	// request has a payload and validation (422) when it implements Validator.
	Errors []uint32

	// Extensions are "x-" keys added to the AsyncAPI operation.
	Extensions map[string]any

	// Timeout overrides the router default for this method.
	Timeout time.Duration
}

Operation describes one RPC method. It mirrors huma.Operation: the fields below are what developers fill in; Register translates them into AsyncAPI.

func OperationFrom

func OperationFrom(ctx context.Context) (*Operation, bool)

OperationFrom returns the operation being executed. Available to OpMiddleware and OpHandler (not to Middleware, which runs one layer lower, in the router).

type OperationReply

type OperationReply struct {
	Channel  RefObj   `json:"channel,omitzero"`
	Messages []RefObj `json:"messages,omitempty"`

	// Extensions holds "x-" values on this object. See [Extensions].
	Extensions Extensions `json:"-"`
}

OperationReply describes the response half of a request/reply exchange, and the channel it arrives on — which may be the request channel itself.

func (OperationReply) MarshalJSON

func (r OperationReply) MarshalJSON() ([]byte, error)

func (*OperationReply) UnmarshalJSON

func (r *OperationReply) UnmarshalJSON(data []byte) error

type Option

type Option func(*config)

func WithDefaultTimeout

func WithDefaultTimeout(d time.Duration) Option

WithDefaultTimeout applies a deadline to every route (override per route with WithTimeout). Zero means no deadline.

func WithErrorMapper

func WithErrorMapper(m ErrorMapper) Option

func WithLogger

func WithLogger(l Logger) Option

func WithMaxInflight

func WithMaxInflight(n int) Option

WithMaxInflight bounds concurrently running handlers across the router. Excess calls are rejected immediately with ErrorLimitExceeded.

type Parameter

type Parameter struct {
	Description string   `json:"description,omitempty"`
	Enum        []string `json:"enum,omitempty"`
	Default     string   `json:"default,omitempty"`
	Examples    []string `json:"examples,omitempty"`
	Location    string   `json:"location,omitempty"`

	// Extensions holds "x-" values on this object. See [Extensions].
	Extensions Extensions `json:"-"`
}

Parameter describes one substitution in a channel address.

func (Parameter) MarshalJSON

func (p Parameter) MarshalJSON() ([]byte, error)

func (*Parameter) UnmarshalJSON

func (p *Parameter) UnmarshalJSON(data []byte) error

type Params

type Params map[string]string

Params holds the values extracted from a channel address's parameters — e.g. {"roomId": "room-42"} for a channel registered with pattern "chat:{roomId}" when a client subscribes to "chat:room-42".

type RefObj

type RefObj struct {
	Ref string `json:"$ref,omitempty"`
}

RefObj is a JSON Reference to another part of the document. Build one with Ref.

func Ref

func Ref(target string) RefObj

Ref returns a reference to target, e.g. "#/channels/portTotals".

type ReflectOption

type ReflectOption func(*reflectConfig)

ReflectOption configures SchemaFromType.

func RequireAll

func RequireAll() ReflectOption

RequireAll marks every property of every reflected definition as required. Correct only for payloads whose Go structs never use omitempty — Go then marshals every field on every message.

type Registrar

type Registrar interface {
	// contains filtered or unexported methods
}

Registrar is implemented by *API and *Group so Register works on both.

type Request

type Request struct {
	Method string
	Data   []byte
}

type Response

type Response struct {
	Data []byte
}

type Route

type Route struct {
	Path    string
	Subtree bool
	Handler http.Handler
}

Route is one path to mount. Subtree means "this path and everything below it" (a prefix match); otherwise it is an exact match.

type RouteGroup

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

func (*RouteGroup) Handle

func (g *RouteGroup) Handle(method string, h Handler, opts ...RouteOption)

func (*RouteGroup) RouteGroup

func (g *RouteGroup) RouteGroup(prefix string, mw ...Middleware) *RouteGroup

RouteGroup creates a sub-group; names become "<parent>.<prefix>.<method>".

func (*RouteGroup) Use

func (g *RouteGroup) Use(mw ...Middleware)

type RouteOption

type RouteOption func(*routeConfig)

func WithMiddleware

func WithMiddleware(mw ...Middleware) RouteOption

WithMiddleware adds middleware that applies to this route only, innermost.

func WithTimeout

func WithTimeout(d time.Duration) RouteOption

WithTimeout overrides the default timeout for one route (0 disables it).

type Router

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

func NewRouter

func NewRouter(opts ...Option) *Router

func (*Router) Attach

func (r *Router) Attach(c *centrifuge.Client)

Attach wires the router into a client. Call it from node.OnConnect:

node.OnConnect(func(c *centrifuge.Client) { router.Attach(c) })

func (*Router) Call

func (r *Router) Call(ctx context.Context, method string, data []byte) ([]byte, error)

Call runs a route in-process without Centrifuge: ideal for unit tests. Returned errors are the raw handler errors (not mapped to wire errors).

func (*Router) Handle

func (r *Router) Handle(method string, h Handler, opts ...RouteOption)

func (*Router) RouteGroup

func (r *Router) RouteGroup(prefix string, mw ...Middleware) *RouteGroup

func (*Router) Routes

func (r *Router) Routes() []string

Routes lists registered method names (handy for startup logs / docs).

func (*Router) Use

func (r *Router) Use(mw ...Middleware)

Use adds router-wide middleware. Order of Use vs Handle calls does not matter: the final chain is built once, when the router is first used.

type SecurityScheme

type SecurityScheme struct {
	Type             string      `json:"type"`
	Description      string      `json:"description,omitempty"`
	Name             string      `json:"name,omitempty"`
	In               string      `json:"in,omitempty"`
	Scheme           string      `json:"scheme,omitempty"`
	BearerFormat     string      `json:"bearerFormat,omitempty"`
	Flows            *OAuthFlows `json:"flows,omitempty"`
	OpenIDConnectURL string      `json:"openIdConnectUrl,omitempty"`
	Scopes           []string    `json:"scopes,omitempty"`

	// Extensions holds "x-" values on this object. See [Extensions].
	Extensions Extensions `json:"-"`
}

SecurityScheme defines an authentication or authorization mechanism that operations can require. Define schemes under Components.SecuritySchemes and reference them from SpecOperation.Security with Ref("#/components/securitySchemes/<name>") — AsyncAPI's operation security list is a flat "OR" of scheme references (any one satisfies the operation), unlike OpenAPI's map-of-scheme-to-scopes; there is no way to require two schemes at once (an "AND"), and this package does not model an inline (non-referenced) SecurityScheme literal in that list.

fuge supports only the token-based schemes a browser WebSocket can carry, and New panics on any other Type:

http          — Scheme must be "bearer"; BearerFormat optional ("JWT")
httpApiKey    — Name, In: "query" or "cookie" (not "header": browsers cannot
                set headers on a WebSocket)
oauth2        — Flows (any of the four), and optionally Scopes
openIdConnect — OpenIDConnectURL (the .well-known/openid-configuration URL)

For oauth2 and openIdConnect, the interactive docs UI can run the flows and pre-fills them from the scheme; tune that with OAuthExtensions ("x-fuge-*" keys on Extensions). the meta-schema (see fuge/validate) catches combinations the specification itself doesn't allow.

func (SecurityScheme) MarshalJSON

func (s SecurityScheme) MarshalJSON() ([]byte, error)

func (*SecurityScheme) UnmarshalJSON

func (s *SecurityScheme) UnmarshalJSON(data []byte) error

type Server

type Server struct {
	Host        string          `json:"host"`
	Protocol    string          `json:"protocol"`
	Pathname    string          `json:"pathname,omitempty"`
	Description string          `json:"description,omitempty"`
	Title       string          `json:"title,omitempty"`
	Summary     string          `json:"summary,omitempty"`
	Tags        []Tag           `json:"tags,omitempty"`
	Bindings    json.RawMessage `json:"bindings,omitempty"`
	Security    []RefObj        `json:"security,omitempty"`

	// Extensions holds "x-" values on this object. See [Extensions].
	Extensions Extensions `json:"-"`
}

Server describes where the API is reachable. Host and Protocol are required by the specification; Bindings carries protocol-specific configuration as raw JSON.

func (Server) MarshalJSON

func (s Server) MarshalJSON() ([]byte, error)

func (*Server) UnmarshalJSON

func (s *Server) UnmarshalJSON(data []byte) error

type SpecChannel

type SpecChannel struct {
	Address     string               `json:"address,omitempty"`
	Title       string               `json:"title,omitempty"`
	Summary     string               `json:"summary,omitempty"`
	Description string               `json:"description,omitempty"`
	Messages    map[string]Message   `json:"messages,omitempty"`
	Parameters  map[string]Parameter `json:"parameters,omitempty"`
	Servers     []RefObj             `json:"servers,omitempty"`
	Tags        []Tag                `json:"tags,omitempty"`
	Bindings    json.RawMessage      `json:"bindings,omitempty"`

	// Extensions holds "x-" values on this object. See [Extensions].
	Extensions Extensions `json:"-"`
}

SpecChannel is an addressable path messages flow through. An Address may embed parameters in braces — "/ports/{unlocode}" — each of which must have a matching entry in Parameters.

func (SpecChannel) MarshalJSON

func (c SpecChannel) MarshalJSON() ([]byte, error)

func (*SpecChannel) UnmarshalJSON

func (c *SpecChannel) UnmarshalJSON(data []byte) error

type SpecOperation

type SpecOperation struct {
	Action      string          `json:"action,omitempty"`
	Channel     RefObj          `json:"channel,omitzero"`
	Title       string          `json:"title,omitempty"`
	Summary     string          `json:"summary,omitempty"`
	Description string          `json:"description,omitempty"`
	Messages    []RefObj        `json:"messages,omitempty"`
	Reply       *OperationReply `json:"reply,omitempty"`
	// Security lists acceptable security schemes as references into
	// Components.SecuritySchemes, e.g. Ref("#/components/securitySchemes/bearer").
	// Any one entry satisfies the operation (a logical OR); see [SecurityScheme].
	Security []RefObj        `json:"security,omitempty"`
	Tags     []Tag           `json:"tags,omitempty"`
	Bindings json.RawMessage `json:"bindings,omitempty"`

	// Extensions holds "x-" values on this object. See [Extensions].
	Extensions Extensions `json:"-"`
}

SpecOperation is an action the application performs on a channel: ActionSend or ActionReceive. Set Reply to describe a request/reply exchange.

func (SpecOperation) MarshalJSON

func (o SpecOperation) MarshalJSON() ([]byte, error)

func (*SpecOperation) UnmarshalJSON

func (o *SpecOperation) UnmarshalJSON(data []byte) error

type SubscribeInfo

type SubscribeInfo struct {
	UserID   string
	ClientID string
	Channel  string // the literal address requested, e.g. "chat:room-42"
}

SubscribeInfo is what a channel's OnSubscribe handler receives about the client attempting to subscribe.

type Tag

type Tag struct {
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`

	// Extensions holds "x-" values on this object. See [Extensions].
	Extensions Extensions `json:"-"`
}

Tag groups channels, operations, or messages under a common label.

func (Tag) MarshalJSON

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

func (*Tag) UnmarshalJSON

func (t *Tag) UnmarshalJSON(data []byte) error

type Validator

type Validator interface{ Validate() error }

Validator is implemented by request types that can validate themselves. A returned error becomes a client-visible validation error (CodeValidation).

Directories

Path Synopsis
Command example is a minimal, runnable demonstration of fuge: it builds an API, registers one documented RPC method, wires it into both Centrifuge and HTTP, and prints the generated AsyncAPI document.
Command example is a minimal, runnable demonstration of fuge: it builds an API, registers one documented RPC method, wires it into both Centrifuge and HTTP, and prints the generated AsyncAPI document.
Package validate checks a generated AsyncAPI 3.1.0 document against the official meta-schema.
Package validate checks a generated AsyncAPI 3.1.0 document against the official meta-schema.

Jump to

Keyboard shortcuts

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