| 1 | import { IProtocol } from "core/protocol"; |
| 2 | import { IMessenger, Message } from "core/protocol/messenger"; |
| 3 | import net from "net"; |
| 4 | import { v4 as uuidv4 } from "uuid"; |
| 5 | |
| 6 | export class TcpMessenger< |
| 7 | ToProtocol extends IProtocol, |
| 8 | FromProtocol extends IProtocol, |
| 9 | > implements IMessenger<ToProtocol, FromProtocol> |
| 10 | { |
| 11 | private port: number = 3000; |
| 12 | private host: string = "127.0.0.1"; |
| 13 | private socket: net.Socket | null = null; |
| 14 | |
| 15 | typeListeners = new Map<keyof ToProtocol, ((message: Message) => any)[]>(); |
| 16 | idListeners = new Map<string, (message: Message) => any>(); |
| 17 | |
| 18 | constructor() { |
| 19 | const server = net.createServer((socket) => { |
| 20 | this.socket = socket; |
| 21 | |
| 22 | socket.on("connect", () => { |
| 23 | console.log("Connected to server"); |
| 24 | }); |
| 25 | |
| 26 | socket.on("data", (data: Buffer) => { |
| 27 | this._handleData(data); |
| 28 | }); |
| 29 | |
| 30 | socket.on("end", () => { |
| 31 | console.log("Disconnected from server"); |
| 32 | }); |
| 33 | |
| 34 | socket.on("error", (err: any) => { |
| 35 | console.error("Client error:", err); |
| 36 | }); |
| 37 | }); |
| 38 | |
| 39 | server.listen(this.port, this.host, () => { |
| 40 | console.log(`Server listening on port ${this.port}`); |
| 41 | }); |
| 42 | } |
| 43 | |
| 44 | private _onErrorHandlers: ((message: Message, error: Error) => void)[] = []; |
| 45 | |
| 46 | onError(handler: (message: Message, error: Error) => void) { |
| 47 | this._onErrorHandlers.push(handler); |
| 48 | } |
| 49 | |
| 50 | public async awaitConnection() { |
| 51 | while (!this.socket) { |
| 52 | await new Promise((resolve) => setTimeout(resolve, 100)); |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | private _handleLine(line: string) { |
| 57 | try { |
| 58 | const msg: Message = JSON.parse(line); |
| 59 | if (msg.messageType === undefined || msg.messageId === undefined) { |
| 60 | throw new Error("Invalid message sent: " + JSON.stringify(msg)); |
| 61 | } |
| 62 | |
| 63 | // Call handler and respond with return value |
| 64 | const listeners = this.typeListeners.get(msg.messageType as any); |
| 65 | listeners?.forEach(async (handler) => { |
| 66 | try { |
| 67 | const response = await handler(msg); |
| 68 | if ( |
| 69 | response && |
| 70 | typeof response[Symbol.asyncIterator] === "function" |
| 71 | ) { |
| 72 | let next = await response.next(); |
| 73 | while (!next.done) { |
| 74 | this.send( |
| 75 | msg.messageType, |
| 76 | { |
| 77 | done: false, |
| 78 | content: next.value, |
| 79 | status: "success", |
| 80 | }, |
| 81 | msg.messageId, |
| 82 | ); |
| 83 | next = await response.next(); |
| 84 | } |
| 85 | this.send( |
| 86 | msg.messageType, |
| 87 | { |
| 88 | done: true, |
| 89 | content: next.value, |
| 90 | status: "success", |
| 91 | }, |
| 92 | msg.messageId, |
| 93 | ); |
| 94 | } else { |
| 95 | this.send( |
| 96 | msg.messageType, |
| 97 | { |
| 98 | done: true, |
| 99 | content: response, |
| 100 | status: "success", |
| 101 | }, |
| 102 | msg.messageId, |
| 103 | ); |
| 104 | } |
| 105 | } catch (e: any) { |
| 106 | this.send( |
| 107 | msg.messageType, |
| 108 | { done: true, error: e.message, status: "error" }, |
| 109 | msg.messageId, |
| 110 | ); |
| 111 | |
| 112 | console.warn(`Error running handler for "${msg.messageType}": `, e); |
| 113 | this._onErrorHandlers.forEach((handler) => { |
| 114 | handler(msg, e); |
| 115 | }); |
| 116 | } |
| 117 | }); |
| 118 | |
| 119 | // Call handler which is waiting for the response, nothing to return |
| 120 | this.idListeners.get(msg.messageId)?.(msg); |
| 121 | } catch (e) { |
| 122 | let truncatedLine = line; |
| 123 | if (line.length > 200) { |
| 124 | truncatedLine = |
| 125 | line.substring(0, 100) + "..." + line.substring(line.length - 100); |
| 126 | } |
| 127 | console.error("Error parsing line: ", truncatedLine, e); |
| 128 | return; |
| 129 | } |
| 130 | } |
| 131 | |
| 132 | private _unfinishedLine: string | undefined = undefined; |
| 133 | |
| 134 | private _handleData(data: Buffer) { |
| 135 | const d = data.toString(); |
| 136 | const lines = d.split(/\r\n/).filter((line) => line.trim() !== ""); |
| 137 | if (lines.length === 0) { |
| 138 | return; |
| 139 | } |
| 140 | |
| 141 | if (this._unfinishedLine) { |
| 142 | lines[0] = this._unfinishedLine + lines[0]; |
| 143 | this._unfinishedLine = undefined; |
| 144 | } |
| 145 | if (!d.endsWith("\r\n")) { |
| 146 | this._unfinishedLine = lines.pop(); |
| 147 | } |
| 148 | lines.forEach((line) => this._handleLine(line)); |
| 149 | } |
| 150 | |
| 151 | send<T extends keyof FromProtocol>( |
| 152 | messageType: T, |
| 153 | data: FromProtocol[T][0], |
| 154 | messageId?: string, |
| 155 | ): string { |
| 156 | messageId = messageId ?? uuidv4(); |
| 157 | const msg: Message = { |
| 158 | messageType: messageType as string, |
| 159 | data, |
| 160 | messageId, |
| 161 | }; |
| 162 | |
| 163 | this.socket?.write(JSON.stringify(msg) + "\r\n"); |
| 164 | return messageId; |
| 165 | } |
| 166 | |
| 167 | on<T extends keyof ToProtocol>( |
| 168 | messageType: T, |
| 169 | handler: (message: Message<ToProtocol[T][0]>) => ToProtocol[T][1], |
| 170 | ): void { |
| 171 | if (!this.typeListeners.has(messageType)) { |
| 172 | this.typeListeners.set(messageType, []); |
| 173 | } |
| 174 | this.typeListeners.get(messageType)?.push(handler); |
| 175 | } |
| 176 | |
| 177 | invoke<T extends keyof ToProtocol>( |
| 178 | messageType: T, |
| 179 | data: ToProtocol[T][0], |
| 180 | ): ToProtocol[T][1] { |
| 181 | return this.typeListeners.get(messageType)?.[0]?.({ |
| 182 | messageId: uuidv4(), |
| 183 | messageType: messageType as string, |
| 184 | data, |
| 185 | }); |
| 186 | } |
| 187 | |
| 188 | request<T extends keyof FromProtocol>( |
| 189 | messageType: T, |
| 190 | data: FromProtocol[T][0], |
| 191 | ): Promise<FromProtocol[T][1]> { |
| 192 | const messageId = uuidv4(); |
| 193 | return new Promise((resolve) => { |
| 194 | const handler = (msg: Message) => { |
| 195 | resolve(msg.data); |
| 196 | this.idListeners.delete(messageId); |
| 197 | }; |
| 198 | this.idListeners.set(messageId, handler); |
| 199 | this.send(messageType, data, messageId); |
| 200 | }); |
| 201 | } |
| 202 | } |