Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

dev-admin support webpack dev server randomly select available port #1842

Merged
merged 5 commits into from
Mar 19, 2021
Merged
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
44 changes: 32 additions & 12 deletions packages/xarc-app-dev/src/lib/dev-admin/admin-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ const getTerminalColumns = () => {
);
};

type ProcessPorts = { webpackDevPort?: number; appPort?: number };
export class AdminServer {
_opts: any;
_passThru: any;
Expand All @@ -78,7 +79,8 @@ export class AdminServer {
_wds: any;
_proxy: any;
_app: any;
_appPort: number;
_ports: ProcessPorts;
_updateProxyTimer: any;
_appLogLevel: any;
_menu: any;
_fullyStarted: any;
Expand Down Expand Up @@ -106,6 +108,8 @@ export class AdminServer {
return autoIo ? new AutomationIO("Dev Admin") : new ConsoleIO();
};

this._ports = { appPort: devProxy.appPort };

this._io = (options && options.inputOutput) || defaultIo();

this._shutdown = false;
Expand Down Expand Up @@ -137,8 +141,6 @@ export class AdminServer {
this._shutdown || (await this.startWebpackDevServer());
this._shutdown || (await this.startAppServer());

this._appPort = devProxy.appPort;

if (!this._shutdown && DEV_PROXY_ENABLED) {
// to debug dev proxy
// await this.startProxyServer("--inspect-brk");
Expand Down Expand Up @@ -509,6 +511,10 @@ ${proxyItem}<magenta>M</> - Show this menu <magenta>Q</> - Shutdown
const listenForReport = () =>
info._child.once("message", data => {
if (data.name === "webpack-report") {
if (data.port) {
SERVER_ENVS[PROXY_SERVER_NAME].WEBPACK_DEV_PORT = data.port;
this.updateProxyServer({ webpackDevPort: parseInt(data.port, 10) });
}
resolve(null);
} else {
listenForReport();
Expand Down Expand Up @@ -770,12 +776,11 @@ ${instruction}`
waitStart: async info => {
info._child.on("message", (data: any) => {
// this._io.show(ck`<orange>proxy message ${JSON.stringify(data)}</>`, this._appPort);
if (data.name === "proxy-started" && `${data.appPort}` !== `${this._appPort}`) {
this.sendMsg(PROXY_SERVER_NAME, {
appPort: this._appPort,
name: "restart",
quiet: true
});
if (data.name === "proxy-started") {
const proxyPorts = { appPort: parseInt(data.appPort, 10) };
if (proxyPorts.appPort !== this._ports.appPort) {
this.updateProxyServer({}, true);
}
}
});
this.passThruLineOutput(this._proxy, info._child.stdout, this._io);
Expand All @@ -784,6 +789,22 @@ ${instruction}`
});
}

updateProxyServer(newPorts: ProcessPorts, force = false) {
const update: ProcessPorts = { ...this._ports, ...newPorts };
if (!_.isEqual(update, this._ports) || force) {
this._ports = update;
clearTimeout(this._updateProxyTimer);
this._updateProxyTimer = setTimeout(() => {
this._updateProxyTimer = null;
this.sendMsg(PROXY_SERVER_NAME, {
...update,
name: "restart",
quiet: true
});
}, 250).unref();
}
}

async waitForAppServerStart(info) {
let startTimeout;
let started = false;
Expand Down Expand Up @@ -829,8 +850,7 @@ ${info.name} - assuming it started.</>`);
if (DEV_PROXY_ENABLED) {
if (data.appPort) {
SERVER_ENVS[PROXY_SERVER_NAME].APP_SERVER_PORT = data.appPort;
this._appPort = data.appPort;
this.sendMsg(PROXY_SERVER_NAME, { ...data, name: "restart" });
this.updateProxyServer({ appPort: parseInt(data.appPort, 10) });
}
}
}
Expand All @@ -843,7 +863,6 @@ ${info.name} - assuming it started.</>`);

if (info._child) {
info._child.removeListener("message", messageHandler);
info._child.on("message", appUpdateHandler);
}
this.watchServer(info.name);
defer.resolve();
Expand All @@ -862,6 +881,7 @@ ${info.name} - assuming it started.</>`);
});

info._child.on("message", messageHandler);
info._child.on("message", appUpdateHandler);

if (info.options.noTimeoutCheck !== true) {
startTimeout = setTimeout(handleTimeout, 20000);
Expand Down
31 changes: 19 additions & 12 deletions packages/xarc-app-dev/src/lib/dev-admin/dev-http.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
/* eslint-disable @typescript-eslint/no-var-requires */
/* eslint-disable no-console */
/* eslint-disable no-console, max-statements */

import { createReadStream } from "fs";
import { Readable } from "stream";
Expand All @@ -9,6 +8,7 @@ import Url from "url";
import { resolve as pathResolve } from "path";
import { FakeRes } from "../fake-res";
import { Middleware } from "./middleware";
import { makeDefer } from "xaa";

export interface DevHttpServerOptions {
port: number;
Expand All @@ -24,6 +24,7 @@ export interface DevHttpServer {
stop: () => void;
httpServer?: Server;
addListener: (event: HttpServerEvent, hander: any) => void;
getPort: () => number;
}

/**
Expand Down Expand Up @@ -53,18 +54,16 @@ export const setupHttpDevServer = function({
host,
protocol = "http"
}: DevHttpServerOptions): DevHttpServer {
const createMiddleware = new Promise(resolve => {
setTimeout(() => {
resolve(getMiddleware({ port, host, protocol }));
}, 1);
});

let createMiddlewarePromise;
let middleware;
let listenDefer = makeDefer();

const server: Server = createServer(async (req, res) => {
try {
if (!middleware) {
middleware = await createMiddleware;
await listenDefer;
middleware = await createMiddlewarePromise;
listenDefer = createMiddlewarePromise = null;
}
const next1 = await middleware.process(req, res, {
skip: () => middleware.canContinue,
Expand Down Expand Up @@ -104,8 +103,13 @@ export const setupHttpDevServer = function({
});

return {
start: () => {
server.listen(port, host);
start() {
server.listen(port, host, () => {
createMiddlewarePromise = new Promise(resolve => {
resolve(getMiddleware({ port: this.getPort(), host, protocol }));
});
listenDefer.resolve();
});
},
stop: () => {
server.close(() => {
Expand All @@ -116,7 +120,10 @@ export const setupHttpDevServer = function({
addListener: (event: HttpServerEvent, cb) => {
server.addListener(event.toString(), cb);
},
httpServer: server
httpServer: server,
getPort: () => {
return server && (server.address() as any).port;
}
};
};
export const setup = setupHttpDevServer;
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,11 @@ function createDevAdminHttpServer(xarcOptions) {
});

devHttpServer.addListener("listening", () => {
console.log(ck`<green>webpack dev server listening on port ${xarcOptions.webpack.devPort}</>`);
const port = devHttpServer.getPort();
console.log(ck`<green>webpack dev server listening on port ${port}</>`);
process.send({
name: "webpack-report",
port,
valid: false
});
});
Expand Down
2 changes: 2 additions & 0 deletions packages/xarc-app-dev/src/lib/dev-admin/redbird-proxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ ${APP_RULES.map(
};

let regAppPort = 0;
let regWebpackDevPort = 0;

const registerElectrodeDevRules = ({
proxy,
Expand All @@ -130,6 +131,7 @@ const registerElectrodeDevRules = ({
const logStreamsPath = `${devPath}/stream-logs`;
const appForwards: any[] = [[{}, { port: appPort }]];
regAppPort = appPort;
regWebpackDevPort = webpackDevPort;

if (!noDev) {
appForwards.push(
Expand Down
2 changes: 1 addition & 1 deletion packages/xarc-app-dev/src/lib/dev-admin/redbird-spawn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ const isProxyRunning = async () => {
const handleRestart = type => {
const restart = (options: any = {}) => {
if (!options.quiet) {
console.log(`${type}Electrode dev proxy restarting`);
console.log(`${type}Electrode dev proxy restarting`, options);
}
const restartUrl = formUrl({
...httpDevServer,
Expand Down
13 changes: 5 additions & 8 deletions packages/xarc-app-dev/src/lib/dev-tasks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -811,14 +811,11 @@ module.exports = {
- NODE_ENV is set to 'production' if it's not set.
- options: [all options will be passed to node when starting your app server]`,
task(context) {
userXrun.updateEnv(
{
NODE_ENV: "production"
},
{
override: false
}
);
userXrun.updateEnv({ NODE_ENV: "production" }, { override: false });
if (process.env.APP_SERVER_PORT === "0") {
console.log("mock-cloud need to explicitly set APP_SERVER_PORT, changing 0 to 3100");
process.env.APP_SERVER_PORT = "3100";
}

const mockTask = xrun2.concurrent([
"dev-proxy --mock-cdn --no-dev",
Expand Down
Loading