|
| 1 | +// In-process call into the mneme HTTP API. |
| 2 | +// |
| 3 | +// The panel runs inside the engine process, exactly where mneme registered its |
| 4 | +// routes. Going through real HTTP would hit the dsh-go bridge guard (401 unless |
| 5 | +// the request carries the process launch token, which is never written to disk), |
| 6 | +// so we dispatch the registered route handler directly and never leave the |
| 7 | +// process. Everything stays on the local web server table: no sockets, no auth. |
| 8 | +import { EventEmitter } from "node:events"; |
| 9 | + |
| 10 | +const PREFIX = "/api/dsh-mneme"; |
| 11 | +const DEFAULT_TIMEOUT = 5000; |
| 12 | + |
| 13 | +function makeRequest(url, method, body) { |
| 14 | + const req = new EventEmitter(); |
| 15 | + req.url = url; |
| 16 | + req.method = method; |
| 17 | + req.headers = { |
| 18 | + host: "127.0.0.1", |
| 19 | + "content-type": "application/json", |
| 20 | + "content-length": String(body === undefined ? 0 : Buffer.byteLength(body)), |
| 21 | + }; |
| 22 | + req.socket = { remoteAddress: "127.0.0.1", encrypted: false }; |
| 23 | + req.resume = () => {}; |
| 24 | + req.pause = () => {}; |
| 25 | + req.setEncoding = () => {}; |
| 26 | + // The handler attaches its body listeners synchronously when invoked, so the |
| 27 | + // body is only released afterwards by flushRequest(); emitting during |
| 28 | + // construction would fire 'data'/'end' with no listener attached and the |
| 29 | + // handler's readBody() would wait forever. |
| 30 | + req.flush = () => { |
| 31 | + queueMicrotask(() => { |
| 32 | + if (body !== undefined) req.emit("data", Buffer.from(body)); |
| 33 | + req.emit("end"); |
| 34 | + }); |
| 35 | + }; |
| 36 | + return req; |
| 37 | +} |
| 38 | + |
| 39 | +function makeResponse() { |
| 40 | + const chunks = []; |
| 41 | + let settled; |
| 42 | + const done = new Promise((resolve) => { |
| 43 | + settled = resolve; |
| 44 | + }); |
| 45 | + const headers = {}; |
| 46 | + const res = { |
| 47 | + statusCode: 200, |
| 48 | + headersSent: false, |
| 49 | + done, |
| 50 | + writeHead(status, extra) { |
| 51 | + res.statusCode = status; |
| 52 | + res.headersSent = true; |
| 53 | + if (extra !== undefined && extra !== null) { |
| 54 | + for (const key of Object.keys(extra)) headers[key.toLowerCase()] = extra[key]; |
| 55 | + } |
| 56 | + return res; |
| 57 | + }, |
| 58 | + setHeader(key, value) { |
| 59 | + headers[key.toLowerCase()] = value; |
| 60 | + return res; |
| 61 | + }, |
| 62 | + getHeader(key) { |
| 63 | + return headers[key.toLowerCase()]; |
| 64 | + }, |
| 65 | + removeHeader(key) { |
| 66 | + delete headers[key.toLowerCase()]; |
| 67 | + }, |
| 68 | + write(chunk) { |
| 69 | + if (chunk !== undefined && chunk !== null && typeof chunk !== "function") { |
| 70 | + chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk))); |
| 71 | + } |
| 72 | + return true; |
| 73 | + }, |
| 74 | + end(chunk) { |
| 75 | + if (chunk !== undefined && chunk !== null && typeof chunk !== "function") { |
| 76 | + chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk))); |
| 77 | + } |
| 78 | + settled(); |
| 79 | + return res; |
| 80 | + }, |
| 81 | + flushHeaders() {}, |
| 82 | + }; |
| 83 | + res.text = () => Buffer.concat(chunks).toString("utf8"); |
| 84 | + res.bytes = () => Buffer.concat(chunks); |
| 85 | + return res; |
| 86 | +} |
| 87 | + |
| 88 | +function timeout(ms) { |
| 89 | + return new Promise((_, reject) => { |
| 90 | + const timer = setTimeout(() => reject(new Error("mneme 接口超时")), ms); |
| 91 | + timer.unref?.(); |
| 92 | + }); |
| 93 | +} |
| 94 | + |
| 95 | +/** |
| 96 | + * Resolve the mneme route handler and run it in-process. |
| 97 | + * @param {object} ctx - the plugin context (must expose get()). |
| 98 | + */ |
| 99 | +export function createHostCall(ctx) { |
| 100 | + return async function callMneme(path, options = {}) { |
| 101 | + const method = (options.method ?? "GET").toUpperCase(); |
| 102 | + const body = options.body === undefined ? undefined : JSON.stringify(options.body); |
| 103 | + const url = new URL(PREFIX + path, "http://127.0.0.1"); |
| 104 | + const webServer = ctx.get?.("webServer") ?? ctx.reflect?.get?.("webServer"); |
| 105 | + if (webServer === undefined || typeof webServer.match !== "function") { |
| 106 | + throw new Error("宿主 webServer 不可用"); |
| 107 | + } |
| 108 | + const route = webServer.match(url.pathname); |
| 109 | + if (route === undefined || route === null) throw new Error(`mneme 未注册 ${url.pathname}`); |
| 110 | + const req = makeRequest(url.pathname + url.search, method, body); |
| 111 | + const res = makeResponse(); |
| 112 | + let run; |
| 113 | + try { |
| 114 | + run = Promise.resolve(route.handler(req, res)); |
| 115 | + } finally { |
| 116 | + req.flush(); |
| 117 | + } |
| 118 | + await Promise.race([run, res.done, timeout(options.timeoutMs ?? DEFAULT_TIMEOUT)]); |
| 119 | + const text = res.text(); |
| 120 | + if (res.statusCode >= 400) { |
| 121 | + const detail = text.length > 200 ? `${text.slice(0, 200)}…` : text; |
| 122 | + const error = new Error(`mneme ${method} ${path} → ${res.statusCode} ${detail}`); |
| 123 | + error.status = res.statusCode; |
| 124 | + error.body = text; |
| 125 | + throw error; |
| 126 | + } |
| 127 | + if (options.raw === true) return text; |
| 128 | + if (text === "") return {}; |
| 129 | + try { |
| 130 | + return JSON.parse(text); |
| 131 | + } catch { |
| 132 | + return { text }; |
| 133 | + } |
| 134 | + }; |
| 135 | +} |
0 commit comments