@camstack/types 1.2.141 → 1.2.143

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_event_category = require("./event-category-BaEgqJNv.js");
3
- const require_sleep = require("./sleep-BwGJ_wL_.js");
3
+ const require_sleep = require("./sleep-jdpPltQH.js");
4
4
  const require_canonical_hash = require("./canonical-hash-DNV8S5ET.js");
5
5
  const require_enums = require("./enums.js");
6
6
  const require_err_msg = require("./err-msg-COpsHMw2.js");
@@ -6616,6 +6616,89 @@ var LocationStatSchema = zod.z.object({
6616
6616
  fileCount: zod.z.number(),
6617
6617
  present: zod.z.boolean()
6618
6618
  });
6619
+ /** Lifecycle of a backup run. Terminal states: succeeded / failed / cancelled. */
6620
+ var BackupRunStateSchema = zod.z.enum([
6621
+ "queued",
6622
+ "running",
6623
+ "succeeded",
6624
+ "failed",
6625
+ "cancelled"
6626
+ ]);
6627
+ /**
6628
+ * Where a running backup currently is. `queued` before it starts,
6629
+ * `building` while the tar.gz is being staged, `uploading` during the
6630
+ * per-destination fan-out, `done` once terminal.
6631
+ */
6632
+ var BackupRunPhaseSchema = zod.z.enum([
6633
+ "queued",
6634
+ "building",
6635
+ "uploading",
6636
+ "done"
6637
+ ]);
6638
+ /**
6639
+ * Observable state of one backup run — readable WHILE it runs via
6640
+ * `backup.listRuns`. This is what makes the execution queue and
6641
+ * `backup.cancel` usable: the 2026-09-04 incident (two concurrent
6642
+ * multi-GB builds, staging 5.1 GB → 18 GB, load 62) was only
6643
+ * diagnosable with `du` because nothing reported that runs existed or
6644
+ * how large the staged archive had grown.
6645
+ */
6646
+ var BackupRunSchema = zod.z.object({
6647
+ /** Stable run id — the handle `backup.cancel` takes. */
6648
+ id: zod.z.string(),
6649
+ state: BackupRunStateSchema,
6650
+ phase: BackupRunPhaseSchema,
6651
+ /**
6652
+ * Resolved destination location ids. Empty while queued (targets are
6653
+ * resolved when the run starts, against the then-current policies).
6654
+ */
6655
+ destinationIds: zod.z.array(zod.z.string()).readonly(),
6656
+ label: zod.z.string().optional(),
6657
+ /** ms-epoch when the run was submitted (trigger call / schedule fire). */
6658
+ requestedAt: zod.z.number(),
6659
+ /** ms-epoch when the run left the queue and started building. */
6660
+ startedAt: zod.z.number().optional(),
6661
+ /** ms-epoch when the run reached a terminal state. */
6662
+ finishedAt: zod.z.number().optional(),
6663
+ /** Compressed bytes of the staging archive written so far. */
6664
+ stagedBytes: zod.z.number(),
6665
+ /** Final staged archive size, once the build phase completes. */
6666
+ archiveSizeBytes: zod.z.number().optional(),
6667
+ /** Bytes pushed to the destination currently uploading. */
6668
+ uploadedBytes: zod.z.number(),
6669
+ /** Destinations where the archive fully landed (uploaded + indexed). */
6670
+ completedDestinationIds: zod.z.array(zod.z.string()).readonly(),
6671
+ /** Destinations that failed during the fan-out. */
6672
+ failedDestinationIds: zod.z.array(zod.z.string()).readonly(),
6673
+ /** Failure message when `state === 'failed'`. */
6674
+ error: zod.z.string().optional(),
6675
+ /**
6676
+ * 1-based place in the execution queue — 1 = runs next. Present only
6677
+ * while `state === 'queued'`. Stamped by the orchestrator from the
6678
+ * queue's OWN pending order, never derived from timestamps, so the
6679
+ * UI cannot show an order the executor will not honour.
6680
+ */
6681
+ queuePosition: zod.z.number().int().min(1).optional()
6682
+ });
6683
+ /**
6684
+ * Result of `backup.trigger`. The call still resolves when the run
6685
+ * terminates (compat with schedule-driven runs and the admin UI), but
6686
+ * it now names the run and says whether it had to WAIT: a trigger that
6687
+ * arrives while another run is in flight is enqueued (or joined onto
6688
+ * an identical already-queued run), never started concurrently.
6689
+ */
6690
+ var BackupTriggerResultSchema = zod.z.object({
6691
+ /** The run this trigger mapped to — poll it via `listRuns`, stop it via `cancel`. */
6692
+ runId: zod.z.string(),
6693
+ /** True when the run waited behind an in-flight run instead of starting immediately. */
6694
+ queued: zod.z.boolean(),
6695
+ /** True when this trigger was coalesced onto an identical already-queued run. */
6696
+ joined: zod.z.boolean(),
6697
+ /** True when the run was cancelled before completing every destination. */
6698
+ cancelled: zod.z.boolean(),
6699
+ /** One entry per destination the archive landed at (partial on cancel). */
6700
+ entries: zod.z.array(BackupEntrySchema).readonly()
6701
+ });
6619
6702
  /**
6620
6703
  * A backup schedule — the N:M "entry" that binds one cron cadence to a
6621
6704
  * SET of destination locations. Supersedes the per-location cron on
@@ -6673,6 +6756,11 @@ var backupCapability = {
6673
6756
  * Trigger a backup. Without `destinations` the orchestrator fans
6674
6757
  * out to every destination flagged as enabled in the routing
6675
6758
  * config; with it, only the listed addons receive the archive.
6759
+ *
6760
+ * At most ONE backup run executes at a time — the source tree and
6761
+ * the staging disk are shared by every run, so a second trigger
6762
+ * while one is in flight is enqueued (or joined onto an identical
6763
+ * queued run) and the result says so. See D342.
6676
6764
  */
