// Package runs is Archie's durable run engine. A run executes a registered // workflow step by step; each step's result is saved before the next starts, // so after a crash the run replays from saved results without repeating a // finished step. Every write is fenced by the worker's lease. package runs import ( "context" "encoding/json/jsontext" "errors" "fmt" "log/slog" "sync" "time" "github.com/google/uuid" "github.com/jmoiron/sqlx" "github.com/samcharles93/archie-core/modules/runs/internal/store" ) // Workflow is the code a run executes. It must choose its next step only from // its input and the results of earlier steps; clock reads, randomness and // lookups belong inside steps. type Workflow func(rc *Context, input jsontext.Value) (jsontext.Value, error) // StartRequest names the workflow to run and the organisation it runs for. // A non-empty Key makes the start idempotent within the organisation. type StartRequest struct { OrgID string Workflow string Key string Input jsontext.Value } // Options tune the engine. Zero values take the defaults. type Options struct { Owner string Workers int LeaseTTL time.Duration PollInterval time.Duration } // workerStore is what a worker needs from storage; every write is fenced. type workerStore interface { Claim(ctx context.Context, owner string, token uuid.UUID, ttl time.Duration) (store.Run, bool, error) RenewLease(ctx context.Context, id, token uuid.UUID, ttl time.Duration) (bool, error) Steps(ctx context.Context, id uuid.UUID) ([]store.Step, error) RecordStep(ctx context.Context, token uuid.UUID, step store.Step) error Suspend(ctx context.Context, id, token uuid.UUID, wakeAt *time.Time, waitingFor string) error Finish(ctx context.Context, id, token uuid.UUID, state string, result jsontext.Value, errText string) error Signalled(ctx context.Context, id uuid.UUID, key string) (jsontext.Value, bool, error) CancelRequested(ctx context.Context, id uuid.UUID) (bool, error) } // Engine starts, executes and resumes runs. type Engine struct { db *store.Store work workerStore log *slog.Logger opts Options mu sync.RWMutex workflows map[string]Workflow } // New returns an engine on db. func New(db *sqlx.DB, log *slog.Logger, opts Options) *Engine { s := store.New(db) return newEngine(s, s, log, opts) } func newEngine(db *store.Store, work workerStore, log *slog.Logger, opts Options) *Engine { if opts.Workers <= 0 { opts.Workers = 4 } if opts.LeaseTTL <= 0 { opts.LeaseTTL = 30 * time.Second } if opts.PollInterval <= 0 { opts.PollInterval = time.Second } if opts.Owner == "" { opts.Owner = "archie" } return &Engine{db: db, work: work, log: log, opts: opts, workflows: map[string]Workflow{}} } // Register makes a workflow available to runs by name. func (e *Engine) Register(name string, wf Workflow) { e.mu.Lock() defer e.mu.Unlock() e.workflows[name] = wf } // Start queues a run and returns its id. func (e *Engine) Start(ctx context.Context, req StartRequest) (uuid.UUID, error) { input := req.Input if len(input) == 0 { input = jsontext.Value("null") } return e.db.Start(ctx, req.OrgID, req.Workflow, req.Key, input) } // Signal delivers a payload to a run waiting on key, now or later. func (e *Engine) Signal(ctx context.Context, id uuid.UUID, key string, payload jsontext.Value) error { return e.db.Signal(ctx, id, key, payload) } // Cancel asks a run to stop. func (e *Engine) Cancel(ctx context.Context, id uuid.UUID) error { return e.db.Cancel(ctx, id) } // Work runs the engine's workers until ctx ends. func (e *Engine) Work(ctx context.Context) { var wg sync.WaitGroup for range e.opts.Workers { wg.Go(func() { e.workerLoop(ctx) }) } wg.Wait() } func (e *Engine) workerLoop(ctx context.Context) { for ctx.Err() == nil { claimed, err := e.claimAndExecute(ctx) if err != nil { e.log.ErrorContext(ctx, "run worker", "error", err) } if claimed && err == nil { continue } select { case <-ctx.Done(): case <-time.After(e.opts.PollInterval): } } } func (e *Engine) claimAndExecute(ctx context.Context) (bool, error) { token := uuid.New() run, ok, err := e.work.Claim(ctx, e.opts.Owner, token, e.opts.LeaseTTL) if err != nil || !ok { return false, err } e.execute(ctx, run, token) return true, nil } // execute runs one claimed run to its next suspension or end. The run's // context ends if the lease can't be renewed, so a stale worker stops. func (e *Engine) execute(ctx context.Context, run store.Run, token uuid.UUID) { runCtx, cancel := context.WithCancel(ctx) defer cancel() go e.keepLease(runCtx, cancel, run.ID, token) log := e.log.With("run", run.ID, "workflow", run.Workflow, "attempt", run.Attempts) result, err := e.invoke(runCtx, run, token) switch { case errors.Is(err, errSuspended): log.InfoContext(ctx, "run suspended") return case errors.Is(err, store.ErrLeaseLost), errors.Is(err, context.Canceled): log.WarnContext(ctx, "run stopped: lease lost or shutting down") return } state, errText := store.StateSucceeded, "" if errors.Is(err, ErrCancelled) { state, errText = store.StateCancelled, err.Error() } else if err != nil { state, errText = store.StateFailed, err.Error() } if ferr := e.work.Finish(ctx, run.ID, token, state, result, errText); ferr != nil { log.WarnContext(ctx, "finish run", "error", ferr) return } log.InfoContext(ctx, "run finished", "state", state) } // invoke runs the workflow, turning a panic in workflow or step code into a // failure of this run rather than of the process. func (e *Engine) invoke(ctx context.Context, run store.Run, token uuid.UUID) (result jsontext.Value, err error) { defer func() { if p := recover(); p != nil { err = fmt.Errorf("panic: %v", p) } }() wf, ok := e.workflow(run.Workflow) if !ok { return nil, fmt.Errorf("no workflow named %q", run.Workflow) } steps, err := e.work.Steps(ctx, run.ID) if err != nil { return nil, err } return wf(newContext(ctx, e.work, run, token, steps), run.Input) } func (e *Engine) workflow(name string) (Workflow, bool) { e.mu.RLock() defer e.mu.RUnlock() wf, ok := e.workflows[name] return wf, ok } func (e *Engine) keepLease(ctx context.Context, lost context.CancelFunc, id, token uuid.UUID) { tick := time.NewTicker(e.opts.LeaseTTL / 3) defer tick.Stop() for { select { case <-ctx.Done(): return case <-tick.C: held, err := e.work.RenewLease(ctx, id, token, e.opts.LeaseTTL) if err != nil || !held { e.log.WarnContext(ctx, "lease not renewed", "run", id, "error", err) lost() return } } } }