| 1 |
const bincode = @import("../bincode.zig"); |
| 2 |
const std = @import("std"); |
| 3 |
const shared = @import("../shared.zig"); |
| 4 |
|
| 5 |
const fs = std.fs; |
| 6 |
const os = std.os; |
| 7 |
const mem = std.mem; |
| 8 |
const Allocator = std.mem.Allocator; |
| 9 |
const Path = []const u8; |
| 10 |
pub const Command = shared.Command; |
| 11 |
|
| 12 |
extern "c" fn mkfifo(path: [*:0]const u8, mode: c_uint) c_int; |
| 13 |
|
| 14 |
/// Wait until `fd` is readable, returning `error.AckTimeout` if no data |
| 15 |
/// arrives within `timeout_ns`. Used to gate blocking reads so we never |
| 16 |
/// consume bytes from a partially-written FIFO frame and lose framing. |
| 17 |
fn waitReadable(fd: std.posix.fd_t, timeout_ns: u64) !void { |
| 18 |
var pfd = [_]std.posix.pollfd{.{ |
| 19 |
.fd = fd, |
| 20 |
.events = std.posix.POLL.IN, |
| 21 |
.revents = 0, |
| 22 |
}}; |
| 23 |
const ms_total = timeout_ns / std.time.ns_per_ms; |
| 24 |
const timeout_ms: i32 = if (ms_total > std.math.maxInt(i32)) |
| 25 |
std.math.maxInt(i32) |
| 26 |
else |
| 27 |
@intCast(ms_total); |
| 28 |
const ready = std.posix.poll(&pfd, timeout_ms) catch return error.AckTimeout; |
| 29 |
if (ready == 0) return error.AckTimeout; |
| 30 |
} |
| 31 |
|
| 32 |
pub const Pipe = struct { |
| 33 |
pub const Reader = struct { |
| 34 |
file: fs.File, |
| 35 |
allocator: Allocator, |
| 36 |
buffer: std.ArrayList(u8), |
| 37 |
|
| 38 |
pub fn init(file: fs.File, allocator: Allocator) Reader { |
| 39 |
var buffer = std.ArrayList(u8).init(allocator); |
| 40 |
// Pre-allocate 1KB to avoid allocations for typical command sizes |
| 41 |
buffer.ensureTotalCapacity(1024) catch {}; |
| 42 |
return .{ |
| 43 |
.file = file, |
| 44 |
.allocator = allocator, |
| 45 |
.buffer = buffer, |
| 46 |
}; |
| 47 |
} |
| 48 |
|
| 49 |
pub fn read(self: *Reader, buffer: []u8) !usize { |
| 50 |
return self.file.read(buffer); |
| 51 |
} |
| 52 |
|
| 53 |
pub fn readAll(self: *Reader, buffer: []u8) !usize { |
| 54 |
return self.file.readAll(buffer); |
| 55 |
} |
| 56 |
|
| 57 |
// IMPORTANT: Caller is responsible for freeing the returned command. |
| 58 |
pub fn recvCmd(self: *Reader) !Command { |
| 59 |
// First read the length (u32 = 4 bytes) |
| 60 |
var len_buffer: [4]u8 = undefined; |
| 61 |
const len_read = self.file.readAll(&len_buffer) catch |err| { |
| 62 |
// Convert blocking/broken pipe errors to something the timeout logic can handle |
| 63 |
return switch (err) { |
| 64 |
error.WouldBlock, error.BrokenPipe => error.NotReady, |
| 65 |
else => err, |
| 66 |
}; |
| 67 |
}; |
| 68 |
if (len_read < 4) { |
| 69 |
return error.UnexpectedEof; |
| 70 |
} |
| 71 |
const message_len = std.mem.readInt(u32, &len_buffer, std.builtin.Endian.little); |
| 72 |
|
| 73 |
// Resize buffer to fit message (only allocates if growing) |
| 74 |
try self.buffer.resize(message_len); |
| 75 |
|
| 76 |
const msg_read = self.file.readAll(self.buffer.items) catch |err| { |
| 77 |
return switch (err) { |
| 78 |
error.WouldBlock, error.BrokenPipe => error.NotReady, |
| 79 |
else => err, |
| 80 |
}; |
| 81 |
}; |
| 82 |
if (msg_read < message_len) { |
| 83 |
return error.UnexpectedEof; |
| 84 |
} |
| 85 |
|
| 86 |
var stream = std.io.fixedBufferStream(self.buffer.items); |
| 87 |
return try bincode.deserializeAlloc(stream.reader(), self.allocator, Command); |
| 88 |
} |
| 89 |
|
| 90 |
pub fn waitForResponse(self: *Reader, timeout_ns: ?u64) !Command { |
| 91 |
const timeout = timeout_ns orelse std.time.ns_per_s * 1; // Default 1 second timeout |
| 92 |
try waitReadable(self.file.handle, timeout); |
| 93 |
return self.recvCmd(); |
| 94 |
} |
| 95 |
|
| 96 |
pub fn waitForAck(self: *Reader, timeout_ns: ?u64) !void { |
| 97 |
const response = try self.waitForResponse(timeout_ns); |
| 98 |
defer response.deinit(self.allocator); |
| 99 |
|
| 100 |
switch (response) { |
| 101 |
.Ack => return, |
| 102 |
.Err => return error.UnexpectedError, |
| 103 |
else => { |
| 104 |
const logger = @import("../logger.zig"); |
| 105 |
logger.debug("waitForAck received unexpected response: {}\n", .{response}); |
| 106 |
return error.UnexpectedResponse; |
| 107 |
}, |
| 108 |
} |
| 109 |
} |
| 110 |
|
| 111 |
pub fn deinit(self: *Reader) void { |
| 112 |
// Drain any pending data from the FIFO before closing to prevent |
| 113 |
// stale messages from being read by subsequent connections. |
| 114 |
// This is crucial when multiple instrument types probe the same FIFO |
| 115 |
// (e.g., AnalysisInstrument fails, then WalltimeInstrument tries). |
| 116 |
// The fd is blocking, so poll with timeout=0 to consume only what's |
| 117 |
// currently available without ever blocking on an empty FIFO. |
| 118 |
var dummy_buffer: [4096]u8 = undefined; |
| 119 |
while (true) { |
| 120 |
var pfd = [_]std.posix.pollfd{.{ |
| 121 |
.fd = self.file.handle, |
| 122 |
.events = std.posix.POLL.IN, |
| 123 |
.revents = 0, |
| 124 |
}}; |
| 125 |
const ready = std.posix.poll(&pfd, 0) catch break; |
| 126 |
if (ready == 0) break; |
| 127 |
const bytes_read = self.file.read(&dummy_buffer) catch break; |
| 128 |
if (bytes_read == 0) break; |
| 129 |
} |
| 130 |
|
| 131 |
self.buffer.deinit(); |
| 132 |
self.file.close(); |
| 133 |
} |
| 134 |
}; |
| 135 |
|
| 136 |
pub const Writer = struct { |
| 137 |
file: fs.File, |
| 138 |
allocator: Allocator, |
| 139 |
buffer: std.ArrayList(u8), |
| 140 |
|
| 141 |
pub fn init(file: fs.File, allocator: Allocator) Writer { |
| 142 |
var buffer = std.ArrayList(u8).init(allocator); |
| 143 |
// Pre-allocate 1KB to avoid allocations for typical command sizes |
| 144 |
buffer.ensureTotalCapacity(1024) catch {}; |
| 145 |
return .{ |
| 146 |
.file = file, |
| 147 |
.allocator = allocator, |
| 148 |
.buffer = buffer, |
| 149 |
}; |
| 150 |
} |
| 151 |
|
| 152 |
pub fn write(self: *Writer, buffer: []const u8) !usize { |
| 153 |
return self.file.write(buffer); |
| 154 |
} |
| 155 |
|
| 156 |
pub fn writeAll(self: *Writer, buffer: []const u8) !void { |
| 157 |
return self.file.writeAll(buffer); |
| 158 |
} |
| 159 |
|
| 160 |
pub fn sendCmd(self: *Writer, cmd: Command) !void { |
| 161 |
// Clear buffer but keep allocated capacity |
| 162 |
self.buffer.clearRetainingCapacity(); |
| 163 |
|
| 164 |
try bincode.serialize(self.buffer.writer(), cmd); |
| 165 |
|
| 166 |
const bytes = self.buffer.items; |
| 167 |
try self.file.writeAll(std.mem.asBytes(&@as(u32, @intCast(bytes.len)))); |
| 168 |
try self.file.writeAll(bytes); |
| 169 |
} |
| 170 |
|
| 171 |
pub fn deinit(self: *Writer) void { |
| 172 |
self.buffer.deinit(); |
| 173 |
self.file.close(); |
| 174 |
} |
| 175 |
}; |
| 176 |
|
| 177 |
/// Create a new named pipe at the given path |
| 178 |
pub fn create(path: [*:0]const u8) !void { |
| 179 |
// Remove the previous FIFO (if it exists) |
| 180 |
fs.deleteFileAbsolute(std.mem.span(path)) catch {}; |
| 181 |
|
| 182 |
if (mkfifo(path, 0o700) != 0) { |
| 183 |
return error.FifoCreationFailed; |
| 184 |
} |
| 185 |
} |
| 186 |
|
| 187 |
fn openPipe(path: []const u8) !fs.File { |
| 188 |
try fs.accessAbsolute(path, .{ .mode = .read_write }); |
| 189 |
return try fs.openFileAbsolute(path, .{ |
| 190 |
.mode = .read_write, |
| 191 |
}); |
| 192 |
} |
| 193 |
|
| 194 |
pub fn openRead(allocator: Allocator, path: []const u8) !Reader { |
| 195 |
const file = try openPipe(path); |
| 196 |
return Reader.init(file, allocator); |
| 197 |
} |
| 198 |
|
| 199 |
pub fn openWrite(allocator: Allocator, path: []const u8) !Writer { |
| 200 |
const file = try openPipe(path); |
| 201 |
return Writer.init(file, allocator); |
| 202 |
} |
| 203 |
}; |
| 204 |
|
| 205 |
pub fn sendCmd(allocator: Allocator, cmd: Command) !void { |
| 206 |
var writer = try Pipe.openWrite(allocator, shared.RUNNER_CTL_FIFO); |
| 207 |
defer writer.deinit(); |
| 208 |
try writer.sendCmd(cmd); |
| 209 |
|
| 210 |
var reader = try Pipe.openRead(allocator, shared.RUNNER_ACK_FIFO); |
| 211 |
defer reader.deinit(); |
| 212 |
try reader.waitForAck(null); |
| 213 |
} |
| 214 |
|
| 215 |
pub fn sendVersion(allocator: Allocator, protocol_version: u64) !void { |
| 216 |
const cmd = Command{ .SetVersion = protocol_version }; |
| 217 |
try sendCmd(allocator, cmd); |
| 218 |
} |
| 219 |
|
| 220 |
test "fail if doesn't exist" { |
| 221 |
const allocator = std.testing.allocator; |
| 222 |
|
| 223 |
const nonexistent_path = "/tmp/nonexistent_pipe_test.fifo"; |
| 224 |
|
| 225 |
// Ensure it doesn't exist |
| 226 |
fs.deleteFileAbsolute(nonexistent_path) catch {}; |
| 227 |
|
| 228 |
// Attempt to open for reading should fail |
| 229 |
const reader_result = Pipe.openRead(allocator, nonexistent_path); |
| 230 |
try std.testing.expectError(error.FileNotFound, reader_result); |
| 231 |
|
| 232 |
// Attempt to open for writing should fail |
| 233 |
const writer_result = Pipe.openWrite(allocator, nonexistent_path); |
| 234 |
try std.testing.expectError(error.FileNotFound, writer_result); |
| 235 |
|
| 236 |
// Attempt to send cmd to runner fifo |
| 237 |
fs.deleteFileAbsolute(shared.RUNNER_ACK_FIFO) catch {}; |
| 238 |
fs.deleteFileAbsolute(shared.RUNNER_CTL_FIFO) catch {}; |
| 239 |
|
| 240 |
const sendcmd_result = sendCmd(allocator, Command.StartBenchmark); |
| 241 |
try std.testing.expectError(error.FileNotFound, sendcmd_result); |
| 242 |
} |
| 243 |
|
| 244 |
test "unix pipe write read" { |
| 245 |
const allocator = std.testing.allocator; |
| 246 |
const test_path = "/tmp/test1.fifo"; |
| 247 |
|
| 248 |
try Pipe.create(test_path); |
| 249 |
|
| 250 |
var reader = try Pipe.openRead(allocator, test_path); |
| 251 |
defer reader.deinit(); |
| 252 |
|
| 253 |
var writer = try Pipe.openWrite(allocator, test_path); |
| 254 |
defer writer.deinit(); |
| 255 |
|
| 256 |
const message = "Hello"; |
| 257 |
try writer.writeAll(message); |
| 258 |
|
| 259 |
var buffer: [5]u8 = undefined; |
| 260 |
_ = try reader.readAll(&buffer); |
| 261 |
|
| 262 |
try std.testing.expectEqualStrings(message, &buffer); |
| 263 |
} |
| 264 |
|
| 265 |
test "unix pipe send recv cmd" { |
| 266 |
const allocator = std.testing.allocator; |
| 267 |
const test_path = "/tmp/test2.fifo"; |
| 268 |
|
| 269 |
try Pipe.create(test_path); |
| 270 |
|
| 271 |
var reader = try Pipe.openRead(allocator, test_path); |
| 272 |
defer reader.deinit(); |
| 273 |
|
| 274 |
var writer = try Pipe.openWrite(allocator, test_path); |
| 275 |
defer writer.deinit(); |
| 276 |
|
| 277 |
try writer.sendCmd(Command.StartBenchmark); |
| 278 |
const cmd = try reader.recvCmd(); |
| 279 |
defer cmd.deinit(writer.allocator); |
| 280 |
|
| 281 |
try std.testing.expectEqual(Command.StartBenchmark, cmd); |
| 282 |
} |
| 283 |
|
| 284 |
test "unix pipe send without ack" { |
| 285 |
const allocator = std.testing.allocator; |
| 286 |
const test_path = "/tmp/test_no_ack.fifo"; |
| 287 |
|
| 288 |
try Pipe.create(test_path); |
| 289 |
|
| 290 |
// Open both reader and writer so they don't block on open |
| 291 |
var reader = try Pipe.openRead(allocator, test_path); |
| 292 |
defer reader.deinit(); |
| 293 |
|
| 294 |
var writer = try Pipe.openWrite(allocator, test_path); |
| 295 |
defer writer.deinit(); |
| 296 |
|
| 297 |
// Writer doesn't send anything, so waitForResponse should timeout |
| 298 |
const result = reader.waitForResponse(std.time.ns_per_ms * 100); |
| 299 |
try std.testing.expectError(error.AckTimeout, result); |
| 300 |
} |
| 301 |
|
| 302 |
test "unix pipe prevents stale messages between connections" { |
| 303 |
const allocator = std.testing.allocator; |
| 304 |
const test_path = "/tmp/test_stale_messages.fifo"; |
| 305 |
|
| 306 |
try Pipe.create(test_path); |
| 307 |
|
| 308 |
// Keep writer open throughout to maintain the FIFO |
| 309 |
var writer = try Pipe.openWrite(allocator, test_path); |
| 310 |
defer writer.deinit(); |
| 311 |
|
| 312 |
// STEP 1: Simulate first connection |
| 313 |
{ |
| 314 |
var first_reader = try Pipe.openRead(allocator, test_path); |
| 315 |
|
| 316 |
// Send and successfully read first command |
| 317 |
try writer.sendCmd(Command.StartBenchmark); |
| 318 |
const cmd1 = try first_reader.recvCmd(); |
| 319 |
defer cmd1.deinit(allocator); |
| 320 |
try std.testing.expect(cmd1.equal(Command.StartBenchmark)); |
| 321 |
|
| 322 |
// Send second command but DON'T read it |
| 323 |
try writer.sendCmd(Command.StopBenchmark); |
| 324 |
|
| 325 |
// Close first reader WITHOUT reading the second command |
| 326 |
// This should drain the unread StopBenchmark message |
| 327 |
first_reader.deinit(); |
| 328 |
} |
| 329 |
|
| 330 |
// STEP 2: Simulate second connection |
| 331 |
{ |
| 332 |
var second_reader = try Pipe.openRead(allocator, test_path); |
| 333 |
defer second_reader.deinit(); |
| 334 |
|
| 335 |
// Send fresh command |
| 336 |
try writer.sendCmd(Command.Ack); |
| 337 |
|
| 338 |
// This should read the fresh Ack, NOT the stale StopBenchmark |
| 339 |
const cmd2 = try second_reader.recvCmd(); |
| 340 |
defer cmd2.deinit(allocator); |
| 341 |
|
| 342 |
// CRITICAL ASSERTION: We should receive the fresh Ack |
| 343 |
// Without the drain logic, this would fail with StopBenchmark |
| 344 |
try std.testing.expect(cmd2.equal(Command.Ack)); |
| 345 |
} |
| 346 |
} |