dispatch

package
v0.0.0-...-31ecaa2 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2026 License: GPL-3.0, GPL-3.0 Imports: 14 Imported by: 0

Documentation

Overview

Package dispatch sends queued events and decides what to do when a send fails.

It is the outbound half of what the admission gate does inbound, and it owns one rule that is easy to get wrong: a retry sends the message that was already sealed, not a newly sealed one. Sealing again for every network retry would consume a message key per attempt, and a ratchet that advances once per lost packet is a ratchet that runs away from the peer.

Nothing here chooses a route. The transport is frozen only after the reachability study, so a Sender is supplied and this package never learns how the bytes travel.

Index

Constants

View Source
const DefaultAttemptLease = 2 * time.Minute

DefaultAttemptLease is how long one sweep holds a delivery by default.

Variables

View Source
var ErrNoTransport = errors.New("no transport is configured")

ErrNoTransport reports a dispatcher that can queue but not send.

Functions

This section is empty.

Types

type AttachmentRequest

type AttachmentRequest struct {
	ConversationID, RoomID, ReplyToEventID string
	IdempotencyKey, IntentDigest           string
	SessionID, RecipientEndpointID         string
	ExpiresAtUnix                          uint64
	Attachment                             payload.EncryptedAttachment
}

AttachmentRequest is assembled only by the daemon-owned attachment emitter after it has encrypted the complete plaintext and obtained exact Endpoint-signed storage grants. An Agent runtime never supplies Reference, capability, locator, sender, network, clock, kind, or Event ID fields.

type BindingResolver

type BindingResolver interface {
	BindingFor(eventlog.Delivery) (e2ee.Binding, error)
}

BindingResolver supplies the associated data one delivery is bound to.

This package cannot construct it: the binding names both devices, and which device of a multi-device recipient a message is for is a routing decision made above.

type Carried

type Carried struct {
	Generation  eventlog.RelayGeneration
	RedepositAt time.Time
}

Carried is a Sender's answer that a relay durably holds the copy and no recipient device has acknowledged it. The dispatcher records the generation and keeps the copy open until a verified delivery ack settles it.

func (*Carried) Error

func (c *Carried) Error() string

type ComposeRequest

type ComposeRequest struct {
	ConversationID, RoomID, ReplyToEventID string
	MembershipEpoch                        uint64
	MediaType, Body, IdempotencyKey        string
	SessionID, RecipientEndpointID         string
	RecipientAgentID                       string
	ExpiresAtUnix                          uint64
}

ComposeRequest is the semantic subset an Agent runtime may choose.

type Config

type Config struct {
	Journal  *eventlog.Journal
	Suite    e2ee.Suite
	Sender   Sender
	Bindings BindingResolver
	Now      func() time.Time
	// Identity is who this installation is. Outbound events must say they came
	// from it, because a runtime that could set the sender fields freely could
	// send as somebody else from this daemon's own sessions.
	Identity Identity
	// Network is fixed by daemon configuration. It is deliberately not a
	// compose-call argument: a runtime may choose words, not their chain domain.
	Network *nativev1.NetworkDomain
	// AllowedEventClasses is the outbound authority granted by the live
	// endpoint delegation. Nil leaves the dispatcher reusable for callers that
	// enforce authority at a higher boundary; daemon startup always supplies
	// the finalized delegation's non-empty list.
	AllowedEventClasses []string
	// AttemptLease bounds how long one sweep may hold a delivery. A lease that
	// never expires strands an event when the sweep holding it dies.
	AttemptLease time.Duration
}

Config wires one dispatcher.

The journal is required and the sending half is not. Queueing an event needs somewhere durable to put it; sealing and sending need a frozen suite and a chosen route, and neither exists yet. An installation without them can accumulate outbound events safely and cannot pretend to deliver them, which is exactly the state this project is in.

type CopyTarget

type CopyTarget struct {
	SessionID, RecipientEndpointID, RecipientDeviceID string
}

CopyTarget is one daemon-selected device destination for a logical Event.

type Deferred

type Deferred struct {
	Code  fault.Code
	Until time.Time
}

Deferred is a SealGate's or Sender's answer that a copy must wait without spending an attempt: the recipient's evidence is stale, or an in-flight cap is reached. Code says why, for the owner surface.

func (*Deferred) Error

func (d *Deferred) Error() string

type Dispatcher

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

Dispatcher sends what the journal says is due.

func New

func New(config Config) (*Dispatcher, error)

New builds a dispatcher.

