transport

package
v0.12.2 Latest Latest
Warning

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

Go to latest
Published: Oct 8, 2026 License: MIT Imports: 13 Imported by: 0

Documentation

Overview

Package transport owns the Discord connection for the life of a generation and nothing else for the life of the process (0018 D8).

One controls.Generational per client holds the platform Client, every comms.Scope over it, and the goroutines that read them. Everything that is not a platform handle — the responder, the store, the thread set — lives outside and borrows through a lease. This package is the only one in the repository that imports comms.Client.

Index

Constants

View Source
const (
	// DefaultStartTimeout bounds Build plus connect. Without a bound, Start
	// blocks on a live predecessor until its context ends.
	DefaultStartTimeout = 30 * time.Second

	// DefaultStopTimeout bounds Stop, and is also the controller's shutdown
	// timeout so there is one budget rather than two that can disagree.
	DefaultStopTimeout = 5 * time.Second

	// DefaultPostTimeout bounds one post through the lease. A Discord REST
	// call is tens of milliseconds; this is a generous ceiling for a slow one,
	// and it must fit inside the stop timeout.
	DefaultPostTimeout = 3 * time.Second

	// DefaultSwapWait is how long a post waits for the next generation. A
	// stop that waits on a post, the initial backoff and a build-and-connect
	// come to close to ten seconds; this covers the first restart only.
	DefaultSwapWait = 15 * time.Second

	// DefaultHandlerTimeout bounds one handler call from the pump.
	DefaultHandlerTimeout = 5 * time.Second

	// DefaultHealthInterval and DefaultHealthThreshold declare death at 60s,
	// longer than Discord's 41.25s heartbeat: the gateway library reconnects
	// itself on a missed heartbeat, and a shorter threshold fights it.
	DefaultHealthInterval  = 15 * time.Second
	DefaultHealthThreshold = 4

	// DefaultMaxRestarts and the backoffs are what serve set before this
	// package existed.
	DefaultMaxRestarts    = 10
	DefaultInitialBackoff = 2 * time.Second
	DefaultMaxBackoff     = 5 * time.Minute

	// DefaultResetInterval is how long a run must last before the restart
	// counter resets. Controls' own default is 30s, which is shorter than a
	// health death (60s) or a hung connect (30s), so at that value exhaustion
	// is unreachable on both paths; five minutes exceeds the longest failed
	// run with margin.
	DefaultResetInterval = 5 * time.Minute
)

Defaults, every one a config key (0018 D8f).

Variables

View Source
var (
	// ErrNonPositive is returned for a duration or count that must be
	// positive. Controls treats a non-positive health threshold as "do not
	// monitor" and a non-positive restart maximum as "unlimited", either of
	// which silently reverses the supervision this configuration exists to set.
	ErrNonPositive = errors.NewSentinel("transport.non_positive",
		"transport: value must be positive")

	// ErrPostExceedsStop is returned when a post may outlive a stop. A post
	// holds a lease, and Stop waits for leases only until its budget.
	ErrPostExceedsStop = errors.NewSentinel("transport.post_exceeds_stop",
		"transport: post_timeout must not exceed stop_timeout")

	// ErrBackoffOrder is returned when the initial backoff exceeds the maximum.
	ErrBackoffOrder = errors.NewSentinel("transport.backoff_order",
		"transport: restart.initial_backoff must not exceed restart.max_backoff")

	// ErrResetTooShort is returned when the restart counter would reset before
	// a failed run could finish, which makes exhaustion unreachable: controls
	// resets the counter after any run at least this long, healthy or not.
	ErrResetTooShort = errors.NewSentinel("transport.reset_too_short",
		"transport: restart.reset_interval must exceed the longest failed run "+
			"(start_timeout + health.interval × health.threshold + stop_timeout)")
)

Configuration errors.

