@camstack/addon-provider-dreame 0.2.58 → 0.2.60

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.
Files changed (3) hide show
  1. package/dist/addon.js +509 -25
  2. package/dist/addon.mjs +509 -25
  3. package/package.json +1 -1
package/dist/addon.js CHANGED
@@ -61032,6 +61032,89 @@ var LocationStatSchema = object({
61032
61032
  fileCount: number(),
61033
61033
  present: boolean()
61034
61034
  });
61035
+ /** Lifecycle of a backup run. Terminal states: succeeded / failed / cancelled. */
61036
+ var BackupRunStateSchema = _enum([
61037
+ "queued",
61038
+ "running",
61039
+ "succeeded",
61040
+ "failed",
61041
+ "cancelled"
61042
+ ]);
61043
+ /**
61044
+ * Where a running backup currently is. `queued` before it starts,
61045
+ * `building` while the tar.gz is being staged, `uploading` during the
61046
+ * per-destination fan-out, `done` once terminal.
61047
+ */
61048
+ var BackupRunPhaseSchema = _enum([
61049
+ "queued",
61050
+ "building",
61051
+ "uploading",
61052
+ "done"
61053
+ ]);
61054
+ /**
61055
+ * Observable state of one backup run — readable WHILE it runs via
61056
+ * `backup.listRuns`. This is what makes the execution queue and
61057
+ * `backup.cancel` usable: the 2026-09-04 incident (two concurrent
61058
+ * multi-GB builds, staging 5.1 GB → 18 GB, load 62) was only
61059
+ * diagnosable with `du` because nothing reported that runs existed or
61060
+ * how large the staged archive had grown.
61061
+ */
61062
+ var BackupRunSchema = object({
61063
+ /** Stable run id — the handle `backup.cancel` takes. */
61064
+ id: string(),
61065
+ state: BackupRunStateSchema,
61066
+ phase: BackupRunPhaseSchema,
61067
+ /**
61068
+ * Resolved destination location ids. Empty while queued (targets are
61069
+ * resolved when the run starts, against the then-current policies).
61070
+ */
61071
+ destinationIds: array(string()).readonly(),
61072
+ label: string().optional(),
61073
+ /** ms-epoch when the run was submitted (trigger call / schedule fire). */
61074
+ requestedAt: number(),
61075
+ /** ms-epoch when the run left the queue and started building. */
61076
+ startedAt: number().optional(),
61077
+ /** ms-epoch when the run reached a terminal state. */
61078
+ finishedAt: number().optional(),
61079
+ /** Compressed bytes of the staging archive written so far. */
61080
+ stagedBytes: number(),
61081
+ /** Final staged archive size, once the build phase completes. */
61082
+ archiveSizeBytes: number().optional(),
61083
+ /** Bytes pushed to the destination currently uploading. */
61084
+ uploadedBytes: number(),
61085
+ /** Destinations where the archive fully landed (uploaded + indexed). */
61086
+ completedDestinationIds: array(string()).readonly(),
61087
+ /** Destinations that failed during the fan-out. */
61088
+ failedDestinationIds: array(string()).readonly(),
61089
+ /** Failure message when `state === 'failed'`. */
61090
+ error: string().optional(),
61091
+ /**
61092
+ * 1-based place in the execution queue — 1 = runs next. Present only
61093
+ * while `state === 'queued'`. Stamped by the orchestrator from the
61094
+ * queue's OWN pending order, never derived from timestamps, so the
61095
+ * UI cannot show an order the executor will not honour.
61096
+ */
61097
+ queuePosition: number().int().min(1).optional()
61098
+ });
61099
+ /**
61100
+ * Result of `backup.trigger`. The call still resolves when the run
61101
+ * terminates (compat with schedule-driven runs and the admin UI), but
61102
+ * it now names the run and says whether it had to WAIT: a trigger that
61103
+ * arrives while another run is in flight is enqueued (or joined onto
61104
+ * an identical already-queued run), never started concurrently.
61105
+ */
61106
+ var BackupTriggerResultSchema = object({
61107
+ /** The run this trigger mapped to — poll it via `listRuns`, stop it via `cancel`. */
61108
+ runId: string(),
61109
+ /** True when the run waited behind an in-flight run instead of starting immediately. */
61110
+ queued: boolean(),
61111
+ /** True when this trigger was coalesced onto an identical already-queued run. */
61112
+ joined: boolean(),
61113
+ /** True when the run was cancelled before completing every destination. */
61114
+ cancelled: boolean(),
61115
+ /** One entry per destination the archive landed at (partial on cancel). */
61116
+ entries: array(BackupEntrySchema).readonly()
61117
+ });
61035
61118
  /**
61036
61119
  * A backup schedule — the N:M "entry" that binds one cron cadence to a
61037
61120
  * SET of destination locations. Supersedes the per-location cron on
@@ -61079,7 +61162,10 @@ method(_void(), array(BackupDestinationInfoSchema).readonly(), { auth: "admin" }
61079
61162
  * retention (manual runs).
61080
61163
  */
61081
61164
  retentionCount: number().int().min(1).max(1e3).optional()
