summaryrefslogtreecommitdiff
path: root/runtime/client.zig
diff options
context:
space:
mode:
Diffstat (limited to 'runtime/client.zig')
-rw-r--r--runtime/client.zig391
1 files changed, 391 insertions, 0 deletions
diff --git a/runtime/client.zig b/runtime/client.zig
new file mode 100644
index 00000000..544be588
--- /dev/null
+++ b/runtime/client.zig
@@ -0,0 +1,391 @@
+//! A replica client's loop: the terminal's (dev/tui `runClient`) and the
+//! window's (dev/gui `clientSession`) alike, each over a frontend of its
+//! own. Its own core, loaded from the session's dump, applies its input at
+//! once (core/replica.zig); the session's units are the truth it rolls back
+//! to. The link and the replica are inside it; what a frontend does is:
+//!
+//! per pass, in its order:
+//! - `own(l) bool`: the frontend's own work over the frame it shows,
+//! before anything is drawn (a window's size posted, its font
+//! followed, a touchpad's rows, the pointer, the timedemo, a test's
+//! feed; a terminal has none). False ends the loop (a test feed's end).
+//! - `again(l) bool`: nothing to draw, but its own motion (a glide, a
+//! blink, a jump's trail) goes on: the last frame again, moved on;
+//! whether it was presented.
+//! - `deadline(l) u32`: when it wants to be woken for its own sake, ms
+//! (`forever`: never); 0 when it holds an input already (a terminal's
+//! queued key) or something is due at once. The loop wakes it a frame
+//! on while an echo is predicted, and for the quiet check.
+//! - `wait(l, ms)`: until an input, a message of the session's stream or
+//! `ms`: its inputs go in through `l.input`, the stream's messages
+//! through `l.take`, in their order.
+//! - `present(fe, surface) bool` (views.Present's): a frame shown, or held
+//! for the frontend's answer (owed); and `drawn() Drawn`, read after it:
+//! whether it wrote anything, and whether its own motion goes on.
+//! - `copy(text)`, `paste(l)`, `open(url)`: what its view asked of the
+//! machine it is shown on (the user's ruling: a client's yank fills
+//! the CLIENT's clipboard): register `+` to its clipboard, its
+//! clipboard asked for and sent back as a paste (through `l.input`,
+//! now or as its answer comes), a link opened.
+//! per join:
+//! - `start(l)`: a join's first inputs (what it is, its size).
+//! - `said(msg) bool`, `ended()`: the session's stream, from the reader's
+//! thread, onto the frontend's own queue (a terminal's event loop, a
+//! window's inbox and SDL's wake), so that its wait wakes for them.
+//! - `drop()`: what the reader queued, let go once the link has ended.
+const std = @import("std");
+const libc = std.c;
+const pardes = @import("core");
+const replica = pardes.replica;
+
+/// A wait with no wake of its own: until an input or a message.
+pub const forever: u32 = std.math.maxInt(u32);
+const frame_ms: u32 = @intCast(pardes.frame_ns / std.time.ns_per_ms);
+
+/// What a frame showed, read after its present.
+pub const Drawn = struct { drew: bool, moving: bool };
+
+/// The session a client dials: a socket's path or `<host>` (through ssh),
+/// the session's name, and whether it is far (its blobs by hash, its stream
+/// compressed).
+pub const Dial = struct { path: []const u8, session: []const u8, far: bool };
+
+/// What a client holds across its joins: its allocators, the addons it
+/// distrusts, its frame timings (Pardes.frames), the blobs it keeps when
+/// far, and its replica and link as joined. Made in place (`open`).
+pub const Start = struct {
+ gpa: std.mem.Allocator,
+ env: *std.process.Environ.Map,
+ dial: Dial,
+ have_store: replica.Have,
+ have: ?*replica.Have = null,
+ allocs: pardes.memory.Allocators,
+ o: pardes.Options,
+ distrusted: pardes.Addon.Distrusted = .{},
+ frames: pardes.FrameStats = .{},
+ joined: replica.Joined = undefined,
+ r: *replica.Replica = undefined,
+ why: [600]u8 = @splat(0),
+
+ /// The client's process made ready and its first join: false, and why
+ /// (`said`), when it cannot join.
+ pub fn open(s: *Start, init: std.process.Init, opts: pardes.Options, dial: Dial) bool {
+ const io = init.io;
+ // Far (through ssh, or PARDES_REPLICA_FAR=1): its join's blobs by
+ // hash, those it holds kept from the link, and its stream in zstd.
+ // A client on this machine's own socket is sent the dump whole: a
+ // hash and a compression there cost more than the bytes.
+ const far = if (init.environ_map.get("PARDES_REPLICA_FAR")) |v| std.mem.eql(u8, v, "1") else dial.far;
+ s.* = .{
+ .gpa = init.gpa,
+ .env = init.environ_map,
+ .dial = dial,
+ .have_store = if (far) .init(io) else .{ .io = io },
+ .allocs = pardes.memory.init(init.gpa),
+ .o = opts,
+ };
+ if (far) s.have = &s.have_store;
+ pardes.Term.start(s.allocs.image);
+ pardes.Kind.heap = s.allocs.addon;
+ pardes.syntax.start(s.allocs.tree_sitter);
+ s.o.image_allocator = s.allocs.image;
+ s.o.distrusted = &s.distrusted;
+ // Its frame timings, this process's (Pardes.frames).
+ s.o.frames = &s.frames;
+ s.r = replica.join(s.gpa, &s.joined, dial.path, dial.session, s.o, s.have, &s.why, null) orelse return false;
+ return true;
+ }
+
+ pub fn close(s: *Start) void {
+ pardes.Term.stop();
+ pardes.syntax.stop();
+ pardes.memory.deinit();
+ s.have_store.deinit();
+ }
+
+ /// Why it could not join.
+ pub fn said(s: *const Start) []const u8 {
+ return std.mem.sliceTo(&s.why, 0);
+ }
+};
+
+/// How a client's joins ended: it quit, the session let it go, or it could
+/// not join again (`Start.said`).
+pub const Ended = enum { done, gone, failed };
+
+pub fn Loop(comptime Frontend: type) type {
+ return struct {
+ const L = @This();
+
+ link: replica.Link,
+ fe: *Frontend,
+ frames: *pardes.FrameStats,
+
+ pub fn init(fe: *Frontend, s: *Start) !L {
+ var l: L = .{ .link = .{ .r = s.r, .fd = s.joined.fd }, .fe = fe, .frames = &s.frames };
+ try l.link.fromEnv(s.gpa, s.env);
+ return l;
+ }
+
+ /// The frontend's input: applied at once, and sent to the session.
+ pub fn input(l: *L, ev: pardes.Event) void {
+ l.link.input(ev);
+ }
+
+ /// A message of the session's stream, in its order.
+ pub fn take(l: *L, msg: replica.Said) void {
+ l.link.take(msg);
+ }
+
+ /// A join a pass: the first, and one after the replica diverged or
+ /// the session let it go to upgrade; the frontend stays as it is.
+ pub fn run(l: *L, s: *Start) !Ended {
+ const link = &l.link;
+ while (true) {
+ link.reset(s.r, &s.joined);
+ l.fe.start(l);
+ var done: std.atomic.Value(bool) = .init(false);
+ const reader = try std.Thread.spawn(.{}, read, .{ l, s, &done });
+ while (!link.quit) {
+ if (!l.pass()) break;
+ l.after();
+ }
+ if (s.env.get("PARDES_REPLICA_STATS")) |file| link.writeStats(file);
+ if (!link.gone) replica.bye(s.joined.fd, s.r.diverged != null);
+ // The link's reader ends with the link, posting as it goes:
+ // what it posted is let go until it has (a terminal's queue
+ // is bounded: a reader blocked on it would never end).
+ _ = libc.shutdown(s.joined.fd, 2);
+ while (true) {
+ const ended = done.load(.acquire);
+ l.fe.drop();
+ if (ended) break;
+ std.Thread.yield() catch {};
+ }
+ reader.join();
+ _ = libc.close(s.joined.fd);
+ s.joined.rest.deinit(s.gpa);
+ // Why it joins again is in its notice until a key.
+ if (!link.rejoins()) {
+ // What it made since it joined, kept for its next start.
+ if (s.have) |h| h.keep(s.r.core());
+ s.r.deinit();
+ return if (link.gone) .gone else .done;
+ }
+ // The session again, the core it leaves held meanwhile: its
+ // blobs are not sent again.
+ s.r = replica.join(s.gpa, &s.joined, s.dial.path, s.dial.session, s.o, s.have, &s.why, s.r) orelse return .failed;
+ }
+ }
+
+ /// The session's stream, onto the frontend's queue: its messages,
+ /// and its end.
+ fn read(l: *L, s: *Start, done: *std.atomic.Value(bool)) void {
+ defer done.store(true, .release);
+ replica.readLink(s.gpa, s.joined.fd, &s.joined.rest, l.fe, Frontend.said);
+ l.fe.ended();
+ }
+
+ /// A pass up to its wait, and the wait: false when the frontend
+ /// ended the loop.
+ pub fn pass(l: *L) bool {
+ const ms = l.before() orelse return false;
+ l.fe.wait(l, ms);
+ return true;
+ }
+
+ /// The loop of a frontend that is woken from outside (the soak's,
+ /// test/replicas.zig, whose clock and link are a simulation's):
+ /// what woke it taken already (`input`, `take`), the rest of the
+ /// pass and the next up to its wait, as `run` goes round.
+ pub fn woken(l: *L) void {
+ l.after();
+ if (!l.link.quit) _ = l.pass();
+ }
+
+ /// A pass up to its wait: the frontend's own work, its predicted
+ /// echo judged and caught up (once a frame), its view drawn if
+ /// anything changed (else its own motion moved on), and how long
+ /// it may wait; idle, the copy is taken so that the next input
+ /// needs none. Null: the frontend ended it.
+ pub fn before(l: *L) ?u32 {
+ const link = &l.link;
+ const r = link.r;
+ if (!l.fe.own(l)) return null;
+ if (r.echoFrame()) link.dirty = true;
+ if (link.dirty) l.draw() else if (l.fe.again(l)) link.again += 1;
+ var ms = l.fe.deadline(l);
+ if (r.echo.n > 0 or r.echo.cursor != null or r.echo.nd > 0) ms = @min(ms, frame_ms);
+ if (link.quietCheck()) |quiet| ms = @min(ms, quiet);
+ if (ms != 0) r.ready();
+ return ms;
+ }
+
+ /// The pass after its wait: its inputs settled; a rollback since it
+ /// drew is drawn again, never moved on from cells the copy put
+ /// back, and so is a frame owed or an echo changed.
+ pub fn after(l: *L) void {
+ const link = &l.link;
+ const r = link.r;
+ r.settle();
+ if (r.moved) {
+ r.moved = false;
+ link.dirty = true;
+ }
+ if (link.owed or r.echo.changed) link.dirty = true;
+ if (r.diverged != null) link.quit = true;
+ l.asks();
+ }
+
+ /// What the view asked of its frontend since it last looked (the
+ /// session's host does not do it for a view a client draws): a
+ /// yank's register `+` copied out, the clipboard asked for, a link
+ /// opened. Each once: a count a rollback put back and made again
+ /// is not a second.
+ fn asks(l: *L) void {
+ const link = &l.link;
+ const c = link.r.core();
+ const v = if (c.views[link.r.view]) |*v| v else return;
+ if (ahead(v.yanks, link.yanks)) {
+ link.yanks = v.yanks;
+ l.fe.copy(c.registers.text(c.gpa, '+') orelse "");
+ }
+ if (ahead(v.pastes, link.pastes)) {
+ link.pastes = v.pastes;
+ l.fe.paste(l);
+ }
+ if (ahead(v.links, link.links)) {
+ link.links = v.links;
+ l.fe.open(v.link.slice());
+ }
+ }
+
+ fn ahead(now: u32, seen: u32) bool {
+ return @as(i32, @bitCast(now -% seen)) > 0;
+ }
+
+ /// Its own view drawn by the frontend, outside any step: the
+ /// replica's digest stays the session's (views.drawOne); the frame
+ /// timings are this process's.
+ fn draw(l: *L) void {
+ const frames = l.frames;
+ frames.mark_start = pardes.FrameStats.nowNs();
+ frames.mark_update = frames.mark_start;
+ // A frontend that marks its render's end does so as it presents.
+ frames.mark_render = frames.mark_update;
+ l.link.owed = !l.link.r.draw(.{ .ctx = l.fe, .f = Frontend.present });
+ const shown = l.fe.drawn();
+ frames.record(pardes.FrameStats.nowNs(), shown.moving, l.link.owed);
+ l.link.drawn(shown.drew);
+ }
+ };
+}
+
+// ---- a client's clipboard and links are its frontend's ----
+
+/// A frontend that draws nothing and counts what its view asked of it.
+const Null = struct {
+ copied: u32 = 0,
+ pasted: u32 = 0,
+ opened: u32 = 0,
+ text: [64]u8 = undefined,
+ text_len: usize = 0,
+ url: [64]u8 = undefined,
+ url_len: usize = 0,
+
+ const L = Loop(Null);
+ pub fn own(_: *Null, _: *L) bool {
+ return true;
+ }
+ pub fn again(_: *Null, _: *L) bool {
+ return false;
+ }
+ pub fn deadline(_: *Null, _: *L) u32 {
+ return forever;
+ }
+ pub fn wait(_: *Null, _: *L, _: u32) void {}
+ pub fn present(_: ?*anyopaque, _: *const pardes.Surface) bool {
+ return true;
+ }
+ pub fn drawn(_: *Null) Drawn {
+ return .{ .drew = true, .moving = false };
+ }
+ pub fn copy(n: *Null, text: []const u8) void {
+ n.copied += 1;
+ n.text_len = @min(text.len, n.text.len);
+ @memcpy(n.text[0..n.text_len], text[0..n.text_len]);
+ }
+ pub fn paste(n: *Null, _: *L) void {
+ n.pasted += 1;
+ }
+ pub fn open(n: *Null, url: []const u8) void {
+ n.opened += 1;
+ n.url_len = @min(url.len, n.url.len);
+ @memcpy(n.url[0..n.url_len], url[0..n.url_len]);
+ }
+};
+
+/// The session's host, which counts what it is asked of the clipboard and
+/// links.
+const AskedHost = struct {
+ yanked: u32 = 0,
+ asked: u32 = 0,
+ linked: u32 = 0,
+ fn of(ctx: ?*anyopaque) *AskedHost {
+ return @ptrCast(@alignCast(ctx.?));
+ }
+ fn setClipboard(ctx: ?*anyopaque, _: []const u8) void {
+ of(ctx).yanked += 1;
+ }
+ fn readClipboard(ctx: ?*anyopaque) void {
+ of(ctx).asked += 1;
+ }
+ fn openLink(ctx: ?*anyopaque, _: []const u8) void {
+ of(ctx).linked += 1;
+ }
+ const vtable = replica.everyEntry(.{ .set_clipboard = setClipboard, .read_clipboard = readClipboard, .open_link = openLink });
+ fn host(h: *AskedHost) pardes.Host {
+ return .{ .ctx = h, .vtable = &vtable };
+ }
+};
+
+test "a client's yank, paste and link reach its own frontend once each, through the loop, and the session's host is asked none of them" {
+ const gpa = std.testing.allocator;
+ var h: AskedHost = .{};
+ const a = try replica.Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, h.host(), false);
+ defer a.deinit();
+ _ = try a.unit(0, 0);
+ const j = (try a.join(1, null)) orelse return error.NoView;
+ defer gpa.free(j.dump);
+ const r = try replica.Replica.initDump(gpa, 1, j.view, j.dump, .{ .cols = 80, .rows = 24 });
+ defer r.deinit();
+ var fds: [2]c_int = undefined;
+ if (libc.socketpair(libc.AF.UNIX, libc.SOCK.STREAM | libc.SOCK.CLOEXEC, 0, &fds) != 0) return error.NoSocket;
+ defer for (fds) |fd| {
+ _ = libc.close(fd);
+ };
+ var frames: pardes.FrameStats = .{};
+ var n: Null = .{};
+ var l: Null.L = .{ .link = .{ .r = r, .fd = fds[1] }, .fe = &n, .frames = &frames };
+ const joined: replica.Joined = .{ .fd = fds[1], .pid = 0, .client = 1, .view = j.view, .gmtoff = 0, .dump = &.{} };
+ l.link.reset(r, &joined);
+ _ = l.pass();
+ var sink: [1 << 14]u8 = undefined;
+ for ([_][]const u8{ "ClipYank", "ClipPaste", "Look https://ziglang.org" }) |cmd| {
+ l.input(.{ .command = cmd });
+ const msg = try gpa.dupe(u8, r.out.items);
+ defer gpa.free(msg);
+ // At once, by its own step; and not again when the session's unit
+ // confirms it.
+ l.woken();
+ l.take(.{ .unit = try std.heap.c_allocator.dupe(u8, try a.take(msg)) });
+ l.woken();
+ _ = libc.read(fds[0], &sink, sink.len);
+ }
+ try std.testing.expectEqual(@as(u32, 1), n.copied);
+ try std.testing.expectEqual(@as(u32, 1), n.pasted);
+ try std.testing.expectEqual(@as(u32, 1), n.opened);
+ try std.testing.expectEqualStrings("https://ziglang.org", n.url[0..n.url_len]);
+ try std.testing.expectEqual(@as(u32, 0), h.yanked + h.asked + h.linked);
+ try std.testing.expect(r.diverged == null and r.quiet());
+}