backplane

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Oct 14, 2026 License: MIT Imports: 53 Imported by: 7

Documentation

Overview

Package backplane is the Go SDK. The author describes the service as one Config struct and one State built by an explicit constructor:

type Config struct {
    config.Backplane `json:"backplane"`
    Postgres pgx.Config `json:"postgres"`
}

type State struct {
    DB    deps.Dependency[*pgxpool.Pool]
    Users *users.Repo
}

func NewState(root backplane.Root[Config]) (*State, error) { ... }

svc, err := backplane.Open(ctx, NewState)
svc.GRPC(svc.State().Users.Register)
err = svc.Run(ctx)

Everything — the SDK's own parts and the author's tree — is one tree of nodes. Run starts it in order:

config → telemetry → health → platform → consul → nats → temporal → hooks →
author's tree → internal-api → reactors → worker →
public:<addr> → drain → register → serving

so components may publish events and call hooks from OnStart to OnStop. It stops in exact reverse within Shutdown.Timeout: readiness drops, the instance deregisters, after Shutdown.Drain the listeners and the internal API finish in-flight calls within one Shutdown.Listeners window (then streams are cut and internal calls cancelled), and at least Shutdown.Reserve is left for components, which stop before the dependencies they use. A second SIGINT/SIGTERM during the stop exits at once with status 1. A panicking handler fails its request (codes.Internal, HTTP 500), never the process. Consul, NATS, Temporal and the telemetry collector are optional. Install configured backends explicitly with drivers (for example standard.Drivers). RequireNATS or RequireTemporal make a configured connection part of readiness.

Index

Constants

View Source
const (
	AuditLabel = "backplane.audit"
	// AuditID deduplicates a record the Collector retries; without it the
	// record's content does.
	AuditID      = "backplane.audit.id"
	AuditActor   = "backplane.audit.actor"
	AuditSubject = "backplane.audit.subject"
	// AuditOutcome: succeeded, failed or rejected by convention.
	AuditOutcome = "backplane.audit.outcome"
)

Application audit (§14): a log record carrying AuditLabel=true is audit. The deployment's Collector forwards such records to backplane, which keeps them; the log itself goes wherever logs go. The rest of the keys are optional and filterable in the console's Audit; the action is the record's event.name, else its message.

Variables

View Source
var ErrClosed = errors.New("backplane: service already ran or was closed")

ErrClosed is returned by Run after Close or a previous Run.

View Source
var ErrConfig = errors.New("backplane: invalid configuration")

ErrConfig: the SDK block or the service name is unusable.

Functions

func Audit

func Audit() xlog.Field

Audit marks a log record as application audit:

log.Info("identity deleted", backplane.Audit(),
	xlog.String("event.name", "identity.deleted"),
	xlog.String(backplane.AuditSubject, "identity/"+id))

func CaptureError

func CaptureError(ctx context.Context, log *xlog.Logger, err error, fields ...xlog.Field)

CaptureError logs err as an OpenTelemetry exception record (its type, message and the caller's stack, and the context's trace), which the console's Errors section lists with its trace and related logs. It only logs: it neither stops nor retries anything, and returns nothing to check.

if err := charge(ctx); err != nil {
	backplane.CaptureError(ctx, c.Log(), err, xlog.String("order", id))
	return err
}

Types

type ConfigurationState

type ConfigurationState = configrt.State

ConfigurationState exposes masked configuration and live update notifications.

type Connection

type Connection interface {
	Connect(ctx context.Context, group TaskGroup) error
	Close(ctx context.Context) error
	Connected() bool
}

Connection is a transport managed by the service lifecycle.

type EventMessage

type EventMessage = env.Message

EventMessage is the transport-neutral event envelope.

type EventTransport

type EventTransport interface {
	Connection
	Publish(ctx context.Context, message EventMessage) error
	StartReactors(ctx context.Context, group TaskGroup) error
	StopReactors(ctx context.Context) error
}

EventTransport publishes events and serves declared consumers.

type EventTransportFactory

type EventTransportFactory func(config.Backplane, deps.Scope, Identity) EventTransport

EventTransportFactory builds one transport per service, without connecting.

type HookDiscovery added in v0.3.0

type HookDiscovery = direct.Discovery

HookDiscovery finds the platform addresses of backplane's replicas for the direct hook transport.

type HookDiscoveryFactory added in v0.3.0

type HookDiscoveryFactory func(cfg config.Backplane, log *xlog.Logger) (HookDiscovery, error)

HookDiscoveryFactory builds the discovery from the configuration.