The sending half is all or nothing: a dispatcher with a suite but no sender would seal messages nothing can carry, advancing a ratchet for nothing.

func (*Dispatcher) CanSend

func (d *Dispatcher) CanSend() bool

CanSend reports whether this dispatcher has a transport.

func (*Dispatcher) ComposeAndQueue

func (d *Dispatcher) ComposeAndQueue(request ComposeRequest) (envelope.Event, bool, error)

ComposeAndQueue constructs the canonical event under daemon-owned identity, network, clock and kind, then durably binds it to the runtime's idempotency key before queueing it. A process crash at either boundary is retry-safe.

func (*Dispatcher) ComposeHistoryAndQueue

func (d *Dispatcher) ComposeHistoryAndQueue(request HistoryRequest) (envelope.Event, payload.DeviceHistorySegment, bool, error)

ComposeHistoryAndQueue builds a stable page from durable applied/delivered Events and queues it to another device of this Endpoint. The idempotency intent describes the requested page, not the current journal contents, so a retry returns the first committed Event even if newer messages arrived.

func (*Dispatcher) ComposeProtocolResultAndQueue

func (d *Dispatcher) ComposeProtocolResultAndQueue(request ProtocolResultRequest) (envelope.Event, bool, error)

ComposeProtocolResultAndQueue constructs only A2A responses and MCP results. Calls cannot be synthesized through this result-only boundary.

func (*Dispatcher) ConfigureSealGate

func (d *Dispatcher) ConfigureSealGate(gate SealGate) error

ConfigureSealGate installs the route's pre-seal and pre-deposit check during daemon assembly. It may be installed once.

func (*Dispatcher) ConfigureTransport

func (d *Dispatcher) ConfigureTransport(suite e2ee.Suite, sender Sender, bindings BindingResolver) error

ConfigureTransport installs the complete carrier tuple during daemon assembly. Partial installation and replacement are refused; callers must do this before serving or sweeping.

func (*Dispatcher) LocalIdentity

func (d *Dispatcher) LocalIdentity() Identity

LocalIdentity returns the daemon-owned identity used for every composition.

func (*Dispatcher) LookupComposition

func (d *Dispatcher) LookupComposition(idempotencyKey, intentDigest string) (envelope.Event, bool, error)

LookupComposition returns a previously committed Event for an exact daemon intent. It is used before attachment encryption/upload so a completed retry performs no new external side effect.

func (*Dispatcher) LookupQueuedComposition

func (d *Dispatcher) LookupQueuedComposition(idempotencyKey, intentDigest string) (envelope.Event, bool, error)

LookupQueuedComposition returns a composition only after its exact delivery record is durable. Attachment emission deliberately commits a composition before contacting storage, so composition existence alone is not completion evidence: a crash may leave a prepared Event whose ciphertext lease was never acknowledged and whose delivery was never queued.

func (*Dispatcher) Network

func (d *Dispatcher) Network() *nativev1.NetworkDomain

Network returns a defensive copy of the daemon-owned chain domain. It is exposed for daemon subsystems that must repeat the exact Event domain in an independently signed authority object; runtimes cannot set it.

func (*Dispatcher) PrepareEncryptedAttachment

func (d *Dispatcher) PrepareEncryptedAttachment(request AttachmentRequest) (envelope.Event, bool, error)

PrepareEncryptedAttachment durably binds the first complete, daemon-built Event to its idempotency intent without queueing it. The caller must obtain and verify the storage StoredAck before QueuePreparedAttachment; therefore a recipient can never receive an Event whose exact ciphertext lease was not acknowledged first.

func (*Dispatcher) Queue

func (d *Dispatcher) Queue(event envelope.Event, sessionID, recipientEndpointID string, expiresAtUnix uint64) (bool, eventlog.Delivery, error)

Queue records an event for delivery.

The plaintext is stored before anything is sealed, so a crash between advancing the session and committing the ciphertext leaves something to seal again.

func (*Dispatcher) QueueCopies

func (d *Dispatcher) QueueCopies(event envelope.Event, targets []CopyTarget,
	expiresAtUnix uint64) ([]eventlog.Delivery, error)

QueueCopies records one independently sealed delivery per verified device. Every copy carries the same Event bytes and EventID; only the journal key and cryptographic device session differ.

func (*Dispatcher) QueuePreparedAttachment

func (d *Dispatcher) QueuePreparedAttachment(event envelope.Event, sessionID, recipientEndpointID string, expiresAtUnix uint64) (bool, error)

