@camstack/addon-provider-homematic 1.2.60 → 1.2.61

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
@@ -12887,6 +12887,35 @@ var deviceProviderCapability = {
12887
12887
  name: string(),
12888
12888
  type: string()
12889
12889
  }))),
12890
+ /**
12891
+ * Tear down and reconstruct ONE device in place from its persisted rows —
12892
+ * touching no other device this provider owns.
12893
+ *
12894
+ * The primitive `deviceManager.migrateDevice` uses to flush the two
12895
+ * migrated numbers: after `swapIds` the runner's live instance still
12896
+ * carries the PRE-swap numeric id (baked into the object, its native-cap
12897
+ * registrations and its log tags), and a live object cannot be renumbered.
12898
+ * Before this method the only flush was restarting the whole owning addon
12899
+ * — which took every camera the provider owns down with it (28 devices
12900
+ * for one migrated camera, measured 2026-09-04, and the morning of the
12901
+ * same day ~27 devices' native caps did not come back on their own).
12902
+ *
12903
+ * Keyed by `stableId`, deliberately: the numeric id is exactly the thing
12904
+ * that changes. The reply carries the id the device answers on NOW.
12905
+ * Implemented once in `BaseDeviceProvider` — decommission the live
12906
+ * instance (if any), then re-create from the persisted row: the same
12907
+ * teardown/rehydrate pair every graceful shutdown + boot already uses.
12908
+ * An RPC, never an event: a dropped event would leave the runner writing
12909
+ * against the wrong camera (D8).
12910
+ *
12911
+ * Construction can dial hardware, and the migrated source is
12912
+ * characteristically dead — the timeout covers a full activate window
12913
+ * rather than the 60 s default.
12914
+ */
12915
+ reloadDevice: method(object({ stableId: string() }), object({ deviceId: number() }), {
12916
+ kind: "mutation",
12917
+ timeoutMs: 3 * 6e4
12918
+ }),
12890
12919
  supportsDiscovery: method(object({}), boolean()),
12891
12920
  /**
12892
12921
  * Run a network scan. `params` carries optional provider-specific scan
@@ -13214,7 +13243,8 @@ method(object({
13214
13243
  targetId: number()
13215
13244
  }), MigrateDeviceResultSchema, {
13216
13245
  kind: "mutation",
13217
- auth: "admin"
13246
+ auth: "admin",
13247
+ timeoutMs: 12 * 6e4
13218
13248
  }), 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({
13219
13249
  deviceId: number(),
13220
13250
  name: string()
@@ -32570,6 +32600,147 @@ var BaseDevice = class {
32570
32600
  }
32571
32601
  };
32572
32602
  /**
32603
+ * Delays before retry rounds 1..N — the round count IS the bound.
32604
+ * 10 s catches "the hub was busy for a moment"; the full schedule
32605
+ * (10 + 30 + 90 s of waiting, plus up to one 60 s transport timeout
32606
+ * per attempt) covers a device-manager lock held for minutes — the
32607
+ * 2026-09-04 outage's migration hold was ~3.5 min.
32608
+ */
32609
+ var DEVICE_RESTORE_RETRY_DELAYS_MS = [
32610
+ 1e4,
32611
+ 3e4,
32612
+ 9e4
32613
+ ];
32614
+ /** Abortable sleep — resolves early (never rejects) on abort. */
32615
+ function sleep$1(ms, signal) {
32616
+ return new Promise((resolve) => {
32617
+ if (signal.aborted) {
32618
+ resolve();
32619
+ return;
32620
+ }
32621
+ const onAbort = () => {
32622
+ clearTimeout(timer);
32623
+ resolve();
32624
+ };
32625
+ const timer = setTimeout(() => {
32626
+ signal.removeEventListener("abort", onAbort);
32627
+ resolve();
32628
+ }, ms);
32629
+ timer.unref?.();
32630
+ signal.addEventListener("abort", onAbort, { once: true });
32631
+ });
32632
+ }
32633
+ /** Drain `items` through at most `width` concurrent lanes. `fn` must
32634
+ * not reject (callers wrap their own try/catch). */
32635
+ async function runWithConcurrency(items, width, fn) {
32636
+ const queue = [...items];
32637
+ const laneCount = Math.max(1, Math.min(width, queue.length));
32638
+ const lane = async () => {
32639
+ for (;;) {
32640
+ const item = queue.shift();
32641
+ if (item === void 0) return;
32642
+ await fn(item);
32643
+ }
32644
+ };
32645
+ await Promise.all(Array.from({ length: laneCount }, lane));
32646
+ }
32647
+ var DeviceRestoreRetryScheduler = class {
32648
+ #logger;
32649
+ #attempt;
32650
+ #onPermanentFailure;
32651
+ #delaysMs;
32652
+ #concurrency;
32653
+ #now;
32654
+ #abort = new AbortController();
32655
+ constructor(options) {
32656
+ this.#logger = options.logger;
32657
+ this.#attempt = options.attempt;
32658
+ this.#onPermanentFailure = options.onPermanentFailure;
32659
+ this.#delaysMs = options.delaysMs ?? DEVICE_RESTORE_RETRY_DELAYS_MS;
32660
+ this.#concurrency = options.concurrency ?? 4;
32661
+ this.#now = options.now ?? Date.now;
32662
+ }
32663
+ /** Stop retrying (shutdown). Pending entries are NOT marked
32664
+ * permanently failed — the next boot restores them from disk. */
32665
+ cancel() {
32666
+ this.#abort.abort();
32667
+ }
32668
+ /**
32669
+ * Run the bounded retry rounds. Resolves when every entry has either
32670
+ * restored, been marked permanently failed, or the scheduler was
32671
+ * cancelled. Never rejects.
32672
+ */
32673
+ async run(initialFailures) {
32674
+ let pending = initialFailures.map((failure) => ({
32675
+ saved: failure.saved,
32676
+ lastError: failure.error,
32677
+ attempts: 1
32678
+ }));
32679
+ for (let round = 0; round < this.#delaysMs.length; round += 1) {
32680
+ if (pending.length === 0 || this.#abort.signal.aborted) break;
32681
+ await sleep$1(this.#delaysMs[round] ?? 0, this.#abort.signal);
32682
+ if (this.#abort.signal.aborted) break;
32683
+ pending = await this.#runRound(pending, round);
32684
+ }
32685
+ if (this.#abort.signal.aborted) return [];
32686
+ const terminal = pending.map((entry) => ({
32687
+ deviceId: entry.saved.id,
32688
+ stableId: entry.saved.stableId,
32689
+ type: String(entry.saved.type),
32690
+ attempts: entry.attempts,
32691
+ lastError: entry.lastError,
32692
+ failedAt: this.#now()
32693
+ }));
32694
+ for (const failure of terminal) this.#onPermanentFailure(failure);
32695
+ return terminal;
32696
+ }
32697
+ /** One retry round: parents first (phase 0), then hub-adopted
32698
+ * children (phase 1) — a child's attempt depends on its parent
32699
+ * having landed, exactly like the initial two-pass restore. */
32700
+ async #runRound(pending, round) {
32701
+ const next = [];
32702
+ const parents = pending.filter((entry) => entry.saved.parentDeviceId === null);
32703
+ const children = pending.filter((entry) => entry.saved.parentDeviceId !== null);
32704
+ for (const phase of [parents, children]) await runWithConcurrency(phase, this.#concurrency, async (entry) => {
32705
+ if (this.#abort.signal.aborted) {
32706
+ next.push(entry);
32707
+ return;
32708
+ }
32709
+ const attemptNo = entry.attempts + 1;
32710
+ try {
32711
+ await this.#attempt(entry.saved);
32712
+ this.#logger.info("Device restored on retry", {
32713
+ tags: {
32714
+ deviceId: entry.saved.id,
32715
+ stableId: entry.saved.stableId
32716
+ },
32717
+ meta: { attempt: attemptNo }
32718
+ });
32719
+ } catch (err) {
32720
+ const lastError = err instanceof Error ? err.message : String(err);
32721
+ const remainingRetries = this.#delaysMs.length - (round + 1);
32722
+ this.#logger.warn("Device restore retry failed", {
32723
+ tags: {
32724
+ deviceId: entry.saved.id,
32725
+ stableId: entry.saved.stableId
32726
+ },
32727
+ meta: {
32728
+ attempt: attemptNo,
32729
+ remainingRetries,
32730
+ error: lastError
32731
+ }
32732
+ });
32733
+ next.push({
32734
+ saved: entry.saved,
32735
+ lastError,
32736
+ attempts: attemptNo
32737
+ });
32738
+ }
32739
+ });
32740
+ return next;
32741
+ }
32742
+ };
32743
+ /**
32573
32744
  * Convert an IDevice to the flat DeviceSummary shape expected by the
32574
32745
  * device-provider cap router. Shared across all providers.
32575
32746
  */
