wire

package
v0.4.1 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2026 License: MIT Imports: 23 Imported by: 0

Documentation

Overview

Package wire carries an error from this module across a process boundary and back, keeping what makes it useful: its message, the identity of its sentinels, its hints, details, attributes and kind, and, when asked, its stack (spec 0003).

Every format translates between bytes and one model, Error, and every semantic of what a layer becomes on the wire is in this package, written once. A format is a Codec. JSON is built in; protobuf is the errors-protobuf module; anything else is a codec of your own, and gitlab.com/phpboyscout/go/errors/wire/wiretest is how you prove it agrees.

The schema in proto/phpboyscout/errors/v1/error.proto, in this module, is the contract every codec implements. The Go model mirrors it.

Index

Constants

View Source
const (
	DefaultMaxDepth      = 64
	DefaultMaxLayers     = 1024
	DefaultMaxText       = 64 << 10
	DefaultMaxItems      = 8192
	DefaultMaxInputBytes = 4 << 20
)

The default decode bounds (spec 0003 D9). Each is far above any error the estate builds, and a caller can lower or raise it.

View Source
const Version = 1

Version is the only model version this package reads and writes.

Variables

View Source
var (
	// ErrNil is returned for an attempt to encode a nil error. A nil error
	// means no error, so an edge encoding one is writing an error response
	// when nothing failed (D16).
	ErrNil = stderrors.New("wire: nil error")
	// ErrBound is returned when a decode exceeds one of its bounds (D9).
	ErrBound = stderrors.New("wire: bound exceeded")
	// ErrVersion is returned for a model version this package does not read.
	ErrVersion = stderrors.New("wire: unknown version")
	// ErrMalformed is returned for a document or tree that is not a valid
	// encoding. A malformed input is never half-decoded.
	ErrMalformed = stderrors.New("wire: malformed")
)
View Source
var (
	// ErrNotAcceptable is returned when an Accept value admits none of an
	// [Encoder]'s codecs. No body is produced, and the edge decides what to
	// send instead; an HTTP edge would answer 406 (spec 0003 D13).
	ErrNotAcceptable = stderrors.New("wire: no acceptable codec")
	// ErrUnsupportedMediaType is returned when [Readers] holds no codec for
	// the media type a sender declared.
	ErrUnsupportedMediaType = stderrors.New("wire: unsupported media type")
)

Functions

func Marshal

func Marshal(err error, c Codec, opts ...Option) ([]byte, error)

Marshal encodes err with c.

func RegisterLayer

func RegisterLayer(kind string, c LayerCodec)

RegisterLayer sends layers of kind through c. A kind under errors. or std. is refused, and two different codecs for one kind make it ambiguous; both are reported by Conflicts, and such a kind decodes opaque.

func RegisterLeaf

func RegisterLeaf(kind string, err error)

RegisterLeaf makes err decode to itself under kind, for a leaf that is not built with errors.NewSentinel, such as sql.ErrNoRows. A kind under errors. or std. is refused and reported by Conflicts.

func Unmarshal

func Unmarshal(b []byte, c Codec, opts ...Option) (error, error)

Unmarshal decodes b with c, treating it as untrusted input: every bound in opts applies, and a document that breaks one, or is malformed, returns an error and no tree.

Types

type Attr

type Attr struct {
	Key   string
	Value Value
}

Attr is one structured attribute.

type BoundedDecoder

type BoundedDecoder interface {
	DecodeBounded(b []byte, limits Limits) (*Error, error)
}

BoundedDecoder is a Codec that can refuse a document over its bounds while parsing it, before the document's size has become the decoder's memory. A parsed document is bounded again either way, so this is protection, not a second definition of the bounds.

type Codec

type Codec interface {
	// MediaType names the format, for an edge to declare and a receiver to
	// dispatch on.
	MediaType() string
	Encode(*Error) ([]byte, error)
	Decode([]byte) (*Error, error)
}

