Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions lib/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,8 @@ export const FILES_CHANGE_EVENT_NAME = "filesChangeEvent";
export const INITIAL_SYNC_EVENT_NAME = "initialSyncEvent";
export const PREPARE_READY_EVENT_NAME = "prepareReadyEvent";
export const BUNDLER_COMPILATION_COMPLETE = "bundlerCompilationComplete";
/** Payload: `IBundlerAppRestartRequest`. */
export const BUNDLER_APP_RESTART_REQUESTED = "bundlerAppRestartRequested";

export class DebugCommandErrors {
public static UNABLE_TO_USE_FOR_DEVICE_AND_EMULATOR =
Expand Down
51 changes: 51 additions & 0 deletions lib/controllers/run-controller.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { HmrConstants, DeviceDiscoveryEventNames } from "../common/constants";
import {
BUNDLER_APP_RESTART_REQUESTED,
PREPARE_READY_EVENT_NAME,
TrackActionNames,
DEBUGGER_DETACHED_EVENT_NAME,
Expand Down Expand Up @@ -28,6 +29,9 @@ import { injector } from "../common/yok";

export class RunController extends EventEmitter implements IRunController {
private prepareReadyEventHandler: any = null;
private appRestartRequestHandler: (
request: IBundlerAppRestartRequest,
) => void = null;
private _syncInProgress = false;
private _pendingSyncs: Map<
string,
Expand All @@ -41,6 +45,7 @@ export class RunController extends EventEmitter implements IRunController {
constructor(
protected $analyticsService: IAnalyticsService,
private $buildController: IBuildController,
private $bundlerCompilerService: IBundlerCompilerService,
private $debugController: IDebugController,
private $deviceInstallAppService: IDeviceInstallAppService,
protected $devicesService: Mobile.IDevicesService,
Expand Down Expand Up @@ -124,6 +129,14 @@ export class RunController extends EventEmitter implements IRunController {
this.prepareReadyEventHandler,
);
}
if (!this.appRestartRequestHandler) {
this.appRestartRequestHandler = (request) =>
this.restartApplicationOnPlatform(request);
this.$bundlerCompilerService.on(
BUNDLER_APP_RESTART_REQUESTED,
this.appRestartRequestHandler,
);
}
await this.syncInitialDataOnDevices(
projectData,
liveSyncInfo,
Expand Down Expand Up @@ -198,6 +211,14 @@ export class RunController extends EventEmitter implements IRunController {
this.prepareReadyEventHandler = null;
}

if (this.appRestartRequestHandler) {
this.$bundlerCompilerService.removeListener(
BUNDLER_APP_RESTART_REQUESTED,
this.appRestartRequestHandler,
);
this.appRestartRequestHandler = null;
}

const projectData = this.$projectDataService.getProjectData(projectDir);
await this.$hooksService.executeAfterHooks("watch", {
hookArgs: {
Expand Down Expand Up @@ -346,6 +367,36 @@ export class RunController extends EventEmitter implements IRunController {
);
}

private async restartApplicationOnPlatform(
request: IBundlerAppRestartRequest,
): Promise<void> {
const { projectDir, platform, reason } = request;
const onPlatform = this.$devicesService
.getDevicesForPlatform(platform)
.map((device) => device.deviceInfo.identifier);
const deviceIdentifiers = this.$liveSyncProcessDataService
.getDeviceDescriptors(projectDir)
.map((descriptor) => descriptor.identifier)
.filter((identifier) => onPlatform.includes(identifier));

// An empty list would mean "every device" to `restartApplication`.
if (!deviceIdentifiers.length) {
this.$logger.trace(
`Ignoring the ${platform} app restart request (${reason}): no ${platform} device in the session.`,
);
return;
}

this.$logger.info(`Restarting the app on ${platform}: ${reason}`);
try {
await this.restartApplication({ projectDir, deviceIdentifiers });
} catch (err) {
this.$logger.warn(
`Unable to restart the app on ${platform}: ${err.message || err}`,
);
}
}

protected async refreshApplication(
projectData: IProjectData,
liveSyncResultInfo: ILiveSyncResultInfo,
Expand Down
90 changes: 86 additions & 4 deletions lib/services/bundler/bundler-compiler-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { performanceLog } from "../../common/decorators";
import {
WEBPACK_PLUGIN_NAME,
BUNDLER_COMPILATION_COMPLETE,
BUNDLER_APP_RESTART_REQUESTED,
PackageManagers,
CONFIG_FILE_NAME_DISPLAY,
VITE_DIST_FOLDER_NAME,
Expand Down Expand Up @@ -59,6 +60,12 @@ const debugLog = false;
/** Grace period a bundler child gets to honour SIGINT before it is killed. */
const BUNDLER_STOP_TIMEOUT_MS = 5000;

/**
* IPC message `vite serve` (`@nativescript/vite`) sends when a change can only
* be applied by restarting the app process.
*/
const VITE_APP_RESTART_MESSAGE_TYPE = "nativescript:restart";

export class BundlerCompilerService
extends EventEmitter
implements IBundlerCompilerService
Expand All @@ -68,6 +75,12 @@ export class BundlerCompilerService
// modules and HMR updates from. Keyed by platform, managed by this CLI
// so users no longer need a separate `concurrently`/`wait-on` process.
private viteServeProcesses: IDictionary<child_process.ChildProcess> = {};
private pendingAppRestarts: IDictionary<{
reasons: string[];
timer: NodeJS.Timeout;
}> = {};
/** Restart requests within this window collapse into one restart. */
private appRestartDebounceMs = 300;
private expectedHashes: IStringDictionary = {};

constructor(
Expand Down Expand Up @@ -736,10 +749,10 @@ export class BundlerCompilerService

const options: { [key: string]: any } = {
cwd: projectData.projectDir,
// Inherit so the dev server's URLs/logs stream to the user as
// before. No IPC needed here — the build watcher provides the
// bundle-complete IPC; the dev server is fetched over HTTP/ws.
stdio: "inherit",
// Logs stream straight to the user. The IPC channel only carries
// app-restart requests; a server that never sends one behaves as
// with plain "inherit".
stdio: ["inherit", "inherit", "inherit", "ipc"],
env: {
...process.env,
NATIVESCRIPT_BUNDLER_ENV: JSON.stringify(envData),
Expand All @@ -762,9 +775,14 @@ export class BundlerCompilerService
this.viteServeProcesses[key] = childProcess;
await this.$cleanupService.addKillProcess(childProcess.pid.toString());

childProcess.on("message", (message: unknown) =>
this.handleViteServeMessage(message, key, projectData.projectDir),
);

childProcess.once("exit", (code: number) => {
if (this.viteServeProcesses[key] === childProcess) {
delete this.viteServeProcesses[key];
this.cancelAppRestart(key);
}
if (code) {
this.$logger.warn(
Expand Down Expand Up @@ -796,6 +814,68 @@ export class BundlerCompilerService
}
}

/**
* Unknown message shapes are ignored without a log, so a newer
* `@nativescript/vite` can add message types without breaking this CLI.
*/
private handleViteServeMessage(
message: unknown,
platform: string,
projectDir: string,
): void {
if (
!message ||
typeof message !== "object" ||
(message as { type?: unknown }).type !== VITE_APP_RESTART_MESSAGE_TYPE
) {
return;
}

const { reason } = message as { reason?: unknown };
this.requestAppRestart(
platform,
projectDir,
typeof reason === "string" && reason
? reason
: "the Vite dev server requested it",
);
}

private requestAppRestart(
platform: string,
projectDir: string,
reason: string,
): void {
const pending = this.pendingAppRestarts[platform] || {
reasons: [],
timer: null,
};
if (!pending.reasons.includes(reason)) {
pending.reasons.push(reason);
}
clearTimeout(pending.timer);
pending.timer = setTimeout(() => {
delete this.pendingAppRestarts[platform];
const request: IBundlerAppRestartRequest = {
projectDir,
platform,
reason: pending.reasons.join("; "),
};
this.emit(BUNDLER_APP_RESTART_REQUESTED, request);
}, this.appRestartDebounceMs);
// A pending timer must not be what keeps the CLI alive.
pending.timer.unref?.();
this.pendingAppRestarts[platform] = pending;
}

private cancelAppRestart(platform: string): void {
const pending = this.pendingAppRestarts[platform];
if (pending) {
clearTimeout(pending.timer);
delete this.pendingAppRestarts[platform];
}
}

/**
* Resolve true once `127.0.0.1:<port>` accepts a TCP connection, or
* false after `timeoutMs`. Used to detect the Vite dev server is up.
Expand Down Expand Up @@ -1034,6 +1114,8 @@ export class BundlerCompilerService
// Tear down the Vite dev server we manage alongside the build watcher.
const viteServeProcess = this.viteServeProcesses[platform];
if (viteServeProcess) {
viteServeProcess.removeAllListeners("message");
this.cancelAppRestart(platform);
await this.terminate(viteServeProcess);
if (this.viteServeProcesses[platform] === viteServeProcess) {
delete this.viteServeProcesses[platform];
Expand Down
12 changes: 12 additions & 0 deletions lib/services/bundler/bundler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,18 @@ declare global {
stopBundlerCompiler(platform: string): Promise<void>;
}

/**
* The bundler's dev server asked for the app process to be restarted,
* because a change cannot be applied as a hot update.
*/
interface IBundlerAppRestartRequest {
projectDir: string;
/** Lowercase platform name. */
platform: string;
/** Human-readable; may combine several requests. */
reason: string;
}

interface IBundlerEnvOptions {
sourceMap?: boolean;
uglify?: boolean;
Expand Down
97 changes: 96 additions & 1 deletion test/controllers/run-controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,11 @@ import { LiveSyncServiceResolver } from "../../lib/resolvers/livesync-service-re
import { MobileHelper } from "../../lib/common/mobile/mobile-helper";
import { assert } from "chai";
import * as _ from "lodash";
import { RunOnDeviceEvents } from "../../lib/constants";
import { EventEmitter } from "events";
import {
BUNDLER_APP_RESTART_REQUESTED,
RunOnDeviceEvents,
} from "../../lib/constants";
import { PrepareData } from "../../lib/data/prepare-data";
import { PrepareDataService } from "../../lib/services/prepare-data-service";
import { BuildDataService } from "../../lib/services/build-data-service";
Expand Down Expand Up @@ -124,6 +128,7 @@ function createTestInjector() {
});
injector.register("prepareNativePlatformService", {});
injector.register("projectChangesService", {});
injector.register("bundlerCompilerService", new EventEmitter());
injector.register("runController", RunController);
injector.register("prepareDataService", PrepareDataService);
injector.register("buildDataService", BuildDataService);
Expand Down Expand Up @@ -423,6 +428,96 @@ describe("RunController", () => {
{ device: "myiOSDevice", isFullSync: false },
]);
});

describe("requested by the bundler", () => {
let bundlerCompilerService: EventEmitter = null;

beforeEach(async () => {
bundlerCompilerService = injector.resolve("bundlerCompilerService");
mockDevicesService(injector, []);
await runController.run({ liveSyncInfo, deviceDescriptors: [] });

startSession(
[iOSDeviceDescriptor, androidDeviceDescriptor],
[iOSDevice, androidDevice],
);
injector.resolve("devicesService").getDevicesForPlatform = (
platform: string,
) =>
[iOSDevice, androidDevice].filter(
(device) => device.deviceInfo.platform === platform,
);
infoMessages = [];
});

async function requestRestart(platform: string, reason: string) {
bundlerCompilerService.emit(BUNDLER_APP_RESTART_REQUESTED, {
projectDir,
platform,
reason,
});
await injector
.resolve("liveSyncProcessDataService")
.getPersistedData(projectDir).actionsChain;
}

it("restarts the app only on the session's devices of that platform", async () => {
await requestRestart("android", "vite.config.ts changed");

assert.deepStrictEqual(restartedApps, [
{ device: "myAndroidDevice", isFullSync: false },
]);
assert.deepStrictEqual(infoMessages, [
"Restarting the app on android: vite.config.ts changed",
]);
});

it("restarts nothing when the session has no device of that platform", async () => {
const persisted = injector
.resolve("liveSyncProcessDataService")
.getPersistedData(projectDir);
_.remove(
persisted.deviceDescriptors,
(descriptor: ILiveSyncDeviceDescriptor) =>
descriptor.identifier === "myAndroidDevice",
);

await requestRestart("android", "vite.config.ts changed");

assert.lengthOf(restartedApps, 0);
assert.lengthOf(infoMessages, 0);
});

it("waits for the action already running on the session", async () => {
const persisted = injector
.resolve("liveSyncProcessDataService")
.getPersistedData(projectDir);
let release: () => void;
persisted.actionsChain = new Promise<void>((resolve) => {
release = resolve;
});

const restarting = requestRestart("ios", "app.ts changed");
await new Promise((resolve) => setImmediate(resolve));
assert.lengthOf(restartedApps, 0);

release();
await restarting;

assert.deepStrictEqual(restartedApps, [
{ device: "myiOSDevice", isFullSync: false },
]);
});

it("stops listening once the session stops", async () => {
await runController.stop({ projectDir });

assert.strictEqual(
bundlerCompilerService.listenerCount(BUNDLER_APP_RESTART_REQUESTED),
0,
);
});
});
});

describe("stopRunOnDevices", () => {
Expand Down
Loading
Loading