6677
6765
  trigger: require_sleep.method(zod.z.object({
6678
6766
  /** Subset of registered `backup-destination` addon ids to write to. */
@@ -6686,7 +6774,30 @@ var backupCapability = {
6686
6774
  * retention (manual runs).
6687
6775
  */
6688
6776
  retentionCount: zod.z.number().int().min(1).max(1e3).optional()
6689
- }).optional(), zod.z.array(BackupEntrySchema).readonly(), {
6777
+ }).optional(), BackupTriggerResultSchema, {
6778
+ kind: "mutation",
6779
+ auth: "admin"
6780
+ }),
6781
+ /**
6782
+ * Every run the orchestrator knows about, in EXECUTION order: the
6783
+ * running run first, then queued runs in the exact order they will
6784
+ * execute (each with `queuePosition`, 1 = next), then the bounded
6785
+ * finished history newest-first. Only one run executes at a time
6786
+ * (D342) — the queued section IS the line. Each run carries live
6787
+ * phase + byte counters so a runaway build is visible in seconds,
6788
+ * not via `du`.
6789
+ */
6790
+ listRuns: require_sleep.method(zod.z.void(), zod.z.array(BackupRunSchema).readonly(), { auth: "admin" }),
6791
+ /**
6792
+ * Stop a backup run. Mirrors `storage-migration.cancel` semantics:
6793
+ * id in, `{ cancelled }` out — `false` when the run is unknown or
6794
+ * already terminal. A QUEUED run is removed before it ever starts;
6795
+ * the RUNNING run has its tar/upload stream actually aborted, the
6796
+ * half-written staging archive is deleted, and the in-flight
6797
+ * destination upload is aborted server-side (partial discarded).
6798
+ * Destinations that already completed keep their archive.
6799
+ */
6800
+ cancel: require_sleep.method(zod.z.object({ runId: zod.z.string() }), zod.z.object({ cancelled: zod.z.boolean() }), {
6690
6801
  kind: "mutation",
6691
6802
  auth: "admin"
6692
6803
  }),
@@ -7570,6 +7681,38 @@ var streamBrokerCapability = {
7570
7681
  auth: "admin"
7571
7682
  }),
7572
7683
  /**
7684
+ * The HARDWARE behind a device number was replaced
7685
+ * (`deviceManager.migrateDevice`). Forget every piece of broker state that
7686
+ * described the old box, so the next catalog pull derives everything from
7687
+ * the camera that is actually there:
7688
+ *
7689
+ * - every `derived:*` stream definition — a derived is authored against a
7690
+ * specific profile layout, and against the wrong hardware its feeder
7691
+ * respawns forever (observed at attempt 2732 on the live hub,
7692
+ * 2026-09-01);
7693
+ * - the profile-slot assignment entry, PURGED (not unassigned — unassign
7694
+ * marks the slot manual, which would pin the stale choice instead of
7695
+ * letting `computeInitialAssignment` re-derive it);
7696
+ * - the probe snapshots (`<deviceId>/…` — probed codec/resolution of the
7697
+ * old hardware);
7698
+ * - the persisted RTSP token rows for the device's brokers (keyed
7699
+ * `<deviceId>/<camStreamId>`; the stream ids change with the hardware,
7700
+ * so the rows are dead URLs).
7701
+ *
7702
+ * An RPC, deliberately — an event is telemetry and may be dropped (D8),
7703
+ * and a dropped forget leaves a feeder respawning against a stream that
7704
+ * does not exist.
7705
+ */
7706
+ forgetDeviceHardware: require_sleep.method(zod.z.object({ deviceId: zod.z.number().int().nonnegative() }), zod.z.object({
7707
+ derivedStreamsDeleted: zod.z.array(zod.z.string()).readonly(),
7708
+ assignmentsPurged: zod.z.boolean(),
7709
+ probeSnapshotsDropped: zod.z.number().int().nonnegative(),
7710
+ rtspTokenRowsDeleted: zod.z.number().int().nonnegative()
7711
+ }), {
7712
+ kind: "mutation",
7713
+ auth: "admin"
7714
+ }),
7715
+ /**
7573
7716
  * Render a short GIF or MP4 from the broker's PRE-BUFFER around an instant.
7574
7717
  *
7575
7718
  * The pre-buffer is the only source that already holds the seconds BEFORE
@@ -9974,6 +10117,35 @@ var deviceProviderCapability = {
9974
10117
  name: zod.z.string(),
9975
10118
  type: zod.z.string()
9976
10119
  }))),
10120
+ /**
10121
+ * Tear down and reconstruct ONE device in place from its persisted rows —
10122
+ * touching no other device this provider owns.
10123
+ *
10124
+ * The primitive `deviceManager.migrateDevice` uses to flush the two
10125
+ * migrated numbers: after `swapIds` the runner's live instance still
10126
+ * carries the PRE-swap numeric id (baked into the object, its native-cap
10127
+ * registrations and its log tags), and a live object cannot be renumbered.
10128
+ * Before this method the only flush was restarting the whole owning addon
10129
+ * — which took every camera the provider owns down with it (28 devices
10130
+ * for one migrated camera, measured 2026-09-04, and the morning of the
10131
+ * same day ~27 devices' native caps did not come back on their own).
10132
+ *
10133
+ * Keyed by `stableId`, deliberately: the numeric id is exactly the thing
10134
+ * that changes. The reply carries the id the device answers on NOW.
10135
+ * Implemented once in `BaseDeviceProvider` — decommission the live
10136
+ * instance (if any), then re-create from the persisted row: the same
10137
+ * teardown/rehydrate pair every graceful shutdown + boot already uses.
10138
+ * An RPC, never an event: a dropped event would leave the runner writing
10139
+ * against the wrong camera (D8).
10140
+ *
10141
+ * Construction can dial hardware, and the migrated source is
10142
+ * characteristically dead — the timeout covers a full activate window
10143
+ * rather than the 60 s default.
10144
+ */
10145
+ reloadDevice: require_sleep.method(zod.z.object({ stableId: zod.z.string() }), zod.z.object({ deviceId: zod.z.number() }), {
10146
+ kind: "mutation",
10147
+ timeoutMs: 3 * 6e4
10148
+ }),
9977
10149
  supportsDiscovery: require_sleep.method(zod.z.object({}), zod.z.boolean()),
