Skip to content

Commit 85bb4b4

Browse files
committed
fix: complete install deployment cancellation
1 parent 18b0b96 commit 85bb4b4

35 files changed

Lines changed: 849 additions & 430 deletions

‎packages/contracts/src/app-deployment-runtime.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,7 @@ export type AndroidAppDeploymentExecutor = Readonly<{
117117

118118
/** The HarmonyOS package owns deployment/relaunch semantics above these HDC executor calls. */
119119
export type HarmonyAppDeploymentExecutor = Readonly<{
120-
resolveBundleName(archivePath: string): Promise<string | undefined>;
120+
resolveBundleName(archivePath: string, signal: AbortSignal): Promise<string | undefined>;
121121
install(device: DeviceInfo, archivePath: string, signal: AbortSignal): Promise<void>;
122122
open(device: DeviceInfo, bundleId: string, signal: AbortSignal): Promise<void>;
123123
sleep(milliseconds: number, signal: AbortSignal): Promise<void>;

‎packages/platform-harmonyos/src/deployment/runtime.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@ test('exposes only HarmonyOS deployApp after fact admission', async () => {
5151
appPath: '/tmp/app.hap',
5252
replaceExisting: true,
5353
});
54+
expect(resolveBundleName).toHaveBeenCalledWith('/tmp/app.hap', signal);
5455
expect(resolveBundleName).toHaveBeenCalledTimes(2);
5556
expect(install).toHaveBeenCalledTimes(2);
5657
expect(sleep).toHaveBeenCalledWith(1_000, signal);

‎packages/platform-harmonyos/src/deployment/runtime.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ async function deployHarmonyApp(
5353
input: AppDeploymentInput,
5454
signal: AbortSignal,
5555
): Promise<AppDeploymentResult> {
56-
const bundleId = (await executor.resolveBundleName(input.appPath)) ?? input.app.trim();
56+
const bundleId = (await executor.resolveBundleName(input.appPath, signal)) ?? input.app.trim();
5757
if (!bundleId) {
5858
throw new AppError('INVALID_ARGS', 'Could not determine the bundle name from the HAP archive', {
5959
hint: 'Pass the HarmonyOS bundle name before the HAP path, or provide a valid HAP containing module.json.',

‎packages/provider-limrun/src/android.ts‎

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ import type {
2121
LimrunRuntimeDependencies,
2222
} from './runtime-dependencies.ts';
2323
import { normalizeOptionalString } from './strings.ts';
24+
import { awaitLimrunOperation } from './request-cancellation.ts';
2425

2526
type LimrunAdbTunnel = Awaited<ReturnType<LimrunAndroidClient['startAdbTunnel']>>;
2627

@@ -84,18 +85,28 @@ export async function installLimrunAndroidApp(
8485
session: LimrunAndroidSession,
8586
installablePath: string,
8687
options?: ProviderDeviceInstallOptions,
88+
signal?: AbortSignal,
8789
): Promise<ProviderDeviceInstallResult> {
90+
signal?.throwIfAborted();
8891
const packageName = normalizeOptionalString(options?.packageNameHint);
8992
if (options?.relaunch && packageName) {
9093
await runLimrunAndroidAdb(session, ['shell', 'am', 'force-stop', packageName], {
9194
allowFailure: true,
95+
signal,
9296
});
9397
}
94-
const asset = await limrun.assets.getOrUpload({
95-
path: installablePath,
96-
name: buildAndroidAssetName(packageName, installablePath),
97-
});
98-
await session.client.sendAsset(asset.signedDownloadUrl);
98+
const asset = await awaitLimrunOperation(
99+
limrun.assets.getOrUpload(
100+
{
101+
path: installablePath,
102+
name: buildAndroidAssetName(packageName, installablePath),
103+
},
104+
{ signal },
105+
),
106+
signal,
107+
);
108+
await awaitLimrunOperation(session.client.sendAsset(asset.signedDownloadUrl), signal);
109+
signal?.throwIfAborted();
99110
const appName = packageName
100111
? await session.dependencies.android.inferAppName(packageName)
101112
: undefined;

‎packages/provider-limrun/src/app-log-poller.ts‎

Lines changed: 3 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import type {
88
import { AsyncCleanupStack } from '@agent-device/contracts/platform';
99
import { createAppLogLiveHandleFromFinish } from '@agent-device/capture-kit';
1010
import type { LogBackend } from '@agent-device/contracts/observability';
11+
import { awaitLimrunOperation } from './request-cancellation.ts';
1112

1213
export type LimrunAppLogReader = AsyncDisposable &
1314
Readonly<{
@@ -115,9 +116,10 @@ async function boundedRead(options: {
115116
appBundleId: string;
116117
}): Promise<Readonly<{ status: 'read'; text: string }> | Readonly<{ status: 'timeout' }>> {
117118
const controller = new AbortController();
118-
const read = abortable(
119+
const read = awaitLimrunOperation(
119120
options.reader.readLogs(options.appBundleId, 1_000),
120121
controller.signal,
122+
'App-log provider read aborted',
121123
).then((text) => ({ status: 'read' as const, text }));
122124
try {
123125
const result = await Promise.race([
@@ -136,27 +138,6 @@ async function boundedRead(options: {
136138
}
137139
}
138140

139-
async function abortable<Value>(source: Promise<Value>, signal: AbortSignal): Promise<Value> {
140-
return await new Promise<Value>((resolve, reject) => {
141-
const aborted = () => reject(signal.reason ?? new Error('App-log provider read aborted'));
142-
if (signal.aborted) {
143-
aborted();
144-
return;
145-
}
146-
signal.addEventListener('abort', aborted, { once: true });
147-
void source.then(
148-
(value) => {
149-
signal.removeEventListener('abort', aborted);
150-
resolve(value);
151-
},
152-
(error: unknown) => {
153-
signal.removeEventListener('abort', aborted);
154-
reject(error);
155-
},
156-
);
157-
});
158-
}
159-
160141
function appendedTail(previous: string, current: string): string {
161142
if (!previous || !current) return current;
162143
const prefix = buildPrefixTable(current);

‎packages/provider-limrun/src/deployment-runtime.test.ts‎

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,3 +95,65 @@ test.each([
9595
expect(materializeAndroid).toHaveBeenCalledTimes(device.platform === 'android' ? 1 : 0);
9696
},
9797
);
98+
99+
test.each([
100+
[
101+
'deployApp',
102+
(operations: ReturnType<typeof createLimrunAppDeploymentOperations>) =>
103+
operations.deployApp?.({
104+
app: 'com.example.app',
105+
appPath: '/tmp/app',
106+
replaceExisting: false,
107+
}),
108+
],
109+
[
110+
'deployMaterializedApp',
111+
(operations: ReturnType<typeof createLimrunAppDeploymentOperations>) =>
112+
operations.deployMaterializedApp?.({
113+
artifact: { installablePath: '/tmp/app.apk', cleanup: async () => {} },
114+
}),
115+
],
116+
] as const)(
117+
'aborts an in-flight Limrun %s callback with the binding signal',
118+
async (_name, invoke) => {
119+
const controller = new AbortController();
120+
const abortReason = new Error('request cancelled during Limrun deployment');
121+
const deployApp = vi.fn(async (_device, _input, signal?: AbortSignal) => {
122+
expect(signal).toBe(controller.signal);
123+
return await rejectWhenAborted(signal);
124+
});
125+
const deployMaterializedApp = vi.fn(async (_device, _input, signal?: AbortSignal) => {
126+
expect(signal).toBe(controller.signal);
127+
return await rejectWhenAborted(signal);
128+
});
129+
const operations = createLimrunAppDeploymentOperations(
130+
{
131+
host: unusedLimrunRuntimeHost(),
132+
ownsDevice: () => true,
133+
deployApp,
134+
deployMaterializedApp,
135+
},
136+
limrunIosDevice,
137+
controller.signal,
138+
);
139+
140+
const pending = invoke(operations);
141+
controller.abort(abortReason);
142+
143+
await expect(pending).rejects.toBe(abortReason);
144+
},
145+
);
146+
147+
async function rejectWhenAborted(signal: AbortSignal | undefined): Promise<never> {
148+
return await new Promise<never>((_resolve, reject) => {
149+
if (!signal) {
150+
reject(new Error('provider deployment callback was not given the binding signal'));
151+
return;
152+
}
153+
if (signal.aborted) {
154+
reject(signal.reason);
155+
return;
156+
}
157+
signal.addEventListener('abort', () => reject(signal.reason), { once: true });
158+
});
159+
}

‎packages/provider-limrun/src/deployment-runtime.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,10 +33,12 @@ export type LimrunAppDeploymentRuntimeOptions = Readonly<{
3333
deployApp?(
3434
device: DeviceInfo,
3535
input: AppDeploymentInput,
36+
signal: AbortSignal,
3637
): Promise<ProviderDeviceInstallResult | undefined>;
3738
deployMaterializedApp?(
3839
device: DeviceInfo,
3940
input: DeployMaterializedAppInput,
41+
signal: AbortSignal,
4042
): Promise<ProviderDeviceInstallResult | undefined>;
4143
}>;
4244

@@ -76,11 +78,11 @@ export function createLimrunAppDeploymentOperations(
7678
}
7779
return Object.freeze({
7880
deployApp: async (input: AppDeploymentInput) =>
79-
limrunDeploymentResult(await deployApp(device, input)),
81+
limrunDeploymentResult(await deployApp(device, input, signal)),
8082
materializeAppSource: async (input: MaterializeAppSourceInput) =>
8183
await materializeLimrunSource(options.host, device, input, signal),
8284
deployMaterializedApp: async (input: DeployMaterializedAppInput) =>
83-
limrunDeploymentResult(await deployMaterializedApp(device, input)),
85+
limrunDeploymentResult(await deployMaterializedApp(device, input, signal)),
8486
});
8587
}
8688

‎packages/provider-limrun/src/ios.ts‎

Lines changed: 41 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ import path from 'node:path';
2323
import { setTimeout as sleep } from 'node:timers/promises';
2424
import { flattenIosTree, toIosSelector, writeBase64File, type IosTreeNode } from './snapshot.ts';
2525
import { normalizeOptionalString } from './strings.ts';
26+
import { awaitLimrunOperation } from './request-cancellation.ts';
2627
import type { LimrunRuntimeDependencies } from './runtime-dependencies.ts';
2728

2829
export type LimrunIosSession = {
@@ -76,18 +77,32 @@ export async function installLimrunIosApp(
7677
session: LimrunIosSession,
7778
installablePath: string,
7879
options?: ProviderDeviceInstallOptions,
80+
signal?: AbortSignal,
7981
): Promise<ProviderDeviceInstallResult> {
82+
signal?.throwIfAborted();
8083
const prepared = await prepareLimrunIosAsset(installablePath, session.dependencies);
8184
try {
82-
const asset = await limrun.assets.getOrUpload({
83-
path: prepared.uploadPath,
84-
name: prepared.assetName,
85-
});
86-
const result = await installLimrunIosRemoteApp(session, asset.signedDownloadUrl, {
87-
md5: asset.md5,
88-
relaunch: options?.relaunch,
89-
appIdentifierHint: options?.appIdentifierHint,
90-
});
85+
signal?.throwIfAborted();
86+
const asset = await awaitLimrunOperation(
87+
limrun.assets.getOrUpload(
88+
{
89+
path: prepared.uploadPath,
90+
name: prepared.assetName,
91+
},
92+
{ signal },
93+
),
94+
signal,
95+
);
96+
const result = await installLimrunIosRemoteApp(
97+
session,
98+
asset.signedDownloadUrl,
99+
{
100+
md5: asset.md5,
101+
relaunch: options?.relaunch,
102+
appIdentifierHint: options?.appIdentifierHint,
103+
},
104+
signal,
105+
);
91106
const bundleId = result.appId;
92107
return {
93108
...(bundleId ? { bundleId, launchTarget: bundleId } : {}),
@@ -102,18 +117,28 @@ export async function installLimrunIosRemoteApp(
102117
session: LimrunIosSession,
103118
url: string,
104119
options?: LimrunIosRemoteInstallOptions,
120+
signal?: AbortSignal,
105121
): Promise<LimrunIosRemoteInstallResult> {
106-
const beforeInstallApps = await session.client.listApps().catch(() => undefined);
107-
const result = await session.client.installApp(url, {
108-
md5: options?.md5,
109-
launchMode: options?.relaunch ? 'RelaunchIfRunning' : 'ForegroundIfRunning',
110-
});
122+
signal?.throwIfAborted();
123+
const beforeInstallApps = await awaitLimrunOperation(session.client.listApps(), signal).catch(
124+
(error: unknown) => {
125+
if (signal?.aborted) throw error;
126+
return undefined;
127+
},
128+
);
129+
const result = await awaitLimrunOperation(
130+
session.client.installApp(url, {
131+
md5: options?.md5,
132+
launchMode: options?.relaunch ? 'RelaunchIfRunning' : 'ForegroundIfRunning',
133+
}),
134+
signal,
135+
);
111136
const resultBundleId = normalizeOptionalString(result.bundleId);
112137
const requestedBundleId = normalizeOptionalString(options?.appIdentifierHint);
113138
let afterInstallApps: LimrunIosApp[] = [];
114139
for (const delayMs of IOS_APP_INVENTORY_RETRY_DELAYS_MS) {
115-
if (delayMs > 0) await sleep(delayMs);
116-
afterInstallApps = await session.client.listApps();
140+
if (delayMs > 0) await sleep(delayMs, undefined, { signal });
141+
afterInstallApps = await awaitLimrunOperation(session.client.listApps(), signal);
117142
const verifiedBundleId = resolveInstalledIosAppId({
118143
resultBundleId,
119144
requestedBundleId,
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
* The Limrun WebSocket client does not expose an AbortSignal parameter. Keep the request-bound
3+
* caller cancellable while retaining a handled continuation for the provider operation it started.
4+
*/
5+
export async function awaitLimrunOperation<Value>(
6+
source: Promise<Value>,
7+
signal?: AbortSignal,
8+
abortMessage = 'Limrun provider operation aborted',
9+
): Promise<Value> {
10+
if (!signal) return await source;
11+
return await new Promise<Value>((resolve, reject) => {
12+
const aborted = () => reject(signal.reason ?? new Error(abortMessage));
13+
if (signal.aborted) {
14+
aborted();
15+
return;
16+
}
17+
signal.addEventListener('abort', aborted, { once: true });
18+
void source.then(
19+
(value) => {
20+
signal.removeEventListener('abort', aborted);
21+
resolve(value);
22+
},
23+
(error: unknown) => {
24+
signal.removeEventListener('abort', aborted);
25+
reject(error);
26+
},
27+
);
28+
});
29+
}

0 commit comments

Comments
 (0)