weft

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2026 License: Apache-2.0 Imports: 30 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package weft is Weft for Go: the weft.* runtime that reads the checked contracts (the IR) and validates, encodes and decodes values, runs the lifecycle, and talks over HTTP and messaging.

This file's package is the core. Adapters for libraries are packages inside this module. The behaviour every language shares is written in spec/behaviour.md; the conformance suite checks it.

Index

Constants

View Source
const (
	// CallTimeout is how long a call to another service waits.
	CallTimeout = 10 * time.Second
	// ShutdownGrace is how long Stop waits for in-flight handlers.
	ShutdownGrace = 30 * time.Second
	// MessagingAttempts is the attempts before a message is dead-lettered.
	MessagingAttempts = 5
	// BackoffMin and BackoffMax bound the retry backoff.
	BackoffMin = 200 * time.Millisecond
	BackoffMax = 30 * time.Second
	// CallAttempts is the attempts of an HTTP or gRPC call.
	CallAttempts = 3
)

Defaults every package shares (docs/04-sdk-design.md).

View Source
const IdempotencyHeader = "weft-idempotency-key"

IdempotencyHeader carries the idempotency key of a message.

View Source
const ProblemTypePrefix = "urn:weft:error:"

ProblemTypePrefix starts the RFC 9457 type of a built-in category or a declared error.

View Source
const Version = "0.0.0"

Version is the version of this package. It is replaced by the release process.

Variables

View Source
var Categories = map[Category]CategoryInfo{
	NotFound:     {404, "NOT_FOUND", PolicyNone},
	InvalidInput: {400, "INVALID_ARGUMENT", PolicyDeadLetter},
	Unauthorized: {401, "UNAUTHENTICATED", PolicyNone},
	Forbidden:    {403, "PERMISSION_DENIED", PolicyNone},
	Conflict:     {409, "ALREADY_EXISTS", PolicyNone},
	Unavailable:  {503, "UNAVAILABLE", PolicyRetry},
	Timeout:      {504, "DEADLINE_EXCEEDED", PolicyRetry},
	Internal:     {500, "INTERNAL", PolicyRetryThenDeadLetter},
}

Categories is the table in spec/behaviour.md.

Functions

func BackoffDelay

func BackoffDelay(attempt int, b Backoff, random func() float64) time.Duration

BackoffDelay is exponential backoff with jitter: the delay doubles from Min up to Max, then a random amount between half of it and all of it is used. attempt is the one that just failed (1, 2, ...). random returns a number in [0, 1).

func CheckFormat

func CheckFormat(format, value string) bool

CheckFormat reports whether value is valid for the @format named format (spec/behaviour.md).

func DeadlineAfter

func DeadlineAfter(d time.Duration, existing time.Time, now time.Time) time.Time

DeadlineAfter is the earlier of "d from now" and an existing deadline.

func DeclaredFields

func DeclaredFields[T any](c *Contracts, err error, pkg, name string) (T, bool)

DeclaredFields reads the fields of a declared error into T, if err is that error.

func Environ

func Environ() map[string]string

Environ returns the process environment as a map, for ParseConfig.

func ExtractTraceContext

func ExtractTraceContext(ctx context.Context, headers map[string]string) context.Context

ExtractTraceContext returns ctx with the trace context carried in headers, to be the parent of a span.

func FindConfigFile

func FindConfigFile(dir string) (string, bool)

FindConfigFile looks for weft.yaml in dir and then each folder above it.

func FromProblem

func FromProblem(status int, body map[string]any, c *Contracts) error

FromProblem is the error a client raises for an error response: a *Error with its category, or a *DeclaredError with its fields. It mirrors ToProblem.

func FullPath

func FullPath(r *RouteDef) string

FullPath is the base and path of a route: /v1 + /orders/{id}.

func InjectTraceContext

func InjectTraceContext(ctx context.Context, headers map[string]string)

InjectTraceContext writes the span in ctx into headers as traceparent (and tracestate), W3C Trace Context.

func OnTyped

func OnTyped[T any](m *Messaging, event string, handler func(ctx context.Context, payload T, mc *MessageContext) error, o SubscribeOptions) error

OnTyped receives an event and hands the handler its payload as a Go struct.

func ParseJSON

func ParseJSON(text []byte) (any, error)

ParseJSON parses JSON keeping numbers exact (as json.Number), the form Decode expects.

func PublishTyped

func PublishTyped[T any](ctx context.Context, m *Messaging, event string, payload T, o PublishOptions) error

PublishTyped publishes an event whose payload is a Go struct.

func RecordError

func RecordError(span trace.Span, err error)

RecordError marks a span as failed and records why.

func Remaining

func Remaining(ctx context.Context, now time.Time) (time.Duration, bool)

