Path: blob/main/components/gitpod-protocol/src/messaging/node/connection.ts
2501 views
/*1* Copyright (C) 2017 TypeFox and others.2*3* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.4* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.05*/67import ws from "ws";8import {9IWebSocket,10Logger,11WebSocketMessageReader,12WebSocketMessageWriter,13createMessageConnection,14} from "vscode-ws-jsonrpc";15import { log } from "../../util/logging";1617export function toIWebSocket(ws: ws) {18return <IWebSocket>{19send: (content) => {20if (ws.readyState >= ws.CLOSING) {21// ws is already CLOSING/CLOSED, send() would just return an error.22return;23}2425// in general send-errors should trigger an 'error' event already, we just make sure it actually happens.26try {27ws.send(content, (err) => {28if (!err) {29return;30}31ws.emit("error", err);32});33} catch (err) {34ws.emit("error", err);35}36},37onMessage: (cb) => ws.on("message", cb),38onError: (cb) => ws.on("error", cb),39onClose: (cb) => ws.on("close", cb),40dispose: () => {41if (ws.readyState < ws.CLOSING) {42ws.close();43}44},45};46}4748// copied from /node_modules/vscode-ws-jsonrpc/lib/socket/connection.js49export function createWebSocketConnection(socket: IWebSocket, logger: Logger) {50const messageReader = new SafeWebSocketMessageReader(socket);51const messageWriter = new WebSocketMessageWriter(socket);52const connection = createMessageConnection(messageReader, messageWriter, logger);53connection.onClose(() => connection.dispose());54return connection;55}5657class SafeWebSocketMessageReader extends WebSocketMessageReader {58protected readMessage(message: any): void {59try {60super.readMessage(message);61} catch (error) {62log.debug("Failed to decode JSON-RPC message.", error);63}64}65}666768