Skip to content

Commit 26648ba

Browse files
edusperoniNathanWalker
authored andcommitted
feat(ios): move a device to another origin when its USB tunnel drops
A tunnel address only exists while its tunnel is up: once the cable is pulled or the CoreDevice tunnel resets, the app can no longer reach the dev server, and the session used to need a restart. The tunnel service now reports a tunnel that goes down on its own. The run controller then chooses that device's origin again (typically the Mac's LAN address, for a device that is also on the network), uploads its `dev-server.json` to `LiveSync/app/` and restarts only that device's app. The rewrite waits its turn on the session's action chain; a device that is gone by then is reported rather than failing the session.
1 parent 401672a commit 26648ba

7 files changed

Lines changed: 199 additions & 3 deletions

File tree

‎lib/contracts/internal/ios-device-tunnel-service.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,4 +21,10 @@ export abstract class IOSDeviceTunnelService {
2121
abstract getHostAddress(deviceIdentifier: string): string | undefined;
2222

2323
abstract close(deviceIdentifier: string): Promise<void>;
24+
25+
/**
26+
* Calls `listener` with the device's identifier when an open tunnel goes
27+
* down without `close`, after `getHostAddress` stopped returning it.
28+
*/
29+
abstract onTunnelLost(listener: (deviceIdentifier: string) => void): void;
2430
}

‎lib/controllers/run-controller.ts‎

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,7 @@ export class RunController extends EventEmitter implements IRunController {
150150
);
151151

152152
this.attachDeviceLostHandler();
153+
this.attachTunnelLostHandler();
153154
}
154155

155156
public async stop(data: IStopRunData): Promise<void> {
@@ -648,6 +649,73 @@ export class RunController extends EventEmitter implements IRunController {
648649
);
649650
}
650651

652+
@cache()
653+
private attachTunnelLostHandler(): void {
654+
this.iOSDeviceTunnelService.onTunnelLost((deviceIdentifier) =>
655+
this.switchDevServerOrigin(deviceIdentifier),
656+
);
657+
}
658+
659+
/**
660+
* Points the device's `dev-server.json` at the origin it can use now and
661+
* restarts only its app, so it reconnects there.
662+
*/
663+
private async switchDevServerOrigin(deviceIdentifier: string): Promise<void> {
664+
const previous = this.devServerOriginService.getOrigin(deviceIdentifier);
665+
if (!previous) {
666+
return;
667+
}
668+
for (const projectDir in this.$liveSyncProcessDataService.getAllPersistedData()) {
669+
const descriptor = _.find(
670+
this.$liveSyncProcessDataService.getDeviceDescriptors(projectDir),
671+
(d) => d.identifier === deviceIdentifier,
672+
);
673+
if (!descriptor) {
674+
continue;
675+
}
676+
const switched = await this.addActionToChain(projectDir, async () => {
677+
try {
678+
if (!this.devServerOriginService.getOrigin(deviceIdentifier)) {
679+
return false;
680+
}
681+
const device =
682+
this.$devicesService.getDeviceByIdentifier(deviceIdentifier);
683+
const origin = await this.devServerOriginService.chooseOrigin(device);
684+
if (origin === previous) {
685+
return false;
686+
}
687+
const platformLiveSyncService =
688+
this.$liveSyncServiceResolver.resolveLiveSyncService(
689+
device.deviceInfo.platform,
690+
);
691+
if (!platformLiveSyncService.syncDevServerFile) {
692+
return false;
693+
}
694+
this.$logger.info(
695+
`Switching ${device.deviceInfo.displayName || deviceIdentifier} to the Vite dev server at ${origin} and restarting the app.`,
696+
);
697+
await platformLiveSyncService.syncDevServerFile(
698+
device,
699+
this.$projectDataService.getProjectData(projectDir),
700+
descriptor,
701+
);
702+
return true;
703+
} catch (err) {
704+
this.$logger.warn(
705+
`Unable to point ${deviceIdentifier} at another Vite dev server origin: ${err.message || err}. Restart the run to reconnect.`,
706+
);
707+
return false;
708+
}
709+
});
710+
if (switched) {
711+
await this.restartApplication({
712+
projectDir,
713+
deviceIdentifiers: [deviceIdentifier],
714+
});
715+
}
716+
}
717+
}
718+
651719
private async syncInitialDataOnDevices(
652720
projectData: IProjectData,
653721
liveSyncInfo: ILiveSyncInfo,

‎lib/definitions/livesync.d.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -311,6 +311,15 @@ declare global {
311311
device: Mobile.IDevice,
312312
liveSyncInfo: ILiveSyncWatchInfo,
313313
): Promise<void>;
314+
/**
315+
* Writes the device's current `dev-server.json` into the app already on
316+
* it, outside a full sync. The app reads it when it next starts.
317+
*/
318+
syncDevServerFile?(
319+
device: Mobile.IDevice,
320+
projectData: IProjectData,
321+
liveSyncDeviceData: ILiveSyncDeviceDescriptor,
322+
): Promise<void>;
314323
}
315324