View Source
var (
	// ErrUnknownSpace is returned by Poster for a space the transport was not
	// configured with. A wiring error at construction, not a runtime miss.
	ErrUnknownSpace = errors.NewSentinel("transport.unknown_space",
		"transport: no such space is configured")

	// ErrNoGeneration is returned by a post that found no active generation
	// inside swap_wait. The caller records the answer unposted; it is not
	// retried for ever and it is not dropped silently (0018 D8b).
	ErrNoGeneration = errors.NewSentinel("transport.no_generation",
		"transport: no generation became active inside swap_wait")
)

Poster errors.

View Source
var (
	// ErrNotReady is reported by readiness while no generation is active:
	// before the first start, between generations, and during a connect.
	ErrNotReady = errors.NewSentinel("transport.not_ready", "transport: no active generation")

	// ErrNotConnected is reported when a reader is not currently delivering.
	ErrNotConnected = errors.NewSentinel("transport.not_connected", "transport: gateway not connected")

	// ErrPumpStopped is reported when a pump has exited while its generation
	// lives, which only a closed channel can cause.
	ErrPumpStopped = errors.NewSentinel("transport.pump_stopped", "transport: a message pump has stopped")

	// ErrHandlerStalled is reported by readiness when a handler has ignored its
	// deadline. Never by Status: a transport restart cannot cure a
	// process-scoped handler (0018 D8d).
	ErrHandlerStalled = errors.NewSentinel("transport.handler_stalled",
		"transport: a handler has been running past its timeout")

	// ErrTerminal is reported by liveness once the supervisor has given up.
	ErrTerminal = errors.NewSentinel("transport.terminal", "transport: restarts exhausted")

	// ErrNoReactions is returned when a reaction handler is set and a provider
	// cannot deliver reactions (spec 0027 D1).
	ErrNoReactions = errors.NewSentinel("transport.no_reactions", "transport: the provider cannot deliver reactions")

	// ErrNoGuilds is returned when a transport is built for no space.
	ErrNoGuilds = errors.NewSentinel("transport.no_guilds", "transport: no guild to serve")

	// ErrNoHandler is returned when a transport is built with nothing to hand
	// messages to.
	ErrNoHandler = errors.NewSentinel("transport.no_handler", "transport: no handler")
)

Probe errors.

Functions

func DiscordClient

func DiscordClient(_ context.Context, cfg comms.ClientConfig) (comms.Client, error)

DiscordClient builds the client registered under "discord".

Looked up by name rather than imported, so this package depends on the contract alone — the blank import that registers a provider lives in the command.

func ResolveCredential

func ResolveCredential(ctx context.Context, auth ingest.AuthConfig) (string, error)

ResolveCredential resolves the configured credential through the shared credentials module.

No bare os.Getenv: the mode is what the operator chose, and the rules about which modes are permissible where live in one place rather than being restated by every consumer (R-OPS-6).

Types

type ClientFunc

type ClientFunc func(ctx context.Context, cfg comms.ClientConfig) (comms.Client, error)

ClientFunc builds a platform client from a connection config. It exists so the transport can be driven by a fake in tests without a package-level variable, which would race under t.Parallel().

A Client owns the connection, which is why this seam returns one rather than a provider: something has to close it, and a provider-shaped seam would leave the connection with no owner.

type Config

type Config struct {
	StartTimeout   time.Duration `mapstructure:"start_timeout" yaml:"start_timeout" json:"start_timeout"`
	StopTimeout    time.Duration `mapstructure:"stop_timeout" yaml:"stop_timeout" json:"stop_timeout"`
	PostTimeout    time.Duration `mapstructure:"post_timeout" yaml:"post_timeout" json:"post_timeout"`
	SwapWait       time.Duration `mapstructure:"swap_wait" yaml:"swap_wait" json:"swap_wait"`
	HandlerTimeout time.Duration `mapstructure:"handler_timeout" yaml:"handler_timeout" json:"handler_timeout"`
	Health         HealthConfig  `mapstructure:"health" yaml:"health" json:"health"`
	Restart        RestartConfig `mapstructure:"restart" yaml:"restart" json:"restart"`

	// Auth is the bot's credential, discord.auth. Set from the resolved
	// configuration rather than decoded here (spec 0029 D2).
	Auth ingest.AuthConfig `mapstructure:"-" yaml:"-" json:"-"`
}

