| 1 | import { createServer, type Server } from "node:net"; |
| 2 | import { createHash, randomUUID } from "node:crypto"; |
| 3 | import type { Logger } from "./log.js"; |
| 4 | |
| 5 | export const QUIT_REQUEST = "--reasonix-lifecycle-request=quit"; |
| 6 | export const STATUS_LIMIT = 16 * 1024; |
| 7 | export interface ShellStatus { |
| 8 | schemaVersion: 1; |
| 9 | product: "com.reasonix.desktop"; |
| 10 | pid: number; |
| 11 | version: string; |
| 12 | generation: string; |
| 13 | homeKey: string; |
| 14 | lifecycle: "starting" | "ready" | "failed" | "quitting" | "done"; |
| 15 | service: string; |
| 16 | servicePID: number; |
| 17 | visible: boolean; |
| 18 | rendererVersion: string; |
| 19 | healthy: boolean; |
| 20 | } |
| 21 | |
| 22 | export function homeKey(profile: string): string { |
| 23 | return createHash("sha256").update(profile.replaceAll("/", "\\").toLowerCase()).digest("hex"); |
| 24 | } |
| 25 | |
| 26 | export function initialShellStatus(profile: string, version: string): ShellStatus { |
| 27 | return { schemaVersion: 1, product: "com.reasonix.desktop", pid: process.pid, version, generation: randomUUID(), homeKey: homeKey(profile), lifecycle: "starting", service: "starting", servicePID: 0, visible: false, rendererVersion: "", healthy: false }; |
| 28 | } |
| 29 | |
| 30 | export function listenShellStatus(snapshot: () => ShellStatus, log: Logger, address = `\\\\.\\pipe\\reasonix-shell-v1-${process.pid}`): Server { |
| 31 | const server = createServer((socket) => { |
| 32 | socket.on("error", () => undefined); |
| 33 | socket.setTimeout(2000, () => socket.destroy()); |
| 34 | try { |
| 35 | const data = JSON.stringify(snapshot()) + "\n"; |
| 36 | if (Buffer.byteLength(data) > STATUS_LIMIT) { socket.destroy(); return; } |
| 37 | socket.end(data); |
| 38 | } catch { socket.destroy(); } |
| 39 | }); |
| 40 | server.maxConnections = 8; |
| 41 | server.on("error", (error) => log.error(`shell status endpoint: ${error.message}`)); |
| 42 | server.listen(address); |
| 43 | return server; |
| 44 | } |
| 45 |