Remaining is the time until ctx's deadline, and false when it has none. Never negative.

func Sleep

func Sleep(ctx context.Context, d time.Duration)

Sleep waits d, or less if ctx is cancelled. It returns either way; the caller checks ctx.

func ToHeaders

func ToHeaders(e Envelope, prefix string) map[string]string

ToHeaders returns the headers for an envelope in CloudEvents binary mode: <prefix>specversion, <prefix>id, ... The prefix depends on the transport (ce_ for Kafka, ce- for HTTP, cloudEvents: for AMQP). The key and the body are for the adapter to place natively; other headers are copied.

func WithTimeout

func WithTimeout[T any](parent context.Context, d time.Duration, fn func(ctx context.Context) (T, error)) (T, error)

WithTimeout runs fn with a context that is cancelled after d, or when parent is. If the time runs out first the error is Timeout; if the parent was cancelled, Unavailable. fn should pass the context on to whatever it calls. A deadline only ever gets shorter: if parent already has an earlier one, that one stays.

Types

type AdapterConfigurer

type AdapterConfigurer interface {
	Configure(settings map[string]any, config *Config)
}

AdapterConfigurer is implemented by adapters that read their settings from weft.yaml.

type AdapterReadier

type AdapterReadier interface {
	Ready(ctx context.Context) error
}

AdapterReadier is implemented by adapters that must know every subscription before they start consuming.

type Backoff

type Backoff struct {
	Min time.Duration
	Max time.Duration
}

Backoff bounds the wait between attempts. Zero values mean the defaults (200 ms to 30 s).

type Call

type Call struct {
	Transport string
	// Operation is an event name, a route name or a method.
	Operation string
	Headers   map[string]string
	// State is scratch space for middleware to pass values along.
	State map[string]any
}

Call is what every handler of every transport can see about one call. Transports add their own fields in types that embed it.

func NewCall

func NewCall(transport, operation string) *Call

NewCall makes a Call with its maps ready to use.

type CallOptions

type CallOptions struct {
	Body any
	// Params are values for the {name} parts of the path.
	Params  map[string]any
	Query   map[string]any
	Headers map[string]any
	// Timeout overrides the 10 s call timeout.
	Timeout time.Duration
	// IdempotencyKey is sent as Idempotency-Key; it makes a POST safe to retry.
	IdempotencyKey string
	// Package is for the case where two packages declare the same route.
	Package string
}

CallOptions are the options of a call to another service.

type Category

type Category string

Category is one of the eight error categories every language shares (spec/behaviour.md).

const (
	NotFound     Category = "NotFound"
	InvalidInput Category = "InvalidInput"
	Unauthorized Category = "Unauthorized"
	Forbidden    Category = "Forbidden"
	Conflict     Category = "Conflict"
	Unavailable  Category = "Unavailable"
	Timeout      Category = "Timeout"
	Internal     Category = "Internal"
)

type CategoryInfo

type CategoryInfo struct {
	HTTP      int
	GRPC      string
	Messaging MessagingPolicy
}

CategoryInfo says how a category maps to each transport.

type Config

type Config struct {
	Service string `json:"service"`
	// Transports holds the settings of each transport, such as http: {library: express, port: 3000}.
	Transports map[string]map[string]any `json:"transports"`
	// Topics maps an event name to the real topic or queue name.
	Topics map[string]string `json:"topics"`
	// Services says where other services live.
	Services  map[string]string `json:"services"`
	Telemetry map[string]string `json:"telemetry"`
}

Config is the part of weft.yaml the runtime reads (docs/06-cli.md).

func LoadConfig

func LoadConfig(path string) (*Config, error)

LoadConfig reads weft.yaml from path, or when path is empty from the working folder or a folder above it.

func ParseConfig

func ParseConfig(text string, env map[string]string) (*Config, error)

ParseConfig reads weft.yaml text. ${VAR} reads env, and WEFT_<TRANSPORT>_<KEY> (such as WEFT_KAFKA_BROKERS), WEFT_SERVICES_<NAME>, WEFT_TELEMETRY_<KEY> and WEFT_SERVICE override the file. Every problem is reported at once, in a *ConfigError.

func (*Config) ServiceURL

func (c *Config) ServiceURL(service string) (string, bool)

ServiceURL is the base URL of another service, from services:.

func (*Config) TopicName

func (c *Config) TopicName(event string) string

TopicName is the real topic or queue name for an event: the topics: entry, else the event name.

type ConfigError

type ConfigError struct{ Problems []string }

ConfigError means weft.yaml could not be used. Problems lists everything wrong, not only the first.

func (*ConfigError) Error

func (e *ConfigError) Error() string

type Contracts

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