61082
- }).optional(), array(BackupEntrySchema).readonly(), {
61165
+ }).optional(), BackupTriggerResultSchema, {
61166
+ kind: "mutation",
61167
+ auth: "admin"
61168
+ }), method(_void(), array(BackupRunSchema).readonly(), { auth: "admin" }), method(object({ runId: string() }), object({ cancelled: boolean() }), {
61083
61169
  kind: "mutation",
61084
61170
  auth: "admin"
61085
61171
  }), method(_void(), array(BackupEntrySchema).readonly(), { auth: "admin" }), method(_void(), array(LocationStatSchema).readonly(), { auth: "admin" }), method(object({
@@ -61796,6 +61882,14 @@ method(object({
61796
61882
  }), object({ success: literal(true) }), {
61797
61883
  kind: "mutation",
61798
61884
  auth: "admin"
61885
+ }), method(object({ deviceId: number().int().nonnegative() }), object({
61886
+ derivedStreamsDeleted: array(string()).readonly(),
61887
+ assignmentsPurged: boolean(),
61888
+ probeSnapshotsDropped: number().int().nonnegative(),
61889
+ rtspTokenRowsDeleted: number().int().nonnegative()
61890
+ }), {
61891
+ kind: "mutation",
61892
+ auth: "admin"
61799
61893
  }), method(object({
61800
61894
  deviceId: number(),
61801
61895
  /** Absent = the LOWEST assigned profile — a notification attachment is
@@ -63240,6 +63334,35 @@ var deviceProviderCapability = {
63240
63334
  name: string(),
63241
63335
  type: string()
63242
63336
  }))),
63337
+ /**
63338
+ * Tear down and reconstruct ONE device in place from its persisted rows —
63339
+ * touching no other device this provider owns.
63340
+ *
63341
+ * The primitive `deviceManager.migrateDevice` uses to flush the two
63342
+ * migrated numbers: after `swapIds` the runner's live instance still
63343
+ * carries the PRE-swap numeric id (baked into the object, its native-cap
63344
+ * registrations and its log tags), and a live object cannot be renumbered.
63345
+ * Before this method the only flush was restarting the whole owning addon
63346
+ * — which took every camera the provider owns down with it (28 devices
63347
+ * for one migrated camera, measured 2026-09-04, and the morning of the
63348
+ * same day ~27 devices' native caps did not come back on their own).
63349
+ *
63350
+ * Keyed by `stableId`, deliberately: the numeric id is exactly the thing
63351
+ * that changes. The reply carries the id the device answers on NOW.
63352
+ * Implemented once in `BaseDeviceProvider` — decommission the live
63353
+ * instance (if any), then re-create from the persisted row: the same
63354
+ * teardown/rehydrate pair every graceful shutdown + boot already uses.
63355
+ * An RPC, never an event: a dropped event would leave the runner writing
63356
+ * against the wrong camera (D8).
63357
+ *
63358
+ * Construction can dial hardware, and the migrated source is
63359
+ * characteristically dead — the timeout covers a full activate window
63360
+ * rather than the 60 s default.
63361
+ */
63362
+ reloadDevice: method(object({ stableId: string() }), object({ deviceId: number() }), {
63363
+ kind: "mutation",
63364
+ timeoutMs: 3 * 6e4
63365
+ }),
63243
63366
  supportsDiscovery: method(object({}), boolean()),
63244
63367
  /**
63245
63368
  * Run a network scan. `params` carries optional provider-specific scan
@@ -63567,7 +63690,8 @@ method(object({
63567
63690
  targetId: number()
63568
63691
  }), MigrateDeviceResultSchema, {
63569
63692
  kind: "mutation",
63570
- auth: "admin"
63693
+ auth: "admin",
63694
+ timeoutMs: 12 * 6e4
63571
63695
  }), method(DeviceRegisterPayloadSchema, _void(), { kind: "mutation" }), method(DeviceRemovePayloadSchema, _void(), { kind: "mutation" }), method(DevicePersistConfigPayloadSchema, _void(), { kind: "mutation" }), method(object({ deviceId: number() }), record(string(), unknown())), method(object({ deviceId: number() }), record(string(), unknown())), method(object({ deviceId: number() }), DeviceMetaSchema.nullable()), method(object({
63572
63696
  deviceId: number(),
63573
63697
  name: string()
@@ -82948,6 +83072,147 @@ var BaseDevice = class {
82948
83072
  }
82949
83073
  };
82950
83074
  /**
83075
+ * Delays before retry rounds 1..N — the round count IS the bound.
83076
+ * 10 s catches "the hub was busy for a moment"; the full schedule
83077
+ * (10 + 30 + 90 s of waiting, plus up to one 60 s transport timeout
83078
+ * per attempt) covers a device-manager lock held for minutes — the
83079
+ * 2026-09-04 outage's migration hold was ~3.5 min.
83080
+ */
83081
+ var DEVICE_RESTORE_RETRY_DELAYS_MS = [
83082
+ 1e4,
83083
+ 3e4,
83084
+ 9e4
83085
+ ];
83086
+ /** Abortable sleep — resolves early (never rejects) on abort. */
83087
+ function sleep$1(ms, signal) {
83088
+ return new Promise((resolve) => {
83089
+ if (signal.aborted) {
83090
+ resolve();
83091
+ return;
83092
+ }
83093
+ const onAbort = () => {
83094
+ clearTimeout(timer);
83095
+ resolve();
83096
+ };
83097
+ const timer = setTimeout(() => {
83098
+ signal.removeEventListener("abort", onAbort);
83099
+ resolve();
83100
+ }, ms);
83101
+ timer.unref?.();
83102
+ signal.addEventListener("abort", onAbort, { once: true });
83103
+ });
83104
+ }
83105
+ /** Drain `items` through at most `width` concurrent lanes. `fn` must
83106
+ * not reject (callers wrap their own try/catch). */
83107
+ async function runWithConcurrency(items, width, fn) {
83108
+ const queue = [...items];
83109
+ const laneCount = Math.max(1, Math.min(width, queue.length));
83110
+ const lane = async () => {
83111
+ for (;;) {
83112
+ const item = queue.shift();
83113
+ if (item === void 0) return;
83114
+ await fn(item);
83115
+ }
83116
+ };
83117
+ await Promise.all(Array.from({ length: laneCount }, lane));
83118
+ }
83119
+ var DeviceRestoreRetryScheduler = class {
83120
+ #logger;
83121
+ #attempt;
83122
+ #onPermanentFailure;
83123
+ #delaysMs;
83124
+ #concurrency;
83125
+ #now;
83126
+ #abort = new AbortController();
83127
+ constructor(options) {
83128
+ this.#logger = options.logger;
83129
+ this.#attempt = options.attempt;
83130
+ this.#onPermanentFailure = options.onPermanentFailure;
83131
+ this.#delaysMs = options.delaysMs ?? DEVICE_RESTORE_RETRY_DELAYS_MS;
83132
+ this.#concurrency = options.concurrency ?? 4;
83133
+ this.#now = options.now ?? Date.now;
83134
+ }
83135
+ /** Stop retrying (shutdown). Pending entries are NOT marked
83136
+ * permanently failed — the next boot restores them from disk. */
83137
+ cancel() {
83138
+ this.#abort.abort();
83139
+ }
83140
+ /**
83141
+ * Run the bounded retry rounds. Resolves when every entry has either
83142
+ * restored, been marked permanently failed, or the scheduler was
83143
+ * cancelled. Never rejects.
83144
+ */
83145
+ async run(initialFailures) {
83146
+ let pending = initialFailures.map((failure) => ({
83147
+ saved: failure.saved,
83148
+ lastError: failure.error,
83149
+ attempts: 1
83150
+ }));
83151
+ for (let round = 0; round < this.#delaysMs.length; round += 1) {
83152
+ if (pending.length === 0 || this.#abort.signal.aborted) break;
83153
+ await sleep$1(this.#delaysMs[round] ?? 0, this.#abort.signal);
83154
+ if (this.#abort.signal.aborted) break;
83155
+ pending = await this.#runRound(pending, round);
83156
+ }
83157
+ if (this.#abort.signal.aborted) return [];
83158
+ const terminal = pending.map((entry) => ({
83159
+ deviceId: entry.saved.id,
83160
+ stableId: entry.saved.stableId,
83161
+ type: String(entry.saved.type),
83162
+ attempts: entry.attempts,
83163
+ lastError: entry.lastError,
83164
+ failedAt: this.#now()
83165
+ }));
83166
+ for (const failure of terminal) this.#onPermanentFailure(failure);
83167
+ return terminal;
83168
+ }
83169
+ /** One retry round: parents first (phase 0), then hub-adopted
83170
+ * children (phase 1) — a child's attempt depends on its parent
83171
+ * having landed, exactly like the initial two-pass restore. */
83172
+ async #runRound(pending, round) {
83173
+ const next = [];
83174
+ const parents = pending.filter((entry) => entry.saved.parentDeviceId === null);
83175
+ const children = pending.filter((entry) => entry.saved.parentDeviceId !== null);
83176
+ for (const phase of [parents, children]) await runWithConcurrency(phase, this.#concurrency, async (entry) => {
83177
+ if (this.#abort.signal.aborted) {
83178
+ next.push(entry);
83179
+ return;
83180
+ }
83181
+ const attemptNo = entry.attempts + 1;
83182
+ try {
83183
+ await this.#attempt(entry.saved);
83184
+ this.#logger.info("Device restored on retry", {
83185
+ tags: {
83186
+ deviceId: entry.saved.id,
83187
+ stableId: entry.saved.stableId
83188
+ },
83189
+ meta: { attempt: attemptNo }
83190
+ });
83191
+ } catch (err) {
83192
+ const lastError = err instanceof Error ? err.message : String(err);
83193
+ const remainingRetries = this.#delaysMs.length - (round + 1);
83194
+ this.#logger.warn("Device restore retry failed", {
83195
+ tags: {
83196
+ deviceId: entry.saved.id,
83197
+ stableId: entry.saved.stableId
83198
+ },
83199
+ meta: {
83200
+ attempt: attemptNo,
83201
+ remainingRetries,
83202
+ error: lastError
83203
+ }
83204
+ });
83205
+ next.push({
83206
+ saved: entry.saved,
83207
+ lastError,
83208
+ attempts: attemptNo
83209
+ });
83210
+ }
83211
+ });
83212
+ return next;
83213
+ }
83214
+ };
83215
+ /**
82951
83216
  * Convert an IDevice to the flat DeviceSummary shape expected by the
82952
83217
  * device-provider cap router. Shared across all providers.
82953
83218
  */
@@ -82996,6 +83261,7 @@ var BaseDeviceProvider = class extends BaseAddon {
82996
83261
  }];
82997
83262
  }
82998
83263
  async onShutdown() {
83264
+ this.cancelRestoreRetries();
82999
83265
  const devices = await this.ctx.kernel.devices?.getAll() ?? [];
83000
83266
  for (const device of devices) try {
83001
83267
  await this.ctx.kernel.devices?.decommission(device.id);
@@ -83013,9 +83279,16 @@ var BaseDeviceProvider = class extends BaseAddon {
83013
83279
  async start() {}
83014
83280
  async stop() {}
83015
83281
  async getStatus() {
83282
+ const all = await this.ctx.kernel.devices?.getAll() ?? [];
83283
+ const summary = this.restoreFailureSummary();
83284
+ if (summary === null) return {
83285
+ connected: true,
83286
+ deviceCount: all.length
83287
+ };
83016
83288
  return {
83017
83289
  connected: true,
83018
- deviceCount: (await this.ctx.kernel.devices?.getAll() ?? []).length
83290
+ deviceCount: all.length,
83291
+ error: summary
83019
83292
  };
83020
83293
  }
83021
83294
  async getDevices() {
@@ -83105,8 +83378,137 @@ var BaseDeviceProvider = class extends BaseAddon {
83105
83378
  };
83106
83379
  }
83107
83380
  async restoreDevices(savedDevices) {
83108
- await this.onRestoreDevices(savedDevices);
83109
- if (savedDevices.length > 0) this.ctx.logger.info(`Restored ${savedDevices.length} ${this.providerName} device(s)`);
83381
+ const report = await this.onRestoreDevices(savedDevices);
83382
+ if (savedDevices.length === 0) return;
83383
+ if (report && report.failedCount > 0) {
83384
+ this.ctx.logger.warn(`Restored ${report.restoredCount}/${savedDevices.length} ${this.providerName} device(s) — ${report.failedCount} failed, bounded retry scheduled`);
83385
+ return;
83386
+ }
83387
+ const restoredCount = report ? report.restoredCount : savedDevices.length;
83388
+ this.ctx.logger.info(`Restored ${restoredCount} ${this.providerName} device(s)`);
83389
+ }
83390
+ /** Retry schedule. Overridable (tests use millisecond delays). */
83391
+ restoreRetryDelaysMs = DEVICE_RESTORE_RETRY_DELAYS_MS;
83392
+ /** Retry lane width. See `device-restore-retry.ts` for why retries
83393
+ * never re-stampede full-width while the initial pass does (D167). */
83394
+ restoreRetryConcurrency = 4;
83395
+ _restoreRetryScheduler = null;
83396
+ _restoreRetryCompletion = null;
83397
+ _permanentRestoreFailures = /* @__PURE__ */ new Map();
83398
+ /** Settles when the background retry rounds finish (or `null` when
83399
+ * nothing failed). Exposed for tests and subclass diagnostics —
83400
+ * boot NEVER awaits this: the runner's post-init handshake goes out
83401
+ * with the devices that restored, and a late success is announced
83402
+ * through the `native-cap-change` → `updateCaps` path. */
83403
+ get restoreRetryCompletion() {
83404
+ return this._restoreRetryCompletion;
83405
+ }
83406
+ /** Devices that exhausted the retry bound this process lifetime. */
83407
+ get permanentRestoreFailures() {
83408
+ return [...this._permanentRestoreFailures.values()];
83409
+ }
83410
+ /** One-line operator-facing summary for `getStatus().error`, or
83411
+ * `null` when every device restored. */
83412
+ restoreFailureSummary() {
83413
+ if (this._permanentRestoreFailures.size === 0) return null;
83414
+ const ids = [...this._permanentRestoreFailures.keys()].join(", ");
83415
+ return `${this._permanentRestoreFailures.size} device(s) permanently failed restore (deviceIds: ${ids}) — restart the ${this.providerName} provider to retry`;
83416
+ }
83417
+ cancelRestoreRetries() {
83418
+ this._restoreRetryScheduler?.cancel();
83419
+ this._restoreRetryScheduler = null;
83420
+ }
83421
+ recordPermanentRestoreFailure(failure) {
83422
+ this._permanentRestoreFailures.set(failure.deviceId, failure);
83423
+ this.ctx.logger.error("Device restore permanently failed — its capabilities will not register until the provider restarts", {
83424
+ tags: {
83425
+ deviceId: failure.deviceId,
83426
+ stableId: failure.stableId
83427
+ },
83428
+ meta: {
83429
+ type: failure.type,
83430
+ attempts: failure.attempts,
83431
+ error: failure.lastError
83432
+ }
83433
+ });
83434
+ }
83435
+ scheduleRestoreRetries(failures, attempt) {
83436
+ const scheduler = new DeviceRestoreRetryScheduler({
83437
+ logger: this.ctx.logger,
83438
+ delaysMs: this.restoreRetryDelaysMs,
83439
+ concurrency: this.restoreRetryConcurrency,
83440
+ attempt,
83441
+ onPermanentFailure: (failure) => this.recordPermanentRestoreFailure(failure)
83442
+ });
83443
+ this._restoreRetryScheduler = scheduler;
83444
+ this._restoreRetryCompletion = scheduler.run(failures).then(() => void 0).catch((err) => {
83445
+ this.ctx.logger.error("Restore retry scheduler crashed", { meta: { error: err instanceof Error ? err.message : String(err) } });
83446
+ });
83447
+ }
83448
+ /**
83449
+ * Tear down and reconstruct ONE device from its persisted rows — the
83450
+ * `deviceProvider.reloadDevice` cap method. Persistence is never touched,
83451
+ * and no other device this provider owns is disturbed.
83452
+ *
83453
+ * Keyed by `stableId` because the caller's whole reason to be here is that
83454
+ * the NUMERIC id changed (`deviceManager.migrateDevice` swapped it): the
83455
+ * fresh instance resolves its id through `allocateDeviceId`, which returns
83456
+ * whatever number the row carries NOW. The teardown is `decommission` —
83457
+ * exactly what a graceful shutdown runs per device (fires `removeDevice()`,
83458
+ * unregisters native caps, drops the registry entry) — and the rebuild is
83459
+ * the boot restore's own `create()` path, including its pass 2: first-class
83460
+ * children (hub-adopted cameras under an NVR) are decommissioned with the
83461
+ * parent by the cascade and must be re-created explicitly, because only
83462
+ * accessory children come back through `getAccessoryChildren()`.
83463
+ *
83464
+ * Reloading an accessory child directly is refused (no device class) —
83465
+ * reload its parent instead.
83466
+ */
83467
+ async reloadDevice(input) {
83468
+ const { stableId } = input;
83469
+ const devices = this.ctx.kernel.devices;
83470
+ if (!devices) throw new Error(`${this.providerName}: kernel.devices unavailable — cannot reload`);
83471
+ const live = (await devices.getAll()).find((d) => d.stableId === stableId);
83472
+ if (live) await devices.decommission(live.id);
83473
+ const { id } = await this.ctx.api.deviceManager.allocateDeviceId.mutate({
83474
+ addonId: this.addonId,
83475
+ stableId
83476
+ });
83477
+ const meta = await this.ctx.api.deviceManager.loadMeta.query({ deviceId: id });
83478
+ if (meta === null) throw new Error(`${this.providerName}: no persisted meta for "${stableId}" (id ${id}) — cannot reload`);
83479
+ const deviceType = Object.values(DeviceType).find((t) => t === meta.type);
83480
+ const Class = deviceType !== void 0 ? this.deviceClasses[deviceType] : void 0;
83481
+ if (!Class) throw new Error(`${this.providerName}: no device class for type "${meta.type}" — "${stableId}" is an accessory child; reload its parent instead`);
83482
+ await devices.create(stableId, Class, {}, meta.parentDeviceId ?? null);
83483
+ const rows = await this.ctx.api.deviceManager.listPersistedByAddon.query({ addonId: this.addonId });
83484
+ for (const row of rows) {
83485
+ if (row.parentDeviceId !== id) continue;
83486
+ const childType = Object.values(DeviceType).find((t) => t === row.type);
83487
+ const ChildClass = childType !== void 0 ? this.deviceClasses[childType] : void 0;
83488
+ if (!ChildClass) continue;
83489
+ try {
83490
+ await devices.create(row.stableId, ChildClass, {}, id);
83491
+ } catch (err) {
83492
+ this.ctx.logger.warn("reloadDevice: failed to re-create first-class child", {
83493
+ tags: {
83494
+ deviceId: row.id,
83495
+ stableId: row.stableId
83496
+ },
83497
+ meta: {
83498
+ parentDeviceId: id,
83499
+ error: err instanceof Error ? err.message : String(err)
83500
+ }
83501
+ });
83502
+ }
83503
+ }
83504
+ this.ctx.logger.info("device reloaded in place from persisted rows", {
83505
+ tags: { deviceId: id },
83506
+ meta: {
83507
+ stableId,
83508
+ type: meta.type
83509
+ }
83510
+ });
83511
+ return { deviceId: id };
83110
83512
  }
83111
83513
  /**
83112
83514
  * Restore devices from persisted state. Two-pass:
@@ -83132,55 +83534,108 @@ var BaseDeviceProvider = class extends BaseAddon {
83132
83534
  * accessory-spawn flow handles via the parent's
83133
83535
  * `getAccessoryChildren()`. Override only when the default doesn't
83134
83536
  * fit.
83537
+ *
83538
+ * A row that fails either pass is NOT terminal (D347): it is handed
83539
+ * to a bounded background retry (`DeviceRestoreRetryScheduler`).
83540
+ * Only after the bound is exhausted is the device marked permanently
83541
+ * failed — logged at ERROR with `tags.deviceId` and surfaced via
83542
+ * `getStatus().error`.
83135
83543
  */
83136
83544
  async onRestoreDevices(savedDevices) {
83137
83545
  const restored = /* @__PURE__ */ new Set();
83546
+ const failures = [];
83547
+ const attemptRestore = async (saved) => {
83548
+ if (restored.has(saved.id)) return;
83549
+ const Class = this.deviceClasses[saved.type];
83550
+ if (!Class) throw new Error(`no device class registered for type "${saved.type}"`);
83551
+ if (saved.parentDeviceId !== null && !restored.has(saved.parentDeviceId)) throw new Error(`parent device ${saved.parentDeviceId} not restored`);
83552
+ await this.ctx.kernel.devices.create(saved.stableId, Class, {}, saved.parentDeviceId);
83553
+ restored.add(saved.id);
83554
+ };
83138
83555
  const topLevel = savedDevices.filter((saved) => saved.parentDeviceId === null);
83139
83556
  const restoreOne = async (saved) => {
83140
- const Class = this.deviceClasses[saved.type];
83141
- if (!Class) {
83557
+ if (!this.deviceClasses[saved.type]) {
83142
83558
  this.ctx.logger.warn("No device class registered for restored type — skipping", {
83143
- tags: { stableId: saved.stableId },
83559
+ tags: {
83560
+ deviceId: saved.id,
83561
+ stableId: saved.stableId
83562
+ },
83144
83563
  meta: { type: saved.type }
83145
83564
  });
83146
83565
  return;
83147
83566
  }
83148
83567
  try {
83149
- await this.ctx.kernel.devices.create(saved.stableId, Class, {});
83150
- restored.add(saved.id);
83568
+ await attemptRestore(saved);
83151
83569
  } catch (err) {
83152
- this.ctx.logger.warn("Failed to restore device", {
83153
- tags: { stableId: saved.stableId },
83570
+ const error = err instanceof Error ? err.message : String(err);
83571
+ this.ctx.logger.warn("Failed to restore device — bounded retry scheduled", {
83572
+ tags: {
83573
+ deviceId: saved.id,
83574
+ stableId: saved.stableId
83575
+ },
83154
83576
  meta: {
83155
83577
  type: saved.type,
83156
- error: err instanceof Error ? err.message : String(err)
83578
+ attempt: 1,
83579
+ error
83157
83580
  }
83158
83581
  });
83582
+ failures.push({
83583
+ saved,
83584
+ error
83585
+ });
83159
83586
  }
83160
83587
  };
83161
83588
  await Promise.all(topLevel.map((saved) => restoreOne(saved)));
83589
+ const failedTopLevelIds = new Set(failures.map((failure) => failure.saved.id));
83162
83590
  const childRows = savedDevices.filter((s) => s.parentDeviceId !== null);
83163
83591
  for (const saved of childRows) {
83164
- const Class = this.deviceClasses[saved.type];
83165
- if (!Class) continue;
83592
+ if (!this.deviceClasses[saved.type]) continue;
83166
83593
  if (saved.parentDeviceId === null) continue;
83167
- if (!restored.has(saved.parentDeviceId)) continue;
83168
- try {
83169
- await this.ctx.kernel.devices.create(saved.stableId, Class, {}, saved.parentDeviceId);
83170
- restored.add(saved.id);
83171
- } catch (err) {
83172
- this.ctx.logger.warn("Failed to restore hub-adopted child", {
83594
+ if (restored.has(saved.parentDeviceId)) {
83595
+ try {
83596
+ await attemptRestore(saved);
83597
+ } catch (err) {
83598
+ const error = err instanceof Error ? err.message : String(err);
83599
+ this.ctx.logger.warn("Failed to restore hub-adopted child — bounded retry scheduled", {
83600
+ tags: {
83601
+ deviceId: saved.id,
83602
+ stableId: saved.stableId,
83603
+ parentDeviceId: saved.parentDeviceId
83604
+ },
83605
+ meta: {
83606
+ type: saved.type,
83607
+ attempt: 1,
83608
+ error
83609
+ }
83610
+ });
83611
+ failures.push({
83612
+ saved,
83613
+ error
83614
+ });
83615
+ }
83616
+ continue;
83617
+ }
83618
+ if (failedTopLevelIds.has(saved.parentDeviceId)) {
83619
+ this.ctx.logger.warn("Hub-adopted child deferred — parent failed initial restore", {
83173
83620
  tags: {
83621
+ deviceId: saved.id,
83174
83622
  stableId: saved.stableId,
83175
83623
  parentDeviceId: saved.parentDeviceId
83176
83624
  },
83177
- meta: {
83178
- type: saved.type,
83179
- error: err instanceof Error ? err.message : String(err)
83180
- }
83625
+ meta: { type: saved.type }
83626
+ });
83627
+ failures.push({
83628
+ saved,
83629
+ error: `parent device ${saved.parentDeviceId} not restored`
83181
83630
  });
83631
+ continue;
83182
83632
  }
83183
83633
  }
83634
+ if (failures.length > 0) this.scheduleRestoreRetries(failures, attemptRestore);
83635
+ return {
83636
+ restoredCount: restored.size,
83637
+ failedCount: failures.length
83638
+ };
83184
83639
  }
83185
83640
  /** Convert an IDevice to the flat DeviceSummary for the cap router. */
83186
83641
  toSummary(device) {
@@ -83689,6 +84144,12 @@ Object.freeze({
83689
84144
  addonId: null,
83690
84145
  access: "create"
83691
84146
  },
84147
+ "backup.cancel": {
84148
+ capName: "backup",
84149
+ capScope: "system",
84150
+ addonId: null,
84151
+ access: "create"
84152
+ },
83692
84153
  "backup.delete": {
83693
84154
  capName: "backup",
83694
84155
  capScope: "system",
@@ -83731,6 +84192,12 @@ Object.freeze({
83731
84192
  addonId: null,
83732
84193
  access: "view"
83733
84194
  },
84195
+ "backup.listRuns": {
84196
+ capName: "backup",
84197
+ capScope: "system",
84198
+ addonId: null,
84199
+ access: "view"
84200
+ },
83734
84201
  "backup.listSchedules": {
83735
84202
  capName: "backup",
83736
84203
  capScope: "system",
@@ -84931,6 +85398,12 @@ Object.freeze({
84931
85398
  addonId: null,
84932
85399
  access: "view"
84933
85400
  },
85401
+ "deviceProvider.reloadDevice": {
85402
+ capName: "device-provider",
85403
+ capScope: "system",
85404
+ addonId: null,
85405
+ access: "create"
85406
+ },
84934
85407
  "deviceProvider.start": {
84935
85408
  capName: "device-provider",
84936
85409
  capScope: "system",
@@ -88297,6 +88770,12 @@ Object.freeze({
88297
88770
  addonId: null,
88298
88771
  access: "create"
88299
88772
  },
88773
+ "streamBroker.forgetDeviceHardware": {
88774
+ capName: "stream-broker",
88775
+ capScope: "system",
88776
+ addonId: null,
88777
+ access: "delete"
88778
+ },
88300
88779
  "streamBroker.getAllRtspEntries": {
88301
88780
  capName: "stream-broker",
88302
88781
  capScope: "system",
@@ -90755,6 +91234,11 @@ Object.freeze({
90755
91234
  form: "single",
90756
91235
  optional: false
90757
91236
  }],
91237
+ "streamBroker.forgetDeviceHardware": [{
91238
+ name: "deviceId",
91239
+ form: "single",
91240
+ optional: false
91241
+ }],
90758
91242
  "streamBroker.getDeviceAudioMute": [{
90759
91243
  name: "deviceId",
90760
91244
  form: "single",
package/dist/addon.mjs CHANGED
@@ -61032,6 +61032,89 @@ var LocationStatSchema = object({
61032
61032
  fileCount: number(),
61033
61033
  present: boolean()
61034
61034
  });
61035
+ /** Lifecycle of a backup run. Terminal states: succeeded / failed / cancelled. */
61036
+ var BackupRunStateSchema = _enum([
61037
+ "queued",
61038
+ "running",
61039
+ "succeeded",
61040
+ "failed",
61041
+ "cancelled"
61042
+ ]);
61043
+ /**
61044
+ * Where a running backup currently is. `queued` before it starts,
61045
+ * `building` while the tar.gz is being staged, `uploading` during the
61046
+ * per-destination fan-out, `done` once terminal.
61047
+ */
61048
+ var BackupRunPhaseSchema = _enum([
61049
+ "queued",
61050
+ "building",
61051
+ "uploading",
61052
+ "done"
61053
+ ]);
61054
+ /**
61055
+ * Observable state of one backup run — readable WHILE it runs via
61056
+ * `backup.listRuns`. This is what makes the execution queue and
61057
+ * `backup.cancel` usable: the 2026-09-04 incident (two concurrent
61058
+ * multi-GB builds, staging 5.1 GB → 18 GB, load 62) was only
61059
+ * diagnosable with `du` because nothing reported that runs existed or
61060
+ * how large the staged archive had grown.
61061
+ */
61062
+ var BackupRunSchema = object({
61063
+ /** Stable run id — the handle `backup.cancel` takes. */
61064
+ id: string(),
61065
+ state: BackupRunStateSchema,
61066
+ phase: BackupRunPhaseSchema,
61067
+ /**
61068
+ * Resolved destination location ids. Empty while queued (targets are
61069
+ * resolved when the run starts, against the then-current policies).
61070
+ */
61071
+ destinationIds: array(string()).readonly(),
61072
+ label: string().optional(),
61073
+ /** ms-epoch when the run was submitted (trigger call / schedule fire). */
61074
+ requestedAt: number(),
61075
+ /** ms-epoch when the run left the queue and started building. */
61076
+ startedAt: number().optional(),
61077
+ /** ms-epoch when the run reached a terminal state. */
61078
+ finishedAt: number().optional(),
61079
+ /** Compressed bytes of the staging archive written so far. */
61080
+ stagedBytes: number(),
61081
+ /** Final staged archive size, once the build phase completes. */
61082
+ archiveSizeBytes: number().optional(),
61083
+ /** Bytes pushed to the destination currently uploading. */
61084
+ uploadedBytes: number(),
61085
+ /** Destinations where the archive fully landed (uploaded + indexed). */
61086
+ completedDestinationIds: array(string()).readonly(),
61087
+ /** Destinations that failed during the fan-out. */
61088
+ failedDestinationIds: array(string()).readonly(),
61089
+ /** Failure message when `state === 'failed'`. */
61090
+ error: string().optional(),
61091
+ /**
61092
+ * 1-based place in the execution queue — 1 = runs next. Present only
61093
+ * while `state === 'queued'`. Stamped by the orchestrator from the
61094
+ * queue's OWN pending order, never derived from timestamps, so the
61095
+ * UI cannot show an order the executor will not honour.
61096
+ */
61097
+ queuePosition: number().int().min(1).optional()
61098
+ });
61099
+ /**
61100
+ * Result of `backup.trigger`. The call still resolves when the run
61101
+ * terminates (compat with schedule-driven runs and the admin UI), but
61102
+ * it now names the run and says whether it had to WAIT: a trigger that
61103
+ * arrives while another run is in flight is enqueued (or joined onto
61104
+ * an identical already-queued run), never started concurrently.
61105
+ */
61106
+ var BackupTriggerResultSchema = object({
61107
+ /** The run this trigger mapped to — poll it via `listRuns`, stop it via `cancel`. */
61108
+ runId: string(),
61109
+ /** True when the run waited behind an in-flight run instead of starting immediately. */
61110
+ queued: boolean(),
61111
+ /** True when this trigger was coalesced onto an identical already-queued run. */
61112
+ joined: boolean(),
61113
+ /** True when the run was cancelled before completing every destination. */
61114
+ cancelled: boolean(),
61115
+ /** One entry per destination the archive landed at (partial on cancel). */
61116
+ entries: array(BackupEntrySchema).readonly()
61117
+ });
61035
61118
  /**
61036
61119
  * A backup schedule — the N:M "entry" that binds one cron cadence to a
61037
61120
  * SET of destination locations. Supersedes the per-location cron on
@@ -61079,7 +61162,10 @@ method(_void(), array(BackupDestinationInfoSchema).readonly(), { auth: "admin" }
61079
61162
  * retention (manual runs).
61080
61163
  */
61081
61164
  retentionCount: number().int().min(1).max(1e3).optional()
61082
- }).optional(), array(BackupEntrySchema).readonly(), {
61165
+ }).optional(), BackupTriggerResultSchema, {
61166
+ kind: "mutation",
61167
+ auth: "admin"
61168
+ }), method(_void(), array(BackupRunSchema).readonly(), { auth: "admin" }), method(object({ runId: string() }), object({ cancelled: boolean() }), {
61083
61169
  kind: "mutation",
61084
61170
  auth: "admin"
61085
61171
  }), method(_void(), array(BackupEntrySchema).readonly(), { auth: "admin" }), method(_void(), array(LocationStatSchema).readonly(), { auth: "admin" }), method(object({
@@ -61796,6 +61882,14 @@ method(object({
61796
61882
  }), object({ success: literal(true) }), {
61797
61883
  kind: "mutation",
61798
61884
  auth: "admin"
61885
+ }), method(object({ deviceId: number().int().nonnegative() }), object({
61886
+ derivedStreamsDeleted: array(string()).readonly(),
61887
+ assignmentsPurged: boolean(),
61888
+ probeSnapshotsDropped: number().int().nonnegative(),
61889
+ rtspTokenRowsDeleted: number().int().nonnegative()
61890
+ }), {
61891
+ kind: "mutation",
61892
+ auth: "admin"
61799
61893
  }), method(object({
61800
61894
  deviceId: number(),
61801
61895
  /** Absent = the LOWEST assigned profile — a notification attachment is
@@ -63240,6 +63334,35 @@ var deviceProviderCapability = {
63240
63334
  name: string(),
63241
63335
  type: string()
63242
63336
  }))),
63337
+ /**
63338
+ * Tear down and reconstruct ONE device in place from its persisted rows —
63339
+ * touching no other device this provider owns.
63340
+ *
63341
+ * The primitive `deviceManager.migrateDevice` uses to flush the two
63342
+ * migrated numbers: after `swapIds` the runner's live instance still
63343
+ * carries the PRE-swap numeric id (baked into the object, its native-cap
63344
+ * registrations and its log tags), and a live object cannot be renumbered.
63345
+ * Before this method the only flush was restarting the whole owning addon
63346
+ * — which took every camera the provider owns down with it (28 devices
63347
+ * for one migrated camera, measured 2026-09-04, and the morning of the
63348
+ * same day ~27 devices' native caps did not come back on their own).
63349
+ *
63350
+ * Keyed by `stableId`, deliberately: the numeric id is exactly the thing
63351
+ * that changes. The reply carries the id the device answers on NOW.
63352
+ * Implemented once in `BaseDeviceProvider` — decommission the live
63353
+ * instance (if any), then re-create from the persisted row: the same
63354
+ * teardown/rehydrate pair every graceful shutdown + boot already uses.
63355
+ * An RPC, never an event: a dropped event would leave the runner writing
63356
+ * against the wrong camera (D8).
63357
+ *
63358
+ * Construction can dial hardware, and the migrated source is
63359
+ * characteristically dead — the timeout covers a full activate window
63360
+ * rather than the 60 s default.
63361
+ */
63362
+ reloadDevice: method(object({ stableId: string() }), object({ deviceId: number() }), {
63363
+ kind: "mutation",
63364
+ timeoutMs: 3 * 6e4
63365
+ }),
63243
63366
  supportsDiscovery: method(object({}), boolean()),
63244
63367
  /**
63245
63368
  * Run a network scan. `params` carries optional provider-specific scan
@@ -63567,7 +63690,8 @@ method(object({
63567
63690
  targetId: number()
63568
63691
  }), MigrateDeviceResultSchema, {
63569
63692
  kind: "mutation",
63570
- auth: "admin"
63693
+ auth: "admin",
63694
+ timeoutMs: 12 * 6e4
63571
63695
  }), method(DeviceRegisterPayloadSchema, _void(), { kind: "mutation" }), method(DeviceRemovePayloadSchema, _void(), { kind: "mutation" }), method(DevicePersistConfigPayloadSchema, _void(), { kind: "mutation" }), method(object({ deviceId: number() }), record(string(), unknown())), method(object({ deviceId: number() }), record(string(), unknown())), method(object({ deviceId: number() }), DeviceMetaSchema.nullable()), method(object({
63572
63696
  deviceId: number(),
63573
63697
  name: string()
@@ -82948,6 +83072,147 @@ var BaseDevice = class {
82948
83072
  }
82949
83073
  };
82950
83074
  /**
83075
+ * Delays before retry rounds 1..N — the round count IS the bound.
83076
+ * 10 s catches "the hub was busy for a moment"; the full schedule
83077
+ * (10 + 30 + 90 s of waiting, plus up to one 60 s transport timeout
83078
+ * per attempt) covers a device-manager lock held for minutes — the
83079
+ * 2026-09-04 outage's migration hold was ~3.5 min.
83080
+ */
83081
+ var DEVICE_RESTORE_RETRY_DELAYS_MS = [
83082
+ 1e4,
83083
+ 3e4,
83084
+ 9e4
83085
+ ];
83086
+ /** Abortable sleep — resolves early (never rejects) on abort. */
83087
+ function sleep$1(ms, signal) {
83088
+ return new Promise((resolve) => {
83089
+ if (signal.aborted) {
83090
+ resolve();
83091
+ return;
83092
+ }
83093
+ const onAbort = () => {
83094
+ clearTimeout(timer);
83095
+ resolve();
83096
+ };
83097
+ const timer = setTimeout(() => {
83098
+ signal.removeEventListener("abort", onAbort);
83099
+ resolve();
83100
+ }, ms);
83101
+ timer.unref?.();
83102
+ signal.addEventListener("abort", onAbort, { once: true });
83103
+ });
83104
+ }
83105
+ /** Drain `items` through at most `width` concurrent lanes. `fn` must
83106
+ * not reject (callers wrap their own try/catch). */
83107
+ async function runWithConcurrency(items, width, fn) {
83108
+ const queue = [...items];
83109
+ const laneCount = Math.max(1, Math.min(width, queue.length));
83110
+ const lane = async () => {
83111
+ for (;;) {
83112
+ const item = queue.shift();
83113
+ if (item === void 0) return;
83114
+ await fn(item);
83115
+ }
83116
+ };
83117
+ await Promise.all(Array.from({ length: laneCount }, lane));
83118
+ }
83119
+ var DeviceRestoreRetryScheduler = class {
83120
+ #logger;
83121
+ #attempt;
83122
+ #onPermanentFailure;
83123
+ #delaysMs;
83124
+ #concurrency;
83125
+ #now;
83126
+ #abort = new AbortController();
83127
+ constructor(options) {
83128
+ this.#logger = options.logger;
83129
+ this.#attempt = options.attempt;
83130
+ this.#onPermanentFailure = options.onPermanentFailure;
83131
+ this.#delaysMs = options.delaysMs ?? DEVICE_RESTORE_RETRY_DELAYS_MS;
83132
+ this.#concurrency = options.concurrency ?? 4;
83133
+ this.#now = options.now ?? Date.now;
83134
+ }
83135
+ /** Stop retrying (shutdown). Pending entries are NOT marked
83136
+ * permanently failed — the next boot restores them from disk. */
83137
+ cancel() {
83138
+ this.#abort.abort();
83139
+ }
83140
+ /**
83141
+ * Run the bounded retry rounds. Resolves when every entry has either
83142
+ * restored, been marked permanently failed, or the scheduler was
83143
+ * cancelled. Never rejects.
83144
+ */
83145
+ async run(initialFailures) {
83146
+ let pending = initialFailures.map((failure) => ({
83147
+ saved: failure.saved,
83148
+ lastError: failure.error,
83149
+ attempts: 1
83150
+ }));
83151
+ for (let round = 0; round < this.#delaysMs.length; round += 1) {
83152
+ if (pending.length === 0 || this.#abort.signal.aborted) break;
83153
+ await sleep$1(this.#delaysMs[round] ?? 0, this.#abort.signal);
83154
+ if (this.#abort.signal.aborted) break;
83155
+ pending = await this.#runRound(pending, round);
83156
+ }
83157
+ if (this.#abort.signal.aborted) return [];
83158
+ const terminal = pending.map((entry) => ({
83159
+ deviceId: entry.saved.id,
83160
+ stableId: entry.saved.stableId,
83161
+ type: String(entry.saved.type),
83162
+ attempts: entry.attempts,
83163
+ lastError: entry.lastError,
83164
+ failedAt: this.#now()
83165
+ }));
83166
+ for (const failure of terminal) this.#onPermanentFailure(failure);
83167
+ return terminal;
83168
+ }
83169
+ /** One retry round: parents first (phase 0), then hub-adopted
83170
+ * children (phase 1) — a child's attempt depends on its parent
83171
+ * having landed, exactly like the initial two-pass restore. */
83172
+ async #runRound(pending, round) {
83173
+ const next = [];
83174
+ const parents = pending.filter((entry) => entry.saved.parentDeviceId === null);
83175
+ const children = pending.filter((entry) => entry.saved.parentDeviceId !== null);
83176
+ for (const phase of [parents, children]) await runWithConcurrency(phase, this.#concurrency, async (entry) => {
83177
+ if (this.#abort.signal.aborted) {
83178
+ next.push(entry);
83179
+ return;
83180
+ }
83181
+ const attemptNo = entry.attempts + 1;
83182
+ try {
83183
+ await this.#attempt(entry.saved);
83184
+ this.#logger.info("Device restored on retry", {
83185
+ tags: {
83186
+ deviceId: entry.saved.id,
83187
+ stableId: entry.saved.stableId
83188
+ },
83189
+ meta: { attempt: attemptNo }
83190
+ });
83191
+ } catch (err) {
83192
+ const lastError = err instanceof Error ? err.message : String(err);
83193
+ const remainingRetries = this.#delaysMs.length - (round + 1);
83194
+ this.#logger.warn("Device restore retry failed", {
83195
+ tags: {
83196
+ deviceId: entry.saved.id,
83197
+ stableId: entry.saved.stableId
83198
+ },
83199
+ meta: {
83200
+ attempt: attemptNo,
83201
+ remainingRetries,
83202
+ error: lastError
83203
+ }
83204
+ });
83205
+ next.push({
83206
+ saved: entry.saved,
83207
+ lastError,
83208
+ attempts: attemptNo
83209
+ });
83210
+ }
83211
+ });
83212
+ return next;
83213
+ }
83214
+ };
83215
+ /**
82951
83216
  * Convert an IDevice to the flat DeviceSummary shape expected by the
82952
83217
  * device-provider cap router. Shared across all providers.
82953
83218
  */
@@ -82996,6 +83261,7 @@ var BaseDeviceProvider = class extends BaseAddon {
82996
83261
  }];
82997
83262
  }
82998
83263
  async onShutdown() {
83264
+ this.cancelRestoreRetries();
82999
83265
  const devices = await this.ctx.kernel.devices?.getAll() ?? [];
83000
83266
  for (const device of devices) try {
83001
83267
  await this.ctx.kernel.devices?.decommission(device.id);
@@ -83013,9 +83279,16 @@ var BaseDeviceProvider = class extends BaseAddon {
83013
83279
  async start() {}
83014
83280
  async stop() {}
83015
83281
  async getStatus() {
83282
+ const all = await this.ctx.kernel.devices?.getAll() ?? [];
83283
+ const summary = this.restoreFailureSummary();
83284
+ if (summary === null) return {
83285
+ connected: true,
83286
+ deviceCount: all.length
83287
+ };
83016
83288
  return {
83017
83289
  connected: true,
83018
- deviceCount: (await this.ctx.kernel.devices?.getAll() ?? []).length
83290
+ deviceCount: all.length,
83291
+ error: summary
83019
83292
  };
83020
83293
  }
83021
83294
  async getDevices() {
@@ -83105,8 +83378,137 @@ var BaseDeviceProvider = class extends BaseAddon {
83105
83378
  };
83106
83379
  }
83107
83380
  async restoreDevices(savedDevices) {
83108
- await this.onRestoreDevices(savedDevices);
83109
- if (savedDevices.length > 0) this.ctx.logger.info(`Restored ${savedDevices.length} ${this.providerName} device(s)`);
83381
+ const report = await this.onRestoreDevices(savedDevices);
83382
+ if (savedDevices.length === 0) return;
83383
+ if (report && report.failedCount > 0) {
83384
+ this.ctx.logger.warn(`Restored ${report.restoredCount}/${savedDevices.length} ${this.providerName} device(s) — ${report.failedCount} failed, bounded retry scheduled`);
83385
+ return;
83386
+ }
83387
+ const restoredCount = report ? report.restoredCount : savedDevices.length;
83388
+ this.ctx.logger.info(`Restored ${restoredCount} ${this.providerName} device(s)`);
83389
+ }
83390
+ /** Retry schedule. Overridable (tests use millisecond delays). */
83391
+ restoreRetryDelaysMs = DEVICE_RESTORE_RETRY_DELAYS_MS;
83392
+ /** Retry lane width. See `device-restore-retry.ts` for why retries
83393
+ * never re-stampede full-width while the initial pass does (D167). */
83394
+ restoreRetryConcurrency = 4;
83395
+ _restoreRetryScheduler = null;
83396
+ _restoreRetryCompletion = null;
83397
+ _permanentRestoreFailures = /* @__PURE__ */ new Map();
83398
+ /** Settles when the background retry rounds finish (or `null` when
83399
+ * nothing failed). Exposed for tests and subclass diagnostics —
83400
+ * boot NEVER awaits this: the runner's post-init handshake goes out
83401
+ * with the devices that restored, and a late success is announced
83402
+ * through the `native-cap-change` → `updateCaps` path. */
83403
+ get restoreRetryCompletion() {
83404
+ return this._restoreRetryCompletion;
83405
+ }
83406
+ /** Devices that exhausted the retry bound this process lifetime. */
83407
+ get permanentRestoreFailures() {
83408
+ return [...this._permanentRestoreFailures.values()];
83409
+ }
83410
+ /** One-line operator-facing summary for `getStatus().error`, or
83411
+ * `null` when every device restored. */
83412
+ restoreFailureSummary() {
83413
+ if (this._permanentRestoreFailures.size === 0) return null;
83414
+ const ids = [...this._permanentRestoreFailures.keys()].join(", ");
83415
+ return `${this._permanentRestoreFailures.size} device(s) permanently failed restore (deviceIds: ${ids}) — restart the ${this.providerName} provider to retry`;
83416
+ }
83417
+ cancelRestoreRetries() {
83418
+ this._restoreRetryScheduler?.cancel();
83419
+ this._restoreRetryScheduler = null;
83420
+ }
83421
+ recordPermanentRestoreFailure(failure) {
83422
+ this._permanentRestoreFailures.set(failure.deviceId, failure);
83423
+ this.ctx.logger.error("Device restore permanently failed — its capabilities will not register until the provider restarts", {
83424
+ tags: {
83425
+ deviceId: failure.deviceId,
83426
+ stableId: failure.stableId
83427
+ },
83428
+ meta: {
83429
+ type: failure.type,
83430
+ attempts: failure.attempts,
83431
+ error: failure.lastError
83432
+ }
83433
+ });
83434
+ }
83435
+ scheduleRestoreRetries(failures, attempt) {
83436
+ const scheduler = new DeviceRestoreRetryScheduler({
83437
+ logger: this.ctx.logger,
83438
+ delaysMs: this.restoreRetryDelaysMs,
83439
+ concurrency: this.restoreRetryConcurrency,
83440
+ attempt,
83441
+ onPermanentFailure: (failure) => this.recordPermanentRestoreFailure(failure)
83442
+ });
83443
+ this._restoreRetryScheduler = scheduler;
83444
+ this._restoreRetryCompletion = scheduler.run(failures).then(() => void 0).catch((err) => {
83445
+ this.ctx.logger.error("Restore retry scheduler crashed", { meta: { error: err instanceof Error ? err.message : String(err) } });
83446
+ });
83447
+ }
83448
+ /**
83449
+ * Tear down and reconstruct ONE device from its persisted rows — the
83450
+ * `deviceProvider.reloadDevice` cap method. Persistence is never touched,
83451
+ * and no other device this provider owns is disturbed.
83452
+ *
83453
+ * Keyed by `stableId` because the caller's whole reason to be here is that
83454
+ * the NUMERIC id changed (`deviceManager.migrateDevice` swapped it): the
83455
+ * fresh instance resolves its id through `allocateDeviceId`, which returns
83456
+ * whatever number the row carries NOW. The teardown is `decommission` —
83457
+ * exactly what a graceful shutdown runs per device (fires `removeDevice()`,
83458
+ * unregisters native caps, drops the registry entry) — and the rebuild is
83459
+ * the boot restore's own `create()` path, including its pass 2: first-class
83460
+ * children (hub-adopted cameras under an NVR) are decommissioned with the
83461
+ * parent by the cascade and must be re-created explicitly, because only
83462
+ * accessory children come back through `getAccessoryChildren()`.
83463
+ *
83464
+ * Reloading an accessory child directly is refused (no device class) —
83465
+ * reload its parent instead.
83466
+ */
83467
+ async reloadDevice(input) {
83468
+ const { stableId } = input;
83469
+ const devices = this.ctx.kernel.devices;
83470
+ if (!devices) throw new Error(`${this.providerName}: kernel.devices unavailable — cannot reload`);
83471
+ const live = (await devices.getAll()).find((d) => d.stableId === stableId);
83472
+ if (live) await devices.decommission(live.id);
83473
+ const { id } = await this.ctx.api.deviceManager.allocateDeviceId.mutate({
83474
+ addonId: this.addonId,
83475
+ stableId
83476
+ });
83477
+ const meta = await this.ctx.api.deviceManager.loadMeta.query({ deviceId: id });
83478
+ if (meta === null) throw new Error(`${this.providerName}: no persisted meta for "${stableId}" (id ${id}) — cannot reload`);
83479
+ const deviceType = Object.values(DeviceType).find((t) => t === meta.type);
83480
+ const Class = deviceType !== void 0 ? this.deviceClasses[deviceType] : void 0;
83481
+ if (!Class) throw new Error(`${this.providerName}: no device class for type "${meta.type}" — "${stableId}" is an accessory child; reload its parent instead`);
83482
+ await devices.create(stableId, Class, {}, meta.parentDeviceId ?? null);
83483
+ const rows = await this.ctx.api.deviceManager.listPersistedByAddon.query({ addonId: this.addonId });
83484
+ for (const row of rows) {
83485
+ if (row.parentDeviceId !== id) continue;
83486
+ const childType = Object.values(DeviceType).find((t) => t === row.type);
83487
+ const ChildClass = childType !== void 0 ? this.deviceClasses[childType] : void 0;
83488
+ if (!ChildClass) continue;
83489
+ try {
83490
+ await devices.create(row.stableId, ChildClass, {}, id);
83491
+ } catch (err) {
83492
+ this.ctx.logger.warn("reloadDevice: failed to re-create first-class child", {
83493
+ tags: {
83494
+ deviceId: row.id,
83495
+ stableId: row.stableId
83496
+ },
83497
+ meta: {
83498
+ parentDeviceId: id,
83499
+ error: err instanceof Error ? err.message : String(err)
83500
+ }
83501
+ });
83502
+ }
83503
+ }
83504
+ this.ctx.logger.info("device reloaded in place from persisted rows", {
83505
+ tags: { deviceId: id },
83506
+ meta: {
83507
+ stableId,
83508
+ type: meta.type
83509
+ }
83510
+ });
83511
+ return { deviceId: id };
83110
83512
  }
83111
83513
  /**
83112
83514
  * Restore devices from persisted state. Two-pass:
@@ -83132,55 +83534,108 @@ var BaseDeviceProvider = class extends BaseAddon {
83132
83534
  * accessory-spawn flow handles via the parent's
83133
83535
  * `getAccessoryChildren()`. Override only when the default doesn't
83134
83536
  * fit.
83537
+ *
83538
+ * A row that fails either pass is NOT terminal (D347): it is handed
83539
+ * to a bounded background retry (`DeviceRestoreRetryScheduler`).
83540
+ * Only after the bound is exhausted is the device marked permanently
83541
+ * failed — logged at ERROR with `tags.deviceId` and surfaced via
83542
+ * `getStatus().error`.
83135
83543
  */
83136
83544
  async onRestoreDevices(savedDevices) {
83137
83545
  const restored = /* @__PURE__ */ new Set();
83546
+ const failures = [];
83547
+ const attemptRestore = async (saved) => {
83548
+ if (restored.has(saved.id)) return;
83549
+ const Class = this.deviceClasses[saved.type];
83550
+ if (!Class) throw new Error(`no device class registered for type "${saved.type}"`);
83551
+ if (saved.parentDeviceId !== null && !restored.has(saved.parentDeviceId)) throw new Error(`parent device ${saved.parentDeviceId} not restored`);
83552
+ await this.ctx.kernel.devices.create(saved.stableId, Class, {}, saved.parentDeviceId);
83553
+ restored.add(saved.id);
83554
+ };
83138
83555
  const topLevel = savedDevices.filter((saved) => saved.parentDeviceId === null);
83139
83556
  const restoreOne = async (saved) => {
83140
- const Class = this.deviceClasses[saved.type];
83141
- if (!Class) {
83557
+ if (!this.deviceClasses[saved.type]) {
83142
83558
  this.ctx.logger.warn("No device class registered for restored type — skipping", {
83143
- tags: { stableId: saved.stableId },
83559
+ tags: {
83560
+ deviceId: saved.id,
83561
+ stableId: saved.stableId
83562
+ },
83144
83563
  meta: { type: saved.type }
83145
83564
  });
83146
83565
  return;
83147
83566
  }
83148
83567
  try {
83149
- await this.ctx.kernel.devices.create(saved.stableId, Class, {});
83150
- restored.add(saved.id);
83568
+ await attemptRestore(saved);
83151
83569
  } catch (err) {
83152
- this.ctx.logger.warn("Failed to restore device", {
83153
- tags: { stableId: saved.stableId },
83570
+ const error = err instanceof Error ? err.message : String(err);
83571
+ this.ctx.logger.warn("Failed to restore device — bounded retry scheduled", {
83572
+ tags: {
83573
+ deviceId: saved.id,
83574
+ stableId: saved.stableId
83575
+ },
83154
83576
  meta: {
83155
83577
  type: saved.type,
83156
- error: err instanceof Error ? err.message : String(err)
83578
+ attempt: 1,
83579
+ error
83157
83580
  }
83158
83581
  });
83582
+ failures.push({
83583
+ saved,
83584
+ error
83585
+ });
83159
83586
  }
83160
83587
  };
83161
83588
  await Promise.all(topLevel.map((saved) => restoreOne(saved)));
83589
+ const failedTopLevelIds = new Set(failures.map((failure) => failure.saved.id));
83162
83590
  const childRows = savedDevices.filter((s) => s.parentDeviceId !== null);
83163
83591
  for (const saved of childRows) {
83164
- const Class = this.deviceClasses[saved.type];
83165
- if (!Class) continue;
83592
+ if (!this.deviceClasses[saved.type]) continue;
83166
83593
  if (saved.parentDeviceId === null) continue;
83167
- if (!restored.has(saved.parentDeviceId)) continue;
83168
- try {
83169
- await this.ctx.kernel.devices.create(saved.stableId, Class, {}, saved.parentDeviceId);
83170
- restored.add(saved.id);
83171
- } catch (err) {
83172
- this.ctx.logger.warn("Failed to restore hub-adopted child", {
83594
+ if (restored.has(saved.parentDeviceId)) {
83595
+ try {
83596
+ await attemptRestore(saved);
83597
+ } catch (err) {
83598
+ const error = err instanceof Error ? err.message : String(err);
83599
+ this.ctx.logger.warn("Failed to restore hub-adopted child — bounded retry scheduled", {
83600
+ tags: {
83601
+ deviceId: saved.id,
83602
+ stableId: saved.stableId,
83603
+ parentDeviceId: saved.parentDeviceId
83604
+ },
83605
+ meta: {
83606
+ type: saved.type,
83607
+ attempt: 1,
83608
+ error
83609
+ }
83610
+ });
83611
+ failures.push({
83612
+ saved,
83613
+ error
83614
+ });
83615
+ }
83616
+ continue;
83617
+ }
83618
+ if (failedTopLevelIds.has(saved.parentDeviceId)) {
83619
+ this.ctx.logger.warn("Hub-adopted child deferred — parent failed initial restore", {
83173
83620
  tags: {
83621
+ deviceId: saved.id,
83174
83622
  stableId: saved.stableId,
83175
83623
  parentDeviceId: saved.parentDeviceId
83176
83624
  },
83177
- meta: {
83178
- type: saved.type,
83179
- error: err instanceof Error ? err.message : String(err)
83180
- }
83625
+ meta: { type: saved.type }
83626
+ });
83627
+ failures.push({
83628
+ saved,
83629
+ error: `parent device ${saved.parentDeviceId} not restored`
83181
83630
  });
83631
+ continue;
83182
83632
  }
83183
83633
  }
83634
+ if (failures.length > 0) this.scheduleRestoreRetries(failures, attemptRestore);
83635
+ return {
83636
+ restoredCount: restored.size,
83637
+ failedCount: failures.length
83638
+ };
83184
83639
  }
83185
83640
  /** Convert an IDevice to the flat DeviceSummary for the cap router. */
83186
83641
  toSummary(device) {
@@ -83689,6 +84144,12 @@ Object.freeze({
83689
84144
  addonId: null,
83690
84145
  access: "create"
83691
84146
  },
84147
+ "backup.cancel": {
84148
+ capName: "backup",
84149
+ capScope: "system",
84150
+ addonId: null,
84151
+ access: "create"
84152
+ },
83692
84153
  "backup.delete": {
83693
84154
  capName: "backup",
83694
84155
  capScope: "system",
@@ -83731,6 +84192,12 @@ Object.freeze({
83731
84192
  addonId: null,
83732
84193
  access: "view"
83733
84194
  },
84195
+ "backup.listRuns": {
84196
+ capName: "backup",
84197
+ capScope: "system",
84198
+ addonId: null,
84199
+ access: "view"
84200
+ },
83734
84201
  "backup.listSchedules": {
83735
84202
  capName: "backup",
83736
84203
  capScope: "system",
@@ -84931,6 +85398,12 @@ Object.freeze({
84931
85398
  addonId: null,
84932
85399
  access: "view"
84933
85400
  },
85401
+ "deviceProvider.reloadDevice": {
85402
+ capName: "device-provider",
85403
+ capScope: "system",
85404
+ addonId: null,
85405
+ access: "create"
85406
+ },
84934
85407
  "deviceProvider.start": {
84935
85408
  capName: "device-provider",
84936
85409
  capScope: "system",
@@ -88297,6 +88770,12 @@ Object.freeze({
88297
88770
  addonId: null,
88298
88771
  access: "create"
88299
88772
  },
88773
+ "streamBroker.forgetDeviceHardware": {
88774
+ capName: "stream-broker",
88775
+ capScope: "system",
88776
+ addonId: null,
88777
+ access: "delete"
88778
+ },
88300
88779
  "streamBroker.getAllRtspEntries": {
88301
88780
  capName: "stream-broker",
88302
88781
  capScope: "system",
@@ -90755,6 +91234,11 @@ Object.freeze({
90755
91234
  form: "single",
90756
91235
  optional: false
90757
91236
  }],
91237
+ "streamBroker.forgetDeviceHardware": [{
91238
+ name: "deviceId",
91239
+ form: "single",
91240
+ optional: false
91241
+ }],
90758
91242
  "streamBroker.getDeviceAudioMute": [{
90759
91243
  name: "deviceId",
90760
91244
  form: "single",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@camstack/addon-provider-dreame",
3
- "version": "0.2.58",
3
+ "version": "0.2.60",
4
4
  "description": "Dreame robot-vacuum / lawn-mower device-provider addon for CamStack — wraps the @apocaliss92/nodedreame Dreamehome cloud client",
5
5
  "keywords": [
6
6
  "camstack",