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