9978
10150
  /**
9979
10151
  * Run a network scan. `params` carries optional provider-specific scan
@@ -10368,13 +10540,21 @@ var deviceManagerCapability = {
10368
10540
  * `sourceStillLive` names what stayed live; empty is the only value that
10369
10541
  * means the old hardware is quiet. The migration proceeds either way —
10370
10542
  * refusing would refuse the case this exists for.
10543
+ *
10544
+ * **Safe to retry.** A duplicate call while a migration involving either
10545
+ * device is in flight is REFUSED, never queued; a repeat of a swap that
10546
+ * already completed (matched against the `addonId`/`stableId` fingerprint
10547
+ * the swap left on the rows, within 15 min) is a no-op returning the
10548
+ * original report. A blind re-run can no longer silently undo the
10549
+ * migration it retried.
10371
10550
  */
10372
10551
  migrateDevice: require_sleep.method(zod.z.object({
10373
10552
  sourceId: zod.z.number(),
10374
10553
  targetId: zod.z.number()
10375
10554
  }), MigrateDeviceResultSchema, {
10376
10555
  kind: "mutation",
10377
- auth: "admin"
10556
+ auth: "admin",
10557
+ timeoutMs: 12 * 6e4
10378
10558
  }),
10379
10559
  /** Register a device in the DB + in-memory registry. Called by DeviceManagerApi.register(). */
10380
10560
  registerDevice: require_sleep.method(DeviceRegisterPayloadSchema, zod.z.void(), { kind: "mutation" }),
@@ -36248,6 +36428,152 @@ var BaseDevice = class {
36248
36428
  }
36249
36429
  };
36250
36430
  //#endregion
