@qvac/sdk 0.22.0 โ 0.24.0
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/NOTICE +194 -97
- package/README.md +29 -470
- package/dist/examples/asr/parakeet-sortformer.js +24 -14
- package/dist/examples/asr/parakeet-transcribepsy-filesystem.d.ts +2 -0
- package/dist/examples/asr/parakeet-transcribepsy-filesystem.js +105 -0
- package/dist/examples/asr/parakeet-unified-coreml.js +14 -9
- package/dist/examples/asr/whispercpp-prompt.js +9 -5
- package/dist/examples/assess-model-fit.d.ts +7 -9
- package/dist/examples/assess-model-fit.js +22 -43
- package/dist/examples/calc-tokens.d.ts +2 -0
- package/dist/examples/calc-tokens.js +21 -0
- package/dist/examples/classification/classify-image.js +11 -5
- package/dist/examples/completion-stop-reason.d.ts +3 -3
- package/dist/examples/completion-stop-reason.js +4 -4
- package/dist/examples/diffusion-flux3-klein.d.ts +2 -0
- package/dist/examples/diffusion-flux3-klein.js +102 -0
- package/dist/examples/diffusion-img2vid-ltx.js +7 -14
- package/dist/examples/diffusion-moss-image.d.ts +2 -0
- package/dist/examples/diffusion-moss-image.js +126 -0
- package/dist/examples/diffusion-qwen-image-21.d.ts +2 -0
- package/dist/examples/diffusion-qwen-image-21.js +115 -0
- package/dist/examples/diffusion-txt2vid-ltx.js +7 -14
- package/dist/examples/embed-multimodal.d.ts +2 -0
- package/dist/examples/embed-multimodal.js +80 -0
- package/dist/examples/embed-p2p.js +2 -2
- package/dist/examples/finetune/llamacpp-finetune.js +9 -4
- package/dist/examples/image/megaloc.d.ts +2 -0
- package/dist/examples/image/megaloc.js +37 -0
- package/dist/examples/llamacpp-multimodal.js +21 -1
- package/dist/examples/mcp-websearch.js +1 -1
- package/dist/examples/plugins.js +1 -1
- package/dist/examples/rag/rag-hyperdb/pipeline.js +2 -2
- package/dist/examples/rag/rag-turbovec.js +2 -2
- package/dist/examples/rerank.d.ts +2 -0
- package/dist/examples/rerank.js +33 -0
- package/dist/examples/sessions.d.ts +17 -0
- package/dist/examples/sessions.js +63 -0
- package/dist/examples/tools/llamacpp-deferred-tools.js +12 -8
- package/dist/examples/tools/llamacpp-tools-auto-dialect.js +4 -3
- package/dist/examples/tools/llamacpp-tools-gemma4.js +3 -3
- package/dist/examples/tools/llamacpp-tools-qwen35.js +4 -3
- package/dist/scripts/check-resource-collectors-packaging.js +7 -6
- package/dist/scripts/contract/build-contract.d.ts +2 -1
- package/dist/scripts/contract/build-contract.js +13 -1
- package/dist/scripts/contract/constants-registry.d.ts +19 -0
- package/dist/scripts/contract/constants-registry.js +9 -2
- package/dist/scripts/contract/method-shapes.d.ts +5 -0
- package/dist/scripts/contract/method-shapes.js +5 -0
- package/dist/scripts/enforce-inference-versions.d.ts +1 -1
- package/dist/scripts/enforce-inference-versions.js +28 -18
- package/dist/scripts/generate-bare-kit-runtimes.js +101 -69
- package/dist/src/client/api/assess-model-fit.d.ts +17 -17
- package/dist/src/client/api/assess-model-fit.js +19 -32
- package/dist/src/client/api/audio-edit.d.ts +5 -3
- package/dist/src/client/api/audio-edit.js +7 -5
- package/dist/src/client/api/audio-gen-result.js +136 -47
- package/dist/src/client/api/audio-gen.d.ts +40 -3
- package/dist/src/client/api/audio-gen.js +42 -5
- package/dist/src/client/api/audio-understand.d.ts +2 -2
- package/dist/src/client/api/audio-understand.js +4 -4
- package/dist/src/client/api/batch-completion.js +4 -3
- package/dist/src/client/api/bci-transcribe.js +3 -3
- package/dist/src/client/api/calc-tokens.d.ts +33 -0
- package/dist/src/client/api/calc-tokens.js +44 -0
- package/dist/src/client/api/cancel.d.ts +2 -2
- package/dist/src/client/api/cancel.js +3 -3
- package/dist/src/client/api/classify.d.ts +12 -5
- package/dist/src/client/api/classify.js +18 -6
- package/dist/src/client/api/client-request-id.d.ts +0 -15
- package/dist/src/client/api/client-request-id.js +15 -12
- package/dist/src/client/api/completion-stream.d.ts +9 -1
- package/dist/src/client/api/completion-stream.js +14 -3
- package/dist/src/client/api/decide.d.ts +1 -1
- package/dist/src/client/api/decide.js +3 -3
- package/dist/src/client/api/delete-cache.d.ts +9 -2
- package/dist/src/client/api/delete-cache.js +14 -4
- package/dist/src/client/api/diffusion.d.ts +38 -5
- package/dist/src/client/api/diffusion.js +42 -7
- package/dist/src/client/api/download-asset.js +3 -3
- package/dist/src/client/api/embed.d.ts +82 -29
- package/dist/src/client/api/embed.js +66 -21
- package/dist/src/client/api/finetune.js +3 -3
- package/dist/src/client/api/get-loaded-model-info.js +1 -1
- package/dist/src/client/api/get-model-info.d.ts +2 -2
- package/dist/src/client/api/get-model-info.js +3 -3
- package/dist/src/client/api/get-system-resources.d.ts +2 -2
- package/dist/src/client/api/get-system-resources.js +3 -3
- package/dist/src/client/api/heartbeat.d.ts +3 -2
- package/dist/src/client/api/heartbeat.js +4 -3
- package/dist/src/client/api/index.d.ts +8 -6
- package/dist/src/client/api/index.js +6 -4
- package/dist/src/client/api/invoke-plugin.d.ts +8 -2
- package/dist/src/client/api/invoke-plugin.js +18 -3
- package/dist/src/client/api/load-model.js +9 -6
- package/dist/src/client/api/logging-stream.d.ts +11 -2
- package/dist/src/client/api/logging-stream.js +12 -3
- package/dist/src/client/api/ocr.d.ts +5 -3
- package/dist/src/client/api/ocr.js +45 -22
- package/dist/src/client/api/rag.d.ts +1 -1
- package/dist/src/client/api/rag.js +3 -3
- package/dist/src/client/api/registry.d.ts +19 -8
- package/dist/src/client/api/registry.js +43 -17
- package/dist/src/client/api/rerank.d.ts +22 -0
- package/dist/src/client/api/rerank.js +39 -0
- package/dist/src/client/api/resume.d.ts +2 -1
- package/dist/src/client/api/resume.js +3 -3
- package/dist/src/client/api/rpc-server.d.ts +4 -4
- package/dist/src/client/api/rpc-server.js +12 -12
- package/dist/src/client/api/state.d.ts +2 -2
- package/dist/src/client/api/state.js +3 -3
- package/dist/src/client/api/subscribe-logs.d.ts +2 -2
- package/dist/src/client/api/subscribe-logs.js +4 -3
- package/dist/src/client/api/suspend.d.ts +4 -2
- package/dist/src/client/api/suspend.js +5 -4
- package/dist/src/client/api/text-to-speech.d.ts +14 -5
- package/dist/src/client/api/text-to-speech.js +86 -32
- package/dist/src/client/api/transcribe.d.ts +7 -3
- package/dist/src/client/api/transcribe.js +9 -3
- package/dist/src/client/api/translate.js +2 -2
- package/dist/src/client/api/unload-model.d.ts +19 -7
- package/dist/src/client/api/unload-model.js +31 -13
- package/dist/src/client/api/upscale.d.ts +6 -3
- package/dist/src/client/api/upscale.js +10 -5
- package/dist/src/client/api/vector-index.d.ts +51 -17
- package/dist/src/client/api/vector-index.js +101 -49
- package/dist/src/client/api/video-request.d.ts +5 -5
- package/dist/src/client/api/video.d.ts +3 -2
- package/dist/src/client/api/video.js +6 -5
- package/dist/src/client/api/vla.d.ts +9 -5
- package/dist/src/client/api/vla.js +17 -8
- package/dist/src/client/api/world-result.js +2 -2
- package/dist/src/client/api/world.d.ts +6 -6
- package/dist/src/client/api/world.js +6 -6
- package/dist/src/client/init-hooks.d.ts +6 -4
- package/dist/src/client/init-hooks.js +12 -15
- package/dist/src/client/logging-stream-registry.d.ts +6 -3
- package/dist/src/client/logging-stream-registry.js +36 -14
- package/dist/src/client/plugins-factory.d.ts +1 -1
- package/dist/src/client/plugins-factory.js +1 -1
- package/dist/src/client/rpc/bundle-stamp.d.ts +29 -0
- package/dist/src/client/rpc/bundle-stamp.js +75 -0
- package/dist/src/client/rpc/expo-home-dir.d.ts +2 -0
- package/dist/src/client/rpc/expo-home-dir.js +4 -0
- package/dist/src/client/rpc/expo-rpc-client.js +192 -138
- package/dist/src/client/rpc/node-rpc-client.js +324 -426
- package/dist/src/client/rpc/pear-runtime.d.ts +12 -0
- package/dist/src/client/rpc/pear-runtime.js +12 -0
- package/dist/src/client/rpc/rpc-client.d.ts +6 -4
- package/dist/src/client/rpc/rpc-client.js +168 -31
- package/dist/src/client/rpc/rpc-error.js +24 -2
- package/dist/src/client/rpc/unbundled-harness.d.ts +16 -0
- package/dist/src/client/rpc/unbundled-harness.js +27 -0
- package/dist/src/client/rpc/worker-failure.d.ts +27 -0
- package/dist/src/client/rpc/worker-failure.js +61 -0
- package/dist/src/client/session-registry.d.ts +75 -0
- package/dist/src/client/session-registry.js +149 -0
- package/dist/src/client/session.d.ts +125 -0
- package/dist/src/client/session.js +148 -0
- package/dist/src/commands/bundle/addons.d.ts +14 -0
- package/dist/src/commands/bundle/addons.js +65 -0
- package/dist/src/commands/bundle/constants.js +2 -0
- package/dist/src/commands/bundle/entry-gen.d.ts +1 -5
- package/dist/src/commands/bundle/entry-gen.js +18 -51
- package/dist/src/commands/bundle/index.d.ts +60 -14
- package/dist/src/commands/bundle/index.js +350 -126
- package/dist/src/commands/bundle/link.d.ts +58 -0
- package/dist/src/commands/bundle/link.js +135 -0
- package/dist/src/commands/bundle/node-support.d.ts +13 -0
- package/dist/src/commands/bundle/node-support.js +23 -0
- package/dist/src/commands/bundle/plugins.js +1 -1
- package/dist/src/commands/bundle/read-bundle.d.ts +9 -0
- package/dist/src/commands/bundle/read-bundle.js +27 -0
- package/dist/src/commands/bundle/resolve-sdk-import.d.ts +6 -0
- package/dist/src/commands/bundle/resolve-sdk-import.js +24 -28
- package/dist/src/commands/bundle/scratch.d.ts +35 -0
- package/dist/src/commands/bundle/scratch.js +178 -0
- package/dist/src/commands/bundle/targets.d.ts +14 -0
- package/dist/src/commands/bundle/targets.js +37 -0
- package/dist/src/commands/host-prebuilds/index.d.ts +8 -7
- package/dist/src/commands/host-prebuilds/index.js +13 -11
- package/dist/src/commands/index.d.ts +13 -12
- package/dist/src/commands/index.js +7 -7
- package/dist/src/commands/verify/abi.d.ts +21 -15
- package/dist/src/commands/verify/abi.js +12 -80
- package/dist/src/commands/verify/bare-kit-runtime.d.ts +20 -22
- package/dist/src/commands/verify/bare-kit-runtime.js +102 -150
- package/dist/src/commands/verify/bare-kit-runtimes.d.ts +10 -9
- package/dist/src/commands/verify/bare-kit-runtimes.js +21 -21
- package/dist/src/commands/verify/bundle-source.d.ts +1 -1
- package/dist/src/commands/verify/bundle-source.js +27 -23
- package/dist/src/commands/verify/engines-advice.d.ts +6 -12
- package/dist/src/commands/verify/engines-advice.js +9 -56
- package/dist/src/commands/verify/index.d.ts +34 -33
- package/dist/src/commands/verify/index.js +96 -204
- package/dist/src/commands/verify/node-modules-source.d.ts +1 -1
- package/dist/src/commands/verify/node-modules-source.js +1 -1
- package/dist/src/commands/verify/prebuilds.d.ts +4 -6
- package/dist/src/commands/verify/prebuilds.js +3 -4
- package/dist/src/commands/verify/resource-collectors.d.ts +0 -6
- package/dist/src/commands/verify/resource-collectors.js +3 -52
- package/dist/src/commands/verify/sidecar-runtime.d.ts +6 -0
- package/dist/src/commands/verify/sidecar-runtime.js +51 -0
- package/dist/src/expo/plugins/get-project-root.d.ts +1 -1
- package/dist/src/expo/plugins/withAndroidArchitecture.d.ts +1 -1
- package/dist/src/expo/plugins/withAndroidNdkVersion.d.ts +1 -1
- package/dist/src/expo/plugins/withAndroidNdkVersion.js +16 -10
- package/dist/src/expo/plugins/withBareKit.d.ts +59 -0
- package/dist/src/expo/plugins/withBareKit.js +204 -0
- package/dist/src/expo/plugins/withDeviceInfo.d.ts +1 -1
- package/dist/src/expo/plugins/withDeviceInfo.js +19 -5
- package/dist/src/expo/plugins/withMobileBundle.d.ts +5 -12
- package/dist/src/expo/plugins/withMobileBundle.js +38 -59
- package/dist/src/expo/plugins/withOpenCL.d.ts +1 -1
- package/dist/src/expo/plugins/withQvacSDK.d.ts +2 -1
- package/dist/src/expo/plugins/withQvacSDK.js +3 -0
- package/dist/src/index.d.ts +6 -5
- package/dist/src/index.js +10 -14
- package/dist/src/logging/addon.d.ts +1 -1
- package/dist/src/logging/base-logger.js +1 -1
- package/dist/src/logging/utils.js +11 -3
- package/dist/src/plugin-ids.d.ts +3 -1
- package/dist/src/plugin-ids.js +4 -0
- package/dist/src/schemas/public.d.ts +1 -1
- package/dist/src/schemas/public.js +1 -1
- package/dist/src/schemas/sdk-errors-client.d.ts +5 -6
- package/dist/src/schemas/sdk-errors-client.js +30 -36
- package/dist/src/schemas/sdk-errors-server.d.ts +12 -1
- package/dist/src/schemas/sdk-errors-server.js +65 -2
- package/dist/src/server/rpc/rpc-utils.d.ts +26 -0
- package/dist/src/server/rpc/rpc-utils.js +41 -0
- package/dist/src/utils/aggregate-events.d.ts +1 -1
- package/dist/src/utils/aggregate-events.js +2 -2
- package/dist/src/utils/errors-client.d.ts +37 -29
- package/dist/src/utils/errors-client.js +50 -41
- package/dist/src/utils/errors-server.d.ts +65 -1
- package/dist/src/utils/errors-server.js +122 -1
- package/dist/src/utils/mcp-adapter.d.ts +1 -1
- package/dist/src/utils/mcp-adapter.js +1 -1
- package/dist/src/utils/tool-helpers.js +1 -1
- package/dist/src/utils/withTimeout.js +34 -17
- package/dist/src/worker/handle-request.js +26 -21
- package/dist/src/worker/handler-utils.d.ts +2 -6
- package/dist/src/worker/handler-utils.js +2 -20
- package/dist/src/worker/index.d.ts +2 -4
- package/dist/src/worker/index.js +24 -34
- package/dist/src/worker/plugins/ggml-image-embedding.d.ts +2 -0
- package/dist/src/worker/plugins/ggml-image-embedding.js +1 -0
- package/dist/src/worker/plugins/llamacpp-rerank.d.ts +2 -0
- package/dist/src/worker/plugins/llamacpp-rerank.js +1 -0
- package/dist/src/worker/shim.d.ts +4 -0
- package/dist/src/worker/shim.js +7 -0
- package/dist/src/worker/start.d.ts +9 -0
- package/dist/src/worker/start.js +16 -0
- package/dist/src/worker/unbundled-shim.d.ts +2 -0
- package/dist/src/worker/unbundled-shim.js +4 -0
- package/docs/system-resources-support-matrix.md +27 -19
- package/package.json +91 -74
- package/src/electron-forge/index.cjs +65 -91
- package/dist/examples/model-fit-ui/server.d.ts +0 -24
- package/dist/examples/model-fit-ui/server.js +0 -221
- package/dist/src/client/rpc/ensure-worker-ready.d.ts +0 -9
- package/dist/src/client/rpc/ensure-worker-ready.js +0 -17
- package/dist/src/client/rpc/init-timeout.d.ts +0 -26
- package/dist/src/client/rpc/init-timeout.js +0 -25
- package/dist/src/client/rpc/worker-startup-error.d.ts +0 -12
- package/dist/src/client/rpc/worker-startup-error.js +0 -13
- package/dist/src/commands/bundle/bare-pack.d.ts +0 -21
- package/dist/src/commands/bundle/bare-pack.js +0 -77
- package/dist/src/commands/bundle/manifest.d.ts +0 -25
- package/dist/src/commands/bundle/manifest.js +0 -192
- package/dist/src/expo/plugins/link-addons.d.ts +0 -18
- package/dist/src/expo/plugins/link-addons.js +0 -65
- package/dist/src/pear/pre.d.ts +0 -21
- package/dist/src/pear/pre.js +0 -448
- package/dist/src/server/env.d.ts +0 -22
- package/dist/src/server/env.js +0 -59
- package/dist/src/server/utils/qvac-paths.d.ts +0 -2
- package/dist/src/server/utils/qvac-paths.js +0 -5
- package/dist/src/server/utils/worker-lock.d.ts +0 -3
- package/dist/src/server/utils/worker-lock.js +0 -67
- package/dist/src/worker/create-server.d.ts +0 -8
- package/dist/src/worker/create-server.js +0 -51
- package/dist/src/worker/lifecycle.d.ts +0 -23
- package/dist/src/worker/lifecycle.js +0 -149
|
@@ -1,446 +1,369 @@
|
|
|
1
1
|
import RPC from 'bare-rpc';
|
|
2
|
-
import
|
|
3
|
-
import { randomBytes } from 'node:crypto';
|
|
4
|
-
import fs, { existsSync, unlinkSync } from 'node:fs';
|
|
5
|
-
import { createServer } from 'node:net';
|
|
2
|
+
import fs from 'node:fs';
|
|
6
3
|
import os from 'node:os';
|
|
7
4
|
import path from 'node:path';
|
|
8
|
-
import { fileURLToPath } from 'node:url';
|
|
9
|
-
import { initializeConfig } from '
|
|
10
|
-
import { resolveConfig } from '
|
|
11
|
-
import {
|
|
12
|
-
import {
|
|
13
|
-
import {
|
|
14
|
-
import {
|
|
15
|
-
|
|
5
|
+
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
6
|
+
import { initializeConfig } from '../../client/init-hooks.js';
|
|
7
|
+
import { resolveConfig } from '../../client/config-loader/resolve-config.node.js';
|
|
8
|
+
import { findInAncestorNodeModules } from '../../expo/plugins/find-in-ancestor-node-modules.js';
|
|
9
|
+
import { getClientLogger } from '../../logging/index.js';
|
|
10
|
+
import { WorkerCrashedError, WorkerFileNotFoundError, WorkerShutdownError, WorkerStartupError } from '../../utils/errors-client.js';
|
|
11
|
+
import { bundledSdkMismatch, bundledTarget, installedSdkVersion } from './bundle-stamp.js';
|
|
12
|
+
import { getPearRuntime } from './pear-runtime.js';
|
|
13
|
+
import { start as startUnbundled } from './unbundled-harness.js';
|
|
14
|
+
import { DEFAULT_WORKER_START_TIMEOUT_MS, rejectOnAbort, startDeadline, stderrTail, WORKER_SHUTDOWN_GRACE_MS, workerCrashed, workerStartupFailed } from './worker-failure.js';
|
|
16
15
|
const logger = getClientLogger();
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
const workerLogger = getLogger(SDK_SERVER_NAMESPACE, { enableConsole: false });
|
|
16
|
+
const STOWED_HARNESS = 'index.js';
|
|
17
|
+
const STOWED_BUNDLE = 'index.bundle';
|
|
20
18
|
let rpcInstance = null;
|
|
21
19
|
let rpcPromise = null;
|
|
22
|
-
let
|
|
23
|
-
let ipcServer = null;
|
|
24
|
-
let currentSocketPath = null;
|
|
20
|
+
let worker = null;
|
|
25
21
|
let closePromise = null;
|
|
26
|
-
//
|
|
27
|
-
//
|
|
28
|
-
|
|
29
|
-
//
|
|
22
|
+
// Bumped by close(); a start that finishes under an older generation stops its
|
|
23
|
+
// own worker, so a caller waiting on that start never receives a closed client.
|
|
24
|
+
let generation = 0;
|
|
25
|
+
// Aborted when the worker dies (crash) or close() runs (planned).
|
|
30
26
|
let workerLifeController = null;
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
*/
|
|
27
|
+
// Set while a worker is launching and not yet ready; close() aborts it.
|
|
28
|
+
let launchController = null;
|
|
29
|
+
const workerErrors = new WeakMap();
|
|
35
30
|
function findProjectRootSync() {
|
|
36
31
|
let dir = process.cwd();
|
|
37
32
|
const root = path.parse(dir).root;
|
|
38
33
|
while (dir !== root) {
|
|
39
|
-
if (fs.existsSync(path.join(dir, 'package.json')))
|
|
34
|
+
if (fs.existsSync(path.join(dir, 'package.json')))
|
|
40
35
|
return dir;
|
|
41
|
-
}
|
|
42
36
|
dir = path.dirname(dir);
|
|
43
37
|
}
|
|
44
38
|
return undefined;
|
|
45
39
|
}
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
40
|
+
/**
|
|
41
|
+
* The harness in `dir` when it holds a bundle for `target`. A bundle for
|
|
42
|
+
* another target is skipped with a warning; one that does not record its
|
|
43
|
+
* target is used.
|
|
44
|
+
*/
|
|
45
|
+
function stowedHarness(dir, target) {
|
|
46
|
+
const harness = path.join(dir, STOWED_HARNESS);
|
|
47
|
+
if (!fs.existsSync(harness) || !fs.existsSync(path.join(dir, STOWED_BUNDLE)))
|
|
48
|
+
return undefined;
|
|
49
|
+
const bundledFor = bundledTarget(dir);
|
|
50
|
+
if (bundledFor !== undefined && bundledFor !== target) {
|
|
51
|
+
logger.warn(`โ ๏ธ The worker in ${dir} was bundled for ${bundledFor}; this app runs ${target}. ` +
|
|
52
|
+
`Run \`qvac bundle sdk --target ${target}\` to use a bundled worker.`);
|
|
53
53
|
return undefined;
|
|
54
|
-
const candidates = [
|
|
55
|
-
path.join(resourcesPath, 'app.asar.unpacked', 'qvac', 'worker.entry.mjs'),
|
|
56
|
-
path.join(resourcesPath, 'app', 'qvac', 'worker.entry.mjs'),
|
|
57
|
-
path.join(resourcesPath, 'qvac', 'worker.entry.mjs')
|
|
58
|
-
];
|
|
59
|
-
for (const candidate of candidates) {
|
|
60
|
-
if (fs.existsSync(candidate))
|
|
61
|
-
return candidate;
|
|
62
54
|
}
|
|
63
|
-
|
|
55
|
+
const installed = installedSdkVersion();
|
|
56
|
+
const mismatch = installed === undefined ? null : bundledSdkMismatch(dir, installed);
|
|
57
|
+
if (mismatch)
|
|
58
|
+
logger.warn(`โ ๏ธ ${mismatch}`);
|
|
59
|
+
return harness;
|
|
60
|
+
}
|
|
61
|
+
function packagedWorkerDirs() {
|
|
62
|
+
const { resourcesPath } = process;
|
|
63
|
+
if (typeof resourcesPath !== 'string')
|
|
64
|
+
return [];
|
|
65
|
+
return [
|
|
66
|
+
path.join(resourcesPath, 'app.asar.unpacked', 'qvac', 'worker'),
|
|
67
|
+
path.join(resourcesPath, 'app', 'qvac', 'worker'),
|
|
68
|
+
path.join(resourcesPath, 'qvac', 'worker')
|
|
69
|
+
];
|
|
64
70
|
}
|
|
65
71
|
/**
|
|
66
|
-
*
|
|
67
|
-
*
|
|
68
|
-
*
|
|
69
|
-
* `dist/src/worker/index.js`; Bare cannot run the `@/`-laden source. This file
|
|
70
|
-
* compiles to `dist/src/client/rpc/node-rpc-client.js`, so the built worker sits
|
|
71
|
-
* at `../../worker/index.js` for both the dev and packaged layouts.
|
|
72
|
-
*
|
|
73
|
-
* `path.resolve(__dirname, ...)` is invisible to static analysis, so packaged
|
|
74
|
-
* consumers ship without the worker. We use `import.meta.asset(<literal>)` on
|
|
75
|
-
* Bare (detected by bare-module-lexer) and fall back to
|
|
76
|
-
* `new URL(<literal>, import.meta.url)` elsewhere. The spec must be a string
|
|
77
|
-
* literal at the call site.
|
|
72
|
+
* An asset reference keeps the file visible to bundlers of the host app:
|
|
73
|
+
* `import.meta.asset(<literal>)` on Bare, `new URL(<literal>, import.meta.url)`
|
|
74
|
+
* elsewhere. This module compiles to `dist/src/client/rpc/`.
|
|
78
75
|
*/
|
|
79
|
-
function
|
|
80
|
-
const
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
76
|
+
function sdkWorkerEntry() {
|
|
77
|
+
const asset = import.meta.asset;
|
|
78
|
+
return fileURLToPath(asset ? asset('../../worker/index.js') : new URL('../../worker/index.js', import.meta.url));
|
|
79
|
+
}
|
|
80
|
+
/** An entry that imports `worker-lifecycle` was generated by an older `@qvac/sdk`, which this one cannot run. */
|
|
81
|
+
function assertCurrentEntry(entry) {
|
|
82
|
+
if (!fs.readFileSync(entry, 'utf8').includes('/worker-lifecycle'))
|
|
83
|
+
return entry;
|
|
84
|
+
throw new WorkerStartupError(`${entry} was generated by an older @qvac/sdk. Run \`qvac bundle sdk\` again.`, { exitCode: null, exitSignal: null, timedOut: false });
|
|
85
85
|
}
|
|
86
86
|
/**
|
|
87
|
-
*
|
|
88
|
-
*
|
|
89
|
-
* 2. Packaged Electron app worker entry
|
|
90
|
-
* 3. qvac/worker.entry.mjs in project root (generated by npx qvac bundle sdk)
|
|
91
|
-
* 4. Default SDK worker
|
|
87
|
+
* With a Pear runtime registered, the `pear-runtime` bundle from
|
|
88
|
+
* QVAC_WORKER_PATH, the packaged app, or `qvac/worker/` in the project root.
|
|
92
89
|
*/
|
|
93
|
-
function
|
|
94
|
-
const
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
90
|
+
function resolvePearWorkerSource(pear) {
|
|
91
|
+
const envPath = process.env['QVAC_WORKER_PATH'];
|
|
92
|
+
const projectRoot = findProjectRootSync();
|
|
93
|
+
const projectWorkerDir = path.join(projectRoot ?? process.cwd(), 'qvac', 'worker');
|
|
94
|
+
if (envPath && fs.existsSync(envPath) && fs.statSync(envPath).isFile()) {
|
|
95
|
+
logger.warn(`โ ๏ธ QVAC_WORKER_PATH is a file, but a Pear app runs a bundled worker folder. Ignoring ${envPath}.`);
|
|
96
|
+
}
|
|
97
|
+
const dirs = [
|
|
98
|
+
...(envPath ? [path.resolve(envPath)] : []),
|
|
99
|
+
...packagedWorkerDirs(),
|
|
100
|
+
projectWorkerDir
|
|
101
|
+
];
|
|
102
|
+
for (const dir of dirs) {
|
|
103
|
+
const harness = stowedHarness(dir, 'pear-runtime');
|
|
104
|
+
if (harness) {
|
|
105
|
+
logger.info(`๐ง Using Pear worker: ${harness}`);
|
|
106
|
+
return { harness, pear };
|
|
100
107
|
}
|
|
101
|
-
logger.warn(`โ ๏ธ QVAC_WORKER_PATH was set but file was not found: ${normalized}. Falling back.`);
|
|
102
108
|
}
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
109
|
+
throw new WorkerFileNotFoundError(path.join(projectWorkerDir, STOWED_HARNESS));
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* The worker to start, in order:
|
|
113
|
+
* 1. QVAC_WORKER_PATH: a bundled worker folder, or a worker entry file
|
|
114
|
+
* 2. The packaged Electron app's bundled worker
|
|
115
|
+
* 3. `qvac/worker/` in the project root, written by `bundleSdk`
|
|
116
|
+
* 4. `qvac/worker.entry.mjs` in the project root, run unbundled
|
|
117
|
+
* 5. The SDK's default worker, run unbundled
|
|
118
|
+
*/
|
|
119
|
+
function resolveWorkerSource() {
|
|
120
|
+
const pear = getPearRuntime();
|
|
121
|
+
if (pear)
|
|
122
|
+
return resolvePearWorkerSource(pear);
|
|
123
|
+
const envPath = process.env['QVAC_WORKER_PATH'];
|
|
124
|
+
if (envPath) {
|
|
125
|
+
const resolved = path.resolve(envPath);
|
|
126
|
+
const harness = stowedHarness(resolved, 'bare-sidecar');
|
|
127
|
+
if (harness) {
|
|
128
|
+
logger.info(`๐ง Using bundled worker from QVAC_WORKER_PATH: ${resolved}`);
|
|
129
|
+
return { harness };
|
|
130
|
+
}
|
|
131
|
+
if (fs.existsSync(resolved) && fs.statSync(resolved).isFile()) {
|
|
132
|
+
logger.info(`๐ง Using worker entry from QVAC_WORKER_PATH: ${resolved}`);
|
|
133
|
+
return { entry: assertCurrentEntry(resolved) };
|
|
134
|
+
}
|
|
135
|
+
logger.warn(`โ ๏ธ QVAC_WORKER_PATH was set but no worker was found at ${resolved}. Falling back.`);
|
|
136
|
+
}
|
|
137
|
+
for (const dir of packagedWorkerDirs()) {
|
|
138
|
+
const harness = stowedHarness(dir, 'bare-sidecar');
|
|
139
|
+
if (harness) {
|
|
140
|
+
logger.info(`๐ง Using packaged worker: ${harness}`);
|
|
141
|
+
return { harness };
|
|
142
|
+
}
|
|
110
143
|
}
|
|
111
|
-
// Check for custom worker entry at project root
|
|
112
|
-
// Note: We use worker.entry.mjs (unbundled ESM) for desktop because bare can
|
|
113
|
-
// load ES modules directly. The packed bundle is for mobile only.
|
|
114
144
|
const projectRoot = findProjectRootSync();
|
|
115
145
|
if (projectRoot) {
|
|
116
|
-
const
|
|
117
|
-
if (
|
|
118
|
-
logger.info(`๐ง Using
|
|
119
|
-
return
|
|
146
|
+
const harness = stowedHarness(path.join(projectRoot, 'qvac', 'worker'), 'bare-sidecar');
|
|
147
|
+
if (harness) {
|
|
148
|
+
logger.info(`๐ง Using bundled worker: ${harness}`);
|
|
149
|
+
return { harness };
|
|
150
|
+
}
|
|
151
|
+
const entry = path.join(projectRoot, 'qvac', 'worker.entry.mjs');
|
|
152
|
+
if (fs.existsSync(entry)) {
|
|
153
|
+
logger.info(`๐ง Using worker entry: ${entry}`);
|
|
154
|
+
return { entry: assertCurrentEntry(entry) };
|
|
120
155
|
}
|
|
121
156
|
}
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
return defaultPath;
|
|
157
|
+
const entry = sdkWorkerEntry();
|
|
158
|
+
logger.debug(`๐ง Using default SDK worker: ${entry}`);
|
|
159
|
+
return { entry };
|
|
126
160
|
}
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
const randomSuffix = randomBytes(2).toString('hex');
|
|
131
|
-
const socketName = `qvac-worker-${process.pid}-${timestamp}-${randomSuffix}`;
|
|
132
|
-
return process.platform === 'win32'
|
|
133
|
-
? `\\\\.\\pipe\\${socketName}`
|
|
134
|
-
: path.join(os.tmpdir(), `${socketName}.sock`);
|
|
161
|
+
async function importHarness(file) {
|
|
162
|
+
const loaded = (await import(pathToFileURL(file).href));
|
|
163
|
+
return typeof loaded.start === 'function' ? loaded : loaded.default;
|
|
135
164
|
}
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
165
|
+
/**
|
|
166
|
+
* The config file, read before the worker starts because it sets the startup
|
|
167
|
+
* timeout. A config that fails to load is reported by `initializeConfig`,
|
|
168
|
+
* which reads it again.
|
|
169
|
+
*/
|
|
170
|
+
async function readConfigBeforeStart() {
|
|
140
171
|
try {
|
|
141
|
-
|
|
142
|
-
unlinkSync(socketPath);
|
|
143
|
-
}
|
|
172
|
+
return { config: await resolveConfig() };
|
|
144
173
|
}
|
|
145
174
|
catch (error) {
|
|
146
|
-
logger.debug('
|
|
175
|
+
logger.debug('Reading the config for the worker startup timeout failed; using the default', {
|
|
176
|
+
error
|
|
177
|
+
});
|
|
178
|
+
return null;
|
|
147
179
|
}
|
|
148
180
|
}
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
181
|
+
/**
|
|
182
|
+
* Spawns the bare-sidecar bundle next to `harnessFile` with stderr piped, and
|
|
183
|
+
* hands the process to the harness's `connect`. Without the bare-sidecar the
|
|
184
|
+
* harness imports, the harness starts it with stderr inherited.
|
|
185
|
+
*/
|
|
186
|
+
async function startBundled(harnessFile, harness, options, onStderr, onSpawn) {
|
|
187
|
+
const sidecarDir = findInAncestorNodeModules(path.dirname(harnessFile), 'bare-sidecar');
|
|
188
|
+
if (sidecarDir === null || harness.connect === undefined)
|
|
189
|
+
return harness.start(options);
|
|
190
|
+
const { default: Sidecar } = (await import(pathToFileURL(path.join(sidecarDir, 'index.js')).href));
|
|
191
|
+
const bundle = path.join(path.dirname(harnessFile), STOWED_BUNDLE);
|
|
192
|
+
const sidecar = new Sidecar(bundle, { stdio: ['inherit', 'inherit', 'pipe'] });
|
|
193
|
+
sidecar.stderr?.on('data', onStderr);
|
|
194
|
+
onSpawn(sidecar);
|
|
195
|
+
return harness.connect(sidecar, options);
|
|
154
196
|
}
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
197
|
+
/** `pear` with each process it runs passed to `onSpawn`. */
|
|
198
|
+
function pearReporting(pear, onSpawn) {
|
|
199
|
+
return {
|
|
200
|
+
run(...args) {
|
|
201
|
+
const child = pear.run(...args);
|
|
202
|
+
onSpawn(child);
|
|
203
|
+
return child;
|
|
204
|
+
}
|
|
205
|
+
};
|
|
162
206
|
}
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
207
|
+
/** Kills each spawned worker process once `signal` aborts. */
|
|
208
|
+
function killOnAbort(signal) {
|
|
209
|
+
return (child) => {
|
|
210
|
+
const kill = () => child.kill('SIGKILL');
|
|
211
|
+
if (signal.aborted)
|
|
212
|
+
kill();
|
|
213
|
+
else
|
|
214
|
+
signal.addEventListener('abort', kill, { once: true });
|
|
215
|
+
};
|
|
169
216
|
}
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
const { workerToClose, serverToClose, socketPathToClose } = snapshotAndResetState();
|
|
175
|
-
if (workerToClose) {
|
|
176
|
-
try {
|
|
177
|
-
workerToClose.kill('SIGTERM');
|
|
178
|
-
}
|
|
179
|
-
catch (error) {
|
|
180
|
-
logger.debug('Failed to kill bare worker after init failure', { error });
|
|
181
|
-
}
|
|
217
|
+
async function launchWorker(source, timeout, onStderr, onSpawn) {
|
|
218
|
+
const options = { timeout, grace: WORKER_SHUTDOWN_GRACE_MS };
|
|
219
|
+
if ('entry' in source) {
|
|
220
|
+
return (await startUnbundled(source.entry, { ...options, onStderr, onSpawn })).ipc;
|
|
182
221
|
}
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
}
|
|
187
|
-
catch (error) {
|
|
188
|
-
logger.debug('Failed to close IPC server after init failure', { error });
|
|
189
|
-
}
|
|
222
|
+
const harness = await importHarness(source.harness);
|
|
223
|
+
if ('pear' in source) {
|
|
224
|
+
return (await harness.start(pearReporting(source.pear, onSpawn), options)).ipc;
|
|
190
225
|
}
|
|
191
|
-
|
|
192
|
-
}
|
|
193
|
-
export function getWorkerLifeSignal() {
|
|
194
|
-
return workerLifeController?.signal ?? null;
|
|
226
|
+
return (await startBundled(source.harness, harness, options, onStderr, onSpawn)).ipc;
|
|
195
227
|
}
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
export function notifyChannelClosed() {
|
|
203
|
-
const controller = workerLifeController;
|
|
204
|
-
if (!controller || controller.signal.aborted)
|
|
205
|
-
return;
|
|
206
|
-
const { workerToClose, serverToClose, socketPathToClose } = snapshotAndResetState();
|
|
207
|
-
if (workerToClose) {
|
|
208
|
-
try {
|
|
209
|
-
workerToClose.kill('SIGTERM');
|
|
210
|
-
}
|
|
211
|
-
catch (error) {
|
|
212
|
-
logger.debug('Failed to kill bare worker after channel close', { error });
|
|
213
|
-
}
|
|
228
|
+
/** Starts the worker; aborting `signal` before it is ready kills the worker process. */
|
|
229
|
+
async function startWorker(source, timeout, signal) {
|
|
230
|
+
const stderr = stderrTail((text) => logger.debug(`[worker] ${text}`));
|
|
231
|
+
let ipc;
|
|
232
|
+
try {
|
|
233
|
+
ipc = await launchWorker(source, timeout, stderr.write, killOnAbort(signal));
|
|
214
234
|
}
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
serverToClose.close();
|
|
218
|
-
}
|
|
219
|
-
catch (error) {
|
|
220
|
-
logger.debug('Failed to close IPC server after channel close', { error });
|
|
221
|
-
}
|
|
235
|
+
catch (error) {
|
|
236
|
+
throw workerStartupFailed(error, stderr.read());
|
|
222
237
|
}
|
|
223
|
-
|
|
224
|
-
|
|
238
|
+
ipc.on('error', (error) => workerErrors.set(ipc, error));
|
|
239
|
+
return ipc;
|
|
225
240
|
}
|
|
226
|
-
function
|
|
227
|
-
|
|
241
|
+
function watchWorker(ipc, controller) {
|
|
242
|
+
let exitCode;
|
|
243
|
+
ipc.on('exit', (code) => {
|
|
244
|
+
exitCode = code;
|
|
245
|
+
});
|
|
246
|
+
ipc.on('close', () => {
|
|
247
|
+
if (controller.signal.aborted)
|
|
248
|
+
return;
|
|
249
|
+
logger.info(`๐ชฆ Bare worker ${exitCode === undefined ? 'closed' : 'exited'} unexpectedly`);
|
|
250
|
+
if (workerLifeController === controller)
|
|
251
|
+
resetModuleState();
|
|
252
|
+
controller.abort(workerCrashed(workerErrors.get(ipc) ?? { exitCode }));
|
|
253
|
+
});
|
|
228
254
|
}
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
return error instanceof Error ? error : new Error(message);
|
|
255
|
+
/** Stops `ipc` in the background; a start that follows waits for it. */
|
|
256
|
+
function stopInBackground(ipc) {
|
|
257
|
+
const stopping = ipc
|
|
258
|
+
.terminate()
|
|
259
|
+
.then(() => { }, () => { })
|
|
260
|
+
.finally(() => {
|
|
261
|
+
if (closePromise === stopping)
|
|
262
|
+
closePromise = null;
|
|
263
|
+
});
|
|
264
|
+
closePromise = stopping;
|
|
240
265
|
}
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
logger.debug(`Bare worker exited after planned shutdown (code=${code}, signal=${exitSignal})`);
|
|
247
|
-
return;
|
|
248
|
-
}
|
|
249
|
-
logger.info(`๐ชฆ Bare worker exited post-handshake (code=${code}, signal=${exitSignal})`);
|
|
250
|
-
// Only clear module state if we're still the active spawn.
|
|
251
|
-
if (workerLifeController === spawn.controller) {
|
|
252
|
-
resetModuleState();
|
|
253
|
-
}
|
|
254
|
-
try {
|
|
255
|
-
spawn.server.close();
|
|
256
|
-
}
|
|
257
|
-
catch (err) {
|
|
258
|
-
logger.debug('Failed to close IPC server after worker crash', { err });
|
|
259
|
-
}
|
|
260
|
-
spawn.controller.abort(new WorkerCrashedError(code, exitSignal));
|
|
261
|
-
bestEffortUnlinkSocket(spawn.socketPath);
|
|
266
|
+
function resetModuleState() {
|
|
267
|
+
rpcInstance = null;
|
|
268
|
+
rpcPromise = null;
|
|
269
|
+
worker = null;
|
|
270
|
+
workerLifeController = null;
|
|
262
271
|
}
|
|
263
|
-
function
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
272
|
+
async function ensureRPC() {
|
|
273
|
+
if (rpcInstance)
|
|
274
|
+
return rpcInstance;
|
|
275
|
+
if (rpcPromise)
|
|
276
|
+
return rpcPromise;
|
|
277
|
+
if (closePromise) {
|
|
278
|
+
await closePromise;
|
|
279
|
+
return ensureRPC();
|
|
280
|
+
}
|
|
281
|
+
const startGeneration = generation;
|
|
282
|
+
const attempt = (async () => {
|
|
283
|
+
const preloaded = await readConfigBeforeStart();
|
|
284
|
+
if (startGeneration !== generation)
|
|
285
|
+
throw new WorkerShutdownError();
|
|
286
|
+
const timeout = preloaded?.config?.rpcInitTimeoutMs ?? DEFAULT_WORKER_START_TIMEOUT_MS;
|
|
287
|
+
const launchedAt = Date.now();
|
|
288
|
+
const launch = new AbortController();
|
|
289
|
+
launchController = launch;
|
|
290
|
+
let started;
|
|
268
291
|
try {
|
|
269
|
-
|
|
292
|
+
started = await startWorker(resolveWorkerSource(), timeout, launch.signal);
|
|
270
293
|
}
|
|
271
294
|
catch (error) {
|
|
272
|
-
|
|
295
|
+
if (startGeneration !== generation)
|
|
296
|
+
throw new WorkerShutdownError(error);
|
|
297
|
+
throw error;
|
|
273
298
|
}
|
|
274
|
-
|
|
275
|
-
|
|
299
|
+
finally {
|
|
300
|
+
if (launchController === launch)
|
|
301
|
+
launchController = null;
|
|
302
|
+
}
|
|
303
|
+
if (startGeneration !== generation) {
|
|
304
|
+
await started.terminate();
|
|
305
|
+
throw new WorkerShutdownError();
|
|
306
|
+
}
|
|
307
|
+
const controller = new AbortController();
|
|
308
|
+
worker = started;
|
|
309
|
+
workerLifeController = controller;
|
|
310
|
+
watchWorker(started, controller);
|
|
311
|
+
const rpc = new RPC(started, () => { });
|
|
312
|
+
const runtimeContext = {
|
|
313
|
+
runtime: 'node',
|
|
314
|
+
platform: process.platform
|
|
315
|
+
};
|
|
316
|
+
// Snap's HOME can be revision-scoped; SNAP_USER_COMMON is stable.
|
|
317
|
+
const homeDir = process.env['SNAP_USER_COMMON'] ?? os.homedir();
|
|
318
|
+
const deadline = startDeadline(timeout - (Date.now() - launchedAt));
|
|
276
319
|
try {
|
|
277
|
-
|
|
320
|
+
await Promise.race([
|
|
321
|
+
initializeConfig(rpc, preloaded ? async () => preloaded.config : resolveConfig, runtimeContext, homeDir),
|
|
322
|
+
rejectOnAbort(controller.signal),
|
|
323
|
+
deadline.expired
|
|
324
|
+
]);
|
|
278
325
|
}
|
|
279
|
-
|
|
280
|
-
|
|
326
|
+
finally {
|
|
327
|
+
deadline.clear();
|
|
281
328
|
}
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
* the same object to init-hooks so the file is not parsed twice.
|
|
291
|
-
*
|
|
292
|
-
* A config that fails to load is swallowed here. init-hooks re-runs the
|
|
293
|
-
* resolver post-handshake, so the config error surfaces there rather than as a
|
|
294
|
-
* spawn failure.
|
|
295
|
-
*/
|
|
296
|
-
async function preresolveConfig() {
|
|
329
|
+
if (startGeneration !== generation)
|
|
330
|
+
throw new WorkerShutdownError();
|
|
331
|
+
if (controller.signal.aborted)
|
|
332
|
+
throw controller.signal.reason;
|
|
333
|
+
rpcInstance = rpc;
|
|
334
|
+
return rpc;
|
|
335
|
+
})();
|
|
336
|
+
rpcPromise = attempt;
|
|
297
337
|
try {
|
|
298
|
-
return await
|
|
338
|
+
return await attempt;
|
|
299
339
|
}
|
|
300
340
|
catch (error) {
|
|
301
|
-
|
|
302
|
-
|
|
341
|
+
if (startGeneration === generation) {
|
|
342
|
+
const failed = worker;
|
|
343
|
+
const failedController = workerLifeController;
|
|
344
|
+
resetModuleState();
|
|
345
|
+
failedController?.abort(error);
|
|
346
|
+
if (failed)
|
|
347
|
+
stopInBackground(failed);
|
|
348
|
+
}
|
|
349
|
+
throw error;
|
|
303
350
|
}
|
|
304
351
|
}
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
return rpcInstance;
|
|
308
|
-
if (rpcPromise)
|
|
309
|
-
return rpcPromise;
|
|
310
|
-
if (closePromise) {
|
|
311
|
-
await closePromise;
|
|
312
|
-
}
|
|
313
|
-
const preresolved = await preresolveConfig();
|
|
314
|
-
const initTimeoutMs = resolveRPCInitTimeoutMs({
|
|
315
|
-
envValue: process.env[RPC_INIT_TIMEOUT_ENV_VAR],
|
|
316
|
-
configValue: preresolved === CONFIG_UNRESOLVED ? undefined : (preresolved?.rpcInitTimeoutMs ?? undefined),
|
|
317
|
-
onInvalidEnvValue: (value) => logger.warn(`Ignoring invalid ${RPC_INIT_TIMEOUT_ENV_VAR}=${value}; expected a positive integer of milliseconds`)
|
|
318
|
-
});
|
|
319
|
-
const socketPath = createSocketPath();
|
|
320
|
-
currentSocketPath = socketPath;
|
|
321
|
-
// Allocated here so the init race and exit handler share one controller.
|
|
322
|
-
const spawnController = new AbortController();
|
|
323
|
-
workerLifeController = spawnController;
|
|
324
|
-
rpcPromise = new Promise((resolve, reject) => {
|
|
325
|
-
let settled = false;
|
|
326
|
-
let workerStderrTail = '';
|
|
327
|
-
let workerExitBeforeHandshake = null;
|
|
328
|
-
const timer = setTimeout(() => {
|
|
329
|
-
if (settled)
|
|
330
|
-
return;
|
|
331
|
-
settled = true;
|
|
332
|
-
const cause = createRPCInitTimeoutCause(workerStderrTail, workerExitBeforeHandshake);
|
|
333
|
-
teardownFailedInit();
|
|
334
|
-
reject(new RPCInitTimeoutError(initTimeoutMs, cause));
|
|
335
|
-
}, initTimeoutMs);
|
|
336
|
-
ipcServer = createServer((socket) => {
|
|
337
|
-
if (settled)
|
|
338
|
-
return;
|
|
339
|
-
settled = true;
|
|
340
|
-
clearTimeout(timer);
|
|
341
|
-
rpcInstance = new RPC(socket, () => { });
|
|
342
|
-
resolve(rpcInstance);
|
|
343
|
-
});
|
|
344
|
-
ipcServer.on('error', (error) => {
|
|
345
|
-
if (settled)
|
|
346
|
-
return;
|
|
347
|
-
settled = true;
|
|
348
|
-
clearTimeout(timer);
|
|
349
|
-
teardownFailedInit();
|
|
350
|
-
reject(error);
|
|
351
|
-
});
|
|
352
|
-
ipcServer.listen(socketPath, () => {
|
|
353
|
-
const spawnResources = {
|
|
354
|
-
controller: spawnController,
|
|
355
|
-
server: ipcServer,
|
|
356
|
-
socketPath
|
|
357
|
-
};
|
|
358
|
-
try {
|
|
359
|
-
bareWorkerProc = spawn('bare', {
|
|
360
|
-
args: [
|
|
361
|
-
WORKER_PATH,
|
|
362
|
-
JSON.stringify({
|
|
363
|
-
QVAC_IPC_SOCKET_PATH: socketPath,
|
|
364
|
-
// Snap's HOME can be revision-scoped; SNAP_USER_COMMON is stable.
|
|
365
|
-
HOME_DIR: process.env['SNAP_USER_COMMON']
|
|
366
|
-
? String(process.env['SNAP_USER_COMMON'])
|
|
367
|
-
: os.homedir()
|
|
368
|
-
})
|
|
369
|
-
],
|
|
370
|
-
platform: process.platform,
|
|
371
|
-
arch: process.arch,
|
|
372
|
-
stdio: ['inherit', 'inherit', 'pipe']
|
|
373
|
-
});
|
|
374
|
-
}
|
|
375
|
-
catch (error) {
|
|
376
|
-
// `spawn` resolves the bare binary synchronously and can throw before
|
|
377
|
-
// the worker exists, so there is no process to emit "exit". Without
|
|
378
|
-
// this, the throw escapes the `listen` callback as an uncaught
|
|
379
|
-
// exception and crashes the host process.
|
|
380
|
-
if (settled)
|
|
381
|
-
return;
|
|
382
|
-
settled = true;
|
|
383
|
-
clearTimeout(timer);
|
|
384
|
-
teardownFailedInit();
|
|
385
|
-
reject(mapBareSpawnError(error));
|
|
386
|
-
return;
|
|
387
|
-
}
|
|
388
|
-
if (bareWorkerProc) {
|
|
389
|
-
getWorkerStderr(bareWorkerProc)?.on('data', (chunk) => {
|
|
390
|
-
const text = chunk.toString();
|
|
391
|
-
workerStderrTail = appendWorkerStderrTail(workerStderrTail, text);
|
|
392
|
-
for (const line of text.split('\n')) {
|
|
393
|
-
if (line.trim())
|
|
394
|
-
workerLogger.debug(line);
|
|
395
|
-
}
|
|
396
|
-
});
|
|
397
|
-
bareWorkerProc.on('exit', (code, exitSignal) => {
|
|
398
|
-
if (settled) {
|
|
399
|
-
handlePostHandshakeExit(code, exitSignal, spawnResources);
|
|
400
|
-
return;
|
|
401
|
-
}
|
|
402
|
-
// Keep waiting for "close" so piped stderr can drain, but retain the
|
|
403
|
-
// exit status in case a slow stream (for example, a core dump) lets
|
|
404
|
-
// the initialization timer win that race.
|
|
405
|
-
workerExitBeforeHandshake = { code, signal: exitSignal };
|
|
406
|
-
});
|
|
407
|
-
bareWorkerProc.on('close', (...args) => {
|
|
408
|
-
if (settled)
|
|
409
|
-
return;
|
|
410
|
-
const code = typeof args[0] === 'number' ? args[0] : null;
|
|
411
|
-
const exitSignal = typeof args[1] === 'string' ? args[1] : null;
|
|
412
|
-
// Worker died before handshake. Use close, not exit, so piped
|
|
413
|
-
// stderr has drained before we build the error cause.
|
|
414
|
-
settled = true;
|
|
415
|
-
clearTimeout(timer);
|
|
416
|
-
teardownFailedInit();
|
|
417
|
-
reject(new RPCInitTimeoutError(initTimeoutMs, createRPCInitTimeoutCause(workerStderrTail, { code, signal: exitSignal })));
|
|
418
|
-
});
|
|
419
|
-
}
|
|
420
|
-
});
|
|
421
|
-
});
|
|
422
|
-
const rpc = await rpcPromise;
|
|
423
|
-
const runtimeContext = {
|
|
424
|
-
runtime: 'node',
|
|
425
|
-
platform: process.platform
|
|
426
|
-
};
|
|
427
|
-
// init-hooks calls bare-rpc directly, bypassing rpc-client's race.
|
|
428
|
-
const resolveConfigForInit = preresolved === CONFIG_UNRESOLVED ? resolveConfig : async () => preresolved;
|
|
429
|
-
await Promise.race([
|
|
430
|
-
initializeConfig(rpc, resolveConfigForInit, runtimeContext),
|
|
431
|
-
rejectOnAbort(spawnController.signal)
|
|
432
|
-
]);
|
|
433
|
-
return rpc;
|
|
352
|
+
export function getWorkerLifeSignal() {
|
|
353
|
+
return workerLifeController?.signal ?? null;
|
|
434
354
|
}
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
355
|
+
// Called by the RPC layer when it sees the channel close under an in-flight
|
|
356
|
+
// call before the worker's `close` event arrives. Tears down now, so the next
|
|
357
|
+
// call starts a new worker. A no-op once the life signal has aborted.
|
|
358
|
+
export function notifyChannelClosed() {
|
|
359
|
+
const controller = workerLifeController;
|
|
360
|
+
if (!controller || controller.signal.aborted)
|
|
361
|
+
return;
|
|
362
|
+
const closed = worker;
|
|
363
|
+
resetModuleState();
|
|
364
|
+
controller.abort(workerCrashed(closed ? workerErrors.get(closed) : undefined));
|
|
365
|
+
if (closed)
|
|
366
|
+
stopInBackground(closed);
|
|
444
367
|
}
|
|
445
368
|
export async function getRPC() {
|
|
446
369
|
return ensureRPC();
|
|
@@ -450,24 +373,21 @@ export async function createDuplexSession(payload, commandId) {
|
|
|
450
373
|
const req = rpc.request(commandId);
|
|
451
374
|
const requestStream = req.createRequestStream();
|
|
452
375
|
const responseStream = req.createResponseStream({ encoding: 'utf-8' });
|
|
376
|
+
// bare-rpc cancels the request when the response stream closes first, which
|
|
377
|
+
// destroys this stream with CANCELLED. Consumers read errors from the
|
|
378
|
+
// response stream, so pass the error there instead of throwing it uncaught.
|
|
379
|
+
requestStream.on('error', (error) => responseStream.destroy(error));
|
|
453
380
|
requestStream.write(payload, 'utf-8');
|
|
454
381
|
// Destroy on worker death so consumers' for-await throws instead of hangs.
|
|
455
382
|
const lifeSignal = workerLifeController?.signal;
|
|
456
383
|
if (lifeSignal && !lifeSignal.aborted) {
|
|
457
384
|
const onAbort = () => {
|
|
458
385
|
const err = lifeSignal.reason instanceof Error ? lifeSignal.reason : new WorkerCrashedError(null, null);
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
requestStream.destroy?.(err);
|
|
462
|
-
}
|
|
463
|
-
catch { }
|
|
464
|
-
try {
|
|
465
|
-
;
|
|
466
|
-
responseStream.destroy?.(err);
|
|
467
|
-
}
|
|
468
|
-
catch { }
|
|
386
|
+
requestStream.destroy(err);
|
|
387
|
+
responseStream.destroy(err);
|
|
469
388
|
};
|
|
470
389
|
lifeSignal.addEventListener('abort', onAbort, { once: true });
|
|
390
|
+
responseStream.once('close', () => lifeSignal.removeEventListener('abort', onAbort));
|
|
471
391
|
}
|
|
472
392
|
return { requestStream, responseStream };
|
|
473
393
|
}
|
|
@@ -476,36 +396,23 @@ export async function close() {
|
|
|
476
396
|
await closePromise;
|
|
477
397
|
return;
|
|
478
398
|
}
|
|
479
|
-
|
|
480
|
-
return;
|
|
481
|
-
logger.info('๐งน Closing RPC client');
|
|
482
|
-
// Abort before kill: exit handler sees planned intent; any in-flight
|
|
483
|
-
// caller (contract violators) rejects with WorkerShutdownError.
|
|
484
|
-
workerLifeController?.abort(new WorkerShutdownError());
|
|
485
|
-
const { workerToClose, serverToClose, socketPathToClose } = snapshotAndResetState();
|
|
399
|
+
generation++;
|
|
486
400
|
closePromise = (async () => {
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
}
|
|
496
|
-
if (serverToClose) {
|
|
497
|
-
logger.info('๐ Closing IPC server');
|
|
498
|
-
await new Promise((resolve) => {
|
|
499
|
-
try {
|
|
500
|
-
serverToClose.close(() => resolve());
|
|
501
|
-
}
|
|
502
|
-
catch (error) {
|
|
503
|
-
logger.debug('Failed to close IPC server', { error });
|
|
504
|
-
resolve();
|
|
505
|
-
}
|
|
506
|
-
});
|
|
401
|
+
const closing = worker;
|
|
402
|
+
if (!closing) {
|
|
403
|
+
const pending = rpcPromise;
|
|
404
|
+
rpcPromise = null;
|
|
405
|
+
launchController?.abort();
|
|
406
|
+
launchController = null;
|
|
407
|
+
await pending?.catch(() => { });
|
|
408
|
+
return;
|
|
507
409
|
}
|
|
508
|
-
|
|
410
|
+
logger.info('๐งน Closing RPC client');
|
|
411
|
+
// Abort before terminating: the close handler sees planned intent, and any
|
|
412
|
+
// in-flight caller rejects with WorkerShutdownError.
|
|
413
|
+
workerLifeController?.abort(new WorkerShutdownError());
|
|
414
|
+
resetModuleState();
|
|
415
|
+
await closing.terminate();
|
|
509
416
|
})();
|
|
510
417
|
try {
|
|
511
418
|
await closePromise;
|
|
@@ -514,12 +421,3 @@ export async function close() {
|
|
|
514
421
|
closePromise = null;
|
|
515
422
|
}
|
|
516
423
|
}
|
|
517
|
-
function handleTerminationSignal(signal) {
|
|
518
|
-
logger.info(`Received ${signal}, closing RPC resources...`);
|
|
519
|
-
closeSyncForExit();
|
|
520
|
-
process.kill(process.pid, signal);
|
|
521
|
-
}
|
|
522
|
-
process.once('SIGINT', () => handleTerminationSignal('SIGINT'));
|
|
523
|
-
process.once('SIGTERM', () => handleTerminationSignal('SIGTERM'));
|
|
524
|
-
process.once('SIGHUP', () => handleTerminationSignal('SIGHUP'));
|
|
525
|
-
process.once('exit', closeSyncForExit);
|