service live configslop

This commit is contained in:
legop3
2026-09-14 17:56:53 -04:00
parent 881583ee0a
commit 91e0cc3886
69 changed files with 1188 additions and 619 deletions
+17 -7
View File
@@ -20,6 +20,7 @@ Phase 1 must be complete and verified before Phase 2 begins. Containerization mu
## Decision log ## Decision log
- 2026-09-14: Apply every committed configuration revision immediately. The configuration coordinator atomically replaces the process-wide snapshot, compares top-level service sections, serially reloads only affected service runtimes, and then refreshes all sessions. Long-lived HTTP/socket handlers remain registered once and delegate to the current runtime; integrations may reconnect or replace their own child process, worker, client, timers, and subscriptions without restarting Node.
- 2026-09-14: Render the schema-driven configuration editor as a YAML-like tree inside one `CardFrame`. Every object or array introduces an ordered header and one indentation guide, every scalar occupies one key/value row, and array operations remain beside their item instead of moving to the far edge. Keep all route-specific RJSF styling in `webui/src/admin/styles.css`, outside the shared global stylesheet. - 2026-09-14: Render the schema-driven configuration editor as a YAML-like tree inside one `CardFrame`. Every object or array introduces an ordered header and one indentation guide, every scalar occupies one key/value row, and array operations remain beside their item instead of moving to the far edge. Keep all route-specific RJSF styling in `webui/src/admin/styles.css`, outside the shared global stylesheet.
- 2026-09-14: Treat container deployment as a fresh installation. Neither startup nor the installer searches for, imports, removes, or otherwise manages an old `config.yaml`; the only old-file path retained is an operator-selected YAML upload on `/setup`. The separate command-line importer and its dry-run mode are removed. Internal SQLite schema migrations remain because they evolve the active database rather than discovering an old installation. - 2026-09-14: Treat container deployment as a fresh installation. Neither startup nor the installer searches for, imports, removes, or otherwise manages an old `config.yaml`; the only old-file path retained is an operator-selected YAML upload on `/setup`. The separate command-line importer and its dry-run mode are removed. Internal SQLite schema migrations remain because they evolve the active database rather than discovering an old installation.
- 2026-09-14: Keep the one-time first-run setup code in `data/setup-code.txt` with owner-only permissions instead of writing the credential into server logs. Reuse it across restarts and delete it permanently when setup completes. - 2026-09-14: Keep the one-time first-run setup code in `data/setup-code.txt` with owner-only permissions instead of writing the credential into server logs. Reuse it across restarts and delete it permanently when setup completes.
@@ -132,7 +133,7 @@ Implementation architecture:
- The database validates and commits that complete document as one coherent immutable revision. - The database validates and commits that complete document as one coherent immutable revision.
- The admin UI presents one continuous configuration page in the same top-to-bottom order as the former YAML file. - The admin UI presents one continuous configuration page in the same top-to-bottom order as the former YAML file.
- Nested cards make object relationships readable, but do not create separate categories, navigation destinations, persistence boundaries, or registries. - Nested cards make object relationships readable, but do not create separate categories, navigation destinations, persistence boundaries, or registries.
- Shared editor infrastructure owns loading, dirty state, validation errors, revision conflicts, secret operations, and restart-required status for the whole document. - Shared editor infrastructure owns loading, dirty state, validation errors, revision conflicts, secret operations, and live-application status for the whole document.
- The browser receives this same schema from the protected admin endpoint and renders it with a maintained JSON Schema form library. - The browser receives this same schema from the protected admin endpoint and renders it with a maintained JSON Schema form library.
- Standard JSON Schema types drive ordinary fields, nested objects, enums, and arrays. One field-agnostic widget handles every `writeOnly` secret; there are no feature-specific configuration components in React. - Standard JSON Schema types drive ordinary fields, nested objects, enums, and arrays. One field-agnostic widget handles every `writeOnly` secret; there are no feature-specific configuration components in React.
@@ -186,11 +187,15 @@ Configuration changes use one intentionally simple application rule:
1. Validate the complete proposed document. 1. Validate the complete proposed document.
2. Commit it as a new database revision. 2. Commit it as a new database revision.
3. Report that an application restart is required. 3. Atomically replace the process-wide configuration snapshot.
4. Let the administrator restart immediately or later. 4. Compare the old and new top-level sections.
5. Load one coherent configuration snapshot at the next process start. 5. Reload every service that owns a changed section, replacing its complete internal runtime when necessary.
6. Report per-service application failures without preventing unrelated services from applying the revision.
7. Refresh sessions only after all affected service reloads finish.
Operational actions such as changing server mode, locking a rover, or issuing a rover command remain live actions and do not become restart-required configuration edits. HTTP routes, Socket.IO connection handlers, and process signal handlers are registered once. They consult live state or delegate to the current service runtime, preventing duplicate listeners after repeated saves. Service reloads may reconnect an integration or restart an application-owned child such as MediaMTX, ffmpeg, Kinect, or the Balance Board worker, but never restart the Node application.
Operational actions such as changing server mode, locking a rover, or issuing a rover command remain direct live actions rather than configuration edits.
After migration is complete: After migration is complete:
@@ -398,7 +403,7 @@ Phase 1 is complete only when all of the following are true:
- Configuration, administrator accounts, and secrets survive restart. - Configuration, administrator accounts, and secrets survive restart.
- The final lockdown administrator cannot be removed accidentally. - The final lockdown administrator cannot be removed accidentally.
- All administrative surfaces are available through `/admin` with server-side authorization. - All administrative surfaces are available through `/admin` with server-side authorization.
- Configuration changes create auditable revisions and apply after restart. - Configuration changes create auditable revisions and apply to the running services without an application restart.
- `/video` works through Node without a special public proxy rule for MediaMTX. - `/video` works through Node without a special public proxy rule for MediaMTX.
- Rover sockets, RTSP publishing, WHEP playback, snapshots, replays, PTZ, Discord, Home Assistant, Kinect, Balance Board, and reporting retain their intended behavior when enabled. - Rover sockets, RTSP publishing, WHEP playback, snapshots, replays, PTZ, Discord, Home Assistant, Kinect, Balance Board, and reporting retain their intended behavior when enabled.
@@ -439,6 +444,7 @@ Implemented on 2026-09-14:
- Redacted secrets from browser responses and audit data. The one complete save operation preserves stored secrets unless the administrator explicitly replaces or clears them. - Redacted secrets from browser responses and audit data. The one complete save operation preserves stored secrets unless the administrator explicitly replaces or clears them.
- Converted every runtime configuration consumer to the synchronous database-backed configuration service and removed the YAML loader, `SERVER_CONFIG`, and the tracked example YAML. - Converted every runtime configuration consumer to the synchronous database-backed configuration service and removed the YAML loader, `SERVER_CONFIG`, and the tracked example YAML.
- Added an explicit one-time YAML upload to `/setup`. Existing bcrypt hashes, lockdown roles, Discord identities, configuration, and secrets can be imported only when the operator selects the file; the installer and startup perform no automatic discovery or migration, and there is no command-line importer. - Added an explicit one-time YAML upload to `/setup`. Existing bcrypt hashes, lockdown roles, Discord identities, configuration, and secrets can be imported only when the operator selects the file; the installer and startup perform no automatic discovery or migration, and there is no command-line importer.
- The one-time setup upload now passes its committed configuration through the same live-application coordinator, so a fresh installation does not need an immediate restart after importing YAML.
- Made setup-file import recursively retain only fields present in the current schema. Stale keys from the permissive YAML era are ignored without aliases or historical translations, while invalid values for real current settings still fail validation; stream-only and snapshot-only room-camera entries remain accepted as they were by the runtime. - Made setup-file import recursively retain only fields present in the current schema. Stale keys from the permissive YAML era are ignored without aliases or historical translations, while invalid values for real current settings still fail validation; stream-only and snapshot-only room-camera entries remain accepted as they were by the runtime.
- Added safe empty-data startup, a file-backed one-time setup code, the restricted `/setup` route, and a console administrator-recovery command. The credential persists at `data/setup-code.txt` across restarts with `0600` permissions, never appears in logs, and is deleted when setup completes. - Added safe empty-data startup, a file-backed one-time setup code, the restricted `/setup` route, and a console administrator-recovery command. The credential persists at `data/setup-code.txt` across restarts with `0600` permissions, never appears in logs, and is deleted when setup completes.
- Added the centralized `/admin` route with Overview, Fleet operations, Users and administrators, and one schema-generated hierarchical Configuration page in legacy YAML order. - Added the centralized `/admin` route with Overview, Fleet operations, Users and administrators, and one schema-generated hierarchical Configuration page in legacy YAML order.
@@ -453,16 +459,19 @@ Implemented on 2026-09-14:
- Converged feature control into service-owned configuration: each public feature opts in beside its own schema, and the configuration system derives those exact `enabled` switches for sessions and command discovery. The former server feature registry was removed; configuration completeness and hardware availability remain visible as runtime status instead of becoming hidden enablement rules. - Converged feature control into service-owned configuration: each public feature opts in beside its own schema, and the configuration system derives those exact `enabled` switches for sessions and command discovery. The former server feature registry was removed; configuration completeness and hardware availability remain visible as runtime status instead of becoming hidden enablement rules.
- Lazy-loaded setup and administration so the schema-form dependency is not included in ordinary driver-page downloads. - Lazy-loaded setup and administration so the schema-form dependency is not included in ordinary driver-page downloads.
- Reused the existing fleet and identity administration surfaces, added password reconfirmation for sensitive operations, and prevented removal or demotion of the final lockdown administrator. - Reused the existing fleet and identity administration surfaces, added password reconfirmation for sensitive operations, and prevented removal or demotion of the final lockdown administrator.
- Added configuration revision history, rollback, audit history, and restart-required reporting. Graceful restart itself remains step 7. - Added configuration revision history, rollback, audit history, and immediate application reporting.
- Added a serialized live-configuration coordinator and converted configurable service runtimes to apply changed sections without restarting Node. Passive policies read the current immutable snapshot; network, hardware, timer, and child-process services replace or retune their owned runtime while stable HTTP/socket handlers continue delegating to it. The admin editor reports any service-specific reload failure after the revision is safely committed.
Local verification completed: Local verification completed:
- All 107 server tests passed, including populated legacy-style default coverage, complete schema-description and input-example coverage, file-backed setup-code lifecycle and symlink rejection, service-definition-derived feature projection, schema-derived secret paths, configuration defaults and strict validation, full-document revision conflicts, secret preservation, administrator invariants, explicit setup-file import with recursive removal of nonexistent fields, and the earlier filesystem coverage. - All 107 server tests passed, including populated legacy-style default coverage, complete schema-description and input-example coverage, file-backed setup-code lifecycle and symlink rejection, service-definition-derived feature projection, schema-derived secret paths, configuration defaults and strict validation, full-document revision conflicts, secret preservation, administrator invariants, explicit setup-file import with recursive removal of nonexistent fields, and the earlier filesystem coverage.
- All 24 server test files passed after live application was added. The new isolated coordinator test confirms coherent snapshot replacement, top-level change detection, per-service invocation, applied revision reporting, and failure isolation.
- Focused admin, route, and identity UI lint passed. - Focused admin, route, and identity UI lint passed.
- All 20 existing focused web UI tests passed. - All 20 existing focused web UI tests passed.
- The production web UI build completed successfully and regenerated the checked-in server assets. - The production web UI build completed successfully and regenerated the checked-in server assets.
- Installer syntax and repository whitespace checks passed. - Installer syntax and repository whitespace checks passed.
- A local startup smoke test reached listener initialization. MediaMTX then exited because `/usr/local/bin/mediamtx` is intentionally absent on this development machine; actual enabled integrations and media remain deployment checks for the real server. - A local startup smoke test reached listener initialization. MediaMTX then exited because `/usr/local/bin/mediamtx` is intentionally absent on this development machine; actual enabled integrations and media remain deployment checks for the real server.
- A second empty-data startup smoke test loaded every reloadable service and reached the HTTP listener without listener-limit warnings. A deliberately substituted failing MediaMTX executable then ended the process as expected; enabled hardware and external integrations still require verification on the actual server.
# Phase 2: containerization and image delivery # Phase 2: containerization and image delivery
@@ -672,6 +681,7 @@ Within the two hard phase boundaries, the safest order is:
- [x] Converge optional feature control into service-owned `enabled` switches and derive the public feature map from those definitions. - [x] Converge optional feature control into service-owned `enabled` switches and derive the public feature map from those definitions.
- [x] Build the centralized admin configuration UI. - [x] Build the centralized admin configuration UI.
- [x] Add persistent audit history. - [x] Add persistent audit history.
- [x] Apply every configuration revision to running services without restarting the application.
- [ ] Implement coordinated backup and staged restore. - [ ] Implement coordinated backup and staged restore.
- [ ] Standardize graceful application restart. - [ ] Standardize graceful application restart.
- [ ] Add the internal `/video` proxy and remove the special external route. - [ ] Add the internal `/video` proxy and remove the special external route.
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -1,2 +1,2 @@
import{e as F,r as s,j as e,S as P,C as c,L as $}from"./index-CqMkCfQw.js";import{e as q,f as D,i as I}from"./api-C0PIt_OP.js";function R(){const l=F(),[a,m]=s.useState(null),[n,b]=s.useState(""),[d,C]=s.useState(""),[p,N]=s.useState(""),[r,S]=s.useState(""),[f,v]=s.useState(""),[o,w]=s.useState(null),[x,h]=s.useState(!1),[g,i]=s.useState("");s.useEffect(()=>{q(l).then(t=>m(t.required)).catch(t=>i(t.message))},[l]);async function j(t){h(!0),i("");try{await t(),m(!1),i("Setup completed. You can now open the administration application and log in.")}catch(u){const E=Array.isArray(u.validationErrors)?` ${u.validationErrors.map(y=>`${y.path}: ${y.message}`).join("; ")}`:"";i(`${u.message}${E}`)}finally{h(!1)}}function k(t){if(t.preventDefault(),r!==f){i("Passwords do not match.");return}j(()=>D(l,{setupCode:n,username:d,discordId:p,password:r}))}function A(t){t.preventDefault(),o&&j(async()=>I(l,{setupCode:n,fileName:o.name,yaml:await o.text()}))}return e.jsxs("div",{className:"min-h-screen bg-neutral-950 p-1 text-slate-100",children:[e.jsx(P,{}),e.jsxs("main",{className:"mx-auto flex min-h-screen w-full max-w-3xl flex-col justify-center gap-0.5",children:[e.jsxs(c,{title:"MultiRover setup",meta:a===null?"checking":a?"required":"complete",bodyClassName:"space-y-0.5 p-1 text-sm",children:[a?e.jsx("p",{children:"Enter the one-time code from setup-code.txt in the server data folder, then create the first lockdown administrator or import an existing configuration."}):null,a===!1?e.jsx($,{className:"button-dark inline-block",to:"/admin",children:"Open administration"}):null,g?e.jsx("p",{className:"surface p-1 text-sm text-slate-200",children:g}):null]}),a?e.jsxs(e.Fragment,{children:[e.jsxs(c,{title:"Setup authorization",bodyClassName:"p-1",children:[e.jsx("label",{className:"block text-xs font-semibold text-slate-200",children:"One-time setup code"}),e.jsx("input",{className:"field-input mt-0.5 w-full font-mono",value:n,onChange:t=>b(t.target.value)})]}),e.jsx(c,{title:"Create first administrator",bodyClassName:"p-1",children:e.jsxs("form",{className:"grid gap-0.5 md:grid-cols-2",onSubmit:k,children:[e.jsx("input",{className:"field-input",placeholder:"Username",value:d,onChange:t=>C(t.target.value)}),e.jsx("input",{className:"field-input",placeholder:"Discord id (optional)",value:p,onChange:t=>N(t.target.value)}),e.jsx("input",{className:"field-input",type:"password",placeholder:"Password",value:r,onChange:t=>S(t.target.value)}),e.jsx("input",{className:"field-input",type:"password",placeholder:"Confirm password",value:f,onChange:t=>v(t.target.value)}),e.jsx("button",{className:"button-dark md:col-span-2",type:"submit",disabled:x||!n||!d||!r,children:"Create lockdown administrator"})]})}),e.jsxs(c,{title:"Import configuration file",bodyClassName:"space-y-0.5 p-1 text-sm",children:[e.jsx("p",{className:"text-xs text-slate-400",children:"Choose an existing YAML configuration explicitly. The server validates and imports it once, and its secrets are never displayed back in the browser."}),e.jsxs("form",{className:"flex flex-col gap-0.5 md:flex-row",onSubmit:A,children:[e.jsx("input",{className:"field-input flex-1",type:"file",accept:".yaml,.yml,text/yaml",onChange:t=>w(t.target.files?.[0]||null)}),e.jsx("button",{className:"button-dark",type:"submit",disabled:x||!n||!o,children:"Import selected YAML"})]})]})]}):null]})]})}export{R as default}; import{e as F,r as s,j as e,S as P,C as c,L as $}from"./index-DNdP4vNH.js";import{e as q,f as D,i as I}from"./api-C0PIt_OP.js";function R(){const l=F(),[a,m]=s.useState(null),[n,b]=s.useState(""),[d,C]=s.useState(""),[p,N]=s.useState(""),[r,S]=s.useState(""),[f,v]=s.useState(""),[o,w]=s.useState(null),[x,h]=s.useState(!1),[g,i]=s.useState("");s.useEffect(()=>{q(l).then(t=>m(t.required)).catch(t=>i(t.message))},[l]);async function j(t){h(!0),i("");try{await t(),m(!1),i("Setup completed. You can now open the administration application and log in.")}catch(u){const E=Array.isArray(u.validationErrors)?` ${u.validationErrors.map(y=>`${y.path}: ${y.message}`).join("; ")}`:"";i(`${u.message}${E}`)}finally{h(!1)}}function k(t){if(t.preventDefault(),r!==f){i("Passwords do not match.");return}j(()=>D(l,{setupCode:n,username:d,discordId:p,password:r}))}function A(t){t.preventDefault(),o&&j(async()=>I(l,{setupCode:n,fileName:o.name,yaml:await o.text()}))}return e.jsxs("div",{className:"min-h-screen bg-neutral-950 p-1 text-slate-100",children:[e.jsx(P,{}),e.jsxs("main",{className:"mx-auto flex min-h-screen w-full max-w-3xl flex-col justify-center gap-0.5",children:[e.jsxs(c,{title:"MultiRover setup",meta:a===null?"checking":a?"required":"complete",bodyClassName:"space-y-0.5 p-1 text-sm",children:[a?e.jsx("p",{children:"Enter the one-time code from setup-code.txt in the server data folder, then create the first lockdown administrator or import an existing configuration."}):null,a===!1?e.jsx($,{className:"button-dark inline-block",to:"/admin",children:"Open administration"}):null,g?e.jsx("p",{className:"surface p-1 text-sm text-slate-200",children:g}):null]}),a?e.jsxs(e.Fragment,{children:[e.jsxs(c,{title:"Setup authorization",bodyClassName:"p-1",children:[e.jsx("label",{className:"block text-xs font-semibold text-slate-200",children:"One-time setup code"}),e.jsx("input",{className:"field-input mt-0.5 w-full font-mono",value:n,onChange:t=>b(t.target.value)})]}),e.jsx(c,{title:"Create first administrator",bodyClassName:"p-1",children:e.jsxs("form",{className:"grid gap-0.5 md:grid-cols-2",onSubmit:k,children:[e.jsx("input",{className:"field-input",placeholder:"Username",value:d,onChange:t=>C(t.target.value)}),e.jsx("input",{className:"field-input",placeholder:"Discord id (optional)",value:p,onChange:t=>N(t.target.value)}),e.jsx("input",{className:"field-input",type:"password",placeholder:"Password",value:r,onChange:t=>S(t.target.value)}),e.jsx("input",{className:"field-input",type:"password",placeholder:"Confirm password",value:f,onChange:t=>v(t.target.value)}),e.jsx("button",{className:"button-dark md:col-span-2",type:"submit",disabled:x||!n||!d||!r,children:"Create lockdown administrator"})]})}),e.jsxs(c,{title:"Import configuration file",bodyClassName:"space-y-0.5 p-1 text-sm",children:[e.jsx("p",{className:"text-xs text-slate-400",children:"Choose an existing YAML configuration explicitly. The server validates and imports it once, and its secrets are never displayed back in the browser."}),e.jsxs("form",{className:"flex flex-col gap-0.5 md:flex-row",onSubmit:A,children:[e.jsx("input",{className:"field-input flex-1",type:"file",accept:".yaml,.yml,text/yaml",onChange:t=>w(t.target.files?.[0]||null)}),e.jsx("button",{className:"button-dark",type:"submit",disabled:x||!n||!o,children:"Import selected YAML"})]})]})]}):null]})]})}export{R as default};
//# sourceMappingURL=SetupApp-C2cP8ApY.js.map //# sourceMappingURL=SetupApp-DoWmWQMy.js.map
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+2 -2
View File
@@ -12,8 +12,8 @@
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" /> <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
<!-- site-metadata:inject --> <!-- site-metadata:inject -->
<!-- analytics:inject --> <!-- analytics:inject -->
<script type="module" crossorigin src="/assets/index-CqMkCfQw.js"></script> <script type="module" crossorigin src="/assets/index-DNdP4vNH.js"></script>
<link rel="stylesheet" crossorigin href="/assets/index-1O6avznD.css"> <link rel="stylesheet" crossorigin href="/assets/index-BhA42K5i.css">
</head> </head>
<body> <body>
<div id="root"></div> <div id="root"></div>
@@ -6,6 +6,7 @@ const assert = require('node:assert/strict');
const fs = require('fs'); const fs = require('fs');
const os = require('os'); const os = require('os');
const path = require('path'); const path = require('path');
const { execFileSync } = require('child_process');
const { defaultConfig, normalizeConfig, assertValidConfig } = require('./validation'); const { defaultConfig, normalizeConfig, assertValidConfig } = require('./validation');
const { definitions, rootSchema, secretPaths, featureDefinitions } = require('./definition'); const { definitions, rootSchema, secretPaths, featureDefinitions } = require('./definition');
const { getFeatureFlags } = require('./index'); const { getFeatureFlags } = require('./index');
@@ -353,3 +354,63 @@ bandwidthSavings:
return true; return true;
}); });
}); });
test('committed revisions replace the live snapshot and isolate service reload failures', () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'multirover-live-configuration-'));
temporaryRoots.push(root);
const serverRoot = path.resolve(__dirname, '../..');
const script = `
const configuration = require('./src/configuration');
const applied = [];
configuration.registerConfigurationHandler('timezone', (next, previous) => {
applied.push({ section: 'timezone', next, previous });
});
configuration.registerConfigurationHandler('media', () => {
throw new Error('simulated media reload failure');
});
const database = configuration.getConfigurationDatabase();
const record = database.getClientConfiguration();
const next = structuredClone(record.config);
next.timezone = 'America/Chicago';
next.media.whepBaseUrl = 'http://localhost:9999/video';
database.updateConfiguration({
value: next,
expectedRevision: record.revision,
actor: 'live-configuration-test',
});
configuration.applyCommittedConfiguration().then((application) => {
console.log(JSON.stringify({
application,
applied,
liveTimezone: configuration.loadConfig().timezone,
liveRevision: configuration.getRuntimeConfigurationRevision(),
}));
database.close();
});
`;
const output = execFileSync(process.execPath, ['-e', script], {
cwd: serverRoot,
env: { ...process.env, SERVER_DATA_DIR: root },
encoding: 'utf8',
});
const result = JSON.parse(output.trim());
/*
A failing integration remains visible in application status but cannot
roll back the valid revision or prevent an unrelated service from seeing
it. This is the central guarantee that makes live application usable on a
server where optional hardware may be offline during an ordinary edit.
*/
assert.equal(result.liveTimezone, 'America/Chicago');
assert.equal(result.liveRevision, result.application.revision);
assert.deepEqual(result.application.changedSections, ['timezone', 'media']);
assert.deepEqual(result.applied, [{
section: 'timezone',
next: 'America/Chicago',
previous: defaultConfig.timezone,
}]);
assert.deepEqual(result.application.services, [
{ section: 'timezone', status: 'applied' },
{ section: 'media', status: 'failed', error: 'simulated media reload failure' },
]);
});
+1 -1
View File
@@ -61,7 +61,7 @@ const properties = Object.fromEntries(
); );
const rootSchema = strictObject(properties, { const rootSchema = strictObject(properties, {
title: 'Configuration', title: 'Configuration',
description: 'Complete server configuration. Changes are validated and saved as one revision, then loaded when the application restarts.', description: 'Complete server configuration. Changes are validated, saved as one revision, and applied live by reloading affected services.',
required: definitions.map(({ key }) => key), required: definitions.map(({ key }) => key),
}); });
+97 -19
View File
@@ -1,22 +1,34 @@
// Configuration Service // Configuration Service
// Purpose: Exposes the process-wide synchronous configuration snapshot and the underlying administration store. // Purpose: Exposes the process-wide live configuration snapshot, service reload registry, and administration store.
// Scope: Keeps existing require-time startup semantics while making SQLite the only runtime configuration source. // Scope: Makes SQLite the durable source while applying each committed revision coherently to the running process.
const EventEmitter = require('events');
const { isDeepStrictEqual } = require('util');
const { createConfigurationDatabase } = require('./database'); const { createConfigurationDatabase } = require('./database');
const { rootSchema, featureDefinitions } = require('./definition'); const { definitions, rootSchema, featureDefinitions } = require('./definition');
let singleton; let singleton;
let runtimeConfiguration;
let runtimeConfigurationRevision = null; let runtimeConfigurationRevision = null;
let applicationQueue = Promise.resolve();
let lastApplication = null;
const reloadHandlers = new Map();
const configurationEvents = new EventEmitter();
function getConfigurationDatabase() { function getConfigurationDatabase() {
if (!singleton) { if (!singleton) {
singleton = createConfigurationDatabase(); singleton = createConfigurationDatabase();
/* // Durable state is read once at startup and then replaced atomically after
Capture the active revision once when the process opens its configuration // each committed save or rollback. Every caller therefore sees one complete
store. Later admin saves are intentionally restart-bound, so comparing // revision rather than independently rereading SQLite mid-application.
against this value gives every reconnecting browser an authoritative const active = singleton.getActiveConfigurationRecord();
pending-restart indicator. runtimeConfiguration = Object.freeze(active.config);
*/ runtimeConfigurationRevision = active.revision;
runtimeConfigurationRevision = singleton.getActiveConfigurationRecord().revision; lastApplication = {
revision: active.revision,
changedSections: [],
services: [],
appliedAt: Date.now(),
};
} }
return singleton; return singleton;
} }
@@ -27,16 +39,78 @@ function getRuntimeConfigurationRevision() {
} }
function loadConfig() { function loadConfig() {
/* getConfigurationDatabase();
Services intentionally receive one coherent snapshot for this process. return runtimeConfiguration;
Configuration commits are restart-bound, so re-reading during runtime would }
let only some modules observe the new revision and create a split-brain
process. The database remains queryable through its administrative API. function registerConfigurationHandler(section, handler) {
*/ if (!rootSchema.properties?.[section]) {
if (!loadConfig.cached) { throw new Error(`Cannot register configuration handler for unknown section ${section}.`);
loadConfig.cached = Object.freeze(getConfigurationDatabase().getActiveConfigurationRecord().config);
} }
return loadConfig.cached; if (typeof handler !== 'function') {
throw new Error(`Configuration handler for ${section} must be a function.`);
}
const handlers = reloadHandlers.get(section) || new Set();
handlers.add(handler);
reloadHandlers.set(section, handlers);
return () => handlers.delete(handler);
}
async function applyCommittedConfiguration() {
/*
Saves are serialized even though SQLite commits synchronously. A service
reload may need to close a worker or network client asynchronously, and a
later revision must never overtake that cleanup and start a second runtime.
*/
const apply = async () => {
const active = getConfigurationDatabase().getActiveConfigurationRecord();
const previous = loadConfig();
const next = Object.freeze(active.config);
const changedSections = definitions
.map(({ key }) => key)
.filter((key) => !isDeepStrictEqual(previous[key], next[key]));
// Swap the complete document before invoking handlers. Any service helper
// consulted during a reload consequently observes the same new revision.
runtimeConfiguration = next;
runtimeConfigurationRevision = active.revision;
const services = [];
for (const section of changedSections) {
for (const handler of reloadHandlers.get(section) || []) {
try {
// Sequential application preserves the server's existing dependency
// order, notably Home Assistant before its Neato and lift consumers.
await handler(next[section], previous[section], next, previous);
services.push({ section, status: 'applied' });
} catch (error) {
// One unavailable integration must not prevent unrelated services or
// the session feature map from receiving the committed revision.
services.push({ section, status: 'failed', error: error.message });
}
}
}
lastApplication = {
revision: active.revision,
changedSections,
services,
appliedAt: Date.now(),
};
configurationEvents.emit('applied', lastApplication);
return lastApplication;
};
const queued = applicationQueue.then(apply, apply);
// Retain a fulfilled tail even if an unexpected coordinator error escapes;
// otherwise one failure would permanently poison every later save.
applicationQueue = queued.catch(() => undefined);
return queued;
}
function getLastConfigurationApplication() {
getConfigurationDatabase();
return lastApplication;
} }
function getValueAtPath(value, path) { function getValueAtPath(value, path) {
@@ -62,6 +136,10 @@ function isFeatureEnabled(featureName) {
module.exports = { module.exports = {
getConfigurationDatabase, getConfigurationDatabase,
getRuntimeConfigurationRevision, getRuntimeConfigurationRevision,
getLastConfigurationApplication,
registerConfigurationHandler,
applyCommittedConfiguration,
configurationEvents,
loadConfig, loadConfig,
getFeatureFlags, getFeatureFlags,
isFeatureEnabled, isFeatureEnabled,
+8 -3
View File
@@ -13,8 +13,13 @@ const io = new SocketIOServer(httpServer, {
maxHttpBufferSize: 16 * 1024 * 1024, maxHttpBufferSize: 16 * 1024 * 1024,
}); });
// Allow more service listeners without warnings. /*
io.sockets.setMaxListeners(30); Optional feature gateways now remain registered while disabled so an admin
io.of('/').setMaxListeners(30); can enable them live without adding a second listener tree. Forty is a small
explicit allowance for those one-time service owners, not an unlimited value
that could hide duplicate registrations during repeated configuration saves.
*/
io.sockets.setMaxListeners(40);
io.of('/').setMaxListeners(40);
module.exports = io; module.exports = io;
+3 -3
View File
@@ -83,9 +83,9 @@ function buildBandwidthSavingsPolicy(config = loadConfig()) {
function getBandwidthSavingsPolicy() { function getBandwidthSavingsPolicy() {
/* /*
loadConfig() is cached by configuration service, so rebuilding this small object per The configuration service returns an in-memory snapshot, so rebuilding this
caller is cheap while still letting tests pass explicit config objects into small normalized object per caller is cheap and immediately follows a newly
buildBandwidthSavingsPolicy(). applied revision. Tests may still supply explicit documents directly.
*/ */
return buildBandwidthSavingsPolicy(loadConfig()); return buildBandwidthSavingsPolicy(loadConfig());
} }
@@ -7,6 +7,8 @@ const logger = require('../../globals/logger').child('adminConfigurationService'
const { const {
getConfigurationDatabase, getConfigurationDatabase,
getRuntimeConfigurationRevision, getRuntimeConfigurationRevision,
getLastConfigurationApplication,
applyCommittedConfiguration,
rootSchema, rootSchema,
} = require('../../configuration'); } = require('../../configuration');
const { getRole } = require('../roleService'); const { getRole } = require('../roleService');
@@ -69,7 +71,8 @@ function buildAdminSnapshot() {
a second field definition. a second field definition.
*/ */
configuration: { ...configuration, schema: rootSchema }, configuration: { ...configuration, schema: rootSchema },
restartRequired: configuration.revision !== getRuntimeConfigurationRevision(), appliedRevision: getRuntimeConfigurationRevision(),
configurationApplication: getLastConfigurationApplication(),
administrators: database.listAdministrators(), administrators: database.listAdministrators(),
revisions: database.listConfigurationRevisions(), revisions: database.listConfigurationRevisions(),
auditEvents: database.listAuditEvents(), auditEvents: database.listAuditEvents(),
@@ -88,23 +91,25 @@ io.on('connection', (socket) => {
return { confirmedUntil: socket.data.adminPasswordConfirmedAt + PASSWORD_CONFIRMATION_WINDOW_MS }; return { confirmedUntil: socket.data.adminPasswordConfirmedAt + PASSWORD_CONFIRMATION_WINDOW_MS };
}); });
ackHandler(socket, 'adminConfig:updateConfiguration', requireRecentPassword, (payload) => { ackHandler(socket, 'adminConfig:updateConfiguration', requireRecentPassword, async (payload) => {
const revision = database.updateConfiguration({ const revision = database.updateConfiguration({
value: payload.value, value: payload.value,
expectedRevision: payload.expectedRevision, expectedRevision: payload.expectedRevision,
secretOperations: payload.secretOperations, secretOperations: payload.secretOperations,
actor: actorFor(socket), actor: actorFor(socket),
}); });
return { revision, snapshot: buildAdminSnapshot(), restartRequired: true }; const application = await applyCommittedConfiguration();
return { revision, application, snapshot: buildAdminSnapshot() };
}); });
ackHandler(socket, 'adminConfig:restoreRevision', requireRecentPassword, (payload) => { ackHandler(socket, 'adminConfig:restoreRevision', requireRecentPassword, async (payload) => {
const revision = database.restoreConfigurationRevision({ const revision = database.restoreConfigurationRevision({
revision: payload.revision, revision: payload.revision,
expectedRevision: payload.expectedRevision, expectedRevision: payload.expectedRevision,
actor: actorFor(socket), actor: actorFor(socket),
}); });
return { revision, snapshot: buildAdminSnapshot(), restartRequired: true }; const application = await applyCommittedConfiguration();
return { revision, application, snapshot: buildAdminSnapshot() };
}); });
ackHandler(socket, 'adminConfig:createAdministrator', requireRecentPassword, async (payload) => { ackHandler(socket, 'adminConfig:createAdministrator', requireRecentPassword, async (payload) => {
@@ -7,7 +7,7 @@ function registerAudioForwardHooks(deps) {
roverManager, roverManager,
turnService, turnService,
logger, logger,
serviceEnabled, isServiceEnabled,
workers, workers,
whipOwners, whipOwners,
ensureWorker, ensureWorker,
@@ -57,7 +57,7 @@ function registerAudioForwardHooks(deps) {
stopWorker(roverId); stopWorker(roverId);
return; return;
} }
if (action === 'upsert' && serviceEnabled && !workers.has(roverId)) { if (action === 'upsert' && isServiceEnabled() && !workers.has(roverId)) {
// A rover coming online should not create ffmpeg publishers by itself. // A rover coming online should not create ffmpeg publishers by itself.
// The audio worker is intentionally lazy because uploads, mic forwarding, // The audio worker is intentionally lazy because uploads, mic forwarding,
// and automatic sounds are the moments that actually need a media pipe; // and automatic sounds are the moments that actually need a media pipe;
@@ -5,7 +5,7 @@ const path = require('path');
const EventEmitter = require('events'); const EventEmitter = require('events');
const io = require('../../globals/io'); const io = require('../../globals/io');
const logger = require('../../globals/logger').child('audioForwardService'); const logger = require('../../globals/logger').child('audioForwardService');
const { loadConfig } = require('../../configuration'); const { loadConfig, registerConfigurationHandler } = require('../../configuration');
const { resolveRuntimePath } = require('../../helpers/dataPaths'); const { resolveRuntimePath } = require('../../helpers/dataPaths');
const roverManager = require('../roverManager'); const roverManager = require('../roverManager');
const turnService = require('../turnService'); const turnService = require('../turnService');
@@ -17,18 +17,7 @@ const { registerAudioForwardHooks } = require('./hooks');
const { registerChargeCompleteSound } = require('./chargeCompleteSound'); const { registerChargeCompleteSound } = require('./chargeCompleteSound');
const audioForwardEvents = new EventEmitter(); const audioForwardEvents = new EventEmitter();
const config = loadConfig(); let serviceEnabled = false;
const audioForwardConfig = config.audioForward || {};
const mediaConfig = config.media || {};
// Configuration defaults always provide this boolean. Treat only an explicit
// true as enabled so no credential, path, or historical fallback can opt the
// service in on the operator's behalf.
const serviceEnabled = Boolean(audioForwardConfig.enabled);
const ffmpegBin = audioForwardConfig.ffmpegBin || 'ffmpeg';
const streamSuffix =
typeof audioForwardConfig.streamSuffix === 'string' && audioForwardConfig.streamSuffix.trim()
? audioForwardConfig.streamSuffix.trim()
: '-fwd';
/* /*
FIFOs and uploaded clips are disposable, but they are deliberately created FIFOs and uploaded clips are disposable, but they are deliberately created
and managed by this application. A fixed path below SERVER_DATA_DIR keeps the and managed by this application. A fixed path below SERVER_DATA_DIR keeps the
@@ -37,9 +26,6 @@ const streamSuffix =
*/ */
const runtimeDir = resolveRuntimePath('audio-forward'); const runtimeDir = resolveRuntimePath('audio-forward');
const uploadsDir = path.join(runtimeDir, 'uploads'); const uploadsDir = path.join(runtimeDir, 'uploads');
const maxUploadBytes = Number.isFinite(audioForwardConfig.maxUploadBytes)
? Math.max(256 * 1024, Math.floor(audioForwardConfig.maxUploadBytes))
: 8 * 1024 * 1024;
const states = new Map(); // roverId -> { state, source, error, startedAt, updatedAt } const states = new Map(); // roverId -> { state, source, error, startedAt, updatedAt }
const workers = new Map(); // roverId -> worker const workers = new Map(); // roverId -> worker
@@ -70,51 +56,67 @@ function getAudioForwardState() {
return payload; return payload;
} }
const audioForwardPolicy = createAudioForwardPolicy({ let operations;
isVerified,
isMuted,
roverManager,
turnService,
streamSuffix,
mediaConfig,
});
const {
ensureAudioForwardPermission,
resolveForwardUrl,
resolveForwardPathId,
buildWhipUrl,
} = audioForwardPolicy;
const workerEngine = createAudioForwardWorkerEngine({ function replaceAudioForwardRuntime(fullConfig) {
logger, operations?.stopAllWorkers('configuration-change');
io, const audioForwardConfig = fullConfig.audioForward || {};
roverManager, const mediaConfig = fullConfig.media || {};
turnService, serviceEnabled = Boolean(audioForwardConfig.enabled);
videoSessions, const streamSuffix = typeof audioForwardConfig.streamSuffix === 'string' && audioForwardConfig.streamSuffix.trim()
serviceEnabled, ? audioForwardConfig.streamSuffix.trim()
ffmpegBin, : '-fwd';
runtimeDir, const policy = createAudioForwardPolicy({
uploadsDir, isVerified,
maxUploadBytes, isMuted,
workers, roverManager,
whipOwners, turnService,
setState, streamSuffix,
resolveForwardUrl, mediaConfig,
resolveForwardPathId, });
}); const maxUploadBytes = Number.isFinite(audioForwardConfig.maxUploadBytes)
? Math.max(256 * 1024, Math.floor(audioForwardConfig.maxUploadBytes))
: 8 * 1024 * 1024;
operations = {
...policy,
...createAudioForwardWorkerEngine({
logger,
io,
roverManager,
turnService,
videoSessions,
serviceEnabled,
ffmpegBin: audioForwardConfig.ffmpegBin || 'ffmpeg',
runtimeDir,
uploadsDir,
maxUploadBytes,
workers,
whipOwners,
setState,
resolveForwardUrl: policy.resolveForwardUrl,
resolveForwardPathId: policy.resolveForwardPathId,
}),
};
}
const { replaceAudioForwardRuntime(loadConfig());
ensureWorker,
stopWorker, // Stable delegates keep the one-time socket/event registrations below pointed
stopAllWorkers, // at the newest policy and worker engine after either audio or media changes.
playUploadedAudio, const delegate = (name) => (...args) => operations[name](...args);
playServerAudioFile, const ensureWorker = delegate('ensureWorker');
stopPlayback, const stopWorker = delegate('stopWorker');
revokeWhipSessionForRover, const stopAllWorkers = delegate('stopAllWorkers');
stopWhipForRover, const playUploadedAudio = delegate('playUploadedAudio');
stopOwnedAudioIfUnauthorized, const playServerAudioFile = delegate('playServerAudioFile');
startSilenceWriter, const stopPlayback = delegate('stopPlayback');
} = workerEngine; const revokeWhipSessionForRover = delegate('revokeWhipSessionForRover');
const stopWhipForRover = delegate('stopWhipForRover');
const stopOwnedAudioIfUnauthorized = delegate('stopOwnedAudioIfUnauthorized');
const startSilenceWriter = delegate('startSilenceWriter');
const ensureAudioForwardPermission = delegate('ensureAudioForwardPermission');
const resolveForwardPathId = delegate('resolveForwardPathId');
const buildWhipUrl = delegate('buildWhipUrl');
function installShutdownHooks() { function installShutdownHooks() {
const shutdown = (signal) => { const shutdown = (signal) => {
@@ -136,7 +138,7 @@ registerAudioForwardHooks({
roverManager, roverManager,
turnService, turnService,
logger, logger,
serviceEnabled, isServiceEnabled: () => serviceEnabled,
workers, workers,
whipOwners, whipOwners,
ensureWorker, ensureWorker,
@@ -161,6 +163,13 @@ registerChargeCompleteSound({
playServerAudioFile, playServerAudioFile,
}); });
registerConfigurationHandler('audioForward', (_section, _previous, nextConfig) => {
replaceAudioForwardRuntime(nextConfig);
});
registerConfigurationHandler('media', (_section, _previous, nextConfig) => {
replaceAudioForwardRuntime(nextConfig);
});
module.exports = { module.exports = {
getAudioForwardState, getAudioForwardState,
audioForwardEvents, audioForwardEvents,
@@ -5,7 +5,7 @@ const fs = require('fs');
const EventEmitter = require('events'); const EventEmitter = require('events');
const io = require('../../globals/io'); const io = require('../../globals/io');
const logger = require('../../globals/logger').child('audioLevelsService'); const logger = require('../../globals/logger').child('audioLevelsService');
const { loadConfig } = require('../../configuration'); const { loadConfig, registerConfigurationHandler } = require('../../configuration');
const { resolveDataDir, resolveDataPath } = require('../../helpers/dataPaths'); const { resolveDataDir, resolveDataPath } = require('../../helpers/dataPaths');
const { isAdmin, roleEvents } = require('../roleService'); const { isAdmin, roleEvents } = require('../roleService');
const roverManager = require('../roverManager'); const roverManager = require('../roverManager');
@@ -344,6 +344,32 @@ io.on('connection', (socket) => {
loadState(); loadState();
registerConfigurationHandler('audioLevels', async (nextConfig) => {
/*
Audio levels also have a durable operational store because administrators
can adjust them outside the configuration editor. Applying a configuration
revision intentionally updates that same live state, rather than changing
startup fallbacks that an existing store would immediately override.
*/
const current = loadState();
persistState({
...current,
hornGain: clampGain(nextConfig.hornGain, current.hornGain),
ttsGain: clampGain(nextConfig.ttsGain, current.ttsGain),
forwardGain: clampGain(nextConfig.forwardGain, current.forwardGain),
maxPersonalAdjustmentPercent: clampMaximumAdjustmentPercent(
nextConfig.maxPersonalAdjustmentPercent,
current.maxPersonalAdjustmentPercent,
),
updatedAt: Date.now(),
updatedBy: 'configuration',
adjustmentRangeUpdatedAt: Date.now(),
adjustmentRangeUpdatedBy: 'configuration',
});
pushLevelsToAllRovers();
emitChange('configuration_applied');
});
module.exports = { module.exports = {
ADJUSTMENT_FIELDS, ADJUSTMENT_FIELDS,
PERSONAL_ADJUSTMENT_PERMISSION, PERSONAL_ADJUSTMENT_PERMISSION,
@@ -8,7 +8,7 @@ module.exports = {
feature: true, feature: true,
defaultValue: { enabled: false, simulate: false }, defaultValue: { enabled: false, simulate: false },
schema: strictObject({ schema: strictObject({
enabled: boolean({ description: 'Starts the Wii Balance Board service and exposes its readings and controls after restart.' }), enabled: boolean({ description: 'Immediately starts the Wii Balance Board service and exposes its readings and controls.' }),
simulate: boolean({ description: 'Runs the native worker with generated cyclic sensor data instead of connecting to Bluetooth hardware.' }), simulate: boolean({ description: 'Runs the native worker with generated cyclic sensor data instead of connecting to Bluetooth hardware.' }),
}, { }, {
title: 'Balance Board', title: 'Balance Board',
@@ -7,15 +7,15 @@ const { promisify } = require('util');
const EventEmitter = require('events'); const EventEmitter = require('events');
const io = require('../../globals/io'); const io = require('../../globals/io');
const logger = require('../../globals/logger').child('balanceBoardService'); const logger = require('../../globals/logger').child('balanceBoardService');
const { loadConfig } = require('../../configuration'); const { loadConfig, registerConfigurationHandler } = require('../../configuration');
const { resolveDataDir, resolveDataPath } = require('../../helpers/dataPaths'); const { resolveDataDir, resolveDataPath } = require('../../helpers/dataPaths');
const { isAdmin } = require('../roleService'); const { isAdmin } = require('../roleService');
const { sendAlert } = require('../alertService'); const { sendAlert } = require('../alertService');
const { createBalanceBoardHardware } = require('./hardware'); const { createBalanceBoardHardware } = require('./hardware');
const events = new EventEmitter(); const events = new EventEmitter();
const rawConfig = loadConfig().balanceBoard || {}; let rawConfig = loadConfig().balanceBoard || {};
const enabled = Boolean(rawConfig.enabled); let enabled = Boolean(rawConfig.enabled);
const DATA_DIR = resolveDataDir(); const DATA_DIR = resolveDataDir();
const STORE_PATH = resolveDataPath('balance-board.json'); const STORE_PATH = resolveDataPath('balance-board.json');
const FRAME_ROOM = 'balance-board-viewers'; const FRAME_ROOM = 'balance-board-viewers';
@@ -452,12 +452,14 @@ function handleWorkerMessage(message = {}) {
io.on('connection', (socket) => { io.on('connection', (socket) => {
socket.on('balanceBoard:subscribe', (_payload = {}, cb = () => {}) => { socket.on('balanceBoard:subscribe', (_payload = {}, cb = () => {}) => {
if (!enabled) return cb({ error: 'Balance Board is disabled' });
socket.join(FRAME_ROOM); socket.join(FRAME_ROOM);
if (latestFrame) socket.emit('balanceBoard:frame', latestFrame); if (latestFrame) socket.emit('balanceBoard:frame', latestFrame);
cb({ success: true }); cb({ success: true });
}); });
socket.on('balanceBoard:unsubscribe', () => socket.leave(FRAME_ROOM)); socket.on('balanceBoard:unsubscribe', () => socket.leave(FRAME_ROOM));
socket.on('balanceBoard:zero', (_payload = {}, cb = () => {}) => { socket.on('balanceBoard:zero', (_payload = {}, cb = () => {}) => {
if (!enabled) return cb({ error: 'Balance Board is disabled' });
if (!isAdmin(socket)) { if (!isAdmin(socket)) {
cb({ error: 'Admin access required' }); cb({ error: 'Admin access required' });
return; return;
@@ -470,6 +472,7 @@ io.on('connection', (socket) => {
} }
}); });
socket.on('balanceBoard:resetRecord', (_payload = {}, cb = () => {}) => { socket.on('balanceBoard:resetRecord', (_payload = {}, cb = () => {}) => {
if (!enabled) return cb({ error: 'Balance Board is disabled' });
if (!isAdmin(socket)) { if (!isAdmin(socket)) {
cb({ error: 'Admin access required' }); cb({ error: 'Admin access required' });
return; return;
@@ -484,6 +487,7 @@ io.on('connection', (socket) => {
} }
}); });
socket.on('balanceBoard:unpair', async (_payload = {}, cb = () => {}) => { socket.on('balanceBoard:unpair', async (_payload = {}, cb = () => {}) => {
if (!enabled) return cb({ error: 'Balance Board is disabled' });
if (!isAdmin(socket)) { if (!isAdmin(socket)) {
cb({ error: 'Admin access required' }); cb({ error: 'Admin access required' });
return; return;
@@ -546,7 +550,7 @@ io.on('connection', (socket) => {
}); });
}); });
if (enabled) { function startHardware() {
hardware = createBalanceBoardHardware({ hardware = createBalanceBoardHardware({
logger, logger,
address: store.address, address: store.address,
@@ -554,10 +558,38 @@ if (enabled) {
}); });
hardware.events.on('message', handleWorkerMessage); hardware.events.on('message', handleWorkerMessage);
hardware.start(); hardware.start();
}
if (enabled) {
startHardware();
} else { } else {
logger.info('Balance Board disabled by config'); logger.info('Balance Board disabled by config');
} }
registerConfigurationHandler('balanceBoard', (nextConfig = {}) => {
const wasEnabled = enabled;
hardware?.stop();
hardware = null;
clearZeroTimer();
rawConfig = nextConfig;
enabled = Boolean(rawConfig.enabled);
if (!wasEnabled && enabled) store = loadStore();
connected = false;
batteryPercent = null;
latestFrame = null;
latestRawCorners = null;
latestRawFrameAt = 0;
if (enabled) {
status = store.address ? 'waiting' : 'starting';
detail = store.address ? 'Press the front power button.' : 'Starting Bluetooth discovery.';
startHardware();
} else {
status = 'disabled';
detail = 'Balance Board support is disabled.';
}
events.emit('change', getState());
});
function installShutdownHooks() { function installShutdownHooks() {
const shutdown = () => { const shutdown = () => {
clearZeroTimer(); clearZeroTimer();
+31 -25
View File
@@ -5,7 +5,7 @@
// remain thin IO surfaces that subscribe to state and send votes/scans. // remain thin IO surfaces that subscribe to state and send votes/scans.
const io = require('../../globals/io'); const io = require('../../globals/io');
const logger = require('../../globals/logger').child('barcodeGameService'); const logger = require('../../globals/logger').child('barcodeGameService');
const { loadConfig } = require('../../configuration'); const { loadConfig, registerConfigurationHandler } = require('../../configuration');
const { subscribe } = require('../eventBus'); const { subscribe } = require('../eventBus');
const { sendSystemMessage } = require('../chatService'); const { sendSystemMessage } = require('../chatService');
const { getActiveDrivers } = require('../turnService'); const { getActiveDrivers } = require('../turnService');
@@ -28,11 +28,17 @@ const RESULTS_WINDOW_MS = 45 * 1000;
const GAME_DEFINITIONS = [scanQuest, scansPerSecond, mostItems]; const GAME_DEFINITIONS = [scanQuest, scansPerSecond, mostItems];
const GAMES_BY_ID = Object.fromEntries(GAME_DEFINITIONS.map((game) => [game.id, game])); const GAMES_BY_ID = Object.fromEntries(GAME_DEFINITIONS.map((game) => [game.id, game]));
const config = loadConfig(); let enabled;
const barcodeGamesConfig = config.barcodeGames || {}; let botName;
const enabled = Boolean(barcodeGamesConfig.enabled); let botProfileImageUrl;
const botName = String(barcodeGamesConfig.botName || 'Barcode Games').trim() || 'Barcode Games';
const botProfileImageUrl = String(barcodeGamesConfig.profileImageUrl || '').trim() || null; function applyBarcodeGameConfig(barcodeGamesConfig = {}) {
enabled = Boolean(barcodeGamesConfig.enabled);
botName = String(barcodeGamesConfig.botName || 'Barcode Games').trim() || 'Barcode Games';
botProfileImageUrl = String(barcodeGamesConfig.profileImageUrl || '').trim() || null;
}
applyBarcodeGameConfig(loadConfig().barcodeGames || {});
function sendBarcodeGameChat(text) { function sendBarcodeGameChat(text) {
const message = String(text || '').trim(); const message = String(text || '').trim();
@@ -767,6 +773,7 @@ function settleActiveGameIfNeeded() {
} }
function handleScan(scan) { function handleScan(scan) {
if (!enabled) return;
const now = Number.isFinite(scan?.scannedAt) ? scan.scannedAt : Date.now(); const now = Number.isFinite(scan?.scannedAt) ? scan.scannedAt : Date.now();
withGameStore((draft) => { withGameStore((draft) => {
updateGlobalCounters(draft, scan, now); updateGlobalCounters(draft, scan, now);
@@ -1121,15 +1128,9 @@ function broadcastState() {
}); });
} }
if (enabled) { io.on('connection', (socket) => {
/*
Barcode games are an optional layer on top of the physical scanner station.
The game's own switch controls whether its sockets and subscriptions exist.
Scanner availability is runtime state and must not silently override the
operator's explicit choice to enable the game service.
*/
io.on('connection', (socket) => {
socket.on('barcodeGame:subscribe', (_payload = {}, cb = () => {}) => { socket.on('barcodeGame:subscribe', (_payload = {}, cb = () => {}) => {
if (!enabled) return cb({ error: 'barcode games disabled' });
socket.join(GAME_SOCKET_ROOM); socket.join(GAME_SOCKET_ROOM);
const state = buildStatePayload(socket); const state = buildStatePayload(socket);
socket.emit('barcodeGame:state', state); socket.emit('barcodeGame:state', state);
@@ -1137,6 +1138,7 @@ if (enabled) {
}); });
socket.on('barcodeGame:vote', ({ gameId } = {}, cb = () => {}) => { socket.on('barcodeGame:vote', ({ gameId } = {}, cb = () => {}) => {
if (!enabled) return cb({ error: 'barcode games disabled' });
try { try {
cb(setVote(socket, gameId)); cb(setVote(socket, gameId));
} catch (err) { } catch (err) {
@@ -1145,9 +1147,9 @@ if (enabled) {
} }
}); });
}); });
subscribe('barcode.scanned', (event) => { subscribe('barcode.scanned', (event) => {
try { try {
handleScan(event.payload); handleScan(event.payload);
} catch (err) { } catch (err) {
@@ -1155,21 +1157,25 @@ if (enabled) {
// are logged and skipped so the scanner page can keep resolving barcodes. // are logged and skipped so the scanner page can keep resolving barcodes.
logger.warn('Barcode game scan handling failed', { error: err.message }); logger.warn('Barcode game scan handling failed', { error: err.message });
} }
}); });
} else {
if (!enabled) {
logger.info('Barcode games disabled by config'); logger.info('Barcode games disabled by config');
} }
registerConfigurationHandler('barcodeGames', (barcodeGamesConfig = {}) => {
applyBarcodeGameConfig(barcodeGamesConfig);
broadcastState();
});
module.exports = { module.exports = {
buildStatePayload, buildStatePayload,
handleScan, handleScan,
setVote, setVote,
}; };
if (enabled) { setInterval(() => {
setInterval(() => { if (enabled && settleActiveGameIfNeeded()) {
if (settleActiveGameIfNeeded()) { broadcastState();
broadcastState(); }
} }, GAME_TICK_MS).unref?.();
}, GAME_TICK_MS).unref?.();
}
@@ -8,7 +8,7 @@ module.exports = {
feature: true, feature: true,
defaultValue: { enabled: false }, defaultValue: { enabled: false },
schema: strictObject({ schema: strictObject({
enabled: boolean({ description: 'Registers barcode scanning, barcode administration, and scan-triggered server behavior after restart.' }), enabled: boolean({ description: 'Immediately enables barcode scanning, barcode administration, and scan-triggered server behavior.' }),
}, { }, {
title: 'Barcode scanner', title: 'Barcode scanner',
description: 'Optional physical barcode scanning and barcode registry service.', description: 'Optional physical barcode scanning and barcode registry service.',
@@ -4,7 +4,7 @@
const fs = require('fs'); const fs = require('fs');
const io = require('../../globals/io'); const io = require('../../globals/io');
const logger = require('../../globals/logger').child('barcodeScannerService'); const logger = require('../../globals/logger').child('barcodeScannerService');
const { loadConfig } = require('../../configuration'); const { loadConfig, registerConfigurationHandler } = require('../../configuration');
const { resolveDataDir, resolveDataPath } = require('../../helpers/dataPaths'); const { resolveDataDir, resolveDataPath } = require('../../helpers/dataPaths');
const { getMode, MODES, modeEvents } = require('../modeManager'); const { getMode, MODES, modeEvents } = require('../modeManager');
const { publishEvent } = require('../eventBus'); const { publishEvent } = require('../eventBus');
@@ -15,7 +15,7 @@ const REGISTRY_PATH = resolveDataPath('barcode-registry.json');
const RECENT_SCAN_LIMIT = 8; const RECENT_SCAN_LIMIT = 8;
const VALID_CODE_PATTERN = /^[a-z][0-9]{3}$/; const VALID_CODE_PATTERN = /^[a-z][0-9]{3}$/;
const SCANNER_SOCKET_ROOM = 'barcode-scanner'; const SCANNER_SOCKET_ROOM = 'barcode-scanner';
const enabled = Boolean(loadConfig().barcodeScanner?.enabled); let enabled = Boolean(loadConfig().barcodeScanner?.enabled);
let lastKnownGoodRegistry = null; let lastKnownGoodRegistry = null;
let lastRegistryError = null; let lastRegistryError = null;
@@ -312,19 +312,16 @@ async function applyScan(rawCode) {
return { result }; return { result };
} }
if (enabled) { io.on('connection', (socket) => {
/*
Barcode scanning is tied to a physical scanner station. Disabled installs
should not create the registry file or expose scanner socket commands.
*/
io.on('connection', (socket) => {
socket.on('barcode:subscribe', (_payload = {}, cb = () => {}) => { socket.on('barcode:subscribe', (_payload = {}, cb = () => {}) => {
if (!enabled) return cb({ error: 'barcode scanner disabled' });
socket.join(SCANNER_SOCKET_ROOM); socket.join(SCANNER_SOCKET_ROOM);
socket.emit('barcode:state', buildStatePayload()); socket.emit('barcode:state', buildStatePayload());
cb({ success: true, state: buildStatePayload() }); cb({ success: true, state: buildStatePayload() });
}); });
socket.on('barcode:scan', async ({ code } = {}, cb = () => {}) => { socket.on('barcode:scan', async ({ code } = {}, cb = () => {}) => {
if (!enabled) return cb({ error: 'barcode scanner disabled' });
try { try {
const { result } = await applyScan(code); const { result } = await applyScan(code);
cb({ success: true, result, state: buildStatePayload() }); cb({ success: true, result, state: buildStatePayload() });
@@ -336,20 +333,28 @@ if (enabled) {
cb({ error: err.message || 'barcode scan failed' }); cb({ error: err.message || 'barcode scan failed' });
} }
}); });
}); });
modeEvents.on('change', () => { modeEvents.on('change', () => {
// Access-mode changes affect whether the scanner page should beep when it // Access-mode changes affect whether the scanner page should beep when it
// submits a code, so scanner clients need a fresh state packet even without a // submits a code, so scanner clients need a fresh state packet even without a
// new scan. // new scan.
broadcastState(); broadcastState();
}); });
if (enabled) {
loadRegistryForScan(); loadRegistryForScan();
} else { } else {
logger.info('Barcode scanner disabled by config'); logger.info('Barcode scanner disabled by config');
} }
registerConfigurationHandler('barcodeScanner', (scannerConfig = {}) => {
const wasEnabled = enabled;
enabled = Boolean(scannerConfig.enabled);
if (!wasEnabled && enabled) loadRegistryForScan();
broadcastState();
});
module.exports = { module.exports = {
REGISTRY_PATH, REGISTRY_PATH,
applyScan: (...args) => { applyScan: (...args) => {
@@ -8,7 +8,7 @@ module.exports = {
feature: true, feature: true,
defaultValue: { enabled: false }, defaultValue: { enabled: false },
schema: strictObject({ schema: strictObject({
enabled: boolean({ description: 'Registers the physical button-box input route and enables its persistent button rewards and effects after restart.' }), enabled: boolean({ description: 'Immediately enables the physical button-box input route and its persistent button rewards and effects.' }),
}, { }, {
title: 'Button box', title: 'Button box',
description: 'Optional physical button-box input and reward system.', description: 'Optional physical button-box input and reward system.',
@@ -10,6 +10,7 @@ function registerButtonBoxRoute(deps) {
buttonCount, buttonCount,
normalizeIp, normalizeIp,
isLocalNetwork, isLocalNetwork,
isEnabled,
applyPress, applyPress,
} = deps; } = deps;
@@ -39,6 +40,13 @@ function registerButtonBoxRoute(deps) {
} }
app.post('/buttonbox/press', express.text({ type: 'text/plain' }), async (req, res) => { app.post('/buttonbox/press', express.text({ type: 'text/plain' }), async (req, res) => {
// The route stays registered for the life of Express, but the service gate
// is evaluated per request so the physical endpoint enables and disables
// immediately without accumulating duplicate routes.
if (!isEnabled()) {
res.status(503).json({ error: 'Button box is disabled' });
return;
}
if (denyIfNotLocal(req, res)) return; if (denyIfNotLocal(req, res)) return;
const buttonId = parseButtonId(req.body); const buttonId = parseButtonId(req.body);
if (!Number.isFinite(buttonId) || buttonId < 1 || buttonId > buttonCount) { if (!Number.isFinite(buttonId) || buttonId < 1 || buttonId > buttonCount) {
+25 -15
View File
@@ -4,7 +4,7 @@
const { app } = require('../../globals/http'); const { app } = require('../../globals/http');
const io = require('../../globals/io'); const io = require('../../globals/io');
const logger = require('../../globals/logger').child('buttonBoxService'); const logger = require('../../globals/logger').child('buttonBoxService');
const { loadConfig } = require('../../configuration'); const { loadConfig, registerConfigurationHandler } = require('../../configuration');
const { resolveDataDir, resolveDataPath } = require('../../helpers/dataPaths'); const { resolveDataDir, resolveDataPath } = require('../../helpers/dataPaths');
const { publishEvent } = require('../eventBus'); const { publishEvent } = require('../eventBus');
const { getRewardById, listRewards } = require('../../rewards'); const { getRewardById, listRewards } = require('../../rewards');
@@ -30,7 +30,7 @@ const DATA_DIR = resolveDataDir();
const STORE_PATH = resolveDataPath('buttonbox-state.json'); const STORE_PATH = resolveDataPath('buttonbox-state.json');
const BUTTON_COUNT = 4; const BUTTON_COUNT = 4;
const STORE_VERSION = 1; const STORE_VERSION = 1;
const enabled = Boolean(loadConfig().buttonBox?.enabled); let enabled = Boolean(loadConfig().buttonBox?.enabled);
const store = createButtonBoxStore({ const store = createButtonBoxStore({
logger, logger,
@@ -73,28 +73,38 @@ const core = createButtonBoxCore({
store, store,
}); });
if (enabled) { registerButtonBoxRoute({
/* app,
The button box is physical local hardware, so disabled public installs logger,
should not expose its LAN-only press endpoint or initialize its reward file. buttonCount: BUTTON_COUNT,
*/ normalizeIp,
registerButtonBoxRoute({ isLocalNetwork,
app, isEnabled: () => enabled,
logger, applyPress: core.applyPress,
buttonCount: BUTTON_COUNT, });
normalizeIp,
isLocalNetwork,
applyPress: core.applyPress,
});
function enableButtonBox() {
store.loadState(); store.loadState();
core.recoverEffects().catch((err) => { core.recoverEffects().catch((err) => {
logger.warn('Button box effect recovery failed', err.message); logger.warn('Button box effect recovery failed', err.message);
}); });
}
if (enabled) {
enableButtonBox();
} else { } else {
logger.info('Button box disabled by config'); logger.info('Button box disabled by config');
} }
registerConfigurationHandler('buttonBox', (buttonBoxConfig = {}) => {
const wasEnabled = enabled;
enabled = Boolean(buttonBoxConfig.enabled);
// Persistent state is loaded only on the transition to enabled. The core has
// no long-running hardware client, so disabling is completely represented by
// the route and public-method gates.
if (!wasEnabled && enabled) enableButtonBox();
});
module.exports = { module.exports = {
getButtonBoxState: () => { getButtonBoxState: () => {
/* /*
@@ -43,11 +43,8 @@ const {
createReplaySourceResolver, createReplaySourceResolver,
} = require('../replayDeliveryService/workflow'); } = require('../replayDeliveryService/workflow');
const config = loadConfig();
const discordConfig = config.discord || {};
function isTextCommand(text) { function isTextCommand(text) {
return parseCommandText(text, config).matched; return parseCommandText(text).matched;
} }
function sanitizeMentions(text) { function sanitizeMentions(text) {
@@ -142,6 +139,11 @@ function createChatCommandRequest({ socket, text, sendSystemMessage }) {
async function runChatTextCommand({ text, socket, sendSystemMessage }) { async function runChatTextCommand({ text, socket, sendSystemMessage }) {
if (!isTextCommand(text)) return false; if (!isTextCommand(text)) return false;
// Commands are assembled per message already, so reading the live snapshot
// here applies prefix, URL, and integration settings without retaining a
// stale dependency object between configuration revisions.
const config = loadConfig();
const discordConfig = config.discord || {};
// ReplayEngineV2 has startup side effects by design. Loading it lazily here // ReplayEngineV2 has startup side effects by design. Loading it lazily here
// keeps ordinary chatService initialization from changing the service boot // keeps ordinary chatService initialization from changing the service boot
// order, while still letting `rs replay` use the existing replay pipeline. // order, while still letting `rs replay` use the existing replay pipeline.
@@ -28,7 +28,7 @@ module.exports = {
}, },
}, },
schema: strictObject({ schema: strictObject({
enabled: boolean({ description: 'Logs the Discord bot in and enables commands, chat bridges, replay delivery, and configured announcements after restart.' }), enabled: boolean({ description: 'Logs the Discord bot in and immediately enables commands, chat bridges, replay delivery, and configured announcements.' }),
token: string({ title: 'Bot token', description: 'Discord bot token used to log in. The saved value is never returned to the browser.', examples: ['DISCORD_BOT_TOKEN'], writeOnly: true, maxLength: 10000 }), token: string({ title: 'Bot token', description: 'Discord bot token used to log in. The saved value is never returned to the browser.', examples: ['DISCORD_BOT_TOKEN'], writeOnly: true, maxLength: 10000 }),
guildId: string({ title: 'Guild id', description: 'Reserved Discord server identifier. The current bot runtime does not restrict commands or events using this value.', examples: ['123456789012345678'], maxLength: 100 }), guildId: string({ title: 'Guild id', description: 'Reserved Discord server identifier. The current bot runtime does not restrict commands or events using this value.', examples: ['123456789012345678'], maxLength: 100 }),
siteUrl: string({ title: 'Public site URL', description: 'Public base URL appended to announcement embeds and server-hosted replay links.', examples: ['https://rover.example.com'], maxLength: 2048 }), siteUrl: string({ title: 'Public site URL', description: 'Public base URL appended to announcement embeds and server-hosted replay links.', examples: ['https://rover.example.com'], maxLength: 2048 }),
+80 -22
View File
@@ -9,7 +9,12 @@ const {
} = require('discord.js'); } = require('discord.js');
const logger = require('../../globals/logger').child('discordBot'); const logger = require('../../globals/logger').child('discordBot');
const io = require('../../globals/io'); const io = require('../../globals/io');
const { loadConfig, getConfigurationDatabase, isFeatureEnabled } = require('../../configuration'); const {
loadConfig,
getConfigurationDatabase,
isFeatureEnabled,
registerConfigurationHandler,
} = require('../../configuration');
const { parseCommandText } = require('../operatorCommandService/config'); const { parseCommandText } = require('../operatorCommandService/config');
const roverManager = require('../roverManager'); const roverManager = require('../roverManager');
const { getRoster, lockRover, rovers } = roverManager; const { getRoster, lockRover, rovers } = roverManager;
@@ -79,9 +84,12 @@ const {
buildStatusMessage, buildStatusMessage,
} = require('../replayDeliveryService/workflow'); } = require('../replayDeliveryService/workflow');
const config = loadConfig(); // Discord helper modules retain references to these objects. Mutating those
// references on configuration application updates command and integration
// behavior without registering a second tree of Discord/event listeners.
const config = structuredClone(loadConfig());
const discordConfig = config.discord || {}; const discordConfig = config.discord || {};
const enabled = Boolean(discordConfig.enabled); let enabled = Boolean(discordConfig.enabled);
// These normalized command names mirror the command router. Bridge-channel // These normalized command names mirror the command router. Bridge-channel
// command replies are mirrored into web chat, so this entrypoint needs to know // command replies are mirrored into web chat, so this entrypoint needs to know
// the configured command names before it wraps message.reply. // the configured command names before it wraps message.reply.
@@ -89,10 +97,7 @@ const configuredAdministrators = getConfigurationDatabase().listAdministrators()
const adminIds = new Set(configuredAdministrators.map((admin) => String(admin.discordId || '').trim()).filter(Boolean)); const adminIds = new Set(configuredAdministrators.map((admin) => String(admin.discordId || '').trim()).filter(Boolean));
const lockdownAdminIds = new Set(configuredAdministrators.filter((admin) => admin.role === 'lockdown').map((admin) => String(admin.discordId || '').trim()).filter(Boolean)); const lockdownAdminIds = new Set(configuredAdministrators.filter((admin) => admin.role === 'lockdown').map((admin) => String(admin.discordId || '').trim()).filter(Boolean));
if (!enabled) { if (!enabled) logger.info('Discord disabled by config');
logger.info('Discord disabled by config');
return;
}
const intents = [ const intents = [
GatewayIntentBits.Guilds, GatewayIntentBits.Guilds,
@@ -157,10 +162,10 @@ const replayCaption = createReplayCaptionBuilder({
// Discord is the preferred replay host only while this optional feature is // Discord is the preferred replay host only while this optional feature is
// active. The core replay delivery service owns generation and automatically // active. The core replay delivery service owns generation and automatically
// falls back to its local media store when any operation below fails. // falls back to its local media store when any operation below fails.
if (discordConfig?.channels?.replay) { registerPreferredDeliveryProvider({
registerPreferredDeliveryProvider({
async begin(job) { async begin(job) {
const channelId = discordConfig.channels.replay; const channelId = discordConfig.channels?.replay;
if (!enabled || !channelId) throw new Error('Discord replay delivery is disabled');
const progressMessage = await channelIO.sendToChannel(channelId, buildAcceptedMessage(job), {}, DEFAULT_ALLOWED_MENTIONS); const progressMessage = await channelIO.sendToChannel(channelId, buildAcceptedMessage(job), {}, DEFAULT_ALLOWED_MENTIONS);
if (!progressMessage) throw new Error('Discord replay progress message could not be sent'); if (!progressMessage) throw new Error('Discord replay progress message could not be sent');
const channel = await channelIO.fetchChannel(channelId); const channel = await channelIO.fetchChannel(channelId);
@@ -210,8 +215,7 @@ if (discordConfig?.channels?.replay) {
}); });
} }
}, },
}); });
}
const commandDependencies = { const commandDependencies = {
logger, logger,
@@ -366,24 +370,78 @@ client.on('messageCreate', async (message) => {
} }
}); });
client.once('ready', () => { let fleetDailyReports = null;
logger.info('Discord bot logged in', { tag: client.user?.tag });
presence.schedulePresenceRotation(); function restartFleetDailyReports() {
// Discord is only a delivery consumer. Starting its scheduler after the bot fleetDailyReports?.stop();
// is ready avoids failed sends during login while the collector continues to fleetDailyReports = createFleetDailyReports({
// operate independently of Discord availability.
createFleetDailyReports({
logger, logger,
discordConfig, discordConfig,
fleetConfig: config.fleetReports || {}, fleetConfig: config.fleetReports || {},
fleetReportService, fleetReportService,
roverManager, roverManager,
sendToChannel: channelIO.sendToChannel, sendToChannel: channelIO.sendToChannel,
}).start(); });
fleetDailyReports.start();
}
client.on('ready', () => {
logger.info('Discord bot logged in', { tag: client.user?.tag });
presence.schedulePresenceRotation();
// Discord is only a delivery consumer. Starting its scheduler after the bot
// is ready avoids failed sends during login while the collector continues to
// operate independently of Discord availability.
restartFleetDailyReports();
}); });
client.login(discordConfig.token).catch((err) => { function replaceObject(target, source = {}) {
logger.error('Discord login failed', err.message); Object.keys(target).forEach((key) => delete target[key]);
Object.assign(target, structuredClone(source));
}
function applyDiscordConfig(nextDiscordConfig = {}) {
const wasEnabled = enabled;
const previousToken = discordConfig.token;
replaceObject(discordConfig, nextDiscordConfig);
config.discord = discordConfig;
enabled = Boolean(discordConfig.enabled);
if (!enabled) {
fleetDailyReports?.stop();
fleetDailyReports = null;
if (wasEnabled) client.destroy();
return;
}
if (!wasEnabled || previousToken !== discordConfig.token) {
if (wasEnabled) client.destroy();
// Login health is reported by Discord itself; do not hold the committed
// configuration request open while an external network service connects.
client.login(discordConfig.token).catch((err) => {
logger.error('Discord login failed after configuration change', err.message);
});
} else if (client.isReady()) {
restartFleetDailyReports();
}
}
function applySharedConfigSection(section, value) {
config[section] = structuredClone(value);
// Fleet delivery owns a timer derived from both Discord and fleet settings.
// Reconnecting is unnecessary; rebuild only that scheduler when ready.
if (section === 'fleetReports' && client.isReady()) {
restartFleetDailyReports();
}
}
registerConfigurationHandler('discord', applyDiscordConfig);
['commands', 'timezone', 'fleetReports'].forEach((section) => {
registerConfigurationHandler(section, (value) => applySharedConfigSection(section, value));
}); });
if (enabled) {
client.login(discordConfig.token).catch((err) => {
logger.error('Discord login failed', err.message);
});
}
module.exports = {}; module.exports = {};
@@ -22,9 +22,12 @@ function createUserAnnouncements(deps) {
schedulePresenceRotation, schedulePresenceRotation,
} = deps; } = deps;
const announcementChannelId = discordConfig?.channels?.announcements || null; // The parent Discord service preserves this object identity and updates its
const announcementRoleId = discordConfig?.roles?.announcementPing || null; // contents on live configuration application. Resolve individual values at
const siteUrl = discordConfig?.siteUrl ? String(discordConfig.siteUrl) : ''; // send/render time so announcements do not retain stale channel or site data.
const getAnnouncementChannelId = () => discordConfig?.channels?.announcements || null;
const getAnnouncementRoleId = () => discordConfig?.roles?.announcementPing || null;
const getSiteUrl = () => (discordConfig?.siteUrl ? String(discordConfig.siteUrl) : '');
let previousSnapshot = buildSnapshot(); let previousSnapshot = buildSnapshot();
let skippedFirstModeChange = false; let skippedFirstModeChange = false;
@@ -124,6 +127,7 @@ function createUserAnnouncements(deps) {
}); });
} }
const siteUrl = getSiteUrl();
if (siteUrl) { if (siteUrl) {
embed.addFields({ embed.addFields({
name: 'Join', name: 'Join',
@@ -136,6 +140,8 @@ function createUserAnnouncements(deps) {
} }
async function sendAnnouncement({ content, embeds, ping = false }) { async function sendAnnouncement({ content, embeds, ping = false }) {
const announcementChannelId = getAnnouncementChannelId();
const announcementRoleId = getAnnouncementRoleId();
if (!announcementChannelId) return; if (!announcementChannelId) return;
const shouldPing = Boolean(ping && announcementRoleId); const shouldPing = Boolean(ping && announcementRoleId);
const body = shouldPing ? `<@&${announcementRoleId}> ${content || ''}`.trim() : content; const body = shouldPing ? `<@&${announcementRoleId}> ${content || ''}`.trim() : content;
@@ -14,7 +14,7 @@ module.exports = {
privacy: { retainChatBodies: true }, privacy: { retainChatBodies: true },
}, },
schema: strictObject({ schema: strictObject({
enabled: boolean({ description: 'Starts persistent fleet metric collection, reports, retention cleanup, and configured daily delivery after restart.' }), enabled: boolean({ description: 'Immediately starts persistent fleet metric collection, reports, retention cleanup, and configured daily delivery.' }),
retention: strictObject({ retention: strictObject({
detailedDays: integer({ description: 'Days to retain detailed events, command observations, sessions, and other non-minute fleet records. Zero retains them indefinitely.', minimum: 0, maximum: 36500 }), detailedDays: integer({ description: 'Days to retain detailed events, command observations, sessions, and other non-minute fleet records. Zero retains them indefinitely.', minimum: 0, maximum: 36500 }),
minuteSamplesDays: integer({ description: 'Days to retain per-minute rover metric aggregates. Zero retains them indefinitely.', minimum: 0, maximum: 36500 }), minuteSamplesDays: integer({ description: 'Days to retain per-minute rover metric aggregates. Zero retains them indefinitely.', minimum: 0, maximum: 36500 }),
+84 -66
View File
@@ -1,25 +1,44 @@
// Fleet Report Service // Fleet Report Service
// Purpose: Composes optional passive collection, storage, analysis, retention, and read-only transport. // Purpose: Owns the replaceable collection/report runtime and its stable browser API.
// Scope: This is the sole feature boundary; disabled installations register no collectors, timers, database, or sockets. // Scope: Applies the complete fleetReports section without restarting the Node process.
const { loadConfig } = require('../../configuration'); const { loadConfig, registerConfigurationHandler } = require('../../configuration');
const logger = require('../../globals/logger').child('fleetReportService'); const logger = require('../../globals/logger').child('fleetReportService');
const { subscribeAll } = require('../eventBus');
const roverManager = require('../roverManager');
const { commandEvents } = require('../commandService');
const { odometerEvents } = require('../odometerService');
const { createStorage } = require('./storage');
const { createCollector } = require('./collector');
const { createReportBuilder } = require('./reportBuilder');
const { registerSocketGateway } = require('./socketGateway');
const config = loadConfig().fleetReports || {}; let runtime = null;
let storage = null;
if (!config.enabled) { function retentionDays(value, fallback) {
module.exports = { const number = Number(value);
enabled: false, return Number.isFinite(number) && number >= 0 ? number : fallback;
getDailyReport: () => null, }
};
} else { function stopRuntime() {
const { subscribeAll } = require('../eventBus'); if (!runtime) return;
const roverManager = require('../roverManager'); runtime.unsubscribeEvents();
const { commandEvents } = require('../commandService'); if (runtime.batteryEnabled) roverManager.managerEvents.off('sensor', runtime.collector.collectSensor);
const { odometerEvents } = require('../odometerService'); commandEvents.off('observation', runtime.collector.collectCommand);
const { createStorage } = require('./storage'); odometerEvents.off('update', runtime.collector.collectOdometer);
const { createCollector } = require('./collector'); runtime.managerEventHandlers.forEach((handler, kind) => roverManager.managerEvents.off(kind, handler));
const { createReportBuilder } = require('./reportBuilder'); clearInterval(runtime.flushTimer);
const { registerSocketGateway } = require('./socketGateway'); clearInterval(runtime.retentionTimer);
runtime.collector.flushMinutes();
runtime = null;
}
function startRuntime(config = {}) {
stopRuntime();
if (!config.enabled) {
logger.info('Fleet reporting disabled by config');
return;
}
const batteryConfig = config.battery || {}; const batteryConfig = config.battery || {};
const retentionConfig = config.retention || {}; const retentionConfig = config.retention || {};
@@ -31,11 +50,14 @@ if (!config.enabled) {
10, 10,
Math.min(100, Number(batteryConfig.minimumCapacityTestDepthPercent) || 60), Math.min(100, Number(batteryConfig.minimumCapacityTestDepthPercent) || 60),
); );
// Battery collection follows its own explicit nested switch. Defaults are
// supplied by the validated configuration document, so a missing value does
// not need a compatibility fallback that could accidentally enable it.
const batteryEnabled = Boolean(batteryConfig.enabled); const batteryEnabled = Boolean(batteryConfig.enabled);
const storage = createStorage({ logger });
// Keep one SQLite connection for the process lifetime. Configuration reloads
// replace collectors and timers, not the durable database they share.
if (!storage) {
storage = createStorage({ logger });
storage.open();
}
const collector = createCollector({ const collector = createCollector({
storage, storage,
logger, logger,
@@ -43,8 +65,6 @@ if (!config.enabled) {
minimumCapacityTestDepthPercent, minimumCapacityTestDepthPercent,
}); });
const reportBuilder = createReportBuilder({ storage, collector, roverManager }); const reportBuilder = createReportBuilder({ storage, collector, roverManager });
storage.open();
const unsubscribeEvents = subscribeAll(collector.collectEvent); const unsubscribeEvents = subscribeAll(collector.collectEvent);
if (batteryEnabled) roverManager.managerEvents.on('sensor', collector.collectSensor); if (batteryEnabled) roverManager.managerEvents.on('sensor', collector.collectSensor);
commandEvents.on('observation', collector.collectCommand); commandEvents.on('observation', collector.collectCommand);
@@ -55,18 +75,9 @@ if (!config.enabled) {
roverManager.managerEvents.on(kind, handler); roverManager.managerEvents.on(kind, handler);
return [kind, handler]; return [kind, handler];
})); }));
registerSocketGateway({ roverManager, reportBuilder, storage, collector, logger });
// Periodic upserts bound data-loss on an unclean shutdown while still
// avoiding writes at the 20 Hz sensor-frame rate.
const flushTimer = setInterval(() => collector.flushMinutes(), 30 * 1000); const flushTimer = setInterval(() => collector.flushMinutes(), 30 * 1000);
flushTimer.unref?.(); flushTimer.unref?.();
function retentionDays(value, fallback) {
const number = Number(value);
return Number.isFinite(number) && number >= 0 ? number : fallback;
}
function pruneNow() { function pruneNow() {
const now = Date.now(); const now = Date.now();
const detailedDays = retentionDays(retentionConfig.detailedDays, 0); const detailedDays = retentionDays(retentionConfig.detailedDays, 0);
@@ -80,43 +91,50 @@ if (!config.enabled) {
const retentionTimer = setInterval(pruneNow, 6 * 60 * 60 * 1000); const retentionTimer = setInterval(pruneNow, 6 * 60 * 60 * 1000);
retentionTimer.unref?.(); retentionTimer.unref?.();
function getDailyReport({ since, until, roverIds } = {}) { runtime = {
const end = Number(until) || Date.now(); batteryEnabled,
return reportBuilder.build({ storage,
since: Number(since) || end - 24 * 60 * 60 * 1000, collector,
until: end, reportBuilder,
roverIds: Array.isArray(roverIds) ? roverIds : undefined, unsubscribeEvents,
// Daily Discord output is intentionally metric-only. Avoiding the event managerEventHandlers,
// query here also prevents irrelevant event volume from bloating the flushTimer,
// durable daily snapshot that supports delivery idempotency. retentionTimer,
includeEvents: false, };
});
}
logger.info('Fleet reporting enabled', { logger.info('Fleet reporting enabled', {
databaseAvailable: storage.getDiagnostics().available, databaseAvailable: storage.getDiagnostics().available,
maximumIntegrationGapMs, maximumIntegrationGapMs,
minimumCapacityTestDepthPercent, minimumCapacityTestDepthPercent,
batteryEnabled, batteryEnabled,
}); });
module.exports = {
enabled: true,
getDailyReport,
collector,
storage,
reportBuilder,
// Exposed for controlled tests and graceful future shutdown wiring. Normal
// runtime leaves subscriptions active for the lifetime of the server.
stop() {
unsubscribeEvents();
if (batteryEnabled) roverManager.managerEvents.off('sensor', collector.collectSensor);
commandEvents.off('observation', collector.collectCommand);
odometerEvents.off('update', collector.collectOdometer);
managerEventHandlers.forEach((handler, kind) => roverManager.managerEvents.off(kind, handler));
clearInterval(flushTimer);
clearInterval(retentionTimer);
collector.flushMinutes();
},
};
} }
registerSocketGateway({ roverManager, getRuntime: () => runtime, logger });
startRuntime(loadConfig().fleetReports || {});
registerConfigurationHandler('fleetReports', startRuntime);
module.exports = {
get enabled() {
return Boolean(runtime);
},
getDailyReport({ since, until, roverIds } = {}) {
if (!runtime) return null;
const end = Number(until) || Date.now();
return runtime.reportBuilder.build({
since: Number(since) || end - 24 * 60 * 60 * 1000,
until: end,
roverIds: Array.isArray(roverIds) ? roverIds : undefined,
includeEvents: false,
});
},
get collector() {
return runtime?.collector || null;
},
get storage() {
return runtime?.storage || storage;
},
get reportBuilder() {
return runtime?.reportBuilder || null;
},
stop: stopRuntime,
};
@@ -17,10 +17,13 @@ function normalizeRange(payload = {}) {
return { since, until: Math.max(since + 1, until) }; return { since, until: Math.max(since + 1, until) };
} }
function registerSocketGateway({ roverManager, reportBuilder, storage, collector, logger }) { function registerSocketGateway({ roverManager, getRuntime, logger }) {
io.on('connection', (socket) => { io.on('connection', (socket) => {
socket.on('fleetReports:get', (payload = {}, cb = () => {}) => { socket.on('fleetReports:get', (payload = {}, cb = () => {}) => {
try { try {
const runtime = getRuntime();
if (!runtime) throw new Error('Fleet reports are disabled');
const { reportBuilder } = runtime;
const { since, until } = normalizeRange(payload); const { since, until } = normalizeRange(payload);
// getRosterForSocket is the canonical live private-rover visibility // getRosterForSocket is the canonical live private-rover visibility
// resolver. Historical queries use precisely those currently visible // resolver. Historical queries use precisely those currently visible
@@ -59,6 +62,9 @@ function registerSocketGateway({ roverManager, reportBuilder, storage, collector
socket.on('fleetReports:replaceBattery', (payload = {}, cb = () => {}) => { socket.on('fleetReports:replaceBattery', (payload = {}, cb = () => {}) => {
try { try {
const runtime = getRuntime();
if (!runtime) throw new Error('Fleet reports are disabled');
const { storage, collector } = runtime;
if (!isAdmin(socket)) throw new Error('Admin access required'); if (!isAdmin(socket)) throw new Error('Admin access required');
const roverId = String(payload.roverId || '').trim(); const roverId = String(payload.roverId || '').trim();
if (!roverId || !roverManager.rovers.has(roverId)) throw new Error('Known online rover required'); if (!roverId || !roverManager.rovers.has(roverId)) throw new Error('Known online rover required');
@@ -52,7 +52,7 @@ module.exports = {
], ],
}, },
schema: strictObject({ schema: strictObject({
enabled: boolean({ description: 'Connects to Home Assistant and enables configured room entities, physical-button triggers, Neato controls, and lift controls after restart.' }), enabled: boolean({ description: 'Immediately connects to Home Assistant and enables configured room entities, physical-button triggers, Neato controls, and lift controls.' }),
url: string({ title: 'Server URL', description: 'Base URL of the Home Assistant server used for its REST and WebSocket APIs.', format: 'uri', maxLength: 2048 }), url: string({ title: 'Server URL', description: 'Base URL of the Home Assistant server used for its REST and WebSocket APIs.', format: 'uri', maxLength: 2048 }),
token: string({ title: 'Long-lived access token', description: 'Home Assistant long-lived access token used to authenticate every API request. The saved value is never returned to the browser.', examples: ['REPLACE_WITH_LONG_LIVED_TOKEN'], writeOnly: true, maxLength: 20000 }), token: string({ title: 'Long-lived access token', description: 'Home Assistant long-lived access token used to authenticate every API request. The saved value is never returned to the browser.', examples: ['REPLACE_WITH_LONG_LIVED_TOKEN'], writeOnly: true, maxLength: 20000 }),
[neato.key]: neato.schema, [neato.key]: neato.schema,
@@ -8,7 +8,7 @@ const { isAdmin, isLockdownAdmin } = require('../roleService');
function registerHomeAssistantHooks(deps) { function registerHomeAssistantHooks(deps) {
const { const {
logger, logger,
haConfig, getHaConfig,
isLightControlLocked, isLightControlLocked,
setLightsLockedOn, setLightsLockedOn,
toggleEntity, toggleEntity,
@@ -110,7 +110,9 @@ function registerHomeAssistantHooks(deps) {
} }
try { try {
if (!entityId) throw new Error('entityId required'); if (!entityId) throw new Error('entityId required');
await setLightWhite(entityId, haConfig?.whiteKelvin); // Resolve configuration at interaction time because the socket handler
// is intentionally registered once and survives service reloads.
await setLightWhite(entityId, getHaConfig()?.whiteKelvin);
cb({ success: true }); cb({ success: true });
} catch (err) { } catch (err) {
cb({ error: err.message }); cb({ error: err.message });
@@ -2,83 +2,88 @@
// Purpose: Composes Home Assistant transport, runtime automation engine, and event/socket hooks. // Purpose: Composes Home Assistant transport, runtime automation engine, and event/socket hooks.
// Scope: Exposes stable room-control APIs while delegating internals to focused modules. // Scope: Exposes stable room-control APIs while delegating internals to focused modules.
const logger = require('../../globals/logger').child('homeAssistantService'); const logger = require('../../globals/logger').child('homeAssistantService');
const { loadConfig } = require('../../configuration'); const { loadConfig, registerConfigurationHandler } = require('../../configuration');
const { events } = require('./state'); const { events } = require('./state');
const { createRuntimeEngine } = require('./runtimeEngine'); const { createRuntimeEngine } = require('./runtimeEngine');
const { createTransport } = require('./transport'); const { createTransport } = require('./transport');
const { registerHomeAssistantHooks } = require('./hooks'); const { registerHomeAssistantHooks } = require('./hooks');
const config = loadConfig(); let current;
const haConfig = config.homeAssistant || {};
const enabled = Boolean(haConfig.enabled);
let callHomeAssistantServiceImpl = async () => { function createHomeAssistantRuntime(haConfig = {}) {
throw new Error('Home Assistant not connected'); const enabled = Boolean(haConfig.enabled);
}; let callHomeAssistantServiceImpl = async () => {
throw new Error('Home Assistant not connected');
const runtimeEngine = createRuntimeEngine({ };
logger, const runtimeEngine = createRuntimeEngine({
enabled,
haConfig,
callHomeAssistantService: (...args) => callHomeAssistantServiceImpl(...args),
});
const transport = createTransport({
logger,
enabled,
haConfig,
onSnapshot: runtimeEngine.handleEntitySnapshot,
onStatus: () => runtimeEngine.emitStatus(runtimeEngine.getState),
});
callHomeAssistantServiceImpl = transport.callHomeAssistantService;
runtimeEngine.loadEntityConfig();
runtimeEngine.loadTriggerConfig();
if (enabled) {
/*
Loading the module should be harmless on rover-only installs. The explicit
service-owned switch alone decides whether connection should be attempted;
missing credentials are then reported as a runtime connection failure.
*/
transport.connect();
}
if (enabled) {
/*
Socket routes are part of the visible Home Assistant feature. Register them
only when enabled so disabled installs do not expose hidden controls that
the UI has intentionally removed.
*/
registerHomeAssistantHooks({
logger, logger,
enabled,
haConfig, haConfig,
isLightControlLocked: runtimeEngine.isLightControlLocked, callHomeAssistantService: (...args) => callHomeAssistantServiceImpl(...args),
setLightsLockedOn: runtimeEngine.setLightsLockedOn,
toggleEntity: runtimeEngine.toggleEntity,
setEntityState: runtimeEngine.setEntityState,
setLightColor: runtimeEngine.setLightColor,
setLightWhite: runtimeEngine.setLightWhite,
}); });
const transport = createTransport({
logger,
enabled,
haConfig,
onSnapshot: runtimeEngine.handleEntitySnapshot,
onStatus: () => runtimeEngine.emitStatus(runtimeEngine.getState),
});
callHomeAssistantServiceImpl = transport.callHomeAssistantService;
runtimeEngine.loadEntityConfig();
runtimeEngine.loadTriggerConfig();
if (enabled) {
// A service reload creates one fresh transport with the new credentials and
// entity schema. Disabled installations perform no network work.
transport.connect();
}
return { enabled, haConfig, runtimeEngine, transport };
} }
function replaceHomeAssistantRuntime(haConfig) {
current?.transport.disconnect();
current = createHomeAssistantRuntime(haConfig);
}
replaceHomeAssistantRuntime(loadConfig().homeAssistant || {});
/*
Browser and mode hooks are registered exactly once. Their delegates resolve
`current` for every call, so a configuration save does not duplicate socket
listeners while still routing existing connections into the new runtime.
*/
registerHomeAssistantHooks({
logger,
getHaConfig: () => current.haConfig,
isLightControlLocked: (...args) => current.runtimeEngine.isLightControlLocked(...args),
setLightsLockedOn: (...args) => current.runtimeEngine.setLightsLockedOn(...args),
toggleEntity: (...args) => current.runtimeEngine.toggleEntity(...args),
setEntityState: (...args) => current.runtimeEngine.setEntityState(...args),
setLightColor: (...args) => current.runtimeEngine.setLightColor(...args),
setLightWhite: (...args) => current.runtimeEngine.setLightWhite(...args),
});
registerConfigurationHandler('homeAssistant', (haConfig) => {
replaceHomeAssistantRuntime(haConfig || {});
});
module.exports = { module.exports = {
getState: runtimeEngine.getState, getState: (...args) => current.runtimeEngine.getState(...args),
isConnected: transport.isConnected, isConnected: (...args) => current.transport.isConnected(...args),
enabled, get enabled() {
getLightPolicyState: runtimeEngine.getLightPolicyState, return current.enabled;
isLightControlLocked: runtimeEngine.isLightControlLocked, },
getRawEntitySnapshot: runtimeEngine.getRawEntitySnapshot, getLightPolicyState: (...args) => current.runtimeEngine.getLightPolicyState(...args),
getControllableEntityIds: runtimeEngine.getControllableEntityIds, isLightControlLocked: (...args) => current.runtimeEngine.isLightControlLocked(...args),
callHomeAssistantService: transport.callHomeAssistantService, getRawEntitySnapshot: (...args) => current.runtimeEngine.getRawEntitySnapshot(...args),
toggleEntity: runtimeEngine.toggleEntity, getControllableEntityIds: (...args) => current.runtimeEngine.getControllableEntityIds(...args),
setEntityState: runtimeEngine.setEntityState, callHomeAssistantService: (...args) => current.transport.callHomeAssistantService(...args),
setLightColor: runtimeEngine.setLightColor, toggleEntity: (...args) => current.runtimeEngine.toggleEntity(...args),
setLightWhite: runtimeEngine.setLightWhite, setEntityState: (...args) => current.runtimeEngine.setEntityState(...args),
setAllControllableEntitiesState: runtimeEngine.setAllControllableEntitiesState, setLightColor: (...args) => current.runtimeEngine.setLightColor(...args),
setRandomColorScene: runtimeEngine.setRandomColorScene, setLightWhite: (...args) => current.runtimeEngine.setLightWhite(...args),
setLightsLockedOn: runtimeEngine.setLightsLockedOn, setAllControllableEntitiesState: (...args) => current.runtimeEngine.setAllControllableEntitiesState(...args),
toggleLightsLockedOn: runtimeEngine.toggleLightsLockedOn, setRandomColorScene: (...args) => current.runtimeEngine.setRandomColorScene(...args),
setLightsLockedOn: (...args) => current.runtimeEngine.setLightsLockedOn(...args),
toggleLightsLockedOn: (...args) => current.runtimeEngine.toggleLightsLockedOn(...args),
homeAssistantEvents: events, homeAssistantEvents: events,
}; };
@@ -11,6 +11,9 @@ if (!global.WebSocket) {
function createTransport(deps) { function createTransport(deps) {
const { logger, enabled, haConfig, onSnapshot, onStatus } = deps; const { logger, enabled, haConfig, onSnapshot, onStatus } = deps;
let active = true;
let connection = null;
let unsubscribeEntities = null;
function getCallerFrame() { function getCallerFrame() {
const stack = new Error().stack || ''; const stack = new Error().stack || '';
const lines = stack.split('\n').slice(2).map((line) => line.trim()); const lines = stack.split('\n').slice(2).map((line) => line.trim());
@@ -37,33 +40,40 @@ function createTransport(deps) {
} }
function teardownConnection() { function teardownConnection() {
if (runtime.unsubscribeEntities) { const ownedUnsubscribe = unsubscribeEntities;
unsubscribeEntities = null;
if (ownedUnsubscribe) {
try { try {
runtime.unsubscribeEntities(); ownedUnsubscribe();
} catch (err) { } catch (err) {
logger.warn('Failed to unsubscribe entity stream', err.message); logger.warn('Failed to unsubscribe entity stream', err.message);
} }
} }
runtime.unsubscribeEntities = null; const ownedConnection = connection;
connection = null;
if (runtime.connection) { if (ownedConnection) {
try { try {
runtime.connection.close(); ownedConnection.close();
} catch (err) { } catch (err) {
logger.warn('Error closing Home Assistant connection', err.message); logger.warn('Error closing Home Assistant connection', err.message);
} }
} }
runtime.connection = null; // An old transport's delayed disconnected event must not clear the newer
const wasConnected = runtime.connected; // transport stored in shared runtime state after a configuration reload.
runtime.connected = false; if (runtime.connection === ownedConnection) {
if (wasConnected) { runtime.connection = null;
onStatus(); runtime.unsubscribeEntities = null;
const wasConnected = runtime.connected;
runtime.connected = false;
if (wasConnected) onStatus();
} }
} }
function scheduleReconnect(delayMs = 5000) { function scheduleReconnect(delayMs = 5000) {
if (!enabled) return; // A replaced transport must never reconnect after its successor has taken
// ownership of the shared Home Assistant connection state.
if (!active || !enabled) return;
if (runtime.reconnectTimer) return; if (runtime.reconnectTimer) return;
runtime.reconnectTimer = setTimeout(() => { runtime.reconnectTimer = setTimeout(() => {
runtime.reconnectTimer = null; runtime.reconnectTimer = null;
@@ -72,23 +82,30 @@ function createTransport(deps) {
} }
async function connect() { async function connect() {
if (!enabled) { if (!active || !enabled) {
// Disabled and misconfigured are intentionally different states. The // Disabled and misconfigured are intentionally different states. The
// explicit switch prevents connection attempts; missing credentials are // explicit switch prevents connection attempts; missing credentials are
// surfaced by buildAuth() as a runtime connection failure when enabled. // surfaced by buildAuth() as a runtime connection failure when enabled.
logger.info('Home Assistant disabled by config'); logger.info('Home Assistant disabled by config');
return; return;
} }
if (runtime.connection) return; if (connection) return;
try { try {
const auth = buildAuth(); const auth = buildAuth();
runtime.connection = await createConnection({ auth, setupRetry: 0 }); const nextConnection = await createConnection({ auth, setupRetry: 0 });
if (!active) {
nextConnection.close();
return;
}
connection = nextConnection;
runtime.connection = connection;
runtime.connected = true; runtime.connected = true;
onStatus(); onStatus();
logger.info('Connected to Home Assistant'); logger.info('Connected to Home Assistant');
runtime.unsubscribeEntities = subscribeEntities(runtime.connection, onSnapshot); unsubscribeEntities = subscribeEntities(connection, onSnapshot);
runtime.connection.addEventListener('disconnected', () => { runtime.unsubscribeEntities = unsubscribeEntities;
connection.addEventListener('disconnected', () => {
logger.warn('Home Assistant connection lost'); logger.warn('Home Assistant connection lost');
teardownConnection(); teardownConnection();
scheduleReconnect(); scheduleReconnect();
@@ -101,12 +118,12 @@ function createTransport(deps) {
} }
function isConnected() { function isConnected() {
return Boolean(runtime.connection && runtime.connected); return Boolean(connection && runtime.connection === connection && runtime.connected);
} }
async function callHomeAssistantService(domain, service, serviceData = {}) { async function callHomeAssistantService(domain, service, serviceData = {}) {
if (!enabled) throw new Error('Home Assistant not configured'); if (!active || !enabled) throw new Error('Home Assistant not configured');
if (!runtime.connection) throw new Error('Home Assistant not connected'); if (!connection || runtime.connection !== connection) throw new Error('Home Assistant not connected');
if (!domain || !service) throw new Error('domain and service required'); if (!domain || !service) throw new Error('domain and service required');
logger.info('Home Assistant outbound service call', { logger.info('Home Assistant outbound service call', {
domain: String(domain), domain: String(domain),
@@ -114,11 +131,24 @@ function createTransport(deps) {
serviceData: serviceData && typeof serviceData === 'object' ? { ...serviceData } : serviceData, serviceData: serviceData && typeof serviceData === 'object' ? { ...serviceData } : serviceData,
caller: getCallerFrame(), caller: getCallerFrame(),
}); });
await callService(runtime.connection, String(domain), String(service), serviceData || {}); await callService(connection, String(domain), String(service), serviceData || {});
}
function disconnect() {
// Configuration reloads deliberately retire the complete transport. Clear
// its pending retry before closing so the old credentials cannot race the
// newly created transport and reclaim the shared connection.
active = false;
if (runtime.reconnectTimer) {
clearTimeout(runtime.reconnectTimer);
runtime.reconnectTimer = null;
}
teardownConnection();
} }
return { return {
connect, connect,
disconnect,
isConnected, isConnected,
callHomeAssistantService, callHomeAssistantService,
}; };
@@ -6,7 +6,7 @@ const { v4: uuidv4 } = require('uuid');
const { app } = require('../../globals/http'); const { app } = require('../../globals/http');
const io = require('../../globals/io'); const io = require('../../globals/io');
const logger = require('../../globals/logger').child('interInstanceService'); const logger = require('../../globals/logger').child('interInstanceService');
const { loadConfig, getFeatureFlags } = require('../../configuration'); const { loadConfig, getFeatureFlags, registerConfigurationHandler } = require('../../configuration');
const { getConfiguredSocials } = require('../sessionService/configuration'); const { getConfiguredSocials } = require('../sessionService/configuration');
const { getMode, MODES } = require('../modeManager'); const { getMode, MODES } = require('../modeManager');
const roverManager = require('../roverManager'); const roverManager = require('../roverManager');
@@ -20,13 +20,13 @@ const DEFAULT_POLL_INTERVAL_MS = 30000;
const DEFAULT_REQUEST_TIMEOUT_MS = 5000; const DEFAULT_REQUEST_TIMEOUT_MS = 5000;
const INFO_PATH = '/api/inter-instance/info'; const INFO_PATH = '/api/inter-instance/info';
const INSTANCE_ID = uuidv4(); const INSTANCE_ID = uuidv4();
const config = loadConfig(); let interInstanceConfig = loadConfig().interInstance || {};
const interInstanceConfig = config.interInstance || {};
const profileConfig = interInstanceConfig.profile || {};
const interInstanceEvents = new EventEmitter(); const interInstanceEvents = new EventEmitter();
const remoteInstances = new Map(); const remoteInstances = new Map();
let polling = false; let pollGeneration = 0;
let pollingGeneration = null;
let pollTimer = null;
function asTrimmedString(value) { function asTrimmedString(value) {
return typeof value === 'string' ? value.trim() : ''; return typeof value === 'string' ? value.trim() : '';
} }
@@ -59,7 +59,7 @@ function pollIntervalMs() {
} }
function ownPublicUrl() { function ownPublicUrl() {
return normalizeBaseUrl(profileConfig.publicUrl); return normalizeBaseUrl(interInstanceConfig.profile?.publicUrl);
} }
function ownInstanceId() { function ownInstanceId() {
@@ -79,6 +79,7 @@ function buildPublicUrl(pathname) {
function publicProfile() { function publicProfile() {
const publicUrl = ownPublicUrl(); const publicUrl = ownPublicUrl();
const profileConfig = interInstanceConfig.profile || {};
return { return {
id: ownInstanceId(), id: ownInstanceId(),
name: asTrimmedString(profileConfig.name) || publicUrl || 'Rover server', name: asTrimmedString(profileConfig.name) || publicUrl || 'Rover server',
@@ -429,25 +430,40 @@ async function pollRemoteInstance(entry) {
} }
} }
async function pollNow() { async function pollNow(expectedGeneration = pollGeneration) {
if (!isEnabled() || polling) return; if (!isEnabled() || expectedGeneration !== pollGeneration || pollingGeneration === expectedGeneration) return;
polling = true; pollingGeneration = expectedGeneration;
try { try {
const entries = await fetchDirectoryEntries(); const entries = await fetchDirectoryEntries();
const nextEntries = await Promise.all(entries.map((entry) => pollRemoteInstance(entry))); const nextEntries = await Promise.all(entries.map((entry) => pollRemoteInstance(entry)));
// Ignore responses from the previous directory/profile after a live edit;
// otherwise a slow retired request could repopulate peers after disable or
// overwrite results produced by the newly configured directory.
if (!isEnabled() || expectedGeneration !== pollGeneration) return;
replaceRemoteInstances(nextEntries); replaceRemoteInstances(nextEntries);
interInstanceEvents.emit('change'); interInstanceEvents.emit('change');
} catch (err) { } catch (err) {
logger.warn('Inter-instance poll failed', { error: err.message }); logger.warn('Inter-instance poll failed', { error: err.message });
} finally { } finally {
polling = false; if (pollingGeneration === expectedGeneration) pollingGeneration = null;
} }
} }
function startPolling() { function startPolling() {
if (!isEnabled()) return; pollGeneration += 1;
pollNow(); const expectedGeneration = pollGeneration;
setInterval(pollNow, pollIntervalMs()); if (pollTimer) {
clearInterval(pollTimer);
pollTimer = null;
}
if (!isEnabled()) {
remoteInstances.clear();
interInstanceEvents.emit('change');
return;
}
pollNow(expectedGeneration);
pollTimer = setInterval(() => pollNow(expectedGeneration), pollIntervalMs());
pollTimer.unref?.();
} }
function getState() { function getState() {
@@ -462,6 +478,14 @@ function getState() {
startPolling(); startPolling();
registerConfigurationHandler('interInstance', (nextConfig = {}) => {
// Replacing this single reference updates request timeouts, identity fields,
// directory URLs, and peer lists together. Rebuilding the interval applies
// the new cadence immediately and clears stale peers when disabled.
interInstanceConfig = nextConfig;
startPolling();
});
module.exports = { module.exports = {
getState, getState,
interInstanceEvents, interInstanceEvents,
@@ -8,7 +8,7 @@ module.exports = {
feature: true, feature: true,
defaultValue: { enabled: false, captureCooldownMs: 10000 }, defaultValue: { enabled: false, captureCooldownMs: 10000 },
schema: strictObject({ schema: strictObject({
enabled: boolean({ description: 'Starts the Kinect worker and exposes authorized frame capture after restart.' }), enabled: boolean({ description: 'Immediately starts the Kinect worker and exposes authorized frame capture.' }),
captureCooldownMs: integer({ description: 'Minimum milliseconds between accepted Kinect frame-capture requests across all clients.', minimum: 0, maximum: 3600000 }), captureCooldownMs: integer({ description: 'Minimum milliseconds between accepted Kinect frame-capture requests across all clients.', minimum: 0, maximum: 3600000 }),
}, { }, {
title: 'Kinect', title: 'Kinect',
+5 -1
View File
@@ -1,7 +1,7 @@
// Kinect Service // Kinect Service
// Purpose: Composes Kinect hardware capture and browser socket delivery. // Purpose: Composes Kinect hardware capture and browser socket delivery.
// Scope: Exposes session-readable state while keeping startup side effects in this service folder. // Scope: Exposes session-readable state while keeping startup side effects in this service folder.
const { loadConfig } = require('../../configuration'); const { loadConfig, registerConfigurationHandler } = require('../../configuration');
const hardware = require('./hardware'); const hardware = require('./hardware');
const { registerKinectSocketGateway, kinectEvents } = require('./socketGateway'); const { registerKinectSocketGateway, kinectEvents } = require('./socketGateway');
@@ -11,6 +11,10 @@ const gateway = registerKinectSocketGateway({
hardware, hardware,
}); });
registerConfigurationHandler('kinect', (kinectConfig) => {
gateway.reconfigure({ kinect: kinectConfig || {} });
});
module.exports = { module.exports = {
getState: gateway.getState, getState: gateway.getState,
kinectEvents, kinectEvents,
@@ -33,7 +33,7 @@ function normalizeKinectConfig(config = {}) {
} }
function registerKinectSocketGateway({ config, hardware }) { function registerKinectSocketGateway({ config, hardware }) {
const settings = normalizeKinectConfig(config); let settings = normalizeKinectConfig(config);
let captureCooldownUntil = 0; let captureCooldownUntil = 0;
let busy = false; let busy = false;
let lastAction = null; let lastAction = null;
@@ -206,8 +206,31 @@ function registerKinectSocketGateway({ config, hardware }) {
} }
} }
function reconfigure(nextConfig) {
const previousEnabled = settings.enabled;
settings = normalizeKinectConfig(nextConfig);
lastError = null;
// The native worker is the Kinect service's complete hardware runtime.
// Restarting only when the enabled state changes avoids interrupting an
// unrelated cooldown edit while still making enable/disable immediate.
if (previousEnabled && !settings.enabled) {
hardware.stopWorker();
busy = false;
} else if (!previousEnabled && settings.enabled) {
try {
hardware.startWorker();
} catch (err) {
lastError = err.message || 'kinect worker failed to start';
logger.warn('Kinect worker startup failed after configuration change', { err: lastError });
}
}
emitStatusChange();
}
return { return {
getState: buildStatus, getState: buildStatus,
reconfigure,
}; };
} }
@@ -16,7 +16,7 @@ module.exports = {
commandCooldownMs: 3000, commandCooldownMs: 3000,
}, },
schema: strictObject({ schema: strictObject({
enabled: boolean({ description: 'Enables lift status and commands through the two configured Home Assistant switches after restart.' }), enabled: boolean({ description: 'Immediately enables lift status and commands through the two configured Home Assistant switches.' }),
upSwitch: string({ description: 'Home Assistant switch entity that powers upward lift movement.', examples: ['switch.lift_up'], maxLength: 255 }), upSwitch: string({ description: 'Home Assistant switch entity that powers upward lift movement.', examples: ['switch.lift_up'], maxLength: 255 }),
downSwitch: string({ description: 'Home Assistant switch entity that powers downward lift movement.', examples: ['switch.lift_down'], maxLength: 255 }), downSwitch: string({ description: 'Home Assistant switch entity that powers downward lift movement.', examples: ['switch.lift_down'], maxLength: 255 }),
interlockMs: integer({ description: 'Milliseconds to wait after turning off the opposing direction before energizing the requested direction. Runtime always enforces at least 250 ms.', minimum: 0, maximum: 600000 }), interlockMs: integer({ description: 'Milliseconds to wait after turning off the opposing direction before energizing the requested direction. Runtime always enforces at least 250 ms.', minimum: 0, maximum: 600000 }),
+33 -30
View File
@@ -4,27 +4,28 @@
const EventEmitter = require('events'); const EventEmitter = require('events');
const io = require('../../globals/io'); const io = require('../../globals/io');
const logger = require('../../globals/logger').child('liftService'); const logger = require('../../globals/logger').child('liftService');
const { loadConfig } = require('../../configuration'); const { loadConfig, registerConfigurationHandler } = require('../../configuration');
const { getMode, MODES } = require('../modeManager'); const { getMode, MODES } = require('../modeManager');
const { isAdmin, isLockdownAdmin } = require('../roleService'); const { isAdmin, isLockdownAdmin } = require('../roleService');
const { const homeAssistantService = require('../homeAssistantService');
homeAssistantEvents, const { homeAssistantEvents, getRawEntitySnapshot, callHomeAssistantService } = homeAssistantService;
getRawEntitySnapshot,
callHomeAssistantService,
isConnected: isHomeAssistantConnected,
enabled: homeAssistantEnabled,
} = require('../homeAssistantService');
const events = new EventEmitter(); const events = new EventEmitter();
const config = loadConfig(); let featureEnabled;
const haConfig = config.homeAssistant || {}; let upSwitchId;
const liftConfig = haConfig.lift || {}; let downSwitchId;
const featureEnabled = Boolean(liftConfig.enabled); let interlockMs;
let commandCooldownMs;
const upSwitchId = String(liftConfig.upSwitch || '').trim(); function applyLiftConfig(liftConfig = {}) {
const downSwitchId = String(liftConfig.downSwitch || '').trim(); featureEnabled = Boolean(liftConfig.enabled);
const interlockMs = Math.max(250, Number(liftConfig.interlockMs) || 9000); upSwitchId = String(liftConfig.upSwitch || '').trim();
const commandCooldownMs = Math.max(interlockMs, Number(liftConfig.commandCooldownMs) || 25000); downSwitchId = String(liftConfig.downSwitch || '').trim();
interlockMs = Math.max(250, Number(liftConfig.interlockMs) || 9000);
commandCooldownMs = Math.max(interlockMs, Number(liftConfig.commandCooldownMs) || 25000);
}
applyLiftConfig(loadConfig().homeAssistant?.lift || {});
const state = { const state = {
busy: false, busy: false,
@@ -70,7 +71,7 @@ function isConfigured() {
function getState() { function getState() {
const configured = isConfigured(); const configured = isConfigured();
const connected = isHomeAssistantConnected(); const connected = homeAssistantService.isConnected();
return { return {
enabled: featureEnabled, enabled: featureEnabled,
configured, configured,
@@ -105,8 +106,8 @@ function emitUpdate() {
function assertReady() { function assertReady() {
if (!featureEnabled) throw new Error('Lift is disabled'); if (!featureEnabled) throw new Error('Lift is disabled');
if (!isConfigured()) throw new Error('Lift not configured'); if (!isConfigured()) throw new Error('Lift not configured');
if (!homeAssistantEnabled) throw new Error('Home Assistant not configured'); if (!homeAssistantService.enabled) throw new Error('Home Assistant not configured');
if (!isHomeAssistantConnected()) throw new Error('Home Assistant not connected'); if (!homeAssistantService.isConnected()) throw new Error('Home Assistant not connected');
} }
async function applyPosition(target) { async function applyPosition(target) {
@@ -175,16 +176,10 @@ async function moveDown(actor = 'unknown') {
return requestPosition('down', actor); return requestPosition('down', actor);
} }
if (featureEnabled) { homeAssistantEvents.on('snapshot', emitUpdate);
/* homeAssistantEvents.on('status', emitUpdate);
Lift state depends on Home Assistant switch snapshots. Subscribe only when
the lift exists so disabled installs do not maintain hardware-specific UI
sync paths.
*/
homeAssistantEvents.on('snapshot', emitUpdate);
homeAssistantEvents.on('status', emitUpdate);
io.on('connection', (socket) => { io.on('connection', (socket) => {
function assertFeatureAccess() { function assertFeatureAccess() {
const mode = getMode(); const mode = getMode();
// Lift is a public activity feature in open and turns modes. Restricted // Lift is a public activity feature in open and turns modes. Restricted
@@ -215,11 +210,19 @@ if (featureEnabled) {
cb({ error: err.message }); cb({ error: err.message });
} }
}); });
}); });
} else {
if (!featureEnabled) {
logger.info('Lift disabled by config'); logger.info('Lift disabled by config');
} }
registerConfigurationHandler('homeAssistant', (haConfig = {}) => {
// Lift is nested under the Home Assistant section, so it participates in the
// same section reload and immediately sees the replacement HA transport.
applyLiftConfig(haConfig.lift || {});
emitUpdate();
});
emitUpdate(); emitUpdate();
module.exports = { module.exports = {
@@ -5,7 +5,7 @@ const fsp = require('fs/promises');
const { Ollama } = require('ollama'); const { Ollama } = require('ollama');
const io = require('../../globals/io'); const io = require('../../globals/io');
const logger = require('../../globals/logger').child('llmCommentary'); const logger = require('../../globals/logger').child('llmCommentary');
const { loadConfig } = require('../../configuration'); const { loadConfig, registerConfigurationHandler } = require('../../configuration');
const { getRole, roleEvents } = require('../roleService'); const { getRole, roleEvents } = require('../roleService');
const { getMode, MODES, modeEvents } = require('../modeManager'); const { getMode, MODES, modeEvents } = require('../modeManager');
const roverManager = require('../roverManager'); const roverManager = require('../roverManager');
@@ -34,13 +34,12 @@ const { createSnapshotEngine } = require('./snapshotEngine');
const { registerHooks } = require('./hooks'); const { registerHooks } = require('./hooks');
const { createRunner } = require('./runner'); const { createRunner } = require('./runner');
const config = loadConfig(); let enabled;
const commentaryConfig = config.llmCommentary || {}; let ollamaUrl;
const enabled = Boolean(commentaryConfig.enabled); let model;
const ollamaUrl = String(commentaryConfig.ollamaServer || '').trim(); let ollamaClient;
const model = String(commentaryConfig.model || '').trim(); let frequencyMs;
const ollamaClient = ollamaUrl ? new Ollama({ host: ollamaUrl }) : null; let runner;
const frequencyMs = normalizeFrequencyMs(Number(commentaryConfig.frequency));
const runtime = { const runtime = {
timer: null, timer: null,
@@ -234,73 +233,67 @@ const snapshotEngine = createSnapshotEngine({
getSkipStreak: () => runtime.skipStreak, getSkipStreak: () => runtime.skipStreak,
}); });
const runner = createRunner({ function applyCommentaryConfig(commentaryConfig = {}) {
logger, runner?.stop('configuration changed');
enabled, enabled = Boolean(commentaryConfig.enabled);
model, ollamaUrl = String(commentaryConfig.ollamaServer || '').trim();
ollamaUrl, model = String(commentaryConfig.model || '').trim();
frequencyMs, ollamaClient = ollamaUrl ? new Ollama({ host: ollamaUrl }) : null;
jitterMs: JITTER_MS, frequencyMs = normalizeFrequencyMs(Number(commentaryConfig.frequency));
postCooldownMs: POST_COOLDOWN_MS, status = { ...status, enabled, model, ollamaUrl, frequencyMs };
maxBotMessages: MAX_BOT_MESSAGES, runner = createRunner({
runtime, logger,
snapshotEngine, enabled,
readSystemPrompt, model,
buildModelMessages, ollamaUrl,
generateCommentary, frequencyMs,
normalizeDuplicateKey, jitterMs: JITTER_MS,
getRecentMessages, postCooldownMs: POST_COOLDOWN_MS,
sendSystemMessage, maxBotMessages: MAX_BOT_MESSAGES,
buildFailureInfo, runtime,
updatePhase, snapshotEngine,
startRunRecord, readSystemPrompt,
patchCurrentRun, buildModelMessages,
finalizeRunRecord, generateCommentary,
updateStatus, normalizeDuplicateKey,
}); getRecentMessages,
sendSystemMessage,
const canRunFromConfig = enabled && model && ollamaUrl; buildFailureInfo,
updatePhase,
if (canRunFromConfig) { startRunRecord,
registerHooks({ patchCurrentRun,
io, finalizeRunRecord,
roleEvents, updateStatus,
roverManager,
emitStatusToSocket,
isAdminSocket,
clearRuntimeHistory: runner.clearRuntimeHistory,
getAdminState: () => buildAdminState(status, runtime.runHistory),
onDriverActivity: runner.wakeForDriverActivity,
onSensorEvent: snapshotEngine.onSensorEvent,
onRoverRemoved: snapshotEngine.removeRover,
}); });
if (getMode() === MODES.LOCKDOWN) {
const mode = getMode();
if (mode === MODES.LOCKDOWN) {
runner.stop('paused during lockdown'); runner.stop('paused during lockdown');
logger.info('LLM commentary paused due to lockdown mode');
} else { } else {
runner.start(); runner.start();
} }
modeEvents.on('change', (nextMode) => {
if (nextMode === MODES.LOCKDOWN) {
runner.stop('paused during lockdown');
logger.info('LLM commentary paused due to lockdown mode');
return;
}
runner.start();
});
} else {
const disabledReason = !enabled
? 'llmCommentary.enabled is false'
: 'model or ollama server missing';
updatePhase('disabled', {
running: false,
inFlight: false,
currentRunId: null,
lastOutcome: 'disabled',
lastReason: disabledReason,
});
logger.info('LLM commentary service not started', { reason: disabledReason });
} }
applyCommentaryConfig(loadConfig().llmCommentary || {});
// Runtime hooks stay attached once and route actions through the newest runner.
registerHooks({
io,
roleEvents,
roverManager,
emitStatusToSocket,
isAdminSocket,
clearRuntimeHistory: (...args) => runner.clearRuntimeHistory(...args),
getAdminState: () => buildAdminState(status, runtime.runHistory),
onDriverActivity: (...args) => runner.wakeForDriverActivity(...args),
onSensorEvent: snapshotEngine.onSensorEvent,
onRoverRemoved: snapshotEngine.removeRover,
});
modeEvents.on('change', (nextMode) => {
if (nextMode === MODES.LOCKDOWN) {
runner.stop('paused during lockdown');
return;
}
runner.start();
});
registerConfigurationHandler('llmCommentary', applyCommentaryConfig);
@@ -26,12 +26,14 @@ function createRunner(deps) {
finalizeRunRecord, finalizeRunRecord,
updateStatus, updateStatus,
} = deps; } = deps;
let active = false;
function defaultTickDelayMs() { function defaultTickDelayMs() {
return frequencyMs + Math.floor(Math.random() * (jitterMs + 1)); return frequencyMs + Math.floor(Math.random() * (jitterMs + 1));
} }
function scheduleNextTick(runTick, delayMs = defaultTickDelayMs()) { function scheduleNextTick(runTick, delayMs = defaultTickDelayMs()) {
if (!active) return;
const safeDelay = Math.max(0, Number.isFinite(delayMs) ? Math.floor(delayMs) : defaultTickDelayMs()); const safeDelay = Math.max(0, Number.isFinite(delayMs) ? Math.floor(delayMs) : defaultTickDelayMs());
const nextRunAt = Date.now() + safeDelay; const nextRunAt = Date.now() + safeDelay;
updateStatus({ nextRunAt }); updateStatus({ nextRunAt });
@@ -39,6 +41,7 @@ function createRunner(deps) {
} }
function wakeForDriverActivity(runTick) { function wakeForDriverActivity(runTick) {
if (!active) return;
if (runtime.inFlight) return; if (runtime.inFlight) return;
if (runtime.timer) { if (runtime.timer) {
clearTimeout(runtime.timer); clearTimeout(runtime.timer);
@@ -48,6 +51,7 @@ function createRunner(deps) {
} }
function stop(reason = 'stopped') { function stop(reason = 'stopped') {
active = false;
if (runtime.timer) { if (runtime.timer) {
clearTimeout(runtime.timer); clearTimeout(runtime.timer);
runtime.timer = null; runtime.timer = null;
@@ -335,6 +339,8 @@ function createRunner(deps) {
}); });
return; return;
} }
if (active) return;
active = true;
logger.info('LLM commentary enabled', { model, ollamaUrl, frequencyMs }); logger.info('LLM commentary enabled', { model, ollamaUrl, frequencyMs });
updatePhase('idle', { updatePhase('idle', {
running: true, running: true,
+25 -6
View File
@@ -1,21 +1,40 @@
// MediaMTX Service // MediaMTX Service
// Purpose: Composes server configuration, runtime paths, and child-process supervision. // Purpose: Composes server configuration, runtime paths, and child-process supervision.
// Scope: Starts MediaMTX only after the HTTP auth endpoint is listening and stops it with the server. // Scope: Starts MediaMTX only after the HTTP auth endpoint is listening and stops it with the server.
const { loadConfig } = require('../../configuration'); const { loadConfig, registerConfigurationHandler } = require('../../configuration');
const globalConfig = require('../../globals/config'); const globalConfig = require('../../globals/config');
const logger = require('../../globals/logger').child('mediamtx'); const logger = require('../../globals/logger').child('mediamtx');
const { createMediaMtxSupervisor } = require('./supervisor'); const { createMediaMtxSupervisor } = require('./supervisor');
const supervisor = createMediaMtxSupervisor({ let supervisor = createSupervisor();
config: loadConfig(), let started = false;
serverPort: globalConfig.port,
logger, function createSupervisor() {
}); return createMediaMtxSupervisor({
config: loadConfig(),
serverPort: globalConfig.port,
logger,
});
}
function startMediaMtx() { function startMediaMtx() {
started = true;
return supervisor.start(); return supervisor.start();
} }
function stopSupervisor() {
return new Promise((resolve) => supervisor.stop(resolve));
}
registerConfigurationHandler('media', async () => {
// MediaMTX consumes a generated document rather than the Node configuration
// object directly. Replace its child process so every media setting is
// regenerated and applied as one coherent revision.
await stopSupervisor();
supervisor = createSupervisor();
if (started) supervisor.start();
});
/* /*
Other services already use process signal hooks for their own workers. This hook performs Other services already use process signal hooks for their own workers. This hook performs
only synchronous signal delivery; systemd's default control-group cleanup remains the final only synchronous signal delivery; systemd's default control-group cleanup remains the final
@@ -39,6 +39,9 @@ function createMediaMtxSupervisor(deps) {
function start() { function start() {
if (child) return child; if (child) return child;
// `stop()` marks the old lifecycle as intentional. Reset that marker when
// the same supervisor is started again so later crashes remain fatal.
stopping = false;
const generatedConfig = buildMediaMtxConfig({ config, serverPort, snapshotWriterPath }); const generatedConfig = buildMediaMtxConfig({ config, serverPort, snapshotWriterPath });
/* /*
@@ -10,7 +10,7 @@ module.exports = {
// ESPHome naming shape while `enabled: false` prevents accidental control. // ESPHome naming shape while `enabled: false` prevents accidental control.
defaultValue: { enabled: false, device: 'neato_vacuum' }, defaultValue: { enabled: false, device: 'neato_vacuum' },
schema: strictObject({ schema: strictObject({
enabled: boolean({ description: 'Exposes Neato status and commands through the configured Home Assistant ESPHome device after restart.' }), enabled: boolean({ description: 'Immediately exposes Neato status and commands through the configured Home Assistant ESPHome device.' }),
device: string({ description: 'ESPHome device name used to derive the Neato entity IDs in Home Assistant; punctuation is normalized to underscores.', examples: ['neato_vacuum'], maxLength: 255 }), device: string({ description: 'ESPHome device name used to derive the Neato entity IDs in Home Assistant; punctuation is normalized to underscores.', examples: ['neato_vacuum'], maxLength: 255 }),
}, { }, {
title: 'Neato', title: 'Neato',
+46 -41
View File
@@ -4,24 +4,16 @@
const EventEmitter = require('events'); const EventEmitter = require('events');
const io = require('../../globals/io'); const io = require('../../globals/io');
const logger = require('../../globals/logger').child('neatoService'); const logger = require('../../globals/logger').child('neatoService');
const { loadConfig } = require('../../configuration'); const { loadConfig, registerConfigurationHandler } = require('../../configuration');
const { isVerified } = require('../verificationService'); const { isVerified } = require('../verificationService');
const { getMode, MODES } = require('../modeManager'); const { getMode, MODES } = require('../modeManager');
const { isAdmin, isLockdownAdmin } = require('../roleService'); const { isAdmin, isLockdownAdmin } = require('../roleService');
const { sendAlert } = require('../alertService'); const { sendAlert } = require('../alertService');
const { const homeAssistantService = require('../homeAssistantService');
homeAssistantEvents, const { homeAssistantEvents, getRawEntitySnapshot, callHomeAssistantService } = homeAssistantService;
getRawEntitySnapshot,
callHomeAssistantService,
isConnected: isHomeAssistantConnected,
enabled: homeAssistantEnabled,
} = require('../homeAssistantService');
const events = new EventEmitter(); const events = new EventEmitter();
const config = loadConfig(); let featureEnabled;
const haConfig = config.homeAssistant || {};
const neatoConfig = haConfig.neato || {};
const featureEnabled = Boolean(neatoConfig.enabled);
function normalizeDeviceName(value) { function normalizeDeviceName(value) {
const raw = String(value || '').trim().toLowerCase(); const raw = String(value || '').trim().toLowerCase();
@@ -29,7 +21,7 @@ function normalizeDeviceName(value) {
return raw.replace(/[^a-z0-9_]+/g, '_').replace(/^_+|_+$/g, ''); return raw.replace(/[^a-z0-9_]+/g, '_').replace(/^_+|_+$/g, '');
} }
const device = normalizeDeviceName(neatoConfig.device); let device;
const RESUME_DELAY_MS = 3000; const RESUME_DELAY_MS = 3000;
const ALERT_COLOR = '#a855f7'; const ALERT_COLOR = '#a855f7';
// BrainSlug exposes these exact select values for Gen 3 robots. Keeping the // BrainSlug exposes these exact select values for Gen 3 robots. Keeping the
@@ -42,7 +34,11 @@ function entityId(domain, suffix) {
return `${domain}.${device}_${suffix}`; return `${domain}.${device}_${suffix}`;
} }
const ENTITY_IDS = { let ENTITY_IDS;
let ALERT_ENTITIES;
function buildEntityIds() {
return {
buttons: { buttons: {
start: entityId('button', 'house_clean'), start: entityId('button', 'house_clean'),
resume: entityId('button', 'resume_cleaning'), resume: entityId('button', 'resume_cleaning'),
@@ -69,18 +65,26 @@ const ENTITY_IDS = {
selects: { selects: {
navigationMode: entityId('select', 'navigation_mode'), navigationMode: entityId('select', 'navigation_mode'),
}, },
}; };
}
// Alert Feed coverage is intentionally limited to the raw robot lifecycle and // Alert Feed coverage is intentionally limited to the raw robot lifecycle and
// issue fields requested for Neato. Battery and charger telemetry poll often and // issue fields requested for Neato. Battery and charger telemetry poll often and
// would create noise without representing a useful robot status transition. // would create noise without representing a useful robot status transition.
const ALERT_ENTITIES = Object.freeze([ function applyNeatoConfig(neatoConfig = {}) {
{ title: 'Neato UI state', entityId: ENTITY_IDS.textSensors.uiState }, featureEnabled = Boolean(neatoConfig.enabled);
{ title: 'Neato robot state', entityId: ENTITY_IDS.textSensors.robotState }, device = normalizeDeviceName(neatoConfig.device);
{ title: 'Neato robot alert', entityId: ENTITY_IDS.textSensors.robotAlert }, ENTITY_IDS = buildEntityIds();
{ title: 'Neato robot error', entityId: ENTITY_IDS.textSensors.robotError }, ALERT_ENTITIES = [
{ title: 'Neato external power', entityId: ENTITY_IDS.binarySensors.extPowerPresent }, { title: 'Neato UI state', entityId: ENTITY_IDS.textSensors.uiState },
]); { title: 'Neato robot state', entityId: ENTITY_IDS.textSensors.robotState },
{ title: 'Neato robot alert', entityId: ENTITY_IDS.textSensors.robotAlert },
{ title: 'Neato robot error', entityId: ENTITY_IDS.textSensors.robotError },
{ title: 'Neato external power', entityId: ENTITY_IDS.binarySensors.extPowerPresent },
];
}
applyNeatoConfig(loadConfig().homeAssistant?.neato || {});
// Each entity establishes its own baseline because ESPHome entities can become // Each entity establishes its own baseline because ESPHome entities can become
// available on different snapshots. A Map also distinguishes "not observed yet" // available on different snapshots. A Map also distinguishes "not observed yet"
@@ -165,7 +169,9 @@ function requiredEntityIds() {
function buildState() { function buildState() {
const configured = Boolean(device); const configured = Boolean(device);
const haConnected = isHomeAssistantConnected(); // Home Assistant may have replaced its transport since this service module
// loaded, so readiness must be resolved from the live service object.
const haConnected = homeAssistantService.isConnected();
const requiredIds = requiredEntityIds(); const requiredIds = requiredEntityIds();
const entitiesAvailable = requiredIds.length > 0 && requiredIds.every((id) => isEntityAvailable(id)); const entitiesAvailable = requiredIds.length > 0 && requiredIds.every((id) => isEntityAvailable(id));
const connected = Boolean(haConnected && entitiesAvailable); const connected = Boolean(haConnected && entitiesAvailable);
@@ -249,21 +255,14 @@ function emitUpdate() {
} }
} }
if (featureEnabled) { homeAssistantEvents.on('snapshot', () => {
/* if (featureEnabled) {
Neato telemetry is derived from Home Assistant entities. Disabled installs
should keep the exported API inert instead of tracking HA snapshots for a
robot vacuum feature that does not exist on that server.
*/
homeAssistantEvents.on('snapshot', () => {
emitUpdate(); emitUpdate();
emitRawStateAlerts(); emitRawStateAlerts();
}); }
});
homeAssistantEvents.on('status', () => { homeAssistantEvents.on('status', emitUpdate);
emitUpdate();
});
}
function assertConfiguredAndConnected() { function assertConfiguredAndConnected() {
if (!featureEnabled) { if (!featureEnabled) {
@@ -272,10 +271,10 @@ function assertConfiguredAndConnected() {
if (!device) { if (!device) {
throw new Error('Neato not configured'); throw new Error('Neato not configured');
} }
if (!homeAssistantEnabled) { if (!homeAssistantService.enabled) {
throw new Error('Home Assistant not configured'); throw new Error('Home Assistant not configured');
} }
if (!isHomeAssistantConnected()) { if (!homeAssistantService.isConnected()) {
throw new Error('Home Assistant not connected'); throw new Error('Home Assistant not connected');
} }
} }
@@ -349,8 +348,7 @@ function hasVerifiedSockets() {
return false; return false;
} }
if (featureEnabled) { io.on('connection', (socket) => {
io.on('connection', (socket) => {
function assertFeatureAccess() { function assertFeatureAccess() {
const mode = getMode(); const mode = getMode();
// Neato shares the same public-activity policy as lift: everyone may use // Neato shares the same public-activity policy as lift: everyone may use
@@ -420,11 +418,18 @@ if (featureEnabled) {
cb({ error: err.message }); cb({ error: err.message });
} }
}); });
}); });
} else {
if (!featureEnabled) {
logger.info('Neato disabled by config'); logger.info('Neato disabled by config');
} }
registerConfigurationHandler('homeAssistant', (haConfig = {}) => {
applyNeatoConfig(haConfig.neato || {});
alertBaselines.clear();
emitUpdate();
});
emitUpdate(); emitUpdate();
module.exports = { module.exports = {
@@ -2,7 +2,7 @@ const fsp = require('fs/promises');
const { Ollama } = require('ollama'); const { Ollama } = require('ollama');
const io = require('../../globals/io'); const io = require('../../globals/io');
const logger = require('../../globals/logger').child('overseerControl'); const logger = require('../../globals/logger').child('overseerControl');
const { loadConfig } = require('../../configuration'); const { loadConfig, registerConfigurationHandler } = require('../../configuration');
const { getRole, roleEvents } = require('../roleService'); const { getRole, roleEvents } = require('../roleService');
const { getMode, MODES, modeEvents } = require('../modeManager'); const { getMode, MODES, modeEvents } = require('../modeManager');
const { verificationEvents } = require('../verificationService'); const { verificationEvents } = require('../verificationService');
@@ -31,26 +31,24 @@ const { toStateUpdate, buildToolState, buildConversation, buildModelMessages } =
const { buildOllamaTools, executeToolAction } = require('./tools'); const { buildOllamaTools, executeToolAction } = require('./tools');
const { loadMemory, saveMemory, createDefaultMemory, summarizeMemory } = require('./memoryStore'); const { loadMemory, saveMemory, createDefaultMemory, summarizeMemory } = require('./memoryStore');
const config = loadConfig();
const overseerConfig = config.overseerControl || {};
const RUN_MODE_AUTONOMOUS = 'autonomous'; const RUN_MODE_AUTONOMOUS = 'autonomous';
const RUN_MODE_DIRECT_ADDRESS = 'directAddress'; const RUN_MODE_DIRECT_ADDRESS = 'directAddress';
const RUN_MODES = new Set([RUN_MODE_AUTONOMOUS, RUN_MODE_DIRECT_ADDRESS]); const RUN_MODES = new Set([RUN_MODE_AUTONOMOUS, RUN_MODE_DIRECT_ADDRESS]);
const enabled = Boolean(overseerConfig.enabled); let enabled;
const observeOnly = overseerConfig.observeOnly !== false; let observeOnly;
const name = String(overseerConfig.name || DEFAULT_NAME).trim() || DEFAULT_NAME; let name;
const configuredRunMode = String(overseerConfig.mode || RUN_MODE_AUTONOMOUS).trim(); let runMode;
const runMode = RUN_MODES.has(configuredRunMode) ? configuredRunMode : RUN_MODE_AUTONOMOUS; let autonomousMode;
const autonomousMode = runMode === RUN_MODE_AUTONOMOUS; let directAddressMode;
const directAddressMode = runMode === RUN_MODE_DIRECT_ADDRESS; let model;
const model = String(overseerConfig.model || '').trim(); let ollamaUrl;
const ollamaUrl = String(overseerConfig.ollamaServer || '').trim(); let gateIntervalMs;
const gateIntervalMs = normalizeMs(Number(overseerConfig.gateIntervalMs), DEFAULT_GATE_INTERVAL_MS); let postToolsOnlyMessages;
const postToolsOnlyMessages = Boolean(overseerConfig.postToolsOnlyMessages); let tiebreakerEnable;
const tiebreakerEnable = Boolean(overseerConfig.tiebreakerEnable); let runWhileNoPeopleOnline;
const runWhileNoPeopleOnline = Boolean(overseerConfig.runWhileNoPeopleOnline); let profileImageUrl;
const profileImageUrl = String(overseerConfig.profileImageUrl || '').trim() || null; let ollamaClient;
const ollamaClient = ollamaUrl ? new Ollama({ host: ollamaUrl }) : null; let normalizedConfiguredName;
function normalizeNameMentionText(value) { function normalizeNameMentionText(value) {
return String(value || '') return String(value || '')
@@ -63,7 +61,26 @@ function normalizeNameMentionText(value) {
.replace(/\s+/g, ' '); .replace(/\s+/g, ' ');
} }
const normalizedConfiguredName = normalizeNameMentionText(name); function applyOverseerConfig(overseerConfig = {}) {
enabled = Boolean(overseerConfig.enabled);
observeOnly = overseerConfig.observeOnly !== false;
name = String(overseerConfig.name || DEFAULT_NAME).trim() || DEFAULT_NAME;
const configuredRunMode = String(overseerConfig.mode || RUN_MODE_AUTONOMOUS).trim();
runMode = RUN_MODES.has(configuredRunMode) ? configuredRunMode : RUN_MODE_AUTONOMOUS;
autonomousMode = runMode === RUN_MODE_AUTONOMOUS;
directAddressMode = runMode === RUN_MODE_DIRECT_ADDRESS;
model = String(overseerConfig.model || '').trim();
ollamaUrl = String(overseerConfig.ollamaServer || '').trim();
gateIntervalMs = normalizeMs(Number(overseerConfig.gateIntervalMs), DEFAULT_GATE_INTERVAL_MS);
postToolsOnlyMessages = Boolean(overseerConfig.postToolsOnlyMessages);
tiebreakerEnable = Boolean(overseerConfig.tiebreakerEnable);
runWhileNoPeopleOnline = Boolean(overseerConfig.runWhileNoPeopleOnline);
profileImageUrl = String(overseerConfig.profileImageUrl || '').trim() || null;
ollamaClient = ollamaUrl ? new Ollama({ host: ollamaUrl }) : null;
normalizedConfiguredName = normalizeNameMentionText(name);
}
applyOverseerConfig(loadConfig().overseerControl || {});
const runtime = { const runtime = {
timer: null, timer: null,
@@ -797,6 +814,27 @@ modeEvents.on('change', (mode) => {
evaluateSchedulerGate(observeOnly ? 'observe-only mode' : null); evaluateSchedulerGate(observeOnly ? 'observe-only mode' : null);
}); });
registerConfigurationHandler('overseerControl', (overseerConfig = {}) => {
// All scheduler and model parameters are one runtime unit. Cancel the old
// cadence, replace them atomically, and let the normal vote/mode gate decide
// whether the newly configured scheduler should run.
stopScheduler('configuration changed');
applyOverseerConfig(overseerConfig);
updateStatus({
enabled,
runMode,
observeOnly,
name,
model,
ollamaUrl,
gateIntervalMs,
postToolsOnlyMessages,
tiebreakerEnable,
runWhileNoPeopleOnline,
});
evaluateSchedulerGate('configuration changed');
});
if (!enabled) { if (!enabled) {
logger.info('overseerControl disabled'); logger.info('overseerControl disabled');
updateStatus({ running: false, lastReason: 'overseerControl.enabled is false' }); updateStatus({ running: false, lastReason: 'overseerControl.enabled is false' });
@@ -21,7 +21,7 @@ module.exports = {
replayEnabled: false, replayEnabled: false,
}, },
schema: strictObject({ schema: strictObject({
enabled: boolean({ description: 'Connects to the configured ONVIF camera and exposes its controls after restart.' }), enabled: boolean({ description: 'Immediately connects to the configured ONVIF camera and exposes its controls.' }),
name: string({ description: 'Human-readable camera name shown in the control interface.', minLength: 1, maxLength: 120 }), name: string({ description: 'Human-readable camera name shown in the control interface.', minLength: 1, maxLength: 120 }),
color: string({ description: 'Six-digit hexadecimal accent color used to identify this camera in the UI.', pattern: '^#[0-9a-fA-F]{6}$' }), color: string({ description: 'Six-digit hexadecimal accent color used to identify this camera in the UI.', pattern: '^#[0-9a-fA-F]{6}$' }),
host: string({ description: 'Hostname or IP address of the ONVIF camera.', examples: ['192.168.0.8'], maxLength: 255 }), host: string({ description: 'Hostname or IP address of the ONVIF camera.', examples: ['192.168.0.8'], maxLength: 255 }),
+42 -5
View File
@@ -9,7 +9,7 @@ const { Cam } = require('onvif');
const io = require('../../globals/io'); const io = require('../../globals/io');
const logger = require('../../globals/logger').child('ptzCamera'); const logger = require('../../globals/logger').child('ptzCamera');
const { loadConfig } = require('../../configuration'); const { loadConfig, registerConfigurationHandler } = require('../../configuration');
const { resolveRoverSnapshotDir } = require('../../helpers/dataPaths'); const { resolveRoverSnapshotDir } = require('../../helpers/dataPaths');
const { const {
shouldUseSnapshotsForNonTurnVideo, shouldUseSnapshotsForNonTurnVideo,
@@ -51,9 +51,8 @@ const PUBLISHER_STDERR_SYNC_MS = 10000;
const PUBLISHER_RTSP_TIMEOUT_US = 10000000; const PUBLISHER_RTSP_TIMEOUT_US = 10000000;
const events = new EventEmitter(); const events = new EventEmitter();
const config = loadConfig(); let cameraConfig = loadConfig().ptzCamera || {};
const cameraConfig = config.ptzCamera || {}; let enabled = Boolean(cameraConfig.enabled);
const enabled = Boolean(cameraConfig.enabled);
const state = { const state = {
initialized: false, initialized: false,
@@ -114,7 +113,7 @@ let lastSnapshotState = null;
const snapshotSubscribers = new Map(); const snapshotSubscribers = new Map();
const socketSnapshotSubscriptions = new Map(); const socketSnapshotSubscriptions = new Map();
const snapshotLastSentBySocket = new Map(); const snapshotLastSentBySocket = new Map();
const audioPlayback = createPtzAudioPlayback({ let audioPlayback = createPtzAudioPlayback({
logger, logger,
cameraConfig, cameraConfig,
enabled, enabled,
@@ -1831,6 +1830,44 @@ if (enabled) {
initialize(); initialize();
} }
function stopCameraRuntime() {
// Disable restart-producing callbacks before terminating the publisher. The
// old ffmpeg exit event can then observe `enabled === false` and will not
// resurrect a process built from the previous camera configuration.
enabled = false;
revokeOperator('configuration-change');
state.queue = [];
stopPublisher();
audioPlayback.stopActivePlayback('configuration-change');
if (snapshotTimer) {
clearInterval(snapshotTimer);
snapshotTimer = null;
}
if (spotlightVerifyTimer) {
clearTimeout(spotlightVerifyTimer);
spotlightVerifyTimer = null;
}
clearMotionWatchdog();
clearPanTiltRenewal();
clearZoomRepeat();
onvifCam = null;
state.initialized = false;
state.initializing = false;
state.rtspUri = null;
state.profileToken = DEFAULT_PROFILE_TOKEN;
}
registerConfigurationHandler('ptzCamera', (nextCameraConfig = {}) => {
stopCameraRuntime();
cameraConfig = nextCameraConfig;
enabled = Boolean(cameraConfig.enabled);
state.profileToken = String(cameraConfig.profileToken || DEFAULT_PROFILE_TOKEN);
state.error = null;
audioPlayback = createPtzAudioPlayback({ logger, cameraConfig, enabled, getSocketLabel });
emitChange('configuration-change');
if (enabled) initialize();
});
module.exports = { module.exports = {
PTZ_CAMERA_ID, PTZ_CAMERA_ID,
PTZ_STREAM_PATH, PTZ_STREAM_PATH,
@@ -3,10 +3,8 @@
// Scope: Owns camera identity/url normalization and read-only accessors for room camera metadata. // Scope: Owns camera identity/url normalization and read-only accessors for room camera metadata.
const EventEmitter = require('events'); const EventEmitter = require('events');
const logger = require('../../globals/logger').child('roomCameraService'); const logger = require('../../globals/logger').child('roomCameraService');
const { loadConfig } = require('../../configuration');
const events = new EventEmitter(); const events = new EventEmitter();
const config = loadConfig();
const cameraMap = new Map(); const cameraMap = new Map();
function normalizeCamera(camera) { function normalizeCamera(camera) {
@@ -38,11 +36,11 @@ function getRoomCamera(id) {
return cameraMap.get(String(id)) || null; return cameraMap.get(String(id)) || null;
} }
function loadFromConfig() { function loadFromConfig(roomCameraConfig = {}) {
cameraMap.clear(); cameraMap.clear();
// Schema validation guarantees the configured list shape. Keeping its // Schema validation guarantees the configured list shape. Keeping its
// fallback local makes the camera catalog independent of feature projection. // fallback local makes the camera catalog independent of feature projection.
const list = Array.isArray(config.roomCameras?.cameras) ? config.roomCameras.cameras : []; const list = Array.isArray(roomCameraConfig.cameras) ? roomCameraConfig.cameras : [];
list.forEach((camera) => { list.forEach((camera) => {
const normalized = normalizeCamera(camera); const normalized = normalizeCamera(camera);
if (normalized) cameraMap.set(normalized.id, normalized); if (normalized) cameraMap.set(normalized.id, normalized);
@@ -28,7 +28,7 @@ module.exports = {
], ],
}, },
schema: strictObject({ schema: strictObject({
enabled: boolean({ description: 'Publishes the configured room-camera catalog and enables camera snapshots and streams after restart.' }), enabled: boolean({ description: 'Immediately publishes the configured room-camera catalog and enables camera snapshots and streams.' }),
cameras: { cameras: {
type: 'array', type: 'array',
description: 'Room cameras available to the web UI and replay system.', description: 'Room cameras available to the web UI and replay system.',
+17 -23
View File
@@ -5,34 +5,28 @@ const { loadFromConfig, getRoomCameras, getRoomCamera, roomCameraEvents } = requ
const { createSnapshotEngine } = require('./snapshotEngine'); const { createSnapshotEngine } = require('./snapshotEngine');
const { registerRoomCameraSocketGateway } = require('./socketGateway'); const { registerRoomCameraSocketGateway } = require('./socketGateway');
const replay = require('../replayEngineV2/roomCameraReplayBuilder'); const replay = require('../replayEngineV2/roomCameraReplayBuilder');
const { loadConfig } = require('../../configuration'); const { loadConfig, registerConfigurationHandler } = require('../../configuration');
const enabled = Boolean(loadConfig().roomCameras?.enabled); let enabled = false;
const snapshotEngine = createSnapshotEngine({ getRoomCameras, roomCameraEvents }); const snapshotEngine = createSnapshotEngine({ getRoomCameras, roomCameraEvents });
if (enabled) { function applyRoomCameraConfig(roomCameraConfig = {}) {
/* enabled = Boolean(roomCameraConfig.enabled);
Room cameras are optional local hardware/network devices. The service module // Loading an empty catalog on disable causes the snapshot engine's existing
can still be imported by replay, health, and session code, but disabled // update listener to close every stream and timer without unregistering the
installs must not start polling LAN cameras in the background. // stable browser gateway.
*/ loadFromConfig(enabled ? roomCameraConfig : { cameras: [] });
loadFromConfig();
snapshotEngine.startAll();
} }
if (enabled) { registerRoomCameraSocketGateway({
/* getRoomCamera,
Camera frame sockets are part of the room-camera feature surface. Keeping getRoomCameras,
them behind the same gate prevents disabled features from being callable by getRoomCameraState: snapshotEngine.getRoomCameraState,
hand even though server/index.js still imports this module. roomCameraStreamEvents: snapshotEngine.roomCameraStreamEvents,
*/ });
registerRoomCameraSocketGateway({
getRoomCamera, applyRoomCameraConfig(loadConfig().roomCameras || {});
getRoomCameras, registerConfigurationHandler('roomCameras', applyRoomCameraConfig);
getRoomCameraState: snapshotEngine.getRoomCameraState,
roomCameraStreamEvents: snapshotEngine.roomCameraStreamEvents,
});
}
function buildRoomCameraReplayVideo(options = {}) { function buildRoomCameraReplayVideo(options = {}) {
return replay.buildRoomCameraReplayVideo(options, { getRoomCamera, getRoomCameras }); return replay.buildRoomCameraReplayVideo(options, { getRoomCamera, getRoomCameras });
@@ -74,7 +74,17 @@ function handleStreamError(camera, err) {
} }
function createSnapshotEngine({ getRoomCameras, roomCameraEvents }) { function createSnapshotEngine({ getRoomCameras, roomCameraEvents }) {
function isCurrentCamera(camera) {
return getRoomCameras().some((current) => (
current.id === camera.id && current.url === camera.url && current.streamUrl === camera.streamUrl
));
}
function startStream(camera) { function startStream(camera) {
// Stream close/error events can arrive after a configuration reload. Verify
// identity and URL against the current catalog before allowing an old
// reconnect timer to recreate a retired camera connection.
if (!isCurrentCamera(camera)) return;
const streamUrl = getStreamUrl(camera); const streamUrl = getStreamUrl(camera);
if (!streamUrl || streamState.get(camera.id)?.req) return; if (!streamUrl || streamState.get(camera.id)?.req) return;
const url = new URL(streamUrl); const url = new URL(streamUrl);
@@ -7,6 +7,12 @@ const rovers = new Map();
const socketToRovers = new Map(); const socketToRovers = new Map();
const spectatorSockets = new Set(); const spectatorSockets = new Set();
const managerEvents = new EventEmitter(); const managerEvents = new EventEmitter();
/*
Service reload support requires optional consumers such as commentary to keep
one stable rover listener even while disabled. Preserve a finite ceiling so
accidental reload-time duplication still becomes visible.
*/
managerEvents.setMaxListeners(20);
const backoffTimers = new Map(); const backoffTimers = new Map();
const dockGuardStates = new Map(); const dockGuardStates = new Map();
const dockProtectionStrikeStates = new Map(); const dockProtectionStrikeStates = new Map();
+17 -10
View File
@@ -4,9 +4,13 @@
const { loadConfig } = require('../../configuration'); const { loadConfig } = require('../../configuration');
const { getConfiguredSocials } = require('./configuration'); const { getConfiguredSocials } = require('./configuration');
const config = loadConfig(); function getServerTimezone() {
const serverTimezone = config.timezone || null; return loadConfig().timezone || null;
const configuredSocials = getConfiguredSocials(config); }
function getConfiguredSessionSocials() {
return getConfiguredSocials(loadConfig());
}
/* /*
The driver ad is trusted deployment content supplied by the server operator. The driver ad is trusted deployment content supplied by the server operator.
Normalize both values at the server boundary so every browser receives a Normalize both values at the server boundary so every browser receives a
@@ -16,19 +20,22 @@ const configuredSocials = getConfiguredSocials(config);
An empty HTML string disables the card; the title alone must never leave an An empty HTML string disables the card; the title alone must never leave an
empty panel at the bottom of the driver layout. empty panel at the bottom of the driver layout.
*/ */
const driverAd = { function getDriverAd() {
title: typeof config.driverAd?.title === 'string' ? config.driverAd.title.trim() : '', const configured = loadConfig().driverAd;
html: typeof config.driverAd?.html === 'string' ? config.driverAd.html.trim() : '', return {
}; title: typeof configured?.title === 'string' ? configured.title.trim() : '',
html: typeof configured?.html === 'string' ? configured.html.trim() : '',
};
}
const ACTIVITY_SYNC_COOLDOWN_MS = 3000; const ACTIVITY_SYNC_COOLDOWN_MS = 3000;
const GPIO_TOGGLE_SYNC_COOLDOWN_MS = 1000; const GPIO_TOGGLE_SYNC_COOLDOWN_MS = 1000;
const PERIODIC_SYNC_MS = 20000; const PERIODIC_SYNC_MS = 20000;
module.exports = { module.exports = {
serverTimezone, getServerTimezone,
configuredSocials, getConfiguredSessionSocials,
driverAd, getDriverAd,
ACTIVITY_SYNC_COOLDOWN_MS, ACTIVITY_SYNC_COOLDOWN_MS,
GPIO_TOGGLE_SYNC_COOLDOWN_MS, GPIO_TOGGLE_SYNC_COOLDOWN_MS,
PERIODIC_SYNC_MS, PERIODIC_SYNC_MS,
+15 -8
View File
@@ -3,7 +3,7 @@
// Scope: Keeps runtime behavior unchanged while isolating responsibilities into a clear module boundary. // Scope: Keeps runtime behavior unchanged while isolating responsibilities into a clear module boundary.
const io = require('../../globals/io'); const io = require('../../globals/io');
const logger = require('../../globals/logger').child('sessionService'); const logger = require('../../globals/logger').child('sessionService');
const { getFeatureFlags } = require('../../configuration'); const { getFeatureFlags, configurationEvents } = require('../../configuration');
const { getRole, isAdmin, roleEvents } = require('../roleService'); const { getRole, isAdmin, roleEvents } = require('../roleService');
const { getMode, modeEvents } = require('../modeManager'); const { getMode, modeEvents } = require('../modeManager');
const roverManager = require('../roverManager'); const roverManager = require('../roverManager');
@@ -58,9 +58,9 @@ const { getAudioLevels, getAudioAdjustmentStateForSocket, audioLevelsEvents } =
const { getButtonBoxState } = require('../buttonBoxService'); const { getButtonBoxState } = require('../buttonBoxService');
const { getState: getInterInstanceState, interInstanceEvents } = require('../interInstanceService'); const { getState: getInterInstanceState, interInstanceEvents } = require('../interInstanceService');
const { const {
serverTimezone, getServerTimezone,
configuredSocials, getConfiguredSessionSocials,
driverAd, getDriverAd,
ACTIVITY_SYNC_COOLDOWN_MS, ACTIVITY_SYNC_COOLDOWN_MS,
GPIO_TOGGLE_SYNC_COOLDOWN_MS, GPIO_TOGGLE_SYNC_COOLDOWN_MS,
PERIODIC_SYNC_MS, PERIODIC_SYNC_MS,
@@ -71,7 +71,6 @@ const {
filterActiveDriversForSocket, filterActiveDriversForSocket,
filterTurnQueuesForSocket, filterTurnQueuesForSocket,
} = require('./filters'); } = require('./filters');
logger.info('Socials config loaded:', configuredSocials?.length ? `${configuredSocials.length} entries` : 'not configured');
const SPECTATOR_ACCESS_NAMESPACE = 'spectatorAccess'; const SPECTATOR_ACCESS_NAMESPACE = 'spectatorAccess';
@@ -195,7 +194,8 @@ function buildSession(socket) {
const assignmentRoverId = filterVisibleRoverId(socket, verifiedAssignmentRover); const assignmentRoverId = filterVisibleRoverId(socket, verifiedAssignmentRover);
const activeDrivers = filterActiveDriversForSocket(getActiveDrivers(), socket); const activeDrivers = filterActiveDriversForSocket(getActiveDrivers(), socket);
const turnQueues = filterTurnQueuesForSocket(getTurnQueues(), socket); const turnQueues = filterTurnQueuesForSocket(getTurnQueues(), socket);
const socials = features.socials && configuredSocials?.length ? configuredSocials : []; const configuredSocials = getConfiguredSessionSocials();
const socials = features.socials && configuredSocials.length ? configuredSocials : [];
return { return {
socketId: socket?.id || null, socketId: socket?.id || null,
role: getRole(socket), role: getRole(socket),
@@ -240,8 +240,8 @@ function buildSession(socket) {
session payload makes the server configuration the single source of session payload makes the server configuration the single source of
truth and avoids a separate endpoint for one small optional card. truth and avoids a separate endpoint for one small optional card.
*/ */
driverAd, driverAd: getDriverAd(),
timezone: serverTimezone, timezone: getServerTimezone(),
identity: getIdentitySummary(socket), identity: getIdentitySummary(socket),
verification: getVerificationStateForSocket(socket), verification: getVerificationStateForSocket(socket),
moderation: getModerationStateForSocket(socket), moderation: getModerationStateForSocket(socket),
@@ -510,6 +510,13 @@ interInstanceEvents.on('change', () => {
syncAll(); syncAll();
}); });
configurationEvents.on('applied', () => {
// Feature switches and passive presentation values share the session payload.
// Broadcast only after all affected service reloads finish so clients never
// see a new feature map paired with an old service runtime.
syncAll();
});
// sync all sockets 20 seconds // sync all sockets 20 seconds
// setInterval(() => { // setInterval(() => {
// logger.info('Periodic session sync for all clients'); // logger.info('Periodic session sync for all clients');
+7 -3
View File
@@ -5,7 +5,7 @@ const crypto = require('crypto');
const bcrypt = require('bcrypt'); const bcrypt = require('bcrypt');
const io = require('../../globals/io'); const io = require('../../globals/io');
const logger = require('../../globals/logger').child('setupService'); const logger = require('../../globals/logger').child('setupService');
const { getConfigurationDatabase } = require('../../configuration'); const { getConfigurationDatabase, applyCommittedConfiguration } = require('../../configuration');
const { importConfigurationFile } = require('../../configuration/configurationFileImporter'); const { importConfigurationFile } = require('../../configuration/configurationFileImporter');
const { createSetupCodeFile } = require('./setupCodeFile'); const { createSetupCodeFile } = require('./setupCodeFile');
@@ -83,7 +83,7 @@ io.on('connection', (socket) => {
}); });
socket.on('setup:importConfigurationFile', (payload = {}, cb = () => {}) => { socket.on('setup:importConfigurationFile', (payload = {}, cb = () => {}) => {
respond(cb, () => { respond(cb, async () => {
requireOpenSetup(payload.setupCode); requireOpenSetup(payload.setupCode);
const yamlText = String(payload.yaml || ''); const yamlText = String(payload.yaml || '');
if (!yamlText || Buffer.byteLength(yamlText, 'utf8') > MAX_CONFIGURATION_FILE_BYTES) { if (!yamlText || Buffer.byteLength(yamlText, 'utf8') > MAX_CONFIGURATION_FILE_BYTES) {
@@ -95,8 +95,12 @@ io.on('connection', (socket) => {
actor: 'first-run-setup', actor: 'first-run-setup',
source: String(payload.fileName || 'uploaded-config.yaml').slice(0, 255), source: String(payload.fileName || 'uploaded-config.yaml').slice(0, 255),
}); });
// By the time a browser can reach setup, server startup has registered
// every service handler. Apply the imported revision now so first-run
// setup follows the same no-restart contract as later admin edits.
const application = await applyCommittedConfiguration();
setupCodeFile.remove(); setupCodeFile.remove();
return result; return { ...result, application };
}); });
}); });
}); });
@@ -3,12 +3,10 @@
// Scope: Handles WHEP/WHP path-prefix trimming and SRT streamid extraction without performing auth decisions. // Scope: Handles WHEP/WHP path-prefix trimming and SRT streamid extraction without performing auth decisions.
const { loadConfig } = require('../../configuration'); const { loadConfig } = require('../../configuration');
const config = loadConfig();
const mediaConfig = config.media || {};
const PTZ_STREAM_PATH = 'ptz-camera'; const PTZ_STREAM_PATH = 'ptz-camera';
function getPathPrefix() { function getPathPrefix() {
const base = mediaConfig.whepBaseUrl; const base = loadConfig().media?.whepBaseUrl;
if (!base) return ''; if (!base) return '';
try { try {
const parsed = new URL(base); const parsed = new URL(base);
@@ -18,10 +16,11 @@ function getPathPrefix() {
} }
} }
const whepPathPrefix = getPathPrefix().replace(/\/+$/, '').replace(/^\/+/, '');
const whepPrefixSegments = whepPathPrefix ? whepPathPrefix.split('/').filter(Boolean) : [];
function extractStreamInfo(path) { function extractStreamInfo(path) {
// The path prefix is tiny to derive and must follow media changes immediately;
// retaining it at module load would make auth disagree with newly issued URLs.
const whepPathPrefix = getPathPrefix().replace(/\/+$/, '').replace(/^\/+/, '');
const whepPrefixSegments = whepPathPrefix ? whepPathPrefix.split('/').filter(Boolean) : [];
const segments = (path || '').split('/').filter(Boolean); const segments = (path || '').split('/').filter(Boolean);
if (!segments.length) return null; if (!segments.length) return null;
@@ -16,11 +16,8 @@ const {
shouldUseSnapshotsForExternalSpectatorVideo, shouldUseSnapshotsForExternalSpectatorVideo,
} = require('../../helpers/bandwidthSavings'); } = require('../../helpers/bandwidthSavings');
const config = loadConfig();
const mediaConfig = config.media || {};
function getMediaPrefix() { function getMediaPrefix() {
const base = mediaConfig.whepBaseUrl; const base = loadConfig().media?.whepBaseUrl;
if (!base) { if (!base) {
return ''; return '';
} }
+1 -1
View File
@@ -149,7 +149,7 @@ export default function AdminApp() {
<PasswordConfirmationDialog open={confirmationOpen} busy={confirmationBusy} error={confirmationError} onCancel={cancelPasswordConfirmation} onConfirm={submitPasswordConfirmation} /> <PasswordConfirmationDialog open={confirmationOpen} busy={confirmationBusy} error={confirmationError} onCancel={cancelPasswordConfirmation} onConfirm={submitPasswordConfirmation} />
<main className="mx-auto min-h-screen w-full max-w-[100rem] p-1"> <main className="mx-auto min-h-screen w-full max-w-[100rem] p-1">
<CardFrame title="MultiRover administration" meta={connected ? role : 'offline'} bodyClassName="p-0.5 text-xs text-slate-400"> <CardFrame title="MultiRover administration" meta={connected ? role : 'offline'} bodyClassName="p-0.5 text-xs text-slate-400">
<p>{snapshot ? `Active configuration revision ${snapshot.configuration.revision}.${snapshot.restartRequired ? ' An application restart is required to apply saved changes.' : ' The running application has loaded this revision.'}` : 'Central server administration and configuration.'}</p> <p>{snapshot ? `Active configuration revision ${snapshot.configuration.revision}. The running application has applied revision ${snapshot.appliedRevision}.` : 'Central server administration and configuration.'}</p>
</CardFrame> </CardFrame>
{isAdmin ? ( {isAdmin ? (
<Tabs currentTab={activeSection} onTabChange={selectSection}> <Tabs currentTab={activeSection} onTabChange={selectSection}>
+1 -1
View File
@@ -13,7 +13,7 @@ export default function AdminOverview({ snapshot, socket, runSensitive, onSnapsh
const config = snapshot.configuration; const config = snapshot.configuration;
async function restore(revision) { async function restore(revision) {
if (!window.confirm(`Restore configuration revision ${revision}? This creates a new active revision and requires a restart.`)) return; if (!window.confirm(`Restore configuration revision ${revision}? This creates and immediately applies a new active revision.`)) return;
try { try {
const response = await runSensitive(() => restoreConfigurationRevision(socket, { const response = await runSensitive(() => restoreConfigurationRevision(socket, {
revision, revision,
@@ -65,7 +65,7 @@ export default function ConfigurationEditor({ snapshot, socket, runSensitive, on
return ( return (
<CardFrame title="Configuration" meta={`revision ${revision}`} clipOverflow={false} bodyClassName="p-0.5"> <CardFrame title="Configuration" meta={`revision ${revision}`} clipOverflow={false} bodyClassName="p-0.5">
<div className="configuration-toolbar sticky top-0 z-20 mb-0.5 space-y-0.5 border border-neutral-500/60 bg-neutral-900/95 p-0.5 backdrop-blur"> <div className="configuration-toolbar sticky top-0 z-20 mb-0.5 space-y-0.5 border border-neutral-500/60 bg-neutral-900/95 p-0.5 backdrop-blur">
<p className="text-xs text-slate-400">Saved changes apply after an application restart.</p> <p className="text-xs text-slate-400">Saving applies the complete revision immediately and reloads each affected service.</p>
{/* All document actions stay together at the start of the toolbar. The {/* All document actions stay together at the start of the toolbar. The
editor may use a wide canvas, but width is never used to separate a editor may use a wide canvas, but width is never used to separate a
control from the content that explains it. */} control from the content that explains it. */}
@@ -75,9 +75,19 @@ export default function ConfigurationEditor({ snapshot, socket, runSensitive, on
setDraft(clone(serverValue)); setDraft(clone(serverValue));
setSecretOperations({}); setSecretOperations({});
}}>Reset</button> }}>Reset</button>
<button type="button" className="button-dark" disabled={!dirty || saving} onClick={save}>{saving ? 'Saving…' : 'Save configuration'}</button> <button type="button" className="button-dark" disabled={!dirty || saving} onClick={save}>{saving ? 'Applying…' : 'Save configuration'}</button>
</div> </div>
</div> </div>
{snapshot.configurationApplication?.services?.some((service) => service.status === 'failed') ? (
<div className="mb-0.5 border border-amber-500/60 bg-amber-950/40 p-1 text-xs text-amber-100">
<p className="font-semibold">Configuration was saved, but some services could not reload</p>
<ul className="mt-0.5 list-disc space-y-0.25 pl-4">
{snapshot.configurationApplication.services
.filter((service) => service.status === 'failed')
.map((service, index) => <li key={`${service.section}-${index}`}>{service.section}: {service.error}</li>)}
</ul>
</div>
) : null}
{error ? <p className="border border-red-500/60 bg-red-950/40 p-1 text-xs text-red-100">{error}</p> : null} {error ? <p className="border border-red-500/60 bg-red-950/40 p-1 text-xs text-red-100">{error}</p> : null}
{validationErrors.length ? ( {validationErrors.length ? (
<div className="border border-red-500/60 bg-red-950/40 p-1 text-xs text-red-100"> <div className="border border-red-500/60 bg-red-950/40 p-1 text-xs text-red-100">