Summary: Standardize WS implementation for JS environments. Why do we need a separate server implementation for browsers? Browser targets cannot authenticate via the default certificate exchange flow. For browser targets we verify the origin instead. Moreover, for already forgotten reasons the initial implementation of the WS server for browsers used a different kind of message structure and added extra `connect`/`disconnect` messages. After examination, it seems the `connect`/`disconnect` flow is redundant. Major changes: 1. Updated class hierarchy for WS server implementations. 2. Updated browser WS server to support the modern and the legacy protocols. 3. Now a websocket connection with the device is closed on error. The idea is it is highly unlikely to handle any subsequent messages properly once we observe an error. It is better to bail and reconnect. What do you think? Reviewed By: mweststrate Differential Revision: D31532172 fbshipit-source-id: f86aa63a40efe4d5263353cc124fac8c63b80e45
55 lines
1.6 KiB
TypeScript
55 lines
1.6 KiB
TypeScript
/**
|
|
* Copyright (c) Facebook, Inc. and its affiliates.
|
|
*
|
|
* This source code is licensed under the MIT license found in the
|
|
* LICENSE file in the root directory of this source tree.
|
|
*
|
|
* @format
|
|
*/
|
|
|
|
import {ClientResponseType} from 'flipper-common';
|
|
import WebSocket from 'ws';
|
|
import {WSCloseCode} from '../utils/WSCloseCode';
|
|
import {
|
|
ClientConnection,
|
|
ConnectionStatus,
|
|
ConnectionStatusChange,
|
|
PendingRequestResolvers,
|
|
} from './ClientConnection';
|
|
|
|
export default class WebSocketClientConnection implements ClientConnection {
|
|
protected pendingRequests: Map<number, PendingRequestResolvers> = new Map();
|
|
constructor(protected ws: WebSocket) {}
|
|
subscribeToEvents(subscriber: ConnectionStatusChange): void {
|
|
this.ws.on('close', () => subscriber(ConnectionStatus.CLOSED));
|
|
this.ws.on('error', () => subscriber(ConnectionStatus.ERROR));
|
|
}
|
|
close(): void {
|
|
this.ws.close(WSCloseCode.NormalClosure);
|
|
}
|
|
send(data: any): void {
|
|
this.ws.send(this.serializeData(data));
|
|
}
|
|
sendExpectResponse(data: any): Promise<ClientResponseType> {
|
|
return new Promise((resolve, reject) => {
|
|
this.pendingRequests.set(data.id, {reject, resolve});
|
|
this.ws.send(this.serializeData(data));
|
|
});
|
|
}
|
|
|
|
matchPendingRequest(id: number): PendingRequestResolvers {
|
|
const callbacks = this.pendingRequests.get(id);
|
|
|
|
if (!callbacks) {
|
|
throw new Error(`Pending request ${id} is not found`);
|
|
}
|
|
|
|
this.pendingRequests.delete(id);
|
|
return callbacks;
|
|
}
|
|
|
|
protected serializeData(data: object): string {
|
|
return JSON.stringify(data);
|
|
}
|
|
}
|