//! Redis client connection and command execution //! //! This module provides the core `Client` type which manages: //! - TCP connection to Redis //! - Buffer management for reads/writes //! - RESP protocol serialization/deserialization //! - Authentication and database selection //! //! ## Memory Model //! //! The client owns a read buffer (for inline bulk-string content) and a //! per-command arena (for `Value.array` backing `[]Value` slices). Both //! are reset/invalidated at the start of every `sendCommand`, so every //! slice returned by a command is valid only until the next command. //! //! Concretely: //! - `Value.string` / `Value.bulk` / `Value.err` byte slices → read_buf //! - `Value.array` `[]Value` backing → arena //! //! For data that must outlive the next command, copy it: //! ```zig //! const ephemeral = try client.get("key"); //! const owned = try allocator.dupe(u8, ephemeral orelse return); //! defer allocator.free(owned); //! ``` //! //! Callers do NOT need to call `freeValue` — it's a no-op kept only for //! source compatibility with older client versions. //! //! ## Thread Safety //! //! A single `Client` instance is NOT thread-safe. For concurrent access: //! - Create one client per thread //! - Use external synchronization (mutex) //! - Use a connection pool (not provided here) const std = @import("std"); const Io = std.Io; const net = Io.net; const Allocator = std.mem.Allocator; const resp = @import("resp.zig"); pub const Value = resp.Value; pub const ConnectionError = resp.ConnectionError; pub const ProtocolError = resp.ProtocolError; pub const CommandError = resp.CommandError; pub const ClientError = resp.ClientError; /// Redis client with connection and buffer management. /// /// The client is designed for simplicity and efficiency: /// - Single TCP connection (no pipelining yet) /// - Owned read buffer (grows as needed) /// - Stack-allocated command buffer for small commands pub const Client = struct { const Self = @This(); io: Io, stream: net.Stream, allocator: Allocator, read_buf: []u8, buf_len: usize = 0, buf_pos: usize = 0, read_timeout_ms: i32 = 0, write_timeout_ms: i32 = 0, /// Per-command arena. Backs the `Value.array` (`[]Value`) trees /// returned by `sendCommand`. Reset (not deinited) at the start of /// every command, so the previously-returned Value's nested array /// allocations are freed in one shot without forcing callers to /// recursively traverse and free the tree themselves. /// /// Bulk-string slices still reference `read_buf` — that contract is /// unchanged: they remain valid until the next command, the same /// lifetime as the arena. response_arena: std.heap.ArenaAllocator, /// Stack buffer for small commands (16KB covers most cases) cmd_buf: [16384]u8 = undefined, /// Read buffers retired by mid-response growth. A response larger than /// the current read buffer used to be `realloc`ed, which moves the /// allocation and dangles every bulk slice already parsed from it. /// Instead, growth copies into a fresh buffer and retires the old one /// here; retired buffers are freed at the start of the next command, /// which is exactly the documented lifetime of returned slices. retired_bufs: std.ArrayList([]u8) = .empty, /// Heap buffer for large commands (allocated on demand) heap_cmd_buf: ?[]u8 = null, const DEFAULT_READ_BUF_SIZE = 65536; // ======================================================================== // Configuration // ======================================================================== /// Connection configuration pub const Config = struct { host: []const u8 = "localhost", port: u16 = 6379, username: []const u8 = "default", password: []const u8 = "", db: u8 = 0, /// Read buffer size (default 64KB) read_buffer_size: usize = DEFAULT_READ_BUF_SIZE, /// Max milliseconds to wait for the socket to become readable before a /// read fails with `ProtocolError.Timeout`. 0 = block forever. read_timeout_ms: i32 = 0, /// Max milliseconds to wait for the socket to become writable before a /// write fails with `ProtocolError.Timeout`. 0 = block forever. write_timeout_ms: i32 = 0, }; // ======================================================================== // Connection // ======================================================================== /// Connect to Redis with minimal configuration. /// Use `connectWithConfig` for full control. pub fn connect(io: Io, allocator: Allocator, host: []const u8, port: u16) ClientError!Self { return connectWithConfig(io, allocator, .{ .host = host, .port = port }); } /// Connect to Redis with full configuration. pub fn connectWithConfig(io: Io, allocator: Allocator, config: Config) ClientError!Self { // Resolve address: try numeric IP first, then DNS const tcp_stream = if (std.mem.eql(u8, config.host, "localhost")) blk: { const address = net.IpAddress{ .ip4 = net.Ip4Address.loopback(config.port) }; break :blk address.connect(io, .{ .mode = .stream }) catch |err| switch (err) { error.Canceled => return error.Canceled, else => return ConnectionError.ConnectionRefused, }; } else if (net.IpAddress.parse(config.host, config.port)) |address| blk: { break :blk address.connect(io, .{ .mode = .stream }) catch |err| switch (err) { error.Canceled => return error.Canceled, else => return ConnectionError.ConnectionRefused, }; } else |_| blk: { const host_name = net.HostName.init(config.host) catch { return ConnectionError.AddressResolutionFailed; }; break :blk host_name.connect(io, config.port, .{ .mode = .stream }) catch |err| switch (err) { error.Canceled => return error.Canceled, else => return ConnectionError.AddressResolutionFailed, }; }; errdefer tcp_stream.close(io); const read_buf = try allocator.alloc(u8, config.read_buffer_size); errdefer allocator.free(read_buf); var self = Self{ .io = io, .stream = tcp_stream, .allocator = allocator, .read_buf = read_buf, .read_timeout_ms = config.read_timeout_ms, .write_timeout_ms = config.write_timeout_ms, .response_arena = std.heap.ArenaAllocator.init(allocator), }; // Authenticate if password provided if (config.password.len > 0) { const result = try self.sendCommand(&.{ "AUTH", config.username, config.password }); if (result.isError()) return ConnectionError.AuthenticationFailed; } // Select database if non-default if (config.db != 0) { var db_buf: [4]u8 = undefined; const db_str = std.fmt.bufPrint(&db_buf, "{d}", .{config.db}) catch unreachable; const result = try self.sendCommand(&.{ "SELECT", db_str }); if (result.isError()) return ConnectionError.InvalidDatabase; } return self; } /// Close the connection and free resources. pub fn close(self: *Self) void { if (self.heap_cmd_buf) |buf| { self.allocator.free(buf); } for (self.retired_bufs.items) |buf| self.allocator.free(buf); self.retired_bufs.deinit(self.allocator); self.allocator.free(self.read_buf); self.response_arena.deinit(); self.stream.close(self.io); } // ======================================================================== // Command Execution (Core) // ======================================================================== /// Send a command and receive the response. /// This is the foundation for all other commands. /// /// Arguments must be string slices. For integer arguments, /// format them to a buffer first: /// ```zig /// var buf: [16]u8 = undefined; /// const n_str = std.fmt.bufPrint(&buf, "{d}", .{n}) catch unreachable; /// try client.sendCommand(&.{"EXPIRE", key, n_str}); /// ``` pub fn sendCommand(self: *Self, args: []const []const u8) ClientError!Value { // Drop everything the previous command's reply allocated. Bulk // slices reference `read_buf` and are about to be invalidated by // the new response anyway, so the documented "valid until the // next command" lifetime aligns exactly with this reset. _ = self.response_arena.reset(.retain_capacity); for (self.retired_bufs.items) |buf| self.allocator.free(buf); self.retired_bufs.clearRetainingCapacity(); // Calculate required buffer size var total_size: usize = 16; // header overhead for (args) |arg| { total_size += 16 + arg.len; // $\r\n\r\n } // Get command buffer (stack or heap) const cmd_buf = try self.getCommandBuffer(total_size); // Build RESP array var pos: usize = 0; // Array header: *\r\n pos += (std.fmt.bufPrint(cmd_buf[pos..], "*{d}\r\n", .{args.len}) catch { return ProtocolError.BufferOverflow; }).len; // Each argument as bulk string: $\r\n\r\n for (args) |arg| { pos += (std.fmt.bufPrint(cmd_buf[pos..], "${d}\r\n", .{arg.len}) catch { return ProtocolError.BufferOverflow; }).len; @memcpy(cmd_buf[pos..][0..arg.len], arg); pos += arg.len; cmd_buf[pos] = '\r'; cmd_buf[pos + 1] = '\n'; pos += 2; } // Send command try self.waitReady(std.posix.POLL.OUT, self.write_timeout_ms); var write_buf: [4096]u8 = undefined; var writer = self.stream.writer(self.io, &write_buf); writer.interface.writeAll(cmd_buf[0..pos]) catch |err| switch (err) { error.WriteFailed => return writer.err orelse ProtocolError.ConnectionClosed, }; writer.interface.flush() catch |err| switch (err) { error.WriteFailed => return writer.err orelse ProtocolError.ConnectionClosed, }; // Reset buffer state for new response self.buf_len = 0; self.buf_pos = 0; // Read and parse response return self.readResponse(); } /// Send a command with a pre-built argument array. /// Useful when the argument count is dynamic. pub fn sendCommandDynamic(self: *Self, comptime prefix: []const []const u8, suffix: []const []const u8) ClientError!Value { const total_len = prefix.len + suffix.len; var args = try self.allocator.alloc([]const u8, total_len); defer self.allocator.free(args); inline for (prefix, 0..) |p, i| { args[i] = p; } @memcpy(args[prefix.len..], suffix); return self.sendCommand(args); } // ======================================================================== // Buffer Management // ======================================================================== fn getCommandBuffer(self: *Self, required_size: usize) ClientError![]u8 { if (required_size <= self.cmd_buf.len) { return &self.cmd_buf; } // Need heap allocation for large command if (self.heap_cmd_buf) |buf| { if (buf.len >= required_size) return buf; } const replacement = try self.allocator.alloc(u8, required_size); if (self.heap_cmd_buf) |buf| self.allocator.free(buf); self.heap_cmd_buf = replacement; return replacement; } fn readResponse(self: *Self) ClientError!Value { // Ensure we have at least one byte if (self.buf_len == 0) { const n = try self.readFromStream(self.read_buf); if (n == 0) return ProtocolError.ConnectionClosed; self.buf_len = n; } return self.parseValue(); } fn parseValue(self: *Self) ClientError!Value { // Ensure we have data while (self.buf_pos >= self.buf_len) { try self.readMore(); } const type_char = self.read_buf[self.buf_pos]; self.buf_pos += 1; return switch (type_char) { '+' => .{ .string = try self.readLine() }, '-' => .{ .err = try self.readLine() }, ':' => .{ .integer = try self.readInt() }, '$' => try self.readBulk(), '*' => try self.readArray(), else => ProtocolError.InvalidResponse, }; } fn readLine(self: *Self) ClientError![]const u8 { const start = self.buf_pos; while (true) { while (self.buf_pos + 1 < self.buf_len) { if (self.read_buf[self.buf_pos] == '\r' and self.read_buf[self.buf_pos + 1] == '\n') { const line = self.read_buf[start..self.buf_pos]; self.buf_pos += 2; return line; } self.buf_pos += 1; } try self.readMore(); } } fn readInt(self: *Self) ClientError!i64 { const line = try self.readLine(); return std.fmt.parseInt(i64, line, 10) catch ProtocolError.InvalidResponse; } fn readBulk(self: *Self) ClientError!Value { const len = try self.readInt(); if (len < 0) return .nil; const ulen: usize = @intCast(len); // Ensure we have all the data while (self.buf_pos + ulen + 2 > self.buf_len) { try self.readMore(); } const data = self.read_buf[self.buf_pos..][0..ulen]; self.buf_pos += ulen + 2; return .{ .bulk = data }; } /// Allocate the `[]Value` backing for an array reply from the /// response_arena instead of the heap. Bulk children inside still /// reference `read_buf` (same lifetime), and the next sendCommand /// drops the whole tree in one reset. fn readArray(self: *Self) ClientError!Value { const len = try self.readInt(); if (len < 0) return .nil; if (len == 0) return .{ .array = &.{} }; const ulen: usize = @intCast(len); // Arena-allocated: no individual free, reset on next sendCommand. const values = try self.response_arena.allocator().alloc(Value, ulen); for (0..ulen) |i| { values[i] = try self.parseValue(); } return .{ .array = values }; } /// Reserve decoding space for one bulk reply of at most `payload_len` bytes. /// Existing response slices remain valid until the next sendCommand. Growth /// preserves their backing storage, which close or the next command releases. /// This does not reserve array metadata or command-encoding storage, nor does /// it prevent transport errors. A later larger reply may still allocate. pub fn reserveBulkReply(self: *Self, payload_len: usize) ClientError!void { var header_buf: [32]u8 = undefined; const header = std.fmt.bufPrint(&header_buf, "${d}\r\n", .{payload_len}) catch return error.BufferOverflow; const framed_len = std.math.add(usize, payload_len, header.len + 2) catch return error.BufferOverflow; if (framed_len <= self.read_buf.len) return; const new_buf = try self.allocator.alloc(u8, framed_len); errdefer self.allocator.free(new_buf); @memcpy(new_buf[0..self.buf_len], self.read_buf[0..self.buf_len]); try self.retired_bufs.append(self.allocator, self.read_buf); self.read_buf = new_buf; } fn readMore(self: *Self) ClientError!void { // Grow buffer if needed. Copy + retire rather than realloc: realloc // may move the allocation, dangling bulk slices already parsed from // the old buffer mid-response. if (self.buf_len >= self.read_buf.len) { const new_buf = try self.allocator.alloc(u8, self.read_buf.len * 2); errdefer self.allocator.free(new_buf); @memcpy(new_buf[0..self.buf_len], self.read_buf[0..self.buf_len]); try self.retired_bufs.append(self.allocator, self.read_buf); self.read_buf = new_buf; } const n = try self.readFromStream(self.read_buf[self.buf_len..]); if (n == 0) return ProtocolError.ConnectionClosed; self.buf_len += n; } fn readFromStream(self: *Self, dest: []u8) ClientError!usize { try self.waitReady(std.posix.POLL.IN, self.read_timeout_ms); var empty: [0]u8 = .{}; var reader = self.stream.reader(self.io, &empty); var bufs = [_][]u8{dest}; return reader.interface.readVec(&bufs) catch |err| switch (err) { error.EndOfStream => return 0, error.ReadFailed => return reader.err orelse ProtocolError.ConnectionClosed, }; } /// Wait for the socket to become ready for `events` (POLL.IN / POLL.OUT), /// failing with `ConnectionError.Timeout` after `timeout_ms`. A timeout of /// 0 (the default) preserves the historical block-forever behavior. Done /// via poll(2) rather than SO_RCVTIMEO: the socket stays blocking, so the /// Io runtime never sees an EAGAIN it considers unreachable. fn waitReady(self: *Self, events: i16, timeout_ms: i32) ClientError!void { if (timeout_ms <= 0) return; var fds = [_]std.posix.pollfd{.{ .fd = self.stream.socket.handle, .events = events, .revents = 0, }}; const ready = std.posix.poll(&fds, timeout_ms) catch { return ProtocolError.ConnectionClosed; }; if (ready == 0) return ProtocolError.Timeout; } // ======================================================================== // Connection Commands // ======================================================================== /// Send PING, returns true if server responds with PONG. pub fn ping(self: *Self) ClientError!bool { const result = try self.sendCommand(&.{"PING"}); return switch (result) { .string => |s| std.mem.eql(u8, s, "PONG"), else => false, }; } /// Send ECHO, returns the message back. pub fn echo(self: *Self, message: []const u8) ClientError!?[]const u8 { const result = try self.sendCommand(&.{ "ECHO", message }); return result.asString(); } /// Get server info. pub fn info(self: *Self, section: ?[]const u8) ClientError!?[]const u8 { const result = if (section) |s| try self.sendCommand(&.{ "INFO", s }) else try self.sendCommand(&.{"INFO"}); return result.asString(); } /// Get number of keys in current database. pub fn dbsize(self: *Self) ClientError!i64 { const result = try self.sendCommand(&.{"DBSIZE"}); return result.asInt() orelse 0; } /// Delete all keys in current database (use with caution!). pub fn flushDb(self: *Self) ClientError!void { const result = try self.sendCommand(&.{"FLUSHDB"}); if (result.isError()) return CommandError.RedisError; } // ======================================================================== // Command Module Accessors // ======================================================================== const strings_mod = @import("commands/strings.zig"); const keys_mod = @import("commands/keys.zig"); const hashes_mod = @import("commands/hashes.zig"); const lists_mod = @import("commands/lists.zig"); const sets_mod = @import("commands/sets.zig"); const sorted_sets_mod = @import("commands/sorted_sets.zig"); const streams_mod = @import("commands/streams.zig"); /// Get string commands interface pub fn strings(self: *Self) strings_mod.StringCommands { return strings_mod.StringCommands.init(self); } /// Get key commands interface pub fn keys(self: *Self) keys_mod.KeyCommands { return keys_mod.KeyCommands.init(self); } /// Get hash commands interface pub fn hashes(self: *Self) hashes_mod.HashCommands { return hashes_mod.HashCommands.init(self); } /// Get list commands interface pub fn lists(self: *Self) lists_mod.ListCommands { return lists_mod.ListCommands.init(self); } /// Get set commands interface pub fn sets(self: *Self) sets_mod.SetCommands { return sets_mod.SetCommands.init(self); } /// Get sorted set commands interface pub fn sortedSets(self: *Self) sorted_sets_mod.SortedSetCommands { return sorted_sets_mod.SortedSetCommands.init(self); } /// Get stream commands interface pub fn streams(self: *Self) streams_mod.StreamCommands { return streams_mod.StreamCommands.init(self); } // ======================================================================== // Value Management // ======================================================================== /// No-op since v0.2: Value trees are now arena-allocated and freed /// automatically at the start of the next `sendCommand`. Kept as a /// no-op for source compatibility with callers that still invoke it. pub fn freeValue(_: *Self, _: Value) void {} /// Allocator backing the per-command response arena. Use this for /// any parsed-reply structures (typed array results like /// `[]StreamEntry`) that need to live as long as the returned Value /// tree — they all get freed together at the next `sendCommand`. pub fn responseAlloc(self: *Self) Allocator { return self.response_arena.allocator(); } }; // ============================================================================ // Tests // ============================================================================ test "Client struct size is reasonable" { // Ensure the client doesn't grow unexpectedly try std.testing.expect(@sizeOf(Client) < 20000); } test "read_timeout_ms fails a read on a silent server" { var threaded: std.Io.Threaded = .init(std.testing.allocator, .{}); defer threaded.deinit(); const io = threaded.io(); // A "redis server" that accepts and then never says anything. var listen_addr = net.IpAddress{ .ip4 = net.Ip4Address.loopback(0) }; var server = try listen_addr.listen(io, .{}); defer server.deinit(io); const port = server.socket.address.ip4.port; var client = try Client.connectWithConfig(io, std.testing.allocator, .{ .host = "localhost", .port = port, .read_timeout_ms = 100, }); defer client.close(); // If the timeout doesn't fire this blocks forever and the test run hangs, // which is exactly the regression this guards against. try std.testing.expectError(ProtocolError.Timeout, client.ping()); } fn connectWithPendingCancel(io: Io, gate: *Io.Event, host: []const u8, port: u16) ClientError!void { gate.wait(io) catch |err| switch (err) { error.Canceled => io.recancel(), }; var client = try Client.connectWithConfig(io, std.testing.allocator, .{ .host = host, .port = port }); client.close(); } test "connect propagates error.Canceled" { var threaded: std.Io.Threaded = .init(std.testing.allocator, .{}); defer threaded.deinit(); const io = threaded.io(); var listen_addr = net.IpAddress{ .ip4 = net.Ip4Address.loopback(0) }; var server = try listen_addr.listen(io, .{}); defer server.deinit(io); const port = server.socket.address.ip4.port; for ([_][]const u8{ "localhost", "127.0.0.1", "redis.localhost" }) |host| { var gate: Io.Event = .unset; var fut = try io.concurrent(connectWithPendingCancel, .{ io, &gate, host, port }); try std.testing.expectError(error.Canceled, fut.cancel(io)); } }