36431
+ //#region src/device/device-restore-retry.ts
36432
+ /**
36433
+ * Delays before retry rounds 1..N — the round count IS the bound.
36434
+ * 10 s catches "the hub was busy for a moment"; the full schedule
36435
+ * (10 + 30 + 90 s of waiting, plus up to one 60 s transport timeout
36436
+ * per attempt) covers a device-manager lock held for minutes — the
36437
+ * 2026-09-04 outage's migration hold was ~3.5 min.
36438
+ */
36439
+ var DEVICE_RESTORE_RETRY_DELAYS_MS = [
36440
+ 1e4,
36441
+ 3e4,
36442
+ 9e4
36443
+ ];
36444
+ /** Lane width for retry rounds. See module docblock — retries are
36445
+ * evidence of congestion, so they never re-stampede full-width. */
36446
+ var DEVICE_RESTORE_RETRY_CONCURRENCY = 4;
36447
+ /** Abortable sleep — resolves early (never rejects) on abort. */
36448
+ function sleep$1(ms, signal) {
36449
+ return new Promise((resolve) => {
36450
+ if (signal.aborted) {
36451
+ resolve();
36452
+ return;
36453
+ }
36454
+ const onAbort = () => {
36455
+ clearTimeout(timer);
36456
+ resolve();
36457
+ };
36458
+ const timer = setTimeout(() => {
36459
+ signal.removeEventListener("abort", onAbort);
36460
+ resolve();
36461
+ }, ms);
36462
+ timer.unref?.();
36463
+ signal.addEventListener("abort", onAbort, { once: true });
36464
+ });
36465
+ }
36466
+ /** Drain `items` through at most `width` concurrent lanes. `fn` must
36467
+ * not reject (callers wrap their own try/catch). */
36468
+ async function runWithConcurrency(items, width, fn) {
36469
+ const queue = [...items];
36470
+ const laneCount = Math.max(1, Math.min(width, queue.length));
36471
+ const lane = async () => {
36472
+ for (;;) {
36473
+ const item = queue.shift();
36474
+ if (item === void 0) return;
36475
+ await fn(item);
36476
+ }
36477
+ };
36478
+ await Promise.all(Array.from({ length: laneCount }, lane));
36479
+ }
36480
+ var DeviceRestoreRetryScheduler = class {
36481
+ #logger;
36482
+ #attempt;
36483
+ #onPermanentFailure;
36484
+ #delaysMs;
36485
+ #concurrency;
36486
+ #now;
36487
+ #abort = new AbortController();
36488
+ constructor(options) {
36489
+ this.#logger = options.logger;
36490
+ this.#attempt = options.attempt;
36491
+ this.#onPermanentFailure = options.onPermanentFailure;
36492
+ this.#delaysMs = options.delaysMs ?? DEVICE_RESTORE_RETRY_DELAYS_MS;
36493
+ this.#concurrency = options.concurrency ?? 4;
36494
+ this.#now = options.now ?? Date.now;
36495
+ }
36496
+ /** Stop retrying (shutdown). Pending entries are NOT marked
36497
+ * permanently failed — the next boot restores them from disk. */
36498
+ cancel() {
36499
+ this.#abort.abort();
36500
+ }
36501
+ /**
36502
+ * Run the bounded retry rounds. Resolves when every entry has either
36503
+ * restored, been marked permanently failed, or the scheduler was
36504
+ * cancelled. Never rejects.
36505
+ */
36506
+ async run(initialFailures) {
36507
+ let pending = initialFailures.map((failure) => ({
36508
+ saved: failure.saved,
36509
+ lastError: failure.error,
36510
+ attempts: 1
36511
+ }));
36512
+ for (let round = 0; round < this.#delaysMs.length; round += 1) {
36513
+ if (pending.length === 0 || this.#abort.signal.aborted) break;
36514
+ await sleep$1(this.#delaysMs[round] ?? 0, this.#abort.signal);
36515
+ if (this.#abort.signal.aborted) break;
36516
+ pending = await this.#runRound(pending, round);
36517
+ }
36518
+ if (this.#abort.signal.aborted) return [];
36519
+ const terminal = pending.map((entry) => ({
36520
+ deviceId: entry.saved.id,
36521
+ stableId: entry.saved.stableId,
36522
+ type: String(entry.saved.type),
36523
+ attempts: entry.attempts,
36524
+ lastError: entry.lastError,
36525
+ failedAt: this.#now()
36526
+ }));
36527
+ for (const failure of terminal) this.#onPermanentFailure(failure);
36528
+ return terminal;
36529
+ }
36530
+ /** One retry round: parents first (phase 0), then hub-adopted
36531
+ * children (phase 1) — a child's attempt depends on its parent
36532
+ * having landed, exactly like the initial two-pass restore. */
36533
+ async #runRound(pending, round) {
36534
+ const next = [];
36535
+ const parents = pending.filter((entry) => entry.saved.parentDeviceId === null);
36536
+ const children = pending.filter((entry) => entry.saved.parentDeviceId !== null);
36537
+ for (const phase of [parents, children]) await runWithConcurrency(phase, this.#concurrency, async (entry) => {
36538
+ if (this.#abort.signal.aborted) {
36539
+ next.push(entry);
36540
+ return;
36541
+ }
36542
+ const attemptNo = entry.attempts + 1;
36543
+ try {
36544
+ await this.#attempt(entry.saved);
36545
+ this.#logger.info("Device restored on retry", {
36546
+ tags: {
36547
+ deviceId: entry.saved.id,
36548
+ stableId: entry.saved.stableId
36549
+ },
36550
+ meta: { attempt: attemptNo }
36551
+ });
36552
+ } catch (err) {
36553
+ const lastError = err instanceof Error ? err.message : String(err);
36554
+ const remainingRetries = this.#delaysMs.length - (round + 1);
36555
+ this.#logger.warn("Device restore retry failed", {
36556
+ tags: {
36557
+ deviceId: entry.saved.id,
36558
+ stableId: entry.saved.stableId
36559
+ },
36560
+ meta: {
36561
+ attempt: attemptNo,
36562
+ remainingRetries,
36563
+ error: lastError
36564
+ }
36565
+ });
36566
+ next.push({
36567
+ saved: entry.saved,
36568
+ lastError,
36569
+ attempts: attemptNo
36570
+ });
36571
+ }
36572
+ });
36573
+ return next;
36574
+ }
36575
+ };
36576
+ //#endregion
36251
36577
  //#region src/device/base-device-provider.ts