Codec maps the model to bytes and back. It holds no semantics of its own: what a layer becomes, and becomes again, is this package's (spec 0003 D12). A codec passes [wiretest.Run] to be interchangeable with JSON.

var JSON Codec = jsonCodec{}

JSON is the codec built into the core. Its documents are protojson's rendering of the schema in proto/phpboyscout/errors/v1/error.proto, in both directions, so a reader in any language that speaks protojson can read them (spec 0003 D11). It decodes with encoding/json/v2, which refuses a duplicated name where encoding/json keeps the last.

type Conflict

type Conflict struct {
	Kind   string
	Reason Reason
	// Layer reports that the registration was a [LayerCodec], not a leaf.
	Layer bool
}

Conflict is one kind a registration asked for that will not decode to it.

func Conflicts

func Conflicts() []Conflict

Conflicts lists every kind registered through errors.NewSentinel, RegisterLeaf or RegisterLayer that will not decode to its registration, sorted by kind. An instance registered under a second kind is reported under that kind, and keeps the first. A test can assert the list is empty.

type Encoder

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

Encoder is the sending edge's choice of codec, configured once. The first codec is the default.

func NewEncoder

func NewEncoder(codecs []Codec, opts ...Option) *Encoder

NewEncoder returns an encoder offering codecs, the first being the default, with opts as the defaults for every call.

func (*Encoder) Encode

func (e *Encoder) Encode(err error, accept string, opts ...Option) ([]byte, string, error)

Encode encodes err with the codec accept prefers, and returns the media type to declare. accept is an Accept value as RFC 9110 defines it; an empty one gets the default. A codec's media type is its own, so a range such as application/json matches none of the built-in ones; application/* or */* does. Options given here override the encoder's for this call.

type Error

type Error struct {
	Version uint32
	Root    *Layer
}

Error is one encoded error tree.

func FromError

func FromError(err error, opts ...Option) (*Error, error)

FromError builds the model of err. Every codec starts here, which is what makes them agree. A nil err fails with ErrNil.

The depth and layer bounds apply here too, so an encode never produces a document a receiver on the default bounds refuses.

func (*Error) ToError

func (m *Error) ToError(opts ...Option) (error, error)

ToError rebuilds an error tree from the model, treating it as untrusted input: every bound in opts applies, and a tree that breaks one, or is malformed, returns an error and no tree.

type Form

type Form int32

Form says how a layer's message is rebuilt (spec 0003 D4). The set is closed: any other value fails the decode (D15).

const (
	// FormUnspecified is never valid on the wire.
	FormUnspecified Form = iota
	// FormLeaf is a leaf, whose message is Text.
	FormLeaf
	// FormTransparent renders its one cause unchanged.
	FormTransparent
	// FormPrefix renders Text + ": " + its one cause.
	FormPrefix
	// FormJoined renders its causes joined by newlines.
	FormJoined
	// FormFull renders Text, whatever the causes say.
	FormFull
)

The message forms.

type Frame

type Frame struct {
	Function string
	File     string
	Line     int64
}

Frame is one resolved frame of the sender's stack. File is module-relative, never the build host's absolute path (D8).

type Layer

type Layer struct {
	// Kind is the layer's ErrorKind, or empty for a layer that declares none.
	Kind string
	// Structural reports that KindOf looks past this layer.
	Structural bool
	// TypeName is the Go type that produced the layer. It is diagnostic only,
	// and never decides how the layer decodes.
	TypeName string
	// Form and Text say how the layer's message is rebuilt from its causes.
	Form Form
	Text string
	// Payload is what the layer carries.
	Payload Payload
	// Causes is empty for a leaf, one for a wrapper, more for an aggregate.
	Causes []*Layer
}

Layer is one layer of an encoded tree.

type LayerCodec

