@capybara-hq/testing 0.1.0-rc.39 → 0.1.0-rc.40
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import type { DeviceProvider, SandboxHandle } from "@capybara-hq/plugin-sdk";
|
|
2
|
+
/**
|
|
3
|
+
* The request body {@link DEVICE_SERVICE_ECHO_SCRIPT} answers with its own `process.argv[1]`
|
|
4
|
+
* (the entry path it was started from) instead of the body.
|
|
5
|
+
*/
|
|
6
|
+
export declare const DEVICE_SERVICE_ARGV_PROBE = "capybara-conformance:argv1";
|
|
7
|
+
/**
|
|
8
|
+
* A framed echo device service (the device service socket protocol of the SDK's
|
|
9
|
+
* `device-service.ts`, written out so it runs alone from the service's code directory): it
|
|
10
|
+
* listens on `$CAPYBARA_SERVICE_SOCKET`, answers a `request` connection with its body unchanged
|
|
11
|
+
* (with its `process.argv[1]` for {@link DEVICE_SERVICE_ARGV_PROBE}) and echoes every message of a
|
|
12
|
+
* `stream` connection.
|
|
13
|
+
*/
|
|
14
|
+
export declare const DEVICE_SERVICE_ECHO_SCRIPT: string;
|
|
15
|
+
/** What {@link runDeviceServiceConformance} runs against: one running instance of a fresh device. */
|
|
16
|
+
export interface DeviceServiceFixture {
|
|
17
|
+
provider: Pick<DeviceProvider, "ensureService" | "stopService" | "serviceRequest">;
|
|
18
|
+
/** A running instance with no service started yet. */
|
|
19
|
+
handle: SandboxHandle;
|
|
20
|
+
/** Removes fixture-owned resources (the instance, its files), also after a failure. */
|
|
21
|
+
dispose(): Promise<void>;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* The device service contract every `device-provider@1` with services must pass (browser use spec
|
|
25
|
+
* §5). The kernel's launch review relies on it: a launch is reviewed only after an `ifRunning`
|
|
26
|
+
* ensure answered `stopped`, so a provider that started a service there would run it unreviewed.
|
|
27
|
+
* Every `ifRunning` ensure here uses the name-only spec the kernel sends
|
|
28
|
+
* (`{ name, runtime: "node", entry: "", args: [], files: {} }`). Checks: an `ifRunning` ensure of a
|
|
29
|
+
* stopped service starts nothing and answers `stopped` with an absolute `stateDir` (and an
|
|
30
|
+
* absolute `codeDir` when the provider reports one); both stay the same for the device and name
|
|
31
|
+
* across calls; a normal ensure starts the service once (a second one finds it running, same
|
|
32
|
+
* `startedAt`); an `ifRunning` ensure keeps a running one running; the service runs its entry
|
|
33
|
+
* from `codeDir ?? stateDir` (its `process.argv[1]` is exactly `<codeDir ?? stateDir>/<entry>`,
|
|
34
|
+
* the path the kernel reviewed); `serviceRequest` round-trips the echo service; `stopService`
|
|
35
|
+
* stops it (requests then fail, `ifRunning` answers `stopped`) and succeeds when it is not
|
|
36
|
+
* running. The fixture's `dispose` always runs.
|
|
37
|
+
*/
|
|
38
|
+
export declare function runDeviceServiceConformance(fixture: DeviceServiceFixture): Promise<void>;
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
/**
|
|
3
|
+
* The request body {@link DEVICE_SERVICE_ECHO_SCRIPT} answers with its own `process.argv[1]`
|
|
4
|
+
* (the entry path it was started from) instead of the body.
|
|
5
|
+
*/
|
|
6
|
+
export const DEVICE_SERVICE_ARGV_PROBE = "capybara-conformance:argv1";
|
|
7
|
+
/**
|
|
8
|
+
* A framed echo device service (the device service socket protocol of the SDK's
|
|
9
|
+
* `device-service.ts`, written out so it runs alone from the service's code directory): it
|
|
10
|
+
* listens on `$CAPYBARA_SERVICE_SOCKET`, answers a `request` connection with its body unchanged
|
|
11
|
+
* (with its `process.argv[1]` for {@link DEVICE_SERVICE_ARGV_PROBE}) and echoes every message of a
|
|
12
|
+
* `stream` connection.
|
|
13
|
+
*/
|
|
14
|
+
export const DEVICE_SERVICE_ECHO_SCRIPT = `import { createServer } from "node:net";
|
|
15
|
+
const socket = process.env.CAPYBARA_SERVICE_SOCKET;
|
|
16
|
+
if (!socket) process.exit(2);
|
|
17
|
+
const frame = (body) => {
|
|
18
|
+
const out = Buffer.alloc(4 + body.byteLength);
|
|
19
|
+
out.writeUInt32BE(body.byteLength, 0);
|
|
20
|
+
Buffer.from(body).copy(out, 4);
|
|
21
|
+
return out;
|
|
22
|
+
};
|
|
23
|
+
createServer((conn) => {
|
|
24
|
+
let buf = Buffer.alloc(0);
|
|
25
|
+
let kind = null;
|
|
26
|
+
conn.on("data", (chunk) => {
|
|
27
|
+
buf = Buffer.concat([buf, chunk]);
|
|
28
|
+
for (;;) {
|
|
29
|
+
if (buf.byteLength < 4) return;
|
|
30
|
+
const len = buf.readUInt32BE(0);
|
|
31
|
+
if (buf.byteLength < 4 + len) return;
|
|
32
|
+
const msg = buf.subarray(4, 4 + len);
|
|
33
|
+
buf = buf.subarray(4 + len);
|
|
34
|
+
if (kind === null) {
|
|
35
|
+
kind = JSON.parse(msg.toString("utf8")).kind;
|
|
36
|
+
continue;
|
|
37
|
+
}
|
|
38
|
+
if (kind === "request") {
|
|
39
|
+
const probe = msg.toString("utf8") === ${JSON.stringify(DEVICE_SERVICE_ARGV_PROBE)};
|
|
40
|
+
conn.end(frame(probe ? Buffer.from(process.argv[1] ?? "", "utf8") : msg));
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
conn.write(frame(msg));
|
|
44
|
+
}
|
|
45
|
+
});
|
|
46
|
+
conn.on("error", () => {});
|
|
47
|
+
}).listen(socket);
|
|
48
|
+
`;
|
|
49
|
+
const SERVICE = "conformance-echo";
|
|
50
|
+
/** What the kernel sends with every `ifRunning` ensure: the name, nothing to run. */
|
|
51
|
+
const nameOnly = (name) => ({
|
|
52
|
+
name,
|
|
53
|
+
runtime: "node",
|
|
54
|
+
entry: "",
|
|
55
|
+
args: [],
|
|
56
|
+
files: {},
|
|
57
|
+
});
|
|
58
|
+
/**
|
|
59
|
+
* The device service contract every `device-provider@1` with services must pass (browser use spec
|
|
60
|
+
* §5). The kernel's launch review relies on it: a launch is reviewed only after an `ifRunning`
|
|
61
|
+
* ensure answered `stopped`, so a provider that started a service there would run it unreviewed.
|
|
62
|
+
* Every `ifRunning` ensure here uses the name-only spec the kernel sends
|
|
63
|
+
* (`{ name, runtime: "node", entry: "", args: [], files: {} }`). Checks: an `ifRunning` ensure of a
|
|
64
|
+
* stopped service starts nothing and answers `stopped` with an absolute `stateDir` (and an
|
|
65
|
+
* absolute `codeDir` when the provider reports one); both stay the same for the device and name
|
|
66
|
+
* across calls; a normal ensure starts the service once (a second one finds it running, same
|
|
67
|
+
* `startedAt`); an `ifRunning` ensure keeps a running one running; the service runs its entry
|
|
68
|
+
* from `codeDir ?? stateDir` (its `process.argv[1]` is exactly `<codeDir ?? stateDir>/<entry>`,
|
|
69
|
+
* the path the kernel reviewed); `serviceRequest` round-trips the echo service; `stopService`
|
|
70
|
+
* stops it (requests then fail, `ifRunning` answers `stopped`) and succeeds when it is not
|
|
71
|
+
* running. The fixture's `dispose` always runs.
|
|
72
|
+
*/
|
|
73
|
+
export async function runDeviceServiceConformance(fixture) {
|
|
74
|
+
const { provider, handle } = fixture;
|
|
75
|
+
const ensure = provider.ensureService?.bind(provider);
|
|
76
|
+
const stop = provider.stopService?.bind(provider);
|
|
77
|
+
const request = provider.serviceRequest?.bind(provider);
|
|
78
|
+
assert(ensure && stop && request, "device services need ensureService, stopService and serviceRequest");
|
|
79
|
+
const signal = () => AbortSignal.timeout(30_000);
|
|
80
|
+
const spec = {
|
|
81
|
+
name: SERVICE,
|
|
82
|
+
runtime: "node",
|
|
83
|
+
entry: "echo.mjs",
|
|
84
|
+
args: [],
|
|
85
|
+
files: { "echo.mjs": new TextEncoder().encode(DEVICE_SERVICE_ECHO_SCRIPT) },
|
|
86
|
+
};
|
|
87
|
+
const ask = (text) => request(handle, SERVICE, new TextEncoder().encode(text), {
|
|
88
|
+
timeoutMs: 5_000,
|
|
89
|
+
signal: signal(),
|
|
90
|
+
});
|
|
91
|
+
const ifRunning = () => ensure(handle, nameOnly(SERVICE), signal(), { ifRunning: true });
|
|
92
|
+
const assertDirs = (s, first, when) => {
|
|
93
|
+
assert(s.stateDir.startsWith("/"), `${when}: stateDir must be absolute, got ${s.stateDir}`);
|
|
94
|
+
if (s.codeDir !== undefined)
|
|
95
|
+
assert(s.codeDir.startsWith("/"), `${when}: codeDir must be absolute, got ${s.codeDir}`);
|
|
96
|
+
if (first !== null) {
|
|
97
|
+
assert.equal(s.stateDir, first.stateDir, `${when}: stateDir must be stable`);
|
|
98
|
+
assert.equal(s.codeDir, first.codeDir, `${when}: codeDir must be stable`);
|
|
99
|
+
}
|
|
100
|
+
};
|
|
101
|
+
const assertStopped = async (s, first, when) => {
|
|
102
|
+
assert.equal(s.name, SERVICE, `${when}: status names the service`);
|
|
103
|
+
assert.equal(s.state, "stopped", `${when}: an ifRunning ensure must not start the service`);
|
|
104
|
+
assert.equal(s.startedAt, null, `${when}: a stopped service has no startedAt`);
|
|
105
|
+
assertDirs(s, first, when);
|
|
106
|
+
await assert.rejects(ask("nobody"), `${when}: no service may answer requests`);
|
|
107
|
+
};
|
|
108
|
+
try {
|
|
109
|
+
const before = await ifRunning();
|
|
110
|
+
await assertStopped(before, null, "before any start");
|
|
111
|
+
const again = await ifRunning();
|
|
112
|
+
await assertStopped(again, before, "a second ifRunning ensure");
|
|
113
|
+
const started = await ensure(handle, spec, signal());
|
|
114
|
+
assert.equal(started.state, "running", "a normal ensure starts the service");
|
|
115
|
+
assert.equal(typeof started.startedAt, "string", "a running service has startedAt");
|
|
116
|
+
assertDirs(started, before, "once started");
|
|
117
|
+
const found = await ensure(handle, spec, signal());
|
|
118
|
+
assert.deepEqual(found, started, "a second normal ensure keeps the running service");
|
|
119
|
+
const kept = await ifRunning();
|
|
120
|
+
assert.deepEqual(kept, started, "an ifRunning ensure keeps the running service");
|
|
121
|
+
const answer = await ask("hello conformance");
|
|
122
|
+
assert.equal(new TextDecoder().decode(answer), "hello conformance", "requests round-trip");
|
|
123
|
+
// the running service is still the one started, and it runs the reviewed entry path
|
|
124
|
+
const argv1 = new TextDecoder().decode(await ask(DEVICE_SERVICE_ARGV_PROBE));
|
|
125
|
+
const dir = (started.codeDir ?? started.stateDir).replace(/\/+$/, "");
|
|
126
|
+
assert.equal(argv1, `${dir}/${spec.entry}`, "the service's process.argv[1] must be <codeDir ?? stateDir>/<entry>, the reviewed path");
|
|
127
|
+
await stop(handle, SERVICE, signal());
|
|
128
|
+
const after = await ifRunning();
|
|
129
|
+
await assertStopped(after, before, "after stopService");
|
|
130
|
+
await stop(handle, SERVICE, signal());
|
|
131
|
+
}
|
|
132
|
+
finally {
|
|
133
|
+
try {
|
|
134
|
+
await stop(handle, SERVICE, signal());
|
|
135
|
+
}
|
|
136
|
+
catch {
|
|
137
|
+
// the fixture's dispose removes the instance anyway
|
|
138
|
+
}
|
|
139
|
+
await fixture.dispose();
|
|
140
|
+
}
|
|
141
|
+
}
|
|
@@ -16,6 +16,62 @@ export interface FakeDialInMachineOptions {
|
|
|
16
16
|
programRunId?: string;
|
|
17
17
|
}
|
|
18
18
|
type RequestHandler = (body: unknown) => unknown | Promise<unknown>;
|
|
19
|
+
/**
|
|
20
|
+
* The machine's end of one dial-in stream the kernel opened ({@link FakeDialInMachine.onStream}).
|
|
21
|
+
* It honours the kernel's credit: {@link send} waits while the kernel granted no more messages.
|
|
22
|
+
* By default it grants the kernel one message back for each message it receives; set
|
|
23
|
+
* {@link autoCredit} to false to withhold credit and grant it with {@link grant}.
|
|
24
|
+
*/
|
|
25
|
+
export declare class FakeMachineStream {
|
|
26
|
+
readonly streamId: string;
|
|
27
|
+
private readonly sendFrame;
|
|
28
|
+
/** The messages received from the kernel, in order. */
|
|
29
|
+
readonly received: Uint8Array[];
|
|
30
|
+
/** Grant the kernel one message back for each message received (default true). */
|
|
31
|
+
autoCredit: boolean;
|
|
32
|
+
/** Resolves when the stream closes (by either side), with the reason. */
|
|
33
|
+
readonly closed: Promise<{
|
|
34
|
+
reason: string;
|
|
35
|
+
}>;
|
|
36
|
+
private resolveClosed;
|
|
37
|
+
private isClosed;
|
|
38
|
+
/** Set once the machine answered `stream-opened`: no data goes out before it. */
|
|
39
|
+
private opened;
|
|
40
|
+
/** Messages this side may still send (granted by the kernel). */
|
|
41
|
+
private credit;
|
|
42
|
+
private readonly waiting;
|
|
43
|
+
private readonly countWaiters;
|
|
44
|
+
private messageHandler;
|
|
45
|
+
/** @internal */
|
|
46
|
+
constructor(streamId: string, sendFrame: (frame: unknown) => Promise<void>);
|
|
47
|
+
/** Called for each message received (after it is recorded in {@link received}). */
|
|
48
|
+
onMessage(fn: (m: Uint8Array) => void): void;
|
|
49
|
+
/** Resolves once at least `n` messages were received. */
|
|
50
|
+
receivedCount(n: number): Promise<void>;
|
|
51
|
+
/** Sends one message once the kernel has credit for it. */
|
|
52
|
+
send(message: Uint8Array): Promise<void>;
|
|
53
|
+
/** Grants the kernel `messages` more messages. */
|
|
54
|
+
grant(messages: number): Promise<void>;
|
|
55
|
+
/** Closes the stream from the machine's side. */
|
|
56
|
+
close(reason?: string): Promise<void>;
|
|
57
|
+
/** @internal */
|
|
58
|
+
onFrame(frame: {
|
|
59
|
+
type: string;
|
|
60
|
+
data?: string;
|
|
61
|
+
messages?: number;
|
|
62
|
+
reason?: string;
|
|
63
|
+
}): void;
|
|
64
|
+
/** @internal the machine answered `stream-opened` ok: queued messages may go out. */
|
|
65
|
+
activate(): void;
|
|
66
|
+
/** @internal the stream ended (closed, or the socket went away). */
|
|
67
|
+
end(reason: string): void;
|
|
68
|
+
private flush;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Called for each `stream-open` the kernel sends, with its body and the machine's end of the
|
|
72
|
+
* stream. A throw refuses the stream (`stream-opened` with `ok: false` and the thrown message).
|
|
73
|
+
*/
|
|
74
|
+
type StreamHandler = (open: unknown, stream: FakeMachineStream) => void;
|
|
19
75
|
/**
|
|
20
76
|
* A machine on the dial-in channel for kernel tests: connects to a deployment, sends the hello
|
|
21
77
|
* envelope, waits for the kernel's `ready` and then answers each `req` through the handler set
|
|
@@ -44,6 +100,15 @@ export declare class FakeDialInMachine {
|
|
|
44
100
|
/** Kernel frames that were not JSON, in order (the kernel never sends one). */
|
|
45
101
|
readonly invalid: string[];
|
|
46
102
|
private handler;
|
|
103
|
+
private streamHandler;
|
|
104
|
+
/** Leave every `stream-open` unanswered (a machine that never opens streams). */
|
|
105
|
+
ignoreStreamOpens: boolean;
|
|
106
|
+
/** The ids of the `stream-open` frames received, in order. */
|
|
107
|
+
readonly streamOpens: string[];
|
|
108
|
+
/** The ids of the `stream-close` frames received, in order (also of streams never opened). */
|
|
109
|
+
readonly streamCloses: string[];
|
|
110
|
+
/** The streams the kernel opened and that are still open, by id. */
|
|
111
|
+
private readonly streams;
|
|
47
112
|
private constructor();
|
|
48
113
|
/**
|
|
49
114
|
* Connects and resolves once the kernel answered `ready`. Rejects when the upgrade is refused
|
|
@@ -52,12 +117,18 @@ export declare class FakeDialInMachine {
|
|
|
52
117
|
static connect(opts: FakeDialInMachineOptions): Promise<FakeDialInMachine>;
|
|
53
118
|
/** Sets the handler of `req` bodies; its result (or its thrown message) is the `res` body. */
|
|
54
119
|
onRequest(fn: RequestHandler): void;
|
|
120
|
+
/**
|
|
121
|
+
* Sets the handler of the streams the kernel opens (`stream-open`); without one every stream is
|
|
122
|
+
* refused.
|
|
123
|
+
*/
|
|
124
|
+
onStream(fn: StreamHandler): void;
|
|
55
125
|
/** Sends an unsolicited `event` frame with `event` as its body. */
|
|
56
126
|
send(event: unknown): Promise<void>;
|
|
57
127
|
/** Closes the socket (a normal close) and resolves when it is closed. */
|
|
58
128
|
close(): Promise<void>;
|
|
59
129
|
private sendFrame;
|
|
60
130
|
private onMessage;
|
|
131
|
+
private openStream;
|
|
61
132
|
}
|
|
62
133
|
/**
|
|
63
134
|
* Signs a fake machine in over HTTP like `capybara-device login` does: `authorize` (public),
|
|
@@ -2,6 +2,122 @@ import { randomUUID } from "node:crypto";
|
|
|
2
2
|
import { WebSocket } from "ws";
|
|
3
3
|
/** The protocol of the `fake-dial-in` fixture provider (`permissions.dialIn.protocol`). */
|
|
4
4
|
export const FAKE_DIAL_IN_PROTOCOL = "fake-dial-in/1";
|
|
5
|
+
/**
|
|
6
|
+
* The credit each side of a dial-in stream starts with for the other (the SDK's
|
|
7
|
+
* `DIAL_IN_STREAM_INITIAL_CREDIT`, repeated so this module stays a plain test helper).
|
|
8
|
+
*/
|
|
9
|
+
const INITIAL_CREDIT = 8;
|
|
10
|
+
/**
|
|
11
|
+
* The machine's end of one dial-in stream the kernel opened ({@link FakeDialInMachine.onStream}).
|
|
12
|
+
* It honours the kernel's credit: {@link send} waits while the kernel granted no more messages.
|
|
13
|
+
* By default it grants the kernel one message back for each message it receives; set
|
|
14
|
+
* {@link autoCredit} to false to withhold credit and grant it with {@link grant}.
|
|
15
|
+
*/
|
|
16
|
+
export class FakeMachineStream {
|
|
17
|
+
streamId;
|
|
18
|
+
sendFrame;
|
|
19
|
+
/** The messages received from the kernel, in order. */
|
|
20
|
+
received = [];
|
|
21
|
+
/** Grant the kernel one message back for each message received (default true). */
|
|
22
|
+
autoCredit = true;
|
|
23
|
+
/** Resolves when the stream closes (by either side), with the reason. */
|
|
24
|
+
closed;
|
|
25
|
+
resolveClosed;
|
|
26
|
+
isClosed = false;
|
|
27
|
+
/** Set once the machine answered `stream-opened`: no data goes out before it. */
|
|
28
|
+
opened = false;
|
|
29
|
+
/** Messages this side may still send (granted by the kernel). */
|
|
30
|
+
credit = INITIAL_CREDIT;
|
|
31
|
+
waiting = [];
|
|
32
|
+
countWaiters = [];
|
|
33
|
+
messageHandler;
|
|
34
|
+
/** @internal */
|
|
35
|
+
constructor(streamId, sendFrame) {
|
|
36
|
+
this.streamId = streamId;
|
|
37
|
+
this.sendFrame = sendFrame;
|
|
38
|
+
this.closed = new Promise((resolve) => {
|
|
39
|
+
this.resolveClosed = resolve;
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
/** Called for each message received (after it is recorded in {@link received}). */
|
|
43
|
+
onMessage(fn) {
|
|
44
|
+
this.messageHandler = fn;
|
|
45
|
+
}
|
|
46
|
+
/** Resolves once at least `n` messages were received. */
|
|
47
|
+
receivedCount(n) {
|
|
48
|
+
if (this.received.length >= n)
|
|
49
|
+
return Promise.resolve();
|
|
50
|
+
return new Promise((resolve) => this.countWaiters.push({ n, resolve }));
|
|
51
|
+
}
|
|
52
|
+
/** Sends one message once the kernel has credit for it. */
|
|
53
|
+
send(message) {
|
|
54
|
+
if (this.isClosed)
|
|
55
|
+
return Promise.reject(new Error("stream closed"));
|
|
56
|
+
return new Promise((resolve, reject) => {
|
|
57
|
+
this.waiting.push({ data: Buffer.from(message).toString("base64"), resolve, reject });
|
|
58
|
+
this.flush();
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
/** Grants the kernel `messages` more messages. */
|
|
62
|
+
async grant(messages) {
|
|
63
|
+
if (this.isClosed)
|
|
64
|
+
return;
|
|
65
|
+
await this.sendFrame({ type: "stream-credit", streamId: this.streamId, messages });
|
|
66
|
+
}
|
|
67
|
+
/** Closes the stream from the machine's side. */
|
|
68
|
+
async close(reason = "closed") {
|
|
69
|
+
if (this.isClosed)
|
|
70
|
+
return;
|
|
71
|
+
await this.sendFrame({ type: "stream-close", streamId: this.streamId, reason });
|
|
72
|
+
this.end(reason);
|
|
73
|
+
}
|
|
74
|
+
/** @internal */
|
|
75
|
+
onFrame(frame) {
|
|
76
|
+
if (this.isClosed)
|
|
77
|
+
return;
|
|
78
|
+
if (frame.type === "stream-data" && typeof frame.data === "string") {
|
|
79
|
+
const m = new Uint8Array(Buffer.from(frame.data, "base64"));
|
|
80
|
+
this.received.push(m);
|
|
81
|
+
for (const w of this.countWaiters.splice(0)) {
|
|
82
|
+
if (this.received.length >= w.n)
|
|
83
|
+
w.resolve();
|
|
84
|
+
else
|
|
85
|
+
this.countWaiters.push(w);
|
|
86
|
+
}
|
|
87
|
+
if (this.autoCredit)
|
|
88
|
+
void this.grant(1).catch(() => { });
|
|
89
|
+
this.messageHandler?.(m);
|
|
90
|
+
}
|
|
91
|
+
else if (frame.type === "stream-credit" && typeof frame.messages === "number") {
|
|
92
|
+
this.credit += frame.messages;
|
|
93
|
+
this.flush();
|
|
94
|
+
}
|
|
95
|
+
else if (frame.type === "stream-close") {
|
|
96
|
+
this.end(frame.reason ?? "closed");
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
/** @internal the machine answered `stream-opened` ok: queued messages may go out. */
|
|
100
|
+
activate() {
|
|
101
|
+
this.opened = true;
|
|
102
|
+
this.flush();
|
|
103
|
+
}
|
|
104
|
+
/** @internal the stream ended (closed, or the socket went away). */
|
|
105
|
+
end(reason) {
|
|
106
|
+
if (this.isClosed)
|
|
107
|
+
return;
|
|
108
|
+
this.isClosed = true;
|
|
109
|
+
for (const w of this.waiting.splice(0))
|
|
110
|
+
w.reject(new Error(`stream closed: ${reason}`));
|
|
111
|
+
this.resolveClosed({ reason });
|
|
112
|
+
}
|
|
113
|
+
flush() {
|
|
114
|
+
while (this.opened && this.credit > 0 && this.waiting.length > 0 && !this.isClosed) {
|
|
115
|
+
const w = this.waiting.shift();
|
|
116
|
+
this.credit--;
|
|
117
|
+
this.sendFrame({ type: "stream-data", streamId: this.streamId, data: w.data }).then(w.resolve, w.reject);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
}
|
|
5
121
|
/**
|
|
6
122
|
* A machine on the dial-in channel for kernel tests: connects to a deployment, sends the hello
|
|
7
123
|
* envelope, waits for the kernel's `ready` and then answers each `req` through the handler set
|
|
@@ -27,6 +143,15 @@ export class FakeDialInMachine {
|
|
|
27
143
|
/** Kernel frames that were not JSON, in order (the kernel never sends one). */
|
|
28
144
|
invalid = [];
|
|
29
145
|
handler = () => ({});
|
|
146
|
+
streamHandler;
|
|
147
|
+
/** Leave every `stream-open` unanswered (a machine that never opens streams). */
|
|
148
|
+
ignoreStreamOpens = false;
|
|
149
|
+
/** The ids of the `stream-open` frames received, in order. */
|
|
150
|
+
streamOpens = [];
|
|
151
|
+
/** The ids of the `stream-close` frames received, in order (also of streams never opened). */
|
|
152
|
+
streamCloses = [];
|
|
153
|
+
/** The streams the kernel opened and that are still open, by id. */
|
|
154
|
+
streams = new Map();
|
|
30
155
|
constructor(ws, ready, closed) {
|
|
31
156
|
this.ws = ws;
|
|
32
157
|
this.connectionId = ready.connectionId;
|
|
@@ -35,6 +160,11 @@ export class FakeDialInMachine {
|
|
|
35
160
|
// the connect promise's listener is gone once settled: an error later must not go unhandled
|
|
36
161
|
ws.on("error", (e) => this.errors.push(e));
|
|
37
162
|
ws.on("message", (data) => this.onMessage(data.toString()));
|
|
163
|
+
void closed.then(() => {
|
|
164
|
+
for (const st of this.streams.values())
|
|
165
|
+
st.end("socket closed");
|
|
166
|
+
this.streams.clear();
|
|
167
|
+
});
|
|
38
168
|
}
|
|
39
169
|
/**
|
|
40
170
|
* Connects and resolves once the kernel answered `ready`. Rejects when the upgrade is refused
|
|
@@ -96,6 +226,13 @@ export class FakeDialInMachine {
|
|
|
96
226
|
onRequest(fn) {
|
|
97
227
|
this.handler = fn;
|
|
98
228
|
}
|
|
229
|
+
/**
|
|
230
|
+
* Sets the handler of the streams the kernel opens (`stream-open`); without one every stream is
|
|
231
|
+
* refused.
|
|
232
|
+
*/
|
|
233
|
+
onStream(fn) {
|
|
234
|
+
this.streamHandler = fn;
|
|
235
|
+
}
|
|
99
236
|
/** Sends an unsolicited `event` frame with `event` as its body. */
|
|
100
237
|
async send(event) {
|
|
101
238
|
await this.sendFrame({ type: "event", body: event });
|
|
@@ -137,9 +274,45 @@ export class FakeDialInMachine {
|
|
|
137
274
|
else if (frame.type === "cancel" && frame.id !== undefined) {
|
|
138
275
|
this.cancels.push(frame.id);
|
|
139
276
|
}
|
|
140
|
-
else if (frame.type === "stop" && frame.reason
|
|
277
|
+
else if (frame.type === "stop" && (frame.reason === "drain" || frame.reason === "stop")) {
|
|
141
278
|
this.stops.push(frame.reason);
|
|
142
279
|
}
|
|
280
|
+
else if (frame.type === "stream-open" && frame.streamId !== undefined) {
|
|
281
|
+
this.streamOpens.push(frame.streamId);
|
|
282
|
+
if (!this.ignoreStreamOpens)
|
|
283
|
+
this.openStream(frame.streamId, frame.body);
|
|
284
|
+
}
|
|
285
|
+
else if (frame.type.startsWith("stream-") && frame.streamId !== undefined) {
|
|
286
|
+
if (frame.type === "stream-close")
|
|
287
|
+
this.streamCloses.push(frame.streamId);
|
|
288
|
+
const st = this.streams.get(frame.streamId);
|
|
289
|
+
st?.onFrame(frame);
|
|
290
|
+
if (frame.type === "stream-close")
|
|
291
|
+
this.streams.delete(frame.streamId);
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
openStream(streamId, body) {
|
|
295
|
+
const st = new FakeMachineStream(streamId, (f) => this.sendFrame(f));
|
|
296
|
+
void st.closed.then(() => this.streams.delete(streamId));
|
|
297
|
+
let error;
|
|
298
|
+
if (this.streamHandler === undefined)
|
|
299
|
+
error = "this machine opens no streams";
|
|
300
|
+
else {
|
|
301
|
+
try {
|
|
302
|
+
this.streamHandler(body, st);
|
|
303
|
+
}
|
|
304
|
+
catch (e) {
|
|
305
|
+
error = e instanceof Error ? e.message : String(e);
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
if (error !== undefined) {
|
|
309
|
+
void this.sendFrame({ type: "stream-opened", streamId, ok: false, error }).catch(() => { });
|
|
310
|
+
return;
|
|
311
|
+
}
|
|
312
|
+
this.streams.set(streamId, st);
|
|
313
|
+
// queued on the socket before any data the handler already asked to send
|
|
314
|
+
void this.sendFrame({ type: "stream-opened", streamId, ok: true }).catch(() => { });
|
|
315
|
+
st.activate();
|
|
143
316
|
}
|
|
144
317
|
}
|
|
145
318
|
function expectOk(res, what) {
|
package/dist/index.d.ts
CHANGED
|
@@ -5,10 +5,11 @@
|
|
|
5
5
|
*/
|
|
6
6
|
export { type ConversationEvent, createDb, gatewayReplicasKey, type KernelConfig, type KernelSchemaDb, kernelDb, MAINTENANCE_QUEUE_NAME, runJobId, SANDBOX_LOCK_TTL_MS, SANDBOX_RESTARTED_NOTICE, SANDBOX_STARTED_NOTICE, SANDBOX_SUSPEND_JOB, UNKNOWN_RESULT_TEXT, } from "@capybara-hq/kernel";
|
|
7
7
|
export { createFreshDatabase, startPostgresContainer, startTestPostgres, startTestRedis, startTestS3, TEST_PG_IMAGE, TEST_S3_IMAGE, type TestContainer, type TestS3, } from "./containers.js";
|
|
8
|
+
export { DEVICE_SERVICE_ARGV_PROBE, DEVICE_SERVICE_ECHO_SCRIPT, type DeviceServiceFixture, runDeviceServiceConformance, } from "./device-service-conformance.js";
|
|
8
9
|
export { createDualReplicaHarness, type DualReplicaOptions, type ExtraReplicaHandle, type Harness, REPLICA_HEADER, type ReplicaHandle, type ReplicaResponse, replicaOf, } from "./dual-replica.js";
|
|
9
10
|
export { assertExtensionSecretsReachable, extensionDeploymentSecretValues, } from "./extension-config.js";
|
|
10
11
|
export { FAKE_CHANNEL_BAD_SECRET, FAKE_WEBHOOK_SIGNATURE_HEADER, type FakeChannelCheckCall, type FakeChannelFailMatch, type FakeChannelPost, type FakeChannelSent, type FakeChannelSentFile, type FakeChannelServer, type FakeChannelServerOptions, type FakeChannelStream, type FakeChannelUser, type FakeDirectoryBook, type FakeSenderProfile, fakeCardAction, fakeDirectoryMember, fakeDm, fakeGroupMessage, fakeWebhookChallenge, fakeWebhookEvents, signFakeWebhook, startFakeChannelServer, } from "./fake-channel.js";
|
|
11
|
-
export { FAKE_DIAL_IN_PROTOCOL, FakeDialInMachine, type FakeDialInMachineOptions, signInFakeMachine, } from "./fake-dial-in-machine.js";
|
|
12
|
+
export { FAKE_DIAL_IN_PROTOCOL, FakeDialInMachine, type FakeDialInMachineOptions, FakeMachineStream, signInFakeMachine, } from "./fake-dial-in-machine.js";
|
|
12
13
|
export { type FakeE2BCall, type FakeE2BMatch, type FakeE2BOptions, type FakeE2BSandbox, type FakeE2BServer, startFakeE2B, } from "./fake-e2b.js";
|
|
13
14
|
export { type FakeGitCommitOptions, type FakeGitRequest, type FakeGitServer, type FakeGitServerOptions, startFakeGitServer, } from "./fake-git-server.js";
|
|
14
15
|
export { encryptLarkWebhook, type FakeLarkAck, type FakeLarkApi, type FakeLarkButton, type FakeLarkCall, type FakeLarkDepartment, type FakeLarkFailure, type FakeLarkMessage, type FakeLarkOptions, type FakeLarkServer, type FakeLarkUpload, type FakeLarkUser, findLarkButton, larkCardAction, larkMessageEvent, signLarkWebhook, startFakeLark, } from "./fake-lark.js";
|
package/dist/index.js
CHANGED
|
@@ -5,10 +5,11 @@
|
|
|
5
5
|
*/
|
|
6
6
|
export { createDb, gatewayReplicasKey, kernelDb, MAINTENANCE_QUEUE_NAME, runJobId, SANDBOX_LOCK_TTL_MS, SANDBOX_RESTARTED_NOTICE, SANDBOX_STARTED_NOTICE, SANDBOX_SUSPEND_JOB, UNKNOWN_RESULT_TEXT, } from "@capybara-hq/kernel";
|
|
7
7
|
export { createFreshDatabase, startPostgresContainer, startTestPostgres, startTestRedis, startTestS3, TEST_PG_IMAGE, TEST_S3_IMAGE, } from "./containers.js";
|
|
8
|
+
export { DEVICE_SERVICE_ARGV_PROBE, DEVICE_SERVICE_ECHO_SCRIPT, runDeviceServiceConformance, } from "./device-service-conformance.js";
|
|
8
9
|
export { createDualReplicaHarness, REPLICA_HEADER, replicaOf, } from "./dual-replica.js";
|
|
9
10
|
export { assertExtensionSecretsReachable, extensionDeploymentSecretValues, } from "./extension-config.js";
|
|
10
11
|
export { FAKE_CHANNEL_BAD_SECRET, FAKE_WEBHOOK_SIGNATURE_HEADER, fakeCardAction, fakeDirectoryMember, fakeDm, fakeGroupMessage, fakeWebhookChallenge, fakeWebhookEvents, signFakeWebhook, startFakeChannelServer, } from "./fake-channel.js";
|
|
11
|
-
export { FAKE_DIAL_IN_PROTOCOL, FakeDialInMachine, signInFakeMachine, } from "./fake-dial-in-machine.js";
|
|
12
|
+
export { FAKE_DIAL_IN_PROTOCOL, FakeDialInMachine, FakeMachineStream, signInFakeMachine, } from "./fake-dial-in-machine.js";
|
|
12
13
|
export { startFakeE2B, } from "./fake-e2b.js";
|
|
13
14
|
export { startFakeGitServer, } from "./fake-git-server.js";
|
|
14
15
|
export { encryptLarkWebhook, findLarkButton, larkCardAction, larkMessageEvent, signLarkWebhook, startFakeLark, } from "./fake-lark.js";
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@capybara-hq/testing",
|
|
3
|
-
"version": "0.1.0-rc.
|
|
3
|
+
"version": "0.1.0-rc.40",
|
|
4
4
|
"description": "Test helpers for Capybara: test containers, dual-replica harness and fake third-party servers",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
@@ -47,18 +47,18 @@
|
|
|
47
47
|
"tsx": "^4.23.15",
|
|
48
48
|
"ws": "^8.22.0",
|
|
49
49
|
"zod": "^4.6.7",
|
|
50
|
-
"@capybara-hq/kernel": "^0.1.0-rc.
|
|
50
|
+
"@capybara-hq/kernel": "^0.1.0-rc.86"
|
|
51
51
|
},
|
|
52
52
|
"devDependencies": {
|
|
53
53
|
"@types/pg": "^8.23.1",
|
|
54
54
|
"@types/ws": "^8.18.2",
|
|
55
|
-
"@capybara-hq/plugin-sdk": "^0.1.0-rc.
|
|
55
|
+
"@capybara-hq/plugin-sdk": "^0.1.0-rc.70",
|
|
56
56
|
"@capybara-hq/plugin-client": "^0.1.0-rc.9"
|
|
57
57
|
},
|
|
58
58
|
"peerDependencies": {
|
|
59
59
|
"vitest": "^5.0.5",
|
|
60
|
-
"@capybara-hq/plugin-
|
|
61
|
-
"@capybara-hq/plugin-
|
|
60
|
+
"@capybara-hq/plugin-sdk": "^0.1.0-rc.70",
|
|
61
|
+
"@capybara-hq/plugin-tools": "^0.1.0-rc.24"
|
|
62
62
|
},
|
|
63
63
|
"peerDependenciesMeta": {
|
|
64
64
|
"@capybara-hq/plugin-tools": {
|