//! Memory backend — composite ops backed by the embedded burner-redis engine //! (`tangled.org/zzstoatzz.io/burner-redis`). The same three Lua scripts that //! the Redis backend EVALs remotely run here against an in-process store //! through `burner_redis.LuaEngine`. //! //! What this gives us: //! - Self-contained docket adoption — no external Redis required. //! - Identical wire semantics: the EVAL scripts are byte-for-byte the same. //! - Same `Backend` surface as `RedisBackend`, so `Docket` doesn't care //! which backend it has under the hood. //! //! For ops Redis exposes outside of EVAL (XGROUP CREATE, XREADGROUP), we //! call straight into `burner_redis.Store` rather than round-tripping //! through Lua — those ops have a stable, narrow shape that's easier to //! drive directly. const std = @import("std"); const Allocator = std.mem.Allocator; const Io = std.Io; const burner = @import("burner_redis"); const redis = @import("redis"); const redis_backend = @import("redis.zig"); pub const ScheduleArgs = redis_backend.ScheduleArgs; pub const PromoteResult = redis_backend.PromoteResult; pub const Disposition = redis_backend.Disposition; /// Embed the same Lua scripts the Redis backend uses. Single source of /// truth lives at src/scripts/*.lua. const SCHEDULE_LUA = @embedFile("../scripts/schedule.lua"); const PROMOTE_DUE_LUA = @embedFile("../scripts/promote_due.lua"); const ACK_LUA = @embedFile("../scripts/ack.lua"); pub const MemoryBackend = struct { allocator: Allocator, /// Docket logical name — used as the prefix for all keys, matching the /// redis backend's behaviour. prefix: []const u8, store: burner.Store, engine: burner.scripting.LuaEngine, /// Arena holding the bytes of the most recent consumeStream result. /// Reset on each call so previous slices stop being valid, matching the /// Redis client's read-buffer behaviour. read_arena: std.heap.ArenaAllocator, pub fn connect(allocator: Allocator, io: Io, prefix: []const u8) !MemoryBackend { const store = burner.Store.init(allocator, io); return .{ .allocator = allocator, .prefix = prefix, .store = store, .engine = burner.scripting.LuaEngine.init(allocator, undefined), .read_arena = std.heap.ArenaAllocator.init(allocator), }; } /// Engine has to hold a `*Store` pointer; we patch it here once the /// embedded store has a stable address. Called by `connect_alloc` (the /// `*MemoryBackend` factory in backend.zig). pub fn bindEngine(self: *MemoryBackend) void { self.engine = burner.scripting.LuaEngine.init(self.allocator, &self.store); } pub fn close(self: *MemoryBackend, _: Io) void { self.read_arena.deinit(); self.store.deinit(); self.allocator.destroy(self); } // ------------------------------------------------------------------------ // Composite ops — match RedisBackend's surface byte-for-byte. // ------------------------------------------------------------------------ pub fn scheduleTask(self: *MemoryBackend, args: ScheduleArgs) !Disposition { var arena = std.heap.ArenaAllocator.init(self.allocator); defer arena.deinit(); const a = arena.allocator(); const stream_key = try keyJoin(a, &.{ self.prefix, "stream" }); const parked_key = try keyJoin(a, &.{ self.prefix, "parked", args.task_key }); const queue_key = try keyJoin(a, &.{ self.prefix, "queue" }); const runs_key = try keyJoin(a, &.{ self.prefix, "runs", args.task_key }); const when_str = try std.fmt.allocPrint(a, "{d}", .{args.when_micros}); const is_immediate_str: []const u8 = if (args.is_immediate) "1" else "0"; const keys = [_][]const u8{ stream_key, parked_key, queue_key, runs_key }; var argv: std.ArrayList([]const u8) = .empty; defer argv.deinit(a); try argv.appendSlice(a, &.{ args.task_key, when_str, is_immediate_str, args.replacing }); try argv.appendSlice(a, args.fields); const reply = try self.engine.eval(a, SCHEDULE_LUA, &keys, argv.items); return switch (reply) { .bulk_string, .status => |s| if (std.mem.eql(u8, s, "SCHEDULED")) Disposition.scheduled else if (std.mem.eql(u8, s, "ALREADY_SCHEDULED")) Disposition.already_scheduled else error.UnexpectedScheduleReply, .err => |msg| { std.log.warn("memory backend schedule error: {s}", .{msg}); return error.RedisCommandFailed; }, else => error.UnexpectedScheduleReply, }; } pub fn promoteDueTasks(self: *MemoryBackend, now_micros: i64) !PromoteResult { var arena = std.heap.ArenaAllocator.init(self.allocator); defer arena.deinit(); const a = arena.allocator(); const queue_key = try keyJoin(a, &.{ self.prefix, "queue" }); const stream_key = try keyJoin(a, &.{ self.prefix, "stream" }); const now_str = try std.fmt.allocPrint(a, "{d}", .{now_micros}); const keys = [_][]const u8{ queue_key, stream_key }; const argv = [_][]const u8{ now_str, self.prefix }; const reply = try self.engine.eval(a, PROMOTE_DUE_LUA, &keys, &argv); return switch (reply) { .array => |arr| blk: { if (arr.len != 2) return error.UnexpectedPromoteReply; const total = switch (arr[0]) { .integer => |i| i, else => return error.UnexpectedPromoteReply, }; const promoted = switch (arr[1]) { .integer => |i| i, else => return error.UnexpectedPromoteReply, }; break :blk .{ .total_in_queue = total, .promoted = promoted }; }, .err => |msg| { std.log.warn("promote_due lua error: {s}", .{msg}); return error.RedisCommandFailed; }, else => error.UnexpectedPromoteReply, }; } pub fn ackMessage( self: *MemoryBackend, group: []const u8, msg_id: []const u8, task_key: []const u8, terminal_state: []const u8, execution_ttl_seconds: i64, ) !void { var arena = std.heap.ArenaAllocator.init(self.allocator); defer arena.deinit(); const a = arena.allocator(); const stream_key = try keyJoin(a, &.{ self.prefix, "stream" }); const runs_key = try keyJoin(a, &.{ self.prefix, "runs", task_key }); const ttl_str = try std.fmt.allocPrint(a, "{d}", .{execution_ttl_seconds}); const keys = [_][]const u8{ stream_key, runs_key }; const argv = [_][]const u8{ group, msg_id, terminal_state, ttl_str }; const reply = try self.engine.eval(a, ACK_LUA, &keys, &argv); switch (reply) { .bulk_string => |s| if (!std.mem.eql(u8, s, "OK")) return error.UnexpectedAckReply, .status => |s| if (!std.mem.eql(u8, s, "OK")) return error.UnexpectedAckReply, .err => return error.RedisCommandFailed, else => return error.UnexpectedAckReply, } } pub fn ensureConsumerGroup(self: *MemoryBackend, group: []const u8) !void { var arena = std.heap.ArenaAllocator.init(self.allocator); defer arena.deinit(); const a = arena.allocator(); const stream_key = try keyJoin(a, &.{ self.prefix, "stream" }); self.store.xgroupCreate(stream_key, group, .{ .id = burner.store.StreamId.zero(), .mkstream = true, }) catch |err| switch (err) { burner.store.StoreError.BusyGroup => return, // idempotent else => return err, }; } /// XAUTOCLAIM one idle pending entry — see `RedisBackend.reclaimIdle`. /// The returned slices live in `read_arena`, so a claimed message must be /// handled before the next `reclaimIdle` or `consumeStream` call. pub fn reclaimIdle( self: *MemoryBackend, group: []const u8, consumer: []const u8, min_idle_ms: u32, ) !?redis.StreamEntry { self.read_arena.deinit(); self.read_arena = std.heap.ArenaAllocator.init(self.allocator); const a = self.read_arena.allocator(); const stream_key = try keyJoin(a, &.{ self.prefix, "stream" }); const result = self.store.xautoclaim( a, stream_key, group, consumer, @intCast(min_idle_ms), burner.store.StreamId.zero(), 1, ) catch |err| switch (err) { burner.store.StoreError.NoGroup => return null, else => return err, }; if (result.deleted_ids.len > 0) { _ = self.store.xack(stream_key, group, result.deleted_ids) catch {}; } if (result.claimed.len == 0) return null; const de = result.claimed[0]; const id_str = try std.fmt.allocPrint(a, "{d}-{d}", .{ de.id.ms, de.id.seq }); var fields = try a.alloc(redis.StreamField, de.fields.len); for (de.fields, 0..) |p, i| { fields[i] = .{ .field = p.field, .value = p.value }; } return .{ .id = id_str, .fields = fields }; } /// XREADGROUP one entry. Returns null if no new messages. The returned /// StreamEntry's slices live in `self.read_arena`, valid until the next /// call to consumeStream. This matches the redis client's semantics /// (StreamEntry references the client's read buffer). pub fn consumeStream( self: *MemoryBackend, group: []const u8, consumer: []const u8, block_ms: u32, ) !?redis.StreamEntry { // Reset the read arena so the previous call's slices stop being valid. self.read_arena.deinit(); self.read_arena = std.heap.ArenaAllocator.init(self.allocator); const a = self.read_arena.allocator(); const stream_key = try keyJoin(a, &.{ self.prefix, "stream" }); const delivered = try self.store.xreadgroupOne(a, stream_key, group, consumer, .new_messages, 1); if (delivered.len == 0) { // No entries — sleep for `block_ms` so the worker doesn't busy-loop. // sleep is itself an Io cancellation point, so this is also where // a Worker.runForever in-flight cancel actually lands. if (block_ms > 0) { std.Io.sleep(self.store.io, std.Io.Duration.fromMilliseconds(@intCast(block_ms)), .real) catch |err| switch (err) { error.Canceled => return error.Canceled, }; } return null; } const de = delivered[0]; // Format id as "ms-seq" and copy fields into arena-owned StreamField // slices so the StreamEntry matches the redis client's shape. const id_str = try std.fmt.allocPrint(a, "{d}-{d}", .{ de.id.ms, de.id.seq }); var fields = try a.alloc(redis.StreamField, de.fields.len); for (de.fields, 0..) |p, i| { fields[i] = .{ .field = p.field, .value = p.value }; } return .{ .id = id_str, .fields = fields }; } }; /// Build a Redis key from colon-joined parts. Caller owns the result. fn keyJoin(alloc: Allocator, parts: []const []const u8) ![]const u8 { var total: usize = 0; for (parts, 0..) |p, i| { total += p.len; if (i + 1 < parts.len) total += 1; } const out = try alloc.alloc(u8, total); var pos: usize = 0; for (parts, 0..) |p, i| { @memcpy(out[pos..][0..p.len], p); pos += p.len; if (i + 1 < parts.len) { out[pos] = ':'; pos += 1; } } return out; }