Files
zag/src/ipc.zig
T

447 lines
18 KiB
Zig

//! Local IPC between the zag CLI and the daemon: newline-delimited JSON over a Unix socket.
//!
//! request: {"type":"get_status","payload":{...}}
//! response: {"status":"ok","payload":...}
//! {"status":"error","error":{"code":"NOT_FOUND","message":"..."}}
//!
//! A connection may carry several requests; each gets one response line. The socket is
//! created with mode 0600.
const std = @import("std");
const Io = std.Io;
const net = Io.net;
const Allocator = std.mem.Allocator;
const jsonpretty = @import("jsonpretty.zig");
pub const max_request_bytes = 256 * 1024;
pub const max_response_bytes = 16 * 1024 * 1024;
pub const ErrorCode = enum {
SERVICE_NOT_RUNNING,
CONNECTION_FAILED,
INVALID_REQUEST,
INTERNAL_ERROR,
NOT_FOUND,
INVALID_STATE,
};
pub const Request = struct {
type: []const u8,
/// `.null` when absent.
payload: std.json.Value = .null,
pub fn payloadString(self: Request, key: []const u8) ?[]const u8 {
const obj = switch (self.payload) {
.object => |o| o,
else => return null,
};
return switch (obj.get(key) orelse return null) {
.string => |s| s,
else => null,
};
}
pub fn payloadBool(self: Request, key: []const u8) bool {
const obj = switch (self.payload) {
.object => |o| o,
else => return false,
};
return switch (obj.get(key) orelse return false) {
.bool => |b| b,
else => false,
};
}
pub fn payloadInt(self: Request, key: []const u8) ?i64 {
const obj = switch (self.payload) {
.object => |o| o,
else => return null,
};
return switch (obj.get(key) orelse return null) {
.integer => |n| n,
else => null,
};
}
};
/// What a handler fills in: write the payload through `json`, or call `fail`.
pub const Response = struct {
arena: Allocator,
json: jsonpretty.Writer,
code: ErrorCode = .INTERNAL_ERROR,
message: []const u8 = "",
pub const Failure = error{Failure};
pub fn fail(self: *Response, code: ErrorCode, message: []const u8) Failure {
self.code = code;
self.message = message;
return error.Failure;
}
pub fn failFmt(self: *Response, code: ErrorCode, comptime fmt: []const u8, args: anytype) Failure {
return self.fail(code, std.fmt.allocPrint(self.arena, fmt, args) catch "out of memory");
}
};
pub const HandlerError = Response.Failure || Allocator.Error || Io.Writer.Error || anyerror;
pub const HandlerFn = *const fn (ctx: *anyopaque, req: Request, res: *Response) HandlerError!void;
// -- server ----------------------------------------------------------------------------
pub const Server = struct {
gpa: Allocator,
io: Io,
socket_path: []const u8,
ctx: *anyopaque,
handler: HandlerFn,
listener: ?net.Server = null,
thread: ?std.Thread = null,
stopping: std.atomic.Value(bool) = .init(false),
connections: std.atomic.Value(u32) = .init(0),
pub const StartError = error{ AddressInUse, NameTooLong } || net.UnixAddress.ListenError || std.Thread.SpawnError;
pub fn init(gpa: Allocator, io: Io, socket_path: []const u8, ctx: *anyopaque, handler: HandlerFn) Server {
return .{ .gpa = gpa, .io = io, .socket_path = socket_path, .ctx = ctx, .handler = handler };
}
pub fn start(self: *Server) StartError!void {
const addr = try net.UnixAddress.init(self.socket_path);
// A live server on this path means we must not steal it; a stale file is removed.
const existing = Io.Dir.cwd().statFile(self.io, self.socket_path, .{}) catch null;
if (existing) |st| {
if (st.kind == .unix_domain_socket) {
if (addr.connect(self.io)) |stream| {
stream.close(self.io);
return error.AddressInUse;
} else |_| {}
}
Io.Dir.cwd().deleteFile(self.io, self.socket_path) catch {};
}
self.listener = try addr.listen(self.io, .{});
errdefer {
self.listener.?.deinit(self.io);
self.listener = null;
}
Io.Dir.cwd().setFilePermissions(self.io, self.socket_path, @enumFromInt(0o600), .{}) catch {};
self.stopping.store(false, .release);
self.thread = try std.Thread.spawn(.{}, acceptLoop, .{self});
}
/// Stops accepting, waits briefly for in-flight connections, removes the socket file.
pub fn stop(self: *Server) void {
if (self.thread == null) return;
self.stopping.store(true, .release);
// Wake the blocked accept() with a throwaway connection.
if (net.UnixAddress.init(self.socket_path)) |addr| {
if (addr.connect(self.io)) |s| s.close(self.io) else |_| {}
} else |_| {}
self.thread.?.join();
self.thread = null;
self.listener.?.deinit(self.io);
self.listener = null;
Io.Dir.cwd().deleteFile(self.io, self.socket_path) catch {};
var waited: u32 = 0;
while (self.connections.load(.acquire) > 0 and waited < 2000) : (waited += 10) {
self.io.sleep(.fromMilliseconds(10), .real) catch break;
}
}
fn acceptLoop(self: *Server) void {
while (!self.stopping.load(.acquire)) {
const stream = self.listener.?.accept(self.io) catch |err| switch (err) {
error.SocketNotListening, error.Canceled => return,
else => continue,
};
if (self.stopping.load(.acquire)) {
stream.close(self.io);
return;
}
_ = self.connections.fetchAdd(1, .acq_rel);
const t = std.Thread.spawn(.{}, serveConnection, .{ self, stream }) catch {
stream.close(self.io);
_ = self.connections.fetchSub(1, .acq_rel);
continue;
};
t.detach();
}
}
fn serveConnection(self: *Server, stream: net.Stream) void {
defer {
stream.close(self.io);
_ = self.connections.fetchSub(1, .acq_rel);
}
const rbuf = self.gpa.alloc(u8, max_request_bytes) catch return;
defer self.gpa.free(rbuf);
var wbuf: [4096]u8 = undefined;
var reader = stream.reader(self.io, rbuf);
var writer = stream.writer(self.io, &wbuf);
while (true) {
const line = (reader.interface.takeDelimiter('\n') catch return) orelse return;
if (line.len == 0) continue;
var arena_state = std.heap.ArenaAllocator.init(self.gpa);
defer arena_state.deinit();
const reply = self.handleLine(arena_state.allocator(), line) catch return;
writer.interface.writeAll(reply) catch return;
writer.interface.writeByte('\n') catch return;
writer.interface.flush() catch return;
}
}
/// Builds the response line for one request line.
fn handleLine(self: *Server, arena: Allocator, line: []const u8) Allocator.Error![]const u8 {
const parsed = std.json.parseFromSliceLeaky(Request, arena, line, .{ .ignore_unknown_fields = true }) catch
return errorLine(arena, .INVALID_REQUEST, "Malformed request");
var payload: Io.Writer.Allocating = .init(arena);
var res: Response = .{ .arena = arena, .json = jsonpretty.Writer.initCompact(&payload.writer) };
self.handler(self.ctx, parsed, &res) catch |err| {
if (err == error.Failure) return errorLine(arena, res.code, res.message);
return errorLine(arena, .INTERNAL_ERROR, try std.fmt.allocPrint(arena, "Failed to process request: {s}", .{@errorName(err)}));
};
var out: Io.Writer.Allocating = .init(arena);
out.writer.writeAll("{\"status\":\"ok\",\"payload\":") catch return error.OutOfMemory;
out.writer.writeAll(if (payload.written().len == 0) "null" else payload.written()) catch return error.OutOfMemory;
out.writer.writeByte('}') catch return error.OutOfMemory;
return out.written();
}
};
fn errorLine(arena: Allocator, code: ErrorCode, message: []const u8) Allocator.Error![]const u8 {
var out: Io.Writer.Allocating = .init(arena);
var w = jsonpretty.Writer.initCompact(&out.writer);
(blk: {
w.beginObject() catch |e| break :blk e;
w.field("status", .string, "error") catch |e| break :blk e;
w.key("error") catch |e| break :blk e;
w.beginObject() catch |e| break :blk e;
w.field("code", .string, @tagName(code)) catch |e| break :blk e;
w.field("message", .string, message) catch |e| break :blk e;
w.endObject() catch |e| break :blk e;
w.endObject() catch |e| break :blk e;
}) catch return error.OutOfMemory;
return out.written();
}
// -- client ----------------------------------------------------------------------------
pub const RemoteError = struct {
code: []const u8,
message: []const u8,
};
pub const Reply = union(enum) {
ok: std.json.Value,
err: RemoteError,
};
pub const CallError = error{ ServiceNotRunning, ConnectionFailed, BadResponse } || Allocator.Error;
/// Sends one request and waits for the reply. `payload_json` is already-encoded JSON (or null).
/// Everything in the reply is allocated from `arena`.
pub fn call(io: Io, arena: Allocator, socket_path: []const u8, request_type: []const u8, payload_json: ?[]const u8) CallError!Reply {
const addr = net.UnixAddress.init(socket_path) catch return error.ServiceNotRunning;
const stream = addr.connect(io) catch |err| switch (err) {
error.FileNotFound, error.AccessDenied, error.PermissionDenied => return error.ServiceNotRunning,
else => return error.ConnectionFailed,
};
defer stream.close(io);
var wbuf: [4096]u8 = undefined;
var writer = stream.writer(io, &wbuf);
var req: Io.Writer.Allocating = .init(arena);
{
var w = jsonpretty.Writer.initCompact(&req.writer);
w.beginObject() catch return error.OutOfMemory;
w.field("type", .string, request_type) catch return error.OutOfMemory;
req.writer.writeAll(",\"payload\":") catch return error.OutOfMemory;
req.writer.writeAll(payload_json orelse "null") catch return error.OutOfMemory;
req.writer.writeAll("}\n") catch return error.OutOfMemory;
}
writer.interface.writeAll(req.written()) catch return error.ConnectionFailed;
writer.interface.flush() catch return error.ConnectionFailed;
const rbuf = try arena.alloc(u8, max_response_bytes);
var reader = stream.reader(io, rbuf);
const line = (reader.interface.takeDelimiter('\n') catch return error.ConnectionFailed) orelse return error.ConnectionFailed;
return parseReply(arena, line);
}
pub fn parseReply(arena: Allocator, line: []const u8) CallError!Reply {
const value = std.json.parseFromSliceLeaky(std.json.Value, arena, line, .{}) catch |err| switch (err) {
error.OutOfMemory => return error.OutOfMemory,
else => return error.BadResponse,
};
const obj = switch (value) {
.object => |o| o,
else => return error.BadResponse,
};
const status = switch (obj.get("status") orelse return error.BadResponse) {
.string => |s| s,
else => return error.BadResponse,
};
if (std.mem.eql(u8, status, "ok")) return .{ .ok = obj.get("payload") orelse .null };
const e = switch (obj.get("error") orelse return error.BadResponse) {
.object => |o| o,
else => return error.BadResponse,
};
const code = switch (e.get("code") orelse return error.BadResponse) {
.string => |s| s,
else => return error.BadResponse,
};
const message = switch (e.get("message") orelse .null) {
.string => |s| s,
else => "",
};
return .{ .err = .{ .code = code, .message = message } };
}
// -- tests -----------------------------------------------------------------------------
const TestCtx = struct { calls: std.atomic.Value(u32) = .init(0) };
fn testHandler(ctx_ptr: *anyopaque, req: Request, res: *Response) HandlerError!void {
const ctx: *TestCtx = @ptrCast(@alignCast(ctx_ptr));
_ = ctx.calls.fetchAdd(1, .acq_rel);
if (std.mem.eql(u8, req.type, "echo")) {
try res.json.beginObject();
try res.json.key("name");
try res.json.optString(req.payloadString("name"));
try res.json.field("force", .boolean, req.payloadBool("force"));
try res.json.endObject();
} else if (std.mem.eql(u8, req.type, "missing")) {
return res.failFmt(.NOT_FOUND, "Job not found: {s}", .{req.payloadString("id") orelse "?"});
} else if (std.mem.eql(u8, req.type, "boom")) {
return error.OutOfMemory;
} else if (std.mem.eql(u8, req.type, "void")) {
return;
} else {
return res.fail(.INVALID_REQUEST, "Unknown request type");
}
}
fn testSocket(arena: Allocator, tmp: *std.testing.TmpDir) ![]const u8 {
return std.fmt.allocPrint(arena, ".zig-cache/tmp/{s}/zag.sock", .{tmp.sub_path});
}
test "request/response round trip and errors" {
const io = std.testing.io;
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena_state.deinit();
const arena = arena_state.allocator();
const path = try testSocket(arena, &tmp);
var ctx: TestCtx = .{};
var server = Server.init(std.testing.allocator, io, path, &ctx, testHandler);
try server.start();
defer server.stop();
const ok = try call(io, arena, path, "echo", "{\"name\":\"job-1\",\"force\":true}");
try std.testing.expectEqualStrings("job-1", ok.ok.object.get("name").?.string);
try std.testing.expect(ok.ok.object.get("force").?.bool);
const nf = try call(io, arena, path, "missing", "{\"id\":\"job-9\"}");
try std.testing.expectEqualStrings("NOT_FOUND", nf.err.code);
try std.testing.expectEqualStrings("Job not found: job-9", nf.err.message);
const boom = try call(io, arena, path, "boom", null);
try std.testing.expectEqualStrings("INTERNAL_ERROR", boom.err.code);
const unk = try call(io, arena, path, "nope", null);
try std.testing.expectEqualStrings("INVALID_REQUEST", unk.err.code);
const empty = try call(io, arena, path, "void", null);
try std.testing.expect(empty.ok == .null);
}
test "one connection can carry several requests; malformed input gets an error line" {
const io = std.testing.io;
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena_state.deinit();
const arena = arena_state.allocator();
const path = try testSocket(arena, &tmp);
var ctx: TestCtx = .{};
var server = Server.init(std.testing.allocator, io, path, &ctx, testHandler);
try server.start();
defer server.stop();
const addr = try net.UnixAddress.init(path);
const stream = try addr.connect(io);
defer stream.close(io);
var wbuf: [256]u8 = undefined;
var rbuf: [4096]u8 = undefined;
var w = stream.writer(io, &wbuf);
var r = stream.reader(io, &rbuf);
try w.interface.writeAll("{\"type\":\"echo\",\"payload\":{\"name\":\"a\"}}\nnot json\n{\"type\":\"echo\",\"payload\":{\"name\":\"b\"}}\n");
try w.interface.flush();
const l1 = (try r.interface.takeDelimiter('\n')).?;
try std.testing.expectEqualStrings("{\"status\":\"ok\",\"payload\":{\"name\":\"a\",\"force\":false}}", l1);
const l2 = (try r.interface.takeDelimiter('\n')).?;
try std.testing.expect(std.mem.indexOf(u8, l2, "INVALID_REQUEST") != null);
const l3 = (try r.interface.takeDelimiter('\n')).?;
try std.testing.expectEqualStrings("{\"status\":\"ok\",\"payload\":{\"name\":\"b\",\"force\":false}}", l3);
}
test "client reports a missing service" {
const io = std.testing.io;
var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena_state.deinit();
try std.testing.expectError(error.ServiceNotRunning, call(io, arena_state.allocator(), ".zig-cache/no-such.sock", "echo", null));
}
test "socket is private, removed on stop, and a second server is refused" {
const io = std.testing.io;
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena_state.deinit();
const arena = arena_state.allocator();
const path = try testSocket(arena, &tmp);
var ctx: TestCtx = .{};
var s1 = Server.init(std.testing.allocator, io, path, &ctx, testHandler);
try s1.start();
const st = try Io.Dir.cwd().statFile(io, path, .{});
try std.testing.expectEqual(@as(u32, 0o600), @as(u32, @intCast(@intFromEnum(st.permissions) & 0o777)));
var s2 = Server.init(std.testing.allocator, io, path, &ctx, testHandler);
try std.testing.expectError(error.AddressInUse, s2.start());
s1.stop();
try std.testing.expectError(error.FileNotFound, Io.Dir.cwd().statFile(io, path, .{}));
try s2.start(); // path is free again
s2.stop();
}
test "a stale socket file is replaced" {
const io = std.testing.io;
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena_state.deinit();
const arena = arena_state.allocator();
const path = try testSocket(arena, &tmp);
try tmp.dir.writeFile(io, .{ .sub_path = "zag.sock", .data = "stale" });
var ctx: TestCtx = .{};
var s = Server.init(std.testing.allocator, io, path, &ctx, testHandler);
try s.start();
defer s.stop();
const reply = try call(io, arena, path, "void", null);
try std.testing.expect(reply.ok == .null);
}