Contracts holds the checked contracts of one or more packages, and the one validator and codec that read them. Decode turns wire form into code form; Encode does the reverse. Both validate and collect every problem. A Contracts is safe for concurrent use.

func NewContracts

func NewContracts(irs ...Ir) *Contracts

NewContracts reads the contracts of every package in irs.

func (*Contracts) Decode

func (c *Contracts) Decode(ref TypeRef, wire any) (any, error)

Decode turns a wire value into code form. When it is not valid the error is InvalidInput and lists every issue.

func (*Contracts) DecodeErrorFields

func (c *Contracts) DecodeErrorFields(pkg, name string, wire any) (map[string]any, error)

DecodeErrorFields decodes the fields of a declared error from wire form.

func (*Contracts) DecodeJSON

func (c *Contracts) DecodeJSON(ref TypeRef, text []byte) (any, error)

DecodeJSON decodes JSON text. Text that is not JSON is InvalidInput.

func (*Contracts) Encode

func (c *Contracts) Encode(ref TypeRef, value any) (any, error)

Encode turns a value in code form into wire form. When it is not valid the error is InvalidInput and lists every issue.

func (*Contracts) EncodeErrorFields

func (c *Contracts) EncodeErrorFields(pkg, name string, fields map[string]any) (map[string]any, error)

EncodeErrorFields encodes the fields of a declared error to wire form.

func (*Contracts) EncodeJSON

func (c *Contracts) EncodeJSON(ref TypeRef, value any) ([]byte, error)

EncodeJSON encodes a value and writes it as JSON.

func (*Contracts) Event

func (c *Contracts) Event(name, pkg string) (*Ir, *EventDef, error)

Event finds an event in the contracts by name.

func (*Contracts) FindRoute

func (c *Contracts) FindRoute(method, path, pkg string) (*Ir, *RouteDef, error)

FindRoute finds the route a method and path name: by the full path or, if that is not ambiguous, by the path without its base.

func (*Contracts) FromCode

func (c *Contracts) FromCode(ref TypeRef, code any, out any) error

FromCode stores a code-form value in out, which must be a non-nil pointer.

func (*Contracts) Marshal

func (c *Contracts) Marshal(ref TypeRef, v any) (any, error)

Marshal turns a Go value (a struct that weft gen wrote, or any value shaped like one) into the wire form of the type ref, validating it on the way. Struct fields are matched to the contract's fields by the wire name in their `json` tag.

func (*Contracts) NewDeclaredError

func (c *Contracts) NewDeclaredError(pkg, name string, fields any, message string) *DeclaredError

NewDeclaredError makes the error a handler returns for an error declared in the contracts, from a struct holding its fields.

func (*Contracts) Package

func (c *Contracts) Package(name string) (*Ir, bool)

Package returns the contracts of one package, if it was loaded.

func (*Contracts) Route

func (c *Contracts) Route(name, pkg string) (*Ir, *RouteDef, error)

Route finds a route by its operation name, such as createOrder.

func (*Contracts) ToCode

func (c *Contracts) ToCode(ref TypeRef, v any) (any, error)

ToCode turns a Go value into the code form of the type ref (see Contracts), without validating it beyond what the conversion needs. Marshal does both.

func (*Contracts) Unmarshal

func (c *Contracts) Unmarshal(ref TypeRef, wire any, out any) error

Unmarshal decodes a wire value as the type ref and stores it in out, which must be a non-nil pointer.

func (*Contracts) Validate

func (c *Contracts) Validate(ref TypeRef, value any) []Issue

Validate returns the problems with a value in code form. Empty when it is valid.

type DeclaredError

type DeclaredError struct {
	Package string
	Name    string
	// Fields are in code form.
	Fields  map[string]any
	Message string
}

DeclaredError is an error declared in a contract (error OutOfStock { ... }). A handler returns it; the receiving side gets the same type back, with the same fields.

func (*DeclaredError) Error

func (e *DeclaredError) Error() string

type Delivery

type Delivery struct {
	Envelope Envelope
	// DeliveryCount is how many times the broker has delivered this message, when it knows.
	DeliveryCount int
}

Delivery is what an adapter hands to core for one message.

type Envelope

type Envelope struct {
	// ID is the CloudEvents id: unique per message.
	ID string
	// Type is the CloudEvents type: the event name, such as order.placed.
	Type string
	// Source is the service that sent it.
	Source string
	// Time is RFC 3339.
	Time            string
	DataContentType string
	// Key is the ordering and partition key, if the event declares one.
	Key string
	// Headers are the other headers: trace context, the idempotency key, and anything the sender added.
	Headers map[string]string
	// Body is the encoded payload (JSON by default).
	Body []byte
}

Envelope is one message as it travels: a CloudEvents 1.0 envelope around the encoded payload. Adapters carry the attributes in the transport's own headers (binary mode) and the body as the value.