Config is the transport's supervision configuration, under `discord`.

func (Config) RestartPolicy

func (c Config) RestartPolicy() controls.RestartPolicy

RestartPolicy is the controls policy this configuration describes.

Retrying belongs here, in the supervisor, rather than inside the service — a service that retries silently hides its own failure from the thing meant to be watching it. And a gateway that cannot connect will not connect harder for being asked more often: Discord rate-limits identify.

func (Config) Validate

func (c Config) Validate() error

Validate refuses a configuration whose supervision would not behave as written.

func (Config) WithDefaults

func (c Config) WithDefaults() Config

WithDefaults returns a copy with every zero value replaced by its default, leaving anything the operator set alone.

type Counters

type Counters struct {
	// HandlerTimeouts counts handler calls that ran past their deadline,
	// across every generation.
	HandlerTimeouts int64
	// HandlerPanics counts handler calls that panicked and were recovered.
	HandlerPanics int64
	// PumpsDraining counts pumps from retired generations still finishing
	// their tail. It, not MaxRestarts, bounds their number over a process
	// lifetime.
	PumpsDraining int64
	// ReleasesWedged counts stops whose release outlived the stop budget.
	ReleasesWedged int64
	// ReconnectLosses counts resumes that re-identified and therefore dropped
	// the events buffered during the gap, across every generation.
	ReconnectLosses int64
	// Ingested and Rejected count messages accepted from, and discarded for
	// being outside, the allowlist, across every generation. Rejected carries
	// no labels by design.
	Ingested int64
	Rejected int64
}

Counters are the transport's own instruments, as plain atomics; 0020 wires them to whichever plane it chooses.

type CredentialFunc

type CredentialFunc func(ctx context.Context, auth ingest.AuthConfig) (string, error)

CredentialFunc resolves a configured credential to a secret.

type HealthConfig

type HealthConfig struct {
	Interval  time.Duration `mapstructure:"interval" yaml:"interval" json:"interval"`
	Threshold int           `mapstructure:"threshold" yaml:"threshold" json:"threshold"`
}

HealthConfig is the health-driven restart policy.

type Lifecycle

type Lifecycle interface {
	Start(ctx context.Context) error
	Use(fn func(*Runtime) error) error
	Stop(ctx context.Context) error
}

Lifecycle is the three Generational methods the start wrapper and the Poster call, as an interface so a test can substitute a counting fake.

type Option

type Option func(*Transport)

Option configures a Transport.

func WithClient

func WithClient(fn ClientFunc) Option

WithClient overrides how the platform client is built.

func WithClock

func WithClock(now func() time.Time) Option

WithClock overrides the clock the pumps measure hand-overs with.

func WithCredential

func WithCredential(fn CredentialFunc) Option

WithCredential overrides how the token reference is resolved.

func WithLifecycle

func WithLifecycle(l Lifecycle) Option

WithLifecycle substitutes the Generational the wrappers drive. Tests only.

func WithLogger

func WithLogger(l *slog.Logger) Option

WithLogger sets the logger.

func WithReactionHandler added in v0.9.0

func WithReactionHandler(h ReactionHandler) Option

WithReactionHandler asks the platform for reactions and forwards them to h.

func WithStateInterval

func WithStateInterval(d time.Duration) Option

WithStateInterval sets how often each watcher polls for a lossy reconnect.

type Poster

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

Poster is respond's write path back to one space (0018 D8b).

It never holds an Actor. Every method is one lease around the corresponding Actor method on the current generation's scope, so a stale actor is impossible rather than unlikely: the Discord actor does not fail closed after Close, and a raw Actor that outlived its generation would look healthy and not be. Under the lease the only path to an Actor checks the generation is open first, and a retired one is unreachable.