316325
interface IRestartApplicationInfo {

‎lib/services/ios/ios-device-tunnel-service.ts‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ export class IOSDeviceTunnelServiceImpl implements IOSDeviceTunnelService {
3838

3939
private tunnels: IDictionary<ITunnel> = {};
4040
private hostAddresses: IDictionary<string> = {};
41+
private tunnelLostListeners: ((deviceIdentifier: string) => void)[] = [];
4142
private tunnelReadyTimeoutMs = 10000;
4243
private tunnelPollIntervalMs = 500;
4344
private listTimeoutMs = 10000;
@@ -63,6 +64,10 @@ export class IOSDeviceTunnelServiceImpl implements IOSDeviceTunnelService {
6364
return this.hostAddresses[deviceIdentifier];
6465
}
6566

67+
public onTunnelLost(listener: (deviceIdentifier: string) => void): void {
68+
this.tunnelLostListeners.push(listener);
69+
}
70+
6671
public async close(deviceIdentifier: string): Promise<void> {
6772
const tunnel = this.tunnels[deviceIdentifier];
6873
if (!tunnel) {
@@ -206,8 +211,11 @@ export class IOSDeviceTunnelServiceImpl implements IOSDeviceTunnelService {
206211
delete this.hostAddresses[deviceIdentifier];
207212
}
208213
this.logger.warn(
209-
`The USB tunnel to ${deviceIdentifier} closed, so the app can no longer reach the Vite dev server at ${address}. Restart the run to reconnect.`,
214+
`The USB tunnel to ${deviceIdentifier} closed, so the app can no longer reach the Vite dev server at ${address}.`,
210215
);
216+
for (const listener of this.tunnelLostListeners) {
217+
listener(deviceIdentifier);
218+
}
211219
});
212220
});
213221
if (holder.pid) {

‎lib/services/livesync/ios-livesync-service.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import { APP_FOLDER_NAME, DEV_SERVER_FILE_NAME } from "../../constants";
66
import { LiveSyncPaths } from "../../common/constants";
77
import { performanceLog } from "../../common/decorators";
88
import { IPlatformsDataService } from "../../definitions/platform";
9+
import { IProjectData } from "../../definitions/project";
910
import {
1011
IFileSystem,
1112
IProjectFilesManager,
@@ -270,6 +271,22 @@ export class IOSLiveSyncService
270271
}
271272
}
272273