func FromHeaders

func FromHeaders(headers map[string]string, prefix string, body []byte, key string) (Envelope, []string)

FromHeaders is the reverse. When the message is not a CloudEvent it returns the missing header names.

type Error

type Error struct {
	Category Category
	Message  string
	// Issues is set for InvalidInput raised by validation.
	Issues []Issue
	Cause  error
}

Error is an error with one of the eight categories.

func AsError

func AsError(err error) *Error

AsError returns the *Error in err's chain, or wraps any other error as Internal. A nil error gives nil.

func NewError

func NewError(category Category, message string) *Error

NewError makes an error of a category.

func (*Error) Error

func (e *Error) Error() string

func (*Error) GRPCCode

func (e *Error) GRPCCode() string

GRPCCode is the gRPC status code name of the category.

func (*Error) HTTPStatus

func (e *Error) HTTPStatus() int

HTTPStatus is the status of the category.

func (*Error) MessagingPolicy

func (e *Error) MessagingPolicy() MessagingPolicy

MessagingPolicy is what a consumer does with this error.

func (*Error) Unwrap

func (e *Error) Unwrap() error

type ErrorDef

type ErrorDef struct {
	Name   string     `json:"name"`
	Status int        `json:"status"`
	Fields []FieldDef `json:"fields"`
}

type ErrorRef

type ErrorRef struct {
	Package string `json:"package"`
	Name    string `json:"name"`
}

type EventDef

type EventDef struct {
	Name    string   `json:"name"`
	Payload TypeRef  `json:"payload"`
	Key     []string `json:"key,omitempty"`
	Headers *TypeRef `json:"headers,omitempty"`
}

type FieldDef

type FieldDef struct {
	Name     string   `json:"name"`
	WireName string   `json:"wireName"`
	Type     TypeRef  `json:"type"`
	Optional bool     `json:"optional,omitempty"`
	Rules    []Rule   `json:"rules,omitempty"`
	Doc      []string `json:"doc,omitempty"`
}

type HTTP

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

HTTP is weft.http: serve the routes of the contracts, and call other services. Serving is core's work over an adapter; calling uses net/http.

func NewHTTP

func NewHTTP(w *Weft, o HTTPOptions) (*HTTP, error)

NewHTTP makes an HTTP and registers it with w.

func (*HTTP) Close

func (h *HTTP) Close(ctx context.Context) error

func (*HTTP) Delete

func (h *HTTP) Delete(path string, handler HTTPHandler) error

func (*HTTP) Get

func (h *HTTP) Get(path string, handler HTTPHandler) error

func (*HTTP) Handle

func (h *HTTP) Handle(method, path string, handler HTTPHandler) error

Handle serves a route of the contracts. Register before Weft.Start.

func (*HTTP) HandleIn

func (h *HTTP) HandleIn(pkg, method, path string, handler HTTPHandler) error

HandleIn is Handle for a route of one package, when two packages declare the same route.

func (*HTTP) Name

func (h *HTTP) Name() string

func (*HTTP) NotFound

func (h *HTTP) NotFound(message string) error

NotFound is the error to return for "nothing here".

func (*HTTP) Patch

func (h *HTTP) Patch(path string, handler HTTPHandler) error

func (*HTTP) Post

func (h *HTTP) Post(path string, handler HTTPHandler) error

func (*HTTP) Put

func (h *HTTP) Put(path string, handler HTTPHandler) error

func (*HTTP) Raw

func (h *HTTP) Raw() any

Raw is the library underneath, if serving.

func (*HTTP) Start

func (h *HTTP) Start(ctx context.Context) error

func (*HTTP) StopIntake

func (h *HTTP) StopIntake(ctx context.Context) error

func (*HTTP) To

func (h *HTTP) To(service string) *ServiceClient

To calls another service, whose base URL is under services: in weft.yaml.

func (*HTTP) Use

func (h *HTTP) Use(m HTTPMiddleware)

Use adds middleware for HTTP only. It runs after the middleware added to Weft.

type HTTPAdapter

type HTTPAdapter interface {
	Transport
	Raw() any
	// Route serves template (with {name} parameters) for method. Called before Start.
	Route(method, template string, handler func(HTTPRequest) HTTPResponse)
}

HTTPAdapter is the HTTP library underneath, as core needs it. It owns the socket, the router and the parsing of the URL; core does the contracts, the middleware, the errors and the tracing.

type HTTPContext

type HTTPContext struct {
	*Call
	Route    *RouteDef
	Method   string
	Template string
	// Response: set Status and Headers to change the response. Status defaults to 200.
	Response struct {
		Status  int
		Headers map[string]string
	}
}

