Repository navigation
Expand file tree
/
Copy pathruntime.test.ts
More file actions
562 lines (527 loc) · 21.5 KB
/
Copy pathruntime.test.ts
File metadata and controls
562 lines (527 loc) · 21.5 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
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import { test, vi } from 'vitest';
import type { AppsFilter, DeviceLease } from '@agent-device/contracts/device';
import type { Interactor } from '@agent-device/contracts/interactor-types';
import type { DeviceInfo } from '@agent-device/kernel/device';
import { AppError } from '@agent-device/kernel/errors';
import type { PlatformRequestScope } from '@agent-device/contracts/platform-runtime-host';
import {
androidAdbHostTarget,
androidAdbInvocation,
androidAdbSerialTarget,
} from '@agent-device/platform-android/mechanics';
import { createLimrunRuntime } from './runtime.ts';
import { unusedLimrunRuntimeHost } from './runtime.fixtures.ts';
import { mkdtempForTestSync } from './tmp-dir.fixtures.ts';
import type { LimrunAdbExecutor, LimrunRuntimeDependencies } from './runtime-dependencies.ts';
/**
* The provider's platform module is the daemon's real load path: `createLimrunRuntime(...,
* { includePlatformModule: true })`, then `loadRuntime(host)`, then `bind`. These cases drive the
* app-state reader `loadLimrunPlatformRuntime` wires onto the runtime implementation through that
* entry, which no owner-level test reaches because those hand-author their owner options.
*/
const state = vi.hoisted(() => ({
foreground: { appId: 'com.example.app', activity: '.MainActivity' } as
| { appId?: string; activity?: string }
| undefined,
disconnect: vi.fn(),
tunnelClose: vi.fn(),
captureTunnelClose: vi.fn(),
onInspectionEvent: undefined as ((event: unknown) => void) | undefined,
androidCreate: vi.fn(async () => ({
metadata: { id: 'android-instance-1' },
status: {
token: 'instance-token',
apiUrl: 'https://android.example',
adbWebSocketUrl: 'wss://adb.example',
},
})),
androidDelete: vi.fn(async (_instanceId: string) => undefined),
keepAlive: vi.fn(),
/** Instance-client connections the provider made, so one lease can be shown to make one. */
connectCount: 0,
/**
* Held by a case that has to keep a create in flight after its instance was rented, which is the window
* in which a release or a daemon close has to find the instance.
*/
createGate: undefined as Promise<void> | undefined,
}));
vi.mock('@limrun/api', () => ({
default: class MockLimrun {
readonly iosInstances = { create: vi.fn(), list: vi.fn(), delete: vi.fn() };
readonly androidInstances = {
create: async () => {
const instance = await state.androidCreate();
await state.createGate;
return instance;
},
// Expired-lease recovery finds nothing under this lease's labels, so a release of a lease the
// runtime lost answers nothing rather than reaching an unstubbed SDK call.
list: vi.fn(async () => ({ getPaginatedItems: () => [] })),
delete: state.androidDelete,
};
readonly assets = { getOrUpload: vi.fn(), list: vi.fn() };
},
}));
vi.mock('@limrun/api/instance-client', () => ({
createInstanceClient: vi.fn(async () => {
state.connectCount += 1;
return {
disconnect: state.disconnect,
keepAlive: state.keepAlive,
openUrl: vi.fn(),
sendAsset: vi.fn(),
pressKey: vi.fn(),
setText: vi.fn(),
tap: vi.fn(),
startAdbTunnel: vi.fn(async () => ({
address: { address: '127.0.0.1', port: 62_001 },
close: state.tunnelClose,
})),
startTunnel: vi.fn(async (options: { onInspectionEvent: (event: unknown) => void }) => {
state.onInspectionEvent = options.onInspectionEvent;
return { tunnelId: 't1', selectors: [], close: state.captureTunnelClose };
}),
getTunnelStatus: vi.fn(async () => ({
lastDialFailure: { tunnelId: 't1', reason: 'dns_not_found' },
})),
};
}),
}));
/**
* One lease has one set of resources, however many routes arrive at it: a leased instance cannot be rented
* twice, left untracked by a release or a daemon close that raced its create, or kept alive after it is
* gone. The mock `state` is shared by this file, so each case measures from its own baseline.
*/
test('two allocations of one lease rent one instance and start one keep-alive timer', async () => {
let reportCreate!: () => void;
state.createGate = new Promise<void>((resolve) => {
reportCreate = resolve;
});
const { connects, creates, deletes, disconnects } = limrunActivity();
const runtime = createLimrunRuntime(
{ apiKey: 'lim_test_key', keepAlive: true },
testDependencies(),
);
let started: ReturnType<typeof vi.spyOn> | undefined;
try {
// The second call arrives while the first one's create is still running.
const first = runtime.leaseLifecycle.allocate?.(androidLease('lease-race'));
const second = runtime.leaseLifecycle.allocate?.(androidLease('lease-race'));
await waitForCreate(creates + 1);
started = vi.spyOn(globalThis, 'setInterval');
reportCreate();
assert.equal((await first)?.limrunInstanceId, 'android-instance-1');
assert.equal((await second)?.limrunInstanceId, 'android-instance-1');
assert.equal(state.connectCount - connects, 1);
assert.equal(started.mock.calls.length, 1);
} finally {
started?.mockRestore();
await runtime.shutdown();
state.createGate = undefined;
}
// The second allocation is not an orphaned session behind the first: one create, one connection, one delete.
const activity = limrunActivity();
assert.equal(activity.creates - creates, 1);
assert.equal(activity.connects - connects, 1);
assert.deepEqual(
state.androidDelete.mock.calls.slice(deletes).map(([instanceId]) => instanceId),
['android-instance-1'],
);
assert.equal(activity.disconnects - disconnects, 1);
});
test('a release that arrives before the create answered ends the instance that create made', async () => {
let reportCreate!: () => void;
state.createGate = new Promise<void>((resolve) => {
reportCreate = resolve;
});
const { creates, deletes, disconnects } = limrunActivity();
const runtime = createLimrunRuntime(
{ apiKey: 'lim_test_key', keepAlive: true },
testDependencies(),
);
const lease = androidLease('lease-race-release');
let started: ReturnType<typeof vi.spyOn> | undefined;
try {
const allocating = runtime.leaseLifecycle.allocate?.(lease);
const refused = refusalOf(allocating);
await waitForCreate(creates + 1);
started = vi.spyOn(globalThis, 'setInterval');
const released = runtime.leaseLifecycle.release?.(lease);
reportCreate();
// The release cannot answer before the instance it is waiting for exists, so it names what it ended.
assert.deepEqual(await released, { limrunInstanceId: 'android-instance-1' });
// The allocation whose instance was taken from it is refused rather than handed a dead session.
const error = await refused;
assert.ok(
error instanceof AppError &&
error.details?.reason === 'limrun_lease_released_mid_allocation' &&
error.details.limrunInstanceId === 'android-instance-1',
`expected the allocation to be refused for the release, got ${String(error)}`,
);
assert.equal(started.mock.calls.length, 0);
assert.deepEqual(
state.androidDelete.mock.calls.slice(deletes).map(([instanceId]) => instanceId),
['android-instance-1'],
);
assert.equal(state.disconnect.mock.calls.length - disconnects, 1);
} finally {
started?.mockRestore();
await runtime.shutdown();
state.createGate = undefined;
}
// One instance, so one delete: the allocation's own refusal does not end a second one.
assert.equal(state.androidDelete.mock.calls.length - deletes, 1);
});
test('a shutdown while the create runs ends the instance that create made', async () => {
let reportCreate!: () => void;
state.createGate = new Promise<void>((resolve) => {
reportCreate = resolve;
});
const { creates, deletes } = limrunActivity();
const runtime = createLimrunRuntime(
{ apiKey: 'lim_test_key', keepAlive: true },
testDependencies(),
);
let started: ReturnType<typeof vi.spyOn> | undefined;
try {
const allocating = runtime.leaseLifecycle.allocate?.(androidLease('lease-race-shutdown'));
const refused = refusalOf(allocating);
await waitForCreate(creates + 1);
started = vi.spyOn(globalThis, 'setInterval');
const closing = runtime.shutdown();
reportCreate();
await closing;
const error = await refused;
assert.ok(
error instanceof AppError && error.details?.reason === 'limrun_lease_released_mid_allocation',
`expected the allocation to be refused for the shutdown, got ${String(error)}`,
);
assert.equal(started.mock.calls.length, 0);
// Nothing may allocate into a runtime that was told to end every instance it holds.
await assert.rejects(
async () => await runtime.leaseLifecycle.allocate?.(androidLease('lease-after-shutdown')),
(error) => error instanceof AppError && error.details?.reason === 'limrun_runtime_shut_down',
);
assert.deepEqual(
state.androidDelete.mock.calls.slice(deletes).map(([instanceId]) => instanceId),
['android-instance-1'],
);
} finally {
started?.mockRestore();
state.createGate = undefined;
}
});
/** Lets an allocation reach the instance create, which is a few module loads away, without clock waits. */
async function waitForCreate(calls: number): Promise<void> {
await vi.waitFor(() => assert.equal(state.androidCreate.mock.calls.length, calls));
}
/**
* Why one racing call refused, captured from the moment it starts. Two routes can answer in either order,
* and the one that answers first must not leave the other's refusal unobserved.
*/
function refusalOf(call: Promise<unknown> | undefined): Promise<unknown> {
return (call ?? Promise.resolve()).then(
() => undefined,
(error: unknown) => error,
);
}
/** Where the shared instance-control mocks stand, so a case can measure only what it caused. */
function limrunActivity(): {
creates: number;
deletes: number;
disconnects: number;
connects: number;
} {
return {
creates: state.androidCreate.mock.calls.length,
deletes: state.androidDelete.mock.calls.length,
disconnects: state.disconnect.mock.calls.length,
connects: state.connectCount,
};
}
test('the platform module answers app state from the live Android provider session', async () => {
const registration = createLimrunRuntime(
{ apiKey: 'lim_test_key', runtimeInstance: 'test-instance' },
testDependencies(),
{ includePlatformModule: true },
);
try {
const device = await allocateAndroidDevice(registration.runtime);
const owner = await registration.platformModule.loadRuntime(unusedLimrunRuntimeHost());
const binding = await owner.bind({
device,
intent: { kind: 'ordinary' },
scope: requestScope(),
});
assert.equal(binding.facts.operations.appState.available, true);
assert.deepEqual(await binding.operations.appState?.(), {
package: 'com.example.app',
activity: '.MainActivity',
});
// An instance with no foreground application answers with an empty state rather than failing.
state.foreground = undefined;
assert.deepEqual(await binding.operations.appState?.(), {
package: undefined,
activity: undefined,
});
} finally {
await registration.runtime.shutdown();
}
});
test('the platform module refuses app state once the provider session died behind the device id', async () => {
const registration = createLimrunRuntime(
{ apiKey: 'lim_test_key', runtimeInstance: 'test-instance' },
testDependencies(),
{ includePlatformModule: true },
);
try {
const device = await allocateAndroidDevice(registration.runtime);
const owner = await registration.platformModule.loadRuntime(unusedLimrunRuntimeHost());
const binding = await owner.bind({
device,
intent: { kind: 'ordinary' },
scope: requestScope(),
});
// The lease can end between admission and the read; the reader fails closed on the lost
// session instead of reporting a foreground app it can no longer observe.
await registration.runtime.shutdown();
await assert.rejects(
async () => await binding.operations.appState?.(),
(error) => error instanceof AppError && error.code === 'UNSUPPORTED_OPERATION',
);
} finally {
await registration.runtime.shutdown();
}
});
test('the runtime inventory answers only for its own live lease', async () => {
const runtime = createLimrunRuntime({ apiKey: 'lim_test_key' }, testDependencies());
try {
// A request for another provider or without a lease is not the runtime's to answer.
assert.equal(await runtime.deviceInventoryProvider?.({ leaseProvider: 'maestro' }), null);
assert.equal(await runtime.deviceInventoryProvider?.({ leaseProvider: 'limrun' }), null);
// A limrun lease with no live session declines; the daemon keeps its own inventory answer.
assert.equal(
await runtime.deviceInventoryProvider?.({ leaseProvider: 'limrun', leaseId: 'lease-none' }),
null,
);
const device = await allocateAndroidDevice(runtime, 'lease-inventory');
const request = { leaseProvider: 'limrun', leaseId: 'lease-inventory' };
assert.deepEqual(await runtime.deviceInventoryProvider?.(request), [device]);
// A platform filter that cannot match the leased platform answers an authoritative empty set.
assert.deepEqual(
await runtime.deviceInventoryProvider?.({ ...request, platform: 'apple' }),
[],
);
} finally {
await runtime.shutdown();
}
});
test('the platform module surfaces an aborted request inside the app-state reader', async () => {
const registration = createLimrunRuntime(
{ apiKey: 'lim_test_key', runtimeInstance: 'test-instance' },
testDependencies(),
{ includePlatformModule: true },
);
const abort = new AbortController();
try {
const device = await allocateAndroidDevice(registration.runtime);
const owner = await registration.platformModule.loadRuntime(unusedLimrunRuntimeHost());
const binding = await owner.bind({
device,
intent: { kind: 'ordinary' },
scope: requestScope(abort.signal),
});
abort.abort(new AppError('COMMAND_CANCELLED', 'fixture request canceled'));
await assert.rejects(
async () => await binding.operations.appState?.(),
(error) => error instanceof AppError && error.code === 'COMMAND_CANCELLED',
);
} finally {
await registration.runtime.shutdown();
}
});
test('a network capture writes a private HAR with its failures on artifacts and at release', async () => {
const harDir = mkdtempForTestSync('limrun-har-');
const runtime = createLimrunRuntime(
{ apiKey: 'lim_test_key', networkHarDir: harDir },
testDependencies(),
);
const lease = androidLease('lease-capture');
const harPath = path.join(harDir, `${lease.leaseId}.har`);
// A HAR left by an earlier capture becomes private when it is rewritten.
fs.writeFileSync(harPath, '', { mode: 0o644 });
try {
// A repeat allocation of the live lease starts the capture it newly asks for.
await runtime.leaseLifecycle.allocate?.(lease);
await runtime.leaseLifecycle.allocate?.(lease, { flags: { providerNetworkLogs: true } });
for (let index = 0; index < 499; index += 1) {
state.onInspectionEvent?.(completedRequest(`https://api.example.com/${index}`));
}
state.onInspectionEvent?.(
completedRequest('https://missing.example.com/', 'client_dial_failed'),
);
// Truncation is a buffer statistic, so it keeps the failure that came before it.
state.onInspectionEvent?.(completedRequest('https://api.example.com/last'));
const listed = await runtime.cloudArtifacts?.listCloudArtifacts?.({ leaseId: lease.leaseId });
assert.equal(listed?.cloudArtifacts[0]?.url, harPath);
const har = JSON.parse(fs.readFileSync(harPath, 'utf8'));
assert.equal(har.log.entries.length, 500);
assert.equal(har.log.entries.at(-2).response.status, 0);
assert.equal(fs.statSync(harPath).mode & 0o777, 0o600);
assert.deepEqual(listed?.cloudArtifacts[0]?.metadata, {
failures: {
count: 1,
last: { kind: 'request-failed', host: 'missing.example.com', port: 443 },
lastDialFailure: 'dns_not_found',
truncated: 1,
},
});
const released = (await runtime.leaseLifecycle.release?.(lease)) as {
cloudArtifacts?: { cloudArtifacts: { url?: string }[]; message?: string };
};
assert.equal(released.cloudArtifacts?.cloudArtifacts[0]?.url, harPath);
assert.equal(state.captureTunnelClose.mock.calls.length, 1);
assert.match(
String(released.cloudArtifacts?.message),
/last request-failed missing\.example\.com:443/,
);
const afterClose = await runtime.cloudArtifacts?.listCloudArtifacts?.({
leaseId: lease.leaseId,
});
assert.equal(afterClose?.cloudArtifacts[0]?.url, harPath);
} finally {
await runtime.shutdown();
}
});
test('released captures past the record limit forget the oldest released lease first', async () => {
const runtime = createLimrunRuntime(
{ apiKey: 'lim_test_key', networkHarDir: mkdtempForTestSync('limrun-har-') },
testDependencies(),
);
const live = androidLease('lease-live-unavailable');
try {
await runtime.leaseLifecycle.allocate?.(live, {
flags: { providerNetworkLogs: true, providerNetworkHosts: 'not a host' },
});
for (let index = 0; index < 33; index += 1) {
const lease = androidLease(`lease-released-${index}`);
await runtime.leaseLifecycle.allocate?.(lease, { flags: { providerNetworkLogs: true } });
await runtime.leaseLifecycle.release?.(lease);
}
const list = async (leaseId: string) =>
(await runtime.cloudArtifacts?.listCloudArtifacts?.({ leaseId }))?.status;
assert.equal(await list('lease-released-0'), undefined);
assert.equal(await list('lease-released-1'), undefined);
assert.equal(await list('lease-released-32'), 'ready');
assert.equal(await list(live.leaseId), 'unavailable');
} finally {
await runtime.shutdown();
}
});
test('a network capture that cannot start is an unavailable artifact with its typed reason', async () => {
const runtime = createLimrunRuntime({ apiKey: 'lim_test_key' }, testDependencies());
const lease = androidLease('lease-no-dir');
try {
await runtime.leaseLifecycle.allocate?.(lease, { flags: { providerNetworkLogs: true } });
const listed = await runtime.cloudArtifacts?.listCloudArtifacts?.({ leaseId: lease.leaseId });
assert.equal(listed?.status, 'unavailable');
assert.deepEqual(listed?.cloudArtifacts[0]?.metadata, { reason: 'capture-dir-unset' });
} finally {
await runtime.shutdown();
}
});
function completedRequest(url: string, error?: string): unknown {
return {
type: 'complete',
sequence: 1,
requestId: url,
data: {
startedDateTime: new Date(0).toISOString(),
time: 0,
request: { method: 'GET', url, httpVersion: 'HTTP/1.1', headers: [], cookies: [] },
response: {
status: error ? 0 : 200,
statusText: '',
httpVersion: '',
headers: [],
cookies: [],
},
cache: {},
timings: { send: 0, wait: 0, receive: 0 },
_limrun: { tunnelId: 't1', selectorId: 's1', ...(error ? { error } : {}) },
},
};
}
function requestScope(signal: AbortSignal = new AbortController().signal): PlatformRequestScope {
return {
signal,
diagnostics: { emit: () => {} },
progress: { report: () => {} },
};
}
async function allocateAndroidDevice(
runtime: ReturnType<typeof createLimrunRuntime>,
leaseId = 'lease-appstate',
): Promise<DeviceInfo> {
const allocation = await runtime.leaseLifecycle.allocate?.(androidLease(leaseId));
const device = allocation?.device;
if (!device || typeof device !== 'object') throw new Error('Expected allocated device');
return device as DeviceInfo;
}
function androidLease(leaseId: string): DeviceLease {
return {
leaseId,
tenantId: 'team-a',
runId: 'run-a',
backend: 'android-instance',
leaseProvider: 'limrun',
createdAt: 1,
heartbeatAt: 1,
expiresAt: 60_001,
};
}
function testDependencies(): LimrunRuntimeDependencies {
return {
clientVersion: 'test-version',
android: {
createInteractor: () => ({}) as Interactor,
createPortReverse: async () => ({
ensure: async () => {},
remove: async () => {},
removeAllOwned: async () => {},
list: async () => [],
}),
inferAppName: async () => 'Example',
listApps: async (_adb: LimrunAdbExecutor, _filter: AppsFilter) => [],
getForegroundApp: async () => (state.foreground ? { ...state.foreground } : undefined),
getKeyboardState: async () => ({ visible: false, inputOwner: 'unknown' as const }),
dismissKeyboard: async () => ({
visible: false,
inputOwner: 'unknown' as const,
attempts: 0,
wasVisible: false,
dismissed: false,
}),
readLogs: async () => '',
forceStopApp: async () => {},
deviceAdbInvocation: (serial: string, command: readonly string[]) =>
androidAdbInvocation(androidAdbSerialTarget(serial), command),
hostAdbInvocation: (command: readonly string[]) =>
androidAdbInvocation(androidAdbHostTarget(), command),
adbError: async (message: string) => new AppError('COMMAND_FAILED', message),
},
host: {
runAdb: async () => ({ stdout: '', stderr: '', exitCode: 0 }),
archiveDirectory: async () => undefined,
downloadFile: async () => undefined,
},
ios: {
applySimctlSetting: async () => undefined,
resolveAppAlias: async (app: string) => app,
readBundleAppName: async () => undefined,
},
} satisfies LimrunRuntimeDependencies;
}