Skip to content

worker

import "github.com/danmestas/dagnats/worker"

Task execution framework for building DagNats workers. Handles NATS subscription management, message acknowledgment, retry/NAK logic, heartbeat registration, and the task context API that handlers use.

Key Types

TypeDescription
WorkerCore worker runtime: manages NATS subscriptions, dispatches tasks to handlers, handles lifecycle
TaskContextInterface passed to handlers: provides input, completion, failure, checkpointing, and signal methods
WorkerRegistrationMetadata registered in the workers KV bucket for discovery

Worker Lifecycle

  1. Create a worker with NewWorker(nc, tel)
  2. Register handlers with Handle(taskType, fn) or HandleTyped(taskType, fn)
  3. Call Start() to begin consuming tasks (blocks until shutdown)

Handle vs HandleTyped

MethodSignatureInput Access
Handlefunc(ctx TaskContext) errorctx.Input() returns raw []byte
HandleTyped[I, O]func(ctx TaskContext, input I) (O, error)Automatic JSON unmarshal into I, marshal O on return

HandleTyped is a generic convenience wrapper. It unmarshals the input, calls your function, and auto-completes with the marshaled output on nil error.

TaskContext Methods

MethodDescription
Input() []byteRaw input JSON
RunID() stringWorkflow run ID
StepID() stringStep ID
Attempt() intCurrent retry attempt (1-based)
Complete(output []byte) errorMark task as successfully completed
Fail(err error) errorMark task as failed
Continue(output []byte) errorRequest next agent-loop iteration
Checkpoint(data []byte) errorSave incremental state without pausing
LoadCheckpoint() ([]byte, error)Load previously saved checkpoint
Pause(duration, checkpoint) errorSuspend and redeliver after duration
WaitForSignal(name) ([]byte, error)Block until a named signal arrives

Error Helpers

FunctionDescription
Retryable(err)Wraps an error to indicate it should be retried (NAK with delay)
IsRetryable(err) boolChecks if an error was marked retryable
Fatal(err)Wraps an error to indicate no retry (ACK + fail immediately)
IsFatal(err) boolChecks if an error was marked fatal

Usage

nc, _ := nats.Connect("nats://localhost:4222")
tel := observe.NewNoopTelemetry()
w := worker.NewWorker(nc, tel)

w.Handle("process", func(ctx worker.TaskContext) error {
    input := ctx.Input()
    result := doWork(input)
    return ctx.Complete(result)
})

w.Start() // blocks