type Identity

type Identity struct {
	Service     string
	Version     string
	Instance    string
	Advertise   string
	Environment string
}

Identity is how the instance names itself everywhere: logs, telemetry, Consul, the manifest.

type Info

type Info struct {
	Service     string `json:"service"`
	Version     string `json:"version"`
	Instance    string `json:"instance"`
	Advertise   string `json:"advertise"`
	Environment string `json:"environment,omitempty"`
	SDKVersion  string `json:"sdk_version"`
	GoVersion   string `json:"go_version"`
	Commit      string `json:"commit,omitempty"`
	BuildDate   string `json:"build_date,omitempty"`
}

Info is what /_backplane/info answers.

type Option

type Option func(*options)

Option configures Open.

func Advertise(addr string) Option

Advertise overrides the address registered in Consul.

func ConfigOptions

func ConfigOptions(opts ...config.Option) Option

ConfigOptions pass options to configuration loading.

func GRPCServerOptions

func GRPCServerOptions(opts ...grpc.ServerOption) Option

GRPCServerOptions are passed to every public gRPC server after the SDK's own (telemetry, limits of config.Server, panic recovery): a later limit overrides the SDK's; interceptors run inside recovery and outside those of api.Interceptors. The platform port is not affected.

func Instance

func Instance(id string) Option

