Use HTTP shutdown instead

Summary: Use the newly exposed HTTP shutdown API. It is simpler.

Reviewed By: antonk52

Differential Revision: D49499264

fbshipit-source-id: 2d81db1d1a66c0b7550ee1245e51d8f1a8671aa6
This commit is contained in:
Lorenzo Blasa
2023-09-21 06:59:22 -07:00
committed by Facebook GitHub Bot
parent 6df27824b7
commit b856180530
3 changed files with 24 additions and 64 deletions

View File

@@ -20,15 +20,9 @@ import {
} from 'flipper-server-client'; } from 'flipper-server-client';
import { import {
checkPortInUse, checkPortInUse,
FlipperServerImpl,
getAuthToken, getAuthToken,
getEnvironmentInfo, getEnvironmentInfo,
getGatekeepers,
hasAuthToken, hasAuthToken,
loadLauncherSettings,
loadProcessConfig,
loadSettings,
sessionId,
setupPrefetcher, setupPrefetcher,
startFlipperServer, startFlipperServer,
startServer, startServer,
@@ -38,11 +32,9 @@ import {
getLogger, getLogger,
isTest, isTest,
Logger, Logger,
parseEnvironmentVariables,
setLoggerInstance, setLoggerInstance,
wrapRequire, wrapRequire,
} from 'flipper-common'; } from 'flipper-common';
import constants from './fb-stubs/constants';
import {initializeElectron} from './electron/initializeElectron'; import {initializeElectron} from './electron/initializeElectron';
import path from 'path'; import path from 'path';
import fs from 'fs-extra'; import fs from 'fs-extra';
@@ -106,7 +98,6 @@ async function getExternalServer(url: URL) {
} }
async function getFlipperServer( async function getFlipperServer(
logger: Logger,
electronIpcClient: ElectronIpcClientRenderer, electronIpcClient: ElectronIpcClientRenderer,
): Promise<FlipperServer> { ): Promise<FlipperServer> {
const execPath = const execPath =
@@ -114,16 +105,12 @@ async function getFlipperServer(
const appPath = await electronIpcClient.send('getPath', 'app'); const appPath = await electronIpcClient.send('getPath', 'app');
const staticPath = getStaticPath(appPath); const staticPath = getStaticPath(appPath);
const isProduction = !/node_modules[\\/]electron[\\/]/.test(execPath); const isProduction = !/node_modules[\\/]electron[\\/]/.test(execPath);
const env = process.env;
const environmentInfo = await getEnvironmentInfo( const environmentInfo = await getEnvironmentInfo(
staticPath, staticPath,
isProduction, isProduction,
false, false,
); );
const keytar: KeytarModule | undefined = await getKeytarModule(staticPath); const keytar: KeytarModule | undefined = await getKeytarModule(staticPath);
const gatekeepers = getGatekeepers(environmentInfo.os.unixname);
const settings = await loadSettings();
const port = 52342; const port = 52342;
/** /**
* Only attempt to use the auth token if one is available. Otherwise, * Only attempt to use the auth token if one is available. Otherwise,
@@ -135,22 +122,21 @@ async function getFlipperServer(
if (await hasAuthToken()) { if (await hasAuthToken()) {
token = await getAuthToken(); token = await getAuthToken();
} }
// check first with the actual TCP socket
const searchParams = new URLSearchParams(token ? {token} : {}); const searchParams = new URLSearchParams(token ? {token} : {});
const TCPconnectionURL = new URL(`ws://localhost:${port}?${searchParams}`); const TCPconnectionURL = new URL(`ws://localhost:${port}?${searchParams}`);
/** async function shutdown(): Promise<boolean> {
* Attempt to shutdown a running instance of Flipper server.
* @param url The URL used for connection.
*/
async function shutdown(url: URL) {
console.info('[flipper-server] Attempt to shutdown.'); console.info('[flipper-server] Attempt to shutdown.');
const server = await getExternalServer(url); try {
await server.exec('shutdown').catch(() => { const response = await fetch(`http://localhost:${port}/shutdown`);
/** shutdown will ultimately make this request fail, ignore error. */ const json = await response.json();
console.info('[flipper-server] Shutdown may have succeeded');
}); return json?.success;
} catch {}
return false;
} }
/** /**
@@ -162,10 +148,11 @@ async function getFlipperServer(
*/ */
if (await checkPortInUse(port)) { if (await checkPortInUse(port)) {
console.warn(`[flipper-server] TCP port ${port} is already in use.`); console.warn(`[flipper-server] TCP port ${port} is already in use.`);
await shutdown(TCPconnectionURL); const success = await shutdown();
console.info(`[flipper-server] Shutdown: ${success}`);
} }
console.info('flipper-server: not running/listening, start'); console.info('[flipper-server] Not running/listening, start');
const {readyForIncomingConnections} = await startServer({ const {readyForIncomingConnections} = await startServer({
staticPath, staticPath,
@@ -197,7 +184,6 @@ async function start() {
const electronIpcClient = new ElectronIpcClientRenderer(); const electronIpcClient = new ElectronIpcClientRenderer();
const flipperServer: FlipperServer = await getFlipperServer( const flipperServer: FlipperServer = await getFlipperServer(
logger,
electronIpcClient, electronIpcClient,
); );
const flipperServerConfig = await flipperServer.exec('get-config'); const flipperServerConfig = await flipperServer.exec('get-config');

View File

@@ -151,7 +151,7 @@ async function startHTTPServer(config: Config): Promise<{
const socket = attachWS(server, config); const socket = attachWS(server, config);
exitHook(() => { exitHook(() => {
console.log('Shutdown server'); console.log('[flipper-server] Shutdown HTTP server');
server.close(); server.close();
}); });

View File

@@ -30,12 +30,6 @@ import {isTest} from 'flipper-common';
import exitHook from 'exit-hook'; import exitHook from 'exit-hook';
import {getAuthToken} from 'flipper-server-core'; import {getAuthToken} from 'flipper-server-core';
import {findInstallation} from './findInstallation'; import {findInstallation} from './findInstallation';
import ReconnectingWebSocket from 'reconnecting-websocket';
import {
createFlipperServerWithSocket,
FlipperServerState,
} from 'flipper-server-client';
import WS from 'ws';
const argv = yargs const argv = yargs
.usage('yarn flipper-server [args]') .usage('yarn flipper-server [args]')
@@ -104,39 +98,17 @@ const rootPath = argv.bundler
: path.resolve(__dirname, '..'); // in pre packaged versions of the server, static is copied inside the package : path.resolve(__dirname, '..'); // in pre packaged versions of the server, static is copied inside the package
const staticPath = path.join(rootPath, 'static'); const staticPath = path.join(rootPath, 'static');
async function connectToRunningServer(url: URL) { async function shutdown(): Promise<boolean> {
console.info(`[flipper-server] Obtain connection to existing server.`);
const options = {
WebSocket: class WSWithUnixDomainSocketSupport extends WS {
constructor(url: string, protocols: string | string[]) {
// Flipper exports could be large, and we snd them over the wire
// Setting this limit fairly high (1GB) to allow any reasonable Flipper export to be loaded
super(url, protocols, {maxPayload: 1024 * 1024 * 1024});
}
},
};
const socket = new ReconnectingWebSocket(url.toString(), [], options);
const server = await createFlipperServerWithSocket(
socket as WebSocket,
(_state: FlipperServerState) => {},
);
return server;
}
async function shutdown() {
console.info('[flipper-server] Attempt to shutdown.'); console.info('[flipper-server] Attempt to shutdown.');
const token = await getAuthToken(); try {
const response = await fetch(`http://localhost:${argv.port}/shutdown`);
const json = await response.json();
const searchParams = new URLSearchParams(token ? {token} : {}); return json?.success;
const url = new URL(`ws://localhost:${argv.port}?${searchParams}`); } catch {}
const server = await connectToRunningServer(url); return false;
await server.exec('shutdown').catch(() => {
/** shutdown will ultimately make this request fail, ignore error. */
console.info('[flipper-server] Shutdown may have succeeded');
});
server.close();
} }
async function start() { async function start() {
@@ -193,7 +165,8 @@ async function start() {
console.info(`[flipper-server] Not replacing existing instance, exiting`); console.info(`[flipper-server] Not replacing existing instance, exiting`);
return; return;
} }
await shutdown(); const success = await shutdown();
console.info(`[flipper-server] Shutdown: ${success}`);
} }
const t3 = performance.now(); const t3 = performance.now();
@@ -238,6 +211,7 @@ async function start() {
const launchedMS = t6 - t5; const launchedMS = t6 - t5;
exitHook(async () => { exitHook(async () => {
console.log('[flipper-server] Shutdown Flipper server');
await flipperServer.close(); await flipperServer.close();
}); });