summaryrefslogtreecommitdiff
path: root/test/process/look_and_exec.zig
blob: 9829797b8af6ddf396c84d65384a170376f7f07c (plain) (blame)
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
//! docs/typ/reference.typ, look and exec <look-and-exec>: one session
//! driven as the dogfood agents drive it (test/fs.py's workflow_canary).
const std = @import("std");
const process = @import("../process.zig");
const Conn = process.Conn;
const has = process.has;
const check = process.check;

pub const cases = .{
    .{ "look-and-exec: the canary: Look, Grep and Find hit and miss, a word looked at, Edit and Save, get, pty/run, Kill, a REPL send, columns, ask and answer, Dump and Restore, in under 30 s", canary },
};

const Flow = struct {
    a: std.mem.Allocator,
    c: *Conn,

    fn log(f: Flow) ![]const u8 {
        return f.c.read(f.a, "/log");
    }

    /// Waits up to 10 s for the log to hold `text`.
    fn waitLog(f: Flow, text: []const u8) !void {
        const deadline = process.nowMs() + 10_000;
        while (!has(try f.log(), text)) {
            if (process.nowMs() > deadline) {
                std.debug.print("not in the log: {s}\n", .{text});
                return error.Timeout;
            }
            process.nap(50);
        }
    }

    /// The pane an exec at `serial` made, as exec reads it back.
    fn madeBy(f: Flow, serial: u32, line: []const u8) !u32 {
        try f.c.exec(serial, line);
        var words = std.mem.tokenizeAny(u8, try f.c.pane(f.a, serial, "exec"), " \n");
        var last: []const u8 = "";
        while (words.next()) |w| last = w;
        return std.fmt.parseInt(u32, last, 10);
    }

    /// A line run in terminal `term` through pty/run: its answer.
    fn run(f: Flow, term: u32, line: []const u8) ![]const u8 {
        const fid = try f.c.hold(try std.fmt.allocPrint(f.a, "/pane/{d}/pty/run", .{term}), 2);
        defer f.c.clunk(fid);
        _ = try f.c.writeFid(fid, 0, line);
        return f.a.dupe(u8, try f.c.readFid(fid, 0, 65536));
    }

    /// An event record written back on pane `n`'s event, as a reader acts.
    fn event(f: Flow, n: u32, record: []const u8) !void {
        const fid = try f.c.hold(try std.fmt.allocPrint(f.a, "/pane/{d}/event", .{n}), 2);
        defer f.c.clunk(fid);
        _ = try f.c.writeFid(fid, 0, record);
    }

    fn columns(f: Flow) !usize {
        var n: usize = 0;
        var rows = std.mem.tokenizeScalar(u8, try f.c.read(f.a, "/layout"), '\n');
        while (rows.next()) |row| n += @intFromBool(!std.mem.startsWith(u8, row, "active"));
        return n;
    }
};

