summaryrefslogtreecommitdiff
path: root/src/detached/server.zig
diff options
context:
space:
mode:
authorGabriel Schneider <[email protected]>2026-10-23 17:11:12 -0300
committerGabriel Schneider <[email protected]>2026-10-23 17:11:12 -0300
commit19c83c90ebed4817acd7a12d4d225f5af0957bc1 (patch)
treee6ae660d2768063eb0c3ff0548c23077927de520 /src/detached/server.zig
parentef0de36bf473f22d37cc885054bf4eed98bf275f (diff)
downloadpardes-19c83c90ebed4817acd7a12d4d225f5af0957bc1.tar.gz
pardes-19c83c90ebed4817acd7a12d4d225f5af0957bc1.zip
One inbox for every host: the GUI's queue moves to host_io.Inbox, macOS and the detached server use it
The inbox takes a wake callback instead of an SDL flag and owns starting a pty reader and an LSP query and delivering their answers, status and pipe results. macOS gains the GUI's rule that only a pane's current reader and the current query get in; its reap now cancels the reader on the inbox before its future, since a reader blocked on a full queue cannot be canceled. The detached server's completion mailbox goes; its socket stays the loop's wakeup. Two old macOS ABI test compile errors fixed, so its unit tests run on Linux. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Diffstat (limited to 'src/detached/server.zig')
-rw-r--r--src/detached/server.zig203
1 files changed, 68 insertions, 135 deletions
diff --git a/src/detached/server.zig b/src/detached/server.zig
index 62dff011..124a4c5a 100644
--- a/src/detached/server.zig
+++ b/src/detached/server.zig
@@ -79,68 +79,13 @@ const Pty = struct {
cmd: host_io.CommandWatch = .{},
};
-/// A watched child exited: wake the loop, which takes it (`takeExits`).
+/// A watched child exited, or a worker finished: wake the loop.
fn wakeForExit(ctx: ?*anyopaque) void {
- const box: *Mailbox = @ptrCast(@alignCast(ctx.?));
- box.signal();
+ Session.signal(@ptrCast(@alignCast(ctx.?)));
}
const RetiredShell = struct { pid: posix.pid_t = 0, kill_at: i64 = 0 };
-const Completion = union(enum) {
- lsp: struct { id: u32, rows: ?[]u8 },
- pipe: selection_pipe.Response,
-
- fn deinit(completion: *Completion, gpa: std.mem.Allocator) void {
- switch (completion.*) {
- .lsp => |result| if (result.rows) |rows| gpa.free(rows),
- .pipe => |*result| result.deinit(gpa),
- }
- }
-};
-
-const Mailbox = struct {
- const capacity = selection_pipe.Tasks.capacity + 1;
- const Batch = struct {
- items: [capacity]Completion = undefined,
- len: usize = 0,
- status: ?[]u8 = null,
- };
-
- /// Taken by the workers and the loop; `io` is the session's (initAsync).
- mutex: std.Io.Mutex = .init,
- io: std.Io = undefined,
- batch: Batch = .{},
- wake: [2]c_int = .{ -1, -1 },
-
- fn post(box: *Mailbox, completion: Completion) void {
- box.mutex.lockUncancelable(box.io);
- // Tasks retain their slot until the owner consumes their one completion.
- std.debug.assert(box.batch.len < capacity);
- box.batch.items[box.batch.len] = completion;
- box.batch.len += 1;
- box.mutex.unlock(box.io);
- box.signal();
- }
-
- fn signal(box: *Mailbox) void {
- while (libc.send(box.wake[1], "w", 1, nosignal) < 0) {
- if (libc.errno(-1) != .INTR) break;
- }
- }
-
- fn take(box: *Mailbox) Batch {
- var bytes: [128]u8 = undefined;
- while (libc.recv(box.wake[0], &bytes, bytes.len, 0) > 0) {}
- box.mutex.lockUncancelable(box.io);
- defer box.mutex.unlock(box.io);
- const batch = box.batch;
- box.batch.len = 0;
- box.batch.status = null;
- return batch;
- }
-};
-
const Source = union(enum) {
listener,
completion,
@@ -167,8 +112,10 @@ pub const Session = struct {
scratch: std.ArrayListUnmanaged(u8) = .empty,
ptys: [pardes.MAX_PANES]Pty = @splat(.{}),
retired_shells: [pardes.MAX_PANES]RetiredShell = @splat(.{}),
- mailbox: Mailbox = .{},
- lsp_task: ?host_io.Lsp.Task = null,
+ /// The workers' answers (initAsync sets it up); `wake` is what wakes
+ /// the loop's poll for them, and for a watched child's exit.
+ inbox: host_io.Inbox = undefined,
+ wake: [2]c_int = .{ -1, -1 },
pipe_tasks: selection_pipe.Tasks = .{},
prompt_rcs: host_io.Shell.PromptFiles = .{},
inotify_fd: c_int = -1,
@@ -186,7 +133,6 @@ pub const Session = struct {
accept_paused_ms: i64 = 0,
pub fn initAsync(s: *Session) !void {
- s.mailbox.io = s.io;
var pair: [2]c_int = undefined;
if (libc.socketpair(libc.AF.UNIX, libc.SOCK.STREAM, 0, &pair) != 0) return error.SocketFailed;
errdefer for (pair) |fd| {
@@ -201,31 +147,41 @@ pub const Session = struct {
return error.SocketOptionFailed;
}
}
- s.mailbox.wake = pair;
- pardes.lsp.setStatusSink(s, lspStatus);
- host_io.setExitWake(&s.mailbox, wakeForExit);
+ s.wake = pair;
+ s.inbox = .{ .gpa = s.worker_gpa, .lsp_allocator = s.worker_gpa, .io = s.io, .wake_fn = wakeForExit, .wake_ctx = s };
+ pardes.lsp.setStatusSink(&s.inbox, host_io.Inbox.lspStatus);
+ host_io.setExitWake(s, wakeForExit);
+ }
+
+ fn signal(s: *Session) void {
+ while (libc.send(s.wake[1], "w", 1, nosignal) < 0) {
+ if (libc.errno(-1) != .INTR) break;
+ }
}
fn cancelWorkers(s: *Session) void {
- if (s.lsp_task) |*task| {
+ if (s.wake[0] < 0) return; // no initAsync: no workers
+ if (s.inbox.lsp_task) |*task| {
task.future.cancel(s.io);
- s.lsp_task = null;
+ s.inbox.lsp_task = null;
}
s.pipe_tasks.cancelAll(s.io);
_ = s.drainCompletions(false);
}
fn drainCompletions(s: *Session, apply_results: bool) bool {
- var batch = s.mailbox.take();
- for (batch.items[0..batch.len]) |*completion| {
- defer completion.deinit(s.worker_gpa);
+ var bytes: [128]u8 = undefined;
+ while (libc.recv(s.wake[0], &bytes, bytes.len, 0) > 0) {}
+ var batch = s.inbox.take();
+ for (batch.slice()) |msg| {
+ defer msg.deinit(s.worker_gpa, s.worker_gpa);
if (!apply_results) continue;
- switch (completion.*) {
+ switch (msg) {
.lsp => |result| {
s.core.update(.{ .lsp_resp = .{ .id = result.id, .rows = result.rows } });
- if (s.lsp_task) |*task| if (task.id == result.id) {
+ if (s.inbox.lsp_task) |*task| if (task.id == result.id) {
task.future.await(s.io);
- s.lsp_task = null;
+ s.inbox.lsp_task = null;
};
},
.pipe => |result| {
@@ -237,16 +193,15 @@ pub const Session = struct {
} });
s.pipe_tasks.finish(s.io, result.id);
},
+ .lsp_status => |status| {
+ var buf: [256]u8 = undefined;
+ s.core.setStatus(s.core.active, message.stamp(&buf, "lsp", status));
+ },
+ // Ptys are read in the loop's own poll, not through the inbox.
+ .output, .eof, .files_changed, .fs_ready => {},
}
}
- if (batch.status) |status| {
- defer s.worker_gpa.free(status);
- if (apply_results) {
- var buf: [256]u8 = undefined;
- s.core.setStatus(s.core.active, message.stamp(&buf, "lsp", status));
- }
- }
- return batch.len != 0 or batch.status != null;
+ return batch.len != 0;
}
pub fn restore(s: *Session, bytes: []const u8, from: []const u8) !void {
@@ -268,19 +223,20 @@ pub const Session = struct {
for (&s.clients) |*client| if (client.attached) {
client.need_full = true;
};
- s.mailbox.signal();
+ s.signal();
}
pub fn deinit(s: *Session) void {
- // First: its compile thread wakes the mailbox, closed below.
+ // First: its compile thread wakes the loop, whose socket closes below.
s.shaders.deinit(s.gpa, s.inotify_fd, &s.watches);
- if (s.mailbox.wake[0] >= 0) pardes.lsp.setStatusSink(null, null);
- if (s.mailbox.wake[0] >= 0) host_io.setExitWake(null, null);
+ if (s.wake[0] >= 0) pardes.lsp.setStatusSink(null, null);
+ if (s.wake[0] >= 0) host_io.setExitWake(null, null);
s.cancelWorkers();
- for (s.mailbox.wake) |fd| if (fd >= 0) {
+ if (s.wake[0] >= 0) s.inbox.close();
+ for (s.wake) |fd| if (fd >= 0) {
_ = libc.close(fd);
};
- s.mailbox.wake = .{ -1, -1 };
+ s.wake = .{ -1, -1 };
if (s.ninep) |l| {
l.deinit(s.gpa);
s.ninep = null;
@@ -399,40 +355,13 @@ pub const Session = struct {
fn lspRequest(ctx: ?*anyopaque, request: host_io.Lsp.Request) void {
const s = of(ctx);
_ = s.drainCompletions(true);
- // Canceled here, not in `start`: what it delivered before it went
- // is drained first, which leaves its slot in the mailbox free.
- if (s.lsp_task) |*task| {
- task.future.cancel(s.io);
- s.lsp_task = null;
- _ = s.drainCompletions(true);
- }
- host_io.Lsp.start(s.io, s.worker_gpa, s.core, &s.lsp_task, request, &s.mailbox, deliverLspRows);
- }
-
- fn deliverLspRows(ctx: ?*anyopaque, id: u32, rows: ?[]u8) void {
- const box: *Mailbox = @ptrCast(@alignCast(ctx.?));
- box.post(.{ .lsp = .{ .id = id, .rows = rows } });
- }
-
- fn lspStatus(ctx: ?*anyopaque, text: []const u8) void {
- const s = of(ctx);
- const copy = s.worker_gpa.dupe(u8, text) catch return;
- s.mailbox.mutex.lockUncancelable(s.io);
- if (s.mailbox.batch.status) |old| s.worker_gpa.free(old);
- s.mailbox.batch.status = copy;
- s.mailbox.mutex.unlock(s.io);
- s.mailbox.signal();
+ s.inbox.startLsp(s.core, request);
}
fn pipeRequest(ctx: ?*anyopaque, id: u32) void {
const s = of(ctx);
_ = s.drainCompletions(true);
- selection_pipe.start(s.io, s.worker_gpa, s.core, &s.pipe_tasks, id, &s.mailbox, deliverPipe);
- }
-
- fn deliverPipe(ctx: ?*anyopaque, response: selection_pipe.Response) void {
- const box: *Mailbox = @ptrCast(@alignCast(ctx.?));
- box.post(.{ .pipe = response });
+ selection_pipe.start(s.io, s.worker_gpa, s.core, &s.pipe_tasks, id, &s.inbox, host_io.Inbox.pushPipe);
}
fn primary(s: *Session) ?*Client {
@@ -619,7 +548,7 @@ pub const Session = struct {
fn wakeNinep(ctx: ?*anyopaque) void {
const s = of(ctx);
s.ninep_wake.store(true, .release);
- s.mailbox.signal();
+ s.signal();
}
fn watched(ctx: ?*anyopaque) bool {
@@ -814,8 +743,8 @@ pub const Session = struct {
var fds: [poll_slots]libc.pollfd = undefined;
var src: [poll_slots]Source = undefined;
var n: usize = 0;
- if (s.mailbox.wake[0] >= 0) {
- fds[n] = .{ .fd = s.mailbox.wake[0], .events = poll_in, .revents = 0 };
+ if (s.wake[0] >= 0) {
+ fds[n] = .{ .fd = s.wake[0], .events = poll_in, .revents = 0 };
src[n] = .completion;
n += 1;
}
@@ -852,7 +781,7 @@ pub const Session = struct {
}
if (s.ninep) |l| {
// Unix and TCP connections run on cloud9's runner, which wakes
- // this loop through the mailbox; only QUIC is polled here.
+ // this loop through `wake`; only QUIC is polled here.
if (comptime ninep_io.quic_enabled) {
if (l.quic) |*listener| {
fds[n] = listener.poll();
@@ -1087,7 +1016,7 @@ pub const Session = struct {
}
/// Compiles the post chain's files (a finished compile wakes the loop
- /// through the mailbox) and sends each attached frontend the chain it
+ /// through `wake`) and sends each attached frontend the chain it
/// has not seen: on attach, and when it or a file's SPIR-V changes. True
/// when a compile was taken in, so the loop draws what it said.
/// ponytail: a terminal frontend is sent it too and drops it; a hello
@@ -1096,7 +1025,7 @@ pub const Session = struct {
const files = for (s.core.settings.post.list()) |entry| {
if (entry.scene == null) break true;
} else false;
- const compiled = s.shaders.sync(s.gpa, s.io, s.core, if (files) s.inotify() else s.inotify_fd, &s.watches, .{ .ctx = &s.mailbox, .call = wakeForExit });
+ const compiled = s.shaders.sync(s.gpa, s.io, s.core, if (files) s.inotify() else s.inotify_fd, &s.watches, .{ .ctx = s, .call = wakeForExit });
const key = @as(u64, s.shaders.revision) << 8 | @backingInt(s.core.settings.shader_animation);
var chain: wire.Post = .{ .animation = s.core.settings.shader_animation, .len = s.core.settings.post.len };
_ = s.shaders.view(&s.core.settings.post, &chain.passes);
@@ -1283,7 +1212,7 @@ pub fn run(init: std.process.Init, opts: pardes.Options, name: []const u8) !void
core.host = h;
while (core.nextEffect()) |effect| core.perform(effect);
session.in_loop = true;
- quit_wake = session.mailbox.wake[1];
+ quit_wake = session.wake[1];
const on_quit: std.posix.Sigaction = .{ .handler = .{ .handler = onQuitSignal }, .mask = std.posix.sigemptyset(), .flags = 0 };
for ([_]std.posix.SIG{ .HUP, .INT, .TERM }) |sig| std.posix.sigaction(sig, &on_quit, null);
defer quit_wake = -1;
@@ -1339,24 +1268,27 @@ test "detached queued results preserve current requests and are discarded before
const old_id = s.core.lsp_wait.?.id;
s.core.lspRequest(0, .status, "");
const current_id = s.core.lsp_wait.?.id;
- s.lsp_task = .{ .id = current_id, .future = .{ .any_future = null, .result = {} } };
- s.mailbox.post(.{ .lsp = .{ .id = old_id, .rows = try gpa.dupe(u8, "old result\n") } });
- try std.testing.expect(s.drainCompletions(true));
- try std.testing.expectEqual(current_id, s.lsp_task.?.id);
+ s.inbox.lsp_id = current_id;
+ s.inbox.lsp_task = .{ .id = current_id, .future = .{ .any_future = null, .result = {} } };
+ // The inbox turns the superseded answer away.
+ s.inbox.push(.{ .lsp = .{ .id = old_id, .rows = try gpa.dupe(u8, "old result\n") } });
+ try std.testing.expectEqual(@as(usize, 0), s.inbox.completion_len);
+ _ = s.drainCompletions(true);
+ try std.testing.expectEqual(current_id, s.inbox.lsp_task.?.id);
try std.testing.expectEqual(current_id, s.core.lsp_wait.?.id);
try dump.dumpState(s.core);
const saved = try gpa.dupe(u8, s.core.dump_out.?);
defer gpa.free(saved);
while (s.core.nextEffect()) |_| {}
- s.mailbox.post(.{ .lsp = .{ .id = current_id, .rows = try gpa.dupe(u8, "queued before restore\n") } });
+ s.inbox.push(.{ .lsp = .{ .id = current_id, .rows = try gpa.dupe(u8, "queued before restore\n") } });
const outputs = try gpa.alloc([]u8, 1);
outputs[0] = try gpa.dupe(u8, "old filter output\n");
try std.testing.expect(s.pipe_tasks.add(.{ .id = 77, .future = .{ .any_future = null, .result = {} } }));
- s.mailbox.post(.{ .pipe = .{ .id = 77, .success = true, .outputs = outputs } });
- Session.lspStatus(&s, "old status");
+ s.inbox.push(.{ .pipe = .{ .id = 77, .success = true, .outputs = outputs } });
+ host_io.Inbox.lspStatus(&s.inbox, "old status");
try s.restore(saved, "test");
- try std.testing.expect(s.lsp_task == null);
+ try std.testing.expect(s.inbox.lsp_task == null);
try std.testing.expectEqual(@as(usize, 0), s.pipe_tasks.len);
try std.testing.expect(!s.drainCompletions(true));
try std.testing.expectEqualStrings("saved body\n", s.core.panes[0].?.file.?.content);
@@ -1364,15 +1296,16 @@ test "detached queued results preserve current requests and are discarded before
s.core.lspRequest(0, .status, "");
const restored_id = s.core.lsp_wait.?.id;
try std.testing.expect(restored_id > current_id);
- s.lsp_task = .{ .id = restored_id, .future = .{ .any_future = null, .result = {} } };
- s.mailbox.post(.{ .lsp = .{ .id = current_id, .rows = try gpa.dupe(u8, "late old result\n") } });
+ s.inbox.lsp_id = restored_id;
+ s.inbox.lsp_task = .{ .id = restored_id, .future = .{ .any_future = null, .result = {} } };
+ s.inbox.push(.{ .lsp = .{ .id = current_id, .rows = try gpa.dupe(u8, "late old result\n") } });
_ = s.drainCompletions(true);
- try std.testing.expectEqual(restored_id, s.lsp_task.?.id);
+ try std.testing.expectEqual(restored_id, s.inbox.lsp_task.?.id);
try std.testing.expectEqual(restored_id, s.core.lsp_wait.?.id);
- s.mailbox.post(.{ .lsp = .{ .id = restored_id, .rows = &.{} } });
+ s.inbox.push(.{ .lsp = .{ .id = restored_id, .rows = &.{} } });
const host = s.host();
host.vtable.wait_input.?(host.ctx, 1);
- try std.testing.expect(s.lsp_task == null);
+ try std.testing.expect(s.inbox.lsp_task == null);
try std.testing.expect(s.core.lsp_wait == null);
}
@@ -1434,7 +1367,7 @@ test "detached worker setup failure completes requests without changing document
s.core.lspRequest(0, .status, "");
while (s.core.nextEffect()) |effect| s.core.perform(effect);
try std.testing.expect(s.core.lsp_wait == null);
- try std.testing.expect(s.lsp_task == null);
+ try std.testing.expect(s.inbox.lsp_task == null);
pane.body.cur_col = 2;
pane.body.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true };