@@ -32618,6 +32789,7 @@ var BaseDeviceProvider = class extends BaseAddon {
32618
32789
  }];
32619
32790
  }
32620
32791
  async onShutdown() {
32792
+ this.cancelRestoreRetries();
32621
32793
  const devices = await this.ctx.kernel.devices?.getAll() ?? [];
32622
32794
  for (const device of devices) try {
32623
32795
  await this.ctx.kernel.devices?.decommission(device.id);
@@ -32635,9 +32807,16 @@ var BaseDeviceProvider = class extends BaseAddon {
32635
32807
  async start() {}
32636
32808
  async stop() {}
32637
32809
  async getStatus() {
32810
+ const all = await this.ctx.kernel.devices?.getAll() ?? [];
32811
+ const summary = this.restoreFailureSummary();
32812
+ if (summary === null) return {
32813
+ connected: true,
32814
+ deviceCount: all.length
32815
+ };
32638
32816
  return {
32639
32817
  connected: true,
32640
- deviceCount: (await this.ctx.kernel.devices?.getAll() ?? []).length
32818
+ deviceCount: all.length,
32819
+ error: summary
32641
32820
  };
32642
32821
  }
32643
32822
  async getDevices() {
@@ -32727,8 +32906,137 @@ var BaseDeviceProvider = class extends BaseAddon {
32727
32906
  };
32728
32907
  }
32729
32908
  async restoreDevices(savedDevices) {
32730
- await this.onRestoreDevices(savedDevices);
32731
- if (savedDevices.length > 0) this.ctx.logger.info(`Restored ${savedDevices.length} ${this.providerName} device(s)`);
32909
+ const report = await this.onRestoreDevices(savedDevices);
32910
+ if (savedDevices.length === 0) return;
32911
+ if (report && report.failedCount > 0) {
32912
+ this.ctx.logger.warn(`Restored ${report.restoredCount}/${savedDevices.length} ${this.providerName} device(s) — ${report.failedCount} failed, bounded retry scheduled`);
32913
+ return;
32914
+ }
32915
+ const restoredCount = report ? report.restoredCount : savedDevices.length;
32916
+ this.ctx.logger.info(`Restored ${restoredCount} ${this.providerName} device(s)`);
32917
+ }
32918
+ /** Retry schedule. Overridable (tests use millisecond delays). */
32919
+ restoreRetryDelaysMs = DEVICE_RESTORE_RETRY_DELAYS_MS;
32920
+ /** Retry lane width. See `device-restore-retry.ts` for why retries
32921
+ * never re-stampede full-width while the initial pass does (D167). */
32922
+ restoreRetryConcurrency = 4;
32923
+ _restoreRetryScheduler = null;
32924
+ _restoreRetryCompletion = null;
32925
+ _permanentRestoreFailures = /* @__PURE__ */ new Map();
32926
+ /** Settles when the background retry rounds finish (or `null` when
32927
+ * nothing failed). Exposed for tests and subclass diagnostics —
32928
+ * boot NEVER awaits this: the runner's post-init handshake goes out
32929
+ * with the devices that restored, and a late success is announced
32930
+ * through the `native-cap-change` → `updateCaps` path. */
32931
+ get restoreRetryCompletion() {
32932
+ return this._restoreRetryCompletion;
32933
+ }
32934
+ /** Devices that exhausted the retry bound this process lifetime. */
32935
+ get permanentRestoreFailures() {
32936
+ return [...this._permanentRestoreFailures.values()];
32937
+ }
32938
+ /** One-line operator-facing summary for `getStatus().error`, or
32939
+ * `null` when every device restored. */
32940
+ restoreFailureSummary() {
32941
+ if (this._permanentRestoreFailures.size === 0) return null;
32942
+ const ids = [...this._permanentRestoreFailures.keys()].join(", ");
32943
+ return `${this._permanentRestoreFailures.size} device(s) permanently failed restore (deviceIds: ${ids}) — restart the ${this.providerName} provider to retry`;
32944
+ }
32945
+ cancelRestoreRetries() {
32946
+ this._restoreRetryScheduler?.cancel();
32947
+ this._restoreRetryScheduler = null;
32948
+ }
32949
+ recordPermanentRestoreFailure(failure) {
32950
+ this._permanentRestoreFailures.set(failure.deviceId, failure);
32951
+ this.ctx.logger.error("Device restore permanently failed — its capabilities will not register until the provider restarts", {
32952
+ tags: {
32953
+ deviceId: failure.deviceId,
32954
+ stableId: failure.stableId
32955
+ },
32956
+ meta: {
32957
+ type: failure.type,
32958
+ attempts: failure.attempts,
32959
+ error: failure.lastError
32960
+ }
32961
+ });
32962
+ }
32963
+ scheduleRestoreRetries(failures, attempt) {
32964
+ const scheduler = new DeviceRestoreRetryScheduler({
32965
+ logger: this.ctx.logger,
32966
+ delaysMs: this.restoreRetryDelaysMs,
32967
+ concurrency: this.restoreRetryConcurrency,
32968
+ attempt,
32969
+ onPermanentFailure: (failure) => this.recordPermanentRestoreFailure(failure)
32970
+ });
32971
+ this._restoreRetryScheduler = scheduler;
32972
+ this._restoreRetryCompletion = scheduler.run(failures).then(() => void 0).catch((err) => {
32973
+ this.ctx.logger.error("Restore retry scheduler crashed", { meta: { error: err instanceof Error ? err.message : String(err) } });
32974
+ });
32975
+ }
32976
+ /**
32977
+ * Tear down and reconstruct ONE device from its persisted rows — the
32978
+ * `deviceProvider.reloadDevice` cap method. Persistence is never touched,
32979
+ * and no other device this provider owns is disturbed.
32980
+ *
32981
+ * Keyed by `stableId` because the caller's whole reason to be here is that
32982
+ * the NUMERIC id changed (`deviceManager.migrateDevice` swapped it): the
32983
+ * fresh instance resolves its id through `allocateDeviceId`, which returns
32984
+ * whatever number the row carries NOW. The teardown is `decommission` —
32985
+ * exactly what a graceful shutdown runs per device (fires `removeDevice()`,
32986
+ * unregisters native caps, drops the registry entry) — and the rebuild is
32987
+ * the boot restore's own `create()` path, including its pass 2: first-class
32988
+ * children (hub-adopted cameras under an NVR) are decommissioned with the
32989
+ * parent by the cascade and must be re-created explicitly, because only
32990
+ * accessory children come back through `getAccessoryChildren()`.
32991
+ *
32992
+ * Reloading an accessory child directly is refused (no device class) —
32993
+ * reload its parent instead.
32994
+ */
32995
+ async reloadDevice(input) {
32996
+ const { stableId } = input;
32997
+ const devices = this.ctx.kernel.devices;
32998
+ if (!devices) throw new Error(`${this.providerName}: kernel.devices unavailable — cannot reload`);
32999
+ const live = (await devices.getAll()).find((d) => d.stableId === stableId);
33000
+ if (live) await devices.decommission(live.id);
33001
+ const { id } = await this.ctx.api.deviceManager.allocateDeviceId.mutate({
33002
+ addonId: this.addonId,
33003
+ stableId
33004
+ });
33005
+ const meta = await this.ctx.api.deviceManager.loadMeta.query({ deviceId: id });
33006
+ if (meta === null) throw new Error(`${this.providerName}: no persisted meta for "${stableId}" (id ${id}) — cannot reload`);
33007
+ const deviceType = Object.values(DeviceType).find((t) => t === meta.type);
33008
+ const Class = deviceType !== void 0 ? this.deviceClasses[deviceType] : void 0;
33009
+ if (!Class) throw new Error(`${this.providerName}: no device class for type "${meta.type}" — "${stableId}" is an accessory child; reload its parent instead`);
33010
+ await devices.create(stableId, Class, {}, meta.parentDeviceId ?? null);
33011
+ const rows = await this.ctx.api.deviceManager.listPersistedByAddon.query({ addonId: this.addonId });
33012
+ for (const row of rows) {
33013
+ if (row.parentDeviceId !== id) continue;
33014
+ const childType = Object.values(DeviceType).find((t) => t === row.type);
33015
+ const ChildClass = childType !== void 0 ? this.deviceClasses[childType] : void 0;
33016
+ if (!ChildClass) continue;
33017
+ try {
33018
+ await devices.create(row.stableId, ChildClass, {}, id);
33019
+ } catch (err) {
33020
+ this.ctx.logger.warn("reloadDevice: failed to re-create first-class child", {
33021
+ tags: {
33022
+ deviceId: row.id,
33023
+ stableId: row.stableId
33024
+ },
33025
+ meta: {
33026
+ parentDeviceId: id,
33027
+ error: err instanceof Error ? err.message : String(err)
33028
+ }
33029
+ });
33030
+ }
33031
+ }
33032
+ this.ctx.logger.info("device reloaded in place from persisted rows", {
33033
+ tags: { deviceId: id },
33034
+ meta: {
33035
+ stableId,
33036
+ type: meta.type
33037
+ }
33038
+ });
33039
+ return { deviceId: id };
32732
33040
  }
32733
33041
  /**
32734
33042
  * Restore devices from persisted state. Two-pass:
@@ -32754,55 +33062,108 @@ var BaseDeviceProvider = class extends BaseAddon {
32754
33062
  * accessory-spawn flow handles via the parent's
32755
33063
  * `getAccessoryChildren()`. Override only when the default doesn't
32756
33064
  * fit.
33065
+ *
33066
+ * A row that fails either pass is NOT terminal (D347): it is handed
33067
+ * to a bounded background retry (`DeviceRestoreRetryScheduler`).
33068
+ * Only after the bound is exhausted is the device marked permanently
33069
+ * failed — logged at ERROR with `tags.deviceId` and surfaced via
33070
+ * `getStatus().error`.
32757
33071
  */
32758
33072
  async onRestoreDevices(savedDevices) {
32759
33073
  const restored = /* @__PURE__ */ new Set();
33074
+ const failures = [];
33075
+ const attemptRestore = async (saved) => {
33076
+ if (restored.has(saved.id)) return;
33077
+ const Class = this.deviceClasses[saved.type];
33078
+ if (!Class) throw new Error(`no device class registered for type "${saved.type}"`);
33079
+ if (saved.parentDeviceId !== null && !restored.has(saved.parentDeviceId)) throw new Error(`parent device ${saved.parentDeviceId} not restored`);
33080
+ await this.ctx.kernel.devices.create(saved.stableId, Class, {}, saved.parentDeviceId);
33081
+ restored.add(saved.id);
33082
+ };
32760
33083
  const topLevel = savedDevices.filter((saved) => saved.parentDeviceId === null);
32761
33084
  const restoreOne = async (saved) => {
32762
- const Class = this.deviceClasses[saved.type];
32763
- if (!Class) {
33085
+ if (!this.deviceClasses[saved.type]) {
32764
33086
  this.ctx.logger.warn("No device class registered for restored type — skipping", {
32765
- tags: { stableId: saved.stableId },
33087
+ tags: {
33088
+ deviceId: saved.id,
33089
+ stableId: saved.stableId
33090
+ },
32766
33091
  meta: { type: saved.type }
32767
33092
  });
32768
33093
  return;
32769
33094
  }
32770
33095
  try {
32771
- await this.ctx.kernel.devices.create(saved.stableId, Class, {});
32772
- restored.add(saved.id);
33096
+ await attemptRestore(saved);
32773
33097
  } catch (err) {
32774
- this.ctx.logger.warn("Failed to restore device", {
32775
- tags: { stableId: saved.stableId },
33098
+ const error = err instanceof Error ? err.message : String(err);
33099
+ this.ctx.logger.warn("Failed to restore device — bounded retry scheduled", {
33100
+ tags: {
33101
+ deviceId: saved.id,
33102
+ stableId: saved.stableId
33103
+ },
32776
33104
  meta: {
32777
33105
  type: saved.type,
32778
- error: err instanceof Error ? err.message : String(err)
33106
+ attempt: 1,
33107
+ error
32779
33108
  }
32780
33109
  });
33110
+ failures.push({
33111
+ saved,
33112
+ error
33113
+ });
32781
33114
  }
32782
33115
  };
32783
33116
  await Promise.all(topLevel.map((saved) => restoreOne(saved)));
33117
+ const failedTopLevelIds = new Set(failures.map((failure) => failure.saved.id));
32784
33118
  const childRows = savedDevices.filter((s) => s.parentDeviceId !== null);
32785
33119
  for (const saved of childRows) {
32786
- const Class = this.deviceClasses[saved.type];
32787
- if (!Class) continue;
33120
+ if (!this.deviceClasses[saved.type]) continue;
32788
33121
  if (saved.parentDeviceId === null) continue;
32789
- if (!restored.has(saved.parentDeviceId)) continue;
32790
- try {
32791
- await this.ctx.kernel.devices.create(saved.stableId, Class, {}, saved.parentDeviceId);
32792
- restored.add(saved.id);
32793
- } catch (err) {
32794
- this.ctx.logger.warn("Failed to restore hub-adopted child", {
33122
+ if (restored.has(saved.parentDeviceId)) {
33123
+ try {
33124
+ await attemptRestore(saved);
33125
+ } catch (err) {
33126
+ const error = err instanceof Error ? err.message : String(err);
33127
+ this.ctx.logger.warn("Failed to restore hub-adopted child — bounded retry scheduled", {
33128
+ tags: {
33129
+ deviceId: saved.id,
33130
+ stableId: saved.stableId,
33131
+ parentDeviceId: saved.parentDeviceId
33132
+ },
33133
+ meta: {
33134
+ type: saved.type,
33135
+ attempt: 1,
33136
+ error
33137
+ }
33138
+ });
33139
+ failures.push({
33140
+ saved,
33141
+ error
33142
+ });
33143
+ }
33144
+ continue;
33145
+ }
33146
+ if (failedTopLevelIds.has(saved.parentDeviceId)) {
33147
+ this.ctx.logger.warn("Hub-adopted child deferred — parent failed initial restore", {
32795
33148
  tags: {
33149
+ deviceId: saved.id,
32796
33150
  stableId: saved.stableId,
32797
33151
  parentDeviceId: saved.parentDeviceId
32798
33152
  },
32799
- meta: {
32800
- type: saved.type,
32801
- error: err instanceof Error ? err.message : String(err)
32802
- }
33153
+ meta: { type: saved.type }
33154
+ });
33155
+ failures.push({
33156
+ saved,
33157
+ error: `parent device ${saved.parentDeviceId} not restored`
32803
33158
  });
33159
+ continue;
32804
33160
  }
32805
33161
  }
33162
+ if (failures.length > 0) this.scheduleRestoreRetries(failures, attemptRestore);
33163
+ return {
33164
+ restoredCount: restored.size,
33165
+ failedCount: failures.length
33166
+ };
32806
33167
  }
32807
33168
  /** Convert an IDevice to the flat DeviceSummary for the cap router. */
32808
33169
  toSummary(device) {
@@ -34565,6 +34926,12 @@ Object.freeze({
34565
34926
  addonId: null,
34566
34927
  access: "view"
34567
34928
  },
34929
+ "deviceProvider.reloadDevice": {
34930
+ capName: "device-provider",
34931
+ capScope: "system",
34932
+ addonId: null,
34933
+ access: "create"
34934
+ },
34568
34935
  "deviceProvider.start": {
34569
34936
  capName: "device-provider",
34570
34937
  capScope: "system",
package/dist/addon.mjs CHANGED
@@ -12888,6 +12888,35 @@ var deviceProviderCapability = {
12888
12888
  name: string(),
12889
12889
  type: string()
12890
12890
  }))),
12891
+ /**
12892
+ * Tear down and reconstruct ONE device in place from its persisted rows —
12893
+ * touching no other device this provider owns.
12894
+ *
12895
+ * The primitive `deviceManager.migrateDevice` uses to flush the two
12896
+ * migrated numbers: after `swapIds` the runner's live instance still
12897
+ * carries the PRE-swap numeric id (baked into the object, its native-cap
12898
+ * registrations and its log tags), and a live object cannot be renumbered.
12899
+ * Before this method the only flush was restarting the whole owning addon
12900
+ * — which took every camera the provider owns down with it (28 devices
12901
+ * for one migrated camera, measured 2026-09-04, and the morning of the
12902
+ * same day ~27 devices' native caps did not come back on their own).
12903
+ *
12904
+ * Keyed by `stableId`, deliberately: the numeric id is exactly the thing
12905
+ * that changes. The reply carries the id the device answers on NOW.
12906
+ * Implemented once in `BaseDeviceProvider` — decommission the live
12907
+ * instance (if any), then re-create from the persisted row: the same
12908
+ * teardown/rehydrate pair every graceful shutdown + boot already uses.
12909
+ * An RPC, never an event: a dropped event would leave the runner writing
12910
+ * against the wrong camera (D8).
12911
+ *
12912
+ * Construction can dial hardware, and the migrated source is
12913
+ * characteristically dead — the timeout covers a full activate window
12914
+ * rather than the 60 s default.
12915
+ */
12916
+ reloadDevice: method(object({ stableId: string() }), object({ deviceId: number() }), {
12917
+ kind: "mutation",
12918
+ timeoutMs: 3 * 6e4
12919
+ }),
12891
12920
  supportsDiscovery: method(object({}), boolean()),
12892
12921
  /**
12893
12922
  * Run a network scan. `params` carries optional provider-specific scan
@@ -13215,7 +13244,8 @@ method(object({
13215
13244
  targetId: number()
13216
13245
  }), MigrateDeviceResultSchema, {
13217
13246
  kind: "mutation",
13218
- auth: "admin"
13247
+ auth: "admin",
13248
+ timeoutMs: 12 * 6e4
13219
13249
  }), 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({
13220
13250
  deviceId: number(),
13221
13251
  name: string()
@@ -32571,6 +32601,147 @@ var BaseDevice = class {
32571
32601
  }
32572
32602
  };
32573
32603
  /**
32604
+ * Delays before retry rounds 1..N — the round count IS the bound.
32605
+ * 10 s catches "the hub was busy for a moment"; the full schedule
32606
+ * (10 + 30 + 90 s of waiting, plus up to one 60 s transport timeout
32607
+ * per attempt) covers a device-manager lock held for minutes — the
32608
+ * 2026-09-04 outage's migration hold was ~3.5 min.
32609
+ */
32610
+ var DEVICE_RESTORE_RETRY_DELAYS_MS = [
32611
+ 1e4,
32612
+ 3e4,
32613
+ 9e4
32614
+ ];
32615
+ /** Abortable sleep — resolves early (never rejects) on abort. */
32616
+ function sleep$1(ms, signal) {
32617
+ return new Promise((resolve) => {
32618
+ if (signal.aborted) {
32619
+ resolve();
32620
+ return;
32621
+ }
32622
+ const onAbort = () => {
32623
+ clearTimeout(timer);
32624
+ resolve();
32625
+ };
32626
+ const timer = setTimeout(() => {
32627
+ signal.removeEventListener("abort", onAbort);
32628
+ resolve();
32629
+ }, ms);
32630
+ timer.unref?.();
32631
+ signal.addEventListener("abort", onAbort, { once: true });
32632
+ });
32633
+ }
32634
+ /** Drain `items` through at most `width` concurrent lanes. `fn` must
32635
+ * not reject (callers wrap their own try/catch). */
32636
+ async function runWithConcurrency(items, width, fn) {
32637
+ const queue = [...items];
32638
+ const laneCount = Math.max(1, Math.min(width, queue.length));
32639
+ const lane = async () => {
32640
+ for (;;) {
32641
+ const item = queue.shift();
32642
+ if (item === void 0) return;
32643
+ await fn(item);
32644
+ }
32645
+ };
32646
+ await Promise.all(Array.from({ length: laneCount }, lane));
32647
+ }
32648
+ var DeviceRestoreRetryScheduler = class {
32649
+ #logger;
32650
+ #attempt;
32651
+ #onPermanentFailure;
32652
+ #delaysMs;
32653
+ #concurrency;
32654
+ #now;
32655
+ #abort = new AbortController();
32656
+ constructor(options) {
32657
+ this.#logger = options.logger;
32658
+ this.#attempt = options.attempt;
32659
+ this.#onPermanentFailure = options.onPermanentFailure;
32660
+ this.#delaysMs = options.delaysMs ?? DEVICE_RESTORE_RETRY_DELAYS_MS;
32661
+ this.#concurrency = options.concurrency ?? 4;
32662
+ this.#now = options.now ?? Date.now;
32663
+ }
32664
+ /** Stop retrying (shutdown). Pending entries are NOT marked
32665
+ * permanently failed — the next boot restores them from disk. */
32666
+ cancel() {
32667
+ this.#abort.abort();
32668
+ }
32669
+ /**
32670
+ * Run the bounded retry rounds. Resolves when every entry has either
32671
+ * restored, been marked permanently failed, or the scheduler was
32672
+ * cancelled. Never rejects.
32673
+ */
32674
+ async run(initialFailures) {
32675
+ let pending = initialFailures.map((failure) => ({
32676
+ saved: failure.saved,
32677
+ lastError: failure.error,
32678
+ attempts: 1
32679
+ }));
32680
+ for (let round = 0; round < this.#delaysMs.length; round += 1) {
32681
+ if (pending.length === 0 || this.#abort.signal.aborted) break;
32682
+ await sleep$1(this.#delaysMs[round] ?? 0, this.#abort.signal);
32683
+ if (this.#abort.signal.aborted) break;
32684
+ pending = await this.#runRound(pending, round);
32685
+ }
32686
+ if (this.#abort.signal.aborted) return [];
32687
+ const terminal = pending.map((entry) => ({
32688
+ deviceId: entry.saved.id,
32689
+ stableId: entry.saved.stableId,
32690
+ type: String(entry.saved.type),
32691
+ attempts: entry.attempts,
32692
+ lastError: entry.lastError,
32693
+ failedAt: this.#now()
32694
+ }));
32695
+ for (const failure of terminal) this.#onPermanentFailure(failure);
32696
+ return terminal;
32697
+ }
32698
+ /** One retry round: parents first (phase 0), then hub-adopted
32699
+ * children (phase 1) — a child's attempt depends on its parent
32700
+ * having landed, exactly like the initial two-pass restore. */
32701
+ async #runRound(pending, round) {
32702
+ const next = [];
32703
+ const parents = pending.filter((entry) => entry.saved.parentDeviceId === null);
32704
+ const children = pending.filter((entry) => entry.saved.parentDeviceId !== null);
32705
+ for (const phase of [parents, children]) await runWithConcurrency(phase, this.#concurrency, async (entry) => {
32706
+ if (this.#abort.signal.aborted) {
32707
+ next.push(entry);
32708
+ return;
32709
+ }
32710
+ const attemptNo = entry.attempts + 1;
32711
+ try {
32712
+ await this.#attempt(entry.saved);
32713
+ this.#logger.info("Device restored on retry", {
32714
+ tags: {
32715
+ deviceId: entry.saved.id,
32716
+ stableId: entry.saved.stableId
32717
+ },
32718
+ meta: { attempt: attemptNo }
32719
+ });
32720
+ } catch (err) {
32721
+ const lastError = err instanceof Error ? err.message : String(err);
32722
+ const remainingRetries = this.#delaysMs.length - (round + 1);
32723
+ this.#logger.warn("Device restore retry failed", {
32724
+ tags: {
32725
+ deviceId: entry.saved.id,
32726
+ stableId: entry.saved.stableId
32727
+ },
32728
+ meta: {
32729
+ attempt: attemptNo,
32730
+ remainingRetries,
32731
+ error: lastError
32732
+ }
32733
+ });
32734
+ next.push({
32735
+ saved: entry.saved,
32736
+ lastError,
32737
+ attempts: attemptNo
32738
+ });
32739
+ }
32740
+ });
32741
+ return next;
32742
+ }
32743
+ };
32744
+ /**
32574
32745
  * Convert an IDevice to the flat DeviceSummary shape expected by the
32575
32746
  * device-provider cap router. Shared across all providers.
32576
32747
  */
@@ -32619,6 +32790,7 @@ var BaseDeviceProvider = class extends BaseAddon {
32619
32790
  }];
32620
32791
  }
32621
32792
  async onShutdown() {
32793
+ this.cancelRestoreRetries();
32622
32794
  const devices = await this.ctx.kernel.devices?.getAll() ?? [];
32623
32795
  for (const device of devices) try {
32624
32796
  await this.ctx.kernel.devices?.decommission(device.id);
@@ -32636,9 +32808,16 @@ var BaseDeviceProvider = class extends BaseAddon {
32636
32808
  async start() {}
32637
32809
  async stop() {}
32638
32810
  async getStatus() {
32811
+ const all = await this.ctx.kernel.devices?.getAll() ?? [];
32812
+ const summary = this.restoreFailureSummary();
32813
+ if (summary === null) return {
32814
+ connected: true,
32815
+ deviceCount: all.length
32816
+ };
32639
32817
  return {
32640
32818
  connected: true,
32641
- deviceCount: (await this.ctx.kernel.devices?.getAll() ?? []).length
32819
+ deviceCount: all.length,
32820
+ error: summary
32642
32821
  };
32643
32822
  }
32644
32823
  async getDevices() {
@@ -32728,8 +32907,137 @@ var BaseDeviceProvider = class extends BaseAddon {
32728
32907
  };
32729
32908
  }
32730
32909
  async restoreDevices(savedDevices) {
32731
- await this.onRestoreDevices(savedDevices);
32732
- if (savedDevices.length > 0) this.ctx.logger.info(`Restored ${savedDevices.length} ${this.providerName} device(s)`);
32910
+ const report = await this.onRestoreDevices(savedDevices);
32911
+ if (savedDevices.length === 0) return;
32912
+ if (report && report.failedCount > 0) {
32913
+ this.ctx.logger.warn(`Restored ${report.restoredCount}/${savedDevices.length} ${this.providerName} device(s) — ${report.failedCount} failed, bounded retry scheduled`);
32914
+ return;
32915
+ }
32916
+ const restoredCount = report ? report.restoredCount : savedDevices.length;
32917
+ this.ctx.logger.info(`Restored ${restoredCount} ${this.providerName} device(s)`);
32918
+ }
32919
+ /** Retry schedule. Overridable (tests use millisecond delays). */
32920
+ restoreRetryDelaysMs = DEVICE_RESTORE_RETRY_DELAYS_MS;
32921
+ /** Retry lane width. See `device-restore-retry.ts` for why retries
32922
+ * never re-stampede full-width while the initial pass does (D167). */
32923
+ restoreRetryConcurrency = 4;
32924
+ _restoreRetryScheduler = null;
32925
+ _restoreRetryCompletion = null;
32926
+ _permanentRestoreFailures = /* @__PURE__ */ new Map();
32927
+ /** Settles when the background retry rounds finish (or `null` when
32928
+ * nothing failed). Exposed for tests and subclass diagnostics —
32929
+ * boot NEVER awaits this: the runner's post-init handshake goes out
32930
+ * with the devices that restored, and a late success is announced
32931
+ * through the `native-cap-change` → `updateCaps` path. */
32932
+ get restoreRetryCompletion() {
32933
+ return this._restoreRetryCompletion;
32934
+ }
32935
+ /** Devices that exhausted the retry bound this process lifetime. */
32936
+ get permanentRestoreFailures() {
32937
+ return [...this._permanentRestoreFailures.values()];
32938
+ }
32939
+ /** One-line operator-facing summary for `getStatus().error`, or
32940
+ * `null` when every device restored. */
32941
+ restoreFailureSummary() {
32942
+ if (this._permanentRestoreFailures.size === 0) return null;
32943
+ const ids = [...this._permanentRestoreFailures.keys()].join(", ");
32944
+ return `${this._permanentRestoreFailures.size} device(s) permanently failed restore (deviceIds: ${ids}) — restart the ${this.providerName} provider to retry`;
32945
+ }
32946
+ cancelRestoreRetries() {
32947
+ this._restoreRetryScheduler?.cancel();
32948
+ this._restoreRetryScheduler = null;
32949
+ }
32950
+ recordPermanentRestoreFailure(failure) {
32951
+ this._permanentRestoreFailures.set(failure.deviceId, failure);
32952
+ this.ctx.logger.error("Device restore permanently failed — its capabilities will not register until the provider restarts", {
32953
+ tags: {
32954
+ deviceId: failure.deviceId,
32955
+ stableId: failure.stableId
32956
+ },
32957
+ meta: {
32958
+ type: failure.type,
32959
+ attempts: failure.attempts,
32960
+ error: failure.lastError
32961
+ }
32962
+ });
32963
+ }
32964
+ scheduleRestoreRetries(failures, attempt) {
32965
+ const scheduler = new DeviceRestoreRetryScheduler({
32966
+ logger: this.ctx.logger,
32967
+ delaysMs: this.restoreRetryDelaysMs,
32968
+ concurrency: this.restoreRetryConcurrency,
32969
+ attempt,
32970
+ onPermanentFailure: (failure) => this.recordPermanentRestoreFailure(failure)
32971
+ });
32972
+ this._restoreRetryScheduler = scheduler;
32973
+ this._restoreRetryCompletion = scheduler.run(failures).then(() => void 0).catch((err) => {
32974
+ this.ctx.logger.error("Restore retry scheduler crashed", { meta: { error: err instanceof Error ? err.message : String(err) } });
32975
+ });
32976
+ }
32977
+ /**
32978
+ * Tear down and reconstruct ONE device from its persisted rows — the
32979
+ * `deviceProvider.reloadDevice` cap method. Persistence is never touched,
32980
+ * and no other device this provider owns is disturbed.
32981
+ *
32982
+ * Keyed by `stableId` because the caller's whole reason to be here is that
32983
+ * the NUMERIC id changed (`deviceManager.migrateDevice` swapped it): the
32984
+ * fresh instance resolves its id through `allocateDeviceId`, which returns
32985
+ * whatever number the row carries NOW. The teardown is `decommission` —
32986
+ * exactly what a graceful shutdown runs per device (fires `removeDevice()`,
32987
+ * unregisters native caps, drops the registry entry) — and the rebuild is
32988
+ * the boot restore's own `create()` path, including its pass 2: first-class
32989
+ * children (hub-adopted cameras under an NVR) are decommissioned with the
32990
+ * parent by the cascade and must be re-created explicitly, because only
32991
+ * accessory children come back through `getAccessoryChildren()`.
32992
+ *
32993
+ * Reloading an accessory child directly is refused (no device class) —
32994
+ * reload its parent instead.
32995
+ */
32996
+ async reloadDevice(input) {
32997
+ const { stableId } = input;
32998
+ const devices = this.ctx.kernel.devices;
32999
+ if (!devices) throw new Error(`${this.providerName}: kernel.devices unavailable — cannot reload`);
33000
+ const live = (await devices.getAll()).find((d) => d.stableId === stableId);
33001
+ if (live) await devices.decommission(live.id);
33002
+ const { id } = await this.ctx.api.deviceManager.allocateDeviceId.mutate({
33003
+ addonId: this.addonId,
33004
+ stableId
33005
+ });
33006
+ const meta = await this.ctx.api.deviceManager.loadMeta.query({ deviceId: id });
33007
+ if (meta === null) throw new Error(`${this.providerName}: no persisted meta for "${stableId}" (id ${id}) — cannot reload`);
33008
+ const deviceType = Object.values(DeviceType).find((t) => t === meta.type);
33009
+ const Class = deviceType !== void 0 ? this.deviceClasses[deviceType] : void 0;
33010
+ if (!Class) throw new Error(`${this.providerName}: no device class for type "${meta.type}" — "${stableId}" is an accessory child; reload its parent instead`);
33011
+ await devices.create(stableId, Class, {}, meta.parentDeviceId ?? null);
33012
+ const rows = await this.ctx.api.deviceManager.listPersistedByAddon.query({ addonId: this.addonId });
33013
+ for (const row of rows) {
33014
+ if (row.parentDeviceId !== id) continue;
33015
+ const childType = Object.values(DeviceType).find((t) => t === row.type);
33016
+ const ChildClass = childType !== void 0 ? this.deviceClasses[childType] : void 0;
33017
+ if (!ChildClass) continue;
33018
+ try {
33019
+ await devices.create(row.stableId, ChildClass, {}, id);
33020
+ } catch (err) {
33021
+ this.ctx.logger.warn("reloadDevice: failed to re-create first-class child", {
33022
+ tags: {
33023
+ deviceId: row.id,
33024
+ stableId: row.stableId
33025
+ },
33026
+ meta: {
33027
+ parentDeviceId: id,
33028
+ error: err instanceof Error ? err.message : String(err)
33029
+ }
33030
+ });
33031
+ }
33032
+ }
33033
+ this.ctx.logger.info("device reloaded in place from persisted rows", {
33034
+ tags: { deviceId: id },
33035
+ meta: {
33036
+ stableId,
33037
+ type: meta.type
33038
+ }
33039
+ });
33040
+ return { deviceId: id };
32733
33041
  }
32734
33042
  /**
32735
33043
  * Restore devices from persisted state. Two-pass:
@@ -32755,55 +33063,108 @@ var BaseDeviceProvider = class extends BaseAddon {
32755
33063
  * accessory-spawn flow handles via the parent's
32756
33064
  * `getAccessoryChildren()`. Override only when the default doesn't
32757
33065
  * fit.
33066
+ *
33067
+ * A row that fails either pass is NOT terminal (D347): it is handed
33068
+ * to a bounded background retry (`DeviceRestoreRetryScheduler`).
33069
+ * Only after the bound is exhausted is the device marked permanently
33070
+ * failed — logged at ERROR with `tags.deviceId` and surfaced via
33071
+ * `getStatus().error`.
32758
33072
  */
32759
33073
  async onRestoreDevices(savedDevices) {
32760
33074
  const restored = /* @__PURE__ */ new Set();
33075
+ const failures = [];
33076
+ const attemptRestore = async (saved) => {
33077
+ if (restored.has(saved.id)) return;
33078
+ const Class = this.deviceClasses[saved.type];
33079
+ if (!Class) throw new Error(`no device class registered for type "${saved.type}"`);
33080
+ if (saved.parentDeviceId !== null && !restored.has(saved.parentDeviceId)) throw new Error(`parent device ${saved.parentDeviceId} not restored`);
33081
+ await this.ctx.kernel.devices.create(saved.stableId, Class, {}, saved.parentDeviceId);
33082
+ restored.add(saved.id);
33083
+ };
32761
33084
  const topLevel = savedDevices.filter((saved) => saved.parentDeviceId === null);
32762
33085
  const restoreOne = async (saved) => {
32763
- const Class = this.deviceClasses[saved.type];
32764
- if (!Class) {
33086
+ if (!this.deviceClasses[saved.type]) {
32765
33087
  this.ctx.logger.warn("No device class registered for restored type — skipping", {
32766
- tags: { stableId: saved.stableId },
33088
+ tags: {
33089
+ deviceId: saved.id,
33090
+ stableId: saved.stableId
33091
+ },
32767
33092
  meta: { type: saved.type }
32768
33093
  });
32769
33094
  return;
32770
33095
  }
32771
33096
  try {
32772
- await this.ctx.kernel.devices.create(saved.stableId, Class, {});
32773
- restored.add(saved.id);
33097
+ await attemptRestore(saved);
32774
33098
  } catch (err) {
32775
- this.ctx.logger.warn("Failed to restore device", {
32776
- tags: { stableId: saved.stableId },
33099
+ const error = err instanceof Error ? err.message : String(err);
33100
+ this.ctx.logger.warn("Failed to restore device — bounded retry scheduled", {
33101
+ tags: {
33102
+ deviceId: saved.id,
33103
+ stableId: saved.stableId
33104
+ },
32777
33105
  meta: {
32778
33106
  type: saved.type,
32779
- error: err instanceof Error ? err.message : String(err)
33107
+ attempt: 1,
33108
+ error
32780
33109
  }
32781
33110
  });
33111
+ failures.push({
33112
+ saved,
33113
+ error
33114
+ });
32782
33115
  }
32783
33116
  };
32784
33117
  await Promise.all(topLevel.map((saved) => restoreOne(saved)));
33118
+ const failedTopLevelIds = new Set(failures.map((failure) => failure.saved.id));
32785
33119
  const childRows = savedDevices.filter((s) => s.parentDeviceId !== null);
32786
33120
  for (const saved of childRows) {
32787
- const Class = this.deviceClasses[saved.type];
32788
- if (!Class) continue;
33121
+ if (!this.deviceClasses[saved.type]) continue;
32789
33122
  if (saved.parentDeviceId === null) continue;
32790
- if (!restored.has(saved.parentDeviceId)) continue;
32791
- try {
32792
- await this.ctx.kernel.devices.create(saved.stableId, Class, {}, saved.parentDeviceId);
32793
- restored.add(saved.id);
32794
- } catch (err) {
32795
- this.ctx.logger.warn("Failed to restore hub-adopted child", {
33123
+ if (restored.has(saved.parentDeviceId)) {
33124
+ try {
33125
+ await attemptRestore(saved);
33126
+ } catch (err) {
33127
+ const error = err instanceof Error ? err.message : String(err);
33128
+ this.ctx.logger.warn("Failed to restore hub-adopted child — bounded retry scheduled", {
33129
+ tags: {
33130
+ deviceId: saved.id,
33131
+ stableId: saved.stableId,
33132
+ parentDeviceId: saved.parentDeviceId
33133
+ },
33134
+ meta: {
33135
+ type: saved.type,
33136
+ attempt: 1,
33137
+ error
33138
+ }
33139
+ });
33140
+ failures.push({
33141
+ saved,
33142
+ error
33143
+ });
33144
+ }
33145
+ continue;
33146
+ }
33147
+ if (failedTopLevelIds.has(saved.parentDeviceId)) {
33148
+ this.ctx.logger.warn("Hub-adopted child deferred — parent failed initial restore", {
32796
33149
  tags: {
33150
+ deviceId: saved.id,
32797
33151
  stableId: saved.stableId,
32798
33152
  parentDeviceId: saved.parentDeviceId
32799
33153
  },
32800
- meta: {
32801
- type: saved.type,
32802
- error: err instanceof Error ? err.message : String(err)
32803
- }
33154
+ meta: { type: saved.type }
33155
+ });
33156
+ failures.push({
33157
+ saved,
33158
+ error: `parent device ${saved.parentDeviceId} not restored`
32804
33159
  });
33160
+ continue;
32805
33161
  }
32806
33162
  }
33163
+ if (failures.length > 0) this.scheduleRestoreRetries(failures, attemptRestore);
33164
+ return {
33165
+ restoredCount: restored.size,
33166
+ failedCount: failures.length
33167
+ };
32807
33168
  }
32808
33169
  /** Convert an IDevice to the flat DeviceSummary for the cap router. */
32809
33170
  toSummary(device) {
@@ -34566,6 +34927,12 @@ Object.freeze({
34566
34927
  addonId: null,
34567
34928
  access: "view"
34568
34929
  },
34930
+ "deviceProvider.reloadDevice": {
34931
+ capName: "device-provider",
34932
+ capScope: "system",
34933
+ addonId: null,
34934
+ access: "create"
34935
+ },
34569
34936
  "deviceProvider.start": {
34570
34937
  capName: "device-provider",
34571
34938
  capScope: "system",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@camstack/addon-provider-homematic",
3
- "version": "1.2.60",
3
+ "version": "1.2.61",
4
4
  "description": "Homematic / HomematicIP (CCU3 / RaspberryMatic) device-provider addon for CamStack — wraps the nodehomematic library",
5
5
  "keywords": [
6
6
  "camstack",