1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
|
//! 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;
const upgrade = @import("upgrade.zig");
/// 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;
// Exec'd at an Upgrade (`execAgain`): for the view it had.
if (init.environ_map.get("PARDES_JOIN_VIEW")) |v| s.o.join_view = std.fmt.parseInt(u8, v, 10) catch null;
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, it could
/// not join again (`Start.said`), it left the session running (a Detach in
/// it), the session ended, with its code, or it runs another build now and
/// one is installed at this client's start path since it started: the
/// frontend lets its screen go and execs that, for this view (`execAgain`).
pub const Ended = union(enum) { done, gone, failed, left, ended: u8, upgrade: u8 };
/// An Upgrade's client again (`Ended.upgrade`), its frontend's screen let
/// go: this process exec'd as the file at its start path, an attach of the
/// same session through the same socket (a far one's forward, its ssh this
/// process's child still), joining for `view` (PARDES_JOIN_VIEW; far,
/// PARDES_REPLICA_FAR). The terminal's blink: no record crosses the exec.
/// Returns only when the exec failed: why.
pub fn execAgain(s: *Start, view: u8, size: ?[2]c_int) []const u8 {
const path = upgrade.exe() orelse return "Upgrade: this client does not know the path it was started from";
var at_buf: [4200]u8 = undefined;
const at = std.fmt.bufPrintSentinel(&at_buf, "--attach={s}:{s}", .{ s.dial.path, s.dial.session }, 0) catch return "Upgrade: the session's socket's path is too long to attach again by";
const argv = [_:null]?[*:0]const u8{ path, at };
// A window's new window the size it had (gui.zig reads it as a
// `--geometry`), not the default.
var size_buf: [48]u8 = undefined;
const sized: ?[*:0]const u8 = if (size) |wh| (std.fmt.bufPrintSentinel(&size_buf, "PARDES_JOIN_SIZE={d}x{d}", .{ wh[0], wh[1] }, 0) catch unreachable).ptr else null; // two c_ints fit 48
var view_buf: [32]u8 = undefined;
const joining = std.fmt.bufPrintSentinel(&view_buf, "PARDES_JOIN_VIEW={d}", .{view}, 0) catch unreachable; // a u8 fits 32
var n: usize = 0;
while (libc.environ[n] != null) n += 1;
const envp = s.gpa.allocSentinel(?[*:0]const u8, n + 3, null) catch return "Upgrade: no memory for this client's environment";
var k: usize = 0;
for (libc.environ[0..n]) |e| {
const entry = std.mem.span(e.?);
if (std.mem.startsWith(u8, entry, "PARDES_JOIN_VIEW=") or std.mem.startsWith(u8, entry, "PARDES_JOIN_SIZE=") or std.mem.startsWith(u8, entry, "PARDES_REPLICA_FAR=")) continue;
envp[k] = e;
k += 1;
}
envp[k] = joining.ptr;
k += 1;
if (sized) |e| {
envp[k] = e;
k += 1;
}
if (s.have != null) {
envp[k] = "PARDES_REPLICA_FAR=1";
k += 1;
}
envp[k] = null;
// The mask goes across an exec: the signals a terminal client blocks
// for its own sigwait (HUP, TERM) would stay blocked under a build that
// waits on fewer, a TERM never delivered.
const none = std.posix.sigemptyset();
std.posix.sigprocmask(std.posix.SIG.SETMASK, &none, null);
_ = libc.execve(path, &argv, envp.ptr);
return "Upgrade: the build at this client's start path would not start";
}
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, fell
/// too far behind (replica.behind_max_ms) or the session let it go
/// (to upgrade, or cut off); the frontend stays as it is.
pub fn run(l: *L, s: *Start) !Ended {
const link = &l.link;
// Its start path's file, for an Upgrade's question (`upgrade`).
upgrade.locate();
while (true) {
link.reset(s.r, &s.joined);
if (s.joined.booted) {
if (!l.confirm(s)) return .failed;
} else 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, .{ .again = s.r.diverged != null or link.lagged != 0, .close = link.close });
// 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);
// Its link cut with no word by a session that is there still
// (an Upgrade's exec): joined again, as when told so.
if (link.gone and link.refused == null and link.ended == null and !link.left and replica.cutListed("the session hung up", s.dial.session, s.have != null))
link.refused = std.heap.c_allocator.dupe(u8, replica.upgrading) catch null;
// 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();
if (link.left) return .left;
if (link.ended) |code| return .{ .ended = code };
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 {
if (replica.ended(&s.why)) return .gone;
if (replica.otherBuild(&s.why) and upgrade.replaced()) return .{ .upgrade = s.joined.view };
return .failed;
};
}
}
/// A pair's first join, its replica its own boot (replica.ownBoot): its
/// start's inputs held and its first pass drawn, then the session's
/// welcome read: the same core, what was held is sent; another (the
/// dump came), the dump's replica in place of the boot's, started
/// again. False, and why in `s.why`: no session to go on with.
fn confirm(l: *L, s: *Start) bool {
const link = &l.link;
link.held = .empty;
l.fe.start(l);
_ = l.before();
const r = replica.confirmBoot(s.gpa, &s.joined, s.r, s.o, &s.why) orelse {
link.release(s.gpa, false);
return false;
};
link.release(s.gpa, r == s.r);
if (r == s.r) return true;
s.r = r;
link.reset(r, &s.joined);
l.fe.start(l);
return true;
}
/// 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());
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());
}
|