func (*Poster) React

func (p *Poster) React(ctx context.Context, to comms.Ref, emoji string) error

React reacts through the live generation.

func (*Poster) ReplyInThread

func (p *Poster) ReplyInThread(
	ctx context.Context, to comms.Ref, threadName, content string,
) (comms.Ref, error)

ReplyInThread posts through the live generation.

type ReactionHandler added in v0.9.0

type ReactionHandler func(ctx context.Context, space comms.ID, r comms.Reaction)

ReactionHandler receives each reaction change in a space.

type RestartConfig

type RestartConfig struct {
	Max            int           `mapstructure:"max" yaml:"max" json:"max"`
	InitialBackoff time.Duration `mapstructure:"initial_backoff" yaml:"initial_backoff" json:"initial_backoff"`
	MaxBackoff     time.Duration `mapstructure:"max_backoff" yaml:"max_backoff" json:"max_backoff"`
	ResetInterval  time.Duration `mapstructure:"reset_interval" yaml:"reset_interval" json:"reset_interval"`
}

RestartConfig is the restart allowance and its backoff.

type Runtime

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

Runtime is one generation of the transport: the client, every scope over it, and the goroutines that read them. Built whole by Build, retired whole by Release, exactly one live at a time (0018 D8a).

Exported only so the Lifecycle seam can name it; every field is private.

func (*Runtime) Active

func (rt *Runtime) Active() bool

Active reports whether the start wrapper has finished connecting and starting the pumps.

func (*Runtime) Inflight

func (rt *Runtime) Inflight() int

Inflight reports the posts currently admitted.

type Transport

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

Transport supervises one client for the life of the process, one generation at a time.

func New

func New(cfg Config, guilds []ingest.GuildConfig, h ingest.Handler, opts ...Option) (*Transport, error)

New builds a transport for the configured guilds. It connects nothing.

func (*Transport) Counters

func (t *Transport) Counters() Counters

Counters reports the transport's instruments, across every generation.

func (*Transport) Generation

func (t *Transport) Generation() uint64

Generation reports the live generation's number, zero when none.

func (*Transport) Live

func (t *Transport) Live() error

Live reports whether the supervisor has given up. It is nil with no generation and through a backoff, so an orchestrator's liveness check cannot pre-empt the restart policy.

func (*Transport) MarkTerminal

func (t *Transport) MarkTerminal()

MarkTerminal records that the supervisor has exhausted its restarts. Set by the command that observes it, before the controller is stopped.

func (*Transport) Poster

func (t *Transport) Poster(space comms.ID) (*Poster, error)

Poster returns the write path for a configured space.

func (*Transport) Ready

func (t *Transport) Ready() error

Ready reports whether the transport is delivering: an active generation, every pump running, every reader connected, and no handler stalled.

Reconnect loss is not a readiness failure: a resumed session that lost events is usable, and restarting it would bring nothing back. It is polled here so a loss during a quiet spell is still counted.

func (*Transport) Reload

func (t *Transport) Reload(cfg ingest.Config)

Reload applies a changed configuration's exclusions to the live pumps. Identity is not applied: a changed credential, space or post_answers is warned about by field (R-OPS-5a).

func (*Transport) Start

func (t *Transport) Start(ctx context.Context) error

Start is the controls start function: a bounded Start, then one lease to connect and pump under the installed generation (0018 D8f).

func (*Transport) Status

func (t *Transport) Status() error

Status is the health probe controls restarts on.

func (*Transport) Stop

func (t *Transport) Stop(ctx context.Context) error

Stop is the controls stop function, bounded by the stop timeout whichever context the controller supplies: a health-driven restart passes its lifetime context.

func (*Transport) Use

func (t *Transport) Use(fn func(*Runtime) error) error

Use leases the live runtime.

Jump to

Keyboard shortcuts

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