@camstack/kernel 0.1.1
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/addon-installer-RE7RJMVP.mjs +8 -0
- package/dist/addon-installer-RE7RJMVP.mjs.map +1 -0
- package/dist/chunk-BJTO5JO5.mjs +11 -0
- package/dist/chunk-BJTO5JO5.mjs.map +1 -0
- package/dist/chunk-REHQJR3P.mjs +387 -0
- package/dist/chunk-REHQJR3P.mjs.map +1 -0
- package/dist/chunk-S5YWNNPK.mjs +135 -0
- package/dist/chunk-S5YWNNPK.mjs.map +1 -0
- package/dist/index.d.mts +641 -0
- package/dist/index.d.ts +641 -0
- package/dist/index.js +1833 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +1290 -0
- package/dist/index.mjs.map +1 -0
- package/dist/worker/addon-worker-entry.d.mts +2 -0
- package/dist/worker/addon-worker-entry.d.ts +2 -0
- package/dist/worker/addon-worker-entry.js +688 -0
- package/dist/worker/addon-worker-entry.js.map +1 -0
- package/dist/worker/addon-worker-entry.mjs +194 -0
- package/dist/worker/addon-worker-entry.mjs.map +1 -0
- package/package.json +46 -0
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,1290 @@
|
|
|
1
|
+
import {
|
|
2
|
+
WorkerProcessManager
|
|
3
|
+
} from "./chunk-S5YWNNPK.mjs";
|
|
4
|
+
import {
|
|
5
|
+
AddonInstaller,
|
|
6
|
+
copyDirRecursive,
|
|
7
|
+
copyExtraFileDirs,
|
|
8
|
+
ensureDir,
|
|
9
|
+
ensureLibraryBuilt,
|
|
10
|
+
installPackageFromNpmSync,
|
|
11
|
+
isSourceNewer,
|
|
12
|
+
stripCamstackDeps,
|
|
13
|
+
symlinkAddonsToNodeModules
|
|
14
|
+
} from "./chunk-REHQJR3P.mjs";
|
|
15
|
+
import "./chunk-BJTO5JO5.mjs";
|
|
16
|
+
|
|
17
|
+
// src/addon-loader.ts
|
|
18
|
+
import * as fs from "fs";
|
|
19
|
+
import * as path from "path";
|
|
20
|
+
function resolveAddonClass(mod) {
|
|
21
|
+
let candidate = mod["default"] ?? mod[Object.keys(mod)[0]];
|
|
22
|
+
if (candidate && typeof candidate === "object" && "default" in candidate) {
|
|
23
|
+
candidate = candidate["default"];
|
|
24
|
+
}
|
|
25
|
+
return typeof candidate === "function" ? candidate : void 0;
|
|
26
|
+
}
|
|
27
|
+
var AddonLoader = class {
|
|
28
|
+
addons = /* @__PURE__ */ new Map();
|
|
29
|
+
/** Scan addons directory and load all addon packages.
|
|
30
|
+
* Supports scoped layout: addons/@scope/package-name/ */
|
|
31
|
+
async loadFromDirectory(addonsDir) {
|
|
32
|
+
if (!fs.existsSync(addonsDir)) return;
|
|
33
|
+
const entries = fs.readdirSync(addonsDir, { withFileTypes: true });
|
|
34
|
+
for (const entry of entries) {
|
|
35
|
+
if (!entry.isDirectory()) continue;
|
|
36
|
+
if (entry.name.startsWith("@")) {
|
|
37
|
+
const scopeDir = path.join(addonsDir, entry.name);
|
|
38
|
+
const scopeEntries = fs.readdirSync(scopeDir, { withFileTypes: true });
|
|
39
|
+
for (const scopeEntry of scopeEntries) {
|
|
40
|
+
if (!scopeEntry.isDirectory()) continue;
|
|
41
|
+
await this.tryLoadAddon(path.join(scopeDir, scopeEntry.name));
|
|
42
|
+
}
|
|
43
|
+
continue;
|
|
44
|
+
}
|
|
45
|
+
await this.tryLoadAddon(path.join(addonsDir, entry.name));
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
async tryLoadAddon(addonDir) {
|
|
49
|
+
const pkgJsonPath = path.join(addonDir, "package.json");
|
|
50
|
+
if (!fs.existsSync(pkgJsonPath)) return;
|
|
51
|
+
try {
|
|
52
|
+
await this.loadFromAddonDir(addonDir);
|
|
53
|
+
} catch (err) {
|
|
54
|
+
console.warn(`Failed to load addon from ${addonDir}: ${err}`);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
/** Load addon from a specific directory (package.json + dist/) */
|
|
58
|
+
async loadFromAddonDir(addonDir) {
|
|
59
|
+
const pkgJsonPath = path.join(addonDir, "package.json");
|
|
60
|
+
const pkgJson = JSON.parse(fs.readFileSync(pkgJsonPath, "utf-8"));
|
|
61
|
+
const packageName = pkgJson["name"];
|
|
62
|
+
const packageVersion = pkgJson["version"] ?? "0.0.0";
|
|
63
|
+
const manifest = pkgJson["camstack"];
|
|
64
|
+
if (!manifest?.addons?.length) return;
|
|
65
|
+
for (const declaration of manifest.addons) {
|
|
66
|
+
const entryFile = declaration.entry.replace(/^\.\//, "").replace(/^src\//, "dist/").replace(/\.ts$/, ".js");
|
|
67
|
+
let entryPath = path.resolve(addonDir, entryFile);
|
|
68
|
+
if (!fs.existsSync(entryPath)) {
|
|
69
|
+
const base = entryPath.replace(/\.(js|cjs|mjs)$/, "");
|
|
70
|
+
const alternatives = [
|
|
71
|
+
`${base}.cjs`,
|
|
72
|
+
`${base}.mjs`,
|
|
73
|
+
path.resolve(addonDir, "dist", "index.js"),
|
|
74
|
+
path.resolve(addonDir, "dist", "index.cjs"),
|
|
75
|
+
path.resolve(addonDir, "dist", "index.mjs"),
|
|
76
|
+
path.resolve(addonDir, declaration.entry)
|
|
77
|
+
];
|
|
78
|
+
entryPath = alternatives.find((p) => fs.existsSync(p)) ?? entryPath;
|
|
79
|
+
}
|
|
80
|
+
if (!fs.existsSync(entryPath)) {
|
|
81
|
+
throw new Error(`Entry not found: ${entryPath}`);
|
|
82
|
+
}
|
|
83
|
+
const mod = await import(entryPath);
|
|
84
|
+
const AddonClass = resolveAddonClass(mod);
|
|
85
|
+
if (!AddonClass) {
|
|
86
|
+
throw new Error(`No addon class in ${entryPath}`);
|
|
87
|
+
}
|
|
88
|
+
this.addons.set(declaration.id, {
|
|
89
|
+
declaration,
|
|
90
|
+
packageName,
|
|
91
|
+
packageVersion,
|
|
92
|
+
addonClass: AddonClass
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
/** Load addon from a direct path (for development/testing) */
|
|
97
|
+
async loadFromPath(addonId, modulePath, packageName, declaration, packageVersion = "0.0.0") {
|
|
98
|
+
const mod = await import(modulePath);
|
|
99
|
+
const AddonClass = resolveAddonClass(mod);
|
|
100
|
+
if (!AddonClass) {
|
|
101
|
+
throw new Error(`Module ${modulePath} has no default export`);
|
|
102
|
+
}
|
|
103
|
+
this.addons.set(addonId, {
|
|
104
|
+
declaration: {
|
|
105
|
+
id: addonId,
|
|
106
|
+
entry: modulePath,
|
|
107
|
+
slot: "detector",
|
|
108
|
+
...declaration
|
|
109
|
+
},
|
|
110
|
+
packageName,
|
|
111
|
+
packageVersion,
|
|
112
|
+
addonClass: AddonClass
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
/** Get a registered addon by ID */
|
|
116
|
+
getAddon(addonId) {
|
|
117
|
+
return this.addons.get(addonId);
|
|
118
|
+
}
|
|
119
|
+
/** List all registered addons */
|
|
120
|
+
listAddons() {
|
|
121
|
+
return [...this.addons.values()];
|
|
122
|
+
}
|
|
123
|
+
/** Check if an addon is registered */
|
|
124
|
+
hasAddon(addonId) {
|
|
125
|
+
return this.addons.has(addonId);
|
|
126
|
+
}
|
|
127
|
+
/** Create a new instance of an addon (not yet initialized) */
|
|
128
|
+
createInstance(addonId) {
|
|
129
|
+
const registered = this.addons.get(addonId);
|
|
130
|
+
if (!registered) {
|
|
131
|
+
throw new Error(`Addon "${addonId}" is not registered`);
|
|
132
|
+
}
|
|
133
|
+
return new registered.addonClass();
|
|
134
|
+
}
|
|
135
|
+
};
|
|
136
|
+
|
|
137
|
+
// src/addon-engine-manager.ts
|
|
138
|
+
import { createHash } from "crypto";
|
|
139
|
+
var AddonEngineManager = class {
|
|
140
|
+
constructor(loader, baseContext) {
|
|
141
|
+
this.loader = loader;
|
|
142
|
+
this.baseContext = baseContext;
|
|
143
|
+
}
|
|
144
|
+
engines = /* @__PURE__ */ new Map();
|
|
145
|
+
/**
|
|
146
|
+
* Get or create an addon engine for the given effective config.
|
|
147
|
+
* Cameras with the same addonId + effective config share the same engine.
|
|
148
|
+
*/
|
|
149
|
+
async getOrCreateEngine(addonId, globalConfig, cameraOverride) {
|
|
150
|
+
const effectiveConfig = { ...globalConfig, ...cameraOverride };
|
|
151
|
+
const configKey = `${addonId}:${this.hashConfig(effectiveConfig)}`;
|
|
152
|
+
const existing = this.engines.get(configKey);
|
|
153
|
+
if (existing) return existing;
|
|
154
|
+
const addon = this.loader.createInstance(addonId);
|
|
155
|
+
await addon.initialize({ ...this.baseContext, addonConfig: effectiveConfig });
|
|
156
|
+
this.engines.set(configKey, addon);
|
|
157
|
+
return addon;
|
|
158
|
+
}
|
|
159
|
+
/** Get all active engines */
|
|
160
|
+
getActiveEngines() {
|
|
161
|
+
return new Map(this.engines);
|
|
162
|
+
}
|
|
163
|
+
/** Shutdown a specific engine by its config key */
|
|
164
|
+
async shutdownEngine(configKey) {
|
|
165
|
+
const engine = this.engines.get(configKey);
|
|
166
|
+
if (engine) {
|
|
167
|
+
await engine.shutdown();
|
|
168
|
+
this.engines.delete(configKey);
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
/** Shutdown all engines */
|
|
172
|
+
async shutdownAll() {
|
|
173
|
+
for (const [, engine] of this.engines) {
|
|
174
|
+
await engine.shutdown();
|
|
175
|
+
}
|
|
176
|
+
this.engines.clear();
|
|
177
|
+
}
|
|
178
|
+
/** Compute a deterministic config key (visible for tests) */
|
|
179
|
+
computeConfigKey(addonId, effectiveConfig) {
|
|
180
|
+
return `${addonId}:${this.hashConfig(effectiveConfig)}`;
|
|
181
|
+
}
|
|
182
|
+
hashConfig(config) {
|
|
183
|
+
const sorted = JSON.stringify(config, Object.keys(config).sort());
|
|
184
|
+
return createHash("md5").update(sorted).digest("hex").slice(0, 12);
|
|
185
|
+
}
|
|
186
|
+
};
|
|
187
|
+
|
|
188
|
+
// src/workspace-detect.ts
|
|
189
|
+
import * as fs2 from "fs";
|
|
190
|
+
import * as path2 from "path";
|
|
191
|
+
function detectWorkspacePackagesDir(startDir) {
|
|
192
|
+
let current = path2.resolve(startDir);
|
|
193
|
+
for (let i = 0; i < 6; i++) {
|
|
194
|
+
current = path2.dirname(current);
|
|
195
|
+
const packagesDir = path2.join(current, "packages");
|
|
196
|
+
const rootPkgJson = path2.join(current, "package.json");
|
|
197
|
+
if (fs2.existsSync(packagesDir) && fs2.existsSync(rootPkgJson)) {
|
|
198
|
+
try {
|
|
199
|
+
const rootPkg = JSON.parse(fs2.readFileSync(rootPkgJson, "utf-8"));
|
|
200
|
+
if (rootPkg.workspaces || rootPkg.name === "camstack-server" || rootPkg.name === "camstack") {
|
|
201
|
+
return packagesDir;
|
|
202
|
+
}
|
|
203
|
+
} catch {
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
return null;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
// src/capability-registry.ts
|
|
211
|
+
var CapabilityRegistry = class {
|
|
212
|
+
constructor(logger, configReader) {
|
|
213
|
+
this.logger = logger;
|
|
214
|
+
this.configReader = configReader;
|
|
215
|
+
}
|
|
216
|
+
capabilities = /* @__PURE__ */ new Map();
|
|
217
|
+
/** Per-device singleton overrides: deviceId → (capability → addonId) */
|
|
218
|
+
deviceOverrides = /* @__PURE__ */ new Map();
|
|
219
|
+
/** Per-device collection filters: deviceId → (capability → addonIds[]) */
|
|
220
|
+
deviceCollectionFilters = /* @__PURE__ */ new Map();
|
|
221
|
+
/**
|
|
222
|
+
* Declare a capability (typically called when addon manifests are loaded).
|
|
223
|
+
* Must be called before registerProvider/registerConsumer for that capability.
|
|
224
|
+
*/
|
|
225
|
+
declareCapability(declaration) {
|
|
226
|
+
if (this.capabilities.has(declaration.name)) {
|
|
227
|
+
this.logger.debug(`Capability "${declaration.name}" already declared, skipping`);
|
|
228
|
+
return;
|
|
229
|
+
}
|
|
230
|
+
this.capabilities.set(declaration.name, {
|
|
231
|
+
declaration,
|
|
232
|
+
available: /* @__PURE__ */ new Map(),
|
|
233
|
+
activeAddonId: null,
|
|
234
|
+
activeProvider: null,
|
|
235
|
+
activeCollection: [],
|
|
236
|
+
consumers: /* @__PURE__ */ new Set()
|
|
237
|
+
});
|
|
238
|
+
this.logger.debug(`Capability declared: ${declaration.name} (mode=${declaration.mode})`);
|
|
239
|
+
}
|
|
240
|
+
/**
|
|
241
|
+
* Register a capability provider (called by addon loader when addon is enabled).
|
|
242
|
+
* For singleton: auto-activates if user-preferred or first registered.
|
|
243
|
+
* For collection: adds to active set and notifies consumers.
|
|
244
|
+
*/
|
|
245
|
+
registerProvider(capability, addonId, provider) {
|
|
246
|
+
const state = this.capabilities.get(capability);
|
|
247
|
+
if (!state) {
|
|
248
|
+
this.logger.warn(`Cannot register provider for undeclared capability "${capability}"`);
|
|
249
|
+
return;
|
|
250
|
+
}
|
|
251
|
+
state.available.set(addonId, provider);
|
|
252
|
+
this.logger.info(`Provider registered: ${addonId} \u2192 ${capability}`);
|
|
253
|
+
if (state.declaration.mode === "singleton") {
|
|
254
|
+
const userChoice = this.configReader(capability);
|
|
255
|
+
if (userChoice === addonId) {
|
|
256
|
+
this.activateSingleton(state, addonId, provider);
|
|
257
|
+
} else if (userChoice === void 0 && state.activeAddonId === null) {
|
|
258
|
+
this.activateSingleton(state, addonId, provider);
|
|
259
|
+
}
|
|
260
|
+
} else {
|
|
261
|
+
state.activeCollection.push({ addonId, provider });
|
|
262
|
+
for (const consumer of state.consumers) {
|
|
263
|
+
if (consumer.onAdded) {
|
|
264
|
+
try {
|
|
265
|
+
consumer.onAdded(provider);
|
|
266
|
+
} catch (error) {
|
|
267
|
+
const msg = error instanceof Error ? error.message : String(error);
|
|
268
|
+
this.logger.error(`Consumer onAdded failed for ${capability}: ${msg}`);
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
/**
|
|
275
|
+
* Unregister a provider (called when addon is disabled/uninstalled).
|
|
276
|
+
*/
|
|
277
|
+
unregisterProvider(capability, addonId) {
|
|
278
|
+
const state = this.capabilities.get(capability);
|
|
279
|
+
if (!state) return;
|
|
280
|
+
const provider = state.available.get(addonId);
|
|
281
|
+
state.available.delete(addonId);
|
|
282
|
+
if (state.declaration.mode === "singleton") {
|
|
283
|
+
if (state.activeAddonId === addonId) {
|
|
284
|
+
state.activeAddonId = null;
|
|
285
|
+
state.activeProvider = null;
|
|
286
|
+
this.logger.info(`Singleton deactivated: ${capability} (was ${addonId})`);
|
|
287
|
+
}
|
|
288
|
+
} else {
|
|
289
|
+
const idx = state.activeCollection.findIndex((e) => e.addonId === addonId);
|
|
290
|
+
if (idx !== -1) {
|
|
291
|
+
state.activeCollection.splice(idx, 1);
|
|
292
|
+
for (const consumer of state.consumers) {
|
|
293
|
+
if (consumer.onRemoved && provider !== void 0) {
|
|
294
|
+
try {
|
|
295
|
+
consumer.onRemoved(provider);
|
|
296
|
+
} catch (error) {
|
|
297
|
+
const msg = error instanceof Error ? error.message : String(error);
|
|
298
|
+
this.logger.error(`Consumer onRemoved failed for ${capability}: ${msg}`);
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
/**
|
|
306
|
+
* Register a consumer that wants to be notified when providers change.
|
|
307
|
+
* If a provider is already active, the consumer is immediately notified.
|
|
308
|
+
* Returns a disposer function for cleanup.
|
|
309
|
+
*/
|
|
310
|
+
registerConsumer(registration) {
|
|
311
|
+
const state = this.capabilities.get(registration.capability);
|
|
312
|
+
if (!state) {
|
|
313
|
+
this.logger.debug(`Consumer registered for undeclared capability "${registration.capability}" \u2014 auto-declaring`);
|
|
314
|
+
this.declareCapability({ name: registration.capability, mode: "singleton" });
|
|
315
|
+
return this.registerConsumer(registration);
|
|
316
|
+
}
|
|
317
|
+
const untypedReg = registration;
|
|
318
|
+
state.consumers.add(untypedReg);
|
|
319
|
+
if (state.declaration.mode === "singleton") {
|
|
320
|
+
if (state.activeProvider !== null && registration.onSet) {
|
|
321
|
+
try {
|
|
322
|
+
registration.onSet(state.activeProvider);
|
|
323
|
+
} catch (error) {
|
|
324
|
+
const msg = error instanceof Error ? error.message : String(error);
|
|
325
|
+
this.logger.error(`Consumer onSet (immediate) failed for ${registration.capability}: ${msg}`);
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
} else {
|
|
329
|
+
if (registration.onAdded) {
|
|
330
|
+
for (const entry of state.activeCollection) {
|
|
331
|
+
try {
|
|
332
|
+
registration.onAdded(entry.provider);
|
|
333
|
+
} catch (error) {
|
|
334
|
+
const msg = error instanceof Error ? error.message : String(error);
|
|
335
|
+
this.logger.error(`Consumer onAdded (immediate) failed for ${registration.capability}: ${msg}`);
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
return () => {
|
|
341
|
+
state.consumers.delete(untypedReg);
|
|
342
|
+
};
|
|
343
|
+
}
|
|
344
|
+
/**
|
|
345
|
+
* Get the active singleton provider for a capability.
|
|
346
|
+
* Returns null if none set.
|
|
347
|
+
*/
|
|
348
|
+
getSingleton(capability) {
|
|
349
|
+
const state = this.capabilities.get(capability);
|
|
350
|
+
if (!state || state.declaration.mode !== "singleton") return null;
|
|
351
|
+
return state.activeProvider ?? null;
|
|
352
|
+
}
|
|
353
|
+
/**
|
|
354
|
+
* Get all active collection providers for a capability.
|
|
355
|
+
*/
|
|
356
|
+
getCollection(capability) {
|
|
357
|
+
const state = this.capabilities.get(capability);
|
|
358
|
+
if (!state || state.declaration.mode !== "collection") return [];
|
|
359
|
+
return state.activeCollection.map((e) => e.provider);
|
|
360
|
+
}
|
|
361
|
+
/**
|
|
362
|
+
* Set which addon should be the active singleton for a capability.
|
|
363
|
+
* Call with `immediate: true` to also swap the runtime provider now
|
|
364
|
+
* (consumers' onSet will be awaited).
|
|
365
|
+
*/
|
|
366
|
+
async setActiveSingleton(capability, addonId, immediate = false) {
|
|
367
|
+
const state = this.capabilities.get(capability);
|
|
368
|
+
if (!state) {
|
|
369
|
+
throw new Error(`Unknown capability: ${capability}`);
|
|
370
|
+
}
|
|
371
|
+
if (state.declaration.mode !== "singleton") {
|
|
372
|
+
throw new Error(`Capability "${capability}" is not a singleton`);
|
|
373
|
+
}
|
|
374
|
+
const provider = state.available.get(addonId);
|
|
375
|
+
if (!provider) {
|
|
376
|
+
throw new Error(`No provider "${addonId}" registered for capability "${capability}"`);
|
|
377
|
+
}
|
|
378
|
+
if (immediate) {
|
|
379
|
+
await this.activateSingletonAsync(state, addonId, provider);
|
|
380
|
+
}
|
|
381
|
+
this.logger.info(`Singleton preference set: ${capability} \u2192 ${addonId}`);
|
|
382
|
+
}
|
|
383
|
+
/**
|
|
384
|
+
* Get the mode declared for a capability.
|
|
385
|
+
*/
|
|
386
|
+
getMode(capability) {
|
|
387
|
+
return this.capabilities.get(capability)?.declaration.mode;
|
|
388
|
+
}
|
|
389
|
+
/**
|
|
390
|
+
* List all registered capabilities with their providers.
|
|
391
|
+
*/
|
|
392
|
+
listCapabilities() {
|
|
393
|
+
const result = [];
|
|
394
|
+
for (const [name, state] of this.capabilities) {
|
|
395
|
+
result.push({
|
|
396
|
+
name,
|
|
397
|
+
mode: state.declaration.mode,
|
|
398
|
+
providers: [...state.available.keys()],
|
|
399
|
+
activeProvider: state.activeAddonId
|
|
400
|
+
});
|
|
401
|
+
}
|
|
402
|
+
return result;
|
|
403
|
+
}
|
|
404
|
+
/**
|
|
405
|
+
* Check if all dependencies for a capability are satisfied (have active providers).
|
|
406
|
+
*/
|
|
407
|
+
areDependenciesMet(declaration) {
|
|
408
|
+
if (!declaration.dependsOn?.length) return true;
|
|
409
|
+
return declaration.dependsOn.every((dep) => {
|
|
410
|
+
const state = this.capabilities.get(dep);
|
|
411
|
+
if (!state) return false;
|
|
412
|
+
if (state.declaration.mode === "singleton") {
|
|
413
|
+
return state.activeProvider !== null;
|
|
414
|
+
}
|
|
415
|
+
return state.activeCollection.length > 0;
|
|
416
|
+
});
|
|
417
|
+
}
|
|
418
|
+
/**
|
|
419
|
+
* Get the dependency-ordered list of capability names for boot sequencing.
|
|
420
|
+
* Returns capabilities sorted topologically by dependsOn.
|
|
421
|
+
* Throws if a cycle is detected.
|
|
422
|
+
*/
|
|
423
|
+
getBootOrder() {
|
|
424
|
+
const visited = /* @__PURE__ */ new Set();
|
|
425
|
+
const visiting = /* @__PURE__ */ new Set();
|
|
426
|
+
const order = [];
|
|
427
|
+
const visit = (name) => {
|
|
428
|
+
if (visited.has(name)) return;
|
|
429
|
+
if (visiting.has(name)) {
|
|
430
|
+
throw new Error(`Circular dependency detected involving capability "${name}"`);
|
|
431
|
+
}
|
|
432
|
+
visiting.add(name);
|
|
433
|
+
const state = this.capabilities.get(name);
|
|
434
|
+
if (state?.declaration.dependsOn) {
|
|
435
|
+
for (const dep of state.declaration.dependsOn) {
|
|
436
|
+
visit(dep);
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
visiting.delete(name);
|
|
440
|
+
visited.add(name);
|
|
441
|
+
order.push(name);
|
|
442
|
+
};
|
|
443
|
+
for (const name of this.capabilities.keys()) {
|
|
444
|
+
visit(name);
|
|
445
|
+
}
|
|
446
|
+
return order;
|
|
447
|
+
}
|
|
448
|
+
// ---- Per-device overrides ----
|
|
449
|
+
/**
|
|
450
|
+
* Set a per-device singleton override. When resolveForDevice is called for
|
|
451
|
+
* this device + capability, the specified addon's provider is returned
|
|
452
|
+
* instead of the global singleton.
|
|
453
|
+
*/
|
|
454
|
+
setDeviceOverride(deviceId, capability, addonId) {
|
|
455
|
+
const state = this.capabilities.get(capability);
|
|
456
|
+
if (!state) {
|
|
457
|
+
this.logger.warn(`Cannot set device override for undeclared capability "${capability}"`);
|
|
458
|
+
return;
|
|
459
|
+
}
|
|
460
|
+
if (!state.available.has(addonId)) {
|
|
461
|
+
this.logger.warn(`Cannot set device override: addon "${addonId}" not registered for "${capability}"`);
|
|
462
|
+
return;
|
|
463
|
+
}
|
|
464
|
+
let deviceMap = this.deviceOverrides.get(deviceId);
|
|
465
|
+
if (!deviceMap) {
|
|
466
|
+
deviceMap = /* @__PURE__ */ new Map();
|
|
467
|
+
this.deviceOverrides.set(deviceId, deviceMap);
|
|
468
|
+
}
|
|
469
|
+
deviceMap.set(capability, addonId);
|
|
470
|
+
this.logger.info(`Device override set: ${deviceId} \u2192 ${capability} = ${addonId}`);
|
|
471
|
+
}
|
|
472
|
+
/**
|
|
473
|
+
* Clear a per-device singleton override, reverting to the global singleton.
|
|
474
|
+
*/
|
|
475
|
+
clearDeviceOverride(deviceId, capability) {
|
|
476
|
+
const deviceMap = this.deviceOverrides.get(deviceId);
|
|
477
|
+
if (!deviceMap) return;
|
|
478
|
+
deviceMap.delete(capability);
|
|
479
|
+
if (deviceMap.size === 0) {
|
|
480
|
+
this.deviceOverrides.delete(deviceId);
|
|
481
|
+
}
|
|
482
|
+
this.logger.info(`Device override cleared: ${deviceId} \u2192 ${capability}`);
|
|
483
|
+
}
|
|
484
|
+
/**
|
|
485
|
+
* Get all per-device singleton overrides for a device.
|
|
486
|
+
* Returns a Map of capability name to addon ID.
|
|
487
|
+
*/
|
|
488
|
+
getDeviceOverrides(deviceId) {
|
|
489
|
+
return new Map(this.deviceOverrides.get(deviceId) ?? []);
|
|
490
|
+
}
|
|
491
|
+
/**
|
|
492
|
+
* Resolve a singleton provider for a specific device.
|
|
493
|
+
* 1. Check device override — return that addon's provider
|
|
494
|
+
* 2. Fallback to global singleton
|
|
495
|
+
*/
|
|
496
|
+
resolveForDevice(capability, deviceId) {
|
|
497
|
+
const state = this.capabilities.get(capability);
|
|
498
|
+
if (!state || state.declaration.mode !== "singleton") return null;
|
|
499
|
+
const deviceMap = this.deviceOverrides.get(deviceId);
|
|
500
|
+
if (deviceMap) {
|
|
501
|
+
const overrideAddonId = deviceMap.get(capability);
|
|
502
|
+
if (overrideAddonId) {
|
|
503
|
+
const provider = state.available.get(overrideAddonId);
|
|
504
|
+
if (provider) return provider;
|
|
505
|
+
this.logger.warn(
|
|
506
|
+
`Device override for ${deviceId}/${capability} references unregistered addon "${overrideAddonId}" \u2014 falling back to global`
|
|
507
|
+
);
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
return state.activeProvider ?? null;
|
|
511
|
+
}
|
|
512
|
+
/**
|
|
513
|
+
* Set a per-device collection filter. When resolveCollectionForDevice is called
|
|
514
|
+
* for this device + capability, only providers from the specified addon IDs
|
|
515
|
+
* are returned instead of the full collection.
|
|
516
|
+
*/
|
|
517
|
+
setDeviceCollectionFilter(deviceId, capability, addonIds) {
|
|
518
|
+
const state = this.capabilities.get(capability);
|
|
519
|
+
if (!state) {
|
|
520
|
+
this.logger.warn(`Cannot set device collection filter for undeclared capability "${capability}"`);
|
|
521
|
+
return;
|
|
522
|
+
}
|
|
523
|
+
let deviceMap = this.deviceCollectionFilters.get(deviceId);
|
|
524
|
+
if (!deviceMap) {
|
|
525
|
+
deviceMap = /* @__PURE__ */ new Map();
|
|
526
|
+
this.deviceCollectionFilters.set(deviceId, deviceMap);
|
|
527
|
+
}
|
|
528
|
+
deviceMap.set(capability, [...addonIds]);
|
|
529
|
+
this.logger.info(`Device collection filter set: ${deviceId} \u2192 ${capability} = [${addonIds.join(", ")}]`);
|
|
530
|
+
}
|
|
531
|
+
/**
|
|
532
|
+
* Clear a per-device collection filter, reverting to the full collection.
|
|
533
|
+
*/
|
|
534
|
+
clearDeviceCollectionFilter(deviceId, capability) {
|
|
535
|
+
const deviceMap = this.deviceCollectionFilters.get(deviceId);
|
|
536
|
+
if (!deviceMap) return;
|
|
537
|
+
deviceMap.delete(capability);
|
|
538
|
+
if (deviceMap.size === 0) {
|
|
539
|
+
this.deviceCollectionFilters.delete(deviceId);
|
|
540
|
+
}
|
|
541
|
+
this.logger.info(`Device collection filter cleared: ${deviceId} \u2192 ${capability}`);
|
|
542
|
+
}
|
|
543
|
+
/**
|
|
544
|
+
* Resolve collection providers for a specific device.
|
|
545
|
+
* If a filter exists for the device + capability, only those addon's providers are returned.
|
|
546
|
+
* If no filter exists, the full collection is returned.
|
|
547
|
+
*/
|
|
548
|
+
resolveCollectionForDevice(capability, deviceId) {
|
|
549
|
+
const state = this.capabilities.get(capability);
|
|
550
|
+
if (!state || state.declaration.mode !== "collection") return [];
|
|
551
|
+
const deviceMap = this.deviceCollectionFilters.get(deviceId);
|
|
552
|
+
if (deviceMap) {
|
|
553
|
+
const filterAddonIds = deviceMap.get(capability);
|
|
554
|
+
if (filterAddonIds) {
|
|
555
|
+
const filterSet = new Set(filterAddonIds);
|
|
556
|
+
return state.activeCollection.filter((e) => filterSet.has(e.addonId)).map((e) => e.provider);
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
return state.activeCollection.map((e) => e.provider);
|
|
560
|
+
}
|
|
561
|
+
/**
|
|
562
|
+
* Get a specific addon's provider by addon ID, regardless of whether it's the active singleton.
|
|
563
|
+
* Useful for per-device overrides that need to look up any registered provider.
|
|
564
|
+
*/
|
|
565
|
+
getProviderByAddonId(capability, addonId) {
|
|
566
|
+
const state = this.capabilities.get(capability);
|
|
567
|
+
if (!state) return null;
|
|
568
|
+
const provider = state.available.get(addonId);
|
|
569
|
+
return provider ?? null;
|
|
570
|
+
}
|
|
571
|
+
activateSingleton(state, addonId, provider) {
|
|
572
|
+
state.activeAddonId = addonId;
|
|
573
|
+
state.activeProvider = provider;
|
|
574
|
+
this.logger.info(`Singleton activated: ${state.declaration.name} \u2192 ${addonId}`);
|
|
575
|
+
for (const consumer of state.consumers) {
|
|
576
|
+
if (consumer.onSet) {
|
|
577
|
+
try {
|
|
578
|
+
consumer.onSet(provider);
|
|
579
|
+
} catch (error) {
|
|
580
|
+
const msg = error instanceof Error ? error.message : String(error);
|
|
581
|
+
this.logger.error(`Consumer onSet failed for ${state.declaration.name}: ${msg}`);
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
async activateSingletonAsync(state, addonId, provider) {
|
|
587
|
+
state.activeAddonId = addonId;
|
|
588
|
+
state.activeProvider = provider;
|
|
589
|
+
this.logger.info(`Singleton activated (async): ${state.declaration.name} \u2192 ${addonId}`);
|
|
590
|
+
for (const consumer of state.consumers) {
|
|
591
|
+
if (consumer.onSet) {
|
|
592
|
+
try {
|
|
593
|
+
await consumer.onSet(provider);
|
|
594
|
+
} catch (error) {
|
|
595
|
+
const msg = error instanceof Error ? error.message : String(error);
|
|
596
|
+
this.logger.error(`Consumer onSet (async) failed for ${state.declaration.name}: ${msg}`);
|
|
597
|
+
}
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
};
|
|
602
|
+
|
|
603
|
+
// src/infra-capabilities.ts
|
|
604
|
+
var INFRA_CAPABILITIES = [
|
|
605
|
+
{ name: "storage", required: true },
|
|
606
|
+
{ name: "settings-store", required: true },
|
|
607
|
+
{ name: "log-destination", required: false }
|
|
608
|
+
];
|
|
609
|
+
var infraNames = new Set(INFRA_CAPABILITIES.map((c) => c.name));
|
|
610
|
+
function isInfraCapability(name) {
|
|
611
|
+
return infraNames.has(name);
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
// src/config-manager.ts
|
|
615
|
+
import * as fs3 from "fs";
|
|
616
|
+
import * as yaml from "js-yaml";
|
|
617
|
+
|
|
618
|
+
// src/config-schema.ts
|
|
619
|
+
import { z } from "zod";
|
|
620
|
+
var DEFAULT_DATA_PATH = "camstack-data";
|
|
621
|
+
var bootstrapSchema = z.object({
|
|
622
|
+
/** Server mode: 'hub' (full server) or 'agent' (worker node) */
|
|
623
|
+
mode: z.enum(["hub", "agent"]).default("hub"),
|
|
624
|
+
server: z.object({
|
|
625
|
+
port: z.number().default(4443),
|
|
626
|
+
host: z.string().default("0.0.0.0"),
|
|
627
|
+
dataPath: z.string().default(DEFAULT_DATA_PATH)
|
|
628
|
+
}).default({}),
|
|
629
|
+
auth: z.object({
|
|
630
|
+
jwtSecret: z.string().nullable().default(null),
|
|
631
|
+
adminUsername: z.string().default("admin"),
|
|
632
|
+
adminPassword: z.string().default(process.env.ADMIN_PASSWORD ?? "changeme")
|
|
633
|
+
}).default({}),
|
|
634
|
+
/** Hub connection config — only used when mode='agent' */
|
|
635
|
+
hub: z.object({
|
|
636
|
+
url: z.string().default("ws://localhost:4443/agent"),
|
|
637
|
+
token: z.string().default("")
|
|
638
|
+
}).default({}),
|
|
639
|
+
/** Agent-specific config — only used when mode='agent' */
|
|
640
|
+
agent: z.object({
|
|
641
|
+
name: z.string().default(""),
|
|
642
|
+
/** Port for the agent status page (minimal HTML) */
|
|
643
|
+
statusPort: z.number().default(4444)
|
|
644
|
+
}).default({}),
|
|
645
|
+
/** TLS configuration */
|
|
646
|
+
tls: z.object({
|
|
647
|
+
/** Enable HTTPS (default: true) */
|
|
648
|
+
enabled: z.boolean().default(true),
|
|
649
|
+
/** Path to custom cert file (PEM). If not set, auto-generates self-signed. */
|
|
650
|
+
certPath: z.string().optional(),
|
|
651
|
+
/** Path to custom key file (PEM). Required if certPath is set. */
|
|
652
|
+
keyPath: z.string().optional()
|
|
653
|
+
}).default({})
|
|
654
|
+
});
|
|
655
|
+
var RUNTIME_DEFAULTS = {
|
|
656
|
+
"features.streaming": true,
|
|
657
|
+
"features.notifications": true,
|
|
658
|
+
"features.objectDetection": false,
|
|
659
|
+
"features.remoteAccess": true,
|
|
660
|
+
"features.agentCluster": false,
|
|
661
|
+
"features.smartHome": true,
|
|
662
|
+
"features.recordings": true,
|
|
663
|
+
"features.backup": true,
|
|
664
|
+
"features.repl": true,
|
|
665
|
+
"retention.detectionEventsDays": 30,
|
|
666
|
+
"retention.audioLevelsDays": 7,
|
|
667
|
+
"logging.level": "info",
|
|
668
|
+
"logging.retentionDays": 30,
|
|
669
|
+
"eventBus.ringBufferSize": 1e4,
|
|
670
|
+
"storage.provider": "sqlite-storage",
|
|
671
|
+
"storage.locations": {
|
|
672
|
+
data: "camstack-data/data",
|
|
673
|
+
media: "camstack-data/media",
|
|
674
|
+
recordings: "camstack-data/recordings",
|
|
675
|
+
cache: "/tmp/camstack-cache",
|
|
676
|
+
logs: "camstack-data/logs",
|
|
677
|
+
models: "camstack-data/models"
|
|
678
|
+
},
|
|
679
|
+
"providers": [],
|
|
680
|
+
// Recording
|
|
681
|
+
"recording.segmentDurationSeconds": 4,
|
|
682
|
+
"recording.defaultRetentionDays": 30,
|
|
683
|
+
// Streaming ports are addon-specific (go2rtc owns its defaults)
|
|
684
|
+
// FFmpeg
|
|
685
|
+
"ffmpeg.binaryPath": "ffmpeg",
|
|
686
|
+
"ffmpeg.hwAccel": "auto",
|
|
687
|
+
"ffmpeg.threadCount": 0,
|
|
688
|
+
// Detection defaults
|
|
689
|
+
"detection.defaultMotionFps": 2,
|
|
690
|
+
"detection.defaultDetectionFps": 5,
|
|
691
|
+
"detection.defaultCooldownSeconds": 10,
|
|
692
|
+
"detection.defaultConfidenceThreshold": 0.4,
|
|
693
|
+
"detection.trackerMaxAgeFrames": 30,
|
|
694
|
+
"detection.trackerMinHits": 3,
|
|
695
|
+
"detection.trackerIouThreshold": 0.3,
|
|
696
|
+
// Backup retention is addon-specific (local-backup owns its default)
|
|
697
|
+
// Auth (runtime)
|
|
698
|
+
"auth.tokenExpiry": "24h"
|
|
699
|
+
};
|
|
700
|
+
|
|
701
|
+
// src/config-manager.ts
|
|
702
|
+
var ENV_VAR_MAP = {
|
|
703
|
+
CAMSTACK_PORT: "server.port",
|
|
704
|
+
CAMSTACK_HOST: "server.host",
|
|
705
|
+
CAMSTACK_DATA: "server.dataPath",
|
|
706
|
+
CAMSTACK_JWT_SECRET: "auth.jwtSecret",
|
|
707
|
+
CAMSTACK_ADMIN_USER: "auth.adminUsername",
|
|
708
|
+
CAMSTACK_ADMIN_PASS: "auth.adminPassword"
|
|
709
|
+
};
|
|
710
|
+
var ConfigManager = class _ConfigManager {
|
|
711
|
+
constructor(configPath) {
|
|
712
|
+
this.configPath = configPath;
|
|
713
|
+
const rawYaml = this.loadYaml();
|
|
714
|
+
const merged = this.applyEnvOverrides(rawYaml);
|
|
715
|
+
this.bootstrapConfig = bootstrapSchema.parse(merged);
|
|
716
|
+
this.warnDefaultCredentials();
|
|
717
|
+
}
|
|
718
|
+
// Non-readonly so update() can sync the in-memory view after a write.
|
|
719
|
+
bootstrapConfig;
|
|
720
|
+
settingsStore = null;
|
|
721
|
+
/** Called by main.ts after the SQLite DB is ready (Phase 2). */
|
|
722
|
+
setSettingsStore(store) {
|
|
723
|
+
this.settingsStore = store;
|
|
724
|
+
}
|
|
725
|
+
/**
|
|
726
|
+
* Get a config value by dot-notation path.
|
|
727
|
+
* Priority: bootstrap config -> SQL system_settings -> RUNTIME_DEFAULTS fallback.
|
|
728
|
+
*/
|
|
729
|
+
get(path3) {
|
|
730
|
+
const bootstrapValue = this.getFromBootstrap(path3);
|
|
731
|
+
if (bootstrapValue !== void 0) {
|
|
732
|
+
return bootstrapValue;
|
|
733
|
+
}
|
|
734
|
+
if (this.settingsStore !== null) {
|
|
735
|
+
const sqlValue = this.settingsStore.getSystem(path3);
|
|
736
|
+
if (sqlValue !== void 0) {
|
|
737
|
+
return sqlValue;
|
|
738
|
+
}
|
|
739
|
+
const sqlNested = this.getNestedFromSystemSettings(path3);
|
|
740
|
+
if (sqlNested !== void 0) {
|
|
741
|
+
return sqlNested;
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
if (path3 in RUNTIME_DEFAULTS) {
|
|
745
|
+
return RUNTIME_DEFAULTS[path3];
|
|
746
|
+
}
|
|
747
|
+
const nested = this.getFromRuntimeDefaults(path3);
|
|
748
|
+
if (nested !== void 0) {
|
|
749
|
+
return nested;
|
|
750
|
+
}
|
|
751
|
+
return void 0;
|
|
752
|
+
}
|
|
753
|
+
/**
|
|
754
|
+
* Write a value to SQL system_settings.
|
|
755
|
+
* Throws if the settings store is not yet wired.
|
|
756
|
+
*/
|
|
757
|
+
set(key, value) {
|
|
758
|
+
if (this.settingsStore === null) {
|
|
759
|
+
throw new Error("[ConfigManager] SettingsStore not initialized -- call setSettingsStore() first");
|
|
760
|
+
}
|
|
761
|
+
this.settingsStore.setSystem(key, value);
|
|
762
|
+
}
|
|
763
|
+
/**
|
|
764
|
+
* Bulk-read all system_settings keys that belong to a logical section.
|
|
765
|
+
* A "section" is the first segment of a dot-notation key (e.g. 'features', 'logging').
|
|
766
|
+
*/
|
|
767
|
+
getSection(section) {
|
|
768
|
+
if (this.settingsStore !== null) {
|
|
769
|
+
const nested = this.getNestedFromSystemSettings(section);
|
|
770
|
+
if (nested !== void 0) return nested;
|
|
771
|
+
}
|
|
772
|
+
const bootstrapValue = this.bootstrapConfig[section];
|
|
773
|
+
if (bootstrapValue !== void 0 && bootstrapValue !== null && typeof bootstrapValue === "object") {
|
|
774
|
+
return bootstrapValue;
|
|
775
|
+
}
|
|
776
|
+
return this.getFromRuntimeDefaults(section) ?? {};
|
|
777
|
+
}
|
|
778
|
+
/**
|
|
779
|
+
* Bulk-write a section of runtime settings to SQL system_settings.
|
|
780
|
+
* Each entry in `data` is stored as `section.key`.
|
|
781
|
+
*/
|
|
782
|
+
setSection(section, data) {
|
|
783
|
+
if (this.settingsStore === null) {
|
|
784
|
+
throw new Error("[ConfigManager] SettingsStore not initialized -- call setSettingsStore() first");
|
|
785
|
+
}
|
|
786
|
+
for (const [key, value] of Object.entries(data)) {
|
|
787
|
+
this.settingsStore.setSystem(`${section}.${key}`, value);
|
|
788
|
+
}
|
|
789
|
+
}
|
|
790
|
+
// ---------------------------------------------------------------------------
|
|
791
|
+
// Addon / Provider / Device scoped config
|
|
792
|
+
// ---------------------------------------------------------------------------
|
|
793
|
+
/** Read all config for an addon from addon_settings. */
|
|
794
|
+
getAddonConfig(addonId) {
|
|
795
|
+
if (this.settingsStore !== null) {
|
|
796
|
+
return this.settingsStore.getAllAddon(addonId);
|
|
797
|
+
}
|
|
798
|
+
return this.getFromBootstrap(`addons.${addonId}`) ?? {};
|
|
799
|
+
}
|
|
800
|
+
/** Write (bulk-replace) config for an addon to addon_settings. */
|
|
801
|
+
setAddonConfig(addonId, config) {
|
|
802
|
+
if (this.settingsStore === null) {
|
|
803
|
+
throw new Error("[ConfigManager] SettingsStore not initialized -- call setSettingsStore() first");
|
|
804
|
+
}
|
|
805
|
+
this.settingsStore.setAllAddon(addonId, config);
|
|
806
|
+
}
|
|
807
|
+
/** Read all config for a provider from provider_settings. */
|
|
808
|
+
getProviderConfig(providerId) {
|
|
809
|
+
if (this.settingsStore !== null) {
|
|
810
|
+
return this.settingsStore.getAllProvider(providerId);
|
|
811
|
+
}
|
|
812
|
+
return {};
|
|
813
|
+
}
|
|
814
|
+
/** Write (upsert) a single key for a provider to provider_settings. */
|
|
815
|
+
setProviderConfig(providerId, key, value) {
|
|
816
|
+
if (this.settingsStore === null) {
|
|
817
|
+
throw new Error("[ConfigManager] SettingsStore not initialized -- call setSettingsStore() first");
|
|
818
|
+
}
|
|
819
|
+
this.settingsStore.setProvider(providerId, key, value);
|
|
820
|
+
}
|
|
821
|
+
/** Read all config for a device from device_settings. */
|
|
822
|
+
getDeviceConfig(deviceId) {
|
|
823
|
+
if (this.settingsStore !== null) {
|
|
824
|
+
return this.settingsStore.getAllDevice(deviceId);
|
|
825
|
+
}
|
|
826
|
+
return {};
|
|
827
|
+
}
|
|
828
|
+
/** Write (upsert) a single key for a device to device_settings. */
|
|
829
|
+
setDeviceConfig(deviceId, key, value) {
|
|
830
|
+
if (this.settingsStore === null) {
|
|
831
|
+
throw new Error("[ConfigManager] SettingsStore not initialized -- call setSettingsStore() first");
|
|
832
|
+
}
|
|
833
|
+
this.settingsStore.setDevice(deviceId, key, value);
|
|
834
|
+
}
|
|
835
|
+
/** Get a value from the parsed bootstrap config */
|
|
836
|
+
getBootstrap(path3) {
|
|
837
|
+
return this.getFromBootstrap(path3);
|
|
838
|
+
}
|
|
839
|
+
/** Features accessor -- reads from SQL when available, falls back to RUNTIME_DEFAULTS */
|
|
840
|
+
get features() {
|
|
841
|
+
const g = (key) => this.get(`features.${key}`) ?? RUNTIME_DEFAULTS[`features.${key}`];
|
|
842
|
+
return {
|
|
843
|
+
streaming: g("streaming"),
|
|
844
|
+
notifications: g("notifications"),
|
|
845
|
+
objectDetection: g("objectDetection"),
|
|
846
|
+
remoteAccess: g("remoteAccess"),
|
|
847
|
+
agentCluster: g("agentCluster"),
|
|
848
|
+
smartHome: g("smartHome"),
|
|
849
|
+
recordings: g("recordings"),
|
|
850
|
+
backup: g("backup"),
|
|
851
|
+
repl: g("repl")
|
|
852
|
+
};
|
|
853
|
+
}
|
|
854
|
+
/**
|
|
855
|
+
* Returns a merged view of bootstrap config + runtime defaults for backward compat.
|
|
856
|
+
*/
|
|
857
|
+
get raw() {
|
|
858
|
+
const features = {
|
|
859
|
+
streaming: RUNTIME_DEFAULTS["features.streaming"],
|
|
860
|
+
notifications: RUNTIME_DEFAULTS["features.notifications"],
|
|
861
|
+
objectDetection: RUNTIME_DEFAULTS["features.objectDetection"],
|
|
862
|
+
remoteAccess: RUNTIME_DEFAULTS["features.remoteAccess"],
|
|
863
|
+
agentCluster: RUNTIME_DEFAULTS["features.agentCluster"],
|
|
864
|
+
smartHome: RUNTIME_DEFAULTS["features.smartHome"],
|
|
865
|
+
recordings: RUNTIME_DEFAULTS["features.recordings"],
|
|
866
|
+
backup: RUNTIME_DEFAULTS["features.backup"],
|
|
867
|
+
repl: RUNTIME_DEFAULTS["features.repl"]
|
|
868
|
+
};
|
|
869
|
+
return {
|
|
870
|
+
...this.bootstrapConfig,
|
|
871
|
+
features,
|
|
872
|
+
storage: RUNTIME_DEFAULTS["storage.locations"] !== void 0 ? {
|
|
873
|
+
provider: RUNTIME_DEFAULTS["storage.provider"],
|
|
874
|
+
locations: RUNTIME_DEFAULTS["storage.locations"]
|
|
875
|
+
} : { provider: "sqlite-storage", locations: {} },
|
|
876
|
+
logging: {
|
|
877
|
+
level: RUNTIME_DEFAULTS["logging.level"],
|
|
878
|
+
retentionDays: RUNTIME_DEFAULTS["logging.retentionDays"]
|
|
879
|
+
},
|
|
880
|
+
eventBus: {
|
|
881
|
+
ringBufferSize: RUNTIME_DEFAULTS["eventBus.ringBufferSize"]
|
|
882
|
+
},
|
|
883
|
+
retention: {
|
|
884
|
+
detectionEventsDays: RUNTIME_DEFAULTS["retention.detectionEventsDays"],
|
|
885
|
+
audioLevelsDays: RUNTIME_DEFAULTS["retention.audioLevelsDays"]
|
|
886
|
+
},
|
|
887
|
+
providers: RUNTIME_DEFAULTS["providers"]
|
|
888
|
+
};
|
|
889
|
+
}
|
|
890
|
+
/** Sections that live in config.yaml. Everything else goes to SQL. */
|
|
891
|
+
static BOOTSTRAP_SECTIONS = /* @__PURE__ */ new Set(["server", "auth", "mode"]);
|
|
892
|
+
/**
|
|
893
|
+
* Atomically update one top-level section of config.yaml and sync in-memory.
|
|
894
|
+
* Only bootstrap sections (server, auth, mode) are written to YAML.
|
|
895
|
+
* Runtime settings must use setSection() which writes to SQL.
|
|
896
|
+
*/
|
|
897
|
+
update(section, data) {
|
|
898
|
+
if (!_ConfigManager.BOOTSTRAP_SECTIONS.has(section)) {
|
|
899
|
+
throw new Error(
|
|
900
|
+
`[ConfigManager] Section "${section}" is a runtime setting \u2014 use setSection() to write to DB, not update() which writes to config.yaml`
|
|
901
|
+
);
|
|
902
|
+
}
|
|
903
|
+
let raw = {};
|
|
904
|
+
if (fs3.existsSync(this.configPath)) {
|
|
905
|
+
raw = yaml.load(fs3.readFileSync(this.configPath, "utf-8")) ?? {};
|
|
906
|
+
}
|
|
907
|
+
const existing = raw[section] ?? {};
|
|
908
|
+
raw[section] = { ...existing, ...data };
|
|
909
|
+
const validation = bootstrapSchema.safeParse(raw);
|
|
910
|
+
if (!validation.success) {
|
|
911
|
+
throw new Error(`[ConfigManager] Invalid config update for section "${section}": ${validation.error.message}`);
|
|
912
|
+
}
|
|
913
|
+
const tmpPath = `${this.configPath}.tmp`;
|
|
914
|
+
fs3.writeFileSync(tmpPath, yaml.dump(raw, { lineWidth: 120, indent: 2, quotingType: '"' }), "utf-8");
|
|
915
|
+
fs3.renameSync(tmpPath, this.configPath);
|
|
916
|
+
this.bootstrapConfig = validation.data;
|
|
917
|
+
}
|
|
918
|
+
/**
|
|
919
|
+
* Deep-set a value in a nested plain object using a dot-notation path.
|
|
920
|
+
* Returns a new object (immutable).
|
|
921
|
+
*/
|
|
922
|
+
setNested(obj, path3, value) {
|
|
923
|
+
const [head, ...rest] = path3.split(".");
|
|
924
|
+
if (!head) return obj;
|
|
925
|
+
if (rest.length === 0) {
|
|
926
|
+
return { ...obj, [head]: value };
|
|
927
|
+
}
|
|
928
|
+
const child = obj[head] ?? {};
|
|
929
|
+
return { ...obj, [head]: this.setNested(child, rest.join("."), value) };
|
|
930
|
+
}
|
|
931
|
+
/**
|
|
932
|
+
* Apply env var overrides onto the raw YAML object.
|
|
933
|
+
* Only bootstrap-level env vars are applied.
|
|
934
|
+
*/
|
|
935
|
+
applyEnvOverrides(raw) {
|
|
936
|
+
let result = { ...raw };
|
|
937
|
+
for (const [envKey, configPath] of Object.entries(ENV_VAR_MAP)) {
|
|
938
|
+
const envValue = process.env[envKey];
|
|
939
|
+
if (envValue === void 0 || envValue === "") continue;
|
|
940
|
+
const coerced = configPath === "server.port" ? Number(envValue) : envValue;
|
|
941
|
+
result = this.setNested(result, configPath, coerced);
|
|
942
|
+
console.log(`[ConfigManager] Env override applied: ${envKey} \u2192 ${configPath}`);
|
|
943
|
+
}
|
|
944
|
+
return result;
|
|
945
|
+
}
|
|
946
|
+
loadYaml() {
|
|
947
|
+
if (!fs3.existsSync(this.configPath)) {
|
|
948
|
+
console.warn(
|
|
949
|
+
`[ConfigManager] Config file not found at: ${this.configPath}
|
|
950
|
+
\u2192 Using built-in defaults. Set CONFIG_PATH env var or create the file.
|
|
951
|
+
\u2192 Example path from project root: ./server/backend/data/config.yaml`
|
|
952
|
+
);
|
|
953
|
+
return {};
|
|
954
|
+
}
|
|
955
|
+
const content = fs3.readFileSync(this.configPath, "utf-8");
|
|
956
|
+
const parsed = yaml.load(content) ?? {};
|
|
957
|
+
console.log(`[ConfigManager] Loaded config from: ${this.configPath}`);
|
|
958
|
+
return parsed;
|
|
959
|
+
}
|
|
960
|
+
warnDefaultCredentials() {
|
|
961
|
+
if (this.bootstrapConfig.auth.adminPassword === "changeme") {
|
|
962
|
+
console.warn(
|
|
963
|
+
`[ConfigManager] Warning: Using default admin password "changeme". Set auth.adminPassword in your config.yaml or the ADMIN_PASSWORD env var.`
|
|
964
|
+
);
|
|
965
|
+
}
|
|
966
|
+
}
|
|
967
|
+
getFromBootstrap(path3) {
|
|
968
|
+
const keys = path3.split(".");
|
|
969
|
+
let current = this.bootstrapConfig;
|
|
970
|
+
for (const key of keys) {
|
|
971
|
+
if (current === null || current === void 0 || typeof current !== "object") {
|
|
972
|
+
return void 0;
|
|
973
|
+
}
|
|
974
|
+
current = current[key];
|
|
975
|
+
}
|
|
976
|
+
return current;
|
|
977
|
+
}
|
|
978
|
+
getFromRuntimeDefaults(path3) {
|
|
979
|
+
const prefix = path3 + ".";
|
|
980
|
+
const result = {};
|
|
981
|
+
let found = false;
|
|
982
|
+
for (const [key, value] of Object.entries(RUNTIME_DEFAULTS)) {
|
|
983
|
+
if (key.startsWith(prefix)) {
|
|
984
|
+
const subKey = key.slice(prefix.length);
|
|
985
|
+
result[subKey] = value;
|
|
986
|
+
found = true;
|
|
987
|
+
}
|
|
988
|
+
}
|
|
989
|
+
return found ? result : void 0;
|
|
990
|
+
}
|
|
991
|
+
/**
|
|
992
|
+
* Perform a prefix-based nested lookup against SQL system_settings.
|
|
993
|
+
* e.g. path='features' matches keys 'features.streaming', 'features.notifications', etc.
|
|
994
|
+
* Returns an object keyed by the sub-key, or undefined if nothing is found.
|
|
995
|
+
*/
|
|
996
|
+
getNestedFromSystemSettings(path3) {
|
|
997
|
+
if (this.settingsStore === null) return void 0;
|
|
998
|
+
const all = this.settingsStore.getAllSystem();
|
|
999
|
+
const prefix = path3 + ".";
|
|
1000
|
+
const result = {};
|
|
1001
|
+
let found = false;
|
|
1002
|
+
for (const [key, value] of Object.entries(all)) {
|
|
1003
|
+
if (key.startsWith(prefix)) {
|
|
1004
|
+
result[key.slice(prefix.length)] = value;
|
|
1005
|
+
found = true;
|
|
1006
|
+
}
|
|
1007
|
+
}
|
|
1008
|
+
return found ? result : void 0;
|
|
1009
|
+
}
|
|
1010
|
+
};
|
|
1011
|
+
|
|
1012
|
+
// src/worker/addon-worker-host.ts
|
|
1013
|
+
import { fork } from "child_process";
|
|
1014
|
+
var INFRA_ADDON_IDS = /* @__PURE__ */ new Set([
|
|
1015
|
+
"filesystem-storage",
|
|
1016
|
+
"sqlite-settings",
|
|
1017
|
+
"winston-logging"
|
|
1018
|
+
]);
|
|
1019
|
+
var AddonWorkerHost = class {
|
|
1020
|
+
workers = /* @__PURE__ */ new Map();
|
|
1021
|
+
options;
|
|
1022
|
+
heartbeatTimer = null;
|
|
1023
|
+
/** Set of addons that failed to fork and fell back to in-process */
|
|
1024
|
+
fallbackInProcess = /* @__PURE__ */ new Set();
|
|
1025
|
+
constructor(options) {
|
|
1026
|
+
this.options = {
|
|
1027
|
+
workerEntryPath: options.workerEntryPath,
|
|
1028
|
+
devMode: options.devMode ?? false,
|
|
1029
|
+
forceInProcess: options.forceInProcess ?? process.env.CAMSTACK_FORCE_INPROCESS === "true",
|
|
1030
|
+
heartbeatIntervalMs: options.heartbeatIntervalMs ?? 5e3,
|
|
1031
|
+
heartbeatTimeoutMs: options.heartbeatTimeoutMs ?? 3e4,
|
|
1032
|
+
maxCrashesInWindow: options.maxCrashesInWindow ?? 3,
|
|
1033
|
+
crashWindowMs: options.crashWindowMs ?? 6e4,
|
|
1034
|
+
shutdownTimeoutMs: options.shutdownTimeoutMs ?? 1e4,
|
|
1035
|
+
onWorkerLog: options.onWorkerLog
|
|
1036
|
+
};
|
|
1037
|
+
}
|
|
1038
|
+
/** Check if an addon is infrastructure (must stay in-process) */
|
|
1039
|
+
isInfraAddon(addonId) {
|
|
1040
|
+
return INFRA_ADDON_IDS.has(addonId);
|
|
1041
|
+
}
|
|
1042
|
+
/** Check if an addon fell back to in-process after fork failure */
|
|
1043
|
+
isFallbackInProcess(addonId) {
|
|
1044
|
+
return this.fallbackInProcess.has(addonId);
|
|
1045
|
+
}
|
|
1046
|
+
/** Mark an addon as fallen back to in-process */
|
|
1047
|
+
markFallbackInProcess(addonId) {
|
|
1048
|
+
this.fallbackInProcess.add(addonId);
|
|
1049
|
+
}
|
|
1050
|
+
/**
|
|
1051
|
+
* Determine if an addon should be forked.
|
|
1052
|
+
* Default: fork everything except infra addons.
|
|
1053
|
+
* Addons can opt out with `inProcess: true` in declaration.
|
|
1054
|
+
* Emergency fallback: CAMSTACK_FORCE_INPROCESS=true disables all forking.
|
|
1055
|
+
*/
|
|
1056
|
+
shouldFork(addonId, declaration) {
|
|
1057
|
+
if (this.options.forceInProcess) return false;
|
|
1058
|
+
if (this.options.devMode) return false;
|
|
1059
|
+
if (this.isInfraAddon(addonId)) return false;
|
|
1060
|
+
if (this.fallbackInProcess.has(addonId)) return false;
|
|
1061
|
+
if (declaration?.inProcess === true) return false;
|
|
1062
|
+
if (declaration?.forkable !== true) return false;
|
|
1063
|
+
return true;
|
|
1064
|
+
}
|
|
1065
|
+
/** Fork a worker for an addon */
|
|
1066
|
+
async forkWorker(addonId, addonDir, config, storagePaths, dataDir, locationPaths, workerToken) {
|
|
1067
|
+
if (this.workers.has(addonId)) {
|
|
1068
|
+
throw new Error(`Worker for addon "${addonId}" already exists`);
|
|
1069
|
+
}
|
|
1070
|
+
const workerEnv = {
|
|
1071
|
+
PATH: process.env.PATH ?? "",
|
|
1072
|
+
HOME: process.env.HOME ?? "",
|
|
1073
|
+
NODE_ENV: process.env.NODE_ENV ?? "production",
|
|
1074
|
+
NODE_TLS_REJECT_UNAUTHORIZED: "0",
|
|
1075
|
+
// Accept self-signed cert
|
|
1076
|
+
CAMSTACK_WORKER_HUB_URL: `wss://localhost:${process.env.CAMSTACK_PORT ?? "4443"}/trpc`,
|
|
1077
|
+
CAMSTACK_WORKER_TOKEN: workerToken ?? "",
|
|
1078
|
+
CAMSTACK_ADDON_ID: addonId,
|
|
1079
|
+
CAMSTACK_ADDON_DIR: addonDir,
|
|
1080
|
+
CAMSTACK_ADDON_CONFIG: JSON.stringify(config),
|
|
1081
|
+
CAMSTACK_DATA_DIR: dataDir ?? `camstack-data/addons-data/${addonId}`,
|
|
1082
|
+
CAMSTACK_LOCATION_PATHS: JSON.stringify(locationPaths ?? storagePaths)
|
|
1083
|
+
};
|
|
1084
|
+
const forkOptions = {
|
|
1085
|
+
stdio: ["inherit", "inherit", "inherit", "ipc"],
|
|
1086
|
+
execArgv: [],
|
|
1087
|
+
env: workerEnv
|
|
1088
|
+
};
|
|
1089
|
+
const child = fork(this.options.workerEntryPath, [], forkOptions);
|
|
1090
|
+
const worker = {
|
|
1091
|
+
addonId,
|
|
1092
|
+
process: child,
|
|
1093
|
+
state: "starting",
|
|
1094
|
+
startedAt: Date.now(),
|
|
1095
|
+
lastHeartbeat: Date.now(),
|
|
1096
|
+
restartCount: 0,
|
|
1097
|
+
crashTimestamps: [],
|
|
1098
|
+
cpuPercent: 0,
|
|
1099
|
+
memoryRss: 0,
|
|
1100
|
+
workerToken
|
|
1101
|
+
};
|
|
1102
|
+
this.workers.set(addonId, worker);
|
|
1103
|
+
child.on("message", (msg) => {
|
|
1104
|
+
if (msg.type === "LOG" && this.options.onWorkerLog) {
|
|
1105
|
+
this.options.onWorkerLog({
|
|
1106
|
+
addonId,
|
|
1107
|
+
level: msg.level,
|
|
1108
|
+
message: msg.message,
|
|
1109
|
+
scope: ["hub", addonId],
|
|
1110
|
+
meta: msg.context
|
|
1111
|
+
});
|
|
1112
|
+
} else if (msg.type === "STATS") {
|
|
1113
|
+
worker.cpuPercent = msg.cpu;
|
|
1114
|
+
worker.memoryRss = msg.memory;
|
|
1115
|
+
}
|
|
1116
|
+
});
|
|
1117
|
+
child.stdout?.on("data", (chunk) => {
|
|
1118
|
+
const lines = chunk.toString().trim();
|
|
1119
|
+
if (!lines) return;
|
|
1120
|
+
if (this.options.onWorkerLog) {
|
|
1121
|
+
this.options.onWorkerLog({
|
|
1122
|
+
addonId,
|
|
1123
|
+
level: "info",
|
|
1124
|
+
message: lines,
|
|
1125
|
+
scope: ["hub", addonId, "__stdout"]
|
|
1126
|
+
});
|
|
1127
|
+
} else {
|
|
1128
|
+
console.log(`[Worker:${addonId}] ${lines}`);
|
|
1129
|
+
}
|
|
1130
|
+
});
|
|
1131
|
+
child.stderr?.on("data", (chunk) => {
|
|
1132
|
+
const lines = chunk.toString().trim();
|
|
1133
|
+
if (!lines) return;
|
|
1134
|
+
if (this.options.onWorkerLog) {
|
|
1135
|
+
this.options.onWorkerLog({
|
|
1136
|
+
addonId,
|
|
1137
|
+
level: "error",
|
|
1138
|
+
message: lines,
|
|
1139
|
+
scope: ["hub", addonId, "__stderr"]
|
|
1140
|
+
});
|
|
1141
|
+
} else {
|
|
1142
|
+
console.error(`[Worker:${addonId}:ERR] ${lines}`);
|
|
1143
|
+
}
|
|
1144
|
+
});
|
|
1145
|
+
child.on("exit", (code) => {
|
|
1146
|
+
this.handleWorkerExit(addonId, code, addonDir, config, storagePaths, dataDir, locationPaths, workerToken);
|
|
1147
|
+
});
|
|
1148
|
+
child.on("error", (err) => {
|
|
1149
|
+
console.error(`[WorkerHost] Worker ${addonId} error:`, err.message);
|
|
1150
|
+
});
|
|
1151
|
+
await new Promise((resolve3, reject) => {
|
|
1152
|
+
const timeout = setTimeout(() => {
|
|
1153
|
+
reject(new Error(`Worker ${addonId} did not become ready within 30s`));
|
|
1154
|
+
}, 3e4);
|
|
1155
|
+
const readyCheck = (msg) => {
|
|
1156
|
+
if (msg.type === "READY") {
|
|
1157
|
+
clearTimeout(timeout);
|
|
1158
|
+
child.off("message", readyCheck);
|
|
1159
|
+
worker.state = "running";
|
|
1160
|
+
resolve3();
|
|
1161
|
+
}
|
|
1162
|
+
};
|
|
1163
|
+
child.on("message", readyCheck);
|
|
1164
|
+
});
|
|
1165
|
+
}
|
|
1166
|
+
/** List all workers with stats */
|
|
1167
|
+
listWorkers() {
|
|
1168
|
+
return [...this.workers.values()].map((w) => ({
|
|
1169
|
+
addonId: w.addonId,
|
|
1170
|
+
pid: w.process.pid ?? 0,
|
|
1171
|
+
state: w.state,
|
|
1172
|
+
cpuPercent: w.cpuPercent,
|
|
1173
|
+
memoryRss: w.memoryRss,
|
|
1174
|
+
uptimeSeconds: Math.round((Date.now() - w.startedAt) / 1e3),
|
|
1175
|
+
restartCount: w.restartCount,
|
|
1176
|
+
subProcesses: []
|
|
1177
|
+
}));
|
|
1178
|
+
}
|
|
1179
|
+
/** Gracefully shutdown a single worker by addon ID */
|
|
1180
|
+
async shutdownWorkerById(addonId) {
|
|
1181
|
+
const worker = this.workers.get(addonId);
|
|
1182
|
+
if (!worker) {
|
|
1183
|
+
throw new Error(`No worker found for addon "${addonId}"`);
|
|
1184
|
+
}
|
|
1185
|
+
await this.shutdownWorker(addonId, worker);
|
|
1186
|
+
this.workers.delete(addonId);
|
|
1187
|
+
}
|
|
1188
|
+
/** Gracefully shutdown all workers */
|
|
1189
|
+
async shutdownAll() {
|
|
1190
|
+
if (this.heartbeatTimer) {
|
|
1191
|
+
clearInterval(this.heartbeatTimer);
|
|
1192
|
+
this.heartbeatTimer = null;
|
|
1193
|
+
}
|
|
1194
|
+
const shutdowns = [...this.workers.entries()].map(
|
|
1195
|
+
([addonId, worker]) => this.shutdownWorker(addonId, worker)
|
|
1196
|
+
);
|
|
1197
|
+
await Promise.allSettled(shutdowns);
|
|
1198
|
+
this.workers.clear();
|
|
1199
|
+
}
|
|
1200
|
+
/** Start heartbeat monitoring — workers now report heartbeat via tRPC, not IPC PING */
|
|
1201
|
+
startHeartbeatMonitoring() {
|
|
1202
|
+
this.heartbeatTimer = setInterval(() => {
|
|
1203
|
+
const now = Date.now();
|
|
1204
|
+
for (const [addonId, worker] of this.workers) {
|
|
1205
|
+
if (worker.state !== "running") continue;
|
|
1206
|
+
if (now - worker.lastHeartbeat > this.options.heartbeatTimeoutMs) {
|
|
1207
|
+
console.warn(`[WorkerHost] Worker ${addonId} heartbeat timeout \u2014 marking unresponsive`);
|
|
1208
|
+
worker.state = "crashed";
|
|
1209
|
+
worker.process.kill("SIGKILL");
|
|
1210
|
+
}
|
|
1211
|
+
}
|
|
1212
|
+
}, this.options.heartbeatIntervalMs);
|
|
1213
|
+
}
|
|
1214
|
+
/** Update heartbeat timestamp for a worker (called when agent.heartbeat arrives) */
|
|
1215
|
+
updateWorkerHeartbeat(addonId, cpuPercent, memoryRss) {
|
|
1216
|
+
const worker = this.workers.get(addonId);
|
|
1217
|
+
if (!worker) return;
|
|
1218
|
+
worker.lastHeartbeat = Date.now();
|
|
1219
|
+
if (cpuPercent !== void 0) worker.cpuPercent = cpuPercent;
|
|
1220
|
+
if (memoryRss !== void 0) worker.memoryRss = memoryRss;
|
|
1221
|
+
}
|
|
1222
|
+
handleWorkerExit(addonId, code, addonDir, config, storagePaths, dataDir, locationPaths, workerToken) {
|
|
1223
|
+
const worker = this.workers.get(addonId);
|
|
1224
|
+
if (!worker) return;
|
|
1225
|
+
if (worker.state === "stopping") {
|
|
1226
|
+
worker.state = "stopped";
|
|
1227
|
+
return;
|
|
1228
|
+
}
|
|
1229
|
+
worker.state = "crashed";
|
|
1230
|
+
console.error(`[WorkerHost] Worker ${addonId} exited with code ${code}`);
|
|
1231
|
+
const now = Date.now();
|
|
1232
|
+
worker.crashTimestamps.push(now);
|
|
1233
|
+
const recentCrashes = worker.crashTimestamps.filter(
|
|
1234
|
+
(t) => now - t < this.options.crashWindowMs
|
|
1235
|
+
);
|
|
1236
|
+
worker.crashTimestamps = recentCrashes;
|
|
1237
|
+
if (recentCrashes.length >= this.options.maxCrashesInWindow) {
|
|
1238
|
+
console.error(`[WorkerHost] Worker ${addonId} crashed ${recentCrashes.length} times in ${this.options.crashWindowMs}ms \u2014 not restarting`);
|
|
1239
|
+
return;
|
|
1240
|
+
}
|
|
1241
|
+
const backoff = Math.min(2e3 * (worker.restartCount + 1), 3e4);
|
|
1242
|
+
console.log(`[WorkerHost] Restarting worker ${addonId} in ${backoff}ms`);
|
|
1243
|
+
setTimeout(() => {
|
|
1244
|
+
worker.restartCount++;
|
|
1245
|
+
this.workers.delete(addonId);
|
|
1246
|
+
this.forkWorker(addonId, addonDir, config, storagePaths, dataDir, locationPaths, workerToken).catch((err) => {
|
|
1247
|
+
console.error(`[WorkerHost] Failed to restart worker ${addonId}:`, err);
|
|
1248
|
+
});
|
|
1249
|
+
}, backoff);
|
|
1250
|
+
}
|
|
1251
|
+
async shutdownWorker(addonId, worker) {
|
|
1252
|
+
worker.state = "stopping";
|
|
1253
|
+
worker.process.kill("SIGTERM");
|
|
1254
|
+
await new Promise((resolve3) => {
|
|
1255
|
+
const timeout = setTimeout(() => {
|
|
1256
|
+
console.warn(`[WorkerHost] Worker ${addonId} did not exit within ${this.options.shutdownTimeoutMs}ms \u2014 SIGKILL`);
|
|
1257
|
+
worker.process.kill("SIGKILL");
|
|
1258
|
+
resolve3();
|
|
1259
|
+
}, this.options.shutdownTimeoutMs);
|
|
1260
|
+
worker.process.on("exit", () => {
|
|
1261
|
+
clearTimeout(timeout);
|
|
1262
|
+
resolve3();
|
|
1263
|
+
});
|
|
1264
|
+
});
|
|
1265
|
+
}
|
|
1266
|
+
};
|
|
1267
|
+
export {
|
|
1268
|
+
AddonEngineManager,
|
|
1269
|
+
AddonInstaller,
|
|
1270
|
+
AddonLoader,
|
|
1271
|
+
AddonWorkerHost,
|
|
1272
|
+
CapabilityRegistry,
|
|
1273
|
+
ConfigManager,
|
|
1274
|
+
DEFAULT_DATA_PATH,
|
|
1275
|
+
INFRA_CAPABILITIES,
|
|
1276
|
+
RUNTIME_DEFAULTS,
|
|
1277
|
+
WorkerProcessManager,
|
|
1278
|
+
bootstrapSchema,
|
|
1279
|
+
copyDirRecursive,
|
|
1280
|
+
copyExtraFileDirs,
|
|
1281
|
+
detectWorkspacePackagesDir,
|
|
1282
|
+
ensureDir,
|
|
1283
|
+
ensureLibraryBuilt,
|
|
1284
|
+
installPackageFromNpmSync,
|
|
1285
|
+
isInfraCapability,
|
|
1286
|
+
isSourceNewer,
|
|
1287
|
+
stripCamstackDeps,
|
|
1288
|
+
symlinkAddonsToNodeModules
|
|
1289
|
+
};
|
|
1290
|
+
//# sourceMappingURL=index.mjs.map
|