diff options
| author | Gabriel Schneider <[email protected]> | 2026-11-17 01:57:33 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-11-17 12:15:01 -0300 |
| commit | 41bdeb1b3fadc266823c43086de61913be8e60f6 (patch) | |
| tree | bc042874c8c614b788e6f59d3e090144671fd90e /src/host/control.zig | |
| parent | b1311b3d489a8054456cba7054160ed7fb7e70e1 (diff) | |
| download | sketchbook-41bdeb1b3fadc266823c43086de61913be8e60f6.tar.gz sketchbook-41bdeb1b3fadc266823c43086de61913be8e60f6.zip | |
Dial by name, and fs in every sketch's binary, answering with the sketch closed
A run a person watches (not headless, a script or an export) posts its
tree as $XDG_RUNTIME_DIR/9p/sketchbook/<name>, the sketch's Info.name;
--9p NAME posts under another name, --9p /path listens at a socket path
as before. A name a live run holds is refused, a stale one replaced; a
default post that fails says so and the run goes on without one, an
explicit --9p that fails ends it as before. (cloud9's post() takes names
without a slash, so control.zig makes the sketchbook/ directory and binds
there itself, with post.probe deciding live or stale.)
`fs VERB [PATH [WORDS]]`, after the options, in the generic host
(`sketchbook LIBRARY fs ...`) and in every executable built with
sketchbook (`drat-meout fs read state/scene`), is cloud9.verbs.run on
an Fsys: the running sketch's tree when one is posted (or at --9p), else
the same tree served in this process over a socketpair, on a thread
(Control.serveOffline, the same respond with `offline` set), from the
save's newest State (--state's save, else the default one; read only:
Sessions.openRead, no session started, restored into today's layout),
else from the State's declared defaults (init is not run). README,
commands, ctl's read and state/ answer; a write and status, log,
screen.png and the traces answer in words, "drat-meout is not running:
this is its save's newest State, frame 61 of <save>". No window, no SDL.
sketchbook.init's modules gain cloud9, so an app's own tests can dial
its executable with cloud9.Fsys.
Tests: a new step, test-fs (in test): the replay fixture posted by name
under a private runtime directory, driven with its own binary's fs: ls,
a state write and read, a refused value in words, a live click, a
screenshot read, help of state/dots and ctl, quit and the name gone; then
closed: a state file read from the defaults, status refused in words.
test-fs, test-control, test-paths, test-setup, test-sessions: 56/56
steps, 27/27 tests. drat-meout's copy builds unchanged and answers fs
with the game closed: 94 leaves, 16,522 files, 17,608 values, 10,408
directories.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T
Diffstat (limited to 'src/host/control.zig')
| -rw-r--r-- | src/host/control.zig | 69 |
1 files changed, 61 insertions, 8 deletions
diff --git a/src/host/control.zig b/src/host/control.zig index 6fb997b..5722a4d 100644 --- a/src/host/control.zig +++ b/src/host/control.zig @@ -65,6 +65,9 @@ pub const Control = struct { allocator: std.mem.Allocator, path: [:0]u8, listener: c_int, + /// Serving with no sketch running (`fs` with it closed): the State to + /// show and where it came from; the host is not touched. + offline: ?Offline = null, connections: [4]Connection = @splat(.{}), png: []u8 = &.{}, capture_pending: bool = false, @@ -87,6 +90,36 @@ pub const Control = struct { return self; } + /// Listens at `where`: a socket path, or a name posted as + /// `$XDG_RUNTIME_DIR/9p/sketchbook/<where>` (a stale entry replaced, a + /// live one refused). + pub fn open(a: std.mem.Allocator, environ: *const std.process.Environ.Map, where: []const u8) !*Control { + if (std.mem.startsWith(u8, where, "/")) return init(a, where); + var buf: [c9.post.sun_path_len]u8 = undefined; + const path = try registered(environ, where, &buf); + const dir = path[0..std.mem.lastIndexOfScalar(u8, path, '/').?]; + var dir_buf: [c9.post.sun_path_len]u8 = undefined; + for ([_]usize{ dir.len - "/sketchbook".len, dir.len }) |n| _ = std.c.mkdir(std.fmt.bufPrintSentinel(&dir_buf, "{s}", .{dir[0..n]}, 0) catch unreachable, 0o700); + switch (c9.post.probe(path)) { + .live => return error.AlreadyPosted, + .stale => _ = std.c.unlink(path), + .none => {}, + } + return init(a, path); + } + + /// Serves one client on `fd` until it hangs up: `fs` with no sketch + /// running, on a thread of its own. + pub fn serveOffline(self: *Control, fd: c_int) void { + const conn = self.allocator.create(Connection) catch return transport.close(fd); + defer self.allocator.destroy(conn); + conn.* = .{ .fd = fd }; + conn.server = .init(.{ .in = &conn.input, .out = &conn.output, .root = 1 }); + var host: Host = undefined; // Offline, nothing reads it. + while (true) self.service(&host, conn) catch break; + conn.close(self.allocator); + } + pub fn deinit(self: *Control) void { for (&self.connections) |*conn| conn.close(self.allocator); transport.close(self.listener); @@ -156,15 +189,16 @@ pub const Control = struct { self.capture_error = null; } const bytes = self.respond(host, conn, req, &reply, &buffer) catch |err| blk: { - reply = if (err == error.CapturePending) .{ .tag = req.tag, .status = .again } else .{ .tag = req.tag, .status = .err, .errno = fs.E.INVAL, .ename = @errorName(err) }; + reply = if (err == error.CapturePending) .{ .tag = req.tag, .status = .again } else .{ .tag = req.tag, .status = .err, .errno = fs.E.INVAL, .ename = if (err == error.SketchNotRunning) self.offline.?.from else @errorName(err) }; break :blk &.{}; }; conn.server.reply(&reply, bytes); } fn respond(self: *Control, host: *Host, conn: *Connection, req: fs.Req, reply: *fs.Reply, buffer: []u8) ![]const u8 { - if (req.node & @as(u64, @bitCast(state_files.root)) != 0) return stateRespond(host, req, reply, buffer); + if (req.node & @as(u64, @bitCast(state_files.root)) != 0) return stateRespond(self, host, req, reply, buffer); const file = std.enums.fromInt(File, req.node) orelse return error.UnknownFile; + if (self.offline != null and (req.op == .write or (req.op == .open or req.op == .read) and file != .README and file != .commands and file != .ctl and file != .@"/")) return error.SketchNotRunning; switch (req.op) { .lookup => { if (file != .@"/") return error.NotDirectory; @@ -188,7 +222,8 @@ pub const Control = struct { .README, .commands => blk: { var text: std.Io.Writer.Allocating = .init(self.allocator); defer text.deinit(); - if (file == .README) try readme(host, &text.writer) else try verbLines(&text.writer, "", host.completions); + const layout = if (self.offline) |o| o.layout else host.state.layout; + if (file == .README) try readme(layout, &text.writer) else try verbLines(&text.writer, "", if (self.offline) |o| o.completions else host.completions); break :blk try text.toOwnedSlice(); }, else => try self.presentationTrace(host), @@ -357,14 +392,14 @@ pub const Control = struct { /// The README: a line a file, ctl's verbs indented under it and the /// State's files under state/, in the shape cloud9's `help` reads. -fn readme(host: *Host, w: *std.Io.Writer) !void { +fn readme(layout: @import("memory.zig").Layout, w: *std.Io.Writer) !void { for (std.enums.values(File)[1..]) |f| { const name = @tagName(f); try w.print("{s}{s}", .{ name, if (f == .state) "/" else "" }); try w.splatByteAll(' ', @max(1, 41 -| (name.len + @intFromBool(f == .state)))); try w.print("{s}\n", .{files.get(f).doc}); if (f == .ctl) try verbLines(w, " ", &.{}); - if (f == .state) try state_files.readme(host.state.layout, w); + if (f == .state) try state_files.readme(layout, w); } } @@ -385,8 +420,8 @@ fn verbLine(w: *std.Io.Writer, indent: []const u8, name: []const u8, args: []con /// Under `state/`: the live State as files (state_files.zig), a write /// run as the console's `set`. -fn stateRespond(host: *Host, req: fs.Req, reply: *fs.Reply, buffer: []u8) ![]const u8 { - const layout = host.state.layout; +fn stateRespond(self: *Control, host: *Host, req: fs.Req, reply: *fs.Reply, buffer: []u8) ![]const u8 { + const layout = if (self.offline) |o| o.layout else host.state.layout; const node: state_files.Node = @bitCast(req.node); if (!state_files.valid(layout, node)) return error.StateLayoutChangedWalkAgain; const dir = state_files.isDir(layout, node); @@ -411,11 +446,12 @@ fn stateRespond(host: *Host, req: fs.Req, reply: *fs.Reply, buffer: []u8) ![]con .read => { if (dir) return error.NotFile; var w: std.Io.Writer = .fixed(buffer); - state_files.read(layout, host.live(), node, &w) catch return error.ValueTooLong; + state_files.read(layout, if (self.offline) |o| o.bytes else host.live(), node, &w) catch return error.ValueTooLong; return window(w.buffered(), req.off, req.size); }, .write => { if (mode != 0o600) return error.ReadOnly; + if (self.offline != null) return error.SketchNotRunning; var w: std.Io.Writer = .fixed(buffer); w.writeAll("set ") catch unreachable; state_files.path(layout, node, &w) catch return error.ValueTooLong; @@ -428,6 +464,23 @@ fn stateRespond(host: *Host, req: fs.Req, reply: *fs.Reply, buffer: []u8) ![]con return &.{}; } +/// The State `fs` shows with no sketch running, and its words for what a +/// running one would answer. +pub const Offline = struct { + layout: @import("memory.zig").Layout, + bytes: []const u8, + completions: []const []const u8, + /// "drat-meout is not running: ..." + from: []const u8, +}; + +/// `$XDG_RUNTIME_DIR/9p/sketchbook/<name>`, where a sketch posts its tree. +pub fn registered(environ: *const std.process.Environ.Map, name: []const u8, buf: []u8) ![:0]u8 { + if (!c9.post.legalName(name)) return error.IllegalName; + const runtime = environ.get("XDG_RUNTIME_DIR") orelse return error.NotRuntimeDir; + return std.fmt.bufPrintSentinel(buf, "{s}/9p/sketchbook/{s}", .{ runtime, name }, 0) catch error.NameTooLong; +} + fn window(bytes: []const u8, offset: u64, count: u32) []const u8 { if (offset >= bytes.len) return &.{}; const start: usize = @intCast(offset); |
