@camstack/server 1.2.728 → 1.2.730
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +19 -0
- package/dist/agent/main.js +2 -14
- package/dist/api/core/cap-providers.js +0 -7
- package/dist/api/trpc/generated-cap-mounts.js +4 -1
- package/dist/api/trpc/generated-cap-routers.js +1923 -1839
- package/dist/boot/boot-config.js +1 -1
- package/dist/core/addon/addon-package.service.js +3 -105
- package/dist/core/addon-bridge/addon-bridge.service.js +1 -5
- package/dist/launcher.js +12 -124
- package/package.json +19 -17
- package/system/dist/addon-runner.js +1 -2
- package/system/dist/addon-runner.mjs +1 -2
- package/system/dist/{agent-https-B1XLr4nm.js → agent-https-C8Gz2jjS.js} +1 -1
- package/system/dist/{agent-https-BsedJhrb.mjs → agent-https-DZq8uf8L.mjs} +1 -1
- package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.js +1 -1
- package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.mjs +1 -1
- package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.js +1 -1
- package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.mjs +1 -1
- package/system/dist/builtins/alerts/alerts.addon.js +1 -1
- package/system/dist/builtins/alerts/alerts.addon.mjs +1 -1
- package/system/dist/builtins/autotrack/index.js +1 -1
- package/system/dist/builtins/autotrack/index.mjs +1 -1
- package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.js +2 -2
- package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.mjs +2 -2
- package/system/dist/builtins/calendars/calendars.addon.js +1 -1
- package/system/dist/builtins/calendars/calendars.addon.mjs +1 -1
- package/system/dist/builtins/camera-grid/index.js +1 -1
- package/system/dist/builtins/camera-grid/index.mjs +1 -1
- package/system/dist/builtins/composer/composer.addon.js +3 -3
- package/system/dist/builtins/composer/composer.addon.mjs +3 -3
- package/system/dist/builtins/console-logging/index.js +1 -1
- package/system/dist/builtins/console-logging/index.mjs +1 -1
- package/system/dist/builtins/core-blocks/core-blocks.addon.d.ts +6 -0
- package/system/dist/builtins/core-blocks/core-blocks.addon.js +1361 -440
- package/system/dist/builtins/core-blocks/core-blocks.addon.mjs +1360 -440
- package/system/dist/builtins/core-blocks/fan-presets-action-source.d.ts +35 -0
- package/system/dist/builtins/core-blocks/fan-presets-service.d.ts +83 -0
- package/system/dist/builtins/core-blocks/fan-presets-wiring.d.ts +31 -0
- package/system/dist/builtins/core-blocks/record-kinds.d.ts +15 -0
- package/system/dist/builtins/core-blocks/timed-run/timed-run-service.d.ts +84 -0
- package/system/dist/builtins/core-blocks/timed-run/timed-run-wiring.d.ts +21 -0
- package/system/dist/builtins/device-history/device-history.addon.d.ts +4 -0
- package/system/dist/builtins/device-history/device-history.addon.js +769 -17
- package/system/dist/builtins/device-history/device-history.addon.mjs +769 -17
- package/system/dist/builtins/device-history/runs/device-runs-provider.d.ts +7 -0
- package/system/dist/builtins/device-history/runs/device-runs-record-kinds.d.ts +15 -0
- package/system/dist/builtins/device-history/runs/device-runs-service.d.ts +42 -0
- package/system/dist/builtins/device-history/runs/energy-from-history.d.ts +22 -0
- package/system/dist/builtins/device-history/runs/run-recorder.d.ts +111 -0
- package/system/dist/builtins/device-history/runs/slice-readers.d.ts +9 -0
- package/system/dist/builtins/device-manager/device-manager.addon.js +1 -1
- package/system/dist/builtins/device-manager/device-manager.addon.mjs +1 -1
- package/system/dist/builtins/hub-forwarder/index.js +1 -1
- package/system/dist/builtins/hub-forwarder/index.mjs +1 -1
- package/system/dist/builtins/keychain/index.js +47 -38
- package/system/dist/builtins/keychain/index.mjs +47 -38
- package/system/dist/builtins/keychain/key-sources.d.ts +12 -7
- package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.js +1 -1
- package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.mjs +1 -1
- package/system/dist/builtins/local-auth/local-auth.addon.js +3 -3
- package/system/dist/builtins/local-auth/local-auth.addon.mjs +3 -3
- package/system/dist/builtins/local-network/local-network.addon.js +2 -2
- package/system/dist/builtins/local-network/local-network.addon.mjs +2 -2
- package/system/dist/builtins/loki-logging/index.js +1 -1
- package/system/dist/builtins/loki-logging/index.mjs +1 -1
- package/system/dist/builtins/native-metrics/native-metrics.addon.js +1 -1
- package/system/dist/builtins/native-metrics/native-metrics.addon.mjs +1 -1
- package/system/dist/builtins/platform-probe/index.js +1 -1
- package/system/dist/builtins/platform-probe/index.mjs +1 -1
- package/system/dist/builtins/record-entries/index.js +1 -1
- package/system/dist/builtins/record-entries/index.mjs +1 -1
- package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.js +1 -1
- package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.mjs +1 -1
- package/system/dist/builtins/snapshot/index.js +1 -1
- package/system/dist/builtins/snapshot/index.mjs +1 -1
- package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.js +1 -1
- package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.mjs +1 -1
- package/system/dist/builtins/sqlite-storage/index.js +1 -1
- package/system/dist/builtins/sqlite-storage/index.mjs +1 -1
- package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.js +2 -2
- package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.mjs +2 -2
- package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.js +1 -1
- package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.mjs +1 -1
- package/system/dist/builtins/system-config/system-config.addon.js +3 -3
- package/system/dist/builtins/system-config/system-config.addon.mjs +3 -3
- package/system/dist/builtins/winston-logging/index.js +1 -1
- package/system/dist/builtins/winston-logging/index.mjs +1 -1
- package/system/dist/{composition-sources-BjuQ3xot.mjs → composition-sources-4M_NnTnV.mjs} +1 -1
- package/system/dist/{composition-sources-C5r8i46e.js → composition-sources-hokiaS3J.js} +1 -1
- package/system/dist/{constants-Bh5wQoTg.js → constants-B0L3suFC.js} +1 -1
- package/system/dist/{constants-GnxjCxT3.mjs → constants-DTVU00LZ.mjs} +1 -1
- package/system/dist/{device-ca-OWEYAYaG.mjs → device-ca-C_y2GrU5.mjs} +2 -2
- package/system/dist/{device-ca-oM-nuINR.js → device-ca-DaTT1Y9v.js} +2 -2
- package/system/dist/{dist-Cw8KtuQY.mjs → dist-9lvgpcnm.mjs} +43394 -42706
- package/system/dist/{dist-B9xpybTG.js → dist-B3S0ruBa.js} +43217 -42457
- package/system/dist/file-host-worker.js +1 -1
- package/system/dist/file-host-worker.mjs +1 -1
- package/system/dist/{hub-mdns-ciao-BPENkOKX.js → hub-mdns-ciao-Dkw38L-g.js} +2 -2
- package/system/dist/{hub-mdns-ciao-C3qMZFP0.mjs → hub-mdns-ciao-xgLfZIVx.mjs} +2 -2
- package/system/dist/index.js +40 -186
- package/system/dist/index.mjs +41 -185
- package/system/dist/kernel/addon-installer.d.ts +9 -60
- package/system/dist/kernel/bootstrap-config.d.ts +3 -1
- package/system/dist/kernel/config-schema.d.ts +2 -11
- package/system/dist/kernel/fs-utils.d.ts +0 -6
- package/system/dist/kernel/index.d.ts +2 -3
- package/system/dist/{restore-archive-DJv5ATV8.mjs → restore-archive-cxnuWxQM.mjs} +1 -1
- package/system/dist/{restore-archive-BiN1yKZV.js → restore-archive-orP6eHBd.js} +1 -1
- package/system/dist/{retention-BT7TgsUn.js → retention-CB2cyW9k.js} +1 -1
- package/system/dist/{retention-DQje-V4I.mjs → retention-Me4u6zMp.mjs} +1 -1
- package/system/dist/{wal-maintenance-DM08Htuy.mjs → wal-maintenance-De7Ifvph.mjs} +0 -0
- package/system/dist/{wal-maintenance-BLwgOIXb.js → wal-maintenance-_PXj626-.js} +0 -0
- package/system/package.json +11 -2
- package/system/dist/kernel/workspace-detect.d.ts +0 -9
|
@@ -3,8 +3,9 @@ Object.defineProperties(exports, {
|
|
|
3
3
|
[Symbol.toStringTag]: { value: "Module" }
|
|
4
4
|
});
|
|
5
5
|
require("../../chunk-Cek0wNdY.js");
|
|
6
|
-
const require_dist = require("../../dist-
|
|
7
|
-
const require_retention = require("../../retention-
|
|
6
|
+
const require_dist = require("../../dist-B3S0ruBa.js");
|
|
7
|
+
const require_retention = require("../../retention-CB2cyW9k.js");
|
|
8
|
+
let node_crypto = require("node:crypto");
|
|
8
9
|
//#region src/builtins/device-history/capture/point-writer.ts
|
|
9
10
|
var FLUSH_INTERVAL_MS = 1e4;
|
|
10
11
|
var MAX_BUFFER_AGE_MS = 6e4;
|
|
@@ -484,7 +485,7 @@ function bounded(newestFirst, maxPoints) {
|
|
|
484
485
|
overflow
|
|
485
486
|
};
|
|
486
487
|
}
|
|
487
|
-
function errorText(err) {
|
|
488
|
+
function errorText$1(err) {
|
|
488
489
|
return err instanceof Error ? err.message : String(err);
|
|
489
490
|
}
|
|
490
491
|
var HistoryQuery = class {
|
|
@@ -549,7 +550,7 @@ var HistoryQuery = class {
|
|
|
549
550
|
} catch (err) {
|
|
550
551
|
out.push({
|
|
551
552
|
ok: false,
|
|
552
|
-
error: errorText(err)
|
|
553
|
+
error: errorText$1(err)
|
|
553
554
|
});
|
|
554
555
|
}
|
|
555
556
|
}
|
|
@@ -2599,6 +2600,688 @@ var HistoryRuntime = class {
|
|
|
2599
2600
|
}
|
|
2600
2601
|
};
|
|
2601
2602
|
//#endregion
|
|
2603
|
+
//#region src/builtins/device-history/runs/device-runs-provider.ts
|
|
2604
|
+
/** `device_outcome` index: deviceId, outcome (equality), then the start as the range. */
|
|
2605
|
+
function outcomeWhere(deviceId, outcome, window) {
|
|
2606
|
+
const range = {
|
|
2607
|
+
...window.atFrom !== void 0 ? { gte: window.atFrom } : {},
|
|
2608
|
+
...window.atTo !== void 0 ? { lt: window.atTo } : {}
|
|
2609
|
+
};
|
|
2610
|
+
return {
|
|
2611
|
+
deviceId,
|
|
2612
|
+
outcome,
|
|
2613
|
+
...Object.keys(range).length > 0 ? { startedAt: range } : {}
|
|
2614
|
+
};
|
|
2615
|
+
}
|
|
2616
|
+
function createDeviceRunsProvider(runs) {
|
|
2617
|
+
return {
|
|
2618
|
+
listRuns: async (input) => {
|
|
2619
|
+
const paging = {
|
|
2620
|
+
desc: true,
|
|
2621
|
+
limit: input.limit,
|
|
2622
|
+
...input.cursor !== void 0 ? { cursor: input.cursor } : {}
|
|
2623
|
+
};
|
|
2624
|
+
const page = input.outcome === void 0 ? await runs.query({
|
|
2625
|
+
deviceId: input.deviceId,
|
|
2626
|
+
...input.atFrom !== void 0 ? { atFrom: input.atFrom } : {},
|
|
2627
|
+
...input.atTo !== void 0 ? { atTo: input.atTo } : {},
|
|
2628
|
+
...paging
|
|
2629
|
+
}) : await runs.query({
|
|
2630
|
+
where: outcomeWhere(input.deviceId, input.outcome, input),
|
|
2631
|
+
...paging
|
|
2632
|
+
});
|
|
2633
|
+
return {
|
|
2634
|
+
runs: page.records.map((row) => row.data),
|
|
2635
|
+
nextCursor: page.nextCursor
|
|
2636
|
+
};
|
|
2637
|
+
},
|
|
2638
|
+
getRun: async ({ deviceId, runId }) => {
|
|
2639
|
+
const row = await runs.get(runId);
|
|
2640
|
+
return row !== null && row.data.deviceId === deviceId ? row.data : null;
|
|
2641
|
+
},
|
|
2642
|
+
getCurrentRun: async ({ deviceId }) => {
|
|
2643
|
+
return (await runs.query({
|
|
2644
|
+
where: {
|
|
2645
|
+
state: "open",
|
|
2646
|
+
deviceId
|
|
2647
|
+
},
|
|
2648
|
+
desc: true,
|
|
2649
|
+
limit: 1
|
|
2650
|
+
})).records[0]?.data ?? null;
|
|
2651
|
+
}
|
|
2652
|
+
};
|
|
2653
|
+
}
|
|
2654
|
+
var deviceRunsRecordKinds = require_dist.defineRecordKinds({ "device-runs": {
|
|
2655
|
+
schema: require_dist.DeviceRunSchema,
|
|
2656
|
+
class: "ledger",
|
|
2657
|
+
database: "events",
|
|
2658
|
+
writeTrigger: "a running-state flip opens (write-through) or closes a run; the boot reconcile closes or opens one the flips missed",
|
|
2659
|
+
device: "required",
|
|
2660
|
+
at: "required",
|
|
2661
|
+
indexes: [{
|
|
2662
|
+
name: "open",
|
|
2663
|
+
fields: ["state", "deviceId"]
|
|
2664
|
+
}, {
|
|
2665
|
+
name: "device_outcome",
|
|
2666
|
+
fields: [
|
|
2667
|
+
"deviceId",
|
|
2668
|
+
"outcome",
|
|
2669
|
+
"startedAt"
|
|
2670
|
+
]
|
|
2671
|
+
}],
|
|
2672
|
+
retention: { maxRowsPerDevice: 500 },
|
|
2673
|
+
deviceRemoval: "delete"
|
|
2674
|
+
} });
|
|
2675
|
+
//#endregion
|
|
2676
|
+
//#region src/builtins/device-history/runs/slice-readers.ts
|
|
2677
|
+
function numberField(slice, key) {
|
|
2678
|
+
const value = slice?.[key];
|
|
2679
|
+
return typeof value === "number" && Number.isFinite(value) ? value : null;
|
|
2680
|
+
}
|
|
2681
|
+
function stringField(slice, key) {
|
|
2682
|
+
const value = slice?.[key];
|
|
2683
|
+
return typeof value === "string" && value.length > 0 ? value : null;
|
|
2684
|
+
}
|
|
2685
|
+
function booleanField(slice, key) {
|
|
2686
|
+
const value = slice?.[key];
|
|
2687
|
+
return typeof value === "boolean" ? value : null;
|
|
2688
|
+
}
|
|
2689
|
+
function isSlice(value) {
|
|
2690
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
2691
|
+
}
|
|
2692
|
+
var MAX_POINTS = 5e3;
|
|
2693
|
+
/** kWh over `[from, to]`, or `null` when the series cannot say (no meter, no points, too short). */
|
|
2694
|
+
async function energyKwhFromHistory(query, deviceId, from, to) {
|
|
2695
|
+
if (to - from < 6e5) return null;
|
|
2696
|
+
const result = await query({
|
|
2697
|
+
key: require_dist.DEVICE_HISTORY_ENERGY_KEY,
|
|
2698
|
+
subject: {
|
|
2699
|
+
kind: "device",
|
|
2700
|
+
deviceId
|
|
2701
|
+
},
|
|
2702
|
+
from,
|
|
2703
|
+
to,
|
|
2704
|
+
resolution: "5m",
|
|
2705
|
+
maxPoints: MAX_POINTS
|
|
2706
|
+
});
|
|
2707
|
+
if (result.truncated) return null;
|
|
2708
|
+
let total = 0;
|
|
2709
|
+
let seen = false;
|
|
2710
|
+
for (const series of result.series) for (const point of series.points) {
|
|
2711
|
+
if (point.delta === null || point.t < from - 5 * 6e4 || point.t > to) continue;
|
|
2712
|
+
total += point.delta;
|
|
2713
|
+
seen = true;
|
|
2714
|
+
}
|
|
2715
|
+
return seen ? total : null;
|
|
2716
|
+
}
|
|
2717
|
+
//#endregion
|
|
2718
|
+
//#region src/builtins/device-history/runs/run-recorder.ts
|
|
2719
|
+
/**
|
|
2720
|
+
* The run recorder (D992): turns the `running-state` flips of a device into one
|
|
2721
|
+
* durable `device-runs` row per run.
|
|
2722
|
+
*
|
|
2723
|
+
* - open: `running` false -> true writes the OPEN row through, so a run that
|
|
2724
|
+
* outlives this process is on disk from its first instant;
|
|
2725
|
+
* - close: true -> false closes it, with the energy of the run and its outcome;
|
|
2726
|
+
* - boot reconcile: the open rows are compared with the live snapshots - a
|
|
2727
|
+
* device still running keeps its row, one that stopped while nobody watched
|
|
2728
|
+
* closes `unknown`, one running with no row opens late. A run is never
|
|
2729
|
+
* duplicated: a device has at most one open run, in the mirror and on disk.
|
|
2730
|
+
*
|
|
2731
|
+
* Nothing one-shot gates on a fallible read (D49): a failed load or snapshot
|
|
2732
|
+
* read changes nothing and the next pass tries again; events that arrive before
|
|
2733
|
+
* the first answered load wait in a bounded buffer and replay after it.
|
|
2734
|
+
*
|
|
2735
|
+
* Energy comes from device-history's own data: the meter counter at open minus
|
|
2736
|
+
* the counter at close, else the stored history of the window. Both unknown is
|
|
2737
|
+
* `null` - never `0`.
|
|
2738
|
+
*/
|
|
2739
|
+
var RUNNING_STATE_CAP = "running-state";
|
|
2740
|
+
var POWER_METER_CAP = "power-meter";
|
|
2741
|
+
/** Events held before the first answered load; beyond it the oldest are dropped, counted and logged. */
|
|
2742
|
+
var MAX_BUFFERED_EVENTS = 2e3;
|
|
2743
|
+
var RECORDER_TICK_MS = 6e4;
|
|
2744
|
+
var APPLIANCE_TYPES = new Set([
|
|
2745
|
+
require_dist.DeviceType.Washer,
|
|
2746
|
+
require_dist.DeviceType.Dryer,
|
|
2747
|
+
require_dist.DeviceType.Dishwasher
|
|
2748
|
+
]);
|
|
2749
|
+
function runIdOf(deviceId, startedAt) {
|
|
2750
|
+
return `${deviceId}:${startedAt}`;
|
|
2751
|
+
}
|
|
2752
|
+
function errorText(err) {
|
|
2753
|
+
return err instanceof Error ? err.message : String(err);
|
|
2754
|
+
}
|
|
2755
|
+
function applianceDetailOf(run) {
|
|
2756
|
+
return run.detail;
|
|
2757
|
+
}
|
|
2758
|
+
var RunRecorder = class {
|
|
2759
|
+
deps;
|
|
2760
|
+
open = /* @__PURE__ */ new Map();
|
|
2761
|
+
lastEnergy = /* @__PURE__ */ new Map();
|
|
2762
|
+
lastPower = /* @__PURE__ */ new Map();
|
|
2763
|
+
lastDishwasher = /* @__PURE__ */ new Map();
|
|
2764
|
+
chains = /* @__PURE__ */ new Map();
|
|
2765
|
+
buffered = [];
|
|
2766
|
+
loaded = false;
|
|
2767
|
+
droppedWhileBuffering = 0;
|
|
2768
|
+
ticks = 0;
|
|
2769
|
+
constructor(deps) {
|
|
2770
|
+
this.deps = deps;
|
|
2771
|
+
}
|
|
2772
|
+
/**
|
|
2773
|
+
* One minute of the owner's clock: retry the load until it answers, then
|
|
2774
|
+
* compare against the snapshots every {@link RECONCILE_EVERY_TICKS} and save
|
|
2775
|
+
* the open totals every {@link FLUSH_EVERY_TICKS}.
|
|
2776
|
+
*/
|
|
2777
|
+
async tick() {
|
|
2778
|
+
this.ticks += 1;
|
|
2779
|
+
if (!this.loaded || this.ticks % 5 === 0) await this.reconcile();
|
|
2780
|
+
if (this.ticks % 5 === 0) await this.flushOpen();
|
|
2781
|
+
}
|
|
2782
|
+
/** Has a load of the open rows ANSWERED? Until then flips are buffered. */
|
|
2783
|
+
isLoaded() {
|
|
2784
|
+
return this.loaded;
|
|
2785
|
+
}
|
|
2786
|
+
/** Resolves when every queued flip has been handled (specs, shutdown). */
|
|
2787
|
+
async idle() {
|
|
2788
|
+
await Promise.all([...this.chains.values()]);
|
|
2789
|
+
}
|
|
2790
|
+
/** The open run of a device, from the mirror. */
|
|
2791
|
+
openRunOf(deviceId) {
|
|
2792
|
+
return this.open.get(deviceId)?.run ?? null;
|
|
2793
|
+
}
|
|
2794
|
+
/** Feed one `DeviceStateChanged` slice. Never throws; a failure is logged with the device. */
|
|
2795
|
+
handleState(deviceId, capName, slice, at) {
|
|
2796
|
+
if (capName !== "running-state" && capName !== "power-meter" && capName !== "dishwasher") return;
|
|
2797
|
+
if (!this.loaded) {
|
|
2798
|
+
this.buffer({
|
|
2799
|
+
deviceId,
|
|
2800
|
+
capName,
|
|
2801
|
+
slice,
|
|
2802
|
+
at
|
|
2803
|
+
});
|
|
2804
|
+
return;
|
|
2805
|
+
}
|
|
2806
|
+
this.enqueue(deviceId, () => this.apply(deviceId, capName, slice, at));
|
|
2807
|
+
}
|
|
2808
|
+
buffer(entry) {
|
|
2809
|
+
this.buffered.push(entry);
|
|
2810
|
+
if (this.buffered.length > 2e3) {
|
|
2811
|
+
this.buffered = this.buffered.slice(this.buffered.length - MAX_BUFFERED_EVENTS);
|
|
2812
|
+
this.droppedWhileBuffering += 1;
|
|
2813
|
+
}
|
|
2814
|
+
}
|
|
2815
|
+
enqueue(deviceId, work) {
|
|
2816
|
+
const next = (this.chains.get(deviceId) ?? Promise.resolve()).then(work).catch((err) => {
|
|
2817
|
+
this.deps.logger.warn("device-runs: a flip could not be recorded", {
|
|
2818
|
+
tags: { deviceId },
|
|
2819
|
+
meta: { error: errorText(err) }
|
|
2820
|
+
});
|
|
2821
|
+
}).finally(() => {
|
|
2822
|
+
if (this.chains.get(deviceId) === next) this.chains.delete(deviceId);
|
|
2823
|
+
});
|
|
2824
|
+
this.chains.set(deviceId, next);
|
|
2825
|
+
return next;
|
|
2826
|
+
}
|
|
2827
|
+
async apply(deviceId, capName, slice, at) {
|
|
2828
|
+
if (capName === "power-meter") {
|
|
2829
|
+
this.notePower(deviceId, slice, at);
|
|
2830
|
+
return;
|
|
2831
|
+
}
|
|
2832
|
+
if (capName === "dishwasher") {
|
|
2833
|
+
this.lastDishwasher.set(deviceId, slice);
|
|
2834
|
+
return;
|
|
2835
|
+
}
|
|
2836
|
+
const type = await this.deps.deviceTypeOf(deviceId);
|
|
2837
|
+
if (type === void 0 || !APPLIANCE_TYPES.has(type)) return;
|
|
2838
|
+
const running = booleanField(slice, "running");
|
|
2839
|
+
if (running === null) return;
|
|
2840
|
+
const held = this.open.get(deviceId);
|
|
2841
|
+
const since = numberField(slice, "since") ?? at;
|
|
2842
|
+
if (running && held === void 0) await this.openRun(deviceId, since, "running-state", slice, at);
|
|
2843
|
+
else if (!running && held !== void 0) await this.closeRun(deviceId, held, since, "running-state", slice);
|
|
2844
|
+
else if (running && held !== void 0) this.notePhase(held, slice, at);
|
|
2845
|
+
}
|
|
2846
|
+
notePower(deviceId, slice, at) {
|
|
2847
|
+
const energy = numberField(slice, "energy");
|
|
2848
|
+
if (energy !== null) this.lastEnergy.set(deviceId, energy);
|
|
2849
|
+
const power = numberField(slice, "power");
|
|
2850
|
+
if (power !== null) this.lastPower.set(deviceId, power);
|
|
2851
|
+
const held = this.open.get(deviceId);
|
|
2852
|
+
if (held === void 0 || power === null) return;
|
|
2853
|
+
this.accrue(held.power, at);
|
|
2854
|
+
held.power.lastW = power;
|
|
2855
|
+
held.power.peakW = held.power.peakW === null ? power : Math.max(held.power.peakW, power);
|
|
2856
|
+
held.dirty = true;
|
|
2857
|
+
}
|
|
2858
|
+
/** Close the interval since the previous reading at the watts it held. */
|
|
2859
|
+
accrue(acc, to) {
|
|
2860
|
+
if (acc.lastW !== null && to > acc.lastAt) {
|
|
2861
|
+
const ms = to - acc.lastAt;
|
|
2862
|
+
acc.weightedWms += acc.lastW * ms;
|
|
2863
|
+
acc.observedMs += ms;
|
|
2864
|
+
}
|
|
2865
|
+
acc.lastAt = Math.max(acc.lastAt, to);
|
|
2866
|
+
}
|
|
2867
|
+
powerOf(open) {
|
|
2868
|
+
const { power } = open;
|
|
2869
|
+
return {
|
|
2870
|
+
peakW: power.peakW,
|
|
2871
|
+
avgW: power.observedMs > 0 ? power.weightedWms / power.observedMs : null,
|
|
2872
|
+
observedMs: power.observedMs
|
|
2873
|
+
};
|
|
2874
|
+
}
|
|
2875
|
+
async energyNow(deviceId) {
|
|
2876
|
+
const seen = this.lastEnergy.get(deviceId);
|
|
2877
|
+
if (seen !== void 0) return seen;
|
|
2878
|
+
try {
|
|
2879
|
+
return numberField(await this.deps.readCapSlice(deviceId, POWER_METER_CAP), "energy");
|
|
2880
|
+
} catch (err) {
|
|
2881
|
+
this.deps.logger.warn("device-runs: the meter could not be read", {
|
|
2882
|
+
tags: { deviceId },
|
|
2883
|
+
meta: { error: errorText(err) }
|
|
2884
|
+
});
|
|
2885
|
+
return null;
|
|
2886
|
+
}
|
|
2887
|
+
}
|
|
2888
|
+
async measureEnergy(deviceId, detail, startedAt, endedAt) {
|
|
2889
|
+
const end = await this.energyNow(deviceId);
|
|
2890
|
+
if (detail.energyStartKwh !== null && end !== null && end >= detail.energyStartKwh) return {
|
|
2891
|
+
kwh: end - detail.energyStartKwh,
|
|
2892
|
+
method: "counter-delta"
|
|
2893
|
+
};
|
|
2894
|
+
if (endedAt - startedAt >= 6e5) try {
|
|
2895
|
+
const kwh = await this.deps.energyFromHistory(deviceId, startedAt, endedAt);
|
|
2896
|
+
if (kwh !== null) return {
|
|
2897
|
+
kwh,
|
|
2898
|
+
method: "history-integral"
|
|
2899
|
+
};
|
|
2900
|
+
} catch (err) {
|
|
2901
|
+
this.deps.logger.warn("device-runs: the stored energy could not be read", {
|
|
2902
|
+
tags: { deviceId },
|
|
2903
|
+
meta: { error: errorText(err) }
|
|
2904
|
+
});
|
|
2905
|
+
}
|
|
2906
|
+
return {
|
|
2907
|
+
kwh: null,
|
|
2908
|
+
method: null
|
|
2909
|
+
};
|
|
2910
|
+
}
|
|
2911
|
+
notePhase(open, slice, at) {
|
|
2912
|
+
const phase = stringField(slice, "phase");
|
|
2913
|
+
if (phase === null) return;
|
|
2914
|
+
if (open.run.phases[open.run.phases.length - 1]?.phase === phase) return;
|
|
2915
|
+
open.run = {
|
|
2916
|
+
...open.run,
|
|
2917
|
+
phases: [...open.run.phases, {
|
|
2918
|
+
phase,
|
|
2919
|
+
at
|
|
2920
|
+
}]
|
|
2921
|
+
};
|
|
2922
|
+
open.dirty = true;
|
|
2923
|
+
}
|
|
2924
|
+
async openRun(deviceId, startedAt, source, slice, now, energyStartKwh) {
|
|
2925
|
+
const dishwasher = this.lastDishwasher.get(deviceId) ?? null;
|
|
2926
|
+
const phase = stringField(slice, "phase");
|
|
2927
|
+
const sliceSource = stringField(slice, "source");
|
|
2928
|
+
const power = this.lastPower.get(deviceId);
|
|
2929
|
+
const detail = {
|
|
2930
|
+
kind: "appliance",
|
|
2931
|
+
energyKwh: null,
|
|
2932
|
+
energyMethod: null,
|
|
2933
|
+
peakW: power ?? null,
|
|
2934
|
+
avgW: null,
|
|
2935
|
+
program: stringField(dishwasher, "program"),
|
|
2936
|
+
remainingAtStartSec: numberField(dishwasher, "remaining"),
|
|
2937
|
+
finalPhase: null,
|
|
2938
|
+
energyStartKwh: energyStartKwh !== void 0 ? energyStartKwh : await this.energyNow(deviceId),
|
|
2939
|
+
powerObservedMs: 0
|
|
2940
|
+
};
|
|
2941
|
+
const run = {
|
|
2942
|
+
runId: runIdOf(deviceId, startedAt),
|
|
2943
|
+
deviceId,
|
|
2944
|
+
kind: "appliance",
|
|
2945
|
+
state: "open",
|
|
2946
|
+
startedAt,
|
|
2947
|
+
endedAt: null,
|
|
2948
|
+
durationMs: null,
|
|
2949
|
+
outcome: null,
|
|
2950
|
+
startSource: source,
|
|
2951
|
+
endSource: null,
|
|
2952
|
+
runningSource: sliceSource === "native" || sliceSource === "assigned" ? sliceSource : null,
|
|
2953
|
+
phases: phase === null ? [] : [{
|
|
2954
|
+
phase,
|
|
2955
|
+
at: startedAt
|
|
2956
|
+
}],
|
|
2957
|
+
detail
|
|
2958
|
+
};
|
|
2959
|
+
await this.deps.runs.put({
|
|
2960
|
+
id: run.runId,
|
|
2961
|
+
deviceId,
|
|
2962
|
+
at: startedAt,
|
|
2963
|
+
data: run
|
|
2964
|
+
});
|
|
2965
|
+
this.open.set(deviceId, {
|
|
2966
|
+
run,
|
|
2967
|
+
dirty: false,
|
|
2968
|
+
power: {
|
|
2969
|
+
lastAt: Math.max(startedAt, now),
|
|
2970
|
+
lastW: power ?? null,
|
|
2971
|
+
weightedWms: 0,
|
|
2972
|
+
observedMs: 0,
|
|
2973
|
+
peakW: power ?? null
|
|
2974
|
+
}
|
|
2975
|
+
});
|
|
2976
|
+
this.deps.logger.info("device-runs: a run opened", {
|
|
2977
|
+
tags: { deviceId },
|
|
2978
|
+
meta: {
|
|
2979
|
+
runId: run.runId,
|
|
2980
|
+
source
|
|
2981
|
+
}
|
|
2982
|
+
});
|
|
2983
|
+
this.announce(require_dist.EventCategory.DeviceRunOpened, run);
|
|
2984
|
+
}
|
|
2985
|
+
async closeRun(deviceId, held, rawEndedAt, source, slice) {
|
|
2986
|
+
const { run } = held;
|
|
2987
|
+
const endedAt = Math.max(rawEndedAt, run.startedAt);
|
|
2988
|
+
this.accrue(held.power, endedAt);
|
|
2989
|
+
const measured = this.powerOf(held);
|
|
2990
|
+
const detail = applianceDetailOf(run);
|
|
2991
|
+
const energy = await this.measureEnergy(deviceId, detail, run.startedAt, endedAt);
|
|
2992
|
+
const phase = stringField(slice, "phase");
|
|
2993
|
+
const phases = phase !== null && run.phases[run.phases.length - 1]?.phase !== phase ? [...run.phases, {
|
|
2994
|
+
phase,
|
|
2995
|
+
at: endedAt
|
|
2996
|
+
}] : run.phases;
|
|
2997
|
+
const durationMs = endedAt - run.startedAt;
|
|
2998
|
+
const closed = {
|
|
2999
|
+
...run,
|
|
3000
|
+
state: "closed",
|
|
3001
|
+
endedAt,
|
|
3002
|
+
durationMs,
|
|
3003
|
+
outcome: this.outcomeOf(deviceId, source, durationMs, phases.map((p) => p.phase)),
|
|
3004
|
+
endSource: source,
|
|
3005
|
+
phases,
|
|
3006
|
+
detail: {
|
|
3007
|
+
...detail,
|
|
3008
|
+
energyKwh: energy.kwh,
|
|
3009
|
+
energyMethod: energy.method,
|
|
3010
|
+
peakW: measured.peakW,
|
|
3011
|
+
avgW: measured.avgW,
|
|
3012
|
+
powerObservedMs: measured.observedMs,
|
|
3013
|
+
finalPhase: phases[phases.length - 1]?.phase ?? null
|
|
3014
|
+
}
|
|
3015
|
+
};
|
|
3016
|
+
await this.deps.runs.put({
|
|
3017
|
+
id: closed.runId,
|
|
3018
|
+
deviceId,
|
|
3019
|
+
at: closed.startedAt,
|
|
3020
|
+
data: closed
|
|
3021
|
+
});
|
|
3022
|
+
this.open.delete(deviceId);
|
|
3023
|
+
this.deps.logger.info("device-runs: a run closed", {
|
|
3024
|
+
tags: { deviceId },
|
|
3025
|
+
meta: {
|
|
3026
|
+
runId: closed.runId,
|
|
3027
|
+
outcome: closed.outcome,
|
|
3028
|
+
durationMs,
|
|
3029
|
+
energyKwh: energy.kwh,
|
|
3030
|
+
energyMethod: energy.method,
|
|
3031
|
+
source
|
|
3032
|
+
}
|
|
3033
|
+
});
|
|
3034
|
+
this.announce(require_dist.EventCategory.DeviceRunClosed, closed);
|
|
3035
|
+
}
|
|
3036
|
+
outcomeOf(deviceId, source, durationMs, phases) {
|
|
3037
|
+
if (source === "reconcile") return "unknown";
|
|
3038
|
+
if (stringField(this.lastDishwasher.get(deviceId) ?? null, "state") === "error") return "error";
|
|
3039
|
+
const finished = phases.some((p) => /finish/i.test(p));
|
|
3040
|
+
return durationMs < 12e4 && !finished ? "aborted" : "completed";
|
|
3041
|
+
}
|
|
3042
|
+
announce(category, run) {
|
|
3043
|
+
try {
|
|
3044
|
+
this.deps.emit(category, run);
|
|
3045
|
+
} catch (err) {
|
|
3046
|
+
this.deps.logger.warn("device-runs: the run event was not emitted", {
|
|
3047
|
+
tags: { deviceId: run.deviceId },
|
|
3048
|
+
meta: {
|
|
3049
|
+
category,
|
|
3050
|
+
error: errorText(err)
|
|
3051
|
+
}
|
|
3052
|
+
});
|
|
3053
|
+
}
|
|
3054
|
+
}
|
|
3055
|
+
/**
|
|
3056
|
+
* Write the power totals of every open run (a crash then loses at most one
|
|
3057
|
+
* interval of peak/mean, never the run). Timer-driven; a failed write leaves
|
|
3058
|
+
* the run dirty for the next pass.
|
|
3059
|
+
*/
|
|
3060
|
+
async flushOpen() {
|
|
3061
|
+
const now = this.deps.clock();
|
|
3062
|
+
for (const [deviceId, held] of this.open) {
|
|
3063
|
+
if (!held.dirty) continue;
|
|
3064
|
+
this.accrue(held.power, now);
|
|
3065
|
+
const measured = this.powerOf(held);
|
|
3066
|
+
try {
|
|
3067
|
+
await this.deps.runs.patch(held.run.runId, {
|
|
3068
|
+
phases: held.run.phases,
|
|
3069
|
+
detail: {
|
|
3070
|
+
peakW: measured.peakW,
|
|
3071
|
+
avgW: measured.avgW,
|
|
3072
|
+
powerObservedMs: measured.observedMs
|
|
3073
|
+
}
|
|
3074
|
+
});
|
|
3075
|
+
held.dirty = false;
|
|
3076
|
+
} catch (err) {
|
|
3077
|
+
this.deps.logger.warn("device-runs: the open run totals were not saved", {
|
|
3078
|
+
tags: { deviceId },
|
|
3079
|
+
meta: {
|
|
3080
|
+
runId: held.run.runId,
|
|
3081
|
+
error: errorText(err)
|
|
3082
|
+
}
|
|
3083
|
+
});
|
|
3084
|
+
}
|
|
3085
|
+
}
|
|
3086
|
+
}
|
|
3087
|
+
/**
|
|
3088
|
+
* Compare the open rows on disk with the live snapshots. Returns `false` when
|
|
3089
|
+
* either read failed - nothing changed and the caller tries again (D49).
|
|
3090
|
+
* Only the FIRST answered pass reads the rows (the mirror is the truth after
|
|
3091
|
+
* it) and replays the flips buffered while it was pending; later passes
|
|
3092
|
+
* compare the mirror with the snapshots, so a row read a moment before a
|
|
3093
|
+
* close can never bring a closed run back.
|
|
3094
|
+
*/
|
|
3095
|
+
async reconcile() {
|
|
3096
|
+
let rows = [];
|
|
3097
|
+
let snapshots;
|
|
3098
|
+
try {
|
|
3099
|
+
if (!this.loaded) rows = await this.loadOpenRows();
|
|
3100
|
+
snapshots = await this.deps.readSnapshots();
|
|
3101
|
+
} catch (err) {
|
|
3102
|
+
this.deps.logger.warn("device-runs: reconcile read failed - nothing changed", { meta: { error: errorText(err) } });
|
|
3103
|
+
return false;
|
|
3104
|
+
}
|
|
3105
|
+
await this.settleAgainst(rows, snapshots);
|
|
3106
|
+
if (!this.loaded) {
|
|
3107
|
+
this.loaded = true;
|
|
3108
|
+
const replay = this.buffered;
|
|
3109
|
+
this.buffered = [];
|
|
3110
|
+
if (this.droppedWhileBuffering > 0) {
|
|
3111
|
+
this.deps.logger.warn("device-runs: flips were dropped while the load was pending", { meta: { dropped: this.droppedWhileBuffering } });
|
|
3112
|
+
this.droppedWhileBuffering = 0;
|
|
3113
|
+
}
|
|
3114
|
+
for (const entry of replay) this.handleState(entry.deviceId, entry.capName, entry.slice, entry.at);
|
|
3115
|
+
}
|
|
3116
|
+
return true;
|
|
3117
|
+
}
|
|
3118
|
+
async loadOpenRows() {
|
|
3119
|
+
const out = [];
|
|
3120
|
+
let cursor;
|
|
3121
|
+
do {
|
|
3122
|
+
const page = await this.deps.runs.query({
|
|
3123
|
+
where: { state: "open" },
|
|
3124
|
+
limit: 500,
|
|
3125
|
+
...cursor !== void 0 ? { cursor } : {}
|
|
3126
|
+
});
|
|
3127
|
+
for (const row of page.records) out.push(row.data);
|
|
3128
|
+
cursor = page.nextCursor ?? void 0;
|
|
3129
|
+
} while (cursor !== void 0);
|
|
3130
|
+
return out;
|
|
3131
|
+
}
|
|
3132
|
+
async settleAgainst(rows, snapshots) {
|
|
3133
|
+
const now = this.deps.clock();
|
|
3134
|
+
const newest = /* @__PURE__ */ new Map();
|
|
3135
|
+
for (const row of rows.toSorted((a, b) => a.startedAt - b.startedAt)) {
|
|
3136
|
+
const earlier = newest.get(row.deviceId);
|
|
3137
|
+
if (earlier !== void 0) await this.exclusive(earlier.deviceId, async () => {
|
|
3138
|
+
await this.closeRun(earlier.deviceId, this.adopt(earlier), now, "reconcile", {});
|
|
3139
|
+
});
|
|
3140
|
+
newest.set(row.deviceId, row);
|
|
3141
|
+
}
|
|
3142
|
+
for (const row of newest.values()) await this.exclusive(row.deviceId, async () => {
|
|
3143
|
+
this.seedPower(row.deviceId, snapshots[String(row.deviceId)]?.[POWER_METER_CAP]);
|
|
3144
|
+
const held = this.adopt(row);
|
|
3145
|
+
const slice = runningSliceOf(snapshots, row.deviceId);
|
|
3146
|
+
if (booleanField(slice, "running") !== false) return;
|
|
3147
|
+
const since = numberField(slice, "since");
|
|
3148
|
+
await this.closeRun(row.deviceId, held, since !== null && since > row.startedAt ? since : now, "reconcile", slice ?? {});
|
|
3149
|
+
});
|
|
3150
|
+
await this.settleMirror(snapshots, now);
|
|
3151
|
+
await this.openLate(snapshots, now);
|
|
3152
|
+
}
|
|
3153
|
+
/** A mirrored run whose device now says it stopped closes `unknown` (a later pass, flips missed). */
|
|
3154
|
+
async settleMirror(snapshots, now) {
|
|
3155
|
+
for (const [deviceId, held] of [...this.open]) {
|
|
3156
|
+
const slice = runningSliceOf(snapshots, deviceId);
|
|
3157
|
+
if (booleanField(slice, "running") !== false) continue;
|
|
3158
|
+
const since = numberField(slice, "since");
|
|
3159
|
+
await this.exclusive(deviceId, async () => {
|
|
3160
|
+
const current = this.open.get(deviceId);
|
|
3161
|
+
if (current === void 0 || current.run.runId !== held.run.runId) return;
|
|
3162
|
+
await this.closeRun(deviceId, current, since !== null && since > held.run.startedAt ? since : now, "reconcile", slice ?? {});
|
|
3163
|
+
});
|
|
3164
|
+
}
|
|
3165
|
+
}
|
|
3166
|
+
/** A device running with no open run: open it late, from its own `since`. */
|
|
3167
|
+
async openLate(snapshots, now) {
|
|
3168
|
+
for (const [key, caps] of Object.entries(snapshots)) {
|
|
3169
|
+
const deviceId = Number(key);
|
|
3170
|
+
if (!Number.isInteger(deviceId)) continue;
|
|
3171
|
+
const slice = caps[RUNNING_STATE_CAP];
|
|
3172
|
+
if (!isSlice(slice) || booleanField(slice, "running") !== true) continue;
|
|
3173
|
+
await this.exclusive(deviceId, async () => {
|
|
3174
|
+
if (this.open.has(deviceId)) return;
|
|
3175
|
+
const type = await this.deps.deviceTypeOf(deviceId);
|
|
3176
|
+
if (type === void 0 || !APPLIANCE_TYPES.has(type)) return;
|
|
3177
|
+
this.seedPower(deviceId, caps[POWER_METER_CAP]);
|
|
3178
|
+
await this.openRun(deviceId, numberField(slice, "since") ?? now, "reconcile", slice, now, null);
|
|
3179
|
+
});
|
|
3180
|
+
}
|
|
3181
|
+
}
|
|
3182
|
+
/** One device at a time; a failure is logged with the device and never aborts the pass. */
|
|
3183
|
+
exclusive(deviceId, work) {
|
|
3184
|
+
return this.enqueue(deviceId, work);
|
|
3185
|
+
}
|
|
3186
|
+
seedPower(deviceId, slice) {
|
|
3187
|
+
if (!isSlice(slice)) return;
|
|
3188
|
+
const energy = numberField(slice, "energy");
|
|
3189
|
+
if (energy !== null && !this.lastEnergy.has(deviceId)) this.lastEnergy.set(deviceId, energy);
|
|
3190
|
+
const power = numberField(slice, "power");
|
|
3191
|
+
if (power !== null && !this.lastPower.has(deviceId)) this.lastPower.set(deviceId, power);
|
|
3192
|
+
}
|
|
3193
|
+
/** Put a stored open row back in the mirror, its power totals resumed from the row. */
|
|
3194
|
+
adopt(row) {
|
|
3195
|
+
const existing = this.open.get(row.deviceId);
|
|
3196
|
+
if (existing !== void 0) return existing;
|
|
3197
|
+
const detail = applianceDetailOf(row);
|
|
3198
|
+
const held = {
|
|
3199
|
+
run: row,
|
|
3200
|
+
dirty: false,
|
|
3201
|
+
power: {
|
|
3202
|
+
lastAt: this.deps.clock(),
|
|
3203
|
+
lastW: this.lastPower.get(row.deviceId) ?? null,
|
|
3204
|
+
weightedWms: (detail.avgW ?? 0) * detail.powerObservedMs,
|
|
3205
|
+
observedMs: detail.powerObservedMs,
|
|
3206
|
+
peakW: detail.peakW
|
|
3207
|
+
}
|
|
3208
|
+
};
|
|
3209
|
+
this.open.set(row.deviceId, held);
|
|
3210
|
+
return held;
|
|
3211
|
+
}
|
|
3212
|
+
};
|
|
3213
|
+
function runningSliceOf(snapshots, deviceId) {
|
|
3214
|
+
const slice = snapshots[String(deviceId)]?.[RUNNING_STATE_CAP];
|
|
3215
|
+
return isSlice(slice) ? slice : null;
|
|
3216
|
+
}
|
|
3217
|
+
//#endregion
|
|
3218
|
+
//#region src/builtins/device-history/runs/device-runs-service.ts
|
|
3219
|
+
var DeviceRunsService = class {
|
|
3220
|
+
deps;
|
|
3221
|
+
recorder = null;
|
|
3222
|
+
handle = null;
|
|
3223
|
+
timer = null;
|
|
3224
|
+
provider = null;
|
|
3225
|
+
constructor(deps) {
|
|
3226
|
+
this.deps = deps;
|
|
3227
|
+
}
|
|
3228
|
+
/** Declare the kind, then the first reconcile; an unanswered one is retried by the timer. */
|
|
3229
|
+
async open() {
|
|
3230
|
+
await this.deps.records.declare(deviceRunsRecordKinds);
|
|
3231
|
+
const handle = this.deps.records.kind(deviceRunsRecordKinds["device-runs"]);
|
|
3232
|
+
this.handle = handle;
|
|
3233
|
+
const recorder = new RunRecorder({
|
|
3234
|
+
...this.deps,
|
|
3235
|
+
runs: handle
|
|
3236
|
+
});
|
|
3237
|
+
this.recorder = recorder;
|
|
3238
|
+
this.provider = createDeviceRunsProvider(handle);
|
|
3239
|
+
await recorder.reconcile();
|
|
3240
|
+
return { provider: this.provider };
|
|
3241
|
+
}
|
|
3242
|
+
startTimer() {
|
|
3243
|
+
const recorder = this.recorder;
|
|
3244
|
+
if (recorder === null || this.timer !== null) return;
|
|
3245
|
+
const timer = setInterval(() => {
|
|
3246
|
+
recorder.tick().catch((err) => {
|
|
3247
|
+
this.deps.logger.warn("device-runs: scheduled pass threw", { meta: { error: err instanceof Error ? err.message : String(err) } });
|
|
3248
|
+
});
|
|
3249
|
+
}, RECORDER_TICK_MS);
|
|
3250
|
+
timer.unref();
|
|
3251
|
+
this.timer = timer;
|
|
3252
|
+
}
|
|
3253
|
+
handleState(deviceId, capName, slice, at) {
|
|
3254
|
+
this.recorder?.handleState(deviceId, capName, slice, at);
|
|
3255
|
+
}
|
|
3256
|
+
async stop() {
|
|
3257
|
+
if (this.timer !== null) clearInterval(this.timer);
|
|
3258
|
+
this.timer = null;
|
|
3259
|
+
const recorder = this.recorder;
|
|
3260
|
+
if (recorder === null) return;
|
|
3261
|
+
await recorder.idle();
|
|
3262
|
+
await recorder.flushOpen();
|
|
3263
|
+
}
|
|
3264
|
+
/** The D865 hook body: how many run rows the removal deleted. */
|
|
3265
|
+
async removeDevice(deviceId) {
|
|
3266
|
+
return (await this.deps.records.deleteDevice(deviceId, { kinds: ["device-runs"] }))["device-runs"] ?? 0;
|
|
3267
|
+
}
|
|
3268
|
+
/** Run rows per device, for the admin clean-up listing. */
|
|
3269
|
+
async countByDevice() {
|
|
3270
|
+
const handle = this.handle;
|
|
3271
|
+
if (handle === null) return [];
|
|
3272
|
+
const rows = await handle.aggregate({
|
|
3273
|
+
op: "count",
|
|
3274
|
+
groupBy: "deviceId"
|
|
3275
|
+
});
|
|
3276
|
+
const out = [];
|
|
3277
|
+
for (const row of rows) if (typeof row.group === "number" && row.value !== null) out.push({
|
|
3278
|
+
deviceId: row.group,
|
|
3279
|
+
count: row.value
|
|
3280
|
+
});
|
|
3281
|
+
return out;
|
|
3282
|
+
}
|
|
3283
|
+
};
|
|
3284
|
+
//#endregion
|
|
2602
3285
|
//#region src/builtins/device-history/device-history.addon.ts
|
|
2603
3286
|
/**
|
|
2604
3287
|
* device-history — the ONE mechanism for numeric history (D850). Hub-only, its
|
|
@@ -2643,6 +3326,8 @@ var DeviceHistoryAddon = class extends require_dist.BaseAddon {
|
|
|
2643
3326
|
runtime = null;
|
|
2644
3327
|
unsubscribe = null;
|
|
2645
3328
|
removalHook = null;
|
|
3329
|
+
runsProvider = null;
|
|
3330
|
+
runs = null;
|
|
2646
3331
|
/** This instance's readiness generation (the base class keeps its own private). */
|
|
2647
3332
|
readinessGeneration = `device-history-${Date.now().toString(36)}`;
|
|
2648
3333
|
constructor() {
|
|
@@ -2658,7 +3343,11 @@ var DeviceHistoryAddon = class extends require_dist.BaseAddon {
|
|
|
2658
3343
|
if (ctx === null) return;
|
|
2659
3344
|
const raw = ctx.kernel?.localNodeId ?? "hub";
|
|
2660
3345
|
const nodeId = raw.includes("/") ? raw.split("/")[0] ?? raw : raw;
|
|
2661
|
-
for (const capName of [
|
|
3346
|
+
for (const capName of [
|
|
3347
|
+
require_dist.deviceHistoryCapability.name,
|
|
3348
|
+
require_dist.deviceRunsCapability.name,
|
|
3349
|
+
require_dist.deviceRemovalHookCapability.name
|
|
3350
|
+
]) try {
|
|
2662
3351
|
require_dist.emitReadiness(ctx.eventBus, {
|
|
2663
3352
|
capName,
|
|
2664
3353
|
scope: {
|
|
@@ -2703,6 +3392,10 @@ var DeviceHistoryAddon = class extends require_dist.BaseAddon {
|
|
|
2703
3392
|
if (this.runtime === null) throw new Error("device-history is starting — the history store is not open yet");
|
|
2704
3393
|
return this.runtime;
|
|
2705
3394
|
}
|
|
3395
|
+
requireRuns() {
|
|
3396
|
+
if (this.runsProvider === null) throw new Error("device-runs is starting — the run ledger is not open yet");
|
|
3397
|
+
return this.runsProvider;
|
|
3398
|
+
}
|
|
2706
3399
|
async onInitialize() {
|
|
2707
3400
|
const provider = {
|
|
2708
3401
|
listSeries: async (input) => this.requireRuntime().query.listSeries({
|
|
@@ -2737,34 +3430,57 @@ var DeviceHistoryAddon = class extends require_dist.BaseAddon {
|
|
|
2737
3430
|
listOrphanSeries: async () => this.requireRuntime().listOrphans(),
|
|
2738
3431
|
deleteOrphanSeries: async (input) => ({ results: await this.requireRuntime().deleteOrphans(input.seriesIds) })
|
|
2739
3432
|
};
|
|
3433
|
+
const runsFacade = {
|
|
3434
|
+
listRuns: async (input) => this.requireRuns().listRuns(input),
|
|
3435
|
+
getRun: async (input) => this.requireRuns().getRun(input),
|
|
3436
|
+
getCurrentRun: async (input) => this.requireRuns().getCurrentRun(input)
|
|
3437
|
+
};
|
|
2740
3438
|
this.emitStoreReadiness("starting");
|
|
2741
3439
|
this.ctx.logger.info("Initialized — device-history provider registered (store opens on hub link)");
|
|
2742
3440
|
const removalHook = {
|
|
2743
3441
|
onDeviceRemoved: async (input) => {
|
|
2744
3442
|
const { series } = await this.requireRuntime().removeDevice(input.deviceId);
|
|
2745
|
-
|
|
3443
|
+
const deviceRuns = await this.runs?.removeDevice(input.deviceId) ?? 0;
|
|
3444
|
+
if (series > 0 || deviceRuns > 0) this.ctx.logger.info("device-history: removed the history of a deleted device", {
|
|
2746
3445
|
tags: { deviceId: input.deviceId },
|
|
2747
3446
|
meta: {
|
|
2748
|
-
counts: {
|
|
3447
|
+
counts: {
|
|
3448
|
+
series,
|
|
3449
|
+
deviceRuns
|
|
3450
|
+
},
|
|
2749
3451
|
deletedAt: input.deletedAt
|
|
2750
3452
|
}
|
|
2751
3453
|
});
|
|
2752
|
-
return { counts: {
|
|
3454
|
+
return { counts: {
|
|
3455
|
+
series,
|
|
3456
|
+
deviceRuns
|
|
3457
|
+
} };
|
|
2753
3458
|
},
|
|
2754
|
-
listDeviceData: async () => [...this.requireRuntime().seriesByDevice()].map(([deviceId, count]) => ({
|
|
3459
|
+
listDeviceData: async () => [...[...this.requireRuntime().seriesByDevice()].map(([deviceId, count]) => ({
|
|
2755
3460
|
store: "series",
|
|
2756
3461
|
deviceId,
|
|
2757
3462
|
count
|
|
2758
|
-
}))
|
|
3463
|
+
})), ...(await this.runs?.countByDevice() ?? []).map(({ deviceId, count }) => ({
|
|
3464
|
+
store: "runs",
|
|
3465
|
+
deviceId,
|
|
3466
|
+
count
|
|
3467
|
+
}))]
|
|
2759
3468
|
};
|
|
2760
3469
|
this.removalHook = removalHook;
|
|
2761
|
-
return [
|
|
2762
|
-
|
|
2763
|
-
|
|
2764
|
-
|
|
2765
|
-
|
|
2766
|
-
|
|
2767
|
-
|
|
3470
|
+
return [
|
|
3471
|
+
{
|
|
3472
|
+
capability: require_dist.deviceHistoryCapability,
|
|
3473
|
+
provider
|
|
3474
|
+
},
|
|
3475
|
+
{
|
|
3476
|
+
capability: require_dist.deviceRunsCapability,
|
|
3477
|
+
provider: runsFacade
|
|
3478
|
+
},
|
|
3479
|
+
{
|
|
3480
|
+
capability: require_dist.deviceRemovalHookCapability,
|
|
3481
|
+
provider: removalHook
|
|
3482
|
+
}
|
|
3483
|
+
];
|
|
2768
3484
|
}
|
|
2769
3485
|
async onHubReachable() {
|
|
2770
3486
|
const api = this.ctx.api;
|
|
@@ -2802,6 +3518,10 @@ var DeviceHistoryAddon = class extends require_dist.BaseAddon {
|
|
|
2802
3518
|
clock: () => Date.now()
|
|
2803
3519
|
});
|
|
2804
3520
|
await runtime.prepare();
|
|
3521
|
+
const runs = this.openRuns(runtime);
|
|
3522
|
+
const runsOpened = await runs.open();
|
|
3523
|
+
this.runsProvider = runsOpened.provider;
|
|
3524
|
+
this.runs = runs;
|
|
2805
3525
|
this.unsubscribe = this.ctx.eventBus.subscribe({ category: require_dist.EventCategory.DeviceStateChanged }, (event) => {
|
|
2806
3526
|
const data = event.data;
|
|
2807
3527
|
if (!isRecord(data)) return;
|
|
@@ -2809,11 +3529,13 @@ var DeviceHistoryAddon = class extends require_dist.BaseAddon {
|
|
|
2809
3529
|
if (typeof deviceId !== "number" || typeof capName !== "string" || !isRecord(slice)) return;
|
|
2810
3530
|
const at = event.timestamp instanceof Date ? event.timestamp.getTime() : Date.now();
|
|
2811
3531
|
runtime.capture.handleState(deviceId, capName, slice, at);
|
|
3532
|
+
runs.handleState(deviceId, capName, slice, at);
|
|
2812
3533
|
});
|
|
2813
3534
|
this.ctx.addDisposer(async () => this.stopRuntime());
|
|
2814
3535
|
this.runtime = runtime;
|
|
2815
3536
|
await runtime.finishBoot();
|
|
2816
3537
|
runtime.startTimers();
|
|
3538
|
+
runs.startTimer();
|
|
2817
3539
|
const removalHook = this.removalHook;
|
|
2818
3540
|
if (removalHook !== null) this.ctx.addDisposer(require_dist.armRemovalReconcile({
|
|
2819
3541
|
api: this.ctx.api,
|
|
@@ -2826,15 +3548,45 @@ var DeviceHistoryAddon = class extends require_dist.BaseAddon {
|
|
|
2826
3548
|
metrics: runtime.status().metrics
|
|
2827
3549
|
} });
|
|
2828
3550
|
}
|
|
3551
|
+
openRuns(runtime) {
|
|
3552
|
+
const { ctx } = this;
|
|
3553
|
+
const records = ctx.records;
|
|
3554
|
+
if (records === void 0) throw new Error("device-history needs ctx.records on the hub for the run ledger");
|
|
3555
|
+
return new DeviceRunsService({
|
|
3556
|
+
records,
|
|
3557
|
+
readSnapshots: async () => ctx.api.deviceState.getAllSnapshots.query({}),
|
|
3558
|
+
readCapSlice: (deviceId, capName) => ctx.api.deviceState.getCapSlice.query({
|
|
3559
|
+
deviceId,
|
|
3560
|
+
capName
|
|
3561
|
+
}),
|
|
3562
|
+
deviceTypeOf: (deviceId) => runtime.directory.ensure(deviceId),
|
|
3563
|
+
energyFromHistory: (deviceId, from, to) => energyKwhFromHistory((query) => runtime.query.query(query), deviceId, from, to),
|
|
3564
|
+
emit: (category, run) => ctx.eventBus.emit({
|
|
3565
|
+
id: (0, node_crypto.randomUUID)(),
|
|
3566
|
+
timestamp: /* @__PURE__ */ new Date(),
|
|
3567
|
+
source: {
|
|
3568
|
+
type: "device",
|
|
3569
|
+
id: run.deviceId
|
|
3570
|
+
},
|
|
3571
|
+
category,
|
|
3572
|
+
data: run
|
|
3573
|
+
}),
|
|
3574
|
+
logger: ctx.logger,
|
|
3575
|
+
clock: () => Date.now()
|
|
3576
|
+
});
|
|
3577
|
+
}
|
|
2829
3578
|
async stopRuntime() {
|
|
2830
3579
|
this.unsubscribe?.();
|
|
2831
3580
|
this.unsubscribe = null;
|
|
3581
|
+
await this.runs?.stop();
|
|
2832
3582
|
await this.runtime?.stop();
|
|
2833
3583
|
}
|
|
2834
3584
|
async onShutdown() {
|
|
2835
3585
|
this.emitStoreReadiness("down");
|
|
2836
3586
|
await this.stopRuntime();
|
|
2837
3587
|
this.runtime = null;
|
|
3588
|
+
this.runs = null;
|
|
3589
|
+
this.runsProvider = null;
|
|
2838
3590
|
}
|
|
2839
3591
|
globalSettingsSchema() {
|
|
2840
3592
|
return this.schema({ sections: [{
|