Repository navigation
Expand file tree
/
Copy pathVcsProcess.test.ts
More file actions
597 lines (558 loc) · 22.1 KB
/
Copy pathVcsProcess.test.ts
File metadata and controls
597 lines (558 loc) · 22.1 KB
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
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, describe, expect, it } from "@effect/vitest";
import * as HostProcess from "@t3tools/shared/HostProcess";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Cause from "effect/Cause";
import * as Fiber from "effect/Fiber";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Queue from "effect/Queue";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as TestClock from "effect/testing/TestClock";
import { ChildProcessSpawner } from "effect/process";
import { VcsProcessExitError, VcsProcessSpawnError } from "@t3tools/contracts";
import * as ProcessRunner from "../processRunner.ts";
import * as VcsProcess from "./VcsProcess.ts";
const encodeExitError = Schema.encodeEffect(Schema.fromJsonString(VcsProcessExitError));
const run = (input: VcsProcess.VcsProcessInput) =>
Effect.gen(function* () {
const process = yield* VcsProcess.VcsProcess;
return yield* process.run(input);
});
const layerLive = VcsProcess.layer.pipe(Layer.provide(NodeServices.layer));
const provideLive = <A, E, R>(effect: Effect.Effect<A, E, R | VcsProcess.VcsProcess>) =>
effect.pipe(Effect.provide(layerLive));
const baseInput = {
operation: "test.process-boundary",
command: "git",
args: ["status", "--short"],
cwd: "/workspace",
} satisfies VcsProcess.VcsProcessInput;
const captureProcessResult = (
result: Effect.Effect<ProcessRunner.ProcessRunOutput, ProcessRunner.ProcessRunError>,
) =>
VcsProcess.make.pipe(
Effect.provideService(
ProcessRunner.ProcessRunner,
ProcessRunner.ProcessRunner.of({ run: () => result }),
),
Effect.flatMap((service) => service.run(baseInput)),
Effect.flip,
);
describe("VcsProcess.run", () => {
it.effect("explains a locked Git index and allows restore after the lock is released", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-index-lock-" });
const git = (args: readonly string[]) =>
run({ operation: "test.checkpoint.restore", command: "git", cwd, args });
yield* git(["init"]);
const file = path.join(cwd, "README.md");
yield* fs.writeFileString(file, "before\n");
yield* git(["add", "README.md"]);
yield* git([
"-c",
"user.name=Test",
"-c",
"user.email=test@example.com",
"commit",
"-m",
"initial",
]);
yield* fs.writeFileString(file, "after\n");
const lock = path.join(cwd, ".git", "index.lock");
yield* fs.writeFileString(lock, "held by another process\n");
const restore = ["restore", "--source=HEAD", "--worktree", "--staged", "--", "README.md"];
const error = yield* Effect.flip(git(restore));
expect(error).toBeInstanceOf(VcsProcessExitError);
expect(error).toMatchObject({
exitCode: 128,
failureKind: "command-failed",
detail: "Git's index is locked. Wait for other Git operations to finish, then try again.",
});
expect(error.message).not.toContain("index.lock");
expect(yield* fs.readFileString(file)).toBe("after\n");
expect(yield* fs.readFileString(lock)).toBe("held by another process\n");
yield* fs.remove(lock);
yield* git(restore);
expect(yield* fs.readFileString(file)).toBe("before\n");
}).pipe(provideLive, Effect.provide(NodeServices.layer), Effect.scoped),
);
it.effect.each([
{
stderr: "fatal: Unable to create '/private/repo/index.lock': File exists",
retryable: true,
detail: "Git's index is locked. Wait for other Git operations to finish, then try again.",
},
{
stderr: "fatal: Unable to create 'C:\\private\\repo\\.git\\index.lock': File exists.",
retryable: true,
detail: "Git's index is locked. Wait for other Git operations to finish, then try again.",
},
{
stderr: "fatal: Unable to create '/private/repo/.git/config.lock': File exists.",
retryable: true,
},
{
stderr: "fatal: Unable to create '/private/repo/index.lock': Permission denied",
retryable: false,
},
{ stderr: 'error: open("/private/repo/file"): No such file or directory', retryable: true },
{
stderr: "fatal: unable to stat '/private/repo/file': No such file or directory",
retryable: true,
},
{ stderr: 'error: open("/private/repo/file"): Permission denied', retryable: false },
{
stderr: "error: '/private/repo/child/' does not have a commit checked out",
retryable: false,
},
{ stderr: "fatal: index file corrupt", retryable: false },
])(
"classifies Git exit retryability and safe detail without retaining stderr: $stderr",
({ stderr, retryable, detail = "Process exited with a non-zero status." }) =>
Effect.gen(function* () {
const error = yield* captureProcessResult(
Effect.succeed({
stdout: "",
stderr,
code: ChildProcessSpawner.ExitCode(128),
timedOut: false,
stdoutTruncated: false,
stderrTruncated: false,
stdoutInvalidUtf8: false,
stderrInvalidUtf8: false,
}),
);
assert.instanceOf(error, VcsProcessExitError);
expect(error.retryable === true).toBe(retryable);
expect(error.detail).toBe(detail);
const encoded = yield* encodeExitError(error);
expect(encoded).not.toContain("private");
}),
);
// Without LANG, macOS Git follows the system language, as in an app launched from Finder.
it.effect("reads Git failures in English when Git would follow the system language", () =>
Effect.gen(function* () {
let attempts = 0;
const service = yield* VcsProcess.make.pipe(
Effect.provideService(
ProcessRunner.ProcessRunner,
ProcessRunner.ProcessRunner.of({
run: (input) =>
Effect.sync(() => {
attempts += 1;
return {
stdout: "",
stderr:
attempts % 2 === 0
? ""
: input.env?.LANGUAGE === "C"
? "fatal: Unable to create '/private/repo/.git/index.lock': File exists.\n"
: "致命錯誤: 無法建立「/private/repo/.git/index.lock」:File exists。\n",
code: ChildProcessSpawner.ExitCode(attempts % 2 === 0 ? 0 : 128),
timedOut: false,
stdoutTruncated: false,
stderrTruncated: false,
stdoutInvalidUtf8: false,
stderrInvalidUtf8: false,
};
}),
}),
),
);
const capture = yield* service
.run({
...baseInput,
operation: VcsProcess.CHECKPOINT_CAPTURE_OPERATION,
args: ["add", "--all"],
})
.pipe(Effect.exit, Effect.forkChild({ startImmediately: true }));
yield* TestClock.adjust("1 second");
expect(Exit.isSuccess(yield* Fiber.join(capture))).toBe(true);
expect(attempts).toBe(2);
attempts = 0;
const error = yield* Effect.flip(service.run(baseInput));
assert.instanceOf(error, VcsProcessExitError);
expect(error.detail).toBe(VcsProcess.GIT_INDEX_LOCKED_DETAIL);
}),
);
it.effect.each([
{
stderr: "fatal: fsync error on '.git/objects/a5/tmp_obj_Pseg66': Operation not supported",
fsyncMethods: ["fsync", "writeout-only"],
},
{
stderr:
"fatal: update_ref failed for ref 'refs/t3/checkpoints/x': cannot update ref 'refs/t3/checkpoints/x': couldn't write '/Volumes/share/.git/refs/t3/checkpoints/x.lock'",
fsyncMethods: ["fsync", "writeout-only"],
},
{ stderr: "fatal: Operation not supported", fsyncMethods: ["fsync"] },
{
stderr:
"fatal: update_ref failed for ref 'refs/t3/checkpoints/x': cannot update ref 'refs/t3/checkpoints/x': couldn't write '/Volumes/share/.git/refs/t3/checkpoints/x.lock': Input/output error",
fsyncMethods: ["fsync"],
},
{
stderr: "fatal: fsync error on '.git/objects/a5/tmp_obj_Pseg66': Operation not supported",
fsyncMethods: ["fsync", "writeout-only"],
fallbackFails: true,
},
{
platform: "linux",
stderr: "fatal: fsync error on '.git/objects/a5/tmp_obj_Pseg66': Operation not supported",
fsyncMethods: ["fsync"],
},
{
operation: baseInput.operation,
stderr: "fatal: fsync error on '.git/objects/a5/tmp_obj_Pseg66': Operation not supported",
fsyncMethods: ["fsync"],
},
{
stderr: "fatal: fsync error on '.git/objects/bulk_fsync_Pseg66': Operation not supported",
fsyncMethods: ["batch", "writeout-only"],
},
{
stderr:
"fatal: update_ref failed for ref 'refs/t3/checkpoints/x': cannot update ref 'refs/t3/checkpoints/x': couldn't write '/Volumes/share/.git/refs/t3/checkpoints/x.lock'",
fsyncMethods: ["batch", "writeout-only"],
},
] as const)(
"falls back to writeout-only only for unsupported flushes on macOS ($fsyncMethods): $stderr",
({ stderr, fsyncMethods, ...scenario }) =>
Effect.gen(function* () {
const seen: Array<ReadonlyArray<string>> = [];
const service = yield* VcsProcess.make.pipe(
Effect.provideService(
HostProcess.Platform,
"platform" in scenario ? scenario.platform : "darwin",
),
Effect.provideService(ProcessRunner.ProcessRunner, {
run: (input) =>
Effect.sync(() => {
seen.push(input.args);
const failed =
input.args.includes(`core.fsyncMethod=${fsyncMethods[0]}`) ||
("fallbackFails" in scenario && scenario.fallbackFails);
return {
stdout: "",
stderr: failed ? stderr : "",
code: ChildProcessSpawner.ExitCode(failed ? 128 : 0),
timedOut: false,
stdoutTruncated: false,
stderrTruncated: false,
stdoutInvalidUtf8: false,
stderrInvalidUtf8: false,
};
}),
}),
);
const exit = yield* service
.run({
...baseInput,
operation:
"operation" in scenario
? scenario.operation
: VcsProcess.CHECKPOINT_CAPTURE_OPERATION,
args: [
"-c",
"core.fsync=objects,reference",
"-c",
...(fsyncMethods[0] === "batch" ? ["core.fsyncMethod=fsync", "-c"] : []),
`core.fsyncMethod=${fsyncMethods[0]}`,
"add",
],
})
.pipe(Effect.exit);
expect(seen).toEqual(
fsyncMethods.map((method) => [
"-c",
"core.fsync=objects,reference",
"-c",
...(fsyncMethods[0] === "batch"
? [`core.fsyncMethod=${method === "batch" ? "fsync" : method}`, "-c"]
: []),
`core.fsyncMethod=${method}`,
"add",
]),
);
expect(Exit.isSuccess(exit)).toBe(
fsyncMethods.length === 2 && !("fallbackFails" in scenario && scenario.fallbackFails),
);
if (Exit.isFailure(exit)) {
expect(Cause.findErrorOption(exit.cause)).toMatchObject({
_tag: "Some",
value: { _tag: "VcsProcessExitError", exitCode: 128 },
});
}
}),
);
it.effect("bounds a burst of processes that share a concurrency key", () =>
Effect.gen(function* () {
const gate = yield* Deferred.make<void>();
const starts = yield* Queue.unbounded<number>();
const active = yield* Ref.make(0);
const peak = yield* Ref.make(0);
const total = yield* Ref.make(0);
const service = yield* VcsProcess.make.pipe(
Effect.provideService(
ProcessRunner.ProcessRunner,
ProcessRunner.ProcessRunner.of({
run: () =>
Effect.gen(function* () {
const count = yield* Ref.updateAndGet(active, (held) => held + 1);
yield* Ref.update(peak, (held) => Math.max(held, count));
yield* Ref.update(total, (held) => held + 1);
yield* Queue.offer(starts, count);
yield* Deferred.await(gate);
return {
stdout: "",
stderr: "",
code: ChildProcessSpawner.ExitCode(0),
timedOut: false,
stdoutTruncated: false,
stderrTruncated: false,
stdoutInvalidUtf8: false,
stderrInvalidUtf8: false,
};
}).pipe(Effect.ensuring(Ref.update(active, (count) => count - 1))),
}),
),
);
const burst = yield* Effect.all(
Array.from({ length: 32 }, (_, index) =>
service.run({
operation: `synthetic.cli.${index}`,
command: "host-cli",
args: ["api", "user"],
cwd: "/workspace",
concurrency: { key: "host-cli", limit: 4 },
}),
),
{ concurrency: "unbounded" },
).pipe(Effect.forkChild);
yield* Effect.all(Array.from({ length: 4 }, () => Queue.take(starts)));
yield* Effect.yieldNow;
expect(yield* Queue.size(starts)).toBe(0);
expect(yield* Ref.get(peak)).toBe(4);
yield* Deferred.succeed(gate, undefined);
yield* Fiber.join(burst);
expect(yield* Ref.get(total)).toBe(32);
expect(yield* Ref.get(peak)).toBe(4);
}),
);
it.effect("leaves git a slot while slow forge CLI processes are running", () =>
Effect.gen(function* () {
const gate = yield* Deferred.make<void>();
const service = yield* VcsProcess.make.pipe(
Effect.provideService(
ProcessRunner.ProcessRunner,
ProcessRunner.ProcessRunner.of({
run: (input) =>
Effect.gen(function* () {
if (input.command !== "git") yield* Deferred.await(gate);
return {
stdout: "",
stderr: "",
code: ChildProcessSpawner.ExitCode(0),
timedOut: false,
stdoutTruncated: false,
stderrTruncated: false,
stdoutInvalidUtf8: false,
stderrInvalidUtf8: false,
};
}),
}),
),
);
const forgeRuns = yield* Effect.forEach(Array.from({ length: 12 }), () =>
service
.run({
operation: "synthetic.forge.listChangeRequests",
command: "tea",
args: ["pulls", "list"],
cwd: "/workspace",
})
.pipe(Effect.forkChild({ startImmediately: true })),
);
const checkpoint = yield* service
.run({
...baseInput,
operation: VcsProcess.CHECKPOINT_CAPTURE_OPERATION,
args: ["rev-parse", "HEAD"],
})
.pipe(Effect.timeoutOption("1 second"), Effect.forkChild({ startImmediately: true }));
yield* TestClock.adjust("1 second");
const gitResult = yield* Fiber.join(checkpoint);
yield* Deferred.succeed(gate, undefined);
yield* Fiber.joinAll(forgeRuns);
expect(
Option.isSome(gitResult),
"git waited behind forge CLI runs that held every VCS process slot",
).toBe(true);
}),
);
it.effect("keeps git from opening a folder laid out as a bare repository", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-vcs-bare-" });
yield* fileSystem.makeDirectory(path.join(cwd, "objects", "info"), { recursive: true });
yield* fileSystem.makeDirectory(path.join(cwd, "refs", "heads"), { recursive: true });
yield* fileSystem.writeFileString(path.join(cwd, "HEAD"), "ref: refs/heads/main\n");
yield* fileSystem.writeFileString(
path.join(cwd, "config"),
'[core]\n\trepositoryformatversion = 0\n\tbare = false\n\tworktree = .\n\tfsmonitor = "echo ran >> fsmonitor-runs; false"\n',
);
const result = yield* run({
operation: "test.bare-repository",
command: "git",
args: ["status"],
cwd,
allowNonZeroExit: true,
});
expect(result.exitCode).not.toBe(0);
expect(yield* fileSystem.exists(path.join(cwd, "fsmonitor-runs"))).toBe(false);
}).pipe(Effect.scoped, provideLive, Effect.provide(NodeServices.layer)),
);
it.effect("classifies authentication failures without retaining stderr", () =>
Effect.gen(function* () {
const secretStderr = "authentication failed for token super-secret-token";
const error = yield* run({
operation: "test.authentication",
command: "node",
args: ["-e", "process.stderr.write(process.argv[1]); process.exit(1)", secretStderr],
cwd: process.cwd(),
}).pipe(Effect.flip);
expect(error).toBeInstanceOf(VcsProcessExitError);
expect(error).toMatchObject({
operation: "test.authentication",
command: "node",
exitCode: 1,
detail: "Authentication failed.",
failureKind: "authentication",
stderrLength: secretStderr.length,
stderrTruncated: false,
});
expect(error.message).not.toContain(secretStderr);
expect(error.message).not.toContain("super-secret-token");
}).pipe(provideLive),
);
it.effect("classifies API rate limits without retaining provider stderr", () =>
Effect.gen(function* () {
const providerStderr =
"GraphQL: API rate limit already exceeded for user ID 51714798 and token secret-value.";
const error = yield* run({
operation: "test.rate-limit",
command: "node",
args: ["-e", "process.stderr.write(process.argv[1]); process.exit(1)", providerStderr],
cwd: process.cwd(),
}).pipe(Effect.flip);
expect(error).toBeInstanceOf(VcsProcessExitError);
expect(error).toMatchObject({
command: "node",
exitCode: 1,
detail: "API rate limit exceeded.",
failureKind: "rate-limited",
stderrLength: providerStderr.length,
stderrTruncated: false,
});
expect(error.message).not.toContain(providerStderr);
expect(error.message).not.toContain("secret-value");
}).pipe(provideLive),
);
it.effect("reads a failure with the command's own classifier and names it in its terms", () =>
Effect.gen(function* () {
const fail = (input: Partial<VcsProcess.VcsProcessInput>) =>
run({
operation: "test.classify",
command: "node",
args: ["-e", "process.stderr.write('HTTP 404: 404 Not Found'); process.exit(1)"],
cwd: process.cwd(),
...input,
}).pipe(Effect.flip);
expect(yield* fail({})).toMatchObject({
failureKind: "command-failed",
detail: "Process exited with a non-zero status.",
});
expect(
yield* fail({
classifyFailure: (stderr) => (stderr.includes("404") ? "not-found" : null),
notFoundDetail: "Merge request not found.",
}),
).toMatchObject({ failureKind: "not-found", detail: "Merge request not found." });
}).pipe(provideLive),
);
it.effect("retains spawn causes without exposing process arguments in the error message", () =>
Effect.gen(function* () {
const secretArgument = "--token=super-secret-token";
const error = yield* run({
operation: "test.spawn",
command: "definitely-not-a-t3code-executable",
args: [secretArgument],
cwd: process.cwd(),
}).pipe(Effect.flip);
expect(error).toBeInstanceOf(VcsProcessSpawnError);
expect(error).toMatchObject({
operation: "test.spawn",
command: "definitely-not-a-t3code-executable",
argumentCount: 1,
});
expect(error).toHaveProperty("cause");
expect(error.message).not.toContain(secretArgument);
}).pipe(provideLive),
);
it.effect("truncates output and appends the marker when requested", () =>
Effect.gen(function* () {
const result = yield* run({
operation: "test.truncate-marker",
command: "node",
args: ["-e", "process.stdout.write('x'.repeat(2048))"],
cwd: process.cwd(),
maxOutputBytes: 128,
appendTruncationMarker: true,
});
expect(result.stdoutTruncated).toBe(true);
expect(result.stdout).toContain("[truncated]");
expect(result.stderrTruncated).toBe(false);
}).pipe(provideLive),
);
it.effect("fails with measured byte counts when output must not be truncated", () =>
Effect.gen(function* () {
const error = yield* run({
operation: "test.output-limit",
command: "node",
args: ["-e", "process.stdout.write('x'.repeat(2048))"],
cwd: yield* HostProcess.WorkingDirectory,
maxOutputBytes: 128,
outputMode: "error",
}).pipe(Effect.flip);
assert(error._tag === "VcsProcessOutputLimitError");
expect(error.stream).toBe("stdout");
expect(error.maxBytes).toBe(128);
expect(error.observedBytes).toBeGreaterThan(error.maxBytes);
}).pipe(provideLive),
);
it.effect("streams all stdout bytes beyond the buffered output cap", () =>
Effect.gen(function* () {
const chunks: Uint8Array[] = [];
const result = yield* run({
operation: "test.stream-output",
command: "node",
args: ["-e", "process.stdout.write('x'.repeat(131072) + '\\0S final\\0')"],
cwd: process.cwd(),
maxOutputBytes: 8,
onStdoutChunk: (chunk) => chunks.push(chunk),
});
expect(result.stdout).toBe("xxxxxxxx");
expect(result.stdoutTruncated).toBe(true);
expect(Buffer.concat(chunks).toString()).toBe("x".repeat(131072) + "\0S final\0");
}).pipe(provideLive),
);
});