HTTPContext is what an HTTP handler sees besides its input.

type HTTPHandler

type HTTPHandler func(ctx context.Context, in *HTTPInput) (any, error)

HTTPHandler handles one route. It returns the route's result in code form, or an error: an *Error of a category, or a *DeclaredError the route lists. Returning (nil, nil) for a route whose result is optional answers 404.

type HTTPInput

type HTTPInput struct {
	Body    any
	Params  map[string]any
	Query   map[string]any
	Headers map[string]any
	Ctx     *HTTPContext
}

HTTPInput is what a handler is given, decoded and validated against the route.

type HTTPMiddleware

type HTTPMiddleware func(ctx context.Context, hc *HTTPContext, next Next) error

HTTPMiddleware wraps an HTTP handler.

type HTTPOptions

type HTTPOptions struct {
	// Adapter serves requests. Leave it nil to use HTTP only as a client.
	Adapter HTTPAdapter
	// Client is used for calls to other services. Default: http.DefaultClient.
	Client *http.Client
	Logger *slog.Logger
	Sleep  func(ctx context.Context, d time.Duration)
	Random func() float64
}

HTTPOptions configures an HTTP.

type HTTPRequest

type HTTPRequest struct {
	Method string
	// Template is the route template that matched, such as /v1/orders/{id}.
	Template string
	Params   map[string]string
	Query    map[string][]string
	// Headers has names in lower case.
	Headers map[string]string
	// Body is the raw body, if there was one. Core parses it.
	Body    *string
	Context context.Context
}

HTTPRequest is a request as an adapter hands it to core. Nothing is decoded yet.

type HTTPResponse

type HTTPResponse struct {
	Status  int
	Headers map[string]string
	Body    string
}

HTTPResponse is what core wants written back.

type HTTPSettings

type HTTPSettings interface {
	Configure(settings map[string]any)
}

HTTPSettings is implemented by adapters that read transports.http from weft.yaml.

type Handler

type Handler func(ctx context.Context, call *Call) error

Handler is what a transport runs for one call.

func Compose

func Compose(middleware []Middleware, handler Handler) Handler

Compose joins middleware in front of a handler, outermost first.

type Ir

type Ir struct {
	IrVersion string     `json:"irVersion"`
	Package   string     `json:"package"`
	Version   string     `json:"version,omitempty"`
	Imports   []string   `json:"imports,omitempty"`
	Types     []TypeDef  `json:"types,omitempty"`
	Errors    []ErrorDef `json:"errors,omitempty"`
	Events    []EventDef `json:"events,omitempty"`
	Routes    []RouteDef `json:"routes,omitempty"`

	// Not read yet.
	RpcServices json.RawMessage `json:"rpcServices,omitempty"`
	Graphql     json.RawMessage `json:"graphql,omitempty"`
	Sockets     json.RawMessage `json:"sockets,omitempty"`
}

Ir is one package's contracts. Operations other than events and routes are read by later tasks.

type Issue

type Issue struct {
	// Path says where, such as "items[0].qty". Empty for the value itself.
	Path    string `json:"path"`
	Message string `json:"message"`
}

Issue is one thing wrong with a value, found by validation.

type MemoryAdapter

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

MemoryAdapter is the messaging adapter over a MemoryBroker.

func NewMemoryAdapter

func NewMemoryAdapter(name string, broker *MemoryBroker) *MemoryAdapter

NewMemoryAdapter makes an adapter named name over broker (a new one if broker is nil).

func (*MemoryAdapter) Broker

func (a *MemoryAdapter) Broker() *MemoryBroker

func (*MemoryAdapter) Capabilities

func (a *MemoryAdapter) Capabilities() MessagingCapabilities

func (*MemoryAdapter) Close

func (a *MemoryAdapter) Close(context.Context) error

func (*MemoryAdapter) FailNextPublishes

func (a *MemoryAdapter) FailNextPublishes(n int)

FailNextPublishes makes the next n calls to Publish fail with Unavailable, to test retries.

func (*MemoryAdapter) Name

func (a *MemoryAdapter) Name() string

func (*MemoryAdapter) Publish

func (a *MemoryAdapter) Publish(_ context.Context, destination string, e Envelope, options map[string]any) error

func (*MemoryAdapter) Raw

func (a *MemoryAdapter) Raw() any

func (*MemoryAdapter) Start

func (a *MemoryAdapter) Start(context.Context) error

func (*MemoryAdapter) StopIntake

func (a *MemoryAdapter) StopIntake(context.Context) error

func (*MemoryAdapter) Subscribe

func (a *MemoryAdapter) Subscribe(_ context.Context, destination string, handler func(context.Context, Delivery) error, options map[string]any) error

type MemoryBroker

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

