@grest-ts/ipc 0.0.5 → 0.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,146 +1,146 @@
1
- import * as http from 'http';
2
- import {WebSocket, WebSocketServer} from 'ws';
3
- import {GGLog} from "@grest-ts/logger";
4
- import {Duplex} from "stream";
5
- import {IPCSocket} from "../common/IPCSocket";
6
- import httpProxy from "http-proxy";
7
-
8
- export const INTERNAL_SOCKET_PATH = '/__ggFrameworkConnection';
9
-
10
- export type WsUpgradeHandler = (req: http.IncomingMessage, socket: Duplex, head: Buffer) => Promise<boolean>;
11
- export type SocketMessageHandler = (msg: SocketMessage) => Promise<unknown>;
12
-
13
- export interface SocketMessage {
14
- clientId: string;
15
- runtimeId?: string;
16
- data: unknown;
17
- }
18
-
19
- interface SocketClient {
20
- id: string;
21
- runtimeId?: string;
22
- socket: IPCSocket;
23
- }
24
-
25
- export class SocketHandler {
26
-
27
- private readonly wss: WebSocketServer;
28
- private readonly clients: Map<string, SocketClient> = new Map();
29
- private readonly clientsByRuntimeId: Map<string, SocketClient> = new Map();
30
- private readonly handlers: Map<string, SocketMessageHandler> = new Map();
31
- private clientIdCounter = 0;
32
-
33
- private routeResolver: (path: string) => string
34
- private readonly proxy: httpProxy;
35
-
36
- constructor() {
37
- this.wss = new WebSocketServer({noServer: true});
38
- this.proxy = httpProxy.createProxyServer({});
39
- }
40
-
41
- public setRouteResolver(routeResolver: (path: string) => string) {
42
- this.routeResolver = routeResolver
43
- }
44
-
45
- public onMessage(path: string, handler: SocketMessageHandler): void {
46
- this.handlers.set(path, handler);
47
- }
48
-
49
- public async handleUpgrade(req: http.IncomingMessage, socket: Duplex, head: Buffer): Promise<void> {
50
- if (req.url.startsWith(INTERNAL_SOCKET_PATH)) {
51
- this.wss.handleUpgrade(req, socket, head, (ws) => {
52
- this.handleNewConnection(ws, req.url);
53
- });
54
- return;
55
- }
56
-
57
- const routeToUrl = this.routeResolver(req.url)
58
- if (routeToUrl) {
59
- GGLog.debug(this, `Proxying WS ${req.url} -> ${routeToUrl}`);
60
- this.proxy.ws(req, socket, head, {target: routeToUrl}, (err: Error) => {
61
- GGLog.error(this, `WebSocket proxy error: ${err.message}`);
62
- socket.destroy();
63
- });
64
- return;
65
- }
66
-
67
- socket.destroy();
68
- }
69
-
70
- private handleNewConnection(ws: WebSocket, url: string): void {
71
- const clientId = `client-${++this.clientIdCounter}`;
72
-
73
- let runtimeId: string | undefined;
74
- const queryStart = url.indexOf('?');
75
- if (queryStart !== -1) {
76
- const params = new URLSearchParams(url.substring(queryStart + 1));
77
- runtimeId = params.get('runtimeId') ?? undefined;
78
- }
79
-
80
- const ipcSocket = new IPCSocket(ws);
81
-
82
- const client: SocketClient = {id: clientId, runtimeId, socket: ipcSocket};
83
- this.clients.set(clientId, client);
84
- if (runtimeId) {
85
- this.clientsByRuntimeId.set(runtimeId, client);
86
- }
87
-
88
- GGLog.debug(this, `Socket client connected: ${clientId}` + (runtimeId ? ` (runtimeId: ${runtimeId})` : ''));
89
-
90
- for (const [path, handler] of this.handlers) {
91
- ipcSocket.onRequest(path, async (data) => {
92
- return handler({
93
- clientId: client.id,
94
- runtimeId: client.runtimeId,
95
- data
96
- });
97
- });
98
- }
99
-
100
- ipcSocket.onClose(() => {
101
- this.clients.delete(clientId);
102
- if (runtimeId) {
103
- this.clientsByRuntimeId.delete(runtimeId);
104
- }
105
- GGLog.debug(this, `Socket client disconnected: ${clientId}`);
106
- });
107
-
108
- ipcSocket.onError((err: Error) => {
109
- GGLog.debug(this, `Socket client error: ${clientId} - ${err.message}`);
110
- });
111
- }
112
-
113
- public async request<T = unknown>(
114
- runtimeId: string,
115
- path: string,
116
- data?: unknown,
117
- timeoutMs: number = 10000
118
- ): Promise<T> {
119
- const client = this.clientsByRuntimeId.get(runtimeId);
120
- if (!client) {
121
- throw new Error(`No client connected with runtimeId: ${runtimeId}`);
122
- }
123
- return client.socket.request<T>(path, data, timeoutMs);
124
- }
125
-
126
- public send(runtimeId: string, path: string, data?: unknown): void {
127
- const client = this.clientsByRuntimeId.get(runtimeId);
128
- if (!client) {
129
- throw new Error(`No client connected with runtimeId: ${runtimeId}`);
130
- }
131
- client.socket.send(path, data);
132
- }
133
-
134
- public async teardown(): Promise<void> {
135
- for (const client of this.clients.values()) {
136
- client.socket.teardown();
137
- }
138
- this.clients.clear();
139
- this.clientsByRuntimeId.clear();
140
- this.proxy.close();
141
-
142
- await new Promise<void>((resolve) => {
143
- this.wss.close(() => resolve());
144
- });
145
- }
146
- }
1
+ import * as http from 'http';
2
+ import {WebSocket, WebSocketServer} from 'ws';
3
+ import {GGLog} from "@grest-ts/logger";
4
+ import {Duplex} from "stream";
5
+ import {IPCSocket} from "../common/IPCSocket";
6
+ import httpProxy from "http-proxy";
7
+
8
+ export const INTERNAL_SOCKET_PATH = '/__ggFrameworkConnection';
9
+
10
+ export type WsUpgradeHandler = (req: http.IncomingMessage, socket: Duplex, head: Buffer) => Promise<boolean>;
11
+ export type SocketMessageHandler = (msg: SocketMessage) => Promise<unknown>;
12
+
13
+ export interface SocketMessage {
14
+ clientId: string;
15
+ runtimeId?: string;
16
+ data: unknown;
17
+ }
18
+
19
+ interface SocketClient {
20
+ id: string;
21
+ runtimeId?: string;
22
+ socket: IPCSocket;
23
+ }
24
+
25
+ export class SocketHandler {
26
+
27
+ private readonly wss: WebSocketServer;
28
+ private readonly clients: Map<string, SocketClient> = new Map();
29
+ private readonly clientsByRuntimeId: Map<string, SocketClient> = new Map();
30
+ private readonly handlers: Map<string, SocketMessageHandler> = new Map();
31
+ private clientIdCounter = 0;
32
+
33
+ private routeResolver: (path: string) => string
34
+ private readonly proxy: httpProxy;
35
+
36
+ constructor() {
37
+ this.wss = new WebSocketServer({noServer: true});
38
+ this.proxy = httpProxy.createProxyServer({});
39
+ }
40
+
41
+ public setRouteResolver(routeResolver: (path: string) => string) {
42
+ this.routeResolver = routeResolver
43
+ }
44
+
45
+ public onMessage(path: string, handler: SocketMessageHandler): void {
46
+ this.handlers.set(path, handler);
47
+ }
48
+
49
+ public async handleUpgrade(req: http.IncomingMessage, socket: Duplex, head: Buffer): Promise<void> {
50
+ if (req.url.startsWith(INTERNAL_SOCKET_PATH)) {
51
+ this.wss.handleUpgrade(req, socket, head, (ws) => {
52
+ this.handleNewConnection(ws, req.url);
53
+ });
54
+ return;
55
+ }
56
+
57
+ const routeToUrl = this.routeResolver(req.url)
58
+ if (routeToUrl) {
59
+ GGLog.debug(this, `Proxying WS ${req.url} -> ${routeToUrl}`);
60
+ this.proxy.ws(req, socket, head, {target: routeToUrl}, (err: Error) => {
61
+ GGLog.error(this, `WebSocket proxy error: ${err.message}`);
62
+ socket.destroy();
63
+ });
64
+ return;
65
+ }
66
+
67
+ socket.destroy();
68
+ }
69
+
70
+ private handleNewConnection(ws: WebSocket, url: string): void {
71
+ const clientId = `client-${++this.clientIdCounter}`;
72
+
73
+ let runtimeId: string | undefined;
74
+ const queryStart = url.indexOf('?');
75
+ if (queryStart !== -1) {
76
+ const params = new URLSearchParams(url.substring(queryStart + 1));
77
+ runtimeId = params.get('runtimeId') ?? undefined;
78
+ }
79
+
80
+ const ipcSocket = new IPCSocket(ws);
81
+
82
+ const client: SocketClient = {id: clientId, runtimeId, socket: ipcSocket};
83
+ this.clients.set(clientId, client);
84
+ if (runtimeId) {
85
+ this.clientsByRuntimeId.set(runtimeId, client);
86
+ }
87
+
88
+ GGLog.debug(this, `Socket client connected: ${clientId}` + (runtimeId ? ` (runtimeId: ${runtimeId})` : ''));
89
+
90
+ for (const [path, handler] of this.handlers) {
91
+ ipcSocket.onRequest(path, async (data) => {
92
+ return handler({
93
+ clientId: client.id,
94
+ runtimeId: client.runtimeId,
95
+ data
96
+ });
97
+ });
98
+ }
99
+
100
+ ipcSocket.onClose(() => {
101
+ this.clients.delete(clientId);
102
+ if (runtimeId) {
103
+ this.clientsByRuntimeId.delete(runtimeId);
104
+ }
105
+ GGLog.debug(this, `Socket client disconnected: ${clientId}`);
106
+ });
107
+
108
+ ipcSocket.onError((err: Error) => {
109
+ GGLog.debug(this, `Socket client error: ${clientId} - ${err.message}`);
110
+ });
111
+ }
112
+
113
+ public async request<T = unknown>(
114
+ runtimeId: string,
115
+ path: string,
116
+ data?: unknown,
117
+ timeoutMs: number = 10000
118
+ ): Promise<T> {
119
+ const client = this.clientsByRuntimeId.get(runtimeId);
120
+ if (!client) {
121
+ throw new Error(`No client connected with runtimeId: ${runtimeId}`);
122
+ }
123
+ return client.socket.request<T>(path, data, timeoutMs);
124
+ }
125
+
126
+ public send(runtimeId: string, path: string, data?: unknown): void {
127
+ const client = this.clientsByRuntimeId.get(runtimeId);
128
+ if (!client) {
129
+ throw new Error(`No client connected with runtimeId: ${runtimeId}`);
130
+ }
131
+ client.socket.send(path, data);
132
+ }
133
+
134
+ public async teardown(): Promise<void> {
135
+ for (const client of this.clients.values()) {
136
+ client.socket.teardown();
137
+ }
138
+ this.clients.clear();
139
+ this.clientsByRuntimeId.clear();
140
+ this.proxy.close();
141
+
142
+ await new Promise<void>((resolve) => {
143
+ this.wss.close(() => resolve());
144
+ });
145
+ }
146
+ }