36252
36578
  /**
36253
36579
  * Convert an IDevice to the flat DeviceSummary shape expected by the
@@ -36298,6 +36624,7 @@ var BaseDeviceProvider = class extends require_sleep.BaseAddon {
36298
36624
  }];
36299
36625
  }
36300
36626
  async onShutdown() {
36627
+ this.cancelRestoreRetries();
36301
36628
  const devices = await this.ctx.kernel.devices?.getAll() ?? [];
36302
36629
  for (const device of devices) try {
36303
36630
  await this.ctx.kernel.devices?.decommission(device.id);
@@ -36315,9 +36642,16 @@ var BaseDeviceProvider = class extends require_sleep.BaseAddon {
36315
36642
  async start() {}
36316
36643
  async stop() {}
36317
36644
  async getStatus() {
36645
+ const all = await this.ctx.kernel.devices?.getAll() ?? [];
36646
+ const summary = this.restoreFailureSummary();
36647
+ if (summary === null) return {
36648
+ connected: true,
36649
+ deviceCount: all.length
36650
+ };
36318
36651
  return {
36319
36652
  connected: true,
36320
- deviceCount: (await this.ctx.kernel.devices?.getAll() ?? []).length
36653
+ deviceCount: all.length,
36654
+ error: summary
36321
36655
  };
36322
36656
  }
36323
36657
  async getDevices() {
@@ -36407,8 +36741,137 @@ var BaseDeviceProvider = class extends require_sleep.BaseAddon {
36407
36741
  };
36408
36742
  }
36409
36743
  async restoreDevices(savedDevices) {
36410
- await this.onRestoreDevices(savedDevices);
36411
- if (savedDevices.length > 0) this.ctx.logger.info(`Restored ${savedDevices.length} ${this.providerName} device(s)`);
36744
+ const report = await this.onRestoreDevices(savedDevices);
36745
+ if (savedDevices.length === 0) return;
36746
+ if (report && report.failedCount > 0) {
36747
+ this.ctx.logger.warn(`Restored ${report.restoredCount}/${savedDevices.length} ${this.providerName} device(s) — ${report.failedCount} failed, bounded retry scheduled`);
36748
+ return;
36749
+ }
36750
+ const restoredCount = report ? report.restoredCount : savedDevices.length;
36751
+ this.ctx.logger.info(`Restored ${restoredCount} ${this.providerName} device(s)`);
36752
+ }
36753
+ /** Retry schedule. Overridable (tests use millisecond delays). */
36754
+ restoreRetryDelaysMs = DEVICE_RESTORE_RETRY_DELAYS_MS;
36755
+ /** Retry lane width. See `device-restore-retry.ts` for why retries
36756
+ * never re-stampede full-width while the initial pass does (D167). */
36757
+ restoreRetryConcurrency = 4;
36758
+ _restoreRetryScheduler = null;
36759
+ _restoreRetryCompletion = null;
36760
+ _permanentRestoreFailures = /* @__PURE__ */ new Map();
36761
+ /** Settles when the background retry rounds finish (or `null` when
36762
+ * nothing failed). Exposed for tests and subclass diagnostics —
36763
+ * boot NEVER awaits this: the runner's post-init handshake goes out
36764
+ * with the devices that restored, and a late success is announced
36765
+ * through the `native-cap-change` → `updateCaps` path. */
36766
+ get restoreRetryCompletion() {
36767
+ return this._restoreRetryCompletion;
36768
+ }
36769
+ /** Devices that exhausted the retry bound this process lifetime. */
36770
+ get permanentRestoreFailures() {
36771
+ return [...this._permanentRestoreFailures.values()];
36772
+ }
36773
+ /** One-line operator-facing summary for `getStatus().error`, or
36774
+ * `null` when every device restored. */
36775
+ restoreFailureSummary() {
36776
+ if (this._permanentRestoreFailures.size === 0) return null;
36777
+ const ids = [...this._permanentRestoreFailures.keys()].join(", ");
36778
+ return `${this._permanentRestoreFailures.size} device(s) permanently failed restore (deviceIds: ${ids}) — restart the ${this.providerName} provider to retry`;
36779
+ }
36780
+ cancelRestoreRetries() {
36781
+ this._restoreRetryScheduler?.cancel();
36782
+ this._restoreRetryScheduler = null;
36783
+ }
36784
+ recordPermanentRestoreFailure(failure) {
36785
+ this._permanentRestoreFailures.set(failure.deviceId, failure);
36786
+ this.ctx.logger.error("Device restore permanently failed — its capabilities will not register until the provider restarts", {
36787
+ tags: {
36788
+ deviceId: failure.deviceId,
36789
+ stableId: failure.stableId
36790
+ },
36791
+ meta: {
36792
+ type: failure.type,
36793
+ attempts: failure.attempts,
36794
+ error: failure.lastError
36795
+ }
36796
+ });
36797
+ }
36798
+ scheduleRestoreRetries(failures, attempt) {
36799
+ const scheduler = new DeviceRestoreRetryScheduler({
36800
+ logger: this.ctx.logger,
36801
+ delaysMs: this.restoreRetryDelaysMs,
36802
+ concurrency: this.restoreRetryConcurrency,
36803
+ attempt,
36804
+ onPermanentFailure: (failure) => this.recordPermanentRestoreFailure(failure)
36805
+ });
36806
+ this._restoreRetryScheduler = scheduler;
36807
+ this._restoreRetryCompletion = scheduler.run(failures).then(() => void 0).catch((err) => {
36808
+ this.ctx.logger.error("Restore retry scheduler crashed", { meta: { error: err instanceof Error ? err.message : String(err) } });
36809
+ });
36810
+ }
36811
+ /**
36812
+ * Tear down and reconstruct ONE device from its persisted rows — the
36813
+ * `deviceProvider.reloadDevice` cap method. Persistence is never touched,
36814
+ * and no other device this provider owns is disturbed.
36815
+ *
36816
+ * Keyed by `stableId` because the caller's whole reason to be here is that
36817
+ * the NUMERIC id changed (`deviceManager.migrateDevice` swapped it): the
36818
+ * fresh instance resolves its id through `allocateDeviceId`, which returns
36819
+ * whatever number the row carries NOW. The teardown is `decommission` —
36820
+ * exactly what a graceful shutdown runs per device (fires `removeDevice()`,
36821
+ * unregisters native caps, drops the registry entry) — and the rebuild is
36822
+ * the boot restore's own `create()` path, including its pass 2: first-class
36823
+ * children (hub-adopted cameras under an NVR) are decommissioned with the
36824
+ * parent by the cascade and must be re-created explicitly, because only
36825
+ * accessory children come back through `getAccessoryChildren()`.
36826
+ *
36827
+ * Reloading an accessory child directly is refused (no device class) —
36828
+ * reload its parent instead.
36829
+ */
36830
+ async reloadDevice(input) {
36831
+ const { stableId } = input;
36832
+ const devices = this.ctx.kernel.devices;
36833
+ if (!devices) throw new Error(`${this.providerName}: kernel.devices unavailable — cannot reload`);
36834
+ const live = (await devices.getAll()).find((d) => d.stableId === stableId);
36835
+ if (live) await devices.decommission(live.id);
36836
+ const { id } = await this.ctx.api.deviceManager.allocateDeviceId.mutate({
36837
+ addonId: this.addonId,
36838
+ stableId
36839
+ });
36840
+ const meta = await this.ctx.api.deviceManager.loadMeta.query({ deviceId: id });
36841
+ if (meta === null) throw new Error(`${this.providerName}: no persisted meta for "${stableId}" (id ${id}) — cannot reload`);
36842
+ const deviceType = Object.values(require_sleep.DeviceType).find((t) => t === meta.type);
36843
+ const Class = deviceType !== void 0 ? this.deviceClasses[deviceType] : void 0;
36844
+ if (!Class) throw new Error(`${this.providerName}: no device class for type "${meta.type}" — "${stableId}" is an accessory child; reload its parent instead`);
36845
+ await devices.create(stableId, Class, {}, meta.parentDeviceId ?? null);
36846
+ const rows = await this.ctx.api.deviceManager.listPersistedByAddon.query({ addonId: this.addonId });
36847
+ for (const row of rows) {
36848
+ if (row.parentDeviceId !== id) continue;
36849
+ const childType = Object.values(require_sleep.DeviceType).find((t) => t === row.type);
36850
+ const ChildClass = childType !== void 0 ? this.deviceClasses[childType] : void 0;
36851
+ if (!ChildClass) continue;
36852
+ try {
36853
+ await devices.create(row.stableId, ChildClass, {}, id);
36854
+ } catch (err) {
36855
+ this.ctx.logger.warn("reloadDevice: failed to re-create first-class child", {
36856
+ tags: {
36857
+ deviceId: row.id,
36858
+ stableId: row.stableId
36859
+ },
36860
+ meta: {
36861
+ parentDeviceId: id,
36862
+ error: err instanceof Error ? err.message : String(err)
36863
+ }
36864
+ });
36865
+ }
36866
+ }
36867
+ this.ctx.logger.info("device reloaded in place from persisted rows", {
36868
+ tags: { deviceId: id },
36869
+ meta: {
36870
+ stableId,
36871
+ type: meta.type
36872
+ }
36873
+ });
36874
+ return { deviceId: id };
36412
36875
  }
