dispatch

package
v0.3.166 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2026 License: MIT Imports: 11 Imported by: 1 module, 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 dispatch runs chat dispatches as jobs that outlive the HTTP request which submitted them (LOOM-80, design spec docs/design/async-dispatch-design.md). A job is persisted, together with its user message, before Submit returns; it then runs on a context the Service owns, so a client going away (a closed tab, a sleeping phone, a proxy timeout) never reaches the turn. Results land on the job row, which clients read back directly, through the conversation's history, or as stream events.

Index

Constants

View Source
const MaxIDLen = 64

MaxIDLen is the longest client-supplied id Submit accepts: a conversation_id or a workspace_hint (LOOM-154).

Variables

View Source
var (
	// ErrInvalidRequest: the request can't be dispatched as given. The
	// error Submit returns wraps it and says what was wrong.
	ErrInvalidRequest = errors.New("dispatch: invalid request")
	// ErrKeyReused: the idempotency key was already used for a
	// different request.
	ErrKeyReused = errors.New("dispatch: idempotency key was already used for a different request")
	// ErrShuttingDown: the Service no longer accepts dispatches.
	ErrShuttingDown = errors.New("dispatch: server is shutting down")
	// ErrNotRunning: Cancel was asked for a job that has already ended,
	// or isn't running in this process.
	ErrNotRunning = errors.New("dispatch: not running")
)

Functions

func ValidID added in v0.3.49

func ValidID(s string) bool

ValidID reports whether s can be a client-supplied id: 1 to MaxIDLen ASCII letters, digits, '-' or '_'. A server-minted id (a UUID) always is. A conversation id is a path segment everywhere else in the API (GET /conversations/{id}), so one that isn't could be stored but never fetched back.

Types

type BusyError

type BusyError struct {
	DispatchID string
}

BusyError is returned when the conversation already has a dispatch in flight. LOOM-83 owns serializing a conversation's dispatches; until then the second one is refused and told which one is running.

func (*BusyError) Error

func (e *BusyError) Error() string

type Option

type Option func(*Service)

Option configures a Service.

func WithErrorClassifier

func WithErrorClassifier(f func(error) registry.ErrorClass) Option

WithErrorClassifier maps a failed run's error to the class recorded on the job. Without one every failure is ErrorClassInternal (bar the Service's own timeout).

func WithLogger

func WithLogger(l *slog.Logger) Option

WithLogger sets where job lifecycle logs go. Defaults to discarding.

func WithMaxDuration

func WithMaxDuration(d time.Duration) Option

WithMaxDuration overrides the per-job ceiling (defaultMaxDuration).

func WithOnFinished

func WithOnFinished(f func(d *registry.Dispatch)) Option

WithOnFinished calls f with each job that ran to its end, succeeded or failed, once its result is recorded (LOOM-102) — not with one interrupted by shutdown. f runs on the job's goroutine before waiters are released, so it must return quickly; d is a copy f may keep.

func WithResumer

func WithResumer(f ResumeFunc) Option

WithResumer sets how Recover carries on jobs left running (LOOM-82). Without one they are all marked interrupted.

func WithWriteRetry added in v0.3.44

func WithWriteRetry(attempts int, backoff time.Duration) Option

WithWriteRetry overrides how a job's status writes are retried (LOOM-146): attempts in all, waiting backoff after the first failure and doubling. For tests.

type Request

type Request struct {
	// ConversationID may be empty: Submit then starts a new conversation.
	ConversationID string
	Message        string
	WorkspaceHint  string
	// ConfirmationID names the offer the message answers (LOOM-123).
	ConfirmationID string
	// IdempotencyKey, when set, makes a repeated Submit of the same
	// request return the original dispatch instead of starting another.
	IdempotencyKey string
}

Request is one submitted chat message.

func (Request) Validate added in v0.3.49

func (req Request) Validate() error

Validate checks what a client supplies: a message, and, when set, a conversation id and workspace hint that are ValidIDs. The error wraps ErrInvalidRequest and names the field.

