Skip to content

Commit

Permalink
Use HTTP shutdown instead
Browse files Browse the repository at this point in the history
Summary: Use the newly exposed HTTP shutdown API. It is simpler.

Reviewed By: antonk52

Differential Revision: D49499264

fbshipit-source-id: 2d81db1d1a66c0b7550ee1245e51d8f1a8671aa6
  • Loading branch information
lblasa authored and facebook-github-bot committed Sep 21, 2023
1 parent 6df2782 commit b856180
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 64 deletions.
40 changes: 13 additions & 27 deletions desktop/app/src/init.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,15 +20,9 @@ import {
} from 'flipper-server-client';
import {
checkPortInUse,
FlipperServerImpl,
getAuthToken,
getEnvironmentInfo,
getGatekeepers,
hasAuthToken,
loadLauncherSettings,
loadProcessConfig,
loadSettings,
sessionId,
setupPrefetcher,
startFlipperServer,
startServer,
Expand All @@ -38,11 +32,9 @@ import {
getLogger,
isTest,
Logger,
parseEnvironmentVariables,
setLoggerInstance,
wrapRequire,
} from 'flipper-common';
import constants from './fb-stubs/constants';
import {initializeElectron} from './electron/initializeElectron';
import path from 'path';
import fs from 'fs-extra';
Expand Down Expand Up @@ -106,24 +98,19 @@ async function getExternalServer(url: URL) {
}

async function getFlipperServer(
logger: Logger,
electronIpcClient: ElectronIpcClientRenderer,
): Promise<FlipperServer> {
const execPath =
process.execPath || (await electronIpcClient.send('getProcess')).execPath;
const appPath = await electronIpcClient.send('getPath', 'app');
const staticPath = getStaticPath(appPath);
const isProduction = !/node_modules[\\/]electron[\\/]/.test(execPath);
const env = process.env;
const environmentInfo = await getEnvironmentInfo(
staticPath,
isProduction,
false,
);
const keytar: KeytarModule | undefined = await getKeytarModule(staticPath);
const gatekeepers = getGatekeepers(environmentInfo.os.unixname);

const settings = await loadSettings();
const port = 52342;
/**
* Only attempt to use the auth token if one is available. Otherwise,
Expand All @@ -135,22 +122,21 @@ async function getFlipperServer(
if (await hasAuthToken()) {
token = await getAuthToken();
}
// check first with the actual TCP socket

const searchParams = new URLSearchParams(token ? {token} : {});
const TCPconnectionURL = new URL(`ws://localhost:${port}?${searchParams}`);

/**
* Attempt to shutdown a running instance of Flipper server.
* @param url The URL used for connection.
*/
async function shutdown(url: URL) {
async function shutdown(): Promise<boolean> {
console.info('[flipper-server] Attempt to shutdown.');

const server = await getExternalServer(url);
await server.exec('shutdown').catch(() => {
/** shutdown will ultimately make this request fail, ignore error. */
console.info('[flipper-server] Shutdown may have succeeded');
});
try {
const response = await fetch(`http://localhost:${port}/shutdown`);
const json = await response.json();

return json?.success;
} catch {}

return false;
}

/**
Expand All @@ -162,10 +148,11 @@ async function getFlipperServer(
*/
if (await checkPortInUse(port)) {
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({
staticPath,
Expand Down Expand Up @@ -197,7 +184,6 @@ async function start() {
const electronIpcClient = new ElectronIpcClientRenderer();

const flipperServer: FlipperServer = await getFlipperServer(
logger,
electronIpcClient,
);
const flipperServerConfig = await flipperServer.exec('get-config');
Expand Down
2 changes: 1 addition & 1 deletion desktop/flipper-server-core/src/server/startServer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ async function startHTTPServer(config: Config): Promise<{
const socket = attachWS(server, config);

exitHook(() => {
console.log('Shutdown server');
console.log('[flipper-server] Shutdown HTTP server');
server.close();
});

Expand Down
46 changes: 10 additions & 36 deletions desktop/flipper-server/src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,6 @@ import {isTest} from 'flipper-common';
import exitHook from 'exit-hook';
import {getAuthToken} from 'flipper-server-core';
import {findInstallation} from './findInstallation';
import ReconnectingWebSocket from 'reconnecting-websocket';
import {
createFlipperServerWithSocket,
FlipperServerState,
} from 'flipper-server-client';
import WS from 'ws';

const argv = yargs
.usage('yarn flipper-server [args]')
Expand Down Expand Up @@ -104,39 +98,17 @@ const rootPath = argv.bundler
: path.resolve(__dirname, '..'); // in pre packaged versions of the server, static is copied inside the package
const staticPath = path.join(rootPath, 'static');

async function connectToRunningServer(url: URL) {
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() {
async function shutdown(): Promise<boolean> {
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} : {});
const url = new URL(`ws://localhost:${argv.port}?${searchParams}`);
return json?.success;
} catch {}

const server = await connectToRunningServer(url);
await server.exec('shutdown').catch(() => {
/** shutdown will ultimately make this request fail, ignore error. */
console.info('[flipper-server] Shutdown may have succeeded');
});
server.close();
return false;
}

async function start() {
Expand Down Expand Up @@ -193,7 +165,8 @@ async function start() {
console.info(`[flipper-server] Not replacing existing instance, exiting`);
return;
}
await shutdown();
const success = await shutdown();
console.info(`[flipper-server] Shutdown: ${success}`);
}

const t3 = performance.now();
Expand Down Expand Up @@ -238,6 +211,7 @@ async function start() {
const launchedMS = t6 - t5;

exitHook(async () => {
console.log('[flipper-server] Shutdown Flipper server');
await flipperServer.close();
});

Expand Down

0 comments on commit b856180

Please sign in to comment.