MemoryBroker is an in-process broker for tests and examples. Each consumer group gets every message once, handed to one of its subscribers in turn; a subscriber that returns an error leaves the message in Unacked.

func NewMemoryBroker

func NewMemoryBroker() *MemoryBroker

NewMemoryBroker makes an empty broker.

func (*MemoryBroker) Idle

func (b *MemoryBroker) Idle()

Idle waits until every delivery started so far has finished.

func (*MemoryBroker) Published

func (b *MemoryBroker) Published() []Published

Published is every message sent so far.

func (*MemoryBroker) To

func (b *MemoryBroker) To(destination string) []Published

To is the messages sent to one destination.

func (*MemoryBroker) Unacked

func (b *MemoryBroker) Unacked() []Published

Unacked is the messages a subscriber refused to acknowledge.

type MessageContext

type MessageContext struct {
	*Call
	Event    string
	Envelope Envelope
	Key      string
	// Attempt is 1 for the first try, then 2, and so on.
	Attempt   int
	Timestamp time.Time
}

MessageContext is what a messaging handler sees besides the payload.

type MessageHandler

type MessageHandler func(ctx context.Context, payload any, mc *MessageContext) error

MessageHandler handles one event. payload is in code form (see Contracts).

type MessageMiddleware

type MessageMiddleware func(ctx context.Context, mc *MessageContext, next Next) error

MessageMiddleware wraps a messaging handler.

func Dedupe

func Dedupe(max int) MessageMiddleware

Dedupe returns middleware that skips a message whose idempotency key (else its CloudEvents id) was already handled successfully. It remembers up to max keys (10 000 if max is 0), the oldest forgotten first. Memory only: it covers redelivery to this process, not a restart. A key is remembered only after the handler succeeds, so a failed message is retried.

type Messaging

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

Messaging is messaging over one adapter: Publish encodes and sends an event, On receives it. Everything the libraries have in common is here: encoding, CloudEvents envelopes, validation, middleware, retries with backoff, dead letters. It is a transport of the Weft it is built on.

func NewMessaging

func NewMessaging(w *Weft, o MessagingOptions) (*Messaging, error)

NewMessaging makes a Messaging and registers it with w.

func (*Messaging) Close

func (m *Messaging) Close(ctx context.Context) error

func (*Messaging) Name

func (m *Messaging) Name() string

func (*Messaging) On

func (m *Messaging) On(event string, handler MessageHandler, o SubscribeOptions) error

On receives an event. Register before Weft.Start.

func (*Messaging) Publish

func (m *Messaging) Publish(ctx context.Context, event string, payload any, o PublishOptions) error

Publish validates, encodes and sends an event. It retries Unavailable and Timeout failures with backoff.

func (*Messaging) Raw

func (m *Messaging) Raw() any

Raw is the library underneath. Weft's tracing and middleware do not apply to calls made through it.

func (*Messaging) Start

func (m *Messaging) Start(ctx context.Context) error

func (*Messaging) StopIntake

func (m *Messaging) StopIntake(ctx context.Context) error

func (*Messaging) Use

func (m *Messaging) Use(mw MessageMiddleware)

Use adds middleware for this transport only. It runs after the middleware added to Weft.

type MessagingAdapter

type MessagingAdapter interface {
	Transport
	Raw() any
	Capabilities() MessagingCapabilities
	Publish(ctx context.Context, destination string, e Envelope, options map[string]any) error
	Subscribe(ctx context.Context, destination string, handler func(context.Context, Delivery) error, options map[string]any) error
}

MessagingAdapter is the messaging library underneath, as core needs it. Adapters only translate: encoding, envelopes, validation, middleware, retries and dead letters are core's. A handler that returns nil means "acknowledge"; an error means "do not acknowledge" (shutdown, or a crash), and the broker will deliver the message again.

type MessagingCapabilities

type MessagingCapabilities struct {
	Ordering, Keys, Headers, Transactions, RequestReply, Delay, ConsumerGroups bool
}

MessagingCapabilities says what a library can do. Core rejects an option the adapter cannot honour, with a clear error.

type MessagingOptions

type MessagingOptions struct {
	Adapter MessagingAdapter
	// Name is the transport's name in weft.yaml and in contexts, such as kafka. Default: the adapter's.
	Name   string
	Logger *slog.Logger
	// Sleep waits between attempts; for tests. Default: Sleep.
	Sleep func(ctx context.Context, d time.Duration)
	// Random is the source of jitter; for tests. Default: a random number in [0, 1).
	Random func() float64
}

MessagingOptions configures a Messaging.

type MessagingPolicy

type MessagingPolicy string

MessagingPolicy is what a messaging consumer does when a handler fails with a category.