274+
public async syncDevServerFile(
275+
device: Mobile.IDevice,
276+
projectData: IProjectData,
277+
liveSyncDeviceData: ILiveSyncDeviceDescriptor,
278+
): Promise<void> {
279+
await this.writeDevServerFile(
280+
await this.getAppData({
281+
projectData,
282+
device,
283+
liveSyncDeviceData,
284+
watch: true,
285+
useHotModuleReload: true,
286+
}),
287+
);
288+
}
289+
273290
/**
274291
* Writes the device's `dev-server.json` next to `bundle.mjs` in the
275292
* installed app (a simulator) or the synced one (a device).

‎test/controllers/run-controller.ts‎

Lines changed: 76 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,7 @@ function createTestInjector() {
151151
open: async (): Promise<string> => null,
152152
getHostAddress: (): string => undefined,
153153
close: async () => ({}),
154+
onTunnelLost: (): void => undefined,
154155
},
155156
});
156157
injector.register({
@@ -335,6 +336,9 @@ describe("RunController", () => {
335336
let filesAtFullSync: IDictionary<string> = null;
336337
let devServerFilePlatforms: string[];
337338
let reverseWorks: boolean;
339+
let tunnelLost: (deviceIdentifier: string) => Promise<void>;
340+
let rewritten: { device: string; file: string }[];
341+
let restarted: string[];
338342

339343
let syncFailures: string[];
340344

@@ -397,6 +401,15 @@ describe("RunController", () => {
397401
return tunnelAddresses[id];
398402
};
399403
tunnelService.getHostAddress = (id: string) => tunnelAddresses[id];
404+
tunnelLost = null;
405+
tunnelService.onTunnelLost = (listener: any) => {
406+
tunnelLost = listener;
407+
};
408+
rewritten = [];
409+
restarted = [];
410+
injector.resolve("devicesService").getDeviceByIdentifier = (
411+
identifier: string,
412+
) => map[identifier]?.device;
400413
tunnelService.close = async (identifier: string) => {
401414
closed.push(identifier);
402415
};
@@ -437,9 +450,28 @@ describe("RunController", () => {
437450
};
438451
};
439452
liveSyncService.shouldRestart = async () => true;
440-
liveSyncService.restartApplication = async (): Promise<void> =>
441-
undefined;
453+
liveSyncService.restartApplication = async (
454+
_projectData: any,
455+
result: ILiveSyncResultInfo,
456+
) => {
457+
restarted.push(result.deviceAppData.device.deviceInfo.identifier);
458+
};
459+
liveSyncService.getAppData = async (syncInfo: IFullSyncInfo) => ({
460+
appIdentifier,
461+
device: syncInfo.device,
462+
platform: syncInfo.device.deviceInfo.platform,
463+
});
442464
}
465+
injector.resolve("iOSLiveSyncService").syncDevServerFile = async (
466+
device: Mobile.IDevice,
467+
) => {
468+
rewritten.push({
469+
device: device.deviceInfo.identifier,
470+
file: devServerOriginService.getDevServerFile(
471+
device.deviceInfo.identifier,
472+
),
473+
});
474+
};
443475
});
444476

445477
afterEach(() => {
@@ -573,6 +605,48 @@ describe("RunController", () => {
573605
assert.deepStrictEqual(filesAtFullSync, { myiOSDevice: null });
574606
});
575607

608+
it("rewrites the file of a device whose tunnel drops and restarts only its app", async () => {
609+
await run([iOSDevice, secondIOSDevice]);
610+
restarted = [];
611+
const before = injector
612+
.get(DevServerOriginService)
613+
.getOrigin("mySecondiOSDevice");
614+
615+
delete tunnelAddresses.myiOSDevice;
616+
await tunnelLost("myiOSDevice");
617+
618+
assert.lengthOf(rewritten, 1);
619+
assert.equal(rewritten[0].device, "myiOSDevice");
620+
assert.notInclude(JSON.parse(rewritten[0].file).origin, "fd00::1");
621+
assert.deepStrictEqual(restarted, ["myiOSDevice"]);
622+
assert.equal(
623+
injector.get(DevServerOriginService).getOrigin("mySecondiOSDevice"),
624+
before,
625+
);
626+
});
627+
628+
it("leaves a device alone when its origin does not change", async () => {
629+
process.env.NS_HMR_HOST = "dev.example.test";
630+
await run([iOSDevice]);
631+
restarted = [];
632+
633+
await tunnelLost("myiOSDevice");
634+
635+
assert.deepStrictEqual(rewritten, []);
636+
assert.deepStrictEqual(restarted, []);
637+
});
638+
639+
it("ignores a tunnel loss for a device on the bundle-baked origin", async () => {
640+
devServerFilePlatforms = [];
641+
await run([iOSDevice]);
642+
restarted = [];
643+
644+
await tunnelLost("myiOSDevice");
645+
646+
assert.deepStrictEqual(rewritten, []);
647+
assert.deepStrictEqual(restarted, []);
648+
});
649+
576650
it("forgets the origin and closes the tunnel of a device that stops", async () => {
577651
await run([iOSDevice]);
578652

‎test/services/ios/ios-device-tunnel-service.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -326,6 +326,20 @@ describe("IOSDeviceTunnelService", () => {
326326
assert.include(warnings[0], "fd6f:72e:8d34::2");
327327
});
328328

329+
it("tells listeners about a tunnel that closed on its own, not about a closed one", async () => {
330+
const lost: string[] = [];
331+
service.onTunnelLost((id) => lost.push(id));
332+
devicectlListings = [[coreDevice(wiredConnected)]];
333+
await service.open(iPhone());
334+
await service.close(UDID);
335+
await service.open(iPhone());
336+
337+
spawned[1].holder.emit("exit", 1, null);
338+
await new Promise((resolve) => setImmediate(resolve));
339+
340+
assert.deepEqual(lost, [UDID]);
341+
});
342+
329343
it("forgets a tunnel that closed on its own, so the next open holds a new one", async () => {
330344
devicectlListings = [[coreDevice(wiredConnected)]];
331345
await service.open(iPhone());

0 commit comments

Comments
 (0)