Repository navigation
Expand file tree
/
Copy pathffiRuntimeHost.test.ts
More file actions
406 lines (363 loc) · 15.9 KB
/
Copy pathffiRuntimeHost.test.ts
File metadata and controls
406 lines (363 loc) · 15.9 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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------------------------------------------*/
/* eslint-disable @typescript-eslint/no-explicit-any */
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const ffi = vi.hoisted(() => {
let registeredCallback:
| ((userData: unknown, bytesPtr: unknown, bytesLen: number) => void)
| undefined;
const callbackToken = {};
const hostStart = Object.assign(vi.fn(), {
async: vi.fn(
(
_argv: Buffer,
_argvLength: number,
_env: Buffer | null,
_envLength: number,
callback: (error: Error | null, result: number) => void
) => callback(null, 11)
),
});
const hostShutdown = Object.assign(
vi.fn(() => true),
{
async: vi.fn<
(serverId: number, callback: (error: Error | null, result: boolean) => void) => void
>(),
}
);
const connectionOpen = vi.fn(() => 21);
const connectionWrite = vi.fn(() => true);
const connectionClose = Object.assign(vi.fn<() => boolean>(), {
async: vi.fn<
(connectionId: number, callback: (error: Error | null, result: boolean) => void) => void
>(),
});
const register = vi.fn(
(callback: (userData: unknown, bytesPtr: unknown, bytesLen: number) => void) => {
registeredCallback = callback;
return callbackToken;
}
);
const unregister = vi.fn();
return {
callbackToken,
connectionClose,
connectionOpen,
connectionWrite,
getRegisteredCallback: () => registeredCallback,
hostShutdown,
hostStart,
register,
unregister,
};
});
vi.mock("node:fs", () => ({
existsSync: vi.fn(() => true),
}));
vi.mock("koffi", () => ({
default: {
array: vi.fn(() => ({})),
decode: vi.fn(() => new Uint8Array([1])),
load: vi.fn(() => ({
func: vi.fn((name: string) => {
if (name.endsWith("host_start")) return ffi.hostStart;
if (name.endsWith("host_shutdown")) return ffi.hostShutdown;
if (name.endsWith("connection_open")) return ffi.connectionOpen;
if (name.endsWith("connection_write")) return ffi.connectionWrite;
if (name.endsWith("connection_close")) return ffi.connectionClose;
throw new Error(`Unexpected FFI symbol: ${name}`);
}),
})),
pointer: vi.fn(() => ({})),
proto: vi.fn(() => ({})),
register: ffi.register,
unregister: ffi.unregister,
},
}));
import { FfiRuntimeHost } from "../src/ffiRuntimeHost.js";
describe("FfiRuntimeHost callback cleanup", () => {
beforeEach(() => {
vi.useFakeTimers();
ffi.connectionClose.mockReset();
ffi.connectionClose.async
.mockReset()
.mockImplementation((_id, callback) => callback(null, true));
ffi.connectionOpen.mockClear();
ffi.hostShutdown.mockClear();
ffi.hostShutdown.async
.mockReset()
.mockImplementation((_id, callback) => callback(null, true));
ffi.hostStart.mockClear();
ffi.hostStart.async.mockClear();
ffi.register.mockClear();
ffi.unregister.mockClear();
});
afterEach(() => {
expect(ffi.connectionClose).not.toHaveBeenCalled();
expect(ffi.hostShutdown).not.toHaveBeenCalled();
vi.clearAllTimers();
vi.useRealTimers();
});
it("finishes disposal after a false close while retaining resources for the detached retry", async () => {
ffi.connectionClose.async.mockImplementationOnce((_id, callback) => callback(null, false));
const host = FfiRuntimeHost.create("runtime.node", undefined, undefined, []);
await host.start();
await host.dispose();
expect(ffi.connectionClose.async).toHaveBeenCalledTimes(1);
expect(ffi.unregister).not.toHaveBeenCalled();
expect(ffi.hostShutdown.async).not.toHaveBeenCalled();
expect((host as any).outboundCallback).toBe(ffi.callbackToken);
expect((host as any).keepAliveTimer).toBeDefined();
await vi.advanceTimersByTimeAsync(100);
expect(ffi.connectionClose.async).toHaveBeenCalledTimes(2);
expect(ffi.unregister).toHaveBeenCalledTimes(1);
expect(ffi.hostShutdown.async).toHaveBeenCalledTimes(1);
expect((host as any).outboundCallback).toBeUndefined();
expect((host as any).keepAliveTimer).toBeUndefined();
expect(vi.getTimerCount()).toBe(0);
await host.dispose();
await vi.advanceTimersByTimeAsync(100);
expect(ffi.connectionClose.async).toHaveBeenCalledTimes(2);
expect(ffi.unregister).toHaveBeenCalledTimes(1);
expect(ffi.hostShutdown.async).toHaveBeenCalledTimes(1);
});
it("waits for successful initial cleanup without overlapping close calls", async () => {
let finishClose!: (error: Error | null, result: boolean) => void;
ffi.connectionClose.async.mockImplementationOnce((_id, callback) => {
finishClose = callback;
});
const host = FfiRuntimeHost.create("runtime.node", undefined, undefined, []);
await host.start();
let disposed = false;
const cleanup = host.dispose().then(() => {
disposed = true;
});
await host.dispose();
await vi.advanceTimersByTimeAsync(1000);
expect(disposed).toBe(false);
expect(ffi.connectionClose.async).toHaveBeenCalledTimes(1);
expect(ffi.unregister).not.toHaveBeenCalled();
expect(ffi.hostShutdown.async).not.toHaveBeenCalled();
expect((host as any).outboundCallback).toBe(ffi.callbackToken);
expect((host as any).keepAliveTimer).toBeDefined();
finishClose(null, true);
await cleanup;
expect(disposed).toBe(true);
expect(ffi.unregister).toHaveBeenCalledTimes(1);
expect(ffi.hostShutdown.async).toHaveBeenCalledTimes(1);
expect(vi.getTimerCount()).toBe(0);
});
it("defers reclamation when dispose is called from the outbound callback", async () => {
ffi.connectionClose.async.mockImplementationOnce((_id, callback) => {
setImmediate(() => callback(null, true));
});
const host = FfiRuntimeHost.create("runtime.node", undefined, undefined, []);
await host.start();
host.receiveStream.once("data", () => {
void host.dispose();
});
ffi.getRegisteredCallback()?.(null, {}, 1);
expect(ffi.unregister).not.toHaveBeenCalled();
expect((host as any).outboundCallback).toBe(ffi.callbackToken);
await vi.advanceTimersByTimeAsync(100);
expect(ffi.unregister).toHaveBeenCalledTimes(1);
expect(ffi.hostShutdown.async).toHaveBeenCalledTimes(1);
expect(vi.getTimerCount()).toBe(0);
});
it.each(["callback", "throw"])(
"quarantines the callback on a close %s error",
async (failure) => {
const closeError = new Error("close failed");
ffi.connectionClose.async.mockImplementationOnce((_id, callback) => {
if (failure === "throw") {
throw closeError;
}
callback(closeError, false);
});
const error = vi.spyOn(console, "error").mockImplementation(() => {});
const host = FfiRuntimeHost.create("runtime.node", undefined, undefined, []);
await host.start();
await host.dispose();
await vi.advanceTimersByTimeAsync(500);
expect(ffi.connectionClose.async).toHaveBeenCalledTimes(1);
expect(ffi.unregister).not.toHaveBeenCalled();
expect(ffi.hostShutdown.async).not.toHaveBeenCalled();
expect((host as any).outboundCallback).toBe(ffi.callbackToken);
expect((FfiRuntimeHost as any).quarantinedHosts.has(host)).toBe(true);
expect(error).toHaveBeenCalledTimes(1);
expect(vi.getTimerCount()).toBe(0);
error.mockRestore();
}
);
it("does not retry a terminal host shutdown failure", async () => {
ffi.hostShutdown.async.mockImplementationOnce((_id, callback) => callback(null, false));
const error = vi.spyOn(console, "error").mockImplementation(() => {});
const host = FfiRuntimeHost.create("runtime.node", undefined, undefined, []);
await host.start();
await host.dispose();
await vi.advanceTimersByTimeAsync(500);
expect(ffi.connectionClose.async).toHaveBeenCalledTimes(1);
expect(ffi.unregister).toHaveBeenCalledTimes(1);
expect(ffi.hostShutdown.async).toHaveBeenCalledTimes(1);
expect(vi.getTimerCount()).toBe(0);
error.mockRestore();
});
it("retains the callback token when Koffi unregistration fails", async () => {
ffi.unregister.mockImplementationOnce(() => {
throw new Error("unregister failed");
});
const error = vi.spyOn(console, "error").mockImplementation(() => {});
const host = FfiRuntimeHost.create("runtime.node", undefined, undefined, []);
await host.start();
await host.dispose();
await vi.advanceTimersByTimeAsync(500);
expect(ffi.connectionClose.async).toHaveBeenCalledTimes(1);
expect(ffi.unregister).toHaveBeenCalledTimes(1);
expect(ffi.hostShutdown.async).toHaveBeenCalledTimes(1);
expect((host as any).outboundCallback).toBe(ffi.callbackToken);
expect((FfiRuntimeHost as any).quarantinedHosts.has(host)).toBe(true);
expect((host as any).keepAliveTimer).toBeUndefined();
expect(vi.getTimerCount()).toBe(0);
await host.dispose();
expect(ffi.unregister).toHaveBeenCalledTimes(1);
error.mockRestore();
});
it("joins host shutdown before startup rejects after disposal during startup", async () => {
let finishStart!: (error: Error | null, result: number) => void;
let finishShutdown: ((error: Error | null, result: boolean) => void) | undefined;
ffi.hostStart.async.mockImplementationOnce(
(_argv, _argvLength, _env, _envLength, callback) => {
finishStart = callback;
}
);
ffi.hostShutdown.async.mockImplementationOnce((_id, callback) => {
finishShutdown = callback;
});
const host = FfiRuntimeHost.create("runtime.node", undefined, undefined, []);
const settled = vi.fn();
const startup = host.start().catch((error: unknown) => {
settled();
return error;
});
await host.dispose();
finishStart(null, 11);
try {
await vi.advanceTimersByTimeAsync(0);
expect(ffi.hostShutdown.async).toHaveBeenCalledExactlyOnceWith(
11,
expect.any(Function)
);
expect(settled).not.toHaveBeenCalled();
} finally {
finishShutdown?.(null, true);
await startup;
}
expect(await startup).toEqual(
new Error("The in-process runtime host was disposed during startup.")
);
expect(host["serverId"]).toBe(0);
expect(ffi.connectionOpen).not.toHaveBeenCalled();
});
it.each(["disposal", "connection-open failure"])(
"awaits asynchronous host shutdown while JS progresses during %s",
async (path) => {
let finishShutdown: ((error: Error | null, result: boolean) => void) | undefined;
ffi.hostShutdown.async.mockImplementationOnce((_id, callback) => {
finishShutdown = callback;
});
const host = FfiRuntimeHost.create("runtime.node", undefined, undefined, []);
if (path === "connection-open failure") {
ffi.connectionOpen.mockReturnValueOnce(0);
} else {
await host.start();
}
const settled = vi.fn();
const operation = (path === "disposal" ? host.dispose() : host.start()).then(
() => {
settled();
return undefined;
},
(error: unknown) => {
settled();
return error;
}
);
try {
const progress = vi.fn();
setImmediate(progress);
await vi.advanceTimersByTimeAsync(0);
expect(ffi.hostShutdown.async).toHaveBeenCalledExactlyOnceWith(
11,
expect.any(Function)
);
expect(progress).toHaveBeenCalledTimes(1);
expect(settled).not.toHaveBeenCalled();
expect(host["serverId"]).toBe(11);
// Callback reclamation precedes host shutdown only once no live connection remains.
expect(ffi.connectionClose.async).toHaveBeenCalledTimes(
path === "disposal" ? 1 : 0
);
expect(ffi.unregister).toHaveBeenCalledExactlyOnceWith(ffi.callbackToken);
expect(host["outboundCallback"]).toBeUndefined();
await host.dispose();
await vi.advanceTimersByTimeAsync(500);
expect(settled).not.toHaveBeenCalled();
expect(host["serverId"]).toBe(11);
expect(host["starting"]).toBe(path === "connection-open failure");
expect(host["cleanupInProgress"]).toBe(path === "disposal");
expect(ffi.hostShutdown.async).toHaveBeenCalledTimes(1);
expect(ffi.unregister).toHaveBeenCalledTimes(1);
} finally {
finishShutdown?.(null, true);
await operation;
await host.dispose();
}
if (path === "connection-open failure") {
expect(await operation).toEqual(
new Error("copilot_runtime_connection_open failed.")
);
} else {
expect(await operation).toBeUndefined();
}
expect(host["serverId"]).toBe(0);
expect(host["starting"]).toBe(false);
expect(host["cleanupInProgress"]).toBe(false);
expect(ffi.hostShutdown.async).toHaveBeenCalledTimes(1);
expect(ffi.unregister).toHaveBeenCalledTimes(1);
expect(vi.getTimerCount()).toBe(0);
}
);
it.each(["callback", "throw"])(
"preserves host shutdown %s errors during disposal",
async (failure) => {
const shutdownError = new Error("shutdown failed");
ffi.hostShutdown.async.mockImplementationOnce((_id, callback) => {
if (failure === "throw") {
throw shutdownError;
}
callback(shutdownError, false);
});
const error = vi.spyOn(console, "error").mockImplementation(() => {});
const host = FfiRuntimeHost.create("runtime.node", undefined, undefined, []);
try {
await host.start();
await host.dispose();
await vi.advanceTimersByTimeAsync(500);
expect(error).toHaveBeenCalledWith(
expect.stringContaining(
"Failed to shut down in-process FFI host: Error: shutdown failed"
)
);
expect(ffi.hostShutdown.async).toHaveBeenCalledTimes(1);
expect(ffi.unregister).toHaveBeenCalledTimes(1);
expect(host["serverId"]).toBe(0);
expect(vi.getTimerCount()).toBe(0);
} finally {
await host.dispose();
error.mockRestore();
}
}
);
});