QueuePreparedAttachment queues the exact previously prepared Event after a verified StoredAck. Queue is idempotent, including a crash after enqueue and before the attachment transaction is removed.

func (*Dispatcher) Sweep

func (d *Dispatcher) Sweep(ctx context.Context, limit int) (Summary, error)

Sweep attempts every delivery whose next attempt has arrived.

One failing delivery does not stop the others: a peer that is unreachable would otherwise block every message to everyone else.

type HistoryRequest

type HistoryRequest struct {
	TargetDeviceID, ConversationID string
	Sequence                       uint64
	PreviousSegmentDigest          string
	AfterCreatedAtUnix             uint64
	AfterEventID, IdempotencyKey   string
	Limit                          int
	ExpiresAtUnix                  uint64
}

HistoryRequest is one owner-authorized direct-history page. The dispatcher derives the source identity, recipient endpoint, device session, network, Event kind, and Event ID; none is supplied by the caller.

type Identity

type Identity struct {
	AgentID    string
	EndpointID string
	DeviceID   string
}

Identity is the Agent, endpoint, and device this installation speaks for.

func (Identity) Validate

func (i Identity) Validate() error

Validate enforces a complete local identity.

type Message

type Message struct {
	EventID             string
	SessionID           string
	RecipientEndpointID string
	RecipientDeviceID   string
	ConversationID      string
	// Bootstrap is present on an initiator's first-contact retries and contains
	// only signed public prekey evidence and suite initial bytes.
	Bootstrap      []byte
	AdmissionToken string
	Ciphertext     []byte
	ExpiresAtUnix  uint64
	// DeliveryID and Generation name this attempt's journal copy and relay
	// deposit generation. A synchronous carrier ignores them; a store-and-
	// forward carrier derives its idempotency key from them, so a retry of
	// one generation reuses the envelope it already deposited.
	DeliveryID string
	Generation uint32
}

Message is one sealed event handed to a transport.

type ProtocolResultRequest

type ProtocolResultRequest struct {
	ConversationID, ReplyToEventID string
	Kind, Protocol, Version        string
	Body                           []byte
	IdempotencyKey                 string
	SessionID, RecipientEndpointID string
	ExpiresAtUnix                  uint64
}

ProtocolResultRequest is the narrow runtime-selected meaning of a reply. Identity, network, clock, schema and Event ID remain daemon-owned.

type SealGate

type SealGate interface {
	CheckCopy(ctx context.Context, delivery eventlog.Delivery, sealing bool) error
}

SealGate is consulted before a copy is sealed and before a sealed copy is deposited again. A route that carries content only to currently verified recipient devices implements it; an error that is not *Deferred is a failure with the error's fault code.

type Sender

type Sender interface {
	Send(context.Context, Message) error
}

Sender delivers a sealed message.

It returns nil once a recipient device has durably accepted the message, and otherwise an error whose fault code says what to do next. Returning nil for "handed to the network" would turn every lost packet into a delivered message. A store-and-forward carrier returns *Carried instead, which is neither delivery nor failure.

type SessionBindings

type SessionBindings struct {
	Journal  *eventlog.Journal
	Identity Identity
	Network  *nativev1.NetworkDomain
}

SessionBindings derives outbound AEAD authority solely from the durable first-contact session and daemon configuration. Network messages and Agent runtimes cannot substitute any identity or route field.

func (SessionBindings) BindingFor

func (r SessionBindings) BindingFor(delivery eventlog.Delivery) (e2ee.Binding, error)

type Summary

type Summary struct {
	// Sent counts messages a recipient durably accepted.
	Sent int
	// Sealed counts messages sealed during this sweep. It is lower than Sent
	// whenever a retry reused a committed ciphertext, which is the point.
	Sealed int
	// Retried counts failures that will be attempted again.
	Retried int
	// Held counts messages waiting on an owner decision rather than on time.
	Held int
	// Abandoned counts messages no further attempt can deliver.
	Abandoned int
	// Carried counts messages a relay now holds without a device ack.
	Carried int
	// Deferred counts messages left pending without spending an attempt.
	Deferred int
}

Summary is what one sweep did.

type SweepPreparer

type SweepPreparer interface {
	PrepareSweep(ctx context.Context, now time.Time) (func(), error)
}

SweepPreparer is an optional SealGate extension called once at the start of each sweep that has due deliveries, so a gate can index what it reads once per sweep instead of once per copy. The returned function ends the sweep and is called when the sweep returns.

Jump to

Keyboard shortcuts

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