| 1 | import { IProtocol } from "core/protocol/index.js"; |
| 2 | import { IMessenger, type Message } from "core/protocol/messenger"; |
| 3 | import { ChildProcessWithoutNullStreams } from "node:child_process"; |
| 4 | import * as fs from "node:fs"; |
| 5 | import net from "node:net"; |
| 6 | import { v4 as uuidv4 } from "uuid"; |
| 7 | |
| 8 | class IPCMessengerBase< |
| 9 | ToProtocol extends IProtocol, |
| 10 | FromProtocol extends IProtocol, |
| 11 | > implements IMessenger<ToProtocol, FromProtocol> |
| 12 | { |
| 13 | _sendMsg(message: Message) { |
| 14 | throw new Error("Not implemented"); |
| 15 | } |
| 16 | |
| 17 | typeListeners = new Map<keyof ToProtocol, ((message: Message) => any)[]>(); |
| 18 | idListeners = new Map<string, (message: Message) => any>(); |
| 19 | |
| 20 | private _handleLine(line: string) { |
| 21 | try { |
| 22 | const msg: Message = JSON.parse(line); |
| 23 | if (msg.messageType === undefined || msg.messageId === undefined) { |
| 24 | throw new Error("Invalid message sent: " + JSON.stringify(msg)); |
| 25 | } |
| 26 | |
| 27 | // Call handler and respond with return value |
| 28 | const listeners = this.typeListeners.get(msg.messageType as any); |
| 29 | listeners?.forEach(async (handler) => { |
| 30 | try { |
| 31 | const response = await handler(msg); |
| 32 | if ( |
| 33 | response && |
| 34 | typeof response[Symbol.asyncIterator] === "function" |
| 35 | ) { |
| 36 | let next = await response.next(); |
| 37 | while (!next.done) { |
| 38 | this.send( |
| 39 | msg.messageType, |
| 40 | { |
| 41 | done: false, |
| 42 | content: next.value, |
| 43 | status: "success", |
| 44 | }, |
| 45 | msg.messageId, |
| 46 | ); |
| 47 | next = await response.next(); |
| 48 | } |
| 49 | this.send( |
| 50 | msg.messageType, |
| 51 | { |
| 52 | done: true, |
| 53 | content: next.value, |
| 54 | status: "success", |
| 55 | }, |
| 56 | msg.messageId, |
| 57 | ); |
| 58 | } else { |
| 59 | this.send( |
| 60 | msg.messageType, |
| 61 | { |
| 62 | done: true, |
| 63 | content: response, |
| 64 | status: "success", |
| 65 | }, |
| 66 | msg.messageId, |
| 67 | ); |
| 68 | } |
| 69 | } catch (e: any) { |
| 70 | this.send( |
| 71 | msg.messageType, |
| 72 | { done: true, error: e.message, status: "error" }, |
| 73 | msg.messageId, |
| 74 | ); |
| 75 | |
| 76 | console.warn(`Error running handler for "${msg.messageType}": `, e); |
| 77 | this._onErrorHandlers.forEach((handler) => { |
| 78 | handler(msg, e); |
| 79 | }); |
| 80 | } |
| 81 | }); |
| 82 | |
| 83 | // Call handler which is waiting for the response, nothing to return |
| 84 | this.idListeners.get(msg.messageId)?.(msg); |
| 85 | } catch (e) { |
| 86 | let truncatedLine = line; |
| 87 | if (line.length > 200) { |
| 88 | truncatedLine = |
| 89 | line.substring(0, 100) + "..." + line.substring(line.length - 100); |
| 90 | } |
| 91 | console.error("Error parsing line: ", truncatedLine, e); |
| 92 | return; |
| 93 | } |
| 94 | } |
| 95 | |
| 96 | private _unfinishedLine: string | undefined = undefined; |
| 97 | |
| 98 | protected _handleData(data: Buffer) { |
| 99 | const d = data.toString(); |
| 100 | const lines = d.split(/\r\n/).filter((line) => line.trim() !== ""); |
| 101 | if (lines.length === 0) { |
| 102 | return; |
| 103 | } |
| 104 | |
| 105 | if (this._unfinishedLine) { |
| 106 | lines[0] = this._unfinishedLine + lines[0]; |
| 107 | this._unfinishedLine = undefined; |
| 108 | } |
| 109 | if (!d.endsWith("\r\n")) { |
| 110 | this._unfinishedLine = lines.pop(); |
| 111 | } |
| 112 | lines.forEach((line) => this._handleLine(line)); |
| 113 | } |
| 114 | |
| 115 | private _onErrorHandlers: ((message: Message, error: Error) => void)[] = []; |
| 116 | |
| 117 | onError(handler: (message: Message, error: Error) => void) { |
| 118 | this._onErrorHandlers.push(handler); |
| 119 | } |
| 120 | |
| 121 | request<T extends keyof FromProtocol>( |
| 122 | messageType: T, |
| 123 | data: FromProtocol[T][0], |
| 124 | ): Promise<FromProtocol[T][1]> { |
| 125 | const messageId = uuidv4(); |
| 126 | return new Promise((resolve) => { |
| 127 | const handler = (msg: Message) => { |
| 128 | resolve(msg.data); |
| 129 | this.idListeners.delete(messageId); |
| 130 | }; |
| 131 | this.idListeners.set(messageId, handler); |
| 132 | this.send(messageType, data, messageId); |
| 133 | }); |
| 134 | } |
| 135 | |
| 136 | mock(data: any) { |
| 137 | const d = JSON.stringify(data); |
| 138 | this._handleData(Buffer.from(d)); |
| 139 | } |
| 140 | |
| 141 | send<T extends keyof FromProtocol>( |
| 142 | messageType: T, |
| 143 | data: FromProtocol[T][0], |
| 144 | messageId?: string, |
| 145 | ): string { |
| 146 | messageId = messageId ?? uuidv4(); |
| 147 | const msg: Message = { |
| 148 | messageType: messageType as string, |
| 149 | data, |
| 150 | messageId, |
| 151 | }; |
| 152 | this._sendMsg(msg); |
| 153 | return messageId; |
| 154 | } |
| 155 | |
| 156 | invoke<T extends keyof ToProtocol>( |
| 157 | messageType: T, |
| 158 | data: ToProtocol[T][0], |
| 159 | ): ToProtocol[T][1] { |
| 160 | return this.typeListeners.get(messageType)?.[0]?.({ |
| 161 | messageId: uuidv4(), |
| 162 | messageType: messageType as string, |
| 163 | data, |
| 164 | }); |
| 165 | } |
| 166 | |
| 167 | on<T extends keyof ToProtocol>( |
| 168 | messageType: T, |
| 169 | handler: ( |
| 170 | message: Message<ToProtocol[T][0]>, |
| 171 | ) => Promise<ToProtocol[T][1]> | ToProtocol[T][1], |
| 172 | ): void { |
| 173 | if (!this.typeListeners.has(messageType)) { |
| 174 | this.typeListeners.set(messageType, []); |
| 175 | } |
| 176 | this.typeListeners.get(messageType)?.push(handler); |
| 177 | } |
| 178 | } |
| 179 | |
| 180 | export class IpcMessenger< |
| 181 | ToProtocol extends IProtocol, |
| 182 | FromProtocol extends IProtocol, |
| 183 | > |
| 184 | extends IPCMessengerBase<ToProtocol, FromProtocol> |
| 185 | implements IMessenger<ToProtocol, FromProtocol> |
| 186 | { |
| 187 | constructor() { |
| 188 | super(); |
| 189 | console.log("Setup"); |
| 190 | process.stdin.on("data", (data) => { |
| 191 | // console.log("[info] Received data: ", data.toString()); |
| 192 | this._handleData(data); |
| 193 | }); |
| 194 | process.stdout.on("close", () => { |
| 195 | fs.writeFileSync("./error.log", `${new Date().toISOString()}\n`); |
| 196 | console.log("[info] Exiting Continue core..."); |
| 197 | process.exit(1); |
| 198 | }); |
| 199 | process.stdin.on("close", () => { |
| 200 | fs.writeFileSync("./error.log", `${new Date().toISOString()}\n`); |
| 201 | console.log("[info] Exiting Continue core..."); |
| 202 | process.exit(1); |
| 203 | }); |
| 204 | } |
| 205 | |
| 206 | _sendMsg(msg: Message) { |
| 207 | const d = JSON.stringify(msg); |
| 208 | // console.log("[info] Sending message: ", d); |
| 209 | process.stdout?.write(d + "\r\n"); |
| 210 | } |
| 211 | } |
| 212 | |
| 213 | export class CoreBinaryMessenger< |
| 214 | ToProtocol extends IProtocol, |
| 215 | FromProtocol extends IProtocol, |
| 216 | > |
| 217 | extends IPCMessengerBase<ToProtocol, FromProtocol> |
| 218 | implements IMessenger<ToProtocol, FromProtocol> |
| 219 | { |
| 220 | private errorHandler: (message: Message, error: Error) => void = () => {}; |
| 221 | private messageHandlers: Map< |
| 222 | keyof ToProtocol, |
| 223 | (message: Message<any>) => Promise<any> | any |
| 224 | > = new Map(); |
| 225 | |
| 226 | constructor(private readonly subprocess: ChildProcessWithoutNullStreams) { |
| 227 | super(); |
| 228 | console.log("Setup"); |
| 229 | this.subprocess.stdout.on("data", (data) => { |
| 230 | console.log("[info] Received data from core:", data.toString() + "\n"); |
| 231 | this._handleData(data); |
| 232 | }); |
| 233 | this.subprocess.stdout.on("close", () => { |
| 234 | console.log("[info] Continue core exited"); |
| 235 | }); |
| 236 | this.subprocess.stdin.on("close", () => { |
| 237 | console.log("[info] Continue core exited"); |
| 238 | }); |
| 239 | } |
| 240 | |
| 241 | _sendMsg(msg: Message) { |
| 242 | console.log("[info] Sending message to core:", msg); |
| 243 | const d = JSON.stringify(msg); |
| 244 | this.subprocess.stdin.write(d + "\r\n"); |
| 245 | } |
| 246 | } |
| 247 | |
| 248 | export class CoreBinaryTcpMessenger< |
| 249 | ToProtocol extends IProtocol, |
| 250 | FromProtocol extends IProtocol, |
| 251 | > |
| 252 | extends IPCMessengerBase<ToProtocol, FromProtocol> |
| 253 | implements IMessenger<ToProtocol, FromProtocol> |
| 254 | { |
| 255 | private port: number = 3000; |
| 256 | private socket: net.Socket | null = null; |
| 257 | |
| 258 | typeListeners = new Map<keyof ToProtocol, ((message: Message) => any)[]>(); |
| 259 | idListeners = new Map<string, (message: Message) => any>(); |
| 260 | |
| 261 | constructor() { |
| 262 | super(); |
| 263 | const socket = net.createConnection(this.port, "localhost"); |
| 264 | |
| 265 | this.socket = socket; |
| 266 | socket.on("data", (data: Buffer) => { |
| 267 | // console.log("[info] Received data from core:", data.toString() + "\n"); |
| 268 | this._handleData(data); |
| 269 | }); |
| 270 | |
| 271 | socket.on("end", () => { |
| 272 | console.log("Disconnected from server"); |
| 273 | }); |
| 274 | |
| 275 | socket.on("error", (err: any) => { |
| 276 | console.error("Client error:", err); |
| 277 | }); |
| 278 | } |
| 279 | |
| 280 | close() { |
| 281 | this.socket?.end(); |
| 282 | } |
| 283 | |
| 284 | _sendMsg(msg: Message) { |
| 285 | if (this.socket) { |
| 286 | // console.log("[info] Sending message to core:", msg); |
| 287 | const d = JSON.stringify(msg); |
| 288 | this.socket.write(d + "\r\n"); |
| 289 | } else { |
| 290 | console.error("Socket is not connected"); |
| 291 | } |
| 292 | } |
| 293 | } |