36413
36876
  /**
36414
36877
  * Restore devices from persisted state. Two-pass:
@@ -36434,55 +36897,108 @@ var BaseDeviceProvider = class extends require_sleep.BaseAddon {
36434
36897
  * accessory-spawn flow handles via the parent's
36435
36898
  * `getAccessoryChildren()`. Override only when the default doesn't
36436
36899
  * fit.
36900
+ *
36901
+ * A row that fails either pass is NOT terminal (D347): it is handed
36902
+ * to a bounded background retry (`DeviceRestoreRetryScheduler`).
36903
+ * Only after the bound is exhausted is the device marked permanently
36904
+ * failed — logged at ERROR with `tags.deviceId` and surfaced via
36905
+ * `getStatus().error`.
36437
36906
  */
36438
36907
  async onRestoreDevices(savedDevices) {
36439
36908
  const restored = /* @__PURE__ */ new Set();
36909
+ const failures = [];
36910
+ const attemptRestore = async (saved) => {
36911
+ if (restored.has(saved.id)) return;
36912
+ const Class = this.deviceClasses[saved.type];
36913
+ if (!Class) throw new Error(`no device class registered for type "${saved.type}"`);
36914
+ if (saved.parentDeviceId !== null && !restored.has(saved.parentDeviceId)) throw new Error(`parent device ${saved.parentDeviceId} not restored`);
36915
+ await this.ctx.kernel.devices.create(saved.stableId, Class, {}, saved.parentDeviceId);
36916
+ restored.add(saved.id);
36917
+ };
36440
36918
  const topLevel = savedDevices.filter((saved) => saved.parentDeviceId === null);
36441
36919
  const restoreOne = async (saved) => {
36442
- const Class = this.deviceClasses[saved.type];
36443
- if (!Class) {
36920
+ if (!this.deviceClasses[saved.type]) {
36444
36921
  this.ctx.logger.warn("No device class registered for restored type — skipping", {
36445
- tags: { stableId: saved.stableId },
36922
+ tags: {
36923
+ deviceId: saved.id,
36924
+ stableId: saved.stableId
36925
+ },
36446
36926
  meta: { type: saved.type }
36447
36927
  });
36448
36928
  return;
36449
36929
  }
36450
36930
  try {
36451
- await this.ctx.kernel.devices.create(saved.stableId, Class, {});
36452
- restored.add(saved.id);
36931
+ await attemptRestore(saved);
36453
36932
  } catch (err) {
36454
- this.ctx.logger.warn("Failed to restore device", {
36455
- tags: { stableId: saved.stableId },
36933
+ const error = err instanceof Error ? err.message : String(err);
36934
+ this.ctx.logger.warn("Failed to restore device — bounded retry scheduled", {
36935
+ tags: {
36936
+ deviceId: saved.id,
36937
+ stableId: saved.stableId
36938
+ },
36456
36939
  meta: {
36457
36940
  type: saved.type,
36458
- error: err instanceof Error ? err.message : String(err)
36941
+ attempt: 1,
36942
+ error
36459
36943
  }
36460
36944
  });
36945
+ failures.push({
36946
+ saved,
36947
+ error
36948
+ });
36461
36949
  }
36462
36950
  };
36463
36951
  await Promise.all(topLevel.map((saved) => restoreOne(saved)));
36952
+ const failedTopLevelIds = new Set(failures.map((failure) => failure.saved.id));
36464
36953
  const childRows = savedDevices.filter((s) => s.parentDeviceId !== null);
36465
36954
  for (const saved of childRows) {
36466
- const Class = this.deviceClasses[saved.type];
36467
- if (!Class) continue;
36955
+ if (!this.deviceClasses[saved.type]) continue;
36468
36956
  if (saved.parentDeviceId === null) continue;
36469
- if (!restored.has(saved.parentDeviceId)) continue;
36470
- try {
36471
- await this.ctx.kernel.devices.create(saved.stableId, Class, {}, saved.parentDeviceId);
36472
- restored.add(saved.id);
36473
- } catch (err) {
36474
- this.ctx.logger.warn("Failed to restore hub-adopted child", {
36957
+ if (restored.has(saved.parentDeviceId)) {
36958
+ try {
36959
+ await attemptRestore(saved);
36960
+ } catch (err) {
36961
+ const error = err instanceof Error ? err.message : String(err);
36962
+ this.ctx.logger.warn("Failed to restore hub-adopted child — bounded retry scheduled", {
36963
+ tags: {
36964
+ deviceId: saved.id,
36965
+ stableId: saved.stableId,
36966
+ parentDeviceId: saved.parentDeviceId
36967
+ },
36968
+ meta: {
36969
+ type: saved.type,
36970
+ attempt: 1,
36971
+ error
36972
+ }
36973
+ });
36974
+ failures.push({
36975
+ saved,
36976
+ error
36977
+ });
36978
+ }
36979
+ continue;
36980
+ }
36981
+ if (failedTopLevelIds.has(saved.parentDeviceId)) {
36982
+ this.ctx.logger.warn("Hub-adopted child deferred — parent failed initial restore", {
36475
36983
  tags: {
36984
+ deviceId: saved.id,
36476
36985
  stableId: saved.stableId,
36477
36986
  parentDeviceId: saved.parentDeviceId
36478
36987
  },
36479
- meta: {
36480
- type: saved.type,
36481
- error: err instanceof Error ? err.message : String(err)
36482
- }
36988
+ meta: { type: saved.type }
36989
+ });
36990
+ failures.push({
36991
+ saved,
36992
+ error: `parent device ${saved.parentDeviceId} not restored`
36483
36993
  });
36994
+ continue;
36484
36995
  }
36485
36996
  }
36997
+ if (failures.length > 0) this.scheduleRestoreRetries(failures, attemptRestore);
36998
+ return {
36999
+ restoredCount: restored.size,
37000
+ failedCount: failures.length
37001
+ };
36486
37002
  }
36487
37003
  /** Convert an IDevice to the flat DeviceSummary for the cap router. */
36488
37004
  toSummary(device) {
@@ -39636,6 +40152,12 @@ var METHOD_ACCESS_MAP = Object.freeze({
39636
40152
  addonId: null,
39637
40153
  access: "create"
39638
40154
  },
40155
+ "backup.cancel": {
40156
+ capName: "backup",
40157
+ capScope: "system",
40158
+ addonId: null,
40159
+ access: "create"
40160
+ },
39639
40161
  "backup.delete": {
39640
40162
  capName: "backup",
39641
40163
  capScope: "system",
@@ -39678,6 +40200,12 @@ var METHOD_ACCESS_MAP = Object.freeze({
39678
40200
  addonId: null,
39679
40201
  access: "view"
39680
40202
  },
40203
+ "backup.listRuns": {
40204
+ capName: "backup",
40205
+ capScope: "system",
40206
+ addonId: null,
40207
+ access: "view"
40208
+ },
39681
40209
  "backup.listSchedules": {
39682
40210
  capName: "backup",
39683
40211
  capScope: "system",
@@ -40878,6 +41406,12 @@ var METHOD_ACCESS_MAP = Object.freeze({
40878
41406
  addonId: null,
40879
41407
  access: "view"
40880
41408
  },
41409
+ "deviceProvider.reloadDevice": {
41410
+ capName: "device-provider",
41411
+ capScope: "system",
41412
+ addonId: null,
41413
+ access: "create"
41414
+ },
40881
41415
  "deviceProvider.start": {
40882
41416
  capName: "device-provider",
40883
41417
  capScope: "system",
@@ -44244,6 +44778,12 @@ var METHOD_ACCESS_MAP = Object.freeze({
44244
44778
  addonId: null,
44245
44779
  access: "create"
44246
44780
  },
44781
+ "streamBroker.forgetDeviceHardware": {
44782
+ capName: "stream-broker",
44783
+ capScope: "system",
44784
+ addonId: null,
44785
+ access: "delete"
44786
+ },
44247
44787
  "streamBroker.getAllRtspEntries": {
44248
44788
  capName: "stream-broker",
44249
44789
  capScope: "system",
@@ -46965,6 +47505,11 @@ var METHOD_DEVICE_SELECTORS = Object.freeze({
46965
47505
  form: "single",
46966
47506
  optional: false
46967
47507
  }],
47508
+ "streamBroker.forgetDeviceHardware": [{
47509
+ name: "deviceId",
47510
+ form: "single",
47511
+ optional: false
47512
+ }],
46968
47513
  "streamBroker.getDeviceAudioMute": [{
46969
47514
  name: "deviceId",
46970
47515
  form: "single",
@@ -47338,6 +47883,7 @@ var SYSTEM_SCOPE_DEVICE_METHODS = [
47338
47883
  "recordingExport.listExports",
47339
47884
  "streamBroker.acquireEgressTranscode",
47340
47885
  "streamBroker.assignProfile",
47886
+ "streamBroker.forgetDeviceHardware",
47341
47887
  "streamBroker.getDeviceAudioMute",
47342
47888
  "streamBroker.getStreamWithCodec",
47343
47889
  "streamBroker.produceEventMedia",
@@ -47881,6 +48427,8 @@ function createSystemProxy(api) {
47881
48427
  backup: {
47882
48428
  listDestinations: (input) => dispatch("backup", "listDestinations", "query", input),
47883
48429
  trigger: (input) => dispatch("backup", "trigger", "mutation", input),
48430
+ listRuns: (input) => dispatch("backup", "listRuns", "query", input),
48431
+ cancel: (input) => dispatch("backup", "cancel", "mutation", input),
47884
48432
  list: (input) => dispatch("backup", "list", "query", input),
47885
48433
  listLocations: (input) => dispatch("backup", "listLocations", "query", input),
47886
48434
  getEntries: (input) => dispatch("backup", "getEntries", "query", input),
@@ -52450,6 +52998,10 @@ exports.BOOT_RECOVERY_BACKOFF_MS = require_sleep.BOOT_RECOVERY_BACKOFF_MS;
52450
52998
  exports.BacklightModeSchema = BacklightModeSchema;
52451
52999
  exports.BackupDestinationInfoSchema = BackupDestinationInfoSchema;
52452
53000
  exports.BackupEntrySchema = BackupEntrySchema;
53001
+ exports.BackupRunPhaseSchema = BackupRunPhaseSchema;
53002
+ exports.BackupRunSchema = BackupRunSchema;
53003
+ exports.BackupRunStateSchema = BackupRunStateSchema;
53004
+ exports.BackupTriggerResultSchema = BackupTriggerResultSchema;
52453
53005
  exports.BaseAddon = require_sleep.BaseAddon;
52454
53006
  exports.BaseDevice = BaseDevice;
52455
53007
  exports.BaseDeviceProvider = BaseDeviceProvider;
@@ -52606,6 +53158,8 @@ exports.DEVICE_BACKEND_TO_FORMAT = DEVICE_BACKEND_TO_FORMAT;
52606
53158
  exports.DEVICE_CAP_NAMES = DEVICE_CAP_NAMES;
52607
53159
  exports.DEVICE_CHILDREN_BATCH_MAX = DEVICE_CHILDREN_BATCH_MAX;
52608
53160
  exports.DEVICE_PROFILES = DEVICE_PROFILES;
53161
+ exports.DEVICE_RESTORE_RETRY_CONCURRENCY = DEVICE_RESTORE_RETRY_CONCURRENCY;
53162
+ exports.DEVICE_RESTORE_RETRY_DELAYS_MS = DEVICE_RESTORE_RETRY_DELAYS_MS;
52609
53163
  exports.DEVICE_SCOPED_CAPS = require_sleep.DEVICE_SCOPED_CAPS;
52610
53164
  exports.DEVICE_SETTINGS_CONTRIBUTION_METHODS = require_sleep.DEVICE_SETTINGS_CONTRIBUTION_METHODS;
52611
53165
  exports.DEVICE_STATE_READERS = DEVICE_STATE_READERS;
@@ -52635,6 +53189,7 @@ exports.DeviceExportUnexposeInputSchema = UnexposeInputSchema;
52635
53189
  exports.DeviceFeature = require_sleep.DeviceFeature;
52636
53190
  exports.DeviceInfoSchema = DeviceInfoSchema;
52637
53191
  exports.DeviceNetworkStatsSchema = DeviceNetworkStatsSchema;
53192
+ exports.DeviceRestoreRetryScheduler = DeviceRestoreRetryScheduler;
52638
53193
  exports.DeviceRole = require_sleep.DeviceRole;
52639
53194
  exports.DeviceRuntimeState = DeviceRuntimeState;
52640
53195
  exports.DeviceSelectorSchema = DeviceSelectorSchema;