type ResumeFunc

type ResumeFunc func(ctx context.Context, d *registry.Dispatch) RunFunc

ResumeFunc is offered each job a previous process left running (LOOM-82). It returns how to carry that job on — in production, by waiting on its agent's still-running turn — or nil when it can't be, and the job is marked interrupted.

type RunFunc

type RunFunc func(ctx context.Context, d *registry.Dispatch) (reply string, err error)

RunFunc carries out one dispatch — in production, the router's Dispatch — and returns the chat reply.

type Service

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

Service accepts, runs and tracks dispatch jobs.

func New

func New(store Store, run RunFunc, opts ...Option) *Service

New returns a Service that runs each job with run.

func (*Service) Cancel

func (s *Service) Cancel(ctx context.Context, id string) error

Cancel stops the running job id (LOOM-99): its context is cancelled with cause orchestrator.ErrCancelled, which the router answers by interrupting the agent and failing its task, and the job then ends failed with class cancelled. It returns once the job has been told, not once it has ended: the stream reports that. registry.ErrNotFound for an unknown id; ErrNotRunning for one that has ended.

func (*Service) Get

func (s *Service) Get(ctx context.Context, id string) (*registry.Dispatch, error)

Get returns dispatch id as stored.

func (*Service) ListByConversation

func (s *Service) ListByConversation(ctx context.Context, conversationID string) ([]*registry.Dispatch, error)

ListByConversation returns a conversation's dispatches, oldest first.

func (*Service) Recover

func (s *Service) Recover(ctx context.Context) (int, error)

Recover deals with every dispatch a previous process left unfinished (LOOM-82), and returns how many it marked interrupted. A queued job never started, so it is simply run now. A running one is offered to the resumer, which can carry it on — its agent may still be working — and is otherwise marked interrupted. Call it once at startup, before Submit.

func (*Service) Shutdown

func (s *Service) Shutdown(ctx context.Context) error

Shutdown stops accepting dispatches and gives running ones until ctx is done to finish. Any still running then have their contexts cancelled with cause orchestrator.ErrInterrupted, which tells the router to leave their tasks running, and their rows are left running too: the next process's Recover resumes them (LOOM-82), so a deploy mid-turn still delivers the reply.

func (*Service) Submit

func (s *Service) Submit(ctx context.Context, req Request) (*registry.Dispatch, error)

Submit persists req as a queued job, with its user message, and starts it. It returns once the job is stored — ctx bounds only that, never the job. A repeat of an earlier request with the same IdempotencyKey returns the earlier job and starts nothing.

func (*Service) SweepOrphans added in v0.3.44

func (s *Service) SweepOrphans(ctx context.Context) (int, error)

SweepOrphans marks interrupted every queued or running dispatch with no job in this process (LOOM-146): one whose own status write failed even after retries, which would otherwise hold its conversation busy (409) until the next restart's Recover. It must only run after Recover, and does nothing once Shutdown has begun: the rows a shutdown leaves running are for the next start to resume.

func (*Service) Wait

func (s *Service) Wait(ctx context.Context, id string) (*registry.Dispatch, error)

Wait blocks until dispatch id is finished or ctx is done, and returns its row. ctx ending only stops the waiting: the job carries on.

type Store

type Store interface {
	CreateDispatch(ctx context.Context, d *registry.Dispatch, userMessage *registry.Message) error
	GetDispatch(ctx context.Context, id string) (*registry.Dispatch, error)
	GetDispatchByIdempotencyKey(ctx context.Context, key string) (*registry.Dispatch, error)
	ListDispatchesByConversation(ctx context.Context, conversationID string) ([]*registry.Dispatch, error)
	ListDispatchesByStatus(ctx context.Context, statuses ...registry.DispatchStatus) ([]*registry.Dispatch, error)
	TransitionDispatch(ctx context.Context, d *registry.Dispatch, from registry.DispatchStatus) error
}

Store is the slice of registry.Store a Service needs.

Jump to

Keyboard shortcuts

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