Skip to content

Commit 6036d95

Browse files
committed
fix(vite): reopen a dropped USB tunnel and retry a failed dev-server.json delivery
- The tunnel-lost handler is attached before the initial sync, so a tunnel that drops during the first build and sync moves the device too. - When a device's tunnel drops and the device is still eligible (physical iOS, no NS_HMR_HOST or NS_HMR_PREFER_LAN_HOST), the CLI opens a new tunnel before choosing the origin again, so a device still on USB keeps a tunnel origin instead of falling back to the LAN. At most once a minute per device, so a holder that keeps exiting can't loop. - A device whose dev-server.json delivery after an install failed gets it on its next sync, before the fast path, instead of never. - adb reverse is skipped when NS_HMR_HOST is set, since the origin doesn't use it.
1 parent 300c0f8 commit 6036d95

2 files changed

Lines changed: 163 additions & 11 deletions

File tree

‎lib/controllers/run-controller.ts‎

Lines changed: 75 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -31,9 +31,13 @@ import { injector } from "../common/yok";
3131
import { isIOSMacDevice } from "../common/mobile/ios/mac/ios-mac-constants";
3232
import { inject } from "../common/di";
3333

34+
const TUNNEL_REOPEN_INTERVAL_MS = 60_000;
35+
3436
export class RunController extends EventEmitter implements IRunController {
3537
private devServerOriginService = inject(DevServerOriginService);
3638
private iOSDeviceTunnelService = inject(IOSDeviceTunnelService);
39+
private pendingSyncAfterInstall = new Set<string>();
40+
private lastTunnelReopen: IDictionary<number> = {};
3741
private prepareReadyEventHandler: any = null;
3842
private appRestartRequestHandler: (
3943
request: IBundlerAppRestartRequest,
@@ -143,14 +147,15 @@ export class RunController extends EventEmitter implements IRunController {
143147
this.appRestartRequestHandler,
144148
);
145149
}
150+
// A tunnel can drop during the initial sync.
151+
this.attachTunnelLostHandler();
146152
await this.syncInitialDataOnDevices(
147153
projectData,
148154
liveSyncInfo,
149155
deviceDescriptorsForInitialSync,
150156
);
151157

152158
this.attachDeviceLostHandler();
153-
this.attachTunnelLostHandler();
154159
}
155160

