@livekit/agents 1.0.30 → 1.0.32
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.
- package/dist/ipc/inference_proc_executor.cjs +6 -3
- package/dist/ipc/inference_proc_executor.cjs.map +1 -1
- package/dist/ipc/inference_proc_executor.d.ts.map +1 -1
- package/dist/ipc/inference_proc_executor.js +6 -3
- package/dist/ipc/inference_proc_executor.js.map +1 -1
- package/dist/ipc/job_proc_executor.cjs +6 -1
- package/dist/ipc/job_proc_executor.cjs.map +1 -1
- package/dist/ipc/job_proc_executor.d.ts.map +1 -1
- package/dist/ipc/job_proc_executor.js +6 -1
- package/dist/ipc/job_proc_executor.js.map +1 -1
- package/dist/ipc/job_proc_lazy_main.cjs +1 -1
- package/dist/ipc/job_proc_lazy_main.cjs.map +1 -1
- package/dist/ipc/job_proc_lazy_main.js +1 -1
- package/dist/ipc/job_proc_lazy_main.js.map +1 -1
- package/dist/ipc/supervised_proc.cjs +29 -7
- package/dist/ipc/supervised_proc.cjs.map +1 -1
- package/dist/ipc/supervised_proc.d.ts.map +1 -1
- package/dist/ipc/supervised_proc.js +29 -7
- package/dist/ipc/supervised_proc.js.map +1 -1
- package/dist/ipc/supervised_proc.test.cjs +145 -0
- package/dist/ipc/supervised_proc.test.cjs.map +1 -0
- package/dist/ipc/supervised_proc.test.js +122 -0
- package/dist/ipc/supervised_proc.test.js.map +1 -0
- package/dist/job.cjs +5 -1
- package/dist/job.cjs.map +1 -1
- package/dist/job.d.ts.map +1 -1
- package/dist/job.js +5 -1
- package/dist/job.js.map +1 -1
- package/dist/llm/chat_context.cjs +19 -2
- package/dist/llm/chat_context.cjs.map +1 -1
- package/dist/llm/chat_context.d.cts +8 -0
- package/dist/llm/chat_context.d.ts +8 -0
- package/dist/llm/chat_context.d.ts.map +1 -1
- package/dist/llm/chat_context.js +19 -2
- package/dist/llm/chat_context.js.map +1 -1
- package/dist/llm/provider_format/google.cjs +6 -2
- package/dist/llm/provider_format/google.cjs.map +1 -1
- package/dist/llm/provider_format/google.d.ts.map +1 -1
- package/dist/llm/provider_format/google.js +6 -2
- package/dist/llm/provider_format/google.js.map +1 -1
- package/dist/llm/realtime.cjs.map +1 -1
- package/dist/llm/realtime.d.cts +4 -0
- package/dist/llm/realtime.d.ts +4 -0
- package/dist/llm/realtime.d.ts.map +1 -1
- package/dist/llm/realtime.js.map +1 -1
- package/dist/log.cjs +3 -3
- package/dist/log.cjs.map +1 -1
- package/dist/log.d.cts +5 -0
- package/dist/log.d.ts +5 -0
- package/dist/log.d.ts.map +1 -1
- package/dist/log.js +3 -3
- package/dist/log.js.map +1 -1
- package/dist/stream/stream_channel.cjs +8 -1
- package/dist/stream/stream_channel.cjs.map +1 -1
- package/dist/stream/stream_channel.d.cts +1 -0
- package/dist/stream/stream_channel.d.ts +1 -0
- package/dist/stream/stream_channel.d.ts.map +1 -1
- package/dist/stream/stream_channel.js +8 -1
- package/dist/stream/stream_channel.js.map +1 -1
- package/dist/telemetry/otel_http_exporter.cjs +13 -10
- package/dist/telemetry/otel_http_exporter.cjs.map +1 -1
- package/dist/telemetry/otel_http_exporter.d.ts.map +1 -1
- package/dist/telemetry/otel_http_exporter.js +13 -10
- package/dist/telemetry/otel_http_exporter.js.map +1 -1
- package/dist/telemetry/traces.cjs +22 -4
- package/dist/telemetry/traces.cjs.map +1 -1
- package/dist/telemetry/traces.d.ts.map +1 -1
- package/dist/telemetry/traces.js +22 -4
- package/dist/telemetry/traces.js.map +1 -1
- package/dist/voice/agent_activity.cjs +25 -5
- package/dist/voice/agent_activity.cjs.map +1 -1
- package/dist/voice/agent_activity.d.cts +1 -0
- package/dist/voice/agent_activity.d.ts +1 -0
- package/dist/voice/agent_activity.d.ts.map +1 -1
- package/dist/voice/agent_activity.js +26 -6
- package/dist/voice/agent_activity.js.map +1 -1
- package/dist/voice/generation.cjs +3 -1
- package/dist/voice/generation.cjs.map +1 -1
- package/dist/voice/generation.d.ts.map +1 -1
- package/dist/voice/generation.js +3 -1
- package/dist/voice/generation.js.map +1 -1
- package/package.json +1 -1
- package/src/ipc/inference_proc_executor.ts +11 -3
- package/src/ipc/job_proc_executor.ts +11 -1
- package/src/ipc/job_proc_lazy_main.ts +1 -1
- package/src/ipc/supervised_proc.test.ts +153 -0
- package/src/ipc/supervised_proc.ts +27 -9
- package/src/job.ts +4 -1
- package/src/llm/chat_context.ts +28 -2
- package/src/llm/provider_format/google.ts +6 -2
- package/src/llm/realtime.ts +5 -0
- package/src/log.ts +9 -3
- package/src/stream/stream_channel.ts +9 -1
- package/src/telemetry/otel_http_exporter.ts +14 -10
- package/src/telemetry/traces.ts +28 -4
- package/src/voice/agent_activity.ts +27 -2
- package/src/voice/generation.ts +2 -0
- package/src/llm/__snapshots__/utils.test.ts.snap +0 -65
|
@@ -24,6 +24,7 @@ module.exports = __toCommonJS(inference_proc_executor_exports);
|
|
|
24
24
|
var getImportMetaUrl = () => typeof document === "undefined" ? new URL(`file:${__filename}`).href : document.currentScript && document.currentScript.src || new URL("main.js", document.baseURI).href;
|
|
25
25
|
var importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
|
|
26
26
|
var import_node_child_process = require("node:child_process");
|
|
27
|
+
var import_node_path = require("node:path");
|
|
27
28
|
var import_log = require("../log.cjs");
|
|
28
29
|
var import_utils = require("../utils.cjs");
|
|
29
30
|
var import_supervised_proc = require("./supervised_proc.cjs");
|
|
@@ -35,6 +36,7 @@ class PendingInference {
|
|
|
35
36
|
arg;
|
|
36
37
|
}
|
|
37
38
|
}
|
|
39
|
+
const currentFileExtension = (0, import_node_path.extname)(importMetaUrl);
|
|
38
40
|
class InferenceProcExecutor extends import_supervised_proc.SupervisedProc {
|
|
39
41
|
#runners;
|
|
40
42
|
#activeRequests = {};
|
|
@@ -61,9 +63,10 @@ class InferenceProcExecutor extends import_supervised_proc.SupervisedProc {
|
|
|
61
63
|
this.#runners = runners;
|
|
62
64
|
}
|
|
63
65
|
createProcess() {
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
66
|
+
const forkUrl = new URL(`./inference_proc_lazy_main${currentFileExtension}`, importMetaUrl);
|
|
67
|
+
const isTypeScript = currentFileExtension === ".ts";
|
|
68
|
+
const forkOptions = isTypeScript ? { execArgv: process.execArgv } : void 0;
|
|
69
|
+
return (0, import_node_child_process.fork)(forkUrl, [JSON.stringify(this.#runners)], forkOptions);
|
|
67
70
|
}
|
|
68
71
|
async mainTask(proc) {
|
|
69
72
|
proc.on("message", (msg) => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/ipc/inference_proc_executor.ts","../../../node_modules/.pnpm/tsup@8.4.0_@microsoft+api-extractor@7.43.7_@types+node@22.15.30__postcss@8.4.38_tsx@4.20.4_typescript@5.4.5/node_modules/tsup/assets/cjs_shims.js"],"sourcesContent":["// SPDX-FileCopyrightText: 2025 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport type { ChildProcess } from 'node:child_process';\nimport { fork } from 'node:child_process';\nimport { log } from '../log.js';\nimport { shortuuid } from '../utils.js';\nimport type { InferenceExecutor } from './inference_executor.js';\nimport type { IPCMessage } from './message.js';\nimport { SupervisedProc } from './supervised_proc.js';\n\nclass PendingInference {\n promise = new Promise<{ requestId: string; data: unknown; error?: Error }>((resolve) => {\n this.resolve = resolve;\n });\n resolve(arg: { requestId: string; data: unknown; error?: Error }) {\n arg;\n }\n}\n\nexport class InferenceProcExecutor extends SupervisedProc implements InferenceExecutor {\n #runners: { [id: string]: string };\n #activeRequests: { [id: string]: PendingInference } = {};\n #logger = log();\n\n constructor({\n runners,\n initializeTimeout,\n closeTimeout,\n memoryWarnMB,\n memoryLimitMB,\n pingInterval,\n pingTimeout,\n highPingThreshold,\n }: {\n runners: { [id: string]: string };\n initializeTimeout: number;\n closeTimeout: number;\n memoryWarnMB: number;\n memoryLimitMB: number;\n pingInterval: number;\n pingTimeout: number;\n highPingThreshold: number;\n }) {\n super(\n initializeTimeout,\n closeTimeout,\n memoryWarnMB,\n memoryLimitMB,\n pingInterval,\n pingTimeout,\n highPingThreshold,\n );\n this.#runners = runners;\n }\n\n createProcess(): ChildProcess {\n
|
|
1
|
+
{"version":3,"sources":["../../src/ipc/inference_proc_executor.ts","../../../node_modules/.pnpm/tsup@8.4.0_@microsoft+api-extractor@7.43.7_@types+node@22.15.30__postcss@8.4.38_tsx@4.20.4_typescript@5.4.5/node_modules/tsup/assets/cjs_shims.js"],"sourcesContent":["// SPDX-FileCopyrightText: 2025 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport type { ChildProcess } from 'node:child_process';\nimport { fork } from 'node:child_process';\nimport { extname } from 'node:path';\nimport { log } from '../log.js';\nimport { shortuuid } from '../utils.js';\nimport type { InferenceExecutor } from './inference_executor.js';\nimport type { IPCMessage } from './message.js';\nimport { SupervisedProc } from './supervised_proc.js';\n\nclass PendingInference {\n promise = new Promise<{ requestId: string; data: unknown; error?: Error }>((resolve) => {\n this.resolve = resolve;\n });\n resolve(arg: { requestId: string; data: unknown; error?: Error }) {\n arg;\n }\n}\n\nconst currentFileExtension = extname(import.meta.url);\n\nexport class InferenceProcExecutor extends SupervisedProc implements InferenceExecutor {\n #runners: { [id: string]: string };\n #activeRequests: { [id: string]: PendingInference } = {};\n #logger = log();\n\n constructor({\n runners,\n initializeTimeout,\n closeTimeout,\n memoryWarnMB,\n memoryLimitMB,\n pingInterval,\n pingTimeout,\n highPingThreshold,\n }: {\n runners: { [id: string]: string };\n initializeTimeout: number;\n closeTimeout: number;\n memoryWarnMB: number;\n memoryLimitMB: number;\n pingInterval: number;\n pingTimeout: number;\n highPingThreshold: number;\n }) {\n super(\n initializeTimeout,\n closeTimeout,\n memoryWarnMB,\n memoryLimitMB,\n pingInterval,\n pingTimeout,\n highPingThreshold,\n );\n this.#runners = runners;\n }\n\n createProcess(): ChildProcess {\n const forkUrl = new URL(`./inference_proc_lazy_main${currentFileExtension}`, import.meta.url);\n\n // When running via tsx/ts-node (TypeScript files), we need to inherit the parent's\n // execArgv so the child process can also execute TypeScript with the same loader\n const isTypeScript = currentFileExtension === '.ts';\n const forkOptions = isTypeScript ? { execArgv: process.execArgv } : undefined;\n\n return fork(forkUrl, [JSON.stringify(this.#runners)], forkOptions);\n }\n\n async mainTask(proc: ChildProcess) {\n proc.on('message', (msg: IPCMessage) => {\n switch (msg.case) {\n case 'inferenceResponse':\n const res = this.#activeRequests[msg.value.requestId];\n delete this.#activeRequests[msg.value.requestId];\n if (!res) {\n this.#logger\n .child({ requestId: msg.value.requestId })\n .warn('received unexpected inference response');\n return;\n }\n\n res.resolve(msg.value);\n }\n });\n }\n\n async doInference(method: string, data: unknown): Promise<unknown> {\n const requestId = shortuuid('inference_req_');\n const fut = new PendingInference();\n this.proc!.send({ case: 'inferenceRequest', value: { requestId, method, data } });\n this.#activeRequests[requestId] = fut;\n\n const res = await fut.promise;\n if (res.error) {\n throw new Error(`inference of ${method} failed: ${res.error}`);\n }\n return res.data;\n }\n}\n","// Shim globals in cjs bundle\n// There's a weird bug that esbuild will always inject importMetaUrl\n// if we export it as `const importMetaUrl = ... __filename ...`\n// But using a function will not cause this issue\n\nconst getImportMetaUrl = () =>\n typeof document === 'undefined'\n ? new URL(`file:${__filename}`).href\n : (document.currentScript && document.currentScript.src) ||\n new URL('main.js', document.baseURI).href\n\nexport const importMetaUrl = /* @__PURE__ */ getImportMetaUrl()\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;ACKA,IAAM,mBAAmB,MACvB,OAAO,aAAa,cAChB,IAAI,IAAI,QAAQ,UAAU,EAAE,EAAE,OAC7B,SAAS,iBAAiB,SAAS,cAAc,OAClD,IAAI,IAAI,WAAW,SAAS,OAAO,EAAE;AAEpC,IAAM,gBAAgC,iCAAiB;ADP9D,gCAAqB;AACrB,uBAAwB;AACxB,iBAAoB;AACpB,mBAA0B;AAG1B,6BAA+B;AAE/B,MAAM,iBAAiB;AAAA,EACrB,UAAU,IAAI,QA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C,SAAK,KAAM,KAAK,EAAE,MAAM,oBAAoB,OAAO,EAAE,WAAW,QAAQ,KAAK,EAAE,CAAC;AAChF,SAAK,gBAAgB,SAAS,IAAI;AAElC,UAAM,MAAM,MAAM,IAAI;AACtB,QAAI,IAAI,OAAO;AACb,YAAM,IAAI,MAAM,gBAAgB,MAAM,YAAY,IAAI,KAAK,EAAE;AAAA,IAC/D;AACA,WAAO,IAAI;AAAA,EACb;AACF;","names":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"inference_proc_executor.d.ts","sourceRoot":"","sources":["../../src/ipc/inference_proc_executor.ts"],"names":[],"mappings":";AAGA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;
|
|
1
|
+
{"version":3,"file":"inference_proc_executor.d.ts","sourceRoot":"","sources":["../../src/ipc/inference_proc_executor.ts"],"names":[],"mappings":";AAGA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAKvD,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AAEjE,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAatD,qBAAa,qBAAsB,SAAQ,cAAe,YAAW,iBAAiB;;gBAKxE,EACV,OAAO,EACP,iBAAiB,EACjB,YAAY,EACZ,YAAY,EACZ,aAAa,EACb,YAAY,EACZ,WAAW,EACX,iBAAiB,GAClB,EAAE;QACD,OAAO,EAAE;YAAE,CAAC,EAAE,EAAE,MAAM,GAAG,MAAM,CAAA;SAAE,CAAC;QAClC,iBAAiB,EAAE,MAAM,CAAC;QAC1B,YAAY,EAAE,MAAM,CAAC;QACrB,YAAY,EAAE,MAAM,CAAC;QACrB,aAAa,EAAE,MAAM,CAAC;QACtB,YAAY,EAAE,MAAM,CAAC;QACrB,WAAW,EAAE,MAAM,CAAC;QACpB,iBAAiB,EAAE,MAAM,CAAC;KAC3B;IAaD,aAAa,IAAI,YAAY;IAWvB,QAAQ,CAAC,IAAI,EAAE,YAAY;IAkB3B,WAAW,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC;CAYnE"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { fork } from "node:child_process";
|
|
2
|
+
import { extname } from "node:path";
|
|
2
3
|
import { log } from "../log.js";
|
|
3
4
|
import { shortuuid } from "../utils.js";
|
|
4
5
|
import { SupervisedProc } from "./supervised_proc.js";
|
|
@@ -10,6 +11,7 @@ class PendingInference {
|
|
|
10
11
|
arg;
|
|
11
12
|
}
|
|
12
13
|
}
|
|
14
|
+
const currentFileExtension = extname(import.meta.url);
|
|
13
15
|
class InferenceProcExecutor extends SupervisedProc {
|
|
14
16
|
#runners;
|
|
15
17
|
#activeRequests = {};
|
|
@@ -36,9 +38,10 @@ class InferenceProcExecutor extends SupervisedProc {
|
|
|
36
38
|
this.#runners = runners;
|
|
37
39
|
}
|
|
38
40
|
createProcess() {
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
41
|
+
const forkUrl = new URL(`./inference_proc_lazy_main${currentFileExtension}`, import.meta.url);
|
|
42
|
+
const isTypeScript = currentFileExtension === ".ts";
|
|
43
|
+
const forkOptions = isTypeScript ? { execArgv: process.execArgv } : void 0;
|
|
44
|
+
return fork(forkUrl, [JSON.stringify(this.#runners)], forkOptions);
|
|
42
45
|
}
|
|
43
46
|
async mainTask(proc) {
|
|
44
47
|
proc.on("message", (msg) => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/ipc/inference_proc_executor.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2025 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport type { ChildProcess } from 'node:child_process';\nimport { fork } from 'node:child_process';\nimport { log } from '../log.js';\nimport { shortuuid } from '../utils.js';\nimport type { InferenceExecutor } from './inference_executor.js';\nimport type { IPCMessage } from './message.js';\nimport { SupervisedProc } from './supervised_proc.js';\n\nclass PendingInference {\n promise = new Promise<{ requestId: string; data: unknown; error?: Error }>((resolve) => {\n this.resolve = resolve;\n });\n resolve(arg: { requestId: string; data: unknown; error?: Error }) {\n arg;\n }\n}\n\nexport class InferenceProcExecutor extends SupervisedProc implements InferenceExecutor {\n #runners: { [id: string]: string };\n #activeRequests: { [id: string]: PendingInference } = {};\n #logger = log();\n\n constructor({\n runners,\n initializeTimeout,\n closeTimeout,\n memoryWarnMB,\n memoryLimitMB,\n pingInterval,\n pingTimeout,\n highPingThreshold,\n }: {\n runners: { [id: string]: string };\n initializeTimeout: number;\n closeTimeout: number;\n memoryWarnMB: number;\n memoryLimitMB: number;\n pingInterval: number;\n pingTimeout: number;\n highPingThreshold: number;\n }) {\n super(\n initializeTimeout,\n closeTimeout,\n memoryWarnMB,\n memoryLimitMB,\n pingInterval,\n pingTimeout,\n highPingThreshold,\n );\n this.#runners = runners;\n }\n\n createProcess(): ChildProcess {\n
|
|
1
|
+
{"version":3,"sources":["../../src/ipc/inference_proc_executor.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2025 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport type { ChildProcess } from 'node:child_process';\nimport { fork } from 'node:child_process';\nimport { extname } from 'node:path';\nimport { log } from '../log.js';\nimport { shortuuid } from '../utils.js';\nimport type { InferenceExecutor } from './inference_executor.js';\nimport type { IPCMessage } from './message.js';\nimport { SupervisedProc } from './supervised_proc.js';\n\nclass PendingInference {\n promise = new Promise<{ requestId: string; data: unknown; error?: Error }>((resolve) => {\n this.resolve = resolve;\n });\n resolve(arg: { requestId: string; data: unknown; error?: Error }) {\n arg;\n }\n}\n\nconst currentFileExtension = extname(import.meta.url);\n\nexport class InferenceProcExecutor extends SupervisedProc implements InferenceExecutor {\n #runners: { [id: string]: string };\n #activeRequests: { [id: string]: PendingInference } = {};\n #logger = log();\n\n constructor({\n runners,\n initializeTimeout,\n closeTimeout,\n memoryWarnMB,\n memoryLimitMB,\n pingInterval,\n pingTimeout,\n highPingThreshold,\n }: {\n runners: { [id: string]: string };\n initializeTimeout: number;\n closeTimeout: number;\n memoryWarnMB: number;\n memoryLimitMB: number;\n pingInterval: number;\n pingTimeout: number;\n highPingThreshold: number;\n }) {\n super(\n initializeTimeout,\n closeTimeout,\n memoryWarnMB,\n memoryLimitMB,\n pingInterval,\n pingTimeout,\n highPingThreshold,\n );\n this.#runners = runners;\n }\n\n createProcess(): ChildProcess {\n const forkUrl = new URL(`./inference_proc_lazy_main${currentFileExtension}`, import.meta.url);\n\n // When running via tsx/ts-node (TypeScript files), we need to inherit the parent's\n // execArgv so the child process can also execute TypeScript with the same loader\n const isTypeScript = currentFileExtension === '.ts';\n const forkOptions = isTypeScript ? { execArgv: process.execArgv } : undefined;\n\n return fork(forkUrl, [JSON.stringify(this.#runners)], forkOptions);\n }\n\n async mainTask(proc: ChildProcess) {\n proc.on('message', (msg: IPCMessage) => {\n switch (msg.case) {\n case 'inferenceResponse':\n const res = this.#activeRequests[msg.value.requestId];\n delete this.#activeRequests[msg.value.requestId];\n if (!res) {\n this.#logger\n .child({ requestId: msg.value.requestId })\n .warn('received unexpected inference response');\n return;\n }\n\n res.resolve(msg.value);\n }\n });\n }\n\n async doInference(method: string, data: unknown): Promise<unknown> {\n const requestId = shortuuid('inference_req_');\n const fut = new PendingInference();\n this.proc!.send({ case: 'inferenceRequest', value: { requestId, method, data } });\n this.#activeRequests[requestId] = fut;\n\n const res = await fut.promise;\n if (res.error) {\n throw new Error(`inference of ${method} failed: ${res.error}`);\n }\n return res.data;\n }\n}\n"],"mappings":"AAIA,SAAS,YAAY;AACrB,SAAS,eAAe;AACxB,SAAS,WAAW;AACpB,SAAS,iBAAiB;AAG1B,SAAS,sBAAsB;AAE/B,MAAM,iBAAiB;AAAA,EACrB,UAAU,IAAI,QAA6D,CAAC,YAAY;AACtF,SAAK,UAAU;AAAA,EACjB,CAAC;AAAA,EACD,QAAQ,KAA0D;AAChE;AAAA,EACF;AAC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AK,gBAAgB,SAAS,IAAI;AAElC,UAAM,MAAM,MAAM,IAAI;AACtB,QAAI,IAAI,OAAO;AACb,YAAM,IAAI,MAAM,gBAAgB,MAAM,YAAY,IAAI,KAAK,EAAE;AAAA,IAC/D;AACA,WAAO,IAAI;AAAA,EACb;AACF;","names":[]}
|
|
@@ -24,9 +24,11 @@ module.exports = __toCommonJS(job_proc_executor_exports);
|
|
|
24
24
|
var getImportMetaUrl = () => typeof document === "undefined" ? new URL(`file:${__filename}`).href : document.currentScript && document.currentScript.src || new URL("main.js", document.baseURI).href;
|
|
25
25
|
var importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
|
|
26
26
|
var import_node_child_process = require("node:child_process");
|
|
27
|
+
var import_node_path = require("node:path");
|
|
27
28
|
var import_log = require("../log.cjs");
|
|
28
29
|
var import_job_executor = require("./job_executor.cjs");
|
|
29
30
|
var import_supervised_proc = require("./supervised_proc.cjs");
|
|
31
|
+
const currentFileExtension = (0, import_node_path.extname)(importMetaUrl);
|
|
30
32
|
class JobProcExecutor extends import_supervised_proc.SupervisedProc {
|
|
31
33
|
#userArgs;
|
|
32
34
|
// eslint-disable-line @typescript-eslint/no-explicit-any
|
|
@@ -65,7 +67,10 @@ class JobProcExecutor extends import_supervised_proc.SupervisedProc {
|
|
|
65
67
|
return this.#runningJob;
|
|
66
68
|
}
|
|
67
69
|
createProcess() {
|
|
68
|
-
|
|
70
|
+
const forkUrl = new URL(`./job_proc_lazy_main${currentFileExtension}`, importMetaUrl);
|
|
71
|
+
const isTypeScript = currentFileExtension === ".ts";
|
|
72
|
+
const forkOptions = isTypeScript ? { execArgv: process.execArgv } : void 0;
|
|
73
|
+
return (0, import_node_child_process.fork)(forkUrl, [this.#agent], forkOptions);
|
|
69
74
|
}
|
|
70
75
|
async mainTask(proc) {
|
|
71
76
|
proc.on("message", (msg) => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/ipc/job_proc_executor.ts","../../../node_modules/.pnpm/tsup@8.4.0_@microsoft+api-extractor@7.43.7_@types+node@22.15.30__postcss@8.4.38_tsx@4.20.4_typescript@5.4.5/node_modules/tsup/assets/cjs_shims.js"],"sourcesContent":["// SPDX-FileCopyrightText: 2025 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport type { ChildProcess } from 'node:child_process';\nimport { fork } from 'node:child_process';\nimport type { RunningJobInfo } from '../job.js';\nimport { log } from '../log.js';\nimport type { InferenceExecutor } from './inference_executor.js';\nimport type { JobExecutor } from './job_executor.js';\nimport { JobStatus } from './job_executor.js';\nimport type { IPCMessage } from './message.js';\nimport { SupervisedProc } from './supervised_proc.js';\n\nexport class JobProcExecutor extends SupervisedProc implements JobExecutor {\n #userArgs?: any; // eslint-disable-line @typescript-eslint/no-explicit-any\n #jobStatus?: JobStatus;\n #runningJob?: RunningJobInfo;\n #agent: string;\n #inferenceExecutor?: InferenceExecutor;\n #inferenceTasks: Promise<void>[] = [];\n #logger = log();\n\n constructor(\n agent: string,\n inferenceExecutor: InferenceExecutor | undefined,\n initializeTimeout: number,\n closeTimeout: number,\n memoryWarnMB: number,\n memoryLimitMB: number,\n pingInterval: number,\n pingTimeout: number,\n highPingThreshold: number,\n ) {\n super(\n initializeTimeout,\n closeTimeout,\n memoryWarnMB,\n memoryLimitMB,\n pingInterval,\n pingTimeout,\n highPingThreshold,\n );\n this.#agent = agent;\n this.#inferenceExecutor = inferenceExecutor;\n }\n\n get status(): JobStatus {\n if (this.#jobStatus) {\n return this.#jobStatus;\n }\n throw new Error('job status not available');\n }\n\n get userArguments(): any {\n return this.#userArgs;\n }\n\n set userArguments(args: any) {\n this.#userArgs = args;\n }\n\n get runningJob(): RunningJobInfo | undefined {\n return this.#runningJob;\n }\n\n createProcess(): ChildProcess {\n
|
|
1
|
+
{"version":3,"sources":["../../src/ipc/job_proc_executor.ts","../../../node_modules/.pnpm/tsup@8.4.0_@microsoft+api-extractor@7.43.7_@types+node@22.15.30__postcss@8.4.38_tsx@4.20.4_typescript@5.4.5/node_modules/tsup/assets/cjs_shims.js"],"sourcesContent":["// SPDX-FileCopyrightText: 2025 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport type { ChildProcess } from 'node:child_process';\nimport { fork } from 'node:child_process';\nimport { extname } from 'node:path';\nimport type { RunningJobInfo } from '../job.js';\nimport { log } from '../log.js';\nimport type { InferenceExecutor } from './inference_executor.js';\nimport type { JobExecutor } from './job_executor.js';\nimport { JobStatus } from './job_executor.js';\nimport type { IPCMessage } from './message.js';\nimport { SupervisedProc } from './supervised_proc.js';\n\nconst currentFileExtension = extname(import.meta.url);\n\nexport class JobProcExecutor extends SupervisedProc implements JobExecutor {\n #userArgs?: any; // eslint-disable-line @typescript-eslint/no-explicit-any\n #jobStatus?: JobStatus;\n #runningJob?: RunningJobInfo;\n #agent: string;\n #inferenceExecutor?: InferenceExecutor;\n #inferenceTasks: Promise<void>[] = [];\n #logger = log();\n\n constructor(\n agent: string,\n inferenceExecutor: InferenceExecutor | undefined,\n initializeTimeout: number,\n closeTimeout: number,\n memoryWarnMB: number,\n memoryLimitMB: number,\n pingInterval: number,\n pingTimeout: number,\n highPingThreshold: number,\n ) {\n super(\n initializeTimeout,\n closeTimeout,\n memoryWarnMB,\n memoryLimitMB,\n pingInterval,\n pingTimeout,\n highPingThreshold,\n );\n this.#agent = agent;\n this.#inferenceExecutor = inferenceExecutor;\n }\n\n get status(): JobStatus {\n if (this.#jobStatus) {\n return this.#jobStatus;\n }\n throw new Error('job status not available');\n }\n\n get userArguments(): any {\n return this.#userArgs;\n }\n\n set userArguments(args: any) {\n this.#userArgs = args;\n }\n\n get runningJob(): RunningJobInfo | undefined {\n return this.#runningJob;\n }\n\n createProcess(): ChildProcess {\n const forkUrl = new URL(`./job_proc_lazy_main${currentFileExtension}`, import.meta.url);\n\n // When running via tsx/ts-node (TypeScript files), we need to inherit the parent's\n // execArgv so the child process can also execute TypeScript with the same loader\n const isTypeScript = currentFileExtension === '.ts';\n const forkOptions = isTypeScript ? { execArgv: process.execArgv } : undefined;\n\n return fork(forkUrl, [this.#agent], forkOptions);\n }\n\n async mainTask(proc: ChildProcess) {\n proc.on('message', (msg: IPCMessage) => {\n switch (msg.case) {\n case 'inferenceRequest':\n this.#inferenceTasks.push(this.#doInferenceTask(proc, msg.value));\n }\n });\n }\n\n async #doInferenceTask(\n proc: ChildProcess,\n req: { method: string; requestId: string; data: unknown },\n ) {\n if (!this.#inferenceExecutor) {\n this.#logger.warn('inference request received but no inference executor');\n proc.send({\n case: 'inferenceResponse',\n value: { requestId: req.requestId, error: new Error('no inference executor') },\n });\n return;\n }\n\n try {\n const data = await this.#inferenceExecutor.doInference(req.method, req.data);\n proc.send({ case: 'inferenceResponse', value: { requestId: req.requestId, data } });\n } catch (error) {\n proc.send({ case: 'inferenceResponse', value: { requestId: req.requestId, error } });\n }\n }\n\n async launchJob(info: RunningJobInfo) {\n if (this.#runningJob) {\n throw Error('process already has a running job');\n }\n if (!this.init.done) {\n throw Error('process not initialized');\n }\n this.#jobStatus = JobStatus.RUNNING;\n this.#runningJob = info;\n\n this.proc!.send({ case: 'startJobRequest', value: { runningJob: info } });\n }\n}\n","// Shim globals in cjs bundle\n// There's a weird bug that esbuild will always inject importMetaUrl\n// if we export it as `const importMetaUrl = ... __filename ...`\n// But using a function will not cause this issue\n\nconst getImportMetaUrl = () =>\n typeof document === 'undefined'\n ? new URL(`file:${__filename}`).href\n : (document.currentScript && document.currentScript.src) ||\n new URL('main.js', document.baseURI).href\n\nexport const importMetaUrl = /* @__PURE__ */ getImportMetaUrl()\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;ACKA,IAAM,mBAAmB,MACvB,OAAO,aAAa,cAChB,IAAI,IAAI,QAAQ,UAAU,EAAE,EAAE,OAC7B,SAAS,iBAAiB,SAAS,cAAc,OAClD,IAAI,IAAI,WAAW,SAAS,OAAO,EAAE;AAEpC,IAAM,gBAAgC,iCAAiB;ADP9D,g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QAAI,CAAC,KAAK,oBAAoB;AAC5B,WAAK,QAAQ,KAAK,sDAAsD;AACxE,WAAK,KAAK;AAAA,QACR,MAAM;AAAA,QACN,OAAO,EAAE,WAAW,IAAI,WAAW,OAAO,IAAI,MAAM,uBAAuB,EAAE;AAAA,MAC/E,CAAC;AACD;AAAA,IACF;AAEA,QAAI;AACF,YAAM,OAAO,MAAM,KAAK,mBAAmB,YAAY,IAAI,QAAQ,IAAI,IAAI;AAC3E,WAAK,KAAK,EAAE,MAAM,qBAAqB,OAAO,EAAE,WAAW,IAAI,WAAW,KAAK,EAAE,CAAC;AAAA,IACpF,SAAS,OAAO;AACd,WAAK,KAAK,EAAE,MAAM,qBAAqB,OAAO,EAAE,WAAW,IAAI,WAAW,MAAM,EAAE,CAAC;AAAA,IACrF;AAAA,EACF;AAAA,EAEA,MAAM,UAAU,MAAsB;AACpC,QAAI,KAAK,aAAa;AACpB,YAAM,MAAM,mCAAmC;AAAA,IACjD;AACA,QAAI,CAAC,KAAK,KAAK,MAAM;AACnB,YAAM,MAAM,yBAAyB;AAAA,IACvC;AACA,SAAK,aAAa,8BAAU;AAC5B,SAAK,cAAc;AAEnB,SAAK,KAAM,KAAK,EAAE,MAAM,mBAAmB,OAAO,EAAE,YAAY,KAAK,EAAE,CAAC;AAAA,EAC1E;AACF;","names":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"job_proc_executor.d.ts","sourceRoot":"","sources":["../../src/ipc/job_proc_executor.ts"],"names":[],"mappings":";AAGA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;
|
|
1
|
+
{"version":3,"file":"job_proc_executor.d.ts","sourceRoot":"","sources":["../../src/ipc/job_proc_executor.ts"],"names":[],"mappings":";AAGA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAGvD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAEhD,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AACjE,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AACrD,OAAO,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAE9C,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAItD,qBAAa,eAAgB,SAAQ,cAAe,YAAW,WAAW;;gBAUtE,KAAK,EAAE,MAAM,EACb,iBAAiB,EAAE,iBAAiB,GAAG,SAAS,EAChD,iBAAiB,EAAE,MAAM,EACzB,YAAY,EAAE,MAAM,EACpB,YAAY,EAAE,MAAM,EACpB,aAAa,EAAE,MAAM,EACrB,YAAY,EAAE,MAAM,EACpB,WAAW,EAAE,MAAM,EACnB,iBAAiB,EAAE,MAAM;IAe3B,IAAI,MAAM,IAAI,SAAS,CAKtB;IAED,IAAI,aAAa,IAAI,GAAG,CAEvB;IAED,IAAI,aAAa,CAAC,IAAI,EAAE,GAAG,EAE1B;IAED,IAAI,UAAU,IAAI,cAAc,GAAG,SAAS,CAE3C;IAED,aAAa,IAAI,YAAY;IAWvB,QAAQ,CAAC,IAAI,EAAE,YAAY;IA8B3B,SAAS,CAAC,IAAI,EAAE,cAAc;CAYrC"}
|
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import { fork } from "node:child_process";
|
|
2
|
+
import { extname } from "node:path";
|
|
2
3
|
import { log } from "../log.js";
|
|
3
4
|
import { JobStatus } from "./job_executor.js";
|
|
4
5
|
import { SupervisedProc } from "./supervised_proc.js";
|
|
6
|
+
const currentFileExtension = extname(import.meta.url);
|
|
5
7
|
class JobProcExecutor extends SupervisedProc {
|
|
6
8
|
#userArgs;
|
|
7
9
|
// eslint-disable-line @typescript-eslint/no-explicit-any
|
|
@@ -40,7 +42,10 @@ class JobProcExecutor extends SupervisedProc {
|
|
|
40
42
|
return this.#runningJob;
|
|
41
43
|
}
|
|
42
44
|
createProcess() {
|
|
43
|
-
|
|
45
|
+
const forkUrl = new URL(`./job_proc_lazy_main${currentFileExtension}`, import.meta.url);
|
|
46
|
+
const isTypeScript = currentFileExtension === ".ts";
|
|
47
|
+
const forkOptions = isTypeScript ? { execArgv: process.execArgv } : void 0;
|
|
48
|
+
return fork(forkUrl, [this.#agent], forkOptions);
|
|
44
49
|
}
|
|
45
50
|
async mainTask(proc) {
|
|
46
51
|
proc.on("message", (msg) => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/ipc/job_proc_executor.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2025 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport type { ChildProcess } from 'node:child_process';\nimport { fork } from 'node:child_process';\nimport type { RunningJobInfo } from '../job.js';\nimport { log } from '../log.js';\nimport type { InferenceExecutor } from './inference_executor.js';\nimport type { JobExecutor } from './job_executor.js';\nimport { JobStatus } from './job_executor.js';\nimport type { IPCMessage } from './message.js';\nimport { SupervisedProc } from './supervised_proc.js';\n\nexport class JobProcExecutor extends SupervisedProc implements JobExecutor {\n #userArgs?: any; // eslint-disable-line @typescript-eslint/no-explicit-any\n #jobStatus?: JobStatus;\n #runningJob?: RunningJobInfo;\n #agent: string;\n #inferenceExecutor?: InferenceExecutor;\n #inferenceTasks: Promise<void>[] = [];\n #logger = log();\n\n constructor(\n agent: string,\n inferenceExecutor: InferenceExecutor | undefined,\n initializeTimeout: number,\n closeTimeout: number,\n memoryWarnMB: number,\n memoryLimitMB: number,\n pingInterval: number,\n pingTimeout: number,\n highPingThreshold: number,\n ) {\n super(\n initializeTimeout,\n closeTimeout,\n memoryWarnMB,\n memoryLimitMB,\n pingInterval,\n pingTimeout,\n highPingThreshold,\n );\n this.#agent = agent;\n this.#inferenceExecutor = inferenceExecutor;\n }\n\n get status(): JobStatus {\n if (this.#jobStatus) {\n return this.#jobStatus;\n }\n throw new Error('job status not available');\n }\n\n get userArguments(): any {\n return this.#userArgs;\n }\n\n set userArguments(args: any) {\n this.#userArgs = args;\n }\n\n get runningJob(): RunningJobInfo | undefined {\n return this.#runningJob;\n }\n\n createProcess(): ChildProcess {\n
|
|
1
|
+
{"version":3,"sources":["../../src/ipc/job_proc_executor.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2025 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport type { ChildProcess } from 'node:child_process';\nimport { fork } from 'node:child_process';\nimport { extname } from 'node:path';\nimport type { RunningJobInfo } from '../job.js';\nimport { log } from '../log.js';\nimport type { InferenceExecutor } from './inference_executor.js';\nimport type { JobExecutor } from './job_executor.js';\nimport { JobStatus } from './job_executor.js';\nimport type { IPCMessage } from './message.js';\nimport { SupervisedProc } from './supervised_proc.js';\n\nconst currentFileExtension = extname(import.meta.url);\n\nexport class JobProcExecutor extends SupervisedProc implements JobExecutor {\n #userArgs?: any; // eslint-disable-line @typescript-eslint/no-explicit-any\n #jobStatus?: JobStatus;\n #runningJob?: RunningJobInfo;\n #agent: string;\n #inferenceExecutor?: InferenceExecutor;\n #inferenceTasks: Promise<void>[] = [];\n #logger = log();\n\n constructor(\n agent: string,\n inferenceExecutor: InferenceExecutor | undefined,\n initializeTimeout: number,\n closeTimeout: number,\n memoryWarnMB: number,\n memoryLimitMB: number,\n pingInterval: number,\n pingTimeout: number,\n highPingThreshold: number,\n ) {\n super(\n initializeTimeout,\n closeTimeout,\n memoryWarnMB,\n memoryLimitMB,\n pingInterval,\n pingTimeout,\n highPingThreshold,\n );\n this.#agent = agent;\n this.#inferenceExecutor = inferenceExecutor;\n }\n\n get status(): JobStatus {\n if (this.#jobStatus) {\n return this.#jobStatus;\n }\n throw new Error('job status not available');\n }\n\n get userArguments(): any {\n return this.#userArgs;\n }\n\n set userArguments(args: any) {\n this.#userArgs = args;\n }\n\n get runningJob(): RunningJobInfo | undefined {\n return this.#runningJob;\n }\n\n createProcess(): ChildProcess {\n const forkUrl = new URL(`./job_proc_lazy_main${currentFileExtension}`, import.meta.url);\n\n // When running via tsx/ts-node (TypeScript files), we need to inherit the parent's\n // execArgv so the child process can also execute TypeScript with the same loader\n const isTypeScript = currentFileExtension === '.ts';\n const forkOptions = isTypeScript ? { execArgv: process.execArgv } : undefined;\n\n return fork(forkUrl, [this.#agent], forkOptions);\n }\n\n async mainTask(proc: ChildProcess) {\n proc.on('message', (msg: IPCMessage) => {\n switch (msg.case) {\n case 'inferenceRequest':\n this.#inferenceTasks.push(this.#doInferenceTask(proc, msg.value));\n }\n });\n }\n\n async #doInferenceTask(\n proc: ChildProcess,\n req: { method: string; requestId: string; data: unknown },\n ) {\n if (!this.#inferenceExecutor) {\n this.#logger.warn('inference request received but no inference executor');\n proc.send({\n case: 'inferenceResponse',\n value: { requestId: req.requestId, error: new Error('no inference executor') },\n });\n return;\n }\n\n try {\n const data = await this.#inferenceExecutor.doInference(req.method, req.data);\n proc.send({ case: 'inferenceResponse', value: { requestId: req.requestId, data } });\n } catch (error) {\n proc.send({ case: 'inferenceResponse', value: { requestId: req.requestId, error } });\n }\n }\n\n async launchJob(info: RunningJobInfo) {\n if (this.#runningJob) {\n throw Error('process already has a running job');\n }\n if (!this.init.done) {\n throw Error('process not initialized');\n }\n this.#jobStatus = JobStatus.RUNNING;\n this.#runningJob = info;\n\n this.proc!.send({ case: 'startJobRequest', value: { runningJob: info } });\n }\n}\n"],"mappings":"AAIA,SAAS,YAAY;AACrB,SAAS,eAAe;AAExB,SAAS,WAAW;AAGpB,SAAS,iBAAiB;AAE1B,SAAS,sBAAsB;AAE/B,MAAM,uBAAuB,QAAQ,YAAY,GAAG;AAE7C,MAAM,wBAAwB,eAAsC;AAAA,EACzE;AAAA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,kBAAmC,CAAC;AAAA,EACpC,UAAU,IAAI;AAAA,EAEd,YACE,OACA,mBACA,mBACA,cACA,cACA,eACA,cACA,aACA,mBACA;AACA;AAAA,MACE;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAC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ACd,WAAK,KAAK,EAAE,MAAM,qBAAqB,OAAO,EAAE,WAAW,IAAI,WAAW,MAAM,EAAE,CAAC;AAAA,IACrF;AAAA,EACF;AAAA,EAEA,MAAM,UAAU,MAAsB;AACpC,QAAI,KAAK,aAAa;AACpB,YAAM,MAAM,mCAAmC;AAAA,IACjD;AACA,QAAI,CAAC,KAAK,KAAK,MAAM;AACnB,YAAM,MAAM,yBAAyB;AAAA,IACvC;AACA,SAAK,aAAa,UAAU;AAC5B,SAAK,cAAc;AAEnB,SAAK,KAAM,KAAK,EAAE,MAAM,mBAAmB,OAAO,EAAE,YAAY,KAAK,EAAE,CAAC;AAAA,EAC1E;AACF;","names":[]}
|
|
@@ -163,7 +163,7 @@ const startJob = (proc, func, info, closeEvent, logger, joinFuture) => {
|
|
|
163
163
|
logger.debug({ error: reason }, "Unhandled promise rejection");
|
|
164
164
|
});
|
|
165
165
|
logger.debug("initializing job runner");
|
|
166
|
-
agent.prewarm(proc);
|
|
166
|
+
await agent.prewarm(proc);
|
|
167
167
|
logger.debug("job runner initialized");
|
|
168
168
|
process.send({ case: "initializeResponse" });
|
|
169
169
|
let job = void 0;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/ipc/job_proc_lazy_main.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2024 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport { Room, RoomEvent } from '@livekit/rtc-node';\nimport { EventEmitter, once } from 'node:events';\nimport { pathToFileURL } from 'node:url';\nimport type { Logger } from 'pino';\nimport { type Agent, isAgent } from '../generator.js';\nimport { JobContext, JobProcess, type RunningJobInfo, runWithJobContextAsync } from '../job.js';\nimport { initializeLogger, log } from '../log.js';\nimport { Future, shortuuid } from '../utils.js';\nimport { defaultInitializeProcessFunc } from '../worker.js';\nimport type { InferenceExecutor } from './inference_executor.js';\nimport type { IPCMessage } from './message.js';\n\nconst ORPHANED_TIMEOUT = 15 * 1000;\n\ntype JobTask = {\n ctx: JobContext;\n task: Promise<void>;\n};\n\nclass PendingInference {\n promise = new Promise<{ requestId: string; data: unknown; error?: Error }>((resolve) => {\n this.resolve = resolve; // this is how JavaScript lets you resolve promises externally\n });\n resolve(arg: { requestId: string; data: unknown; error?: Error }) {\n arg; // useless call to counteract TypeScript E6133\n }\n}\n\nclass InfClient implements InferenceExecutor {\n #requests: { [id: string]: PendingInference } = {};\n\n constructor() {\n process.on('message', (msg: IPCMessage) => {\n switch (msg.case) {\n case 'inferenceResponse':\n const fut = this.#requests[msg.value.requestId];\n delete this.#requests[msg.value.requestId];\n if (!fut) {\n log().child({ resp: msg.value }).warn('received unexpected inference response');\n return;\n }\n fut.resolve(msg.value);\n break;\n }\n });\n }\n\n async doInference(method: string, data: unknown): Promise<unknown> {\n const requestId = shortuuid('inference_job_');\n process.send!({ case: 'inferenceRequest', value: { requestId, method, data } });\n this.#requests[requestId] = new PendingInference();\n const resp = await this.#requests[requestId]!.promise;\n if (resp.error) {\n throw new Error(`inference of ${method} failed: ${resp.error.message}`);\n }\n return resp.data;\n }\n}\n\nconst startJob = (\n proc: JobProcess,\n func: (ctx: JobContext) => Promise<void>,\n info: RunningJobInfo,\n closeEvent: EventEmitter,\n logger: Logger,\n joinFuture: Future,\n): JobTask => {\n let connect = false;\n let shutdown = false;\n\n const room = new Room();\n room.on(RoomEvent.Disconnected, () => {\n if (!shutdown) {\n closeEvent.emit('close', false);\n }\n });\n\n const onConnect = () => {\n connect = true;\n };\n const onShutdown = (reason: string) => {\n shutdown = true;\n closeEvent.emit('close', true, reason);\n };\n\n const ctx = new JobContext(proc, info, room, onConnect, onShutdown, new InfClient());\n\n const task = (async () => {\n const unconnectedTimeout = setTimeout(() => {\n if (!(connect || shutdown)) {\n logger.warn(\n 'room not connect after job_entry was called after 10 seconds, ',\n 'did you forget to call ctx.connect()?',\n );\n }\n }, 10000);\n\n // Run the job function within the AsyncLocalStorage context\n await runWithJobContextAsync(ctx, async () => {\n const { tracer, traceTypes } = await import('../telemetry/index.js');\n return tracer.startActiveSpan(\n async (span) => {\n span.setAttribute(traceTypes.ATTR_JOB_ID, info.job.id);\n span.setAttribute(traceTypes.ATTR_AGENT_NAME, info.job.agentName);\n span.setAttribute(traceTypes.ATTR_ROOM_NAME, info.job.room?.name ?? '');\n return func(ctx);\n },\n { name: 'job_entrypoint' },\n );\n }).finally(() => {\n clearTimeout(unconnectedTimeout);\n });\n\n await once(closeEvent, 'close').then((close) => {\n logger.debug('shutting down');\n shutdown = true;\n process.send!({ case: 'exiting', value: { reason: close[1] } });\n });\n\n // Close the primary agent session if it exists\n if (ctx._primaryAgentSession) {\n await ctx._primaryAgentSession.close();\n }\n\n // Generate and save/upload session report\n await ctx._onSessionEnd();\n\n await room.disconnect();\n logger.debug('disconnected from room');\n\n const shutdownTasks = [];\n for (const callback of ctx.shutdownCallbacks) {\n shutdownTasks.push(callback());\n }\n await Promise.all(shutdownTasks).catch((error) =>\n logger.error('error while shutting down the job', error),\n );\n\n process.send!({ case: 'done' });\n joinFuture.resolve();\n })();\n\n return { ctx, task };\n};\n\n(async () => {\n if (process.send) {\n const join = new Future();\n\n // process.argv:\n // [0] `node'\n // [1] import.meta.filename\n // [2] import.meta.filename of function containing entry file\n const moduleFile = process.argv[2];\n const agent: Agent = await import(pathToFileURL(moduleFile!).pathname).then((module) => {\n const agent = module.default;\n if (agent === undefined || !isAgent(agent)) {\n throw new Error(`Unable to load agent: Missing or invalid default export in ${moduleFile}`);\n }\n return agent;\n });\n if (!agent.prewarm) {\n agent.prewarm = defaultInitializeProcessFunc;\n }\n\n // don't do anything on C-c\n // this is handled in cli, triggering a termination of all child processes at once.\n process.on('SIGINT', () => {\n logger.debug('SIGINT received in job proc');\n });\n\n // don't do anything on SIGTERM\n // Render uses SIGTERM in autoscale, this ensures the processes are properly drained if needed\n process.on('SIGTERM', () => {\n logger.debug('SIGTERM received in job proc');\n });\n\n await once(process, 'message').then(([msg]: IPCMessage[]) => {\n msg = msg!;\n if (msg.case !== 'initializeRequest') {\n throw new Error('first message must be InitializeRequest');\n }\n initializeLogger(msg.value.loggerOptions);\n });\n const proc = new JobProcess();\n let logger = log().child({ pid: proc.pid });\n\n process.on('unhandledRejection', (reason) => {\n logger.debug({ error: reason }, 'Unhandled promise rejection');\n });\n\n logger.debug('initializing job runner');\n agent.prewarm(proc);\n logger.debug('job runner initialized');\n process.send({ case: 'initializeResponse' });\n\n let job: JobTask | undefined = undefined;\n const closeEvent = new EventEmitter();\n\n const orphanedTimeout = setTimeout(() => {\n logger.warn('job process orphaned, shutting down.');\n join.resolve();\n }, ORPHANED_TIMEOUT);\n\n const messageHandler = (msg: IPCMessage) => {\n switch (msg.case) {\n case 'pingRequest': {\n orphanedTimeout.refresh();\n process.send!({\n case: 'pongResponse',\n value: { lastTimestamp: msg.value.timestamp, timestamp: Date.now() },\n });\n break;\n }\n case 'startJobRequest': {\n if (job) {\n throw new Error('job task already running');\n }\n\n logger = logger.child({ jobID: msg.value.runningJob.job.id });\n\n job = startJob(proc, agent.entry, msg.value.runningJob, closeEvent, logger, join);\n logger.debug('job started');\n break;\n }\n case 'shutdownRequest': {\n if (!job) {\n join.resolve();\n }\n closeEvent.emit('close', 'shutdownRequest');\n clearTimeout(orphanedTimeout);\n process.off('message', messageHandler);\n }\n }\n };\n\n process.on('message', messageHandler);\n\n await join.await;\n\n logger.debug('Job process shutdown');\n process.exit(0);\n }\n})();\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAGA,sBAAgC;AAChC,yBAAmC;AACnC,sBAA8B;AAE9B,uBAAoC;AACpC,iBAAoF;AACpF,iBAAsC;AACtC,mBAAkC;AAClC,oBAA6C;AAI7C,MAAM,mBAAmB,KAAK;AAO9B,MAAM,iBAAiB;AAAA,EACrB,UAAU,IAAI,QAA6D,CAAC,YAAY;AACtF,SAAK,UAAU;AAAA,EACjB,CAAC;AAAA,EACD,QAAQ,KAA0D;AAChE;AAAA,EACF;AACF;AAEA,MAAM,UAAuC;AAAA,EAC3C,YAAgD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a;AAEpC,UAAM,kBAAkB,WAAW,MAAM;AACvC,aAAO,KAAK,sCAAsC;AAClD,WAAK,QAAQ;AAAA,IACf,GAAG,gBAAgB;AAEnB,UAAM,iBAAiB,CAAC,QAAoB;AAC1C,cAAQ,IAAI,MAAM;AAAA,QAChB,KAAK,eAAe;AAClB,0BAAgB,QAAQ;AACxB,kBAAQ,KAAM;AAAA,YACZ,MAAM;AAAA,YACN,OAAO,EAAE,eAAe,IAAI,MAAM,WAAW,WAAW,KAAK,IAAI,EAAE;AAAA,UACrE,CAAC;AACD;AAAA,QACF;AAAA,QACA,KAAK,mBAAmB;AACtB,cAAI,KAAK;AACP,kBAAM,IAAI,MAAM,0BAA0B;AAAA,UAC5C;AAEA,mBAAS,OAAO,MAAM,EAAE,OAAO,IAAI,MAAM,WAAW,IAAI,GAAG,CAAC;AAE5D,gBAAM,SAAS,MAAM,MAAM,OAAO,IAAI,MAAM,YAAY,YAAY,QAAQ,IAAI;AAChF,iBAAO,MAAM,aAAa;AAC1B;AAAA,QACF;AAAA,QACA,KAAK,mBAAmB;AACtB,cAAI,CAAC,KAAK;AACR,iBAAK,QAAQ;AAAA,UACf;AACA,qBAAW,KAAK,SAAS,iBAAiB;AAC1C,uBAAa,eAAe;AAC5B,kBAAQ,IAAI,WAAW,cAAc;AAAA,QACvC;AAAA,MACF;AAAA,IACF;AAEA,YAAQ,GAAG,WAAW,cAAc;AAEpC,UAAM,KAAK;AAEX,WAAO,MAAM,sBAAsB;AACnC,YAAQ,KAAK,CAAC;AAAA,EAChB;AACF,GAAG;","names":["module","agent"]}
|
|
1
|
+
{"version":3,"sources":["../../src/ipc/job_proc_lazy_main.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2024 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport { Room, RoomEvent } from '@livekit/rtc-node';\nimport { EventEmitter, once } from 'node:events';\nimport { pathToFileURL } from 'node:url';\nimport type { Logger } from 'pino';\nimport { type Agent, isAgent } from '../generator.js';\nimport { JobContext, JobProcess, type RunningJobInfo, runWithJobContextAsync } from '../job.js';\nimport { initializeLogger, log } from '../log.js';\nimport { Future, shortuuid } from '../utils.js';\nimport { defaultInitializeProcessFunc } from '../worker.js';\nimport type { InferenceExecutor } from './inference_executor.js';\nimport type { IPCMessage } from './message.js';\n\nconst ORPHANED_TIMEOUT = 15 * 1000;\n\ntype JobTask = {\n ctx: JobContext;\n task: Promise<void>;\n};\n\nclass PendingInference {\n promise = new Promise<{ requestId: string; data: unknown; error?: Error }>((resolve) => {\n this.resolve = resolve; // this is how JavaScript lets you resolve promises externally\n });\n resolve(arg: { requestId: string; data: unknown; error?: Error }) {\n arg; // useless call to counteract TypeScript E6133\n }\n}\n\nclass InfClient implements InferenceExecutor {\n #requests: { [id: string]: PendingInference } = {};\n\n constructor() {\n process.on('message', (msg: IPCMessage) => {\n switch (msg.case) {\n case 'inferenceResponse':\n const fut = this.#requests[msg.value.requestId];\n delete this.#requests[msg.value.requestId];\n if (!fut) {\n log().child({ resp: msg.value }).warn('received unexpected inference response');\n return;\n }\n fut.resolve(msg.value);\n break;\n }\n });\n }\n\n async doInference(method: string, data: unknown): Promise<unknown> {\n const requestId = shortuuid('inference_job_');\n process.send!({ case: 'inferenceRequest', value: { requestId, method, data } });\n this.#requests[requestId] = new PendingInference();\n const resp = await this.#requests[requestId]!.promise;\n if (resp.error) {\n throw new Error(`inference of ${method} failed: ${resp.error.message}`);\n }\n return resp.data;\n }\n}\n\nconst startJob = (\n proc: JobProcess,\n func: (ctx: JobContext) => Promise<void>,\n info: RunningJobInfo,\n closeEvent: EventEmitter,\n logger: Logger,\n joinFuture: Future,\n): JobTask => {\n let connect = false;\n let shutdown = false;\n\n const room = new Room();\n room.on(RoomEvent.Disconnected, () => {\n if (!shutdown) {\n closeEvent.emit('close', false);\n }\n });\n\n const onConnect = () => {\n connect = true;\n };\n const onShutdown = (reason: string) => {\n shutdown = true;\n closeEvent.emit('close', true, reason);\n };\n\n const ctx = new JobContext(proc, info, room, onConnect, onShutdown, new InfClient());\n\n const task = (async () => {\n const unconnectedTimeout = setTimeout(() => {\n if (!(connect || shutdown)) {\n logger.warn(\n 'room not connect after job_entry was called after 10 seconds, ',\n 'did you forget to call ctx.connect()?',\n );\n }\n }, 10000);\n\n // Run the job function within the AsyncLocalStorage context\n await runWithJobContextAsync(ctx, async () => {\n const { tracer, traceTypes } = await import('../telemetry/index.js');\n return tracer.startActiveSpan(\n async (span) => {\n span.setAttribute(traceTypes.ATTR_JOB_ID, info.job.id);\n span.setAttribute(traceTypes.ATTR_AGENT_NAME, info.job.agentName);\n span.setAttribute(traceTypes.ATTR_ROOM_NAME, info.job.room?.name ?? '');\n return func(ctx);\n },\n { name: 'job_entrypoint' },\n );\n }).finally(() => {\n clearTimeout(unconnectedTimeout);\n });\n\n await once(closeEvent, 'close').then((close) => {\n logger.debug('shutting down');\n shutdown = true;\n process.send!({ case: 'exiting', value: { reason: close[1] } });\n });\n\n // Close the primary agent session if it exists\n if (ctx._primaryAgentSession) {\n await ctx._primaryAgentSession.close();\n }\n\n // Generate and save/upload session report\n await ctx._onSessionEnd();\n\n await room.disconnect();\n logger.debug('disconnected from room');\n\n const shutdownTasks = [];\n for (const callback of ctx.shutdownCallbacks) {\n shutdownTasks.push(callback());\n }\n await Promise.all(shutdownTasks).catch((error) =>\n logger.error('error while shutting down the job', error),\n );\n\n process.send!({ case: 'done' });\n joinFuture.resolve();\n })();\n\n return { ctx, task };\n};\n\n(async () => {\n if (process.send) {\n const join = new Future();\n\n // process.argv:\n // [0] `node'\n // [1] import.meta.filename\n // [2] import.meta.filename of function containing entry file\n const moduleFile = process.argv[2];\n const agent: Agent = await import(pathToFileURL(moduleFile!).pathname).then((module) => {\n const agent = module.default;\n if (agent === undefined || !isAgent(agent)) {\n throw new Error(`Unable to load agent: Missing or invalid default export in ${moduleFile}`);\n }\n return agent;\n });\n if (!agent.prewarm) {\n agent.prewarm = defaultInitializeProcessFunc;\n }\n\n // don't do anything on C-c\n // this is handled in cli, triggering a termination of all child processes at once.\n process.on('SIGINT', () => {\n logger.debug('SIGINT received in job proc');\n });\n\n // don't do anything on SIGTERM\n // Render uses SIGTERM in autoscale, this ensures the processes are properly drained if needed\n process.on('SIGTERM', () => {\n logger.debug('SIGTERM received in job proc');\n });\n\n await once(process, 'message').then(([msg]: IPCMessage[]) => {\n msg = msg!;\n if (msg.case !== 'initializeRequest') {\n throw new Error('first message must be InitializeRequest');\n }\n initializeLogger(msg.value.loggerOptions);\n });\n const proc = new JobProcess();\n let logger = log().child({ pid: proc.pid });\n\n process.on('unhandledRejection', (reason) => {\n logger.debug({ error: reason }, 'Unhandled promise rejection');\n });\n\n logger.debug('initializing job runner');\n await agent.prewarm(proc);\n logger.debug('job runner initialized');\n process.send({ case: 'initializeResponse' });\n\n let job: JobTask | undefined = undefined;\n const closeEvent = new EventEmitter();\n\n const orphanedTimeout = setTimeout(() => {\n logger.warn('job process orphaned, shutting down.');\n join.resolve();\n }, ORPHANED_TIMEOUT);\n\n const messageHandler = (msg: IPCMessage) => {\n switch (msg.case) {\n case 'pingRequest': {\n orphanedTimeout.refresh();\n process.send!({\n case: 'pongResponse',\n value: { lastTimestamp: msg.value.timestamp, timestamp: Date.now() },\n });\n break;\n }\n case 'startJobRequest': {\n if (job) {\n throw new Error('job task already running');\n }\n\n logger = logger.child({ jobID: msg.value.runningJob.job.id });\n\n job = startJob(proc, agent.entry, msg.value.runningJob, closeEvent, logger, join);\n logger.debug('job started');\n break;\n }\n case 'shutdownRequest': {\n if (!job) {\n join.resolve();\n }\n closeEvent.emit('close', 'shutdownRequest');\n clearTimeout(orphanedTimeout);\n process.off('message', messageHandler);\n }\n }\n };\n\n process.on('message', messageHandler);\n\n await join.await;\n\n logger.debug('Job process shutdown');\n process.exit(0);\n }\n})();\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAGA,sBAAgC;AAChC,yBAAmC;AACnC,sBAA8B;AAE9B,uBAAoC;AACpC,iBAAoF;AACpF,iBAAs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|
@@ -140,7 +140,7 @@ const startJob = (proc, func, info, closeEvent, logger, joinFuture) => {
|
|
|
140
140
|
logger.debug({ error: reason }, "Unhandled promise rejection");
|
|
141
141
|
});
|
|
142
142
|
logger.debug("initializing job runner");
|
|
143
|
-
agent.prewarm(proc);
|
|
143
|
+
await agent.prewarm(proc);
|
|
144
144
|
logger.debug("job runner initialized");
|
|
145
145
|
process.send({ case: "initializeResponse" });
|
|
146
146
|
let job = void 0;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/ipc/job_proc_lazy_main.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2024 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport { Room, RoomEvent } from '@livekit/rtc-node';\nimport { EventEmitter, once } from 'node:events';\nimport { pathToFileURL } from 'node:url';\nimport type { Logger } from 'pino';\nimport { type Agent, isAgent } from '../generator.js';\nimport { JobContext, JobProcess, type RunningJobInfo, runWithJobContextAsync } from '../job.js';\nimport { initializeLogger, log } from '../log.js';\nimport { Future, shortuuid } from '../utils.js';\nimport { defaultInitializeProcessFunc } from '../worker.js';\nimport type { InferenceExecutor } from './inference_executor.js';\nimport type { IPCMessage } from './message.js';\n\nconst ORPHANED_TIMEOUT = 15 * 1000;\n\ntype JobTask = {\n ctx: JobContext;\n task: Promise<void>;\n};\n\nclass PendingInference {\n promise = new Promise<{ requestId: string; data: unknown; error?: Error }>((resolve) => {\n this.resolve = resolve; // this is how JavaScript lets you resolve promises externally\n });\n resolve(arg: { requestId: string; data: unknown; error?: Error }) {\n arg; // useless call to counteract TypeScript E6133\n }\n}\n\nclass InfClient implements InferenceExecutor {\n #requests: { [id: string]: PendingInference } = {};\n\n constructor() {\n process.on('message', (msg: IPCMessage) => {\n switch (msg.case) {\n case 'inferenceResponse':\n const fut = this.#requests[msg.value.requestId];\n delete this.#requests[msg.value.requestId];\n if (!fut) {\n log().child({ resp: msg.value }).warn('received unexpected inference response');\n return;\n }\n fut.resolve(msg.value);\n break;\n }\n });\n }\n\n async doInference(method: string, data: unknown): Promise<unknown> {\n const requestId = shortuuid('inference_job_');\n process.send!({ case: 'inferenceRequest', value: { requestId, method, data } });\n this.#requests[requestId] = new PendingInference();\n const resp = await this.#requests[requestId]!.promise;\n if (resp.error) {\n throw new Error(`inference of ${method} failed: ${resp.error.message}`);\n }\n return resp.data;\n }\n}\n\nconst startJob = (\n proc: JobProcess,\n func: (ctx: JobContext) => Promise<void>,\n info: RunningJobInfo,\n closeEvent: EventEmitter,\n logger: Logger,\n joinFuture: Future,\n): JobTask => {\n let connect = false;\n let shutdown = false;\n\n const room = new Room();\n room.on(RoomEvent.Disconnected, () => {\n if (!shutdown) {\n closeEvent.emit('close', false);\n }\n });\n\n const onConnect = () => {\n connect = true;\n };\n const onShutdown = (reason: string) => {\n shutdown = true;\n closeEvent.emit('close', true, reason);\n };\n\n const ctx = new JobContext(proc, info, room, onConnect, onShutdown, new InfClient());\n\n const task = (async () => {\n const unconnectedTimeout = setTimeout(() => {\n if (!(connect || shutdown)) {\n logger.warn(\n 'room not connect after job_entry was called after 10 seconds, ',\n 'did you forget to call ctx.connect()?',\n );\n }\n }, 10000);\n\n // Run the job function within the AsyncLocalStorage context\n await runWithJobContextAsync(ctx, async () => {\n const { tracer, traceTypes } = await import('../telemetry/index.js');\n return tracer.startActiveSpan(\n async (span) => {\n span.setAttribute(traceTypes.ATTR_JOB_ID, info.job.id);\n span.setAttribute(traceTypes.ATTR_AGENT_NAME, info.job.agentName);\n span.setAttribute(traceTypes.ATTR_ROOM_NAME, info.job.room?.name ?? '');\n return func(ctx);\n },\n { name: 'job_entrypoint' },\n );\n }).finally(() => {\n clearTimeout(unconnectedTimeout);\n });\n\n await once(closeEvent, 'close').then((close) => {\n logger.debug('shutting down');\n shutdown = true;\n process.send!({ case: 'exiting', value: { reason: close[1] } });\n });\n\n // Close the primary agent session if it exists\n if (ctx._primaryAgentSession) {\n await ctx._primaryAgentSession.close();\n }\n\n // Generate and save/upload session report\n await ctx._onSessionEnd();\n\n await room.disconnect();\n logger.debug('disconnected from room');\n\n const shutdownTasks = [];\n for (const callback of ctx.shutdownCallbacks) {\n shutdownTasks.push(callback());\n }\n await Promise.all(shutdownTasks).catch((error) =>\n logger.error('error while shutting down the job', error),\n );\n\n process.send!({ case: 'done' });\n joinFuture.resolve();\n })();\n\n return { ctx, task };\n};\n\n(async () => {\n if (process.send) {\n const join = new Future();\n\n // process.argv:\n // [0] `node'\n // [1] import.meta.filename\n // [2] import.meta.filename of function containing entry file\n const moduleFile = process.argv[2];\n const agent: Agent = await import(pathToFileURL(moduleFile!).pathname).then((module) => {\n const agent = module.default;\n if (agent === undefined || !isAgent(agent)) {\n throw new Error(`Unable to load agent: Missing or invalid default export in ${moduleFile}`);\n }\n return agent;\n });\n if (!agent.prewarm) {\n agent.prewarm = defaultInitializeProcessFunc;\n }\n\n // don't do anything on C-c\n // this is handled in cli, triggering a termination of all child processes at once.\n process.on('SIGINT', () => {\n logger.debug('SIGINT received in job proc');\n });\n\n // don't do anything on SIGTERM\n // Render uses SIGTERM in autoscale, this ensures the processes are properly drained if needed\n process.on('SIGTERM', () => {\n logger.debug('SIGTERM received in job proc');\n });\n\n await once(process, 'message').then(([msg]: IPCMessage[]) => {\n msg = msg!;\n if (msg.case !== 'initializeRequest') {\n throw new Error('first message must be InitializeRequest');\n }\n initializeLogger(msg.value.loggerOptions);\n });\n const proc = new JobProcess();\n let logger = log().child({ pid: proc.pid });\n\n process.on('unhandledRejection', (reason) => {\n logger.debug({ error: reason }, 'Unhandled promise rejection');\n });\n\n logger.debug('initializing job runner');\n agent.prewarm(proc);\n logger.debug('job runner initialized');\n process.send({ case: 'initializeResponse' });\n\n let job: JobTask | undefined = undefined;\n const closeEvent = new EventEmitter();\n\n const orphanedTimeout = setTimeout(() => {\n logger.warn('job process orphaned, shutting down.');\n join.resolve();\n }, ORPHANED_TIMEOUT);\n\n const messageHandler = (msg: IPCMessage) => {\n switch (msg.case) {\n case 'pingRequest': {\n orphanedTimeout.refresh();\n process.send!({\n case: 'pongResponse',\n value: { lastTimestamp: msg.value.timestamp, timestamp: Date.now() },\n });\n break;\n }\n case 'startJobRequest': {\n if (job) {\n throw new Error('job task already running');\n }\n\n logger = logger.child({ jobID: msg.value.runningJob.job.id });\n\n job = startJob(proc, agent.entry, msg.value.runningJob, closeEvent, logger, join);\n logger.debug('job started');\n break;\n }\n case 'shutdownRequest': {\n if (!job) {\n join.resolve();\n }\n closeEvent.emit('close', 'shutdownRequest');\n clearTimeout(orphanedTimeout);\n process.off('message', messageHandler);\n }\n }\n };\n\n process.on('message', messageHandler);\n\n await join.await;\n\n logger.debug('Job process shutdown');\n process.exit(0);\n }\n})();\n"],"mappings":"AAGA,SAAS,MAAM,iBAAiB;AAChC,SAAS,cAAc,YAAY;AACnC,SAAS,qBAAqB;AAE9B,SAAqB,eAAe;AACpC,SAAS,YAAY,YAAiC,8BAA8B;AACpF,SAAS,kBAAkB,WAAW;AACtC,SAAS,QAAQ,iBAAiB;AAClC,SAAS,oCAAoC;AAI7C,MAAM,mBAAmB,KAAK;AAO9B,MAAM,iBAAiB;AAAA,EACrB,UAAU,IAAI,QAA6D,CAAC,YAAY;AACtF,SAAK,UAAU;AAAA,EACjB,CAAC;AAAA,EACD,QAAQ,KAA0D;AAChE;AAAA,EACF;AACF;AAEA,MAAM,UAAuC;AAAA,EAC3C,YAAgD,CAAC;AAAA,EAEjD,cAAc;AACZ,YAAQ,GAAG,WAAW,CAAC,QAAoB;AACzC,cAAQ,IAAI,MAAM;AAAA,QAChB,KAAK;AACH,gBAAM,MAAM,KAAK,UAAU,IAAI,MAAM,SAAS;AAC9C,iBAAO,KAAK,UAAU,IAAI,MAAM,SAAS;AACzC,cAAI,CAAC,KAAK;AACR,gBAAI,EAAE,MAAM,EAAE,MAAM,IAAI,MAAM,CAAC,EAAE,KAAK,wCAAwC;AAC9E;AAAA,UACF;AACA,cAAI,QAAQ,IAAI,KAAK;AACrB;AAAA,MACJ;AAAA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B,cAAI,KAAK;AACP,kBAAM,IAAI,MAAM,0BAA0B;AAAA,UAC5C;AAEA,mBAAS,OAAO,MAAM,EAAE,OAAO,IAAI,MAAM,WAAW,IAAI,GAAG,CAAC;AAE5D,gBAAM,SAAS,MAAM,MAAM,OAAO,IAAI,MAAM,YAAY,YAAY,QAAQ,IAAI;AAChF,iBAAO,MAAM,aAAa;AAC1B;AAAA,QACF;AAAA,QACA,KAAK,mBAAmB;AACtB,cAAI,CAAC,KAAK;AACR,iBAAK,QAAQ;AAAA,UACf;AACA,qBAAW,KAAK,SAAS,iBAAiB;AAC1C,uBAAa,eAAe;AAC5B,kBAAQ,IAAI,WAAW,cAAc;AAAA,QACvC;AAAA,MACF;AAAA,IACF;AAEA,YAAQ,GAAG,WAAW,cAAc;AAEpC,UAAM,KAAK;AAEX,WAAO,MAAM,sBAAsB;AACnC,YAAQ,KAAK,CAAC;AAAA,EAChB;AACF,GAAG;","names":["agent"]}
|
|
1
|
+
{"version":3,"sources":["../../src/ipc/job_proc_lazy_main.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2024 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport { Room, RoomEvent } from '@livekit/rtc-node';\nimport { EventEmitter, once } from 'node:events';\nimport { pathToFileURL } from 'node:url';\nimport type { Logger } from 'pino';\nimport { type Agent, isAgent } from '../generator.js';\nimport { JobContext, JobProcess, type RunningJobInfo, runWithJobContextAsync } from '../job.js';\nimport { initializeLogger, log } from '../log.js';\nimport { Future, shortuuid } from '../utils.js';\nimport { defaultInitializeProcessFunc } from '../worker.js';\nimport type { InferenceExecutor } from './inference_executor.js';\nimport type { IPCMessage } from './message.js';\n\nconst ORPHANED_TIMEOUT = 15 * 1000;\n\ntype JobTask = {\n ctx: JobContext;\n task: Promise<void>;\n};\n\nclass PendingInference {\n promise = new Promise<{ requestId: string; data: unknown; error?: Error }>((resolve) => {\n this.resolve = resolve; // this is how JavaScript lets you resolve promises externally\n });\n resolve(arg: { requestId: string; data: unknown; error?: Error }) {\n arg; // useless call to counteract TypeScript E6133\n }\n}\n\nclass InfClient implements InferenceExecutor {\n #requests: { [id: string]: PendingInference } = {};\n\n constructor() {\n process.on('message', (msg: IPCMessage) => {\n switch (msg.case) {\n case 'inferenceResponse':\n const fut = this.#requests[msg.value.requestId];\n delete this.#requests[msg.value.requestId];\n if (!fut) {\n log().child({ resp: msg.value }).warn('received unexpected inference response');\n return;\n }\n fut.resolve(msg.value);\n break;\n }\n });\n }\n\n async doInference(method: string, data: unknown): Promise<unknown> {\n const requestId = shortuuid('inference_job_');\n process.send!({ case: 'inferenceRequest', value: { requestId, method, data } });\n this.#requests[requestId] = new PendingInference();\n const resp = await this.#requests[requestId]!.promise;\n if (resp.error) {\n throw new Error(`inference of ${method} failed: ${resp.error.message}`);\n }\n return resp.data;\n }\n}\n\nconst startJob = (\n proc: JobProcess,\n func: (ctx: JobContext) => Promise<void>,\n info: RunningJobInfo,\n closeEvent: EventEmitter,\n logger: Logger,\n joinFuture: Future,\n): JobTask => {\n let connect = false;\n let shutdown = false;\n\n const room = new Room();\n room.on(RoomEvent.Disconnected, () => {\n if (!shutdown) {\n closeEvent.emit('close', false);\n }\n });\n\n const onConnect = () => {\n connect = true;\n };\n const onShutdown = (reason: string) => {\n shutdown = true;\n closeEvent.emit('close', true, reason);\n };\n\n const ctx = new JobContext(proc, info, room, onConnect, onShutdown, new InfClient());\n\n const task = (async () => {\n const unconnectedTimeout = setTimeout(() => {\n if (!(connect || shutdown)) {\n logger.warn(\n 'room not connect after job_entry was called after 10 seconds, ',\n 'did you forget to call ctx.connect()?',\n );\n }\n }, 10000);\n\n // Run the job function within the AsyncLocalStorage context\n await runWithJobContextAsync(ctx, async () => {\n const { tracer, traceTypes } = await import('../telemetry/index.js');\n return tracer.startActiveSpan(\n async (span) => {\n span.setAttribute(traceTypes.ATTR_JOB_ID, info.job.id);\n span.setAttribute(traceTypes.ATTR_AGENT_NAME, info.job.agentName);\n span.setAttribute(traceTypes.ATTR_ROOM_NAME, info.job.room?.name ?? '');\n return func(ctx);\n },\n { name: 'job_entrypoint' },\n );\n }).finally(() => {\n clearTimeout(unconnectedTimeout);\n });\n\n await once(closeEvent, 'close').then((close) => {\n logger.debug('shutting down');\n shutdown = true;\n process.send!({ case: 'exiting', value: { reason: close[1] } });\n });\n\n // Close the primary agent session if it exists\n if (ctx._primaryAgentSession) {\n await ctx._primaryAgentSession.close();\n }\n\n // Generate and save/upload session report\n await ctx._onSessionEnd();\n\n await room.disconnect();\n logger.debug('disconnected from room');\n\n const shutdownTasks = [];\n for (const callback of ctx.shutdownCallbacks) {\n shutdownTasks.push(callback());\n }\n await Promise.all(shutdownTasks).catch((error) =>\n logger.error('error while shutting down the job', error),\n );\n\n process.send!({ case: 'done' });\n joinFuture.resolve();\n })();\n\n return { ctx, task };\n};\n\n(async () => {\n if (process.send) {\n const join = new Future();\n\n // process.argv:\n // [0] `node'\n // [1] import.meta.filename\n // [2] import.meta.filename of function containing entry file\n const moduleFile = process.argv[2];\n const agent: Agent = await import(pathToFileURL(moduleFile!).pathname).then((module) => {\n const agent = module.default;\n if (agent === undefined || !isAgent(agent)) {\n throw new Error(`Unable to load agent: Missing or invalid default export in ${moduleFile}`);\n }\n return agent;\n });\n if (!agent.prewarm) {\n agent.prewarm = defaultInitializeProcessFunc;\n }\n\n // don't do anything on C-c\n // this is handled in cli, triggering a termination of all child processes at once.\n process.on('SIGINT', () => {\n logger.debug('SIGINT received in job proc');\n });\n\n // don't do anything on SIGTERM\n // Render uses SIGTERM in autoscale, this ensures the processes are properly drained if needed\n process.on('SIGTERM', () => {\n logger.debug('SIGTERM received in job proc');\n });\n\n await once(process, 'message').then(([msg]: IPCMessage[]) => {\n msg = msg!;\n if (msg.case !== 'initializeRequest') {\n throw new Error('first message must be InitializeRequest');\n }\n initializeLogger(msg.value.loggerOptions);\n });\n const proc = new JobProcess();\n let logger = log().child({ pid: proc.pid });\n\n process.on('unhandledRejection', (reason) => {\n logger.debug({ error: reason }, 'Unhandled promise rejection');\n });\n\n logger.debug('initializing job runner');\n await agent.prewarm(proc);\n logger.debug('job runner initialized');\n process.send({ case: 'initializeResponse' });\n\n let job: JobTask | undefined = undefined;\n const closeEvent = new EventEmitter();\n\n const orphanedTimeout = setTimeout(() => {\n logger.warn('job process orphaned, shutting down.');\n join.resolve();\n }, ORPHANED_TIMEOUT);\n\n const messageHandler = (msg: IPCMessage) => {\n switch (msg.case) {\n case 'pingRequest': {\n orphanedTimeout.refresh();\n process.send!({\n case: 'pongResponse',\n value: { lastTimestamp: msg.value.timestamp, timestamp: Date.now() },\n });\n break;\n }\n case 'startJobRequest': {\n if (job) {\n throw new Error('job task already running');\n }\n\n logger = logger.child({ jobID: msg.value.runningJob.job.id });\n\n job = startJob(proc, agent.entry, msg.value.runningJob, closeEvent, logger, join);\n logger.debug('job started');\n break;\n }\n case 'shutdownRequest': {\n if (!job) {\n join.resolve();\n }\n closeEvent.emit('close', 'shutdownRequest');\n clearTimeout(orphanedTimeout);\n process.off('message', messageHandler);\n }\n }\n };\n\n process.on('message', messageHandler);\n\n await join.await;\n\n logger.debug('Job process shutdown');\n process.exit(0);\n }\n})();\n"],"mappings":"AAGA,SAAS,MAAM,iBAAiB;AAChC,SAAS,cAAc,YAAY;AACnC,SAAS,qBAAqB;AAE9B,SAAqB,eAAe;AACpC,SAAS,YAAY,YAAiC,8BAA8B;AACpF,SAAS,kBAAkB,WAAW;AACtC,SAAS,QAAQ,iBAAiB;AAClC,SAAS,oCAAoC;AAI7C,MAAM,mBAAmB,KAAK;AAO9B,MAAM,iBAAiB;AAAA,EACrB,UAAU,IAAI,QAA6D,CAAC,YAAY;AACtF,SAAK,UAAU;AAAA,EACjB,CAAC;AAAA,EACD,QAAQ,KAA0D;AAChE;AAAA,EACF;AACF;AAEA,MAAM,UAAuC;AAAA,EAC3C,YAAgD,CAAC;AAAA,EAEjD,cAAc;AACZ,YAAQ,GAAG,WAAW,CAAC,QAAoB;AACzC,cAAQ,IAAI,MA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G,gBAAgB;AAEnB,UAAM,iBAAiB,CAAC,QAAoB;AAC1C,cAAQ,IAAI,MAAM;AAAA,QAChB,KAAK,eAAe;AAClB,0BAAgB,QAAQ;AACxB,kBAAQ,KAAM;AAAA,YACZ,MAAM;AAAA,YACN,OAAO,EAAE,eAAe,IAAI,MAAM,WAAW,WAAW,KAAK,IAAI,EAAE;AAAA,UACrE,CAAC;AACD;AAAA,QACF;AAAA,QACA,KAAK,mBAAmB;AACtB,cAAI,KAAK;AACP,kBAAM,IAAI,MAAM,0BAA0B;AAAA,UAC5C;AAEA,mBAAS,OAAO,MAAM,EAAE,OAAO,IAAI,MAAM,WAAW,IAAI,GAAG,CAAC;AAE5D,gBAAM,SAAS,MAAM,MAAM,OAAO,IAAI,MAAM,YAAY,YAAY,QAAQ,IAAI;AAChF,iBAAO,MAAM,aAAa;AAC1B;AAAA,QACF;AAAA,QACA,KAAK,mBAAmB;AACtB,cAAI,CAAC,KAAK;AACR,iBAAK,QAAQ;AAAA,UACf;AACA,qBAAW,KAAK,SAAS,iBAAiB;AAC1C,uBAAa,eAAe;AAC5B,kBAAQ,IAAI,WAAW,cAAc;AAAA,QACvC;AAAA,MACF;AAAA,IACF;AAEA,YAAQ,GAAG,WAAW,cAAc;AAEpC,UAAM,KAAK;AAEX,WAAO,MAAM,sBAAsB;AACnC,YAAQ,KAAK,CAAC;AAAA,EAChB;AACF,GAAG;","names":["agent"]}
|
|
@@ -77,7 +77,10 @@ class SupervisedProc {
|
|
|
77
77
|
async run() {
|
|
78
78
|
await this.init.await;
|
|
79
79
|
this.#pingInterval = setInterval(() => {
|
|
80
|
-
|
|
80
|
+
var _a;
|
|
81
|
+
if ((_a = this.proc) == null ? void 0 : _a.connected) {
|
|
82
|
+
this.proc.send({ case: "pingRequest", value: { timestamp: Date.now() } });
|
|
83
|
+
}
|
|
81
84
|
}, this.#opts.pingInterval);
|
|
82
85
|
this.#pongTimeout = setTimeout(() => {
|
|
83
86
|
this.#logger.warn("job is unresponsive");
|
|
@@ -129,6 +132,7 @@ class SupervisedProc {
|
|
|
129
132
|
this.#join.resolve();
|
|
130
133
|
});
|
|
131
134
|
this.proc.on("exit", () => {
|
|
135
|
+
this.clearTimers();
|
|
132
136
|
this.#join.resolve();
|
|
133
137
|
});
|
|
134
138
|
this.mainTask(this.proc);
|
|
@@ -141,11 +145,14 @@ class SupervisedProc {
|
|
|
141
145
|
await this.#join.await;
|
|
142
146
|
}
|
|
143
147
|
async initialize() {
|
|
148
|
+
var _a;
|
|
144
149
|
const timer = setTimeout(() => {
|
|
145
|
-
|
|
146
|
-
this.init.reject(err);
|
|
147
|
-
throw err;
|
|
150
|
+
this.init.reject(new Error("runner initialization timed out"));
|
|
148
151
|
}, this.#opts.initializeTimeout);
|
|
152
|
+
if (!((_a = this.proc) == null ? void 0 : _a.connected)) {
|
|
153
|
+
this.init.reject(new Error("process not connected"));
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
149
156
|
this.proc.send({
|
|
150
157
|
case: "initializeRequest",
|
|
151
158
|
value: {
|
|
@@ -164,11 +171,14 @@ class SupervisedProc {
|
|
|
164
171
|
this.init.resolve();
|
|
165
172
|
}
|
|
166
173
|
async close() {
|
|
174
|
+
var _a;
|
|
167
175
|
if (!this.#started) {
|
|
168
176
|
return;
|
|
169
177
|
}
|
|
170
178
|
this.#closing = true;
|
|
171
|
-
this.proc
|
|
179
|
+
if ((_a = this.proc) == null ? void 0 : _a.connected) {
|
|
180
|
+
this.proc.send({ case: "shutdownRequest" });
|
|
181
|
+
}
|
|
172
182
|
const timer = setTimeout(() => {
|
|
173
183
|
this.#logger.error("job shutdown is taking too much time");
|
|
174
184
|
this.proc.kill();
|
|
@@ -179,9 +189,13 @@ class SupervisedProc {
|
|
|
179
189
|
});
|
|
180
190
|
}
|
|
181
191
|
async launchJob(info) {
|
|
192
|
+
var _a;
|
|
182
193
|
if (this.#runningJob) {
|
|
183
194
|
throw new Error("executor already has a running job");
|
|
184
195
|
}
|
|
196
|
+
if (!((_a = this.proc) == null ? void 0 : _a.connected)) {
|
|
197
|
+
throw new Error("process not connected");
|
|
198
|
+
}
|
|
185
199
|
this.#runningJob = info;
|
|
186
200
|
this.proc.send({ case: "startJobRequest", value: { runningJob: info } });
|
|
187
201
|
}
|
|
@@ -191,8 +205,16 @@ class SupervisedProc {
|
|
|
191
205
|
if (!pid) {
|
|
192
206
|
return 0;
|
|
193
207
|
}
|
|
194
|
-
|
|
195
|
-
|
|
208
|
+
try {
|
|
209
|
+
const stats = await (0, import_pidusage.default)(pid);
|
|
210
|
+
return stats.memory / (1024 * 1024);
|
|
211
|
+
} catch (err) {
|
|
212
|
+
const code = err.code;
|
|
213
|
+
if (code === "ENOENT" || code === "ESRCH") {
|
|
214
|
+
return 0;
|
|
215
|
+
}
|
|
216
|
+
throw err;
|
|
217
|
+
}
|
|
196
218
|
}
|
|
197
219
|
clearTimers() {
|
|
198
220
|
clearTimeout(this.#pongTimeout);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/ipc/supervised_proc.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2024 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport type { ChildProcess } from 'node:child_process';\nimport { once } from 'node:events';\nimport pidusage from 'pidusage';\nimport type { RunningJobInfo } from '../job.js';\nimport { log, loggerOptions } from '../log.js';\nimport { Future } from '../utils.js';\nimport type { IPCMessage } from './message.js';\n\nexport interface ProcOpts {\n initializeTimeout: number;\n closeTimeout: number;\n memoryWarnMB: number;\n memoryLimitMB: number;\n pingInterval: number;\n pingTimeout: number;\n highPingThreshold: number;\n}\n\nexport abstract class SupervisedProc {\n #opts: ProcOpts;\n #started = false;\n #closing = false;\n #runningJob?: RunningJobInfo = undefined;\n proc?: ChildProcess;\n #pingInterval?: ReturnType<typeof setInterval>;\n #memoryMonitorInterval?: ReturnType<typeof setInterval>;\n #pongTimeout?: ReturnType<typeof setTimeout>;\n protected init = new Future();\n #join = new Future();\n #logger = log().child({ runningJob: this.#runningJob });\n\n constructor(\n initializeTimeout: number,\n closeTimeout: number,\n memoryWarnMB: number,\n memoryLimitMB: number,\n pingInterval: number,\n pingTimeout: number,\n highPingThreshold: number,\n ) {\n this.#opts = {\n initializeTimeout,\n closeTimeout,\n memoryWarnMB,\n memoryLimitMB,\n pingInterval,\n pingTimeout,\n highPingThreshold,\n };\n }\n\n abstract createProcess(): ChildProcess;\n abstract mainTask(child: ChildProcess): Promise<void>;\n\n get started(): boolean {\n return this.#started;\n }\n\n get runningJob(): RunningJobInfo | undefined {\n return this.#runningJob;\n }\n\n async start() {\n if (this.#started) {\n throw new Error('runner already started');\n } else if (this.#closing) {\n throw new Error('runner is closed');\n }\n\n this.proc = this.createProcess();\n\n this.#started = true;\n this.run();\n }\n\n async run() {\n await this.init.await;\n\n this.#pingInterval = setInterval(() => {\n this.proc!.send({ case: 'pingRequest', value: { timestamp: Date.now() } });\n }, this.#opts.pingInterval);\n\n this.#pongTimeout = setTimeout(() => {\n this.#logger.warn('job is unresponsive');\n clearTimeout(this.#pongTimeout);\n clearInterval(this.#pingInterval);\n this.proc!.kill();\n this.#join.resolve();\n }, this.#opts.pingTimeout);\n\n this.#memoryMonitorInterval = setInterval(async () => {\n const memoryMB = await this.getChildMemoryUsageMB();\n if (this.#opts.memoryLimitMB > 0 && memoryMB > this.#opts.memoryLimitMB) {\n this.#logger\n .child({ memoryUsageMB: memoryMB, memoryLimitMB: this.#opts.memoryLimitMB })\n .error('process exceeded memory limit, killing process');\n this.close();\n } else if (this.#opts.memoryWarnMB > 0 && memoryMB > this.#opts.memoryWarnMB) {\n this.#logger\n .child({\n memoryUsageMB: memoryMB,\n memoryWarnMB: this.#opts.memoryWarnMB,\n memoryLimitMB: this.#opts.memoryLimitMB,\n })\n .warn('process memory usage is high');\n }\n }, 5000);\n\n const listener = (msg: IPCMessage) => {\n switch (msg.case) {\n case 'pongResponse': {\n const delay = Date.now() - msg.value.timestamp;\n if (delay > this.#opts.highPingThreshold) {\n this.#logger.child({ delay }).warn('job executor is unresponsive');\n }\n this.#pongTimeout?.refresh();\n break;\n }\n case 'exiting': {\n this.#logger.child({ reason: msg.value.reason }).debug('job exiting');\n break;\n }\n case 'done': {\n this.#closing = true;\n this.proc!.off('message', listener);\n break;\n }\n }\n };\n this.proc!.on('message', listener);\n this.proc!.on('error', (err) => {\n if (this.#closing) return;\n this.#logger\n .child({ err })\n .warn('job process exited unexpectedly; this likely means the error above caused a crash');\n this.clearTimers();\n this.#join.resolve();\n });\n\n this.proc!.on('exit', () => {\n this.#join.resolve();\n });\n\n this.mainTask(this.proc!);\n\n await this.#join.await;\n }\n\n async join() {\n if (!this.#started) {\n throw new Error('runner not started');\n }\n\n await this.#join.await;\n }\n\n async initialize() {\n const timer = setTimeout(() => {\n const err = new Error('runner initialization timed out');\n this.init.reject(err);\n throw err;\n }, this.#opts.initializeTimeout);\n this.proc!.send({\n case: 'initializeRequest',\n value: {\n loggerOptions,\n pingInterval: this.#opts.pingInterval,\n pingTimeout: this.#opts.pingTimeout,\n highPingThreshold: this.#opts.highPingThreshold,\n },\n });\n await once(this.proc!, 'message').then(([msg]: IPCMessage[]) => {\n clearTimeout(timer);\n if (msg!.case !== 'initializeResponse') {\n throw new Error('first message must be InitializeResponse');\n }\n });\n this.init.resolve();\n }\n\n async close() {\n if (!this.#started) {\n return;\n }\n this.#closing = true;\n\n this.proc!.send({ case: 'shutdownRequest' });\n\n const timer = setTimeout(() => {\n this.#logger.error('job shutdown is taking too much time');\n this.proc!.kill();\n }, this.#opts.closeTimeout);\n await this.#join.await.then(() => {\n clearTimeout(timer);\n this.clearTimers();\n });\n }\n\n async launchJob(info: RunningJobInfo) {\n if (this.#runningJob) {\n throw new Error('executor already has a running job');\n }\n this.#runningJob = info;\n this.proc!.send({ case: 'startJobRequest', value: { runningJob: info } });\n }\n\n private async getChildMemoryUsageMB(): Promise<number> {\n const pid = this.proc?.pid;\n if (!pid) {\n return 0;\n }\n const stats = await pidusage(pid);\n return stats.memory / (1024 * 1024); // Convert bytes to MB\n }\n\n private clearTimers() {\n clearTimeout(this.#pongTimeout);\n clearInterval(this.#pingInterval);\n clearInterval(this.#memoryMonitorInterval);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAIA,yBAAqB;AACrB,sBAAqB;AAErB,iBAAmC;AACnC,mBAAuB;AAahB,MAAe,eAAe;AAAA,EACnC;AAAA,EACA,WAAW;AAAA,EACX,WAAW;AAAA,EACX,cAA+B;AAAA,EAC/B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACU,OAAO,IAAI,oBAAO;AAAA,EAC5B,QAAQ,IAAI,oBAAO;AAAA,EACnB,cAAU,gBAAI,EAAE,MAAM,EAAE,YAAY,KAAK,YAAY,CAAC;AAAA,EAEtD,YACE,mBACA,cACA,cACA,eACA,cACA,aACA,mBACA;AACA,SAAK,QAAQ;AAAA,MACX;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAAA,EAKA,IAAI,UAAmB;AACrB,WAAO,KAAK;AAAA,EACd;AAAA,EAEA,IAAI,aAAyC;AAC3C,WAAO,KAAK;AAAA,EACd;AAAA,EAEA,MAAM,QAAQ;AACZ,QAAI,KAAK,UAAU;AACjB,YAAM,IAAI,MAAM,wBAAwB;AAAA,IAC1C,WAAW,KAAK,UAAU;AACxB,YAAM,IAAI,MAAM,kBAAkB;AAAA,IACpC;AAEA,SAAK,OAAO,KAAK,cAAc;AAE/B,SAAK,WAAW;AAChB,SAAK,IAAI;AAAA,EACX;AAAA,EAEA,MAAM,MAAM;AACV,UAAM,KAAK,KAAK;AAEhB,SAAK,gBAAgB,YAAY,MAAM;AACrC,WAAK,KAAM,KAAK,EAAE,MAAM,eAAe,OAAO,EAAE,WAAW,KAAK,IAAI,EAAE,EAAE,CAAC;AAAA,IAC3E,GAAG,KAAK,MAAM,YAAY;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AE3C,UAAM,QAAQ,WAAW,MAAM;AAC7B,WAAK,QAAQ,MAAM,sCAAsC;AACzD,WAAK,KAAM,KAAK;AAAA,IAClB,GAAG,KAAK,MAAM,YAAY;AAC1B,UAAM,KAAK,MAAM,MAAM,KAAK,MAAM;AAChC,mBAAa,KAAK;AAClB,WAAK,YAAY;AAAA,IACnB,CAAC;AAAA,EACH;AAAA,EAEA,MAAM,UAAU,MAAsB;AACpC,QAAI,KAAK,aAAa;AACpB,YAAM,IAAI,MAAM,oCAAoC;AAAA,IACtD;AACA,SAAK,cAAc;AACnB,SAAK,KAAM,KAAK,EAAE,MAAM,mBAAmB,OAAO,EAAE,YAAY,KAAK,EAAE,CAAC;AAAA,EAC1E;AAAA,EAEA,MAAc,wBAAyC;AAjNzD;AAkNI,UAAM,OAAM,UAAK,SAAL,mBAAW;AACvB,QAAI,CAAC,KAAK;AACR,aAAO;AAAA,IACT;AACA,UAAM,QAAQ,UAAM,gBAAAA,SAAS,GAAG;AAChC,WAAO,MAAM,UAAU,OAAO;AAAA,EAChC;AAAA,EAEQ,cAAc;AACpB,iBAAa,KAAK,YAAY;AAC9B,kBAAc,KAAK,aAAa;AAChC,kBAAc,KAAK,sBAAsB;AAAA,EAC3C;AACF;","names":["pidusage"]}
|
|
1
|
+
{"version":3,"sources":["../../src/ipc/supervised_proc.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2024 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport type { ChildProcess } from 'node:child_process';\nimport { once } from 'node:events';\nimport pidusage from 'pidusage';\nimport type { RunningJobInfo } from '../job.js';\nimport { log, loggerOptions } from '../log.js';\nimport { Future } from '../utils.js';\nimport type { IPCMessage } from './message.js';\n\nexport interface ProcOpts {\n initializeTimeout: number;\n closeTimeout: number;\n memoryWarnMB: number;\n memoryLimitMB: number;\n pingInterval: number;\n pingTimeout: number;\n highPingThreshold: number;\n}\n\nexport abstract class SupervisedProc {\n #opts: ProcOpts;\n #started = false;\n #closing = false;\n #runningJob?: RunningJobInfo = undefined;\n proc?: ChildProcess;\n #pingInterval?: ReturnType<typeof setInterval>;\n #memoryMonitorInterval?: ReturnType<typeof setInterval>;\n #pongTimeout?: ReturnType<typeof setTimeout>;\n protected init = new Future();\n #join = new Future();\n #logger = log().child({ runningJob: this.#runningJob });\n\n constructor(\n initializeTimeout: number,\n closeTimeout: number,\n memoryWarnMB: number,\n memoryLimitMB: number,\n pingInterval: number,\n pingTimeout: number,\n highPingThreshold: number,\n ) {\n this.#opts = {\n initializeTimeout,\n closeTimeout,\n memoryWarnMB,\n memoryLimitMB,\n pingInterval,\n pingTimeout,\n highPingThreshold,\n };\n }\n\n abstract createProcess(): ChildProcess;\n abstract mainTask(child: ChildProcess): Promise<void>;\n\n get started(): boolean {\n return this.#started;\n }\n\n get runningJob(): RunningJobInfo | undefined {\n return this.#runningJob;\n }\n\n async start() {\n if (this.#started) {\n throw new Error('runner already started');\n } else if (this.#closing) {\n throw new Error('runner is closed');\n }\n\n this.proc = this.createProcess();\n\n this.#started = true;\n this.run();\n }\n\n async run() {\n await this.init.await;\n\n this.#pingInterval = setInterval(() => {\n if (this.proc?.connected) {\n this.proc.send({ case: 'pingRequest', value: { timestamp: Date.now() } });\n }\n }, this.#opts.pingInterval);\n\n this.#pongTimeout = setTimeout(() => {\n this.#logger.warn('job is unresponsive');\n clearTimeout(this.#pongTimeout);\n clearInterval(this.#pingInterval);\n this.proc!.kill();\n this.#join.resolve();\n }, this.#opts.pingTimeout);\n\n this.#memoryMonitorInterval = setInterval(async () => {\n const memoryMB = await this.getChildMemoryUsageMB();\n if (this.#opts.memoryLimitMB > 0 && memoryMB > this.#opts.memoryLimitMB) {\n this.#logger\n .child({ memoryUsageMB: memoryMB, memoryLimitMB: this.#opts.memoryLimitMB })\n .error('process exceeded memory limit, killing process');\n this.close();\n } else if (this.#opts.memoryWarnMB > 0 && memoryMB > this.#opts.memoryWarnMB) {\n this.#logger\n .child({\n memoryUsageMB: memoryMB,\n memoryWarnMB: this.#opts.memoryWarnMB,\n memoryLimitMB: this.#opts.memoryLimitMB,\n })\n .warn('process memory usage is high');\n }\n }, 5000);\n\n const listener = (msg: IPCMessage) => {\n switch (msg.case) {\n case 'pongResponse': {\n const delay = Date.now() - msg.value.timestamp;\n if (delay > this.#opts.highPingThreshold) {\n this.#logger.child({ delay }).warn('job executor is unresponsive');\n }\n this.#pongTimeout?.refresh();\n break;\n }\n case 'exiting': {\n this.#logger.child({ reason: msg.value.reason }).debug('job exiting');\n break;\n }\n case 'done': {\n this.#closing = true;\n this.proc!.off('message', listener);\n break;\n }\n }\n };\n this.proc!.on('message', listener);\n this.proc!.on('error', (err) => {\n if (this.#closing) return;\n this.#logger\n .child({ err })\n .warn('job process exited unexpectedly; this likely means the error above caused a crash');\n this.clearTimers();\n this.#join.resolve();\n });\n\n this.proc!.on('exit', () => {\n this.clearTimers();\n this.#join.resolve();\n });\n\n this.mainTask(this.proc!);\n\n await this.#join.await;\n }\n\n async join() {\n if (!this.#started) {\n throw new Error('runner not started');\n }\n\n await this.#join.await;\n }\n\n async initialize() {\n const timer = setTimeout(() => {\n this.init.reject(new Error('runner initialization timed out'));\n }, this.#opts.initializeTimeout);\n if (!this.proc?.connected) {\n this.init.reject(new Error('process not connected'));\n return;\n }\n this.proc.send({\n case: 'initializeRequest',\n value: {\n loggerOptions,\n pingInterval: this.#opts.pingInterval,\n pingTimeout: this.#opts.pingTimeout,\n highPingThreshold: this.#opts.highPingThreshold,\n },\n });\n await once(this.proc!, 'message').then(([msg]: IPCMessage[]) => {\n clearTimeout(timer);\n if (msg!.case !== 'initializeResponse') {\n throw new Error('first message must be InitializeResponse');\n }\n });\n this.init.resolve();\n }\n\n async close() {\n if (!this.#started) {\n return;\n }\n this.#closing = true;\n\n if (this.proc?.connected) {\n this.proc.send({ case: 'shutdownRequest' });\n }\n\n const timer = setTimeout(() => {\n this.#logger.error('job shutdown is taking too much time');\n this.proc!.kill();\n }, this.#opts.closeTimeout);\n await this.#join.await.then(() => {\n clearTimeout(timer);\n this.clearTimers();\n });\n }\n\n async launchJob(info: RunningJobInfo) {\n if (this.#runningJob) {\n throw new Error('executor already has a running job');\n }\n if (!this.proc?.connected) {\n throw new Error('process not connected');\n }\n this.#runningJob = info;\n this.proc.send({ case: 'startJobRequest', value: { runningJob: info } });\n }\n\n private async getChildMemoryUsageMB(): Promise<number> {\n const pid = this.proc?.pid;\n if (!pid) {\n return 0;\n }\n try {\n const stats = await pidusage(pid);\n return stats.memory / (1024 * 1024);\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n if (code === 'ENOENT' || code === 'ESRCH') {\n return 0;\n }\n throw err;\n }\n }\n\n private clearTimers() {\n clearTimeout(this.#pongTimeout);\n clearInterval(this.#pingInterval);\n clearInterval(this.#memoryMonitorInterval);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAIA,yBAAqB;AACrB,sBAAqB;AAErB,iBAAmC;AACnC,mBAAuB;AAahB,MAAe,eAAe;AAAA,EACnC;AAAA,EACA,WAAW;AAAA,EACX,WAAW;AAAA,EACX,cAA+B;AAAA,EAC/B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACU,OAAO,IAAI,oBAAO;AAAA,EAC5B,QAAQ,IAAI,oBAAO;AAAA,EACnB,cAAU,gBAAI,EAAE,MAAM,EAAE,YAAY,KAAK,YAAY,CAAC;AAAA,EAEtD,YACE,mBACA,cACA,cACA,eACA,cACA,aACA,mBACA;AACA,SAAK,QAAQ;AAAA,MACX;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAAA,EAKA,IAAI,UAAmB;AACrB,WAAO,KAAK;AAAA,EACd;AAAA,EAEA,IAAI,aAAyC;AAC3C,WAAO,KAAK;AAAA,EACd;AAAA,EAEA,MAAM,QAAQ;AACZ,QAAI,KAAK,UAAU;AACjB,YA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