@camstack/addon-provider-dreame 0.2.59 → 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 +391 -24
  2. package/dist/addon.mjs +391 -24
  3. package/package.json +1 -1
package/dist/addon.js CHANGED
@@ -63334,6 +63334,35 @@ var deviceProviderCapability = {
63334
63334
  name: string(),
63335
63335
  type: string()
63336
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
+ }),
63337
63366
  supportsDiscovery: method(object({}), boolean()),
63338
63367
  /**
63339
63368
  * Run a network scan. `params` carries optional provider-specific scan
@@ -63661,7 +63690,8 @@ method(object({
63661
63690
  targetId: number()
63662
63691
  }), MigrateDeviceResultSchema, {
63663
63692
  kind: "mutation",
63664
- auth: "admin"
63693
+ auth: "admin",
63694
+ timeoutMs: 12 * 6e4
63665
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({
63666
63696
  deviceId: number(),
63667
63697
  name: string()
@@ -83042,6 +83072,147 @@ var BaseDevice = class {
83042
83072
  }
83043
83073
  };
83044
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
+ /**
83045
83216
  * Convert an IDevice to the flat DeviceSummary shape expected by the
83046
83217
  * device-provider cap router. Shared across all providers.
83047
83218
  */
@@ -83090,6 +83261,7 @@ var BaseDeviceProvider = class extends BaseAddon {
83090
83261
  }];
83091
83262
  }
83092
83263
  async onShutdown() {
83264
+ this.cancelRestoreRetries();
83093
83265
  const devices = await this.ctx.kernel.devices?.getAll() ?? [];
83094
83266
  for (const device of devices) try {
83095
83267
  await this.ctx.kernel.devices?.decommission(device.id);
@@ -83107,9 +83279,16 @@ var BaseDeviceProvider = class extends BaseAddon {
83107
83279
  async start() {}
83108
83280
  async stop() {}
83109
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
+ };
83110
83288
  return {
83111
83289
  connected: true,
83112
- deviceCount: (await this.ctx.kernel.devices?.getAll() ?? []).length
83290
+ deviceCount: all.length,
83291
+ error: summary
83113
83292
  };
83114
83293
  }
83115
83294
  async getDevices() {
@@ -83199,8 +83378,137 @@ var BaseDeviceProvider = class extends BaseAddon {
83199
83378
  };
83200
83379
  }
83201
83380
  async restoreDevices(savedDevices) {
83202
- await this.onRestoreDevices(savedDevices);
83203
- 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 };
83204
83512
  }
83205
83513
  /**
83206
83514
  * Restore devices from persisted state. Two-pass:
@@ -83226,55 +83534,108 @@ var BaseDeviceProvider = class extends BaseAddon {
83226
83534
  * accessory-spawn flow handles via the parent's
83227
83535
  * `getAccessoryChildren()`. Override only when the default doesn't
83228
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`.
83229
83543
  */
83230
83544
  async onRestoreDevices(savedDevices) {
83231
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
+ };
83232
83555
  const topLevel = savedDevices.filter((saved) => saved.parentDeviceId === null);
83233
83556
  const restoreOne = async (saved) => {
83234
- const Class = this.deviceClasses[saved.type];
83235
- if (!Class) {
83557
+ if (!this.deviceClasses[saved.type]) {
83236
83558
  this.ctx.logger.warn("No device class registered for restored type — skipping", {
83237
- tags: { stableId: saved.stableId },
83559
+ tags: {
83560
+ deviceId: saved.id,
83561
+ stableId: saved.stableId
83562
+ },
83238
83563
  meta: { type: saved.type }
83239
83564
  });
83240
83565
  return;
83241
83566
  }
83242
83567
  try {
83243
- await this.ctx.kernel.devices.create(saved.stableId, Class, {});
83244
- restored.add(saved.id);
83568
+ await attemptRestore(saved);
83245
83569
  } catch (err) {
83246
- this.ctx.logger.warn("Failed to restore device", {
83247
- 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
+ },
83248
83576
  meta: {
83249
83577
  type: saved.type,
83250
- error: err instanceof Error ? err.message : String(err)
83578
+ attempt: 1,
83579
+ error
83251
83580
  }
83252
83581
  });
83582
+ failures.push({
83583
+ saved,
83584
+ error
83585
+ });
83253
83586
  }
83254
83587
  };
83255
83588
  await Promise.all(topLevel.map((saved) => restoreOne(saved)));
