summaryrefslogtreecommitdiff
path: root/src/host
diff options
context:
space:
mode:
authorGabriel Schneider <[email protected]>2026-11-17 01:57:33 -0300
committerGabriel Schneider <[email protected]>2026-11-17 12:15:01 -0300
commit41bdeb1b3fadc266823c43086de61913be8e60f6 (patch)
treebc042874c8c614b788e6f59d3e090144671fd90e /src/host
parentb1311b3d489a8054456cba7054160ed7fb7e70e1 (diff)
downloadsketchbook-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')
-rw-r--r--src/host/Host.zig12
-rw-r--r--src/host/Sessions.zig13
-rw-r--r--src/host/control.zig69
-rw-r--r--src/host/root.zig78
4 files changed, 162 insertions, 10 deletions
diff --git a/src/host/Host.zig b/src/host/Host.zig
index 93c47c1..135f5c4 100644
--- a/src/host/Host.zig
+++ b/src/host/Host.zig
@@ -284,7 +284,15 @@ pub fn deinit(self: *Host) void {
/// The interactive loop. An export runs it on a clock of its own, frame k
/// at k/fps seconds (from 1 s, as scripts do), whatever the wall clock says.
pub fn run(self: *Host) !void {
- if (self.options.ninep) |path| self.control = try Control.init(self.gpa, path);
+ // A run a person watches posts its tree as sketchbook/<name>; --9p
+ // names another, or a socket path.
+ const o = self.options;
+ const ninep = o.ninep orelse if (o.headless or o.script or o.export_to != null) null else self.name;
+ if (ninep) |where| self.control = Control.open(self.gpa, self.environ, where) catch |err| blk: {
+ if (o.ninep != null) return err;
+ self.print("not posted as sketchbook/{s}: {t}", .{ where, err });
+ break :blk null;
+ };
while (!self.quit) {
if (self.control) |control| control.poll(self);
try self.poll();
@@ -1036,7 +1044,7 @@ fn fileId(io: std.Io, path: []const u8) u64 {
return std.hash.Wyhash.hash(0, std.mem.asBytes(&id)) | 1;
}
-fn scratchDir(environ: *const std.process.Environ.Map) []const u8 {
+pub fn scratchDir(environ: *const std.process.Environ.Map) []const u8 {
return environ.get("XDG_RUNTIME_DIR") orelse "/tmp";
}
diff --git a/src/host/Sessions.zig b/src/host/Sessions.zig
index cf0ab24..d6caf9c 100644
--- a/src/host/Sessions.zig
+++ b/src/host/Sessions.zig
@@ -191,6 +191,19 @@ pub fn open(gpa: std.mem.Allocator, io: std.Io, want: Mode, path: []const u8, fi
return s;
}
+/// The database at `path`, read only and no session started in it: for
+/// its `present` with no run of the sketch (`fs` with the sketch closed).
+pub fn openRead(gpa: std.mem.Allocator, io: std.Io, path: []const u8) !Sessions {
+ var s: Sessions = .{ .gpa = gpa, .io = io };
+ errdefer s.deinit();
+ s.file = try std.Io.Dir.cwd().openFile(io, path, .{});
+ s.buffer = try gpa.create(std.Io.Writer.Allocating);
+ s.buffer.?.* = .init(gpa);
+ s.db = .{ .file = try Disk.init(io, .{ .file = s.file.?, .buffer = s.buffer.?, .fsync = false }) };
+ s.session = try s.count(.sessions);
+ return s;
+}
+
pub fn deinit(s: *Sessions) void {
s.dropQueued();
s.queued.deinit(s.gpa);
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);
diff --git a/src/host/root.zig b/src/host/root.zig
index 44512b2..77fd14e 100644
--- a/src/host/root.zig
+++ b/src/host/root.zig
@@ -9,6 +9,10 @@ pub const memory = @import("memory.zig");
pub const fields = @import("fields.zig");
pub const script = @import("script.zig");
pub const timeline = @import("timeline.zig");
+const c9 = @import("cloud9");
+const control = @import("control.zig");
+const Sessions = @import("Sessions.zig");
+const Library = @import("library.zig").Library;
/// Entry point for both the generic host (`linked == null`) and apps that
/// link their sketch in.
@@ -24,6 +28,12 @@ pub fn main(init: std.process.Init, linked: ?abi.Sketch) !void {
var args = init.minimal.args.iterate();
_ = args.skip();
while (args.next()) |arg| {
+ if (std.mem.eql(u8, arg, "fs")) {
+ var words: std.ArrayList([]const u8) = .empty;
+ defer words.deinit(gpa);
+ while (args.next()) |word| try words.append(gpa, word);
+ std.process.exit(try fs(init, linked, options, words.items));
+ }
if (!std.mem.startsWith(u8, arg, "-")) {
options.library = arg;
continue;
@@ -127,6 +137,74 @@ const usage = blk: {
break :blk text;
};
+/// `fs VERB [PATH [WORDS]]`: cloud9's verbs on the sketch's tree. The
+/// running sketch's, posted as sketchbook/<name> (or at --9p); with none,
+/// the same tree served here from the save's newest State (--state's, or
+/// the default save), else from the State's defaults: README, commands,
+/// state/ answer, and the rest say the sketch is not running. No window.
+fn fs(init: std.process.Init, linked: ?abi.Sketch, options: Host.Options, words: []const []const u8) !u8 {
+ const gpa = init.gpa;
+ const io = init.io;
+ const env = init.environ_map;
+ var in_buf: [4096]u8 = undefined;
+ var out_buf: [4096]u8 = undefined;
+ var err_buf: [1024]u8 = undefined;
+ var in = std.Io.File.stdin().reader(io, &in_buf);
+ var out = std.Io.File.stdout().writer(io, &out_buf);
+ var err = std.Io.File.stderr().writer(io, &err_buf);
+ const user = env.get("USER") orelse "sketchbook";
+ var library: ?Library = null;
+ defer if (library) |*l| l.close();
+ const sketch = linked orelse blk: {
+ library = try Library.openFresh(io, options.library orelse fatal("fs needs the sketch library first: sketchbook LIBRARY fs ...", .{}), Host.scratchDir(env), 0);
+ break :blk library.?.sketch;
+ };
+ const info = sketch.info();
+ const no_env = [_:null]?[*:0]const u8{};
+ var f: c9.Fsys = undefined;
+ var path_buf: [c9.post.sun_path_len]u8 = undefined;
+ const where = options.ninep orelse info.name;
+ const path = if (std.mem.startsWith(u8, where, "/")) where else control.registered(env, where, &path_buf) catch "";
+ if (f.dial(io, &no_env, path, user)) |_| {
+ defer f.close();
+ return c9.verbs.run(&f, words, &in.interface, &out.interface, &err.interface);
+ } else |_| {}
+
+ var arena: std.heap.ArenaAllocator = .init(gpa);
+ defer arena.deinit();
+ const layout = try memory.Layout.copy(arena.allocator(), info.state);
+ const bytes = try arena.allocator().alignedAlloc(u8, .fromByteUnits(memory.page), layout.size);
+ @memset(bytes, 0);
+ sketch.defaults(.state, bytes.ptr);
+ var from = try std.fmt.allocPrint(arena.allocator(), "{s} is not running: this is its State's defaults (no save)", .{info.name});
+ var data_buf: [std.fs.max_path_bytes]u8 = undefined;
+ const save = if (options.state.len > 0)
+ try std.fmt.allocPrint(arena.allocator(), "{s}.xitdb", .{Host.stemOf(options.state)})
+ else
+ try std.fmt.allocPrint(arena.allocator(), "{s}/{s}/{s}.xitdb", .{ env.get("XDG_DATA_HOME") orelse try std.fmt.bufPrint(&data_buf, "{s}/.local/share", .{env.get("HOME") orelse "."}), info.name, info.name });
+ if (Sessions.openRead(gpa, io, save)) |opened| {
+ var s = opened;
+ defer s.deinit();
+ var events: std.ArrayList(abi.Event) = .empty;
+ defer events.deinit(gpa);
+ if (try s.present(&events)) |key| {
+ defer key.free(gpa);
+ _ = try memory.restore(arena.allocator(), key.layout, key.state, layout, bytes, sketch.defaults);
+ from = try std.fmt.allocPrint(arena.allocator(), "{s} is not running: this is its save's newest State, frame {d} of {s}", .{ info.name, key.frame, save });
+ }
+ } else |_| {}
+ const commands = try arena.allocator().alloc([]const u8, info.commands.len);
+ for (commands, info.commands) |*to, word| to.* = word;
+ var server: control.Control = .{ .allocator = gpa, .path = undefined, .listener = -1, .offline = .{ .layout = layout, .bytes = bytes, .completions = commands, .from = from } };
+ var fds: [2]i32 = undefined;
+ if (std.c.socketpair(std.c.AF.UNIX, std.c.SOCK.STREAM | std.c.SOCK.CLOEXEC, 0, &fds) != 0) return error.SocketPair;
+ const thread = try std.Thread.spawn(.{}, control.Control.serveOffline, .{ &server, fds[0] });
+ defer thread.join();
+ try f.init(io, .{ .socket = .{ .handle = fds[1], .address = undefined } }, user);
+ defer f.close();
+ return c9.verbs.run(&f, words, &in.interface, &out.interface, &err.interface);
+}
+
/// A save in a directory named `.sketchbook` (`zig build run`'s): the
/// directory is made, with a `.gitignore` of `*` (the save grows, and a jj
/// snapshot would commit it), and the state file an older build kept beside