//! Docket worker service. //! //! Wraps a `docket.Worker` and runs it via `io.async`, exposing the //! init/start/stop shape that Services.startAll/stopAll calls. //! //! Lifecycle: //! - init: stores config; does NOT start anything. //! - start: ensures the consumer group exists, builds the Worker, and //! spawns `Worker.runForever` via `io.async`. The returned Future is //! stashed on the service. //! - stop: `future.cancel(io)` requests cancellation. The next Io //! operation inside the worker returns `error.Canceled`; runForever //! exits cleanly. We then `await` to ensure the worker has fully //! drained before tearing down dependent state. //! //! Multiple loop services (late_runs, scheduler, lease_cleanup, //! automations) register their perpetual tasks against the shared //! `docket_runtime.docket_instance` BEFORE this worker starts. The worker //! consumes the shared stream and dispatches to whichever task matches //! the message's `function` field. const std = @import("std"); const Allocator = std.mem.Allocator; const Io = std.Io; const docket = @import("docket"); const log = @import("../logging.zig"); const docket_runtime = @import("../docket_runtime.zig"); pub const DocketWorker = struct { allocator: Allocator, io: Io, name: []const u8, worker: ?docket.Worker = null, future: ?Io.Future(anyerror!void) = null, pub fn init(allocator: Allocator, io: Io) DocketWorker { return .{ .allocator = allocator, .io = io, .name = "docket-worker-1", }; } pub fn start(self: *DocketWorker) !void { if (self.future != null) return; if (!docket_runtime.isInitialised()) { log.warn("docket_worker", "docket runtime not initialised — skipping start", .{}); return; } const d = docket_runtime.instance(); // Ensure the consumer group exists on the shared stream. Idempotent // (BusyGroup is swallowed by the redis backend; the memory backend // does the same). try d.backend.ensureConsumerGroup(docket.WORKER_GROUP); self.worker = try docket.Worker.init(self.allocator, self.io, d, .{ .name = self.name, .poll_block_ms = 500, .scheduler_interval_micros = 500 * std.time.us_per_ms, }); log.info("docket_worker", "starting (name={s})", .{self.name}); // Worker must outlive the future — `self.worker` is in our struct, // owned by Services; both share a lifetime tied to main(). self.future = self.io.async(docket.Worker.runForever, .{&self.worker.?}); } pub fn stop(self: *DocketWorker) void { if (self.future == null) return; log.info("docket_worker", "stopping (cancel + await)", .{}); if (self.worker) |*w| w.stop(); if (self.future) |*f| { const result = f.cancel(self.io); result catch |err| switch (err) { error.Canceled => {}, else => log.warn("docket_worker", "worker exited with non-cancel error: {}", .{err}), }; } self.future = null; if (self.worker) |*w| w.deinit(); self.worker = null; } };