83589
+ const failedTopLevelIds = new Set(failures.map((failure) => failure.saved.id));
83256
83590
  const childRows = savedDevices.filter((s) => s.parentDeviceId !== null);
83257
83591
  for (const saved of childRows) {
83258
- const Class = this.deviceClasses[saved.type];
83259
- if (!Class) continue;
83592
+ if (!this.deviceClasses[saved.type]) continue;
83260
83593
  if (saved.parentDeviceId === null) continue;
83261
- if (!restored.has(saved.parentDeviceId)) continue;
83262
- try {
83263
- await this.ctx.kernel.devices.create(saved.stableId, Class, {}, saved.parentDeviceId);
83264
- restored.add(saved.id);
83265
- } catch (err) {
83266
- 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", {
83267
83620
  tags: {
83621
+ deviceId: saved.id,
83268
83622
  stableId: saved.stableId,
83269
83623
  parentDeviceId: saved.parentDeviceId
83270
83624
  },
83271
- meta: {
83272
- type: saved.type,
83273
- error: err instanceof Error ? err.message : String(err)
83274
- }
83625
+ meta: { type: saved.type }
83275
83626
  });
83627
+ failures.push({
83628
+ saved,
83629
+ error: `parent device ${saved.parentDeviceId} not restored`
83630
+ });
83631
+ continue;
83276
83632
  }
83277
83633
  }
83634
+ if (failures.length > 0) this.scheduleRestoreRetries(failures, attemptRestore);
83635
+ return {
83636
+ restoredCount: restored.size,
83637
+ failedCount: failures.length
83638
+ };
83278
83639
  }
83279
83640
  /** Convert an IDevice to the flat DeviceSummary for the cap router. */
83280
83641
  toSummary(device) {
@@ -85037,6 +85398,12 @@ Object.freeze({
85037
85398
  addonId: null,
85038
85399
  access: "view"
85039
85400
  },
85401
+ "deviceProvider.reloadDevice": {
85402
+ capName: "device-provider",
85403
+ capScope: "system",
85404
+ addonId: null,
85405
+ access: "create"
85406
+ },
85040
85407
  "deviceProvider.start": {
85041
85408
  capName: "device-provider",
85042
85409
  capScope: "system",
package/dist/addon.mjs CHANGED
@@ -63334,6 +63334,35 @@ var deviceProviderCapability = {
63334
63334
  name: string(),
63335
63335
  type: string()
63336
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
+ }),
63337
63366
  supportsDiscovery: method(object({}), boolean()),
63338
63367
  /**
63339
63368
  * Run a network scan. `params` carries optional provider-specific scan
@@ -63661,7 +63690,8 @@ method(object({
63661
63690
  targetId: number()
63662
63691
  }), MigrateDeviceResultSchema, {
63663
63692
  kind: "mutation",
63664
- auth: "admin"
63693
+ auth: "admin",
63694
+ timeoutMs: 12 * 6e4
63665
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({
63666
63696
  deviceId: number(),
63667
63697
  name: string()
@@ -83042,6 +83072,147 @@ var BaseDevice = class {
83042
83072
  }
83043
83073
  };
83044
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
+ /**
83045
83216
  * Convert an IDevice to the flat DeviceSummary shape expected by the
83046
83217
  * device-provider cap router. Shared across all providers.
83047
83218
  */
@@ -83090,6 +83261,7 @@ var BaseDeviceProvider = class extends BaseAddon {
83090
83261
  }];
83091
83262
  }
83092
83263
  async onShutdown() {
83264
+ this.cancelRestoreRetries();
83093
83265
  const devices = await this.ctx.kernel.devices?.getAll() ?? [];
83094
83266
  for (const device of devices) try {
83095
83267
  await this.ctx.kernel.devices?.decommission(device.id);
@@ -83107,9 +83279,16 @@ var BaseDeviceProvider = class extends BaseAddon {
83107
83279
  async start() {}
83108
83280
  async stop() {}
83109
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
+ };
83110
83288
  return {
83111
83289
  connected: true,
83112
- deviceCount: (await this.ctx.kernel.devices?.getAll() ?? []).length
83290
+ deviceCount: all.length,
83291
+ error: summary
83113
83292
  };
83114
83293
  }
83115
83294
  async getDevices() {
@@ -83199,8 +83378,137 @@ var BaseDeviceProvider = class extends BaseAddon {
83199
83378
  };
83200
83379
  }
83201
83380
  async restoreDevices(savedDevices) {
83202
- await this.onRestoreDevices(savedDevices);
83203
- 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 };
83204
83512
  }