156161
public async stop(data: IStopRunData): Promise<void> {
@@ -175,6 +180,8 @@ export class RunController extends EventEmitter implements IRunController {
175180
).map((descriptor) => descriptor.identifier);
176181

177182
for (const deviceIdentifier of removedDeviceIdentifiers) {
183+
this.pendingSyncAfterInstall.delete(deviceIdentifier);
184+
delete this.lastTunnelReopen[deviceIdentifier];
178185
this.devServerOriginService.forget(deviceIdentifier);
179186
await this.iOSDeviceTunnelService.close(deviceIdentifier);
180187
}
@@ -680,6 +687,7 @@ export class RunController extends EventEmitter implements IRunController {
680687
}
681688
const device =
682689
this.$devicesService.getDeviceByIdentifier(deviceIdentifier);
690+
await this.reopenUsbTunnel(device);
683691
const origin = await this.devServerOriginService.chooseOrigin(device);
684692
if (origin === previous) {
685693
return false;
@@ -716,6 +724,48 @@ export class RunController extends EventEmitter implements IRunController {
716724
}
717725
}
718726

727+
/**
728+
* A device still on USB gets a new tunnel, so it doesn't fall back to the
729+
* LAN. At most once a minute per device: a holder that keeps exiting
730+
* would otherwise reopen and lose the tunnel in a loop.
731+
*/
732+
private async reopenUsbTunnel(device: Mobile.IDevice): Promise<void> {
733+
if (!this.shouldUseUsbTunnel(device)) {
734+
return;
735+
}
736+
const id = device.deviceInfo.identifier;
737+
const now = Date.now();
738+
if (now - (this.lastTunnelReopen[id] ?? 0) < TUNNEL_REOPEN_INTERVAL_MS) {
739+
return;
740+
}
741+
this.lastTunnelReopen[id] = now;
742+
await this.iOSDeviceTunnelService.open(device);
743+
}
744+
745+
private shouldUseUsbTunnel(device: Mobile.IDevice): boolean {
746+
return (
747+
!this.$mobileHelper.isAndroidPlatform(device.deviceInfo.platform) &&
748+
!device.isEmulator &&
749+
!isTruthyEnvFlag(process.env.NS_HMR_PREFER_LAN_HOST) &&
750+
!process.env.NS_HMR_HOST?.trim()
751+
);
752+
}
753+
754+
/**
755+
* Delivers `dev-server.json` after an install. A device whose delivery
756+
* failed gets it on its next sync instead of the fast path.
757+
*/
758+
private async syncAfterInstall(
759+
platformLiveSyncService: IPlatformLiveSyncService,
760+
device: Mobile.IDevice,
761+
watchInfo: ILiveSyncWatchInfo,
762+
): Promise<void> {
763+
const id = device.deviceInfo.identifier;
764+
this.pendingSyncAfterInstall.add(id);
765+
await platformLiveSyncService.syncAfterInstall(device, watchInfo);
766+
this.pendingSyncAfterInstall.delete(id);
767+
}
768+
719769
private async syncInitialDataOnDevices(
720770
projectData: IProjectData,
721771
liveSyncInfo: ILiveSyncInfo,
@@ -943,7 +993,11 @@ export class RunController extends EventEmitter implements IRunController {
943993
let adbReverse = false;
944994
let port: number;
945995
if (this.$mobileHelper.isAndroidPlatform(platform)) {
946-
if (!isTruthyEnvFlag(process.env.NS_HMR_NO_ADB_REVERSE) && !preferLan) {
996+
if (
997+
!isTruthyEnvFlag(process.env.NS_HMR_NO_ADB_REVERSE) &&
998+
!preferLan &&
999+
!process.env.NS_HMR_HOST?.trim()
1000+
) {
9471001
port = await this.$viteHmrPortService.getPort(platform);
9481002
try {
9491003
adbReverse = await this.ensureAndroidReverse(
@@ -957,11 +1011,7 @@ export class RunController extends EventEmitter implements IRunController {
9571011
);
9581012
}
9591013
}
960-
} else if (
961-
!device.isEmulator &&
962-
!preferLan &&
963-
!process.env.NS_HMR_HOST?.trim()
964-
) {
1014+
} else if (this.shouldUseUsbTunnel(device)) {
9651015
await this.iOSDeviceTunnelService.open(device);
9661016
}
9671017

@@ -1220,7 +1270,11 @@ export class RunController extends EventEmitter implements IRunController {
12201270
rebuiltInformation[platformData.platformNameLowerCase]
12211271
.packageFilePath,
12221272
);
1223-
await platformLiveSyncService.syncAfterInstall(device, watchInfo);
1273+
await this.syncAfterInstall(
1274+
platformLiveSyncService,
1275+
device,
1276+
watchInfo,
1277+
);
12241278
await this.refreshApplication(
12251279
projectData,
12261280
{
@@ -1320,6 +1374,14 @@ export class RunController extends EventEmitter implements IRunController {
13201374
);
13211375
};
13221376

1377+
if (this.pendingSyncAfterInstall.has(device.deviceInfo.identifier)) {
1378+
await this.syncAfterInstall(
1379+
platformLiveSyncService,
1380+
device,
1381+
watchInfo,
1382+
);
1383+
}
1384+
13231385
if (liveSyncInfo.useHotModuleReload) {
13241386
try {
13251387
this.$logger.trace(
@@ -1346,7 +1408,11 @@ export class RunController extends EventEmitter implements IRunController {
13461408
reinstalled &&
13471409
this.usesDevServerFile(device, projectData, liveSyncInfo)
13481410
) {
1349-
await platformLiveSyncService.syncAfterInstall(device, watchInfo);
1411+
await this.syncAfterInstall(
1412+
platformLiveSyncService,
1413+
device,
1414+
watchInfo,
1415+
);
13501416
}
13511417
watchInfo.connectTimeout = null;
13521418
await watchAction();

‎test/controllers/run-controller.ts‎

Lines changed: 88 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -675,6 +675,33 @@ describe("RunController", () => {
675675
});
676676
}
677677

678+
it("delivers dev-server.json on the next sync when the delivery after a reinstall failed", async () => {
679+
await run([androidEmulator]);
680+
const deliver = injector.resolve(
681+
"androidLiveSyncService",
682+
).syncAfterInstall;
683+
let failDelivery = true;
684+
injector.resolve("androidLiveSyncService").syncAfterInstall = async (
685+
device: Mobile.IDevice,
686+
) => {
687+
await deliver(device);
688+
if (failDelivery) {
689+
throw new Error("socket closed");
690+
}
691+
};
692+
693+
await syncChange(androidEmulator);
694+
reinstalls = false;
695+
failDelivery = false;
696+
await syncChange(androidEmulator);
697+
await syncChange(androidEmulator);
698+
699+
assert.deepStrictEqual(afterInstall, [
700+
"emulator-5554",
701+
"emulator-5554",
702+
]);
703+
});
704+
678705
it("delivers nothing when nothing was reinstalled", async () => {
679706
reinstalls = false;
680707
await run([iOSSimulator]);
@@ -732,7 +759,7 @@ describe("RunController", () => {
732759
assert.deepStrictEqual(filesAtFullSync, { myiOSDevice: null });
733760
});
734761

735-
it("rewrites the file of a device whose tunnel drops and restarts only its app", async () => {
762+
it("opens a new tunnel for a device whose tunnel drops, rewrites its file and restarts only its app", async () => {
736763
await run([iOSDevice, secondIOSDevice]);
737764
restarted = [];
738765
const before = injector
@@ -742,16 +769,75 @@ describe("RunController", () => {
742769
delete tunnelAddresses.myiOSDevice;
743770
await tunnelLost("myiOSDevice");
744771

772+
assert.deepStrictEqual(openedFor, [
773+
"myiOSDevice",
774+
"mySecondiOSDevice",
775+
"myiOSDevice",
776+
]);
745777
assert.lengthOf(rewritten, 1);
746778
assert.equal(rewritten[0].device, "myiOSDevice");
747-
assert.notInclude(JSON.parse(rewritten[0].file).origin, "fd00::1");
779+
assert.equal(
780+
JSON.parse(rewritten[0].file).origin,
781+
"http://[fd00::3]:5173",
782+
);
748783
assert.deepStrictEqual(restarted, ["myiOSDevice"]);
749784
assert.equal(
750785
injector.get(DevServerOriginService).getOrigin("mySecondiOSDevice"),
751786
before,
752787
);
753788
});
754789

790+
it("moves a device to the LAN when no new tunnel comes up", async () => {
791+
await run([iOSDevice]);
792+
restarted = [];
793+
injector.get(IOSDeviceTunnelService).open = async () => null;
794+
795+
delete tunnelAddresses.myiOSDevice;
796+
await tunnelLost("myiOSDevice");
797+
798+
assert.equal(
799+
JSON.parse(rewritten[0].file).origin,
800+
`http://${lanAddress}:5173`,
801+
);
802+
assert.deepStrictEqual(restarted, ["myiOSDevice"]);
803+
});
804+
805+
it("opens at most one new tunnel a minute for a device, then uses the LAN", async () => {
806+
await run([iOSDevice]);
807+
808+
delete tunnelAddresses.myiOSDevice;
809+
await tunnelLost("myiOSDevice");
810+
delete tunnelAddresses.myiOSDevice;
811+
await tunnelLost("myiOSDevice");
812+
813+
assert.deepStrictEqual(openedFor, ["myiOSDevice", "myiOSDevice"]);
814+
assert.deepStrictEqual(
815+
rewritten.map((r) => JSON.parse(r.file).origin),
816+
["http://[fd00::2]:5173", `http://${lanAddress}:5173`],
817+
);
818+
});
819+
820+
it("acts on a tunnel lost during the initial sync", async () => {
821+
let lossDuringSync: Promise<void>;
822+
const iOSLiveSyncService = injector.resolve("iOSLiveSyncService");
823+
const fullSync = iOSLiveSyncService.fullSync;
824+
iOSLiveSyncService.fullSync = async (syncInfo: IFullSyncInfo) => {
825+
const result = await fullSync(syncInfo);
826+
injector.get(IOSDeviceTunnelService).open = async () => null;
827+
delete tunnelAddresses.myiOSDevice;
828+
lossDuringSync = tunnelLost("myiOSDevice");
829+
return result;
830+
};
831+
832+
await run([iOSDevice]);
833+
await lossDuringSync;
834+
835+
assert.equal(
836+
JSON.parse(rewritten[0].file).origin,
837+
`http://${lanAddress}:5173`,
838+
);
839+
});
840+
755841
it("leaves a device alone when its origin does not change", async () => {
756842
process.env.NS_HMR_HOST = "dev.example.test";
757843
await run([iOSDevice]);

0 commit comments

Comments
 (0)