//! Task execution: context, scheduling primitives. //! //! `TaskContext` is what user task functions receive. It carries identity //! (key, attempt, generation) and a back-reference to the docket so a task can //! interact with it. For v0, contexts are read-only from the task's perspective. const std = @import("std"); const Allocator = std.mem.Allocator; const Io = std.Io; const uuid = @import("uuid"); const Task = @import("task.zig").Task; /// Result of a scheduling attempt. pub const Disposition = enum { scheduled, already_scheduled, struck, }; /// Handle returned by `Docket.add`. `key` is heap-allocated under the docket's /// allocator; caller is responsible for freeing once it's no longer needed. pub const ExecutionHandle = struct { key: []const u8, disposition: Disposition, pub fn deinit(self: ExecutionHandle, alloc: Allocator) void { alloc.free(self.key); } }; /// Context passed to user task functions. v0: read-only. pub const TaskContext = struct { key: []const u8, attempt: u32, generation: u32, }; /// Schedule a task: serialize params to JSON, generate a uuid7 key if absent, /// EVAL the schedule.lua script via the backend. pub fn schedule( docket: anytype, task_name: []const u8, params: anytype, opts: anytype, ) !ExecutionHandle { // resolve when_micros and is_immediate. const now_micros: i64 = @intCast(@divFloor( std.Io.Timestamp.now(docket.io, .real).nanoseconds, std.time.ns_per_us, )); const when_micros = opts.when_micros orelse now_micros; const is_immediate = when_micros <= now_micros; // generate or dupe the task key (so the returned handle outlives this frame). var key_buf: [36]u8 = undefined; const generated_key: []const u8 = if (opts.key) |k| k else blk: { const id = uuid.v7.new(docket.io); const urn = uuid.urn.serialize(id); @memcpy(&key_buf, &urn); break :blk key_buf[0..36]; }; const task_key = try docket.allocator.dupe(u8, generated_key); errdefer docket.allocator.free(task_key); // serialize params to JSON for the wire body. var params_buf: std.Io.Writer.Allocating = .init(docket.allocator); defer params_buf.deinit(); var jw: std.json.Stringify = .{ .writer = ¶ms_buf.writer }; try jw.write(params); const params_json = params_buf.written(); // message fields — alternating name/value pairs. const attempt_str = "1"; const fields = [_][]const u8{ "function", task_name, "key", task_key, "params", params_json, "attempt", attempt_str, }; const disp = try docket.backend.scheduleTask(.{ .task_key = task_key, .when_micros = when_micros, .is_immediate = is_immediate, .fields = &fields, }); return .{ .key = task_key, .disposition = switch (disp) { .scheduled => .scheduled, .already_scheduled => .already_scheduled, .struck => .struck, }, }; }