83205
83513
  /**
83206
83514
  * Restore devices from persisted state. Two-pass:
@@ -83226,55 +83534,108 @@ var BaseDeviceProvider = class extends BaseAddon {
83226
83534
  * accessory-spawn flow handles via the parent's
83227
83535
  * `getAccessoryChildren()`. Override only when the default doesn't
83228
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`.
83229
83543
  */
83230
83544
  async onRestoreDevices(savedDevices) {
83231
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
+ };
83232
83555
  const topLevel = savedDevices.filter((saved) => saved.parentDeviceId === null);
83233
83556
  const restoreOne = async (saved) => {
83234
- const Class = this.deviceClasses[saved.type];
83235
- if (!Class) {
83557
+ if (!this.deviceClasses[saved.type]) {
83236
83558
  this.ctx.logger.warn("No device class registered for restored type — skipping", {
83237
- tags: { stableId: saved.stableId },
83559
+ tags: {
83560
+ deviceId: saved.id,
83561
+ stableId: saved.stableId
83562
+ },
83238
83563
  meta: { type: saved.type }
83239
83564
  });
83240
83565
  return;
83241
83566
  }
83242
83567
  try {
83243
- await this.ctx.kernel.devices.create(saved.stableId, Class, {});
83244
- restored.add(saved.id);
83568
+ await attemptRestore(saved);
83245
83569
  } catch (err) {
83246
- this.ctx.logger.warn("Failed to restore device", {
83247
- 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
+ },
83248
83576
  meta: {
83249
83577
  type: saved.type,
83250
- error: err instanceof Error ? err.message : String(err)
83578
+ attempt: 1,
83579
+ error
83251
83580
  }
83252
83581
  });
83582
+ failures.push({
83583
+ saved,
83584
+ error
83585
+ });
83253
83586
  }
83254
83587
  };
83255
83588
  await Promise.all(topLevel.map((saved) => restoreOne(saved)));
83589
+ const failedTopLevelIds = new Set(failures.map((failure) => failure.saved.id));
83256
83590
  const childRows = savedDevices.filter((s) => s.parentDeviceId !== null);
83257
83591
  for (const saved of childRows) {
83258
- const Class = this.deviceClasses[saved.type];
83259
- if (!Class) continue;
83592
+ if (!this.deviceClasses[saved.type]) continue;
83260
83593
  if (saved.parentDeviceId === null) continue;
83261
- if (!restored.has(saved.parentDeviceId)) continue;
83262
- try {
83263
- await this.ctx.kernel.devices.create(saved.stableId, Class, {}, saved.parentDeviceId);
83264
- restored.add(saved.id);
83265
- } catch (err) {
83266
- 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", {
83267
83620
  tags: {
83621
+ deviceId: saved.id,
83268
83622
  stableId: saved.stableId,
83269
83623
  parentDeviceId: saved.parentDeviceId
83270
83624
  },
83271
- meta: {
83272
- type: saved.type,
83273
- error: err instanceof Error ? err.message : String(err)
83274
- }
83625
+ meta: { type: saved.type }
83275
83626
  });
83627
+ failures.push({
83628
+ saved,
83629
+ error: `parent device ${saved.parentDeviceId} not restored`
83630
+ });
83631
+ continue;
83276
83632
  }
83277
83633
  }
83634
+ if (failures.length > 0) this.scheduleRestoreRetries(failures, attemptRestore);
83635
+ return {
83636
+ restoredCount: restored.size,
83637
+ failedCount: failures.length
83638
+ };
83278
83639
  }
83279
83640
  /** Convert an IDevice to the flat DeviceSummary for the cap router. */
83280
83641
  toSummary(device) {
@@ -85037,6 +85398,12 @@ Object.freeze({
85037
85398
  addonId: null,
85038
85399
  access: "view"
85039
85400
  },
85401
+ "deviceProvider.reloadDevice": {
85402
+ capName: "device-provider",
85403
+ capScope: "system",
85404
+ addonId: null,
85405
+ access: "create"
85406
+ },
85040
85407
  "deviceProvider.start": {
85041
85408
  capName: "device-provider",
85042
85409
  capScope: "system",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@camstack/addon-provider-dreame",
3
- "version": "0.2.59",
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",