Something went wrong. Try again.
zig port of github.com/chrisguidry/docket
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305//! Worker — consumes the Redis stream, dispatches to registered tasks,//! acks on success. Perpetual tasks self-reschedule before ack.//!//! Shutdown model: cancel-via-Io. Spawn `Worker.runForever` inside an//! `io.async` task (or any other context that produces a `Future`); call//! `future.cancel(io)` to request stop. The next Io operation inside the//! worker (typically the blocking XREADGROUP socket read) returns//! `error.Canceled`; runForever catches it and exits cleanly.//!//! Mid-task cancellation: a running task body whose next Io call returns//! `error.Canceled` propagates that up through `task.invoke`. The worker//! treats it like any other task error — `ackMessage(..., "failed")` is//! the next Io call but runs normally (Cancelable signals once per request//! per task), so cleanup completes. The cancellation then surfaces at the//! NEXT XREADGROUP and the loop exits.//!//! Tasks that must NOT be interruptible mid-execution can wrap their//! critical sections in `Io.CancelProtection.protect`.//!//! Horizontal scale: run multiple workers against the same Redis. Each//! takes the same consumer-group name; XREADGROUP load-balances messages//! across them.
const std = @import("std");const Allocator = std.mem.Allocator;const Io = std.Io;const redis = @import("redis");
const Docket = @import("docket.zig").Docket;const Task = @import("task.zig").Task;const TaskContext = @import("execution.zig").TaskContext;
pub const WORKER_GROUP = "docket-workers";
pub const WorkerConfig = struct { name: []const u8, /// XREADGROUP BLOCK in milliseconds. Long enough that the worker doesn't /// busy-loop; short enough that the redis backend has a polling cadence /// when cancellation is in play (cancel still fires immediately on /// real Io ops, this is for memory-backend rescheduling cadence only). poll_block_ms: u32 = 1_000, /// How often to run the scheduler-promote pass (microseconds). scheduler_interval_micros: i64 = 500 * std.time.us_per_ms, /// How long a delivered-but-unacked message may sit in some consumer's /// pending list before any worker may take it over. This is what makes a /// dead worker's in-flight message run again instead of being stranded /// forever; matches pydocket's `redelivery_timeout` default. /// /// Must exceed a perpetual task's interval — see `runForever`. redelivery_timeout_ms: u32 = 5 * std.time.ms_per_min,};
pub const Worker = struct { allocator: Allocator, io: Io, docket: *Docket, config: WorkerConfig, last_scheduler_run_micros: i64 = 0, running: bool = true,
pub fn init(allocator: Allocator, io: Io, docket: *Docket, cfg: WorkerConfig) !Worker { return .{ .allocator = allocator, .io = io, .docket = docket, .config = cfg, }; }
pub fn deinit(_: *Worker) void {}
pub fn stop(self: *Worker) void { self.running = false; }
/// Run until cancellation. The expected idiom is: /// /// var fut = io.async(Worker.runForever, .{&worker}); /// ... /// _ = fut.cancel(io); /// _ = fut.await(io); /// /// Returns `error.Canceled` when stopped via the Future API, or any /// other unrecoverable error from `ensureConsumerGroup`. Recoverable /// per-tick errors (transient redis failures, unknown task names) are /// logged and the loop continues. pub fn runForever(self: *Worker) anyerror!void { try self.docket.backend.ensureConsumerGroup(WORKER_GROUP);
self.running = true; while (self.running) { self.tick() catch |err| switch (err) { error.Canceled => return, else => { std.log.warn("docket worker: tick error: {s}", .{@errorName(err)}); // Continue — non-cancel errors are per-tick recoverable. }, }; } }
/// One iteration of the worker loop. Exposed for tests + composability. /// Propagates `error.Canceled` so `runForever` can exit cleanly; other /// errors are logged and swallowed so a single failed tick doesn't kill /// the worker. pub fn tick(self: *Worker) anyerror!void { const now_micros = nowMicros(self.io);
if (now_micros - self.last_scheduler_run_micros >= self.config.scheduler_interval_micros) { _ = self.docket.backend.promoteDueTasks(now_micros) catch |err| switch (err) { error.Canceled => return error.Canceled, else => std.log.warn("docket worker: promote_due failed: {s}", .{@errorName(err)}), }; self.last_scheduler_run_micros = now_micros; }
// Redelivery before new work: a message whose worker died between // XREADGROUP and XACK is invisible to XREADGROUP forever (it stays in // that consumer's PEL), so nothing but XAUTOCLAIM can rescue it. // Handling at most one per tick keeps reclaimed and fresh work on the // same footing — and the memory backend hands both back out of one // read arena, so the claimed entry has to be consumed before the // XREADGROUP below would clobber it. const reclaimed = self.docket.backend.reclaimIdle( WORKER_GROUP, self.config.name, self.config.redelivery_timeout_ms, ) catch |err| switch (err) { error.Canceled => return error.Canceled, else => blk: { std.log.warn("docket worker: xautoclaim failed: {s}", .{@errorName(err)}); break :blk null; }, }; if (reclaimed) |msg| { std.log.info("docket worker: redelivering idle message {s}", .{msg.id}); self.handleMessage(msg) catch |err| switch (err) { error.Canceled => return error.Canceled, else => std.log.warn("docket worker: handleMessage failed: {s}", .{@errorName(err)}), }; return; }
const maybe_msg = self.docket.backend.consumeStream( WORKER_GROUP, self.config.name, self.config.poll_block_ms, ) catch |err| switch (err) { error.Canceled => return error.Canceled, else => { std.log.warn("docket worker: xreadgroup failed: {s}", .{@errorName(err)}); return; }, }; if (maybe_msg) |msg| { self.handleMessage(msg) catch |err| switch (err) { error.Canceled => return error.Canceled, else => std.log.warn("docket worker: handleMessage failed: {s}", .{@errorName(err)}), }; } }
/// Parse a stream message, dispatch to the registered task, ack on success. /// Perpetual tasks schedule their next run before ack. fn handleMessage(self: *Worker, msg: redis.StreamEntry) !void { var arena = std.heap.ArenaAllocator.init(self.allocator); defer arena.deinit(); const a = arena.allocator();
// Copy fields out of the stream entry — the redis client's buffer is // reused on the next command, so we can't hold borrowed slices across // calls to scheduleTask or ackMessage. var function_name: []const u8 = ""; var task_key: []const u8 = ""; var params_json: []const u8 = ""; var attempt_str: []const u8 = "1"; for (msg.fields) |f| { if (std.mem.eql(u8, f.field, "function")) function_name = try a.dupe(u8, f.value); if (std.mem.eql(u8, f.field, "key")) task_key = try a.dupe(u8, f.value); if (std.mem.eql(u8, f.field, "params")) params_json = try a.dupe(u8, f.value); if (std.mem.eql(u8, f.field, "attempt")) attempt_str = try a.dupe(u8, f.value); } const msg_id = try a.dupe(u8, msg.id);
const task = self.docket.registry.get(function_name) orelse { std.log.warn( "docket worker: unknown task '{s}' (msg {s}), acking and dropping", .{ function_name, msg_id }, ); try self.docket.backend.ackMessage(WORKER_GROUP, msg_id, task_key, "failed", self.docket.execution_ttl_seconds); return; };
var ctx: TaskContext = .{ .key = task_key, .attempt = std.fmt.parseInt(u32, attempt_str, 10) catch 1, .generation = 0, };
const started_micros = nowMicros(self.io); const exec_result = task.invoke(a, self.io, &ctx, params_json);
// A message stays pending from delivery until ack, so what exposes a // task to redelivery is how long it RUNS, not how often it repeats: a // 5-second perpetual that finishes in milliseconds is never at risk. // Once execution outlasts the redelivery timeout, another worker is // free to claim the same message and run it concurrently. const elapsed_micros = nowMicros(self.io) - started_micros; const timeout_micros = @as(i64, self.config.redelivery_timeout_ms) * std.time.us_per_ms; if (elapsed_micros > timeout_micros) { std.log.warn( "docket worker: task '{s}' (key {s}) ran {d}ms, past the {d}ms redelivery " ++ "timeout — another worker may have claimed it mid-flight", .{ function_name, task_key, @divFloor(elapsed_micros, std.time.us_per_ms), self.config.redelivery_timeout_ms, }, ); }
if (exec_result) { // Perpetual rescheduling happens BEFORE ack: if reschedule fails, // the original message stays pending so XAUTOCLAIM can retry. // We trade at-least-once perpetual scheduling for the guarantee // that perpetual never silently dies. The next run keeps this // run's key, so a second copy (a worker died between reschedule // and ack, or a run outlasted the redelivery timeout) finds the // key already scheduled when it reschedules, and the copies merge. if (task.perpetual) |p| { const next_micros = nowMicros(self.io) + p.every_micros; self.reschedulePerpetual(function_name, task_key, msg_id, params_json, next_micros) catch |err| switch (err) { error.Canceled => return error.Canceled, else => { std.log.warn( "docket worker: perpetual reschedule failed for '{s}': {s}", .{ function_name, @errorName(err) }, ); return; // do not ack — message stays pending }, }; } try self.docket.backend.ackMessage(WORKER_GROUP, msg_id, task_key, "completed", self.docket.execution_ttl_seconds); } else |err| switch (err) { error.Canceled => { // Cancellation took out the task body. The "next cancelation // point" contract means our ackMessage call below runs // normally — we can still record a clean failure state. std.log.info( "docket worker: task '{s}' (key {s}) canceled mid-execution", .{ function_name, task_key }, ); try self.docket.backend.ackMessage(WORKER_GROUP, msg_id, task_key, "failed", self.docket.execution_ttl_seconds); return error.Canceled; }, else => { std.log.warn( "docket worker: task '{s}' (key {s}) failed: {s}", .{ function_name, task_key, @errorName(err) }, ); // v0: ack on failure (no automatic retry). Future: re-park // with bumped attempt counter and respect Retry policies. try self.docket.backend.ackMessage(WORKER_GROUP, msg_id, task_key, "failed", self.docket.execution_ttl_seconds); }, } }
fn reschedulePerpetual( self: *Worker, function_name: []const u8, next_key: []const u8, msg_id: []const u8, params_json: []const u8, when_micros: i64, ) !void { const fields = [_][]const u8{ "function", function_name, "key", next_key, "params", params_json, "attempt", "1", };
const now = nowMicros(self.io); _ = try self.docket.backend.scheduleTask(.{ .task_key = next_key, .when_micros = when_micros, .is_immediate = when_micros <= now, .replacing = msg_id, .fields = &fields, }); }};
fn nowMicros(io: Io) i64 { return @intCast(@divFloor( std.Io.Timestamp.now(io, .real).nanoseconds, std.time.ns_per_us, ));}
test { std.testing.refAllDecls(@This());}