@camstack/addon-provider-tuya 0.2.59 → 0.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.
- package/dist/addon.js +428 -25
- package/dist/addon.mjs +428 -25
- package/package.json +1 -1
package/dist/addon.js
CHANGED
|
@@ -13593,7 +13593,26 @@ var DiscoveryCandidateSchema = object({
|
|
|
13593
13593
|
* identity ahead of adoption. Rendering metadata (unit, precision)
|
|
13594
13594
|
* flows live through the cap STATUS SLICE after adoption.
|
|
13595
13595
|
*/
|
|
13596
|
-
sourceInfo: SourceInfoSchema.optional()
|
|
13596
|
+
sourceInfo: SourceInfoSchema.optional(),
|
|
13597
|
+
/**
|
|
13598
|
+
* Set when this candidate is a device the provider ALREADY owns.
|
|
13599
|
+
*
|
|
13600
|
+
* A scan cannot generally produce the identity a device was onboarded under
|
|
13601
|
+
* (Reolink keys on `mac-<mac>`, learned at adopt time), so a stableId
|
|
13602
|
+
* comparison never matches and an owned device looks addable. Re-adopting one
|
|
13603
|
+
* overwrites its config with scan-derived values — that is how a Home Hub's
|
|
13604
|
+
* Baichuan port was overwritten with its ONVIF port, taking the hub and its
|
|
13605
|
+
* three child cameras offline for four hours.
|
|
13606
|
+
*
|
|
13607
|
+
* A provider that can recognise its own devices says so here. Absent means
|
|
13608
|
+
* "not recognised", which is not the same as "known to be new" — a provider
|
|
13609
|
+
* that cannot tell simply never sets it.
|
|
13610
|
+
*/
|
|
13611
|
+
alreadyOnboarded: boolean().optional(),
|
|
13612
|
+
/** Numeric id of the device this candidate was matched to. Set with `alreadyOnboarded`. */
|
|
13613
|
+
onboardedDeviceId: number().optional(),
|
|
13614
|
+
/** Operator-facing name of the matched device, so the UI can say WHICH one it is. */
|
|
13615
|
+
onboardedName: string().optional()
|
|
13597
13616
|
});
|
|
13598
13617
|
/**
|
|
13599
13618
|
* Flat device summary returned by `createDevice` / `adoptDiscoveredDevice`.
|
|
@@ -13649,6 +13668,35 @@ var deviceProviderCapability = {
|
|
|
13649
13668
|
name: string(),
|
|
13650
13669
|
type: string()
|
|
13651
13670
|
}))),
|
|
13671
|
+
/**
|
|
13672
|
+
* Tear down and reconstruct ONE device in place from its persisted rows —
|
|
13673
|
+
* touching no other device this provider owns.
|
|
13674
|
+
*
|
|
13675
|
+
* The primitive `deviceManager.migrateDevice` uses to flush the two
|
|
13676
|
+
* migrated numbers: after `swapIds` the runner's live instance still
|
|
13677
|
+
* carries the PRE-swap numeric id (baked into the object, its native-cap
|
|
13678
|
+
* registrations and its log tags), and a live object cannot be renumbered.
|
|
13679
|
+
* Before this method the only flush was restarting the whole owning addon
|
|
13680
|
+
* — which took every camera the provider owns down with it (28 devices
|
|
13681
|
+
* for one migrated camera, measured 2026-09-04, and the morning of the
|
|
13682
|
+
* same day ~27 devices' native caps did not come back on their own).
|
|
13683
|
+
*
|
|
13684
|
+
* Keyed by `stableId`, deliberately: the numeric id is exactly the thing
|
|
13685
|
+
* that changes. The reply carries the id the device answers on NOW.
|
|
13686
|
+
* Implemented once in `BaseDeviceProvider` — decommission the live
|
|
13687
|
+
* instance (if any), then re-create from the persisted row: the same
|
|
13688
|
+
* teardown/rehydrate pair every graceful shutdown + boot already uses.
|
|
13689
|
+
* An RPC, never an event: a dropped event would leave the runner writing
|
|
13690
|
+
* against the wrong camera (D8).
|
|
13691
|
+
*
|
|
13692
|
+
* Construction can dial hardware, and the migrated source is
|
|
13693
|
+
* characteristically dead — the timeout covers a full activate window
|
|
13694
|
+
* rather than the 60 s default.
|
|
13695
|
+
*/
|
|
13696
|
+
reloadDevice: method(object({ stableId: string() }), object({ deviceId: number() }), {
|
|
13697
|
+
kind: "mutation",
|
|
13698
|
+
timeoutMs: 3 * 6e4
|
|
13699
|
+
}),
|
|
13652
13700
|
supportsDiscovery: method(object({}), boolean()),
|
|
13653
13701
|
/**
|
|
13654
13702
|
* Run a network scan. `params` carries optional provider-specific scan
|
|
@@ -13976,7 +14024,8 @@ method(object({
|
|
|
13976
14024
|
targetId: number()
|
|
13977
14025
|
}), MigrateDeviceResultSchema, {
|
|
13978
14026
|
kind: "mutation",
|
|
13979
|
-
auth: "admin"
|
|
14027
|
+
auth: "admin",
|
|
14028
|
+
timeoutMs: 12 * 6e4
|
|
13980
14029
|
}), 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({
|
|
13981
14030
|
deviceId: number(),
|
|
13982
14031
|
name: string()
|
|
@@ -33340,6 +33389,147 @@ var BaseDevice = class {
|
|
|
33340
33389
|
}
|
|
33341
33390
|
};
|
|
33342
33391
|
/**
|
|
33392
|
+
* Delays before retry rounds 1..N — the round count IS the bound.
|
|
33393
|
+
* 10 s catches "the hub was busy for a moment"; the full schedule
|
|
33394
|
+
* (10 + 30 + 90 s of waiting, plus up to one 60 s transport timeout
|
|
33395
|
+
* per attempt) covers a device-manager lock held for minutes — the
|
|
33396
|
+
* 2026-09-04 outage's migration hold was ~3.5 min.
|
|
33397
|
+
*/
|
|
33398
|
+
var DEVICE_RESTORE_RETRY_DELAYS_MS = [
|
|
33399
|
+
1e4,
|
|
33400
|
+
3e4,
|
|
33401
|
+
9e4
|
|
33402
|
+
];
|
|
33403
|
+
/** Abortable sleep — resolves early (never rejects) on abort. */
|
|
33404
|
+
function sleep$1(ms, signal) {
|
|
33405
|
+
return new Promise((resolve) => {
|
|
33406
|
+
if (signal.aborted) {
|
|
33407
|
+
resolve();
|
|
33408
|
+
return;
|
|
33409
|
+
}
|
|
33410
|
+
const onAbort = () => {
|
|
33411
|
+
clearTimeout(timer);
|
|
33412
|
+
resolve();
|
|
33413
|
+
};
|
|
33414
|
+
const timer = setTimeout(() => {
|
|
33415
|
+
signal.removeEventListener("abort", onAbort);
|
|
33416
|
+
resolve();
|
|
33417
|
+
}, ms);
|
|
33418
|
+
timer.unref?.();
|
|
33419
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
33420
|
+
});
|
|
33421
|
+
}
|
|
33422
|
+
/** Drain `items` through at most `width` concurrent lanes. `fn` must
|
|
33423
|
+
* not reject (callers wrap their own try/catch). */
|
|
33424
|
+
async function runWithConcurrency(items, width, fn) {
|
|
33425
|
+
const queue = [...items];
|
|
33426
|
+
const laneCount = Math.max(1, Math.min(width, queue.length));
|
|
33427
|
+
const lane = async () => {
|
|
33428
|
+
for (;;) {
|
|
33429
|
+
const item = queue.shift();
|
|
33430
|
+
if (item === void 0) return;
|
|
33431
|
+
await fn(item);
|
|
33432
|
+
}
|
|
33433
|
+
};
|
|
33434
|
+
await Promise.all(Array.from({ length: laneCount }, lane));
|
|
33435
|
+
}
|
|
33436
|
+
var DeviceRestoreRetryScheduler = class {
|
|
33437
|
+
#logger;
|
|
33438
|
+
#attempt;
|
|
33439
|
+
#onPermanentFailure;
|
|
33440
|
+
#delaysMs;
|
|
33441
|
+
#concurrency;
|
|
33442
|
+
#now;
|
|
33443
|
+
#abort = new AbortController();
|
|
33444
|
+
constructor(options) {
|
|
33445
|
+
this.#logger = options.logger;
|
|
33446
|
+
this.#attempt = options.attempt;
|
|
33447
|
+
this.#onPermanentFailure = options.onPermanentFailure;
|
|
33448
|
+
this.#delaysMs = options.delaysMs ?? DEVICE_RESTORE_RETRY_DELAYS_MS;
|
|
33449
|
+
this.#concurrency = options.concurrency ?? 4;
|
|
33450
|
+
this.#now = options.now ?? Date.now;
|
|
33451
|
+
}
|
|
33452
|
+
/** Stop retrying (shutdown). Pending entries are NOT marked
|
|
33453
|
+
* permanently failed — the next boot restores them from disk. */
|
|
33454
|
+
cancel() {
|
|
33455
|
+
this.#abort.abort();
|
|
33456
|
+
}
|
|
33457
|
+
/**
|
|
33458
|
+
* Run the bounded retry rounds. Resolves when every entry has either
|
|
33459
|
+
* restored, been marked permanently failed, or the scheduler was
|
|
33460
|
+
* cancelled. Never rejects.
|
|
33461
|
+
*/
|
|
33462
|
+
async run(initialFailures) {
|
|
33463
|
+
let pending = initialFailures.map((failure) => ({
|
|
33464
|
+
saved: failure.saved,
|
|
33465
|
+
lastError: failure.error,
|
|
33466
|
+
attempts: 1
|
|
33467
|
+
}));
|
|
33468
|
+
for (let round = 0; round < this.#delaysMs.length; round += 1) {
|
|
33469
|
+
if (pending.length === 0 || this.#abort.signal.aborted) break;
|
|
33470
|
+
await sleep$1(this.#delaysMs[round] ?? 0, this.#abort.signal);
|
|
33471
|
+
if (this.#abort.signal.aborted) break;
|
|
33472
|
+
pending = await this.#runRound(pending, round);
|
|
33473
|
+
}
|
|
33474
|
+
if (this.#abort.signal.aborted) return [];
|
|
33475
|
+
const terminal = pending.map((entry) => ({
|
|
33476
|
+
deviceId: entry.saved.id,
|
|
33477
|
+
stableId: entry.saved.stableId,
|
|
33478
|
+
type: String(entry.saved.type),
|
|
33479
|
+
attempts: entry.attempts,
|
|
33480
|
+
lastError: entry.lastError,
|
|
33481
|
+
failedAt: this.#now()
|
|
33482
|
+
}));
|
|
33483
|
+
for (const failure of terminal) this.#onPermanentFailure(failure);
|
|
33484
|
+
return terminal;
|
|
33485
|
+
}
|
|
33486
|
+
/** One retry round: parents first (phase 0), then hub-adopted
|
|
33487
|
+
* children (phase 1) — a child's attempt depends on its parent
|
|
33488
|
+
* having landed, exactly like the initial two-pass restore. */
|
|
33489
|
+
async #runRound(pending, round) {
|
|
33490
|
+
const next = [];
|
|
33491
|
+
const parents = pending.filter((entry) => entry.saved.parentDeviceId === null);
|
|
33492
|
+
const children = pending.filter((entry) => entry.saved.parentDeviceId !== null);
|
|
33493
|
+
for (const phase of [parents, children]) await runWithConcurrency(phase, this.#concurrency, async (entry) => {
|
|
33494
|
+
if (this.#abort.signal.aborted) {
|
|
33495
|
+
next.push(entry);
|
|
33496
|
+
return;
|
|
33497
|
+
}
|
|
33498
|
+
const attemptNo = entry.attempts + 1;
|
|
33499
|
+
try {
|
|
33500
|
+
await this.#attempt(entry.saved);
|
|
33501
|
+
this.#logger.info("Device restored on retry", {
|
|
33502
|
+
tags: {
|
|
33503
|
+
deviceId: entry.saved.id,
|
|
33504
|
+
stableId: entry.saved.stableId
|
|
33505
|
+
},
|
|
33506
|
+
meta: { attempt: attemptNo }
|
|
33507
|
+
});
|
|
33508
|
+
} catch (err) {
|
|
33509
|
+
const lastError = err instanceof Error ? err.message : String(err);
|
|
33510
|
+
const remainingRetries = this.#delaysMs.length - (round + 1);
|
|
33511
|
+
this.#logger.warn("Device restore retry failed", {
|
|
33512
|
+
tags: {
|
|
33513
|
+
deviceId: entry.saved.id,
|
|
33514
|
+
stableId: entry.saved.stableId
|
|
33515
|
+
},
|
|
33516
|
+
meta: {
|
|
33517
|
+
attempt: attemptNo,
|
|
33518
|
+
remainingRetries,
|
|
33519
|
+
error: lastError
|
|
33520
|
+
}
|
|
33521
|
+
});
|
|
33522
|
+
next.push({
|
|
33523
|
+
saved: entry.saved,
|
|
33524
|
+
lastError,
|
|
33525
|
+
attempts: attemptNo
|
|
33526
|
+
});
|
|
33527
|
+
}
|
|
33528
|
+
});
|
|
33529
|
+
return next;
|
|
33530
|
+
}
|
|
33531
|
+
};
|
|
33532
|
+
/**
|
|
33343
33533
|
* Convert an IDevice to the flat DeviceSummary shape expected by the
|
|
33344
33534
|
* device-provider cap router. Shared across all providers.
|
|
33345
33535
|
*/
|
|
@@ -33388,6 +33578,7 @@ var BaseDeviceProvider = class extends BaseAddon {
|
|
|
33388
33578
|
}];
|
|
33389
33579
|
}
|
|
33390
33580
|
async onShutdown() {
|
|
33581
|
+
this.cancelRestoreRetries();
|
|
33391
33582
|
const devices = await this.ctx.kernel.devices?.getAll() ?? [];
|
|
33392
33583
|
for (const device of devices) try {
|
|
33393
33584
|
await this.ctx.kernel.devices?.decommission(device.id);
|
|
@@ -33405,9 +33596,16 @@ var BaseDeviceProvider = class extends BaseAddon {
|
|
|
33405
33596
|
async start() {}
|
|
33406
33597
|
async stop() {}
|
|
33407
33598
|
async getStatus() {
|
|
33599
|
+
const all = await this.ctx.kernel.devices?.getAll() ?? [];
|
|
33600
|
+
const summary = this.restoreFailureSummary();
|
|
33601
|
+
if (summary === null) return {
|
|
33602
|
+
connected: true,
|
|
33603
|
+
deviceCount: all.length
|
|
33604
|
+
};
|
|
33408
33605
|
return {
|
|
33409
33606
|
connected: true,
|
|
33410
|
-
deviceCount:
|
|
33607
|
+
deviceCount: all.length,
|
|
33608
|
+
error: summary
|
|
33411
33609
|
};
|
|
33412
33610
|
}
|
|
33413
33611
|
async getDevices() {
|
|
@@ -33497,8 +33695,137 @@ var BaseDeviceProvider = class extends BaseAddon {
|
|
|
33497
33695
|
};
|
|
33498
33696
|
}
|
|
33499
33697
|
async restoreDevices(savedDevices) {
|
|
33500
|
-
await this.onRestoreDevices(savedDevices);
|
|
33501
|
-
if (savedDevices.length
|
|
33698
|
+
const report = await this.onRestoreDevices(savedDevices);
|
|
33699
|
+
if (savedDevices.length === 0) return;
|
|
33700
|
+
if (report && report.failedCount > 0) {
|
|
33701
|
+
this.ctx.logger.warn(`Restored ${report.restoredCount}/${savedDevices.length} ${this.providerName} device(s) — ${report.failedCount} failed, bounded retry scheduled`);
|
|
33702
|
+
return;
|
|
33703
|
+
}
|
|
33704
|
+
const restoredCount = report ? report.restoredCount : savedDevices.length;
|
|
33705
|
+
this.ctx.logger.info(`Restored ${restoredCount} ${this.providerName} device(s)`);
|
|
33706
|
+
}
|
|
33707
|
+
/** Retry schedule. Overridable (tests use millisecond delays). */
|
|
33708
|
+
restoreRetryDelaysMs = DEVICE_RESTORE_RETRY_DELAYS_MS;
|
|
33709
|
+
/** Retry lane width. See `device-restore-retry.ts` for why retries
|
|
33710
|
+
* never re-stampede full-width while the initial pass does (D167). */
|
|
33711
|
+
restoreRetryConcurrency = 4;
|
|
33712
|
+
_restoreRetryScheduler = null;
|
|
33713
|
+
_restoreRetryCompletion = null;
|
|
33714
|
+
_permanentRestoreFailures = /* @__PURE__ */ new Map();
|
|
33715
|
+
/** Settles when the background retry rounds finish (or `null` when
|
|
33716
|
+
* nothing failed). Exposed for tests and subclass diagnostics —
|
|
33717
|
+
* boot NEVER awaits this: the runner's post-init handshake goes out
|
|
33718
|
+
* with the devices that restored, and a late success is announced
|
|
33719
|
+
* through the `native-cap-change` → `updateCaps` path. */
|
|
33720
|
+
get restoreRetryCompletion() {
|
|
33721
|
+
return this._restoreRetryCompletion;
|
|
33722
|
+
}
|
|
33723
|
+
/** Devices that exhausted the retry bound this process lifetime. */
|
|
33724
|
+
get permanentRestoreFailures() {
|
|
33725
|
+
return [...this._permanentRestoreFailures.values()];
|
|
33726
|
+
}
|
|
33727
|
+
/** One-line operator-facing summary for `getStatus().error`, or
|
|
33728
|
+
* `null` when every device restored. */
|
|
33729
|
+
restoreFailureSummary() {
|
|
33730
|
+
if (this._permanentRestoreFailures.size === 0) return null;
|
|
33731
|
+
const ids = [...this._permanentRestoreFailures.keys()].join(", ");
|
|
33732
|
+
return `${this._permanentRestoreFailures.size} device(s) permanently failed restore (deviceIds: ${ids}) — restart the ${this.providerName} provider to retry`;
|
|
33733
|
+
}
|
|
33734
|
+
cancelRestoreRetries() {
|
|
33735
|
+
this._restoreRetryScheduler?.cancel();
|
|
33736
|
+
this._restoreRetryScheduler = null;
|
|
33737
|
+
}
|
|
33738
|
+
recordPermanentRestoreFailure(failure) {
|
|
33739
|
+
this._permanentRestoreFailures.set(failure.deviceId, failure);
|
|
33740
|
+
this.ctx.logger.error("Device restore permanently failed — its capabilities will not register until the provider restarts", {
|
|
33741
|
+
tags: {
|
|
33742
|
+
deviceId: failure.deviceId,
|
|
33743
|
+
stableId: failure.stableId
|
|
33744
|
+
},
|
|
33745
|
+
meta: {
|
|
33746
|
+
type: failure.type,
|
|
33747
|
+
attempts: failure.attempts,
|
|
33748
|
+
error: failure.lastError
|
|
33749
|
+
}
|
|
33750
|
+
});
|
|
33751
|
+
}
|
|
33752
|
+
scheduleRestoreRetries(failures, attempt) {
|
|
33753
|
+
const scheduler = new DeviceRestoreRetryScheduler({
|
|
33754
|
+
logger: this.ctx.logger,
|
|
33755
|
+
delaysMs: this.restoreRetryDelaysMs,
|
|
33756
|
+
concurrency: this.restoreRetryConcurrency,
|
|
33757
|
+
attempt,
|
|
33758
|
+
onPermanentFailure: (failure) => this.recordPermanentRestoreFailure(failure)
|
|
33759
|
+
});
|
|
33760
|
+
this._restoreRetryScheduler = scheduler;
|
|
33761
|
+
this._restoreRetryCompletion = scheduler.run(failures).then(() => void 0).catch((err) => {
|
|
33762
|
+
this.ctx.logger.error("Restore retry scheduler crashed", { meta: { error: err instanceof Error ? err.message : String(err) } });
|
|
33763
|
+
});
|
|
33764
|
+
}
|
|
33765
|
+
/**
|
|
33766
|
+
* Tear down and reconstruct ONE device from its persisted rows — the
|
|
33767
|
+
* `deviceProvider.reloadDevice` cap method. Persistence is never touched,
|
|
33768
|
+
* and no other device this provider owns is disturbed.
|
|
33769
|
+
*
|
|
33770
|
+
* Keyed by `stableId` because the caller's whole reason to be here is that
|
|
33771
|
+
* the NUMERIC id changed (`deviceManager.migrateDevice` swapped it): the
|
|
33772
|
+
* fresh instance resolves its id through `allocateDeviceId`, which returns
|
|
33773
|
+
* whatever number the row carries NOW. The teardown is `decommission` —
|
|
33774
|
+
* exactly what a graceful shutdown runs per device (fires `removeDevice()`,
|
|
33775
|
+
* unregisters native caps, drops the registry entry) — and the rebuild is
|
|
33776
|
+
* the boot restore's own `create()` path, including its pass 2: first-class
|
|
33777
|
+
* children (hub-adopted cameras under an NVR) are decommissioned with the
|
|
33778
|
+
* parent by the cascade and must be re-created explicitly, because only
|
|
33779
|
+
* accessory children come back through `getAccessoryChildren()`.
|
|
33780
|
+
*
|
|
33781
|
+
* Reloading an accessory child directly is refused (no device class) —
|
|
33782
|
+
* reload its parent instead.
|
|
33783
|
+
*/
|
|
33784
|
+
async reloadDevice(input) {
|
|
33785
|
+
const { stableId } = input;
|
|
33786
|
+
const devices = this.ctx.kernel.devices;
|
|
33787
|
+
if (!devices) throw new Error(`${this.providerName}: kernel.devices unavailable — cannot reload`);
|
|
33788
|
+
const live = (await devices.getAll()).find((d) => d.stableId === stableId);
|
|
33789
|
+
if (live) await devices.decommission(live.id);
|
|
33790
|
+
const { id } = await this.ctx.api.deviceManager.allocateDeviceId.mutate({
|
|
33791
|
+
addonId: this.addonId,
|
|
33792
|
+
stableId
|
|
33793
|
+
});
|
|
33794
|
+
const meta = await this.ctx.api.deviceManager.loadMeta.query({ deviceId: id });
|
|
33795
|
+
if (meta === null) throw new Error(`${this.providerName}: no persisted meta for "${stableId}" (id ${id}) — cannot reload`);
|
|
33796
|
+
const deviceType = Object.values(DeviceType).find((t) => t === meta.type);
|
|
33797
|
+
const Class = deviceType !== void 0 ? this.deviceClasses[deviceType] : void 0;
|
|
33798
|
+
if (!Class) throw new Error(`${this.providerName}: no device class for type "${meta.type}" — "${stableId}" is an accessory child; reload its parent instead`);
|
|
33799
|
+
await devices.create(stableId, Class, {}, meta.parentDeviceId ?? null);
|
|
33800
|
+
const rows = await this.ctx.api.deviceManager.listPersistedByAddon.query({ addonId: this.addonId });
|
|
33801
|
+
for (const row of rows) {
|
|
33802
|
+
if (row.parentDeviceId !== id) continue;
|
|
33803
|
+
const childType = Object.values(DeviceType).find((t) => t === row.type);
|
|
33804
|
+
const ChildClass = childType !== void 0 ? this.deviceClasses[childType] : void 0;
|
|
33805
|
+
if (!ChildClass) continue;
|
|
33806
|
+
try {
|
|
33807
|
+
await devices.create(row.stableId, ChildClass, {}, id);
|
|
33808
|
+
} catch (err) {
|
|
33809
|
+
this.ctx.logger.warn("reloadDevice: failed to re-create first-class child", {
|
|
33810
|
+
tags: {
|
|
33811
|
+
deviceId: row.id,
|
|
33812
|
+
stableId: row.stableId
|
|
33813
|
+
},
|
|
33814
|
+
meta: {
|
|
33815
|
+
parentDeviceId: id,
|
|
33816
|
+
error: err instanceof Error ? err.message : String(err)
|
|
33817
|
+
}
|
|
33818
|
+
});
|
|
33819
|
+
}
|
|
33820
|
+
}
|
|
33821
|
+
this.ctx.logger.info("device reloaded in place from persisted rows", {
|
|
33822
|
+
tags: { deviceId: id },
|
|
33823
|
+
meta: {
|
|
33824
|
+
stableId,
|
|
33825
|
+
type: meta.type
|
|
33826
|
+
}
|
|
33827
|
+
});
|
|
33828
|
+
return { deviceId: id };
|
|
33502
33829
|
}
|
|
33503
33830
|
/**
|
|
33504
33831
|
* Restore devices from persisted state. Two-pass:
|
|
@@ -33524,55 +33851,125 @@ var BaseDeviceProvider = class extends BaseAddon {
|
|
|
33524
33851
|
* accessory-spawn flow handles via the parent's
|
|
33525
33852
|
* `getAccessoryChildren()`. Override only when the default doesn't
|
|
33526
33853
|
* fit.
|
|
33854
|
+
*
|
|
33855
|
+
* A row that fails either pass is NOT terminal (D347): it is handed
|
|
33856
|
+
* to a bounded background retry (`DeviceRestoreRetryScheduler`).
|
|
33857
|
+
* Only after the bound is exhausted is the device marked permanently
|
|
33858
|
+
* failed — logged at ERROR with `tags.deviceId` and surfaced via
|
|
33859
|
+
* `getStatus().error`.
|
|
33527
33860
|
*/
|
|
33861
|
+
/**
|
|
33862
|
+
* Repair a row's PERSISTED config blob immediately before it is restored.
|
|
33863
|
+
* Default: no-op — most providers have nothing to heal.
|
|
33864
|
+
*
|
|
33865
|
+
* This exists because a restored device self-hydrates from the DB: `create()`
|
|
33866
|
+
* passes `{}` and `BaseDevice` parses the stored blob against the device
|
|
33867
|
+
* schema. A blob that lost a REQUIRED field therefore fails restore forever,
|
|
33868
|
+
* and no later pass revisits it — a hub-adopted Reolink camera whose blob had
|
|
33869
|
+
* been emptied failed all four bounded attempts against fields
|
|
33870
|
+
* (`host`, `password`) it inherits from its parent and never dials itself.
|
|
33871
|
+
*
|
|
33872
|
+
* Implementations get every saved row, so a child can read its parent's blob.
|
|
33873
|
+
* A heal that throws is treated like any other restore failure: retried under
|
|
33874
|
+
* the bound, then reported — never swallowed.
|
|
33875
|
+
*/
|
|
33876
|
+
async healSavedConfig(_saved, _allSaved) {}
|
|
33528
33877
|
async onRestoreDevices(savedDevices) {
|
|
33529
33878
|
const restored = /* @__PURE__ */ new Set();
|
|
33879
|
+
const failures = [];
|
|
33880
|
+
const attemptRestore = async (saved) => {
|
|
33881
|
+
if (restored.has(saved.id)) return;
|
|
33882
|
+
const Class = this.deviceClasses[saved.type];
|
|
33883
|
+
if (!Class) throw new Error(`no device class registered for type "${saved.type}"`);
|
|
33884
|
+
if (saved.parentDeviceId !== null && !restored.has(saved.parentDeviceId)) throw new Error(`parent device ${saved.parentDeviceId} not restored`);
|
|
33885
|
+
await this.healSavedConfig(saved, savedDevices);
|
|
33886
|
+
await this.ctx.kernel.devices.create(saved.stableId, Class, {}, saved.parentDeviceId);
|
|
33887
|
+
restored.add(saved.id);
|
|
33888
|
+
};
|
|
33530
33889
|
const topLevel = savedDevices.filter((saved) => saved.parentDeviceId === null);
|
|
33531
33890
|
const restoreOne = async (saved) => {
|
|
33532
|
-
|
|
33533
|
-
if (!Class) {
|
|
33891
|
+
if (!this.deviceClasses[saved.type]) {
|
|
33534
33892
|
this.ctx.logger.warn("No device class registered for restored type — skipping", {
|
|
33535
|
-
tags: {
|
|
33893
|
+
tags: {
|
|
33894
|
+
deviceId: saved.id,
|
|
33895
|
+
stableId: saved.stableId
|
|
33896
|
+
},
|
|
33536
33897
|
meta: { type: saved.type }
|
|
33537
33898
|
});
|
|
33538
33899
|
return;
|
|
33539
33900
|
}
|
|
33540
33901
|
try {
|
|
33541
|
-
await
|
|
33542
|
-
restored.add(saved.id);
|
|
33902
|
+
await attemptRestore(saved);
|
|
33543
33903
|
} catch (err) {
|
|
33544
|
-
|
|
33545
|
-
|
|
33904
|
+
const error = err instanceof Error ? err.message : String(err);
|
|
33905
|
+
this.ctx.logger.warn("Failed to restore device — bounded retry scheduled", {
|
|
33906
|
+
tags: {
|
|
33907
|
+
deviceId: saved.id,
|
|
33908
|
+
stableId: saved.stableId
|
|
33909
|
+
},
|
|
33546
33910
|
meta: {
|
|
33547
33911
|
type: saved.type,
|
|
33548
|
-
|
|
33912
|
+
attempt: 1,
|
|
33913
|
+
error
|
|
33549
33914
|
}
|
|
33550
33915
|
});
|
|
33916
|
+
failures.push({
|
|
33917
|
+
saved,
|
|
33918
|
+
error
|
|
33919
|
+
});
|
|
33551
33920
|
}
|
|
33552
33921
|
};
|
|
33553
33922
|
await Promise.all(topLevel.map((saved) => restoreOne(saved)));
|
|
33923
|
+
const failedTopLevelIds = new Set(failures.map((failure) => failure.saved.id));
|
|
33554
33924
|
const childRows = savedDevices.filter((s) => s.parentDeviceId !== null);
|
|
33555
33925
|
for (const saved of childRows) {
|
|
33556
|
-
|
|
33557
|
-
if (!Class) continue;
|
|
33926
|
+
if (!this.deviceClasses[saved.type]) continue;
|
|
33558
33927
|
if (saved.parentDeviceId === null) continue;
|
|
33559
|
-
if (
|
|
33560
|
-
|
|
33561
|
-
|
|
33562
|
-
|
|
33563
|
-
|
|
33564
|
-
|
|
33928
|
+
if (restored.has(saved.parentDeviceId)) {
|
|
33929
|
+
try {
|
|
33930
|
+
await attemptRestore(saved);
|
|
33931
|
+
} catch (err) {
|
|
33932
|
+
const error = err instanceof Error ? err.message : String(err);
|
|
33933
|
+
this.ctx.logger.warn("Failed to restore hub-adopted child — bounded retry scheduled", {
|
|
33934
|
+
tags: {
|
|
33935
|
+
deviceId: saved.id,
|
|
33936
|
+
stableId: saved.stableId,
|
|
33937
|
+
parentDeviceId: saved.parentDeviceId
|
|
33938
|
+
},
|
|
33939
|
+
meta: {
|
|
33940
|
+
type: saved.type,
|
|
33941
|
+
attempt: 1,
|
|
33942
|
+
error
|
|
33943
|
+
}
|
|
33944
|
+
});
|
|
33945
|
+
failures.push({
|
|
33946
|
+
saved,
|
|
33947
|
+
error
|
|
33948
|
+
});
|
|
33949
|
+
}
|
|
33950
|
+
continue;
|
|
33951
|
+
}
|
|
33952
|
+
if (failedTopLevelIds.has(saved.parentDeviceId)) {
|
|
33953
|
+
this.ctx.logger.warn("Hub-adopted child deferred — parent failed initial restore", {
|
|
33565
33954
|
tags: {
|
|
33955
|
+
deviceId: saved.id,
|
|
33566
33956
|
stableId: saved.stableId,
|
|
33567
33957
|
parentDeviceId: saved.parentDeviceId
|
|
33568
33958
|
},
|
|
33569
|
-
meta: {
|
|
33570
|
-
|
|
33571
|
-
|
|
33572
|
-
|
|
33959
|
+
meta: { type: saved.type }
|
|
33960
|
+
});
|
|
33961
|
+
failures.push({
|
|
33962
|
+
saved,
|
|
33963
|
+
error: `parent device ${saved.parentDeviceId} not restored`
|
|
33573
33964
|
});
|
|
33965
|
+
continue;
|
|
33574
33966
|
}
|
|
33575
33967
|
}
|
|
33968
|
+
if (failures.length > 0) this.scheduleRestoreRetries(failures, attemptRestore);
|
|
33969
|
+
return {
|
|
33970
|
+
restoredCount: restored.size,
|
|
33971
|
+
failedCount: failures.length
|
|
33972
|
+
};
|
|
33576
33973
|
}
|
|
33577
33974
|
/** Convert an IDevice to the flat DeviceSummary for the cap router. */
|
|
33578
33975
|
toSummary(device) {
|
|
@@ -35335,6 +35732,12 @@ Object.freeze({
|
|
|
35335
35732
|
addonId: null,
|
|
35336
35733
|
access: "view"
|
|
35337
35734
|
},
|
|
35735
|
+
"deviceProvider.reloadDevice": {
|
|
35736
|
+
capName: "device-provider",
|
|
35737
|
+
capScope: "system",
|
|
35738
|
+
addonId: null,
|
|
35739
|
+
access: "create"
|
|
35740
|
+
},
|
|
35338
35741
|
"deviceProvider.start": {
|
|
35339
35742
|
capName: "device-provider",
|
|
35340
35743
|
capScope: "system",
|
package/dist/addon.mjs
CHANGED
|
@@ -13592,7 +13592,26 @@ var DiscoveryCandidateSchema = object({
|
|
|
13592
13592
|
* identity ahead of adoption. Rendering metadata (unit, precision)
|
|
13593
13593
|
* flows live through the cap STATUS SLICE after adoption.
|
|
13594
13594
|
*/
|
|
13595
|
-
sourceInfo: SourceInfoSchema.optional()
|
|
13595
|
+
sourceInfo: SourceInfoSchema.optional(),
|
|
13596
|
+
/**
|
|
13597
|
+
* Set when this candidate is a device the provider ALREADY owns.
|
|
13598
|
+
*
|
|
13599
|
+
* A scan cannot generally produce the identity a device was onboarded under
|
|
13600
|
+
* (Reolink keys on `mac-<mac>`, learned at adopt time), so a stableId
|
|
13601
|
+
* comparison never matches and an owned device looks addable. Re-adopting one
|
|
13602
|
+
* overwrites its config with scan-derived values — that is how a Home Hub's
|
|
13603
|
+
* Baichuan port was overwritten with its ONVIF port, taking the hub and its
|
|
13604
|
+
* three child cameras offline for four hours.
|
|
13605
|
+
*
|
|
13606
|
+
* A provider that can recognise its own devices says so here. Absent means
|
|
13607
|
+
* "not recognised", which is not the same as "known to be new" — a provider
|
|
13608
|
+
* that cannot tell simply never sets it.
|
|
13609
|
+
*/
|
|
13610
|
+
alreadyOnboarded: boolean().optional(),
|
|
13611
|
+
/** Numeric id of the device this candidate was matched to. Set with `alreadyOnboarded`. */
|
|
13612
|
+
onboardedDeviceId: number().optional(),
|
|
13613
|
+
/** Operator-facing name of the matched device, so the UI can say WHICH one it is. */
|
|
13614
|
+
onboardedName: string().optional()
|
|
13596
13615
|
});
|
|
13597
13616
|
/**
|
|
13598
13617
|
* Flat device summary returned by `createDevice` / `adoptDiscoveredDevice`.
|
|
@@ -13648,6 +13667,35 @@ var deviceProviderCapability = {
|
|
|
13648
13667
|
name: string(),
|
|
13649
13668
|
type: string()
|
|
13650
13669
|
}))),
|
|
13670
|
+
/**
|
|
13671
|
+
* Tear down and reconstruct ONE device in place from its persisted rows —
|
|
13672
|
+
* touching no other device this provider owns.
|
|
13673
|
+
*
|
|
13674
|
+
* The primitive `deviceManager.migrateDevice` uses to flush the two
|
|
13675
|
+
* migrated numbers: after `swapIds` the runner's live instance still
|
|
13676
|
+
* carries the PRE-swap numeric id (baked into the object, its native-cap
|
|
13677
|
+
* registrations and its log tags), and a live object cannot be renumbered.
|
|
13678
|
+
* Before this method the only flush was restarting the whole owning addon
|
|
13679
|
+
* — which took every camera the provider owns down with it (28 devices
|
|
13680
|
+
* for one migrated camera, measured 2026-09-04, and the morning of the
|
|
13681
|
+
* same day ~27 devices' native caps did not come back on their own).
|
|
13682
|
+
*
|
|
13683
|
+
* Keyed by `stableId`, deliberately: the numeric id is exactly the thing
|
|
13684
|
+
* that changes. The reply carries the id the device answers on NOW.
|
|
13685
|
+
* Implemented once in `BaseDeviceProvider` — decommission the live
|
|
13686
|
+
* instance (if any), then re-create from the persisted row: the same
|
|
13687
|
+
* teardown/rehydrate pair every graceful shutdown + boot already uses.
|
|
13688
|
+
* An RPC, never an event: a dropped event would leave the runner writing
|
|
13689
|
+
* against the wrong camera (D8).
|
|
13690
|
+
*
|
|
13691
|
+
* Construction can dial hardware, and the migrated source is
|
|
13692
|
+
* characteristically dead — the timeout covers a full activate window
|
|
13693
|
+
* rather than the 60 s default.
|
|
13694
|
+
*/
|
|
13695
|
+
reloadDevice: method(object({ stableId: string() }), object({ deviceId: number() }), {
|
|
13696
|
+
kind: "mutation",
|
|
13697
|
+
timeoutMs: 3 * 6e4
|
|
13698
|
+
}),
|
|
13651
13699
|
supportsDiscovery: method(object({}), boolean()),
|
|
13652
13700
|
/**
|
|
13653
13701
|
* Run a network scan. `params` carries optional provider-specific scan
|
|
@@ -13975,7 +14023,8 @@ method(object({
|
|
|
13975
14023
|
targetId: number()
|
|
13976
14024
|
}), MigrateDeviceResultSchema, {
|
|
13977
14025
|
kind: "mutation",
|
|
13978
|
-
auth: "admin"
|
|
14026
|
+
auth: "admin",
|
|
14027
|
+
timeoutMs: 12 * 6e4
|
|
13979
14028
|
}), 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({
|
|
13980
14029
|
deviceId: number(),
|
|
13981
14030
|
name: string()
|
|
@@ -33339,6 +33388,147 @@ var BaseDevice = class {
|
|
|
33339
33388
|
}
|
|
33340
33389
|
};
|
|
33341
33390
|
/**
|
|
33391
|
+
* Delays before retry rounds 1..N — the round count IS the bound.
|
|
33392
|
+
* 10 s catches "the hub was busy for a moment"; the full schedule
|
|
33393
|
+
* (10 + 30 + 90 s of waiting, plus up to one 60 s transport timeout
|
|
33394
|
+
* per attempt) covers a device-manager lock held for minutes — the
|
|
33395
|
+
* 2026-09-04 outage's migration hold was ~3.5 min.
|
|
33396
|
+
*/
|
|
33397
|
+
var DEVICE_RESTORE_RETRY_DELAYS_MS = [
|
|
33398
|
+
1e4,
|
|
33399
|
+
3e4,
|
|
33400
|
+
9e4
|
|
33401
|
+
];
|
|
33402
|
+
/** Abortable sleep — resolves early (never rejects) on abort. */
|
|
33403
|
+
function sleep$1(ms, signal) {
|
|
33404
|
+
return new Promise((resolve) => {
|
|
33405
|
+
if (signal.aborted) {
|
|
33406
|
+
resolve();
|
|
33407
|
+
return;
|
|
33408
|
+
}
|
|
33409
|
+
const onAbort = () => {
|
|
33410
|
+
clearTimeout(timer);
|
|
33411
|
+
resolve();
|
|
33412
|
+
};
|
|
33413
|
+
const timer = setTimeout(() => {
|
|
33414
|
+
signal.removeEventListener("abort", onAbort);
|
|
33415
|
+
resolve();
|
|
33416
|
+
}, ms);
|
|
33417
|
+
timer.unref?.();
|
|
33418
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
33419
|
+
});
|
|
33420
|
+
}
|
|
33421
|
+
/** Drain `items` through at most `width` concurrent lanes. `fn` must
|
|
33422
|
+
* not reject (callers wrap their own try/catch). */
|
|
33423
|
+
async function runWithConcurrency(items, width, fn) {
|
|
33424
|
+
const queue = [...items];
|
|
33425
|
+
const laneCount = Math.max(1, Math.min(width, queue.length));
|
|
33426
|
+
const lane = async () => {
|
|
33427
|
+
for (;;) {
|
|
33428
|
+
const item = queue.shift();
|
|
33429
|
+
if (item === void 0) return;
|
|
33430
|
+
await fn(item);
|
|
33431
|
+
}
|
|
33432
|
+
};
|
|
33433
|
+
await Promise.all(Array.from({ length: laneCount }, lane));
|
|
33434
|
+
}
|
|
33435
|
+
var DeviceRestoreRetryScheduler = class {
|
|
33436
|
+
#logger;
|
|
33437
|
+
#attempt;
|
|
33438
|
+
#onPermanentFailure;
|
|
33439
|
+
#delaysMs;
|
|
33440
|
+
#concurrency;
|
|
33441
|
+
#now;
|
|
33442
|
+
#abort = new AbortController();
|
|
33443
|
+
constructor(options) {
|
|
33444
|
+
this.#logger = options.logger;
|
|
33445
|
+
this.#attempt = options.attempt;
|
|
33446
|
+
this.#onPermanentFailure = options.onPermanentFailure;
|
|
33447
|
+
this.#delaysMs = options.delaysMs ?? DEVICE_RESTORE_RETRY_DELAYS_MS;
|
|
33448
|
+
this.#concurrency = options.concurrency ?? 4;
|
|
33449
|
+
this.#now = options.now ?? Date.now;
|
|
33450
|
+
}
|
|
33451
|
+
/** Stop retrying (shutdown). Pending entries are NOT marked
|
|
33452
|
+
* permanently failed — the next boot restores them from disk. */
|
|
33453
|
+
cancel() {
|
|
33454
|
+
this.#abort.abort();
|
|
33455
|
+
}
|
|
33456
|
+
/**
|
|
33457
|
+
* Run the bounded retry rounds. Resolves when every entry has either
|
|
33458
|
+
* restored, been marked permanently failed, or the scheduler was
|
|
33459
|
+
* cancelled. Never rejects.
|
|
33460
|
+
*/
|
|
33461
|
+
async run(initialFailures) {
|
|
33462
|
+
let pending = initialFailures.map((failure) => ({
|
|
33463
|
+
saved: failure.saved,
|
|
33464
|
+
lastError: failure.error,
|
|
33465
|
+
attempts: 1
|
|
33466
|
+
}));
|
|
33467
|
+
for (let round = 0; round < this.#delaysMs.length; round += 1) {
|
|
33468
|
+
if (pending.length === 0 || this.#abort.signal.aborted) break;
|
|
33469
|
+
await sleep$1(this.#delaysMs[round] ?? 0, this.#abort.signal);
|
|
33470
|
+
if (this.#abort.signal.aborted) break;
|
|
33471
|
+
pending = await this.#runRound(pending, round);
|
|
33472
|
+
}
|
|
33473
|
+
if (this.#abort.signal.aborted) return [];
|
|
33474
|
+
const terminal = pending.map((entry) => ({
|
|
33475
|
+
deviceId: entry.saved.id,
|
|
33476
|
+
stableId: entry.saved.stableId,
|
|
33477
|
+
type: String(entry.saved.type),
|
|
33478
|
+
attempts: entry.attempts,
|
|
33479
|
+
lastError: entry.lastError,
|
|
33480
|
+
failedAt: this.#now()
|
|
33481
|
+
}));
|
|
33482
|
+
for (const failure of terminal) this.#onPermanentFailure(failure);
|
|
33483
|
+
return terminal;
|
|
33484
|
+
}
|
|
33485
|
+
/** One retry round: parents first (phase 0), then hub-adopted
|
|
33486
|
+
* children (phase 1) — a child's attempt depends on its parent
|
|
33487
|
+
* having landed, exactly like the initial two-pass restore. */
|
|
33488
|
+
async #runRound(pending, round) {
|
|
33489
|
+
const next = [];
|
|
33490
|
+
const parents = pending.filter((entry) => entry.saved.parentDeviceId === null);
|
|
33491
|
+
const children = pending.filter((entry) => entry.saved.parentDeviceId !== null);
|
|
33492
|
+
for (const phase of [parents, children]) await runWithConcurrency(phase, this.#concurrency, async (entry) => {
|
|
33493
|
+
if (this.#abort.signal.aborted) {
|
|
33494
|
+
next.push(entry);
|
|
33495
|
+
return;
|
|
33496
|
+
}
|
|
33497
|
+
const attemptNo = entry.attempts + 1;
|
|
33498
|
+
try {
|
|
33499
|
+
await this.#attempt(entry.saved);
|
|
33500
|
+
this.#logger.info("Device restored on retry", {
|
|
33501
|
+
tags: {
|
|
33502
|
+
deviceId: entry.saved.id,
|
|
33503
|
+
stableId: entry.saved.stableId
|
|
33504
|
+
},
|
|
33505
|
+
meta: { attempt: attemptNo }
|
|
33506
|
+
});
|
|
33507
|
+
} catch (err) {
|
|
33508
|
+
const lastError = err instanceof Error ? err.message : String(err);
|
|
33509
|
+
const remainingRetries = this.#delaysMs.length - (round + 1);
|
|
33510
|
+
this.#logger.warn("Device restore retry failed", {
|
|
33511
|
+
tags: {
|
|
33512
|
+
deviceId: entry.saved.id,
|
|
33513
|
+
stableId: entry.saved.stableId
|
|
33514
|
+
},
|
|
33515
|
+
meta: {
|
|
33516
|
+
attempt: attemptNo,
|
|
33517
|
+
remainingRetries,
|
|
33518
|
+
error: lastError
|
|
33519
|
+
}
|
|
33520
|
+
});
|
|
33521
|
+
next.push({
|
|
33522
|
+
saved: entry.saved,
|
|
33523
|
+
lastError,
|
|
33524
|
+
attempts: attemptNo
|
|
33525
|
+
});
|
|
33526
|
+
}
|
|
33527
|
+
});
|
|
33528
|
+
return next;
|
|
33529
|
+
}
|
|
33530
|
+
};
|
|
33531
|
+
/**
|
|
33342
33532
|
* Convert an IDevice to the flat DeviceSummary shape expected by the
|
|
33343
33533
|
* device-provider cap router. Shared across all providers.
|
|
33344
33534
|
*/
|
|
@@ -33387,6 +33577,7 @@ var BaseDeviceProvider = class extends BaseAddon {
|
|
|
33387
33577
|
}];
|
|
33388
33578
|
}
|
|
33389
33579
|
async onShutdown() {
|
|
33580
|
+
this.cancelRestoreRetries();
|
|
33390
33581
|
const devices = await this.ctx.kernel.devices?.getAll() ?? [];
|
|
33391
33582
|
for (const device of devices) try {
|
|
33392
33583
|
await this.ctx.kernel.devices?.decommission(device.id);
|
|
@@ -33404,9 +33595,16 @@ var BaseDeviceProvider = class extends BaseAddon {
|
|
|
33404
33595
|
async start() {}
|
|
33405
33596
|
async stop() {}
|
|
33406
33597
|
async getStatus() {
|
|
33598
|
+
const all = await this.ctx.kernel.devices?.getAll() ?? [];
|
|
33599
|
+
const summary = this.restoreFailureSummary();
|
|
33600
|
+
if (summary === null) return {
|
|
33601
|
+
connected: true,
|
|
33602
|
+
deviceCount: all.length
|
|
33603
|
+
};
|
|
33407
33604
|
return {
|
|
33408
33605
|
connected: true,
|
|
33409
|
-
deviceCount:
|
|
33606
|
+
deviceCount: all.length,
|
|
33607
|
+
error: summary
|
|
33410
33608
|
};
|
|
33411
33609
|
}
|
|
33412
33610
|
async getDevices() {
|
|
@@ -33496,8 +33694,137 @@ var BaseDeviceProvider = class extends BaseAddon {
|
|
|
33496
33694
|
};
|
|
33497
33695
|
}
|
|
33498
33696
|
async restoreDevices(savedDevices) {
|
|
33499
|
-
await this.onRestoreDevices(savedDevices);
|
|
33500
|
-
if (savedDevices.length
|
|
33697
|
+
const report = await this.onRestoreDevices(savedDevices);
|
|
33698
|
+
if (savedDevices.length === 0) return;
|
|
33699
|
+
if (report && report.failedCount > 0) {
|
|
33700
|
+
this.ctx.logger.warn(`Restored ${report.restoredCount}/${savedDevices.length} ${this.providerName} device(s) — ${report.failedCount} failed, bounded retry scheduled`);
|
|
33701
|
+
return;
|
|
33702
|
+
}
|
|
33703
|
+
const restoredCount = report ? report.restoredCount : savedDevices.length;
|
|
33704
|
+
this.ctx.logger.info(`Restored ${restoredCount} ${this.providerName} device(s)`);
|
|
33705
|
+
}
|
|
33706
|
+
/** Retry schedule. Overridable (tests use millisecond delays). */
|
|
33707
|
+
restoreRetryDelaysMs = DEVICE_RESTORE_RETRY_DELAYS_MS;
|
|
33708
|
+
/** Retry lane width. See `device-restore-retry.ts` for why retries
|
|
33709
|
+
* never re-stampede full-width while the initial pass does (D167). */
|
|
33710
|
+
restoreRetryConcurrency = 4;
|
|
33711
|
+
_restoreRetryScheduler = null;
|
|
33712
|
+
_restoreRetryCompletion = null;
|
|
33713
|
+
_permanentRestoreFailures = /* @__PURE__ */ new Map();
|
|
33714
|
+
/** Settles when the background retry rounds finish (or `null` when
|
|
33715
|
+
* nothing failed). Exposed for tests and subclass diagnostics —
|
|
33716
|
+
* boot NEVER awaits this: the runner's post-init handshake goes out
|
|
33717
|
+
* with the devices that restored, and a late success is announced
|
|
33718
|
+
* through the `native-cap-change` → `updateCaps` path. */
|
|
33719
|
+
get restoreRetryCompletion() {
|
|
33720
|
+
return this._restoreRetryCompletion;
|
|
33721
|
+
}
|
|
33722
|
+
/** Devices that exhausted the retry bound this process lifetime. */
|
|
33723
|
+
get permanentRestoreFailures() {
|
|
33724
|
+
return [...this._permanentRestoreFailures.values()];
|
|
33725
|
+
}
|
|
33726
|
+
/** One-line operator-facing summary for `getStatus().error`, or
|
|
33727
|
+
* `null` when every device restored. */
|
|
33728
|
+
restoreFailureSummary() {
|
|
33729
|
+
if (this._permanentRestoreFailures.size === 0) return null;
|
|
33730
|
+
const ids = [...this._permanentRestoreFailures.keys()].join(", ");
|
|
33731
|
+
return `${this._permanentRestoreFailures.size} device(s) permanently failed restore (deviceIds: ${ids}) — restart the ${this.providerName} provider to retry`;
|
|
33732
|
+
}
|
|
33733
|
+
cancelRestoreRetries() {
|
|
33734
|
+
this._restoreRetryScheduler?.cancel();
|
|
33735
|
+
this._restoreRetryScheduler = null;
|
|
33736
|
+
}
|
|
33737
|
+
recordPermanentRestoreFailure(failure) {
|
|
33738
|
+
this._permanentRestoreFailures.set(failure.deviceId, failure);
|
|
33739
|
+
this.ctx.logger.error("Device restore permanently failed — its capabilities will not register until the provider restarts", {
|
|
33740
|
+
tags: {
|
|
33741
|
+
deviceId: failure.deviceId,
|
|
33742
|
+
stableId: failure.stableId
|
|
33743
|
+
},
|
|
33744
|
+
meta: {
|
|
33745
|
+
type: failure.type,
|
|
33746
|
+
attempts: failure.attempts,
|
|
33747
|
+
error: failure.lastError
|
|
33748
|
+
}
|
|
33749
|
+
});
|
|
33750
|
+
}
|
|
33751
|
+
scheduleRestoreRetries(failures, attempt) {
|
|
33752
|
+
const scheduler = new DeviceRestoreRetryScheduler({
|
|
33753
|
+
logger: this.ctx.logger,
|
|
33754
|
+
delaysMs: this.restoreRetryDelaysMs,
|
|
33755
|
+
concurrency: this.restoreRetryConcurrency,
|
|
33756
|
+
attempt,
|
|
33757
|
+
onPermanentFailure: (failure) => this.recordPermanentRestoreFailure(failure)
|
|
33758
|
+
});
|
|
33759
|
+
this._restoreRetryScheduler = scheduler;
|
|
33760
|
+
this._restoreRetryCompletion = scheduler.run(failures).then(() => void 0).catch((err) => {
|
|
33761
|
+
this.ctx.logger.error("Restore retry scheduler crashed", { meta: { error: err instanceof Error ? err.message : String(err) } });
|
|
33762
|
+
});
|
|
33763
|
+
}
|
|
33764
|
+
/**
|
|
33765
|
+
* Tear down and reconstruct ONE device from its persisted rows — the
|
|
33766
|
+
* `deviceProvider.reloadDevice` cap method. Persistence is never touched,
|
|
33767
|
+
* and no other device this provider owns is disturbed.
|
|
33768
|
+
*
|
|
33769
|
+
* Keyed by `stableId` because the caller's whole reason to be here is that
|
|
33770
|
+
* the NUMERIC id changed (`deviceManager.migrateDevice` swapped it): the
|
|
33771
|
+
* fresh instance resolves its id through `allocateDeviceId`, which returns
|
|
33772
|
+
* whatever number the row carries NOW. The teardown is `decommission` —
|
|
33773
|
+
* exactly what a graceful shutdown runs per device (fires `removeDevice()`,
|
|
33774
|
+
* unregisters native caps, drops the registry entry) — and the rebuild is
|
|
33775
|
+
* the boot restore's own `create()` path, including its pass 2: first-class
|
|
33776
|
+
* children (hub-adopted cameras under an NVR) are decommissioned with the
|
|
33777
|
+
* parent by the cascade and must be re-created explicitly, because only
|
|
33778
|
+
* accessory children come back through `getAccessoryChildren()`.
|
|
33779
|
+
*
|
|
33780
|
+
* Reloading an accessory child directly is refused (no device class) —
|
|
33781
|
+
* reload its parent instead.
|
|
33782
|
+
*/
|
|
33783
|
+
async reloadDevice(input) {
|
|
33784
|
+
const { stableId } = input;
|
|
33785
|
+
const devices = this.ctx.kernel.devices;
|
|
33786
|
+
if (!devices) throw new Error(`${this.providerName}: kernel.devices unavailable — cannot reload`);
|
|
33787
|
+
const live = (await devices.getAll()).find((d) => d.stableId === stableId);
|
|
33788
|
+
if (live) await devices.decommission(live.id);
|
|
33789
|
+
const { id } = await this.ctx.api.deviceManager.allocateDeviceId.mutate({
|
|
33790
|
+
addonId: this.addonId,
|
|
33791
|
+
stableId
|
|
33792
|
+
});
|
|
33793
|
+
const meta = await this.ctx.api.deviceManager.loadMeta.query({ deviceId: id });
|
|
33794
|
+
if (meta === null) throw new Error(`${this.providerName}: no persisted meta for "${stableId}" (id ${id}) — cannot reload`);
|
|
33795
|
+
const deviceType = Object.values(DeviceType).find((t) => t === meta.type);
|
|
33796
|
+
const Class = deviceType !== void 0 ? this.deviceClasses[deviceType] : void 0;
|
|
33797
|
+
if (!Class) throw new Error(`${this.providerName}: no device class for type "${meta.type}" — "${stableId}" is an accessory child; reload its parent instead`);
|
|
33798
|
+
await devices.create(stableId, Class, {}, meta.parentDeviceId ?? null);
|
|
33799
|
+
const rows = await this.ctx.api.deviceManager.listPersistedByAddon.query({ addonId: this.addonId });
|
|
33800
|
+
for (const row of rows) {
|
|
33801
|
+
if (row.parentDeviceId !== id) continue;
|
|
33802
|
+
const childType = Object.values(DeviceType).find((t) => t === row.type);
|
|
33803
|
+
const ChildClass = childType !== void 0 ? this.deviceClasses[childType] : void 0;
|
|
33804
|
+
if (!ChildClass) continue;
|
|
33805
|
+
try {
|
|
33806
|
+
await devices.create(row.stableId, ChildClass, {}, id);
|
|
33807
|
+
} catch (err) {
|
|
33808
|
+
this.ctx.logger.warn("reloadDevice: failed to re-create first-class child", {
|
|
33809
|
+
tags: {
|
|
33810
|
+
deviceId: row.id,
|
|
33811
|
+
stableId: row.stableId
|
|
33812
|
+
},
|
|
33813
|
+
meta: {
|
|
33814
|
+
parentDeviceId: id,
|
|
33815
|
+
error: err instanceof Error ? err.message : String(err)
|
|
33816
|
+
}
|
|
33817
|
+
});
|
|
33818
|
+
}
|
|
33819
|
+
}
|
|
33820
|
+
this.ctx.logger.info("device reloaded in place from persisted rows", {
|
|
33821
|
+
tags: { deviceId: id },
|
|
33822
|
+
meta: {
|
|
33823
|
+
stableId,
|
|
33824
|
+
type: meta.type
|
|
33825
|
+
}
|
|
33826
|
+
});
|
|
33827
|
+
return { deviceId: id };
|
|
33501
33828
|
}
|
|
33502
33829
|
/**
|
|
33503
33830
|
* Restore devices from persisted state. Two-pass:
|
|
@@ -33523,55 +33850,125 @@ var BaseDeviceProvider = class extends BaseAddon {
|
|
|
33523
33850
|
* accessory-spawn flow handles via the parent's
|
|
33524
33851
|
* `getAccessoryChildren()`. Override only when the default doesn't
|
|
33525
33852
|
* fit.
|
|
33853
|
+
*
|
|
33854
|
+
* A row that fails either pass is NOT terminal (D347): it is handed
|
|
33855
|
+
* to a bounded background retry (`DeviceRestoreRetryScheduler`).
|
|
33856
|
+
* Only after the bound is exhausted is the device marked permanently
|
|
33857
|
+
* failed — logged at ERROR with `tags.deviceId` and surfaced via
|
|
33858
|
+
* `getStatus().error`.
|
|
33526
33859
|
*/
|
|
33860
|
+
/**
|
|
33861
|
+
* Repair a row's PERSISTED config blob immediately before it is restored.
|
|
33862
|
+
* Default: no-op — most providers have nothing to heal.
|
|
33863
|
+
*
|
|
33864
|
+
* This exists because a restored device self-hydrates from the DB: `create()`
|
|
33865
|
+
* passes `{}` and `BaseDevice` parses the stored blob against the device
|
|
33866
|
+
* schema. A blob that lost a REQUIRED field therefore fails restore forever,
|
|
33867
|
+
* and no later pass revisits it — a hub-adopted Reolink camera whose blob had
|
|
33868
|
+
* been emptied failed all four bounded attempts against fields
|
|
33869
|
+
* (`host`, `password`) it inherits from its parent and never dials itself.
|
|
33870
|
+
*
|
|
33871
|
+
* Implementations get every saved row, so a child can read its parent's blob.
|
|
33872
|
+
* A heal that throws is treated like any other restore failure: retried under
|
|
33873
|
+
* the bound, then reported — never swallowed.
|
|
33874
|
+
*/
|
|
33875
|
+
async healSavedConfig(_saved, _allSaved) {}
|
|
33527
33876
|
async onRestoreDevices(savedDevices) {
|
|
33528
33877
|
const restored = /* @__PURE__ */ new Set();
|
|
33878
|
+
const failures = [];
|
|
33879
|
+
const attemptRestore = async (saved) => {
|
|
33880
|
+
if (restored.has(saved.id)) return;
|
|
33881
|
+
const Class = this.deviceClasses[saved.type];
|
|
33882
|
+
if (!Class) throw new Error(`no device class registered for type "${saved.type}"`);
|
|
33883
|
+
if (saved.parentDeviceId !== null && !restored.has(saved.parentDeviceId)) throw new Error(`parent device ${saved.parentDeviceId} not restored`);
|
|
33884
|
+
await this.healSavedConfig(saved, savedDevices);
|
|
33885
|
+
await this.ctx.kernel.devices.create(saved.stableId, Class, {}, saved.parentDeviceId);
|
|
33886
|
+
restored.add(saved.id);
|
|
33887
|
+
};
|
|
33529
33888
|
const topLevel = savedDevices.filter((saved) => saved.parentDeviceId === null);
|
|
33530
33889
|
const restoreOne = async (saved) => {
|
|
33531
|
-
|
|
33532
|
-
if (!Class) {
|
|
33890
|
+
if (!this.deviceClasses[saved.type]) {
|
|
33533
33891
|
this.ctx.logger.warn("No device class registered for restored type — skipping", {
|
|
33534
|
-
tags: {
|
|
33892
|
+
tags: {
|
|
33893
|
+
deviceId: saved.id,
|
|
33894
|
+
stableId: saved.stableId
|
|
33895
|
+
},
|
|
33535
33896
|
meta: { type: saved.type }
|
|
33536
33897
|
});
|
|
33537
33898
|
return;
|
|
33538
33899
|
}
|
|
33539
33900
|
try {
|
|
33540
|
-
await
|
|
33541
|
-
restored.add(saved.id);
|
|
33901
|
+
await attemptRestore(saved);
|
|
33542
33902
|
} catch (err) {
|
|
33543
|
-
|
|
33544
|
-
|
|
33903
|
+
const error = err instanceof Error ? err.message : String(err);
|
|
33904
|
+
this.ctx.logger.warn("Failed to restore device — bounded retry scheduled", {
|
|
33905
|
+
tags: {
|
|
33906
|
+
deviceId: saved.id,
|
|
33907
|
+
stableId: saved.stableId
|
|
33908
|
+
},
|
|
33545
33909
|
meta: {
|
|
33546
33910
|
type: saved.type,
|
|
33547
|
-
|
|
33911
|
+
attempt: 1,
|
|
33912
|
+
error
|
|
33548
33913
|
}
|
|
33549
33914
|
});
|
|
33915
|
+
failures.push({
|
|
33916
|
+
saved,
|
|
33917
|
+
error
|
|
33918
|
+
});
|
|
33550
33919
|
}
|
|
33551
33920
|
};
|
|
33552
33921
|
await Promise.all(topLevel.map((saved) => restoreOne(saved)));
|
|
33922
|
+
const failedTopLevelIds = new Set(failures.map((failure) => failure.saved.id));
|
|
33553
33923
|
const childRows = savedDevices.filter((s) => s.parentDeviceId !== null);
|
|
33554
33924
|
for (const saved of childRows) {
|
|
33555
|
-
|
|
33556
|
-
if (!Class) continue;
|
|
33925
|
+
if (!this.deviceClasses[saved.type]) continue;
|
|
33557
33926
|
if (saved.parentDeviceId === null) continue;
|
|
33558
|
-
if (
|
|
33559
|
-
|
|
33560
|
-
|
|
33561
|
-
|
|
33562
|
-
|
|
33563
|
-
|
|
33927
|
+
if (restored.has(saved.parentDeviceId)) {
|
|
33928
|
+
try {
|
|
33929
|
+
await attemptRestore(saved);
|
|
33930
|
+
} catch (err) {
|
|
33931
|
+
const error = err instanceof Error ? err.message : String(err);
|
|
33932
|
+
this.ctx.logger.warn("Failed to restore hub-adopted child — bounded retry scheduled", {
|
|
33933
|
+
tags: {
|
|
33934
|
+
deviceId: saved.id,
|
|
33935
|
+
stableId: saved.stableId,
|
|
33936
|
+
parentDeviceId: saved.parentDeviceId
|
|
33937
|
+
},
|
|
33938
|
+
meta: {
|
|
33939
|
+
type: saved.type,
|
|
33940
|
+
attempt: 1,
|
|
33941
|
+
error
|
|
33942
|
+
}
|
|
33943
|
+
});
|
|
33944
|
+
failures.push({
|
|
33945
|
+
saved,
|
|
33946
|
+
error
|
|
33947
|
+
});
|
|
33948
|
+
}
|
|
33949
|
+
continue;
|
|
33950
|
+
}
|
|
33951
|
+
if (failedTopLevelIds.has(saved.parentDeviceId)) {
|
|
33952
|
+
this.ctx.logger.warn("Hub-adopted child deferred — parent failed initial restore", {
|
|
33564
33953
|
tags: {
|
|
33954
|
+
deviceId: saved.id,
|
|
33565
33955
|
stableId: saved.stableId,
|
|
33566
33956
|
parentDeviceId: saved.parentDeviceId
|
|
33567
33957
|
},
|
|
33568
|
-
meta: {
|
|
33569
|
-
|
|
33570
|
-
|
|
33571
|
-
|
|
33958
|
+
meta: { type: saved.type }
|
|
33959
|
+
});
|
|
33960
|
+
failures.push({
|
|
33961
|
+
saved,
|
|
33962
|
+
error: `parent device ${saved.parentDeviceId} not restored`
|
|
33572
33963
|
});
|
|
33964
|
+
continue;
|
|
33573
33965
|
}
|
|
33574
33966
|
}
|
|
33967
|
+
if (failures.length > 0) this.scheduleRestoreRetries(failures, attemptRestore);
|
|
33968
|
+
return {
|
|
33969
|
+
restoredCount: restored.size,
|
|
33970
|
+
failedCount: failures.length
|
|
33971
|
+
};
|
|
33575
33972
|
}
|
|
33576
33973
|
/** Convert an IDevice to the flat DeviceSummary for the cap router. */
|
|
33577
33974
|
toSummary(device) {
|
|
@@ -35334,6 +35731,12 @@ Object.freeze({
|
|
|
35334
35731
|
addonId: null,
|
|
35335
35732
|
access: "view"
|
|
35336
35733
|
},
|
|
35734
|
+
"deviceProvider.reloadDevice": {
|
|
35735
|
+
capName: "device-provider",
|
|
35736
|
+
capScope: "system",
|
|
35737
|
+
addonId: null,
|
|
35738
|
+
access: "create"
|
|
35739
|
+
},
|
|
35337
35740
|
"deviceProvider.start": {
|
|
35338
35741
|
capName: "device-provider",
|
|
35339
35742
|
capScope: "system",
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@camstack/addon-provider-tuya",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.61",
|
|
4
4
|
"description": "Tuya / Smart Life device-provider addon for CamStack — account-onboarded (Tuya IoT cloud fetch of device localKeys) + LOCAL DP control via the @apocaliss92/nodetuya encrypted-LAN client, exposing switch / water-heater-family kettle entities",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"camstack",
|