einherjar/worker

version license go

In Valhalla, there is no rest between battles. There is only preparation for the next.

code.nochebuena.dev/einherjar/worker is the background task pool component of the Einherjar framework. It manages a bounded goroutine pool with a buffered work queue. On shutdown, it drains all queued tasks within the configured timeout before stopping. Dispatch returns false when the buffer is full — the caller decides whether to drop, queue elsewhere, or surface an error.


Usage

Setup

import "code.nochebuena.dev/einherjar/worker"

w := worker.New(logger, worker.DefaultConfig())
lc.Append(w)   // OnInit starts pool; OnStop drains and stops

Dispatching tasks

// Task is func(ctx context.Context) error
dispatched := w.Dispatch(func(ctx context.Context) error {
    return sendWelcomeEmail(ctx, userID)
})

if !dispatched {
    // Buffer full — decide: drop, queue elsewhere, or return an error.
    logger.Warn("worker buffer full, task dropped", nil)
}

Checking queue depth

depth := w.Len() // number of tasks currently buffered (not yet picked up)

Checking pool saturation

if w.Len() >= cfg.BufferSize {
    // Near capacity — consider shedding load.
}

Environment variables

Variable Required Default Description
EINHERJAR_WORKER_POOL_SIZE No 5 Number of goroutines in the pool
EINHERJAR_WORKER_BUFFER_SIZE No 100 Buffered task queue capacity
EINHERJAR_WORKER_TASK_TIMEOUT No 0s Per-task deadline; 0 means no deadline
EINHERJAR_WORKER_SHUTDOWN_TIMEOUT No 30s Maximum drain time on stop

A PoolSize of 5 and BufferSize of 100 means up to 105 tasks can be in flight (5 executing + 100 waiting) before Dispatch returns false.


Dependency graph

contracts  (zero dependencies)
    ↑
  worker  (contracts only)
    ↑
  your app

worker does not depend on core. It is the lightest lifecycle component in the framework.


Verification

cd worker/
go build ./...
go vet ./...
go test ./...
gofmt -l .

A warrior who does not prepare between battles is not a warrior. Build the pool. Fill it with work. Let it run.

S
Description
Bounded goroutine pool for background task dispatch with graceful drain on shutdown
Readme AGPL-3.0
112 KiB
2026-08-12 15:50:16 -06:00
Languages
Go 100%