type LayerCodec interface {
	// Encode returns what err, a layer of the registered kind, carries.
	Encode(err error) ([]Attr, error)
	// Decode rebuilds the layer around its decoded cause, which is nil for a
	// leaf. The attributes come from another process: treat them as untrusted.
	Decode(attrs []Attr, cause error) (error, error)
}

LayerCodec carries a consumer's own wrapper type across the wire, in format-neutral attributes, so one registration serves every codec (D7).

type Limits

type Limits struct {
	MaxDepth  int
	MaxLayers int
	MaxText   int
	MaxItems  int
}

Limits are the decode bounds, for a codec that enforces them while it parses so that a hostile document is refused before it is allocated.

type Option

type Option func(*options)

Option adjusts one encode or decode.

func WithMaxDepth

func WithMaxDepth(n int) Option

WithMaxDepth bounds how deep a tree may nest.

func WithMaxInputBytes

func WithMaxInputBytes(n int) Option

WithMaxInputBytes bounds the size of an encoded document.

func WithMaxItems

func WithMaxItems(n int) Option

WithMaxItems bounds how many attributes and frames a tree may hold in all, counting those inside attribute groups.

func WithMaxLayers

func WithMaxLayers(n int) Option

WithMaxLayers bounds how many layers a tree may hold.

func WithMaxText

func WithMaxText(n int) Option

WithMaxText bounds the length in bytes of any one string in a tree.

func WithStacks

func WithStacks() Option

WithStacks sends each layer's stack. Stacks are off by default, because a stack names internal paths and functions and the boundary is often a trust boundary too (D8).

type Payload

type Payload struct {
	// Text is the payload of errors.hint, errors.detail and errors.message.
	Text *string
	// Attrs is the payload of errors.attrs and of a registered [LayerCodec].
	Attrs []Attr
	// Frames is the layer's stack, sent only with [WithStacks].
	Frames []Frame
}

Payload is a union: at most one field is set.

type Readers

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

Readers is the receiving edge's set of codecs, chosen by the media type the sender declared.

func NewReaders

func NewReaders(codecs []Codec, opts ...Option) *Readers

NewReaders returns readers for codecs, with opts as the defaults for every call. Where two codecs declare one media type, the first is used, as NewEncoder prefers the first.

func (*Readers) Decode

func (r *Readers) Decode(mediaType string, b []byte, opts ...Option) (error, error)

Decode decodes b with the codec for mediaType, ignoring its parameters. Options given here override the readers' for this call.

type Reason

type Reason int

Reason says why a registered kind will not decode to its registration.

const (
	// Ambiguous means two different registrations share the kind.
	Ambiguous Reason = iota + 1
	// Reserved means the kind is under errors. or std., which are the core's.
	Reserved
	// Uncomparable means the registered value cannot be compared with ==, so
	// no leaf can ever be recognised as it.
	Uncomparable
)

The reasons.

func (Reason) String

func (r Reason) String() string

type Value

type Value struct {
	Kind     ValueKind
	String   string
	Int64    int64
	Uint64   uint64
	Float64  float64
	Bool     bool
	Duration time.Duration
	Time     time.Time
	Group    []Attr
}

Value is an attribute's value. An slog.KindAny or KindLogValuer value is resolved and sent as its string, since an arbitrary Go value has no portable form.

type ValueKind

type ValueKind int32

ValueKind says which field of a Value is set.

const (
	// ValueUnknown is a value whose kind this version does not know. It decodes
	// as an empty string, so a newer sender's attribute is not fatal.
	ValueUnknown ValueKind = iota
	ValueString
	ValueInt64
	ValueUint64
	ValueFloat64
	ValueBool
	ValueDuration
	ValueTime
	ValueGroup
)

The value kinds, one for each slog kind that has a portable form.

Directories

Path Synopsis
Package wiretest is the conformance suite for a wire.Codec.
Package wiretest is the conformance suite for a wire.Codec.

Jump to

Keyboard shortcuts

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