interactive shell navigation and history
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315const std = @import("std");const assert = std.debug.assert;const input_output = @import("input_output.zig");
pub const Memcached = struct { allocator: std.mem.Allocator, stream: std.Io.net.Stream, read_buffer: [65536]u8 = @splat(0), write_buffer: [4096]u8 = @splat(0), stream_reader: ?std.Io.net.Stream.Reader = null, stream_writer: ?std.Io.net.Stream.Writer = null,
const chunk_size: usize = 900 * 1024; const chunk_prefix = "\x00chunked:";
pub const max_value_bytes: usize = 64 * 1024 * 1024;
pub fn init(allocator: std.mem.Allocator, host: []const u8, port: u16) !Memcached { assert(host.len > 0); assert(port > 0); const address = try std.Io.net.IpAddress.parseIp4(host, port); const stream = try address.connect(input_output.runtime(), .{ .mode = .stream }); return .{ .allocator = allocator, .stream = stream, }; }
pub fn deinit(self: *Memcached) void { if (self.stream_writer) |*pending| { pending.interface.flush() catch |err| { input_output.warn("failed to flush memcached on deinit: {}\n", .{err}); }; } self.stream.close(input_output.runtime()); }
fn ensureStarted(self: *Memcached) void { if (self.stream_reader != null) { return; } self.stream_reader = self.stream.reader(input_output.runtime(), &self.read_buffer); self.stream_writer = self.stream.writer(input_output.runtime(), &self.write_buffer); }
fn reader(self: *Memcached) *std.Io.Reader { self.ensureStarted(); return &self.stream_reader.?.interface; }
fn writer(self: *Memcached) *std.Io.Writer { self.ensureStarted(); return &self.stream_writer.?.interface; }
fn flushWrite(self: *Memcached) !void { try self.writer().flush(); }
fn bufferedWrite(self: *Memcached, data: []const u8) !void { assert(data.len > 0); try self.writer().writeAll(data); }
pub fn set(self: *Memcached, key: []const u8, value: []const u8, exptime: u32) !void { assertValidKey(key); if (value.len > max_value_bytes) { return error.ValueTooLarge; } if (value.len <= chunk_size) { try self.sendSet(key, value, exptime); try self.flushWrite(); return; }
const chunk_count = try std.math.divCeil(usize, value.len, chunk_size); var meta_buffer: [128]u8 = undefined; const meta = try std.fmt.bufPrint(&meta_buffer, chunk_prefix ++ "{d}:{d}", .{ chunk_count, value.len, }); try self.sendSet(key, meta, exptime);
var index: usize = 0; while (index < chunk_count) : (index += 1) { const start = index * chunk_size; const end = @min((index + 1) * chunk_size, value.len); var chunk_key_buffer: [512]u8 = undefined; const chunk_key = try formatChunkKey(&chunk_key_buffer, key, value.len, index); try self.sendSet(chunk_key, value[start..end], exptime); } try self.flushWrite(); }
fn sendSet(self: *Memcached, key: []const u8, value: []const u8, exptime: u32) !void { assertValidKey(key); var header_buffer: [512]u8 = undefined; const header = try std.fmt.bufPrint(&header_buffer, "ms {s} {d} T{d} q\r\n", .{ key, value.len, exptime, });
try self.bufferedWrite(header); if (value.len > 0) { try self.bufferedWrite(value); } try self.bufferedWrite("\r\n"); }
/// Returns the next CRLF-terminated line, without the terminator. The /// slice points into the read buffer and stays valid until the next /// read. fn readLine(self: *Memcached) !?[]const u8 { const line = self.reader().takeDelimiterInclusive('\n') catch |err| { return switch (err) { error.EndOfStream => null, error.StreamTooLong => error.LineTooLong, else => err, }; }; return std.mem.trim(u8, line, "\r\n"); }
fn readExact(self: *Memcached, buffer: []u8) !void { assert(buffer.len > 0); self.reader().readSliceAll(buffer) catch |err| { if (err == error.EndOfStream) { return error.IncompleteRead; } return err; }; }
fn consumeCrlf(self: *Memcached) void { const input = self.reader(); const first = input.peekByte() catch return; if (first == '\r') { input.toss(1); const second = input.peekByte() catch return; if (second == '\n') { input.toss(1); } return; } if (first == '\n') { input.toss(1); } }
pub fn get(self: *Memcached, key: []const u8) !?[]u8 { assertValidKey(key); var command_buffer: [512]u8 = undefined; const command_text = try std.fmt.bufPrint(&command_buffer, "mg {s} v\r\n", .{key}); try self.bufferedWrite(command_text); try self.flushWrite();
const line = (try self.readLine()) orelse return null;
if (!std.mem.startsWith(u8, line, "VA ")) { return null; } const rest = line["VA ".len..]; const space_index = std.mem.indexOfScalar(u8, rest, ' ') orelse rest.len; const size = try std.fmt.parseInt(usize, rest[0..space_index], 10); if (size > max_value_bytes) { return error.ValueTooLarge; }
const data = try self.allocator.alloc(u8, size); errdefer self.allocator.free(data);
if (size > 0) { try self.readExact(data); }
self.consumeCrlf();
if (std.mem.startsWith(u8, data, chunk_prefix)) { defer self.allocator.free(data); return try self.reassembleChunks(key, data); }
return data; }
fn reassembleChunks(self: *Memcached, key: []const u8, meta: []const u8) ![]u8 { assertValidKey(key); const parsed = try parseChunkMeta(meta);
const result = try self.allocator.alloc(u8, parsed.total_bytes); errdefer self.allocator.free(result);
var index: usize = 0; while (index < parsed.chunk_count) : (index += 1) { var chunk_key_buffer: [512]u8 = undefined; const chunk_key = try formatChunkKey(&chunk_key_buffer, key, parsed.total_bytes, index);
var command_buffer: [512]u8 = undefined; const command_text = try std.fmt.bufPrint( &command_buffer, "mg {s} v\r\n", .{chunk_key}, ); try self.bufferedWrite(command_text); try self.flushWrite();
const line = (try self.readLine()) orelse return error.CacheChunkMissing;
if (!std.mem.startsWith(u8, line, "VA ")) { return error.CacheChunkMissing; }
const rest = line["VA ".len..]; const space_index = std.mem.indexOfScalar(u8, rest, ' ') orelse rest.len; const size = try std.fmt.parseInt(usize, rest[0..space_index], 10);
const chunk_start = index * chunk_size; const chunk_end = @min((index + 1) * chunk_size, parsed.total_bytes); if (size != chunk_end - chunk_start) { return error.InvalidChunkSize; }
if (size > 0) { try self.readExact(result[chunk_start..chunk_end]); }
self.consumeCrlf(); }
return result; }};
fn assertValidKey(key: []const u8) void { assert(key.len > 0); assert(key.len <= 400); for (key) |byte| { assert(byte != ' '); assert(byte != '\r'); assert(byte != '\n'); }}
const ChunkMeta = struct { chunk_count: usize, total_bytes: usize,};
fn parseChunkMeta(meta: []const u8) !ChunkMeta { assert(meta.len > Memcached.chunk_prefix.len); assert(std.mem.startsWith(u8, meta, Memcached.chunk_prefix)); var fields = std.mem.splitScalar(u8, meta[Memcached.chunk_prefix.len..], ':'); const chunk_count_text = fields.next() orelse return error.InvalidCacheData; const total_bytes_text = fields.next() orelse return error.InvalidCacheData;
const chunk_count = std.fmt.parseInt(usize, chunk_count_text, 10) catch { return error.InvalidCacheData; }; const total_bytes = std.fmt.parseInt(usize, total_bytes_text, 10) catch { return error.InvalidCacheData; }; if (chunk_count == 0) { return error.InvalidCacheData; } if (total_bytes > Memcached.max_value_bytes) { return error.ValueTooLarge; } const expected_count = try std.math.divCeil(usize, total_bytes, Memcached.chunk_size); if (chunk_count != expected_count) { return error.InvalidCacheData; } return .{ .chunk_count = chunk_count, .total_bytes = total_bytes };}
fn formatChunkKey(buffer: *[512]u8, key: []const u8, total_bytes: usize, index: usize) ![]const u8 { assertValidKey(key); assert(total_bytes <= Memcached.max_value_bytes); assert(total_bytes > 0); return std.fmt.bufPrint(buffer, "{s}:{d}:{d}", .{ key, total_bytes, index });}
const testing = std.testing;
test "parseChunkMeta: accepts a consistent header" { const meta = try parseChunkMeta("\x00chunked:3:2500000"); try testing.expectEqual(@as(usize, 3), meta.chunk_count); try testing.expectEqual(@as(usize, 2500000), meta.total_bytes);}
test "parseChunkMeta: rejects zero chunks" { try testing.expectError(error.InvalidCacheData, parseChunkMeta("\x00chunked:0:0"));}
test "parseChunkMeta: rejects inconsistent counts" { try testing.expectError(error.InvalidCacheData, parseChunkMeta("\x00chunked:2:2500000")); try testing.expectError(error.InvalidCacheData, parseChunkMeta("\x00chunked:9:2500000"));}
test "parseChunkMeta: rejects oversize totals" { try testing.expectError(error.ValueTooLarge, parseChunkMeta("\x00chunked:73:67108865"));}
test "parseChunkMeta: rejects malformed fields" { try testing.expectError(error.InvalidCacheData, parseChunkMeta("\x00chunked:3")); try testing.expectError(error.InvalidCacheData, parseChunkMeta("\x00chunked:three:2500000")); try testing.expectError(error.InvalidCacheData, parseChunkMeta("\x00chunked:3:lots"));}
test "formatChunkKey: namespaces chunks by total length" { var buffer: [512]u8 = undefined; const key = try formatChunkKey(&buffer, "magdalena:look:directory:9:1:3", 2500000, 2); try testing.expectEqualStrings("magdalena:look:directory:9:1:3:2500000:2", key);}