Attach connection handler earlier

Summary:
This change attaches our event handlers as soon as the ws is created.

As a consequence, we need to wait until the server has created any necessary instances required to process incoming requests.

To achieve this, I created a type called `Lazy`.

This type wraps around a value and a promise to that value. Callers can check if the value is set. If not, callers can wait for it.

Ultimately, the value can be set outside of the promise itself.

Reviewed By: passy

Differential Revision: D37284939

fbshipit-source-id: 17dec548d7155a3d65440c9584cec07cbb826c37
This commit is contained in:
Lorenzo Blasa
2022-06-21 12:48:43 -07:00
committed by Facebook GitHub Bot
parent 40e65901bd
commit 8c67b049ab
4 changed files with 53 additions and 33 deletions

View File

@@ -42,8 +42,8 @@ const safe = (f: () => void) => {
* @param socket A ws socket on which to listen for events.
*/
export function attachSocketServer(
flipperServer: FlipperServerImpl,
socket: WebSocketServer,
server: FlipperServerImpl,
companionEnv: FlipperServerCompanionEnv,
) {
socket.on('connection', (client, req) => {
@@ -53,7 +53,6 @@ export function attachSocketServer(
'';
console.log('Client connected', clientAddress);
let connected = true;
let flipperServerCompanion: FlipperServerCompanion | undefined;
@@ -62,7 +61,7 @@ export function attachSocketServer(
if (params.get('server_companion')) {
flipperServerCompanion = new FlipperServerCompanion(
flipperServer,
server,
getLogger(),
companionEnv.pluginInitializer.initialPlugins,
);
@@ -112,7 +111,7 @@ export function attachSocketServer(
client.send(JSON.stringify(message));
}
flipperServer.onAny(onServerEvent);
server.onAny(onServerEvent);
async function onServerCompanionEvent(event: string, payload: any) {
const message = {
@@ -167,7 +166,7 @@ export function attachSocketServer(
const execRes = flipperServerCompanion?.canHandleCommand(command)
? flipperServerCompanion.exec(command, ...args)
: flipperServer.exec(command, ...args);
: server.exec(command, ...args);
execRes
.then((result: any) => {
@@ -229,7 +228,7 @@ export function attachSocketServer(
}
connected = false;
flipperServer.offAny(onServerEvent);
server.offAny(onServerEvent);
flipperServerCompanion?.destroyAll();
}