const (
	PolicyNone                MessagingPolicy = "none"
	PolicyDeadLetter          MessagingPolicy = "dead-letter"
	PolicyRetry               MessagingPolicy = "retry"
	PolicyRetryThenDeadLetter MessagingPolicy = "retry-then-dead-letter"
)

type Middleware

type Middleware func(ctx context.Context, call *Call, next Next) error

Middleware wraps a handler. It continues by calling next once; not calling it stops the chain, and calling it twice is an error.

type Next

type Next func(ctx context.Context) error

Next continues to the next middleware, and finally to the handler.

type Options

type Options struct {
	Contracts *Contracts
	Config    *Config
	// ShutdownGrace is how long Stop waits for in-flight handlers. Default 30 s.
	ShutdownGrace time.Duration
}

Options configures a Weft.

type ParamDef

type ParamDef struct {
	Name     string  `json:"name"`
	Type     TypeRef `json:"type"`
	Optional bool    `json:"optional,omitempty"`
}

type Problem

type Problem struct {
	Type   string  `json:"type"`
	Title  string  `json:"title"`
	Status int     `json:"status"`
	Detail string  `json:"detail,omitempty"`
	Issues []Issue `json:"issues,omitempty"`
	// Fields are the fields of a declared error, in wire form.
	Fields any `json:"fields,omitempty"`
}

Problem is an RFC 9457 problem details body.

func ToProblem

func ToProblem(err error, route *RouteDef, c *Contracts) (status int, p Problem, unexpected error)

ToProblem turns anything a handler returned into the response it deserves. unexpected is set when this was not a clean, expected error: the server should log it.

type PublishOptions

type PublishOptions struct {
	// Key overrides the key taken from the event's key:.
	Key     string
	Headers map[string]string
	// IdempotencyKey sets weft-idempotency-key, which Dedupe uses on the receiving side.
	IdempotencyKey string
	// Delay delays delivery. Needs the Delay capability.
	Delay time.Duration
	// Package is for the case where two packages declare the same event name.
	Package string
	// Extra holds options of the adapter's own.
	Extra map[string]any
}

PublishOptions are the options of Publish.

type Published

type Published struct {
	Destination string
	Envelope    Envelope
	Options     map[string]any
}

Published is a message as the in-memory broker saw it.

type ResultDef

type ResultDef struct {
	Value    TypeRef    `json:"value"`
	Optional bool       `json:"optional,omitempty"`
	Stream   bool       `json:"stream,omitempty"`
	Errors   []ErrorRef `json:"errors,omitempty"`
}

type RouteDef

type RouteDef struct {
	Name       string     `json:"name"`
	Method     string     `json:"method"`
	Base       string     `json:"base,omitempty"`
	Path       string     `json:"path"`
	PathParams []ParamDef `json:"pathParams,omitempty"`
	Query      *TypeRef   `json:"query,omitempty"`
	Body       *TypeRef   `json:"body,omitempty"`
	Headers    *TypeRef   `json:"headers,omitempty"`
	Result     ResultDef  `json:"result"`
}

type Rule

type Rule struct {
	Rule   string `json:"rule"`
	Value  string `json:"value,omitempty"`  // min, max: a number as text
	Min    uint64 `json:"min,omitempty"`    // length
	Max    uint64 `json:"max,omitempty"`    // length
	Regex  string `json:"regex,omitempty"`  // pattern
	Format string `json:"format,omitempty"` // format
}

Rule is one validation rule on a field. Rule is "min", "max", "length", "pattern" or "format".

type ServiceClient

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

ServiceClient calls one other service: h.To("orders").Call(ctx, "POST", "/orders", opts).

func (*ServiceClient) Call

func (s *ServiceClient) Call(ctx context.Context, method, path string, o CallOptions) (any, error)

Call calls a route of the service.

func (*ServiceClient) Delete

func (s *ServiceClient) Delete(ctx context.Context, path string, o CallOptions) (any, error)

func (*ServiceClient) Get

func (s *ServiceClient) Get(ctx context.Context, path string, o CallOptions) (any, error)

func (*ServiceClient) Post

func (s *ServiceClient) Post(ctx context.Context, path string, o CallOptions) (any, error)

func (*ServiceClient) Put

func (s *ServiceClient) Put(ctx context.Context, path string, o CallOptions) (any, error)

type State

type State string

State is where a Weft is in its life.

const (
	Created  State = "created"
	Starting State = "starting"
	Running  State = "running"
	Stopping State = "stopping"
	Stopped  State = "stopped"
)

type StopResult

type StopResult struct {
	// Drained is false when the grace period ran out with handlers still running.
	Drained bool
	// Abandoned is how many handlers were still running then.
	Abandoned int
}

StopResult says how a Stop ended.

type SubscribeOptions

type SubscribeOptions struct {
	// Group is the consumer group. Needs the ConsumerGroups capability.
	Group         string
	FromBeginning bool
	// Attempts before the message is dead-lettered. Default 5.
	Attempts int
	// DeadLetter is where failed messages go. Default <destination>.dlq.
	DeadLetter string
	// NoDeadLetter drops failed messages instead (with a log line).
	NoDeadLetter bool
	Backoff      Backoff
	Package      string
	// Extra holds options of the adapter's own.
	Extra map[string]any
}

SubscribeOptions are the options of On.

type Transport

type Transport interface {
	Name() string
	// Start connects and begins listening. Called by Weft.Start.
	Start(ctx context.Context) error
	// StopIntake stops taking new work. In-flight work carries on.
	StopIntake(ctx context.Context) error
	// Close closes connections, after in-flight work has finished or the grace period has run out.
	Close(ctx context.Context) error
}

Transport is one way services talk (HTTP, Kafka, ...), run by an adapter on a real library.

type TypeDef

type TypeDef struct {
	Name     string       `json:"name"`
	Kind     string       `json:"kind"` // "record" or "enum"
	Params   []string     `json:"params,omitempty"`
	Inline   bool         `json:"inline,omitempty"`
	Fields   []FieldDef   `json:"fields,omitempty"`
	Variants []VariantDef `json:"variants,omitempty"`
}

TypeDef is a record (Fields) or an enum (Variants), told apart by Kind.

type TypeRef

type TypeRef struct {
	Kind    string    `json:"kind"`
	Name    string    `json:"name,omitempty"`    // primitive, named, param
	Package string    `json:"package,omitempty"` // named
	Args    []TypeRef `json:"args,omitempty"`    // named
	Item    *TypeRef  `json:"item,omitempty"`    // list
	Key     *TypeRef  `json:"key,omitempty"`     // map
	Value   *TypeRef  `json:"value,omitempty"`   // map
}

TypeRef refers to a type. Kind is "primitive", "named", "param", "list" or "map".

func List

func List(item TypeRef) TypeRef

List returns a reference to a list of item.

func Map

func Map(key, value TypeRef) TypeRef

Map returns a reference to a map from key to value.

func Named

func Named(pkg, name string, args ...TypeRef) TypeRef

Named returns a reference to a named type, with type arguments if it is generic.

func Primitive

func Primitive(name string) TypeRef

Primitive returns a reference to a primitive type: Primitive("int64").

type VariantDef

type VariantDef struct {
	Name string `json:"name"`
}

type Weft

type Weft struct {
	Contracts *Contracts
	Config    *Config
	// contains filtered or unexported fields
}

Weft is the lifecycle shared by every transport: register, Start, run handlers through the middleware, Stop. Adapters register themselves as transports and send every handler call through Dispatch.

func New

func New(o Options) *Weft

New makes a Weft.

func (*Weft) Dispatch

func (w *Weft) Dispatch(ctx context.Context, call *Call, handler Handler, extra ...Middleware) error

Dispatch runs handler for one call: the global middleware, then extra (the transport's own), then the handler, counted as in-flight work.

func (*Weft) Register

func (w *Weft) Register(t Transport) error

Register adds a transport. Only before Start.

func (*Weft) ShutdownContext

func (w *Weft) ShutdownContext() context.Context

ShutdownContext is cancelled when Stop gives up on handlers that did not finish in the grace period.

func (*Weft) Start

func (w *Weft) Start(ctx context.Context) error

Start connects every transport, in the order registered. If one fails, the ones already started are closed again and the error is Unavailable.

func (*Weft) State

func (w *Weft) State() State

State is where this Weft is in its life.

func (*Weft) Stop

func (w *Weft) Stop(ctx context.Context) StopResult

Stop stops taking new work, waits for in-flight handlers (up to the grace period), then closes every transport in reverse order. It is safe to call more than once. It does not fail for a handler that is still running: check the result.

func (*Weft) Track

func (w *Weft) Track(fn func() error) error

Track runs fn as in-flight work that Stop waits for. It is refused once stopping has begun.

func (*Weft) Use

func (w *Weft) Use(m Middleware)

Use adds middleware that runs for every transport, in the order added.

Directories

Path Synopsis
cmd
weft-conformance-runner command
Command weft-conformance-runner is the Go runner for the conformance harness.
Command weft-conformance-runner is the Go runner for the conformance harness.
http
nethttp
Package nethttp serves Weft's HTTP routes with the standard library's net/http.
Package nethttp serves Weft's HTTP routes with the standard library's net/http.
kafka
franz
Package franz is Weft's Kafka adapter on franz-go.
Package franz is Weft's Kafka adapter on franz-go.

Jump to

Keyboard shortcuts

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