Instance overrides the instance id (default: the block's instance, then <service>-<hostname>).

func KeepSlog

func KeepSlog() Option

KeepSlog leaves the log/slog default alone. By default Run routes it into the service logger (the OTel SDK and other libraries log through it) and restores it when Run returns.

func Logger

func Logger(l *xlog.Logger) Option

Logger replaces the default logger.

func Name

func Name(n string) Option

Name overrides build.Service.

func Options

func Options(opts ...Option) Option

Options composes explicit driver options without global registration.

func RequireNATS

func RequireNATS() Option

RequireNATS makes the NATS connection part of readiness: the instance is not ready while it is down. Without NATS configured, Open fails.

func RequireTemporal

func RequireTemporal() Option

RequireTemporal makes the Temporal connection part of readiness: the instance is not ready while it is down. Without Temporal configured, Open fails.

func Version

func Version(v string) Option

Version overrides build.Version.

func WithEventTransport

func WithEventTransport(factory EventTransportFactory) Option

WithEventTransport installs an event driver explicitly at the composition root.

func WithHookDiscovery added in v0.3.0

func WithHookDiscovery(factory HookDiscoveryFactory) Option

WithHookDiscovery installs how the direct hook transport finds backplane (the Consul driver installs one over the catalog's instance states).

func WithPresence

func WithPresence(factory PresenceFactory) Option

WithPresence installs the discovery driver used by the service lifecycle.

func WithWorkflowTransport

func WithWorkflowTransport(factory WorkflowTransportFactory) Option

WithWorkflowTransport installs a workflow driver explicitly at the composition root.

type Presence

type Presence interface {
	Start(ctx context.Context, group TaskGroup) error
	Stop(ctx context.Context) error
	Register(ctx context.Context) error
	Deregister(ctx context.Context) error
}

Presence publishes instance state and manages catalog registration.

type PresenceFactory

type PresenceFactory func(PresenceParams) (Presence, error)

PresenceFactory builds a discovery session without starting it.

type PresenceParams

type PresenceParams struct {
	Config        config.Backplane
	Identity      Identity
	Manifest      *backplanev1.Manifest
	Log           *xlog.Logger
	Configuration ConfigurationState
	PlatformPort  uint16
	PrimaryPort   uint16
	Commit        string
	Transports    func() []*backplanev1.TransportStatus
	Nodes         func() []*backplanev1.NodeStatus
}

PresenceParams provides a discovery driver with the service's sealed contract.

type Root

type Root[C any] struct {
	deps.Component
	// contains filtered or unexported fields
}

Root is the root of the author's tree, handed to the State constructor: create components and dependencies under it, read the configuration from it. Embedding it in State is optional.

func (Root[C]) Config

func (r Root[C]) Config() C

Config is a copy of the loaded configuration. Static fields never change; config.Live fields are shared by every copy and update in place.

func (Root[C]) Identity

func (r Root[C]) Identity() Identity

Identity of the instance.

type Service

type Service[St any] struct {
	// contains filtered or unexported fields
}

Service is one process on the SDK: the author's State plus what it serves.

func Open

func Open[C config.Backplaner, St any](
	ctx context.Context, newState func(root Root[C]) (*St, error), opts ...Option,
) (*Service[St], error)

Open loads the configuration, builds the State with newState and returns a service ready to declare routes and Run. Nothing listens until Run.

ctx bounds loading only (a required Live value may wait for Consul); the service does not depend on it afterwards. An invalid configuration or a failing constructor is an error; an absent Consul is not. Call Close if Run will not be called.

func (Service) API

func (c Service) API(d api.Decl)

API describes an API the author serves on their own listener.

func (Service) Close

func (c Service) Close() error

Close releases what Open acquired when Run will not be called. Safe to call more than once; Run closes by itself.

func (Service) GRPC

func (c Service) GRPC(register func(r grpc.ServiceRegistrar), opts ...api.GRPCOption)

GRPC serves gRPC services on a public port: one route per registered service, descriptors derived from the registration. Registering the same service twice on one port is a Run error; so is grpc.health.v1, which every public gRPC server serves already. api.Interceptors and api.StreamInterceptors wrap this registration's services only.

func (Service) GraphQL

func (c Service) GraphQL(prefix string, h http.Handler, introspection []byte, opts ...api.HTTPOption)

GraphQL serves the author's GraphQL handler under prefix on a public port, announced with its introspection result (JSON; nil when none).

func (Service) HTTP

func (c Service) HTTP(prefix string, h http.Handler, opts ...api.HTTPOption)

HTTP serves h under prefix on a public port. The prefix is normalized to end with "/" ("/api" serves "/api/..."); with api.Host it matches that host only, so one prefix may serve several hosts. The same host and prefix twice on one port is a Run error.

func (Service) Identity

func (c Service) Identity() Identity

Identity of the instance.

func (Service) Internal

func (c Service) Internal(register func(r grpc.ServiceRegistrar))

Internal registers the internal API: gRPC on the platform port for the service's own console plugin, behind the internal secret, served only while the author's tree is up. Services must live in the proto package <service>.console.v1.

func (Service) LivenessProbe

func (c Service) LivenessProbe(p probe.Probe)

LivenessProbe adds a liveness probe. Keep dependencies out of it: a dead database is no reason to restart the process.

func (Service) Log

func (c Service) Log() *xlog.Logger

Log is the service logger; context-aware calls carry trace and span ids.

func (Service) Name

func (c Service) Name() string

Name of the service.

func (Service) ReadinessProbe

func (c Service) ReadinessProbe(p probe.Probe)

ReadinessProbe adds a readiness probe; readiness drives grpc.health.v1 and so the Consul check. Required dependencies are readiness probes already.

func (Service) Run

func (c Service) Run(ctx context.Context) error

Run brings the service up and blocks until ctx ends, SIGINT/SIGTERM arrives or a node's goroutine fails; then stops everything within the shutdown budget. A stop requested during start is not an error. A signal during the stop exits the process at once with status 1.

func (Service) StartupProbe

func (c Service) StartupProbe(p probe.Probe)

StartupProbe adds a startup probe.

func (*Service[St]) State

func (s *Service[St]) State() *St

State is what the constructor built.

func (Service) TelemetrySources

func (c Service) TelemetrySources(selectors ...map[string]string)

TelemetrySources declares optional view presets using exact OTel resource attribute matches. Selectors are OR alternatives; each map's entries are AND. Calling with no selectors explicitly disables presets. Not calling retains convention matching by service.name. No admission/visibility rules are created.

func (Service) UI

func (c Service) UI(bundle fs.FS)

UI declares the console plugin bundle, served at /_backplane/ui/ behind the internal secret. Files are snapshotted at declaration; subsequent changes to the source filesystem do not change the bundle or its hash. Every file carries ETag = ui.hash and Cache-Control: no-cache on the internal listener.

type TaskGroup

type TaskGroup = node.Group

TaskGroup runs background tasks within a service lifecycle node.

type WorkflowTransport

type WorkflowTransport interface {
	Connection
	Call(ctx context.Context, hook string, payload []byte) ([]byte, error)
	StartHookWorker(ctx context.Context, group TaskGroup) error
	StopHookWorker(ctx context.Context) error
	StartWorker(ctx context.Context, group TaskGroup) error
	StopWorker(ctx context.Context) error
}

WorkflowTransport carries hooks and serves the service's declared activities and workflows. Native workflow APIs belong to the selected driver.

type WorkflowTransportFactory

type WorkflowTransportFactory func(config.Backplane, deps.Scope, Identity) WorkflowTransport

WorkflowTransportFactory builds one transport per service, without connecting.

Directories

Path Synopsis
Package activity declares operations a service implements ("умею"): the targets of bindings and rules.
Package activity declares operations a service implements ("умею"): the targets of bindings and rules.
Package api describes the APIs a service serves, independently of deployment.
Package api describes the APIs a service serves, independently of deployment.
Package backplanetest runs components without Open, Run, ports or Consul: build them under Root, Start, and inspect what they published, answer their hooks, invoke their activities and reactors, and check their readiness.
Package backplanetest runs components without Open, Run, ports or Consul: build them under Root, Start, and inspect what they published, answer their hooks, invoke their activities and reactors, and check their readiness.
Package build carries what the deployment stamps into the binary at link time.
Package build carries what the deployment stamps into the binary at link time.
Package config loads a service's configuration: one struct, schema from the Go type (schemapb), layers merged by xconf:
Package config loads a service's configuration: one struct, schema from the Go type (schemapb), layers merged by xconf:
Package deps is how a service is composed: a tree of components, dependencies and singletons built explicitly by the author's constructor.
Package deps is how a service is composed: a tree of components, dependencies and singletons built explicitly by the author's constructor.
drivers
consul
Package consul installs optional discovery and live configuration.
Package consul installs optional discovery and live configuration.
nats
Package nats installs the optional nats transport.
Package nats installs the optional nats transport.
standard
Package standard composes the standard platform drivers.
Package standard composes the standard platform drivers.
temporal
Package temporal installs the optional temporal transport.
Package temporal installs the optional temporal transport.
Package event declares the events a service publishes and the reactors it runs.
Package event declares the events a service publishes and the reactors it runs.
Package hook declares operations a service calls without implementing them ("нужно").
Package hook declares operations a service calls without implementing them ("нужно").
infra
nats
Package nats is a NATS connection as a dependency: a configuration section, a connection that never gives up (reconnecting with jitter, no buffering while disconnected, transitions logged), a status probe.
Package nats is a NATS connection as a dependency: a configuration section, a connection that never gives up (reconnecting with jitter, no buffering while disconnected, transitions logged), a status probe.
postgres
Package postgres is a PostgreSQL connection as a dependency: a configuration section, a pgx pool traced and measured through the service's OpenTelemetry providers, a query log, pgtx transactions, an optional schema and sqld migrations applied at start, a ping probe.
Package postgres is a PostgreSQL connection as a dependency: a configuration section, a pgx pool traced and measured through the service's OpenTelemetry providers, a query log, pgtx transactions, an optional schema and sqld migrations applied at start, a ping probe.
temporal
Package temporal is a Temporal client as a dependency: a configuration section, a client traced and measured through the service's OpenTelemetry providers and logging through its logger, a health probe.
Package temporal is a Temporal client as a dependency: a configuration section, a client traced and measured through the service's OpenTelemetry providers and logging through its logger, a health probe.
valkey
Package valkey is a Valkey (Redis protocol) connection as a dependency: a configuration section, a client instrumented with the service's OpenTelemetry providers, a PING probe and a close.
Package valkey is a Valkey (Redis protocol) connection as a dependency: a configuration section, a client instrumented with the service's OpenTelemetry providers, a PING probe and a close.
internal
apifiles
Package apifiles snapshots API files for content-addressed delivery.
Package apifiles snapshots API files for content-addressed delivery.
backoff
Package backoff is the SDK's retry policy as a value: bounds the author can set, run by github.com/cenkalti/backoff (exponential, jittered, so instances recovering from one outage do not retry in lockstep).
Package backoff is the SDK's retry policy as a value: bounds the author can set, run by github.com/cenkalti/backoff (exponential, jittered, so instances recovering from one outage do not retry in lockstep).
broker
Package broker carries events over NATS JetStream (design §8).
Package broker carries events over NATS JetStream (design §8).
configrt
Package configrt is what the SDK core needs from a live configuration and authors do not: the effective values for instance state, schema walks for the manifest and provenance.
Package configrt is what the SDK core needs from a live configuration and authors do not: the effective values for instance state, schema walks for the manifest and provenance.
consul
Package consul keeps a service present in Consul: manifest per version, instance state under a TTL session (it disappears with the instance) and the catalog registration.
Package consul keeps a service present in Consul: manifest per version, instance state under a TTL session (it disappears with the instance) and the catalog registration.
decl
Package decl is shared by the hook, activity and event packages: it resolves the service a Scope belongs to, derives payload schemas and encodes payloads.
Package decl is shared by the hook, activity and event packages: it resolves the service a Scope belongs to, derives payload schemas and encodes payloads.
direct
Package direct is the SDK's side of backplane's direct runtime: the ActivityService that lets backplane run the service's activities over gRPC on the platform port, and the hook Caller that reaches backplane's HookService the same way.
Package direct is the SDK's side of backplane's direct runtime: the ActivityService that lets backplane run the service's activities over gRPC on the platform port, and the hook Caller that reaches backplane's HookService the same way.
env
Package env is what every node of one service shares: the manifest being declared into and the wiring of events, hooks and activities to a transport.
Package env is what every node of one service shares: the manifest being declared into and the wiring of events, hooks and activities to a transport.
exception
Package exception writes errors and panics as OpenTelemetry exception log records: exception.type, exception.message, exception.stacktrace and event.name=exception.
Package exception writes errors and panics as OpenTelemetry exception log records: exception.type, exception.message, exception.stacktrace and event.name=exception.
gate
Package gate admits internal API calls only while the author's tree is up: before it started they get Unavailable, and stopping waits for the calls in flight before the tree (and its dependencies) stops.
Package gate admits internal API calls only while the author's tree is up: before it started they get Unavailable, and stopping waits for the calls in flight before the tree (and its dependencies) stops.
guard
Package guard protects the platform port with the installation's internal secret: the console relay presents it, the SDK checks it.
Package guard protects the platform port with the installation's internal secret: the console relay presents it, the SDK checks it.
health
Package health is the single source of a service's health: probes are registered by kind, their composite status is cached in xprobe states, and grpc.health.v1, the HTTP probe endpoints and the Consul check all read the same states.
Package health is the single source of a service's health: probes are registered by kind, their composite status is cached in xprobe states, and grpc.health.v1, the HTTP probe endpoints and the Consul check all read the same states.
link
Package link lets SDK packages reach what public types keep private: the node behind a deps.Scope.
Package link lets SDK packages reach what public types keep private: the node behind a deps.Scope.
listener
Package listener serves gRPC and HTTP on one address through cmux.
Package listener serves gRPC and HTTP on one address through cmux.
manifest
Package manifest collects a service's declarations into a backplanev1.Manifest.
Package manifest collects a service's declarations into a backplanev1.Manifest.
metrics
Package metrics is the SDK's own instrumentation, on meter github.com/backplane-labs/backplane.
Package metrics is the SDK's own instrumentation, on meter github.com/backplane-labs/backplane.
node
Package node is the service's one lifecycle model: a tree of nodes, each with a name, a logger, an instrumentation scope, start and stop hooks, its own goroutines and an optional readiness probe.
Package node is the service's one lifecycle model: a tree of nodes, each with a name, a logger, an instrumentation scope, start and stop hooks, its own goroutines and an optional readiness probe.
recovery
Package recovery turns a panic in a request handler into an error for that request instead of a crashed process: gRPC and ws-proto calls get codes.Internal, HTTP requests 500.
Package recovery turns a panic in a request handler into an error for that request instead of a crashed process: gRPC and ws-proto calls get codes.Internal, HTTP requests 500.
routes
Package routes holds what route options configure, for the SDK core.
Package routes holds what route options configure, for the SDK core.
telemetry
Package telemetry installs OpenTelemetry through xtrace's SDK bootstrap: resource from the build identity, exporters from the standard OTEL_* environment.
Package telemetry installs OpenTelemetry through xtrace's SDK bootstrap: resource from the build identity, exporters from the standard OTEL_* environment.
temporal
Package temporal runs the service's activities and hook calls on Temporal (design §7.2, §9).
Package temporal runs the service's activities and hook calls on Temporal (design §7.2, §9).
temporal/temporaltest
Package temporaltest runs the SDK's Temporal tests against a dev server (BACKPLANE_TEST_TEMPORAL, e.g.
Package temporaltest runs the SDK's Temporal tests against a dev server (BACKPLANE_TEST_TEMPORAL, e.g.
testlog
Package testlog provides loggers for tests.
Package testlog provides loggers for tests.
Package workflows gives a service its own Temporal workflows (design §9): the SDK owns the connection and the worker on the service's task queue (= its name); the author registers on it and uses the client.
Package workflows gives a service its own Temporal workflows (design §9): the SDK owns the connection and the worker on the service's task queue (= its name); the author registers on it and uses the client.
Package wsproto serves gRPC services over ws-proto (protobuf RPC over WebSocket) as a managed public api.
Package wsproto serves gRPC services over ws-proto (protobuf RPC over WebSocket) as a managed public api.

Jump to

Keyboard shortcuts

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