fn canary(gpa: std.mem.Allocator, exe: [:0]const u8) !void {
    const started = process.nowMs();
    var arena = std.heap.ArenaAllocator.init(gpa);
    defer arena.deinit();
    const a = arena.allocator();
    var d = try process.Detached.start(gpa, exe, "flow", .{});
    defer d.deinit();
    try d.put("a.txt", "alpha one\nshared word\n");
    try d.put("b.txt", "beta two\nshared word\n");
    try d.put("s.sh", "echo from-file\n");
    const root = d.root();
    const c = try Conn.dial(gpa, d.socket());
    defer c.deinit(gpa);
    const f: Flow = .{ .a = a, .c = c };

    // Look opens files, and the log says new.
    const pa = try c.look(a, d.abs("a.txt"), null);
    const pb = try c.look(a, d.abs("b.txt"), null);
    try std.testing.expectEqualStrings("alpha one\nshared word\n", try c.pane(a, pa, "body"));
    try check(has(try f.log(), try std.fmt.allocPrint(a, "new {d} {s}/a.txt\n", .{ pa, root })) and
        has(try f.log(), try std.fmt.allocPrint(a, "new {d} {s}/b.txt\n", .{ pb, root })), "no new records", .{});

    // Grep and Find: a hit fills its query pane, line 1 the query and the
    // lines under each file's name; a miss fails ENOENT.
    const grep = try f.madeBy(pa, "Grep shared\n");
    try std.testing.expectEqualStrings("Grep shared\na.txt\na.txt:2:1    shared word\nb.txt\nb.txt:2:1    shared word\n", try c.pane(a, grep, "body"));
    try c.removePane(grep);
    try c.execRefused(pa, "Grep zzqqnomatch\n", "Grep: text not found");
    const found = try f.madeBy(pa, "Find b.txt\n");
    try check(has(try c.pane(a, found, "body"), "b.txt"), "Find found nothing", .{});
    try c.removePane(found);
    try c.execRefused(pa, "Find zzqqnomatch\n", "Find: name not found");

    // A plain word looked at is found in the pane, after its dot.
    try c.write(try std.fmt.allocPrint(a, "/pane/{d}/dot", .{pa}), "          0           0 ");
    try c.write(try std.fmt.allocPrint(a, "/pane/{d}/look", .{pa}), "shared\n");
    {
        var it = std.mem.tokenizeAny(u8, try c.pane(a, pa, "dot"), " \n");
        try check(std.mem.eql(u8, it.next().?, "10") and std.mem.eql(u8, it.next().?, "16"), "the word not found after dot", .{});
    }

    // Edit in two files, then Save each: on disk, and logged.
    for ([_]u32{ pa, pb }) |n| try c.write(try std.fmt.allocPrint(a, "/pane/{d}/ctl", .{n}), "Edit ,s/shared/SHARED/g\n");
    try std.testing.expectEqualStrings("beta two\nSHARED word\n", try c.pane(a, pb, "body"));
    for ([_]u32{ pa, pb }) |n| try c.exec(n, "Save\n");
    try std.testing.expectEqualStrings("alpha one\nSHARED word\n", try d.get(a, "a.txt"));
    try check(has(try f.log(), try std.fmt.allocPrint(a, "save {d} {s}/a.txt\n", .{ pa, root })) and
        has(try f.log(), try std.fmt.allocPrint(a, "save {d} {s}/b.txt\n", .{ pb, root })), "no save records", .{});

    // get reloads what changed on disk.
    try d.put("b.txt", "from disk\n");
    try c.write(try std.fmt.allocPrint(a, "/pane/{d}/ctl", .{pb}), "get\n");
    try std.testing.expectEqualStrings("from disk\n", try c.pane(a, pb, "body"));

    // A terminal: pty/run failing then passing.
    const term = try f.madeBy(1, "Term\n");
    {
        const deadline = process.nowMs() + 10_000;
        while (true) {
            const answer = try f.run(term, "true\n");
            if (std.mem.eql(u8, answer, "exit 0\n")) break;
            if (process.nowMs() > deadline) {
                std.debug.print("pty/run answered {s}\n", .{answer});
                return error.Timeout;
            }
            process.nap(50);
        }
    }
    try std.testing.expectEqualStrings("exit 1\n", try f.run(term, "false\n"));
    try std.testing.expectEqualStrings("exit 0\npassed\n", try f.run(term, "echo passed\n"));
    // (A run's answer is its record: the log has no err for these.)
    try check(!has(try f.log(), try std.fmt.allocPrint(a, "err {d} pty/run", .{term})), "pty/run logged an err", .{});

    // A command pane, and Kill: its exit is logged.
    const sleeper = try f.madeBy(pa, "sleep 30\n");
    try check(has(try f.log(), try std.fmt.allocPrint(a, "run {d} sleep 30\n", .{sleeper})), "no run record", .{});
    try c.write("/ctl", "Kill sleep\n");
    try f.waitLog(try std.fmt.allocPrint(a, "\nexit {d} ", .{sleeper}));

    // A REPL send: a program in the terminal (cat, which says back what it
    // is sent) bound as bash's REPL; an exec on a .sh file's body (its event
    // written back) goes there.
    const s = try c.look(a, d.abs("s.sh"), null);
    try c.write(try std.fmt.allocPrint(a, "/pane/{d}/pty/data", .{term}), "cat\r");
    {
        const deadline = process.nowMs() + 10_000;
        while (true) {
            const status = std.mem.trimEnd(u8, try c.pane(a, term, "pty/status"), " \n");
            if (std.mem.endsWith(u8, status, " 1") or std.mem.eql(u8, status, "1")) break;
            if (process.nowMs() > deadline) return error.ReplNeverStarted;
            process.nap(50);
        }
    }
    try c.write(try std.fmt.allocPrint(a, "/pane/{d}/ctl", .{term}), "Repl bash\n");
    try f.event(s, "MX0 0 0 14 echo from-file\n");
    try f.waitLog(try std.fmt.allocPrint(a, "\nsend {d} {d} ", .{ s, term }));
    {
        const deadline = process.nowMs() + 10_000;
        while (std.mem.count(u8, try c.pane(a, term, "body"), "echo from-file") < 2) {
            if (process.nowMs() > deadline) return error.ReplNeverGotIt;
            process.nap(50);
        }
    }
    try c.write(try std.fmt.allocPrint(a, "/pane/{d}/ctl", .{term}), "Repl -\n");
    try c.write(try std.fmt.allocPrint(a, "/pane/{d}/pty/data", .{term}), "\x04");
    {
        const deadline = process.nowMs() + 10_000;
        while (!std.mem.eql(u8, try f.run(term, "true\n"), "exit 0\n")) {
            if (process.nowMs() > deadline) return error.ShellNeverBack;
            process.nap(50);
        }
    }

    // The layout and a column's files: Newcol, its tag, rmdir.
    try check(std.mem.count(u8, try c.read(a, "/layout"), "\n") >= 2, "no column in /layout", .{}); // a column, then `active`
    try c.write("/ctl", "Newcol\n");
    try std.testing.expectEqual(@as(usize, 2), try f.columns());
    const empty = blk: {
        var rows = std.mem.tokenizeScalar(u8, try c.read(a, "/layout"), '\n');
        var last: []const u8 = "";
        while (rows.next()) |row| if (!std.mem.startsWith(u8, row, "active")) {
            last = row;
        };
        break :blk std.mem.sliceTo(last, ' ');
    };
    try check(has(try c.read(a, try std.fmt.allocPrint(a, "/col/{s}/tag", .{empty})), "New"), "a column's tag has no New", .{});
    try c.remove(try std.fmt.allocPrint(a, "/col/{s}", .{empty}));
    try std.testing.expectEqual(@as(usize, 1), try f.columns());

    // ask/answer: Save on a terminal asks for a path over 9P.
    try c.exec(term, "Save\n");
    try f.waitLog(try std.fmt.allocPrint(a, "ask {d} save path\n", .{term}));
    try c.write(try std.fmt.allocPrint(a, "/pane/{d}/ctl", .{term}), try std.fmt.allocPrint(a, "answer {s}/scroll.txt\n", .{root}));
    {
        const deadline = process.nowMs() + 10_000;
        while (!d.exists("scroll.txt")) {
            if (process.nowMs() > deadline) return error.AnsweredSaveWroteNothing;
            process.nap(50);
        }
    }
    try check(has(try f.log(), try std.fmt.allocPrint(a, "answer {d} {s}/scroll.txt\n", .{ term, root })), "no answer record", .{});

    // Dump, then Restore it: the new session names its panes.
    try c.write("/ctl", "Dump\n");
    const saved = d.abs("flow.dump.zon");
    {
        const deadline = process.nowMs() + 10_000;
        while (!d.exists("flow.dump.zon")) {
            if (process.nowMs() > deadline) return error.DumpWroteNothing;
            process.nap(50);
        }
    }
    try check(has(try f.log(), try std.fmt.allocPrint(a, "dump {s}\n", .{saved})), "no dump record", .{});
    c.write("/ctl", try std.fmt.allocPrint(a, "Restore {s}\n", .{saved})) catch {};
    process.nap(500);
    const restored = try Conn.dial(gpa, d.socket());
    defer restored.deinit(gpa);
    const r: Flow = .{ .a = a, .c = restored };
    try r.waitLog(try std.fmt.allocPrint(a, "restore {s}", .{saved}));
    const names = try restored.read(a, "/index");
    try check(has(names, d.abs("a.txt")) and has(names, d.abs("b.txt")), "restored {s}", .{names});
    // Recent goes on across the Restore, and is kept after it.
    try check(has(try restored.read(a, "/recent"), try std.fmt.allocPrint(a, "{s}/a.txt\n", .{root})), "Recent lost", .{});
    try d.put("after.txt", "after\n");
    _ = try restored.look(a, d.abs("after.txt"), null);
    try check(has(try restored.read(a, "/recent"), try std.fmt.allocPrint(a, "open {s}/after.txt\n", .{root})), "no open in Recent", .{});
    {
        const deadline = process.nowMs() + 10_000;
        // Recent's lines are a value of the state file, as they are.
        while (!has(d.get(a, ".local/share/pardes/pardes.xitdb") catch "", d.abs("after.txt"))) {
            if (process.nowMs() > deadline) return error.RecentNotKept;
            process.nap(50);
        }
    }
    try check(process.nowMs() - started < 30_000, "the canary took {d} ms", .{process.nowMs() - started});
}