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
- Variables
- func BackoffDelay(attempt int, b Backoff, random func() float64) time.Duration
- func CheckFormat(format, value string) bool
- func DeadlineAfter(d time.Duration, existing time.Time, now time.Time) time.Time
- func DeclaredFields[T any](c *Contracts, err error, pkg, name string) (T, bool)
- func Environ() map[string]string
- func ExtractTraceContext(ctx context.Context, headers map[string]string) context.Context
- func FindConfigFile(dir string) (string, bool)
- func FromProblem(status int, body map[string]any, c *Contracts) error
- func FullPath(r *RouteDef) string
- func InjectTraceContext(ctx context.Context, headers map[string]string)
- func OnTyped[T any](m *Messaging, event string, ...) error
- func ParseJSON(text []byte) (any, error)
- func PublishTyped[T any](ctx context.Context, m *Messaging, event string, payload T, o PublishOptions) error
- func RecordError(span trace.Span, err error)
- func Remaining(ctx context.Context, now time.Time) (time.Duration, bool)
- func Sleep(ctx context.Context, d time.Duration)
- func ToHeaders(e Envelope, prefix string) map[string]string
- func WithTimeout[T any](parent context.Context, d time.Duration, ...) (T, error)
- type AdapterConfigurer
- type AdapterReadier
- type Backoff
- type Call
- type CallOptions
- type Category
- type CategoryInfo
- type Config
- type ConfigError
- type Contracts
- func (c *Contracts) Decode(ref TypeRef, wire any) (any, error)
- func (c *Contracts) DecodeErrorFields(pkg, name string, wire any) (map[string]any, error)
- func (c *Contracts) DecodeJSON(ref TypeRef, text []byte) (any, error)
- func (c *Contracts) Encode(ref TypeRef, value any) (any, error)
- func (c *Contracts) EncodeErrorFields(pkg, name string, fields map[string]any) (map[string]any, error)
- func (c *Contracts) EncodeJSON(ref TypeRef, value any) ([]byte, error)
- func (c *Contracts) Event(name, pkg string) (*Ir, *EventDef, error)
- func (c *Contracts) FindRoute(method, path, pkg string) (*Ir, *RouteDef, error)
- func (c *Contracts) FromCode(ref TypeRef, code any, out any) error
- func (c *Contracts) Marshal(ref TypeRef, v any) (any, error)
- func (c *Contracts) NewDeclaredError(pkg, name string, fields any, message string) *DeclaredError
- func (c *Contracts) Package(name string) (*Ir, bool)
- func (c *Contracts) Route(name, pkg string) (*Ir, *RouteDef, error)
- func (c *Contracts) ToCode(ref TypeRef, v any) (any, error)
- func (c *Contracts) Unmarshal(ref TypeRef, wire any, out any) error
- func (c *Contracts) Validate(ref TypeRef, value any) []Issue
- type DeclaredError
- type Delivery
- type Envelope
- type Error
- type ErrorDef
- type ErrorRef
- type EventDef
- type FieldDef
- type HTTP
- func (h *HTTP) Close(ctx context.Context) error
- func (h *HTTP) Delete(path string, handler HTTPHandler) error
- func (h *HTTP) Get(path string, handler HTTPHandler) error
- func (h *HTTP) Handle(method, path string, handler HTTPHandler) error
- func (h *HTTP) HandleIn(pkg, method, path string, handler HTTPHandler) error
- func (h *HTTP) Name() string
- func (h *HTTP) NotFound(message string) error
- func (h *HTTP) Patch(path string, handler HTTPHandler) error
- func (h *HTTP) Post(path string, handler HTTPHandler) error
- func (h *HTTP) Put(path string, handler HTTPHandler) error
- func (h *HTTP) Raw() any
- func (h *HTTP) Start(ctx context.Context) error
- func (h *HTTP) StopIntake(ctx context.Context) error
- func (h *HTTP) To(service string) *ServiceClient
- func (h *HTTP) Use(m HTTPMiddleware)
- type HTTPAdapter
- type HTTPContext
- type HTTPHandler
- type HTTPInput
- type HTTPMiddleware
- type HTTPOptions
- type HTTPRequest
- type HTTPResponse
- type HTTPSettings
- type Handler
- type Ir
- type Issue
- type MemoryAdapter
- func (a *MemoryAdapter) Broker() *MemoryBroker
- func (a *MemoryAdapter) Capabilities() MessagingCapabilities
- func (a *MemoryAdapter) Close(context.Context) error
- func (a *MemoryAdapter) FailNextPublishes(n int)
- func (a *MemoryAdapter) Name() string
- func (a *MemoryAdapter) Publish(_ context.Context, destination string, e Envelope, options map[string]any) error
- func (a *MemoryAdapter) Raw() any
- func (a *MemoryAdapter) Start(context.Context) error
- func (a *MemoryAdapter) StopIntake(context.Context) error
- func (a *MemoryAdapter) Subscribe(_ context.Context, destination string, ...) error
- type MemoryBroker
- type MessageContext
- type MessageHandler
- type MessageMiddleware
- type Messaging
- func (m *Messaging) Close(ctx context.Context) error
- func (m *Messaging) Name() string
- func (m *Messaging) On(event string, handler MessageHandler, o SubscribeOptions) error
- func (m *Messaging) Publish(ctx context.Context, event string, payload any, o PublishOptions) error
- func (m *Messaging) Raw() any
- func (m *Messaging) Start(ctx context.Context) error
- func (m *Messaging) StopIntake(ctx context.Context) error
- func (m *Messaging) Use(mw MessageMiddleware)
- type MessagingAdapter
- type MessagingCapabilities
- type MessagingOptions
- type MessagingPolicy
- type Middleware
- type Next
- type Options
- type ParamDef
- type Problem
- type PublishOptions
- type Published
- type ResultDef
- type RouteDef
- type Rule
- type ServiceClient
- func (s *ServiceClient) Call(ctx context.Context, method, path string, o CallOptions) (any, error)
- func (s *ServiceClient) Delete(ctx context.Context, path string, o CallOptions) (any, error)
- func (s *ServiceClient) Get(ctx context.Context, path string, o CallOptions) (any, error)
- func (s *ServiceClient) Post(ctx context.Context, path string, o CallOptions) (any, error)
- func (s *ServiceClient) Put(ctx context.Context, path string, o CallOptions) (any, error)
- type State
- type StopResult
- type SubscribeOptions
- type Transport
- type TypeDef
- type TypeRef
- type VariantDef
- type Weft
- func (w *Weft) Dispatch(ctx context.Context, call *Call, handler Handler, extra ...Middleware) error
- func (w *Weft) Register(t Transport) error
- func (w *Weft) ShutdownContext() context.Context
- func (w *Weft) Start(ctx context.Context) error
- func (w *Weft) State() State
- func (w *Weft) Stop(ctx context.Context) StopResult
- func (w *Weft) Track(fn func() error) error
- func (w *Weft) Use(m Middleware)
Constants ¶
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).
const IdempotencyHeader = "weft-idempotency-key"
IdempotencyHeader carries the idempotency key of a message.
const ProblemTypePrefix = "urn:weft:error:"
ProblemTypePrefix starts the RFC 9457 type of a built-in category or a declared error.
const Version = "0.0.0"
Version is the version of this package. It is replaced by the release process.
Variables ¶
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 ¶
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 ¶
CheckFormat reports whether value is valid for the @format named format (spec/behaviour.md).
func DeadlineAfter ¶
DeadlineAfter is the earlier of "d from now" and an existing deadline.
func DeclaredFields ¶
DeclaredFields reads the fields of a declared error into T, if err is that error.
func ExtractTraceContext ¶
ExtractTraceContext returns ctx with the trace context carried in headers, to be the parent of a span.
func FindConfigFile ¶
FindConfigFile looks for weft.yaml in dir and then each folder above it.
func FromProblem ¶
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 InjectTraceContext ¶
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 ¶
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 ¶
RecordError marks a span as failed and records why.
func Remaining ¶
Remaining is the time until ctx's deadline, and false when it has none. Never negative.
func Sleep ¶
Sleep waits d, or less if ctx is cancelled. It returns either way; the caller checks ctx.
func ToHeaders ¶
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 ¶
AdapterConfigurer is implemented by adapters that read their settings from weft.yaml.
type AdapterReadier ¶
AdapterReadier is implemented by adapters that must know every subscription before they start consuming.
type Backoff ¶
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.
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).
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 ¶
LoadConfig reads weft.yaml from path, or when path is empty from the working folder or a folder above it.
func ParseConfig ¶
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 ¶
ServiceURL is the base URL of another service, from services:.
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 ¶
NewContracts reads the contracts of every package in irs.
func (*Contracts) Decode ¶
Decode turns a wire value into code form. When it is not valid the error is InvalidInput and lists every issue.
func (*Contracts) DecodeErrorFields ¶
DecodeErrorFields decodes the fields of a declared error from wire form.
func (*Contracts) DecodeJSON ¶
DecodeJSON decodes JSON text. Text that is not JSON is InvalidInput.
func (*Contracts) Encode ¶
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 ¶
EncodeJSON encodes a value and writes it as JSON.
func (*Contracts) FindRoute ¶
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 ¶
FromCode stores a code-form value in out, which must be a non-nil pointer.
func (*Contracts) Marshal ¶
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) ToCode ¶
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.
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.
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 ¶
AsError returns the *Error in err's chain, or wraps any other error as Internal. A nil error gives nil.
func (*Error) HTTPStatus ¶
HTTPStatus is the status of the category.
func (*Error) MessagingPolicy ¶
func (e *Error) MessagingPolicy() MessagingPolicy
MessagingPolicy is what a consumer does with this error.
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) 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) 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 ¶
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 ¶
HTTPResponse is what core wants written back.
type HTTPSettings ¶
HTTPSettings is implemented by adapters that read transports.http from weft.yaml.
type Handler ¶
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) 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) Raw ¶
func (a *MemoryAdapter) Raw() any
func (*MemoryAdapter) StopIntake ¶
func (a *MemoryAdapter) StopIntake(context.Context) 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 (*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) On ¶
func (m *Messaging) On(event string, handler MessageHandler, o SubscribeOptions) error
On receives an event. Register before Weft.Start.
func (*Messaging) Publish ¶
Publish validates, encodes and sends an event. It retries Unavailable and Timeout failures with backoff.
func (*Messaging) Raw ¶
Raw is the library underneath. Weft's tracing and middleware do not apply to calls made through it.
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 ¶
Middleware wraps a handler. It continues by calling next once; not calling it stops the chain, and calling it twice is an error.
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 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.
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 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 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".
type VariantDef ¶
type VariantDef struct {
Name string `json:"name"`
}
type Weft ¶
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 (*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) ShutdownContext ¶
ShutdownContext is cancelled when Stop gives up on handlers that did not finish in the grace period.
func (*Weft) Start ¶
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) 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 ¶
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.
Source Files
¶
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. |