From e9d138b7e83ac15ab74a77a51517ccdadef99f26 Mon Sep 17 00:00:00 2001 From: Petar Petrov Date: Thu, 3 Dec 2026 12:20:59 +0200 Subject: [PATCH] Add opt-in adaptive throttling for entity state updates --- README.md | 23 ++ lib/connection.ts | 4 + lib/states.ts | 143 ++++++-- lib/store.ts | 18 +- lib/throttle.ts | 622 ++++++++++++++++++++++++++++++++ lib/util.ts | 51 +++ test/states.spec.ts | 811 +++++++++++++++++++++++++++++++++++++++++- test/throttle.spec.ts | 736 ++++++++++++++++++++++++++++++++++++++ 8 files changed, 2373 insertions(+), 35 deletions(-) create mode 100644 lib/throttle.ts create mode 100644 test/throttle.spec.ts diff --git a/README.md b/README.md index f1def67e..0f0b2483 100644 --- a/README.md +++ b/README.md @@ -231,6 +231,29 @@ await coll.refresh(); coll.subscribe((states) => console.log(states)); ``` +Both `entityStatesColl` and `subscribeEntityStates` accept an optional `options` argument with `throttleUpdates` (opt-in; defaults to `false`). Options apply when the collection is first created. When enabled, entity state updates are coalesced in place on the store while subscriber notifications adaptively throttle based on measured publish and paint cost, fast-pathing user actions (matching `userId` or recent `call_service` entity targets) and deferring notifications while the tab is hidden. + +```javascript +import { + subscribeEntityStates, + flushEntityStates, +} from "home-assistant-js-websocket"; + +subscribeEntityStates(conn, (states) => console.log("New states!", states), { + throttleUpdates: { + userId: () => currentUserId, + // targetDutyCycle: 0.12, + // minIntervalMs: 16, + // maxIntervalMs: 1000, + // snapshotThresholdMsPer1k: 4.0, + // pauseWhenHidden: true, + }, +}); + +// Flush any pending throttled updates immediately if needed. +flushEntityStates(conn); +``` + ### Config You can subscribe to the config of Home Assistant. Config can change when either a component gets loaded. diff --git a/lib/connection.ts b/lib/connection.ts index 7089d235..909481b5 100644 --- a/lib/connection.ts +++ b/lib/connection.ts @@ -11,6 +11,7 @@ import { import { HassEvent, MessageBase } from "./types.js"; import { HaWebSocket } from "./socket.js"; import type { Auth } from "./auth.js"; +import { notifyServiceCall } from "./util.js"; const DEBUG = false; @@ -320,6 +321,9 @@ export class Connection { message.id = commandId; this.socket!.send(JSON.stringify(message)); + if (message.type === "call_service") { + notifyServiceCall(this, message); + } } sendMessagePromise(message: MessageBase): Promise { diff --git a/lib/states.ts b/lib/states.ts index 72a28482..433a5013 100644 --- a/lib/states.ts +++ b/lib/states.ts @@ -9,6 +9,19 @@ import { Connection } from "./connection.js"; import { Store } from "./store.js"; import { getStates } from "./commands.js"; import { atLeastHaVersion } from "./util.js"; +import { + createStateUpdateThrottler, + ResolvedThrottleOptions, + resolveThrottleOptions, + throttleOptionsEqual, + ThrottleUpdatesOptions, +} from "./throttle.js"; + +export type { ThrottleUpdatesOptions }; + +export type EntityStatesCollectionOptions = { + throttleUpdates?: boolean | ThrottleUpdatesOptions; +}; interface EntityState { /** state */ @@ -41,16 +54,10 @@ interface StatesUpdates { /** remove */ r?: string[]; // remove /** change */ - c: Record; + c?: Record; } -function processEvent( - store: Store, - updates: StatesUpdates, - replace: boolean, -) { - const state = replace ? {} : { ...store.state }; - +function applyUpdates(state: HassEntityStates, updates: StatesUpdates) { if (updates.a) { for (const entityId in updates.a) { const newState = updates.a[entityId]; @@ -127,38 +134,84 @@ function processEvent( state[entityId] = entityState; } } - - store.setState(state, true); } +const activeFlushers = new WeakMap void>(); + +export const flushEntityStates = (conn: Connection): void => { + activeFlushers.get(conn)?.(); +}; + const subscribeUpdates = async ( conn: Connection, store: Store, + throttleOptions?: ResolvedThrottleOptions, ) => { - let replace = true; - const markReplace = () => { - replace = true; + if (!throttleOptions) { + let replace = true; + const markReplace = () => { + replace = true; + }; + + conn.addEventListener("ready", markReplace); + + try { + const unsub = await conn.subscribeMessage( + (ev) => { + const state = replace ? {} : { ...store.state }; + applyUpdates(state, ev); + replace = false; + store.setState(state, true); + }, + { + type: "subscribe_entities", + }, + ); + + return () => { + conn.removeEventListener("ready", markReplace); + void unsub(); + }; + } catch (err) { + conn.removeEventListener("ready", markReplace); + throw err; + } + } + + const throttler = createStateUpdateThrottler( + conn, + store, + throttleOptions, + applyUpdates, + ); + const markReplace = () => throttler.markReplace(); + const flush = () => throttler.flush(); + + const cleanup = () => { + conn.removeEventListener("ready", markReplace); + if (activeFlushers.get(conn) === flush) { + activeFlushers.delete(conn); + } + throttler.destroy(); }; + activeFlushers.set(conn, flush); conn.addEventListener("ready", markReplace); try { const unsub = await conn.subscribeMessage( - (ev) => { - processEvent(store, ev, replace); - replace = false; - }, + (ev) => throttler.handleEvent(ev), { type: "subscribe_entities", }, ); return () => { - conn.removeEventListener("ready", markReplace); + cleanup(); void unsub(); }; } catch (err) { - conn.removeEventListener("ready", markReplace); + cleanup(); throw err; } }; @@ -201,20 +254,52 @@ const legacySubscribeUpdates = ( "state_changed", ); -export const entityStatesColl = (conn: Connection) => - atLeastHaVersion(conn.haVersion, 2022, 4, 0) - ? getCollection(conn, "_ent", undefined, subscribeUpdates) - : getCollection( - conn, - "_ent", - legacyFetchEntityStates, - legacySubscribeUpdates, - ); +const createdWithThrottleUpdates = new WeakMap< + object, + ResolvedThrottleOptions | false +>(); + +export const entityStatesColl = ( + conn: Connection, + options?: EntityStatesCollectionOptions, +) => { + if (!atLeastHaVersion(conn.haVersion, 2022, 4, 0)) { + return getCollection( + conn, + "_ent", + legacyFetchEntityStates, + legacySubscribeUpdates, + ); + } + const throttleOptions = resolveThrottleOptions(options?.throttleUpdates); + const storedOption: ResolvedThrottleOptions | false = + throttleOptions ?? false; + const exists = Boolean((conn as unknown as Record)._ent); + const coll = getCollection( + conn, + "_ent", + undefined, + (conn, store) => subscribeUpdates(conn, store, throttleOptions), + ); + if (!exists) { + createdWithThrottleUpdates.set(coll, storedOption); + } else if ( + options?.throttleUpdates !== undefined && + createdWithThrottleUpdates.has(coll) && + !throttleOptionsEqual(createdWithThrottleUpdates.get(coll)!, storedOption) + ) { + console.warn( + "Entity states collection already exists with different throttleUpdates options, ignoring new throttleUpdates option", + ); + } + return coll; +}; export const subscribeEntityStates = ( conn: Connection, onChange: (state: HassEntityStates) => void, -): UnsubscribeFunc => entityStatesColl(conn).subscribe(onChange); + options?: EntityStatesCollectionOptions, +): UnsubscribeFunc => entityStatesColl(conn, options).subscribe(onChange); /** @deprecated Use entityStatesColl */ export const entitiesColl = entityStatesColl; diff --git a/lib/store.ts b/lib/store.ts index a5b603a3..a0cbef5f 100644 --- a/lib/store.ts +++ b/lib/store.ts @@ -1,4 +1,5 @@ import { UnsubscribeFunc } from "./types.js"; +import { notifyStoreStateRead } from "./util.js"; // (c) Jason Miller // Unistore - MIT license @@ -14,7 +15,7 @@ type BoundAction = (...args: any[]) => void; export type Store = { state: State | undefined; action(action: Action): BoundAction; - setState(update: Partial, overwrite?: boolean): void; + setState(update: Partial, overwrite?: boolean, notify?: boolean): void; clearState(): void; subscribe(listener: Listener): UnsubscribeFunc; }; @@ -34,8 +35,15 @@ export const createStore = (state?: State): Store => { listeners = out; } - function setState(update: Partial, overwrite: boolean): void { + function setState( + update: Partial, + overwrite = false, + notify = true, + ): void { state = overwrite ? (update as State) : { ...state!, ...update }; + if (!notify) { + return; + } let currentListeners = listeners; for (let i = 0; i < currentListeners.length; i++) { currentListeners[i](state); @@ -47,8 +55,9 @@ export const createStore = (state?: State): Store => { * @name store */ - return { + const store: Store = { get state() { + notifyStoreStateRead(store); return state; }, @@ -80,6 +89,7 @@ export const createStore = (state?: State): Store => { * Apply a partial state object to the current state, invoking registered listeners. * @param {Object} update An object with properties to be merged into state * @param {Boolean} [overwrite=false] If `true`, update will replace state instead of being merged into it + * @param {Boolean} [notify=true] If `false`, listeners are not called */ setState, @@ -106,4 +116,6 @@ export const createStore = (state?: State): Store => { // */ // unsubscribe, }; + + return store; }; diff --git a/lib/throttle.ts b/lib/throttle.ts new file mode 100644 index 00000000..1138348d --- /dev/null +++ b/lib/throttle.ts @@ -0,0 +1,622 @@ +import type { Connection } from "./connection.js"; +import type { Store } from "./store.js"; +import type { HassEntityStates, MessageBase } from "./types.js"; +import { addServiceCallListener, setStoreStateReadListener } from "./util.js"; + +export interface StatesUpdateLike { + a?: Record; + r?: string[]; + c?: Record; +} + +export interface ThrottleUpdatesOptions { + targetDutyCycle?: number; + minIntervalMs?: number; + maxIntervalMs?: number; + snapshotThresholdMsPer1k?: number; + userId?: string | (() => string | undefined); + pauseWhenHidden?: boolean; +} + +export interface ResolvedThrottleOptions { + targetDutyCycle: number; + minIntervalMs: number; + maxIntervalMs: number; + snapshotThresholdMsPer1k: number; + userId: string | (() => string | undefined) | undefined; + pauseWhenHidden: boolean; +} + +export interface StateUpdateThrottler { + handleEvent(ev: Update): void; + markReplace(): void; + flush(): void; + destroy(): void; + readonly throttleMs: number; + readonly emaCostMs: number; +} + +const DEFAULT_TARGET_DUTY_CYCLE = 0.12; +const DEFAULT_MIN_INTERVAL_MS = 16; +const DEFAULT_MAX_INTERVAL_MS = 1000; +const DEFAULT_SNAPSHOT_THRESHOLD_MS_PER_1K = 4.0; +const DEFAULT_PAUSE_WHEN_HIDDEN = true; + +const EMA_ALPHA = 0.25; +const MAX_SAMPLE_MS = 200; +const SNAPSHOT_SEED_FACTOR = 1.4; +const SERVICE_TARGET_TTL_MS = 2000; + +export function resolveThrottleOptions( + option: boolean | ThrottleUpdatesOptions | undefined, +): ResolvedThrottleOptions | undefined { + if (!option) { + return undefined; + } + const opts = option === true ? {} : option; + return { + targetDutyCycle: + typeof opts.targetDutyCycle === "number" && + Number.isFinite(opts.targetDutyCycle) && + opts.targetDutyCycle > 0 + ? opts.targetDutyCycle + : DEFAULT_TARGET_DUTY_CYCLE, + minIntervalMs: + typeof opts.minIntervalMs === "number" && + Number.isFinite(opts.minIntervalMs) && + opts.minIntervalMs >= 0 + ? opts.minIntervalMs + : DEFAULT_MIN_INTERVAL_MS, + maxIntervalMs: + typeof opts.maxIntervalMs === "number" && + Number.isFinite(opts.maxIntervalMs) && + opts.maxIntervalMs >= 0 + ? opts.maxIntervalMs + : DEFAULT_MAX_INTERVAL_MS, + snapshotThresholdMsPer1k: + typeof opts.snapshotThresholdMsPer1k === "number" && + Number.isFinite(opts.snapshotThresholdMsPer1k) && + opts.snapshotThresholdMsPer1k >= 0 + ? opts.snapshotThresholdMsPer1k + : DEFAULT_SNAPSHOT_THRESHOLD_MS_PER_1K, + userId: opts.userId, + pauseWhenHidden: opts.pauseWhenHidden ?? DEFAULT_PAUSE_WHEN_HIDDEN, + }; +} + +export function throttleOptionsEqual( + a: ResolvedThrottleOptions | false, + b: ResolvedThrottleOptions | false, +): boolean { + if (a === b) { + return true; + } + if (!a || !b) { + return false; + } + return ( + a.targetDutyCycle === b.targetDutyCycle && + a.minIntervalMs === b.minIntervalMs && + a.maxIntervalMs === b.maxIntervalMs && + a.snapshotThresholdMsPer1k === b.snapshotThresholdMsPer1k && + a.userId === b.userId && + a.pauseWhenHidden === b.pauseWhenHidden + ); +} + +const now = (): number => + typeof performance !== "undefined" && typeof performance.now === "function" + ? performance.now() + : Date.now(); + +const isDocumentHidden = (): boolean => + typeof document !== "undefined" && document.hidden === true; + +const unrefPort = (port: MessagePort) => { + (port as unknown as { unref?: () => void }).unref?.(); +}; + +const createUnrefChannel = (): MessageChannel => { + const channel = new MessageChannel(); + unrefPort(channel.port1); + unrefPort(channel.port2); + return channel; +}; + +const setPortHandler = ( + channel: MessageChannel, + handler: (ev: MessageEvent) => void, +) => { + channel.port1.onmessage = handler; + // Assigning onmessage calls start() in Node.js, which re-refs the port. + unrefPort(channel.port1); +}; + +const closeChannel = (channel: MessageChannel | undefined) => { + if (!channel) { + return; + } + channel.port1.onmessage = null; + channel.port2.onmessage = null; + channel.port1.close(); + channel.port2.close(); +}; + +const recordEntityIds = ( + targets: Map, + value: unknown, + expiresAt: number, +) => { + if (typeof value === "string") { + if (value.length > 0) { + targets.set(value, expiresAt); + } + } else if (Array.isArray(value)) { + for (let i = 0; i < value.length; i++) { + const item = value[i]; + if (typeof item === "string" && item.length > 0) { + targets.set(item, expiresAt); + } + } + } +}; + +export function createStateUpdateThrottler( + conn: Connection, + store: Store, + options: ResolvedThrottleOptions, + applyUpdates: (state: HassEntityStates, updates: Update) => void, +): StateUpdateThrottler { + let replace = true; + let pending: HassEntityStates | undefined; + let pendingObserved = false; + let readingOwnState = false; + let destroyed = false; + + let emaCostMs = 0; + let hasSample = false; + let hasProbeSample = false; + let throttleMs = 0; + let lastPublishAt = -Infinity; + + let timerId: ReturnType | undefined; + let microtaskScheduled = false; + let pendingResumeFlush = false; + + let probeInFlight = false; + let probeToken = 0; + let rafId: number | undefined; + let mcA: MessageChannel | undefined; + let mcB: MessageChannel | undefined; + + const recentTargets = new Map(); + let latestTargetExpiry = 0; + + const updateThrottleMs = () => { + const raw = emaCostMs / options.targetDutyCycle; + throttleMs = + raw < options.minIntervalMs + ? 0 + : Math.min(options.maxIntervalMs, Math.round(raw)); + }; + + const recordSample = (sampleMs: number) => { + const clamped = Math.min(MAX_SAMPLE_MS, Math.max(0, sampleMs)); + emaCostMs = hasSample + ? EMA_ALPHA * clamped + (1 - EMA_ALPHA) * emaCostMs + : clamped; + hasSample = true; + hasProbeSample = true; + updateThrottleMs(); + }; + + const cancelProbe = () => { + probeToken++; + probeInFlight = false; + if (rafId !== undefined) { + if (typeof cancelAnimationFrame === "function") { + cancelAnimationFrame(rafId); + } + rafId = undefined; + } + }; + + const startProbe = (t0: number) => { + if (typeof MessageChannel !== "function") { + recordSample(now() - t0); + return; + } + + probeInFlight = true; + const token = ++probeToken; + mcA ??= createUnrefChannel(); + + setPortHandler(mcA, (ev) => { + if (ev.data !== token) { + return; + } + if (destroyed || token !== probeToken || isDocumentHidden()) { + if (token === probeToken) { + probeInFlight = false; + } + return; + } + + const jsMs = Math.max(0, now() - t0); + + if (typeof requestAnimationFrame !== "function") { + probeInFlight = false; + recordSample(jsMs); + return; + } + + let rafFired = false; + const id = requestAnimationFrame(() => { + rafFired = true; + rafId = undefined; + if (destroyed || token !== probeToken || isDocumentHidden()) { + if (token === probeToken) { + probeInFlight = false; + } + return; + } + + const tRaf = now(); + mcB ??= createUnrefChannel(); + setPortHandler(mcB, (ev2) => { + if (ev2.data !== token) { + return; + } + if (destroyed || token !== probeToken || isDocumentHidden()) { + if (token === probeToken) { + probeInFlight = false; + } + return; + } + probeInFlight = false; + const paintMs = Math.max(0, now() - tRaf); + recordSample(jsMs + paintMs); + }); + mcB.port2.postMessage(token); + }); + if (!rafFired) { + rafId = id; + } + }); + + mcA.port2.postMessage(token); + }; + + const onServiceCall = (message: MessageBase) => { + const targetEntityId = message.target?.entity_id; + const serviceDataEntityId = message.service_data?.entity_id; + if (targetEntityId === undefined && serviceDataEntityId === undefined) { + return; + } + + const currentNow = now(); + if (recentTargets.size > 0) { + if ( + currentNow >= latestTargetExpiry || + latestTargetExpiry > currentNow + SERVICE_TARGET_TTL_MS * 2 + ) { + recentTargets.clear(); + latestTargetExpiry = 0; + } else { + for (const [entityId, exp] of recentTargets) { + if ( + exp <= currentNow || + exp > currentNow + SERVICE_TARGET_TTL_MS * 2 + ) { + recentTargets.delete(entityId); + } + } + } + } + + const expiresAt = currentNow + SERVICE_TARGET_TTL_MS; + recordEntityIds(recentTargets, targetEntityId, expiresAt); + recordEntityIds(recentTargets, serviceDataEntityId, expiresAt); + if (recentTargets.size > 0 && expiresAt > latestTargetExpiry) { + latestTargetExpiry = expiresAt; + } + }; + + const isRecentTarget = (entityId: string, currentNow: number): boolean => { + const exp = recentTargets.get(entityId); + if (exp === undefined) { + return false; + } + if (exp > currentNow && exp <= currentNow + SERVICE_TARGET_TTL_MS * 2) { + return true; + } + recentTargets.delete(entityId); + return false; + }; + + const hasRecentServiceTarget = (ev: Update, currentNow: number): boolean => { + if (recentTargets.size === 0) { + return false; + } + if ( + currentNow >= latestTargetExpiry || + latestTargetExpiry > currentNow + SERVICE_TARGET_TTL_MS * 2 + ) { + recentTargets.clear(); + latestTargetExpiry = 0; + return false; + } + if (ev.a) { + for (const entityId in ev.a) { + if (isRecentTarget(entityId, currentNow)) { + return true; + } + } + } + if (ev.c) { + for (const entityId in ev.c) { + if (isRecentTarget(entityId, currentNow)) { + return true; + } + } + } + if (ev.r) { + for (let i = 0; i < ev.r.length; i++) { + if (isRecentTarget(ev.r[i], currentNow)) { + return true; + } + } + } + return false; + }; + + const isUserActionFastPath = ( + ev: Update, + state: HassEntityStates, + currentNow: number, + ): boolean => { + if (hasRecentServiceTarget(ev, currentNow)) { + return true; + } + if (options.userId === undefined) { + return false; + } + const uid = + typeof options.userId === "function" ? options.userId() : options.userId; + if (!uid) { + return false; + } + if (ev.a) { + for (const entityId in ev.a) { + if (state[entityId]?.context?.user_id === uid) { + return true; + } + } + } + if (ev.c) { + for (const entityId in ev.c) { + if (state[entityId]?.context?.user_id === uid) { + return true; + } + } + } + return false; + }; + + const readStoreState = () => { + readingOwnState = true; + try { + return store.state; + } finally { + readingOwnState = false; + } + }; + + const flush = (force = false) => { + if (destroyed || !pending) { + return; + } + if (!force && options.pauseWhenHidden && isDocumentHidden()) { + return; + } + + if (timerId !== undefined) { + clearTimeout(timerId); + timerId = undefined; + } + + const state = pending; + const isResume = pendingResumeFlush; + pending = undefined; + pendingObserved = false; + pendingResumeFlush = false; + + // The collection was torn down meanwhile: don't bring the old states back. + if (readStoreState() !== state) { + return; + } + + const shouldProbe = !probeInFlight && !isResume && !isDocumentHidden(); + const t0 = shouldProbe ? now() : 0; + + try { + store.setState(state, true); + } finally { + lastPublishAt = now(); + } + + if (shouldProbe && !destroyed && !isDocumentHidden()) { + startProbe(t0); + } + }; + + const scheduleMicrotaskFlush = () => { + if (timerId !== undefined) { + clearTimeout(timerId); + timerId = undefined; + } + if (microtaskScheduled) { + return; + } + microtaskScheduled = true; + Promise.resolve().then(() => { + microtaskScheduled = false; + flush(); + }); + }; + + const scheduleTimerFlush = (delayMs: number) => { + if (microtaskScheduled || timerId !== undefined) { + return; + } + timerId = setTimeout(() => { + timerId = undefined; + flush(); + }, delayMs); + }; + + const onVisibilityChange = () => { + if (destroyed) { + return; + } + if (isDocumentHidden()) { + cancelProbe(); + if (options.pauseWhenHidden && timerId !== undefined) { + clearTimeout(timerId); + timerId = undefined; + } + } else if (options.pauseWhenHidden && pending) { + pendingResumeFlush = true; + flush(); + } + }; + + const unsubServiceCall = addServiceCallListener(conn, onServiceCall); + const unsubStoreRead = setStoreStateReadListener(store, () => { + if (!readingOwnState && pending) { + pendingObserved = true; + } + }); + const visibilityTarget = + typeof document !== "undefined" && + typeof document.addEventListener === "function" + ? document + : undefined; + visibilityTarget?.addEventListener("visibilitychange", onVisibilityChange); + + return { + get throttleMs() { + return throttleMs; + }, + + get emaCostMs() { + return emaCostMs; + }, + + handleEvent(ev: Update) { + if (destroyed) { + return; + } + + const isReplace = replace; + const shouldCopy = !pending || pendingObserved; + const target = shouldCopy + ? isReplace + ? {} + : { ...(pending ?? readStoreState()) } + : pending!; + + const measureSnapshot = isReplace && !hasProbeSample; + const t0 = measureSnapshot ? now() : 0; + applyUpdates(target, ev); + + if (shouldCopy) { + pending = target; + pendingObserved = false; + store.setState(pending, true, false); + } + replace = false; + + if (measureSnapshot) { + const snapshotMs = Math.max(0, now() - t0); + const entityCount = Object.keys(target).length; + if (entityCount > 0) { + const msPer1k = (snapshotMs * 1000) / entityCount; + if (msPer1k > options.snapshotThresholdMsPer1k) { + emaCostMs = Math.min(MAX_SAMPLE_MS, msPer1k * SNAPSHOT_SEED_FACTOR); + hasSample = true; + updateThrottleMs(); + } + } + } + + if (options.pauseWhenHidden && isDocumentHidden()) { + if (timerId !== undefined) { + clearTimeout(timerId); + timerId = undefined; + } + return; + } + + if (isReplace) { + scheduleMicrotaskFlush(); + return; + } + + const currentNow = now(); + if (isUserActionFastPath(ev, target, currentNow)) { + scheduleMicrotaskFlush(); + return; + } + + const elapsed = currentNow - lastPublishAt; + if (throttleMs === 0 || elapsed >= throttleMs || elapsed < 0) { + scheduleMicrotaskFlush(); + } else { + scheduleTimerFlush(throttleMs - elapsed); + } + }, + + markReplace() { + replace = true; + pending = undefined; + pendingObserved = false; + pendingResumeFlush = false; + if (timerId !== undefined) { + clearTimeout(timerId); + timerId = undefined; + } + }, + + flush() { + flush(true); + }, + + destroy() { + if (destroyed) { + return; + } + destroyed = true; + cancelProbe(); + closeChannel(mcA); + closeChannel(mcB); + mcA = undefined; + mcB = undefined; + if (timerId !== undefined) { + clearTimeout(timerId); + timerId = undefined; + } + pending = undefined; + pendingObserved = false; + pendingResumeFlush = false; + recentTargets.clear(); + latestTargetExpiry = 0; + unsubServiceCall(); + unsubStoreRead(); + visibilityTarget?.removeEventListener( + "visibilitychange", + onVisibilityChange, + ); + }, + }; +} diff --git a/lib/util.ts b/lib/util.ts index 69323cdd..42199fe3 100644 --- a/lib/util.ts +++ b/lib/util.ts @@ -1,3 +1,54 @@ +import type { MessageBase } from "./types.js"; + +type ServiceCallListener = (message: MessageBase) => void; + +const serviceCallListeners = new WeakMap>(); +const storeReadListeners = new WeakMap void>(); + +export function setStoreStateReadListener( + store: object, + listener: () => void, +): () => void { + storeReadListeners.set(store, listener); + return () => { + if (storeReadListeners.get(store) === listener) { + storeReadListeners.delete(store); + } + }; +} + +export function notifyStoreStateRead(store: object): void { + storeReadListeners.get(store)?.(); +} + +export function addServiceCallListener( + conn: object, + listener: ServiceCallListener, +): () => void { + let listeners = serviceCallListeners.get(conn); + if (!listeners) { + listeners = new Set(); + serviceCallListeners.set(conn, listeners); + } + listeners.add(listener); + return () => { + listeners!.delete(listener); + if (listeners!.size === 0) { + serviceCallListeners.delete(conn); + } + }; +} + +export function notifyServiceCall(conn: object, message: MessageBase): void { + const listeners = serviceCallListeners.get(conn); + if (!listeners) { + return; + } + for (const listener of listeners) { + listener(message); + } +} + export function parseQuery(queryString: string) { const query: any = {}; const items = queryString.split("&"); diff --git a/test/states.spec.ts b/test/states.spec.ts index 3586421b..30f59353 100644 --- a/test/states.spec.ts +++ b/test/states.spec.ts @@ -1,6 +1,12 @@ import * as assert from "assert"; -import { subscribeEntityStates } from "../dist/states.js"; +import { callService } from "../dist/commands.js"; +import { Connection } from "../dist/connection.js"; +import { + entityStatesColl, + flushEntityStates, + subscribeEntityStates, +} from "../dist/states.js"; import { MockConnection, AwaitableEvent } from "./util.ts"; const MOCK_LIGHT = { @@ -28,15 +34,134 @@ const modernEntity = (entity_id: string, state: string, lc: number) => ({ lu: lc, }); -const modernState = (entity_id: string, state: string, lc: number) => ({ +const modernState = ( + entity_id: string, + state: string, + lc: number, + context = MOCK_CONTEXT, +) => ({ entity_id, state, attributes: {}, - context: MOCK_CONTEXT, + context, last_changed: new Date(lc * 1000).toISOString(), last_updated: new Date(lc * 1000).toISOString(), }); +class FakeSocket { + OPEN = 1; + readyState = 1; + haVersion = "2026.4.0"; + sent: any[] = []; + listeners: Record void)[]> = {}; + + addEventListener(type: string, cb: (ev: any) => void) { + (this.listeners[type] ??= []).push(cb); + } + + removeEventListener(type: string, cb: (ev: any) => void) { + this.listeners[type] = (this.listeners[type] ?? []).filter((l) => l !== cb); + } + + send(msg: string) { + this.sent.push(JSON.parse(msg)); + } + + close() { + this.readyState = 3; + this.listeners.close?.forEach((cb) => cb({})); + } + + receive(msg: any) { + this.listeners.message?.forEach((cb) => cb({ data: JSON.stringify(msg) })); + } + + succeed(type: string) { + for (let i = this.sent.length - 1; i >= 0; i--) { + if (this.sent[i].type === type) { + const id = this.sent[i].id; + this.receive({ id, type: "result", success: true, result: null }); + return id; + } + } + throw new Error(`No sent message of type ${type}`); + } +} + +const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); + +const withFakeClock = async ( + run: (clock: { now: number; advance: (ms: number) => void }) => Promise, +) => { + const originalPerf = globalThis.performance; + const clock = { + now: 1000, + advance(ms: number) { + clock.now += ms; + }, + }; + Object.defineProperty(globalThis, "performance", { + configurable: true, + value: { now: () => clock.now }, + }); + try { + await run(clock); + } finally { + Object.defineProperty(globalThis, "performance", { + configurable: true, + value: originalPerf, + }); + } +}; + +const withMockDocument = async ( + run: (doc: { + hidden: boolean; + listeners: Map void>>; + dispatchVisibilityChange: () => void; + }) => Promise, +) => { + const hadDoc = "document" in globalThis; + const originalDoc = (globalThis as any).document; + const listeners = new Map void>>(); + const doc = { + hidden: false, + listeners, + addEventListener(type: string, cb: () => void) { + let set = listeners.get(type); + if (!set) { + set = new Set(); + listeners.set(type, set); + } + set.add(cb); + }, + removeEventListener(type: string, cb: () => void) { + listeners.get(type)?.delete(cb); + }, + dispatchVisibilityChange() { + for (const cb of [...(listeners.get("visibilitychange") ?? [])]) { + cb(); + } + }, + }; + Object.defineProperty(globalThis, "document", { + configurable: true, + value: doc, + }); + try { + await run(doc); + } finally { + if (hadDoc) { + Object.defineProperty(globalThis, "document", { + configurable: true, + value: originalDoc, + }); + } else { + delete (globalThis as any).document; + } + } +}; + describe("subscribeEntityStates legacy", () => { let conn: MockConnection; let awaitableEvent: AwaitableEvent; @@ -203,4 +328,684 @@ describe("subscribeEntityStates", () => { [MOCK_LIGHT.entity_id]: modernState(MOCK_LIGHT.entity_id, "on", 3), }); }); + + it("should publish every message synchronously by default", () => { + const updates: unknown[] = []; + subscribeEntityStates(conn, (entities) => updates.push(entities)); + + conn.mockEvent("subscribe_entities", { + a: { + [MOCK_LIGHT.entity_id]: modernEntity(MOCK_LIGHT.entity_id, "on", 1), + }, + }); + conn.mockEvent("subscribe_entities", { + c: { [MOCK_LIGHT.entity_id]: { "+": { s: "off", lc: 2 } } }, + }); + + assert.deepStrictEqual(updates, [ + { [MOCK_LIGHT.entity_id]: modernState(MOCK_LIGHT.entity_id, "on", 1) }, + { [MOCK_LIGHT.entity_id]: modernState(MOCK_LIGHT.entity_id, "off", 2) }, + ]); + }); + + it("should not apply a later snapshot on top of a message that failed", () => { + const updates: unknown[] = []; + subscribeEntityStates(conn, (entities) => updates.push(entities)); + + conn.mockEvent("subscribe_entities", { + a: { + [MOCK_LIGHT.entity_id]: modernEntity(MOCK_LIGHT.entity_id, "on", 1), + [MOCK_SWITCH.entity_id]: modernEntity(MOCK_SWITCH.entity_id, "off", 1), + }, + }); + assert.throws(() => + conn.mockEvent("subscribe_entities", { + c: { [MOCK_LIGHT.entity_id]: { "-": { a: 5 } } }, + }), + ); + conn.fireEvent("ready"); + conn.mockEvent("subscribe_entities", { + a: { + [MOCK_LIGHT.entity_id]: modernEntity(MOCK_LIGHT.entity_id, "on", 2), + }, + }); + + assert.deepStrictEqual(updates[updates.length - 1], { + [MOCK_LIGHT.entity_id]: modernState(MOCK_LIGHT.entity_id, "on", 2), + }); + }); +}); + +describe("subscribeEntityStates throttleUpdates", () => { + let conn: MockConnection; + + beforeEach(() => { + conn = new MockConnection(); + conn.haVersion = "2026.4.0"; + }); + + it("should coalesce same-task messages and update store.state immediately", async () => { + const updates: any[] = []; + const unsub = subscribeEntityStates( + conn, + (entities) => updates.push(entities), + { throttleUpdates: true }, + ); + + conn.mockEvent("subscribe_entities", { + a: { + [MOCK_LIGHT.entity_id]: modernEntity(MOCK_LIGHT.entity_id, "on", 1), + [MOCK_SWITCH.entity_id]: modernEntity(MOCK_SWITCH.entity_id, "off", 2), + }, + }); + + assert.strictEqual(updates.length, 0); + assert.strictEqual( + entityStatesColl(conn).state[MOCK_LIGHT.entity_id].state, + "on", + ); + + conn.mockEvent("subscribe_entities", { + c: { [MOCK_LIGHT.entity_id]: { "+": { s: "off", lc: 3 } } }, + }); + conn.mockEvent("subscribe_entities", { + c: { [MOCK_SWITCH.entity_id]: { "+": { s: "on", lc: 4 } } }, + }); + + assert.strictEqual(updates.length, 0); + assert.strictEqual( + entityStatesColl(conn).state[MOCK_LIGHT.entity_id].state, + "off", + ); + assert.strictEqual( + entityStatesColl(conn).state[MOCK_SWITCH.entity_id].state, + "on", + ); + + await Promise.resolve(); + + assert.deepStrictEqual(updates, [ + { + [MOCK_LIGHT.entity_id]: modernState(MOCK_LIGHT.entity_id, "off", 3), + [MOCK_SWITCH.entity_id]: modernState(MOCK_SWITCH.entity_id, "on", 4), + }, + ]); + + unsub(); + conn.fireEvent("disconnected"); + }); + + it("should not restore states torn down during a pending batch", async () => { + const unsubscribe = subscribeEntityStates(conn, () => undefined, { + throttleUpdates: true, + }); + unsubscribe(); + + conn.mockEvent("subscribe_entities", { + a: { + [MOCK_LIGHT.entity_id]: modernEntity(MOCK_LIGHT.entity_id, "on", 1), + }, + }); + conn.fireEvent("disconnected"); + + await Promise.resolve(); + + assert.strictEqual(entityStatesColl(conn).state, undefined); + }); + + it("should coalesce updates across cooldown window with leading and trailing edge", async function () { + this.timeout(500); + await withFakeClock(async (clock) => { + const updates: any[] = []; + const unsub = subscribeEntityStates( + conn, + (entities) => { + updates.push(entities); + // Simulate 6ms publish work -> emaCostMs=6 -> 6/0.12 = 50ms cooldown + clock.advance(6); + }, + { + throttleUpdates: { + targetDutyCycle: 0.12, + minIntervalMs: 16, + maxIntervalMs: 1000, + }, + }, + ); + + // Initial snapshot flushes immediately in microtask + conn.mockEvent("subscribe_entities", { + a: { + [MOCK_LIGHT.entity_id]: modernEntity(MOCK_LIGHT.entity_id, "on", 1), + [MOCK_SWITCH.entity_id]: modernEntity( + MOCK_SWITCH.entity_id, + "off", + 1, + ), + }, + }); + await Promise.resolve(); + // Let MessageChannel probe complete + await wait(5); + assert.strictEqual(updates.length, 1); + const publishedFirst = updates[0]; + + // Within cooldown window (elapsed = 10ms < 50ms) + clock.advance(10); + conn.mockEvent("subscribe_entities", { + c: { [MOCK_LIGHT.entity_id]: { "+": { s: "off", lc: 2 } } }, + }); + clock.advance(10); + conn.mockEvent("subscribe_entities", { + c: { [MOCK_SWITCH.entity_id]: { "+": { s: "on", lc: 3 } } }, + }); + + await Promise.resolve(); + // Not published yet, but store.state is immediately updated and publishedFirst is untouched + assert.strictEqual(updates.length, 1); + assert.strictEqual(publishedFirst[MOCK_LIGHT.entity_id].state, "on"); + assert.strictEqual( + entityStatesColl(conn).state[MOCK_LIGHT.entity_id].state, + "off", + ); + assert.strictEqual( + entityStatesColl(conn).state[MOCK_SWITCH.entity_id].state, + "on", + ); + + // Wait for trailing edge (~40ms remaining) + clock.advance(45); + await wait(55); + assert.strictEqual(updates.length, 2); + assert.strictEqual(updates[1][MOCK_LIGHT.entity_id].state, "off"); + assert.strictEqual(updates[1][MOCK_SWITCH.entity_id].state, "on"); + + // After idle period (>= throttleMs), next event flushes on leading edge + clock.advance(100); + conn.mockEvent("subscribe_entities", { + c: { [MOCK_LIGHT.entity_id]: { "+": { s: "on", lc: 4 } } }, + }); + await Promise.resolve(); + assert.strictEqual(updates.length, 3); + assert.strictEqual(updates[2][MOCK_LIGHT.entity_id].state, "on"); + + unsub(); + conn.fireEvent("disconnected"); + }); + }); + + it("should fast-path matching userId updates during cooldown", async function () { + this.timeout(500); + await withFakeClock(async (clock) => { + let currentUser: string | undefined = "user-1"; + const updates: any[] = []; + const unsub = subscribeEntityStates( + conn, + (entities) => { + updates.push(entities); + clock.advance(12); // -> 100ms cooldown + }, + { + throttleUpdates: { + targetDutyCycle: 0.12, + userId: () => currentUser, + }, + }, + ); + + conn.mockEvent("subscribe_entities", { + a: { + [MOCK_LIGHT.entity_id]: modernEntity(MOCK_LIGHT.entity_id, "on", 1), + [MOCK_SWITCH.entity_id]: modernEntity( + MOCK_SWITCH.entity_id, + "off", + 1, + ), + }, + }); + await Promise.resolve(); + await wait(5); + assert.strictEqual(updates.length, 1); + + // Background update during cooldown stays pending + clock.advance(5); + conn.mockEvent("subscribe_entities", { + c: { [MOCK_SWITCH.entity_id]: { "+": { s: "on", lc: 2 } } }, + }); + await Promise.resolve(); + assert.strictEqual(updates.length, 1); + + // Matching user_id update cancels cooldown timer and flushes immediately in microtask + clock.advance(5); + conn.mockEvent("subscribe_entities", { + c: { + [MOCK_LIGHT.entity_id]: { + "+": { + s: "off", + lc: 3, + c: { id: "ctx-user", user_id: "user-1", parent_id: null }, + }, + }, + }, + }); + await Promise.resolve(); + assert.strictEqual(updates.length, 2); + assert.strictEqual(updates[1][MOCK_LIGHT.entity_id].state, "off"); + assert.strictEqual(updates[1][MOCK_SWITCH.entity_id].state, "on"); + + // Compressed string context keeping same user_id also fast-paths + clock.advance(5); + conn.mockEvent("subscribe_entities", { + c: { + [MOCK_LIGHT.entity_id]: { + "+": { s: "on", lc: 4, c: "ctx-user-2" }, + }, + }, + }); + await Promise.resolve(); + assert.strictEqual(updates.length, 3); + assert.strictEqual(updates[2][MOCK_LIGHT.entity_id].state, "on"); + + // Same context reused (Core omits `c` from diff) also fast-paths + clock.advance(5); + conn.mockEvent("subscribe_entities", { + c: { + [MOCK_LIGHT.entity_id]: { + "+": { a: { brightness: 200 }, lu: 5 }, + }, + }, + }); + await Promise.resolve(); + assert.strictEqual(updates.length, 4); + assert.strictEqual( + updates[3][MOCK_LIGHT.entity_id].attributes.brightness, + 200, + ); + + // Update with context cleared to user_id: null does not fast-path + clock.advance(5); + conn.mockEvent("subscribe_entities", { + c: { + [MOCK_LIGHT.entity_id]: { + "+": { + s: "off", + lc: 6, + c: { id: "ctx-auto", user_id: null, parent_id: null }, + }, + }, + }, + }); + await Promise.resolve(); + assert.strictEqual(updates.length, 4); + + // Dynamic getter returning undefined userId does not fast-path + currentUser = undefined; + clock.advance(5); + conn.mockEvent("subscribe_entities", { + c: { + [MOCK_LIGHT.entity_id]: { + "+": { + s: "on", + lc: 7, + c: { id: "ctx-other", user_id: "user-1", parent_id: null }, + }, + }, + }, + }); + await Promise.resolve(); + assert.strictEqual(updates.length, 4); + + unsub(); + conn.fireEvent("disconnected"); + }); + }); + + it("should fast-path entities targeted by call_service on the connection", async function () { + this.timeout(500); + await withFakeClock(async (clock) => { + const socket = new FakeSocket(); + const realConn = new Connection(socket as any, { + setupRetry: 0, + createSocket: async () => new FakeSocket() as any, + }); + + const updates: any[] = []; + const unsub = subscribeEntityStates( + realConn, + (entities) => { + updates.push(entities); + clock.advance(12); // -> 100ms cooldown + }, + { throttleUpdates: true }, + ); + + const subId = socket.succeed("subscribe_entities"); + socket.receive({ + id: subId, + type: "event", + event: { + a: { + [MOCK_LIGHT.entity_id]: modernEntity( + MOCK_LIGHT.entity_id, + "off", + 1, + ), + [MOCK_SWITCH.entity_id]: modernEntity( + MOCK_SWITCH.entity_id, + "off", + 1, + ), + }, + }, + }); + await Promise.resolve(); + await wait(5); + assert.strictEqual(updates.length, 1); + + // Call service targeting light.kitchen via target.entity_id + const svcProm = callService(realConn, "light", "turn_on", undefined, { + entity_id: MOCK_LIGHT.entity_id, + }); + socket.succeed("call_service"); + await svcProm; + + // Unrelated entity stays throttled during cooldown + clock.advance(10); + socket.receive({ + id: subId, + type: "event", + event: { + c: { [MOCK_SWITCH.entity_id]: { "+": { s: "on", lc: 2 } } }, + }, + }); + await Promise.resolve(); + assert.strictEqual(updates.length, 1); + + // Targeted entity flushes immediately in current microtask + clock.advance(10); + socket.receive({ + id: subId, + type: "event", + event: { + c: { [MOCK_LIGHT.entity_id]: { "+": { s: "on", lc: 3 } } }, + }, + }); + await Promise.resolve(); + assert.strictEqual(updates.length, 2); + assert.strictEqual(updates[1][MOCK_LIGHT.entity_id].state, "on"); + + // Also works with service_data.entity_id array + const svcProm2 = callService(realConn, "switch", "turn_off", { + entity_id: [MOCK_SWITCH.entity_id], + }); + socket.succeed("call_service"); + await svcProm2; + + clock.advance(5); + socket.receive({ + id: subId, + type: "event", + event: { + c: { [MOCK_SWITCH.entity_id]: { "+": { s: "off", lc: 4 } } }, + }, + }); + await Promise.resolve(); + assert.strictEqual(updates.length, 3); + assert.strictEqual(updates[2][MOCK_SWITCH.entity_id].state, "off"); + + unsub(); + realConn.close(); + }); + }); + + it("should defer updates while document is hidden and flush on visibilitychange", async () => { + await withMockDocument(async (doc) => { + const updates: any[] = []; + const unsub = subscribeEntityStates( + conn, + (entities) => updates.push(entities), + { throttleUpdates: true }, + ); + + conn.mockEvent("subscribe_entities", { + a: { + [MOCK_LIGHT.entity_id]: modernEntity(MOCK_LIGHT.entity_id, "on", 1), + [MOCK_SWITCH.entity_id]: modernEntity( + MOCK_SWITCH.entity_id, + "off", + 1, + ), + }, + }); + await Promise.resolve(); + assert.strictEqual(updates.length, 1); + + doc.hidden = true; + doc.dispatchVisibilityChange(); + + conn.mockEvent("subscribe_entities", { + c: { [MOCK_LIGHT.entity_id]: { "+": { s: "off", lc: 2 } } }, + }); + conn.mockEvent("subscribe_entities", { + c: { [MOCK_SWITCH.entity_id]: { "+": { s: "on", lc: 3 } } }, + }); + + await Promise.resolve(); + assert.strictEqual(updates.length, 1); + assert.strictEqual( + entityStatesColl(conn).state[MOCK_LIGHT.entity_id].state, + "off", + ); + assert.strictEqual( + entityStatesColl(conn).state[MOCK_SWITCH.entity_id].state, + "on", + ); + + doc.hidden = false; + doc.dispatchVisibilityChange(); + + assert.strictEqual(updates.length, 2); + assert.strictEqual(updates[1][MOCK_LIGHT.entity_id].state, "off"); + assert.strictEqual(updates[1][MOCK_SWITCH.entity_id].state, "on"); + + // Becoming visible again with no pending updates does not spuriously publish + doc.hidden = true; + doc.dispatchVisibilityChange(); + doc.hidden = false; + doc.dispatchVisibilityChange(); + assert.strictEqual(updates.length, 2); + + unsub(); + conn.fireEvent("disconnected"); + await Promise.resolve(); + assert.strictEqual(doc.listeners.get("visibilitychange")?.size ?? 0, 0); + }); + }); + + it("should not mutate pending state already delivered to a joining subscriber", async () => { + await withMockDocument(async (doc) => { + doc.hidden = true; + const unsub1 = subscribeEntityStates(conn, () => undefined, { + throttleUpdates: true, + }); + + conn.mockEvent("subscribe_entities", { + a: { + [MOCK_LIGHT.entity_id]: modernEntity(MOCK_LIGHT.entity_id, "off", 1), + }, + }); + flushEntityStates(conn); + + // First hidden update creates a pending batch + conn.mockEvent("subscribe_entities", { + c: { [MOCK_LIGHT.entity_id]: { "+": { s: "on", lc: 2 } } }, + }); + + // Second subscriber joins while batch is pending and receives initial state + const sub2Updates: any[] = []; + const unsub2 = subscribeEntityStates(conn, (entities) => + sub2Updates.push(entities), + ); + await wait(5); + assert.strictEqual(sub2Updates.length, 1); + const initialRef = sub2Updates[0]; + assert.strictEqual(initialRef[MOCK_LIGHT.entity_id].state, "on"); + + // Another hidden update arrives: must NOT mutate initialRef + conn.mockEvent("subscribe_entities", { + c: { [MOCK_LIGHT.entity_id]: { "+": { s: "off", lc: 3 } } }, + }); + assert.strictEqual(initialRef[MOCK_LIGHT.entity_id].state, "on"); + + // Resume flush delivers a new reference with the latest state + doc.hidden = false; + doc.dispatchVisibilityChange(); + assert.strictEqual(sub2Updates.length, 2); + assert.notStrictEqual(sub2Updates[1], initialRef); + assert.strictEqual(sub2Updates[1][MOCK_LIGHT.entity_id].state, "off"); + + unsub2(); + unsub1(); + conn.fireEvent("disconnected"); + }); + }); + + it("should clear pending batch on reconnect ready and replace cleanly", async function () { + this.timeout(500); + await withFakeClock(async (clock) => { + const updates: any[] = []; + const unsub = subscribeEntityStates( + conn, + (entities) => { + updates.push(entities); + clock.advance(12); // -> 100ms cooldown + }, + { throttleUpdates: true }, + ); + + conn.mockEvent("subscribe_entities", { + a: { + [MOCK_LIGHT.entity_id]: modernEntity(MOCK_LIGHT.entity_id, "on", 1), + "sensor.ghost_probe": modernEntity("sensor.ghost_probe", "1", 1), + }, + }); + await Promise.resolve(); + await wait(5); + assert.strictEqual(updates.length, 1); + + // Queue an update inside cooldown + clock.advance(5); + conn.mockEvent("subscribe_entities", { + c: { [MOCK_LIGHT.entity_id]: { "+": { s: "off", lc: 2 } } }, + }); + await Promise.resolve(); + assert.strictEqual(updates.length, 1); + + // Reconnect fires ready: stale pending batch is dropped and timer cancelled + conn.fireEvent("ready"); + await wait(120); + assert.strictEqual(updates.length, 1); + + // New snapshot replaces state cleanly and flushes immediately (ignoring cooldown) + conn.mockEvent("subscribe_entities", { + a: { + [MOCK_LIGHT.entity_id]: modernEntity(MOCK_LIGHT.entity_id, "on", 3), + }, + }); + await Promise.resolve(); + assert.strictEqual(updates.length, 2); + assert.deepStrictEqual(updates[1], { + [MOCK_LIGHT.entity_id]: modernState(MOCK_LIGHT.entity_id, "on", 3), + }); + + unsub(); + conn.fireEvent("disconnected"); + }); + }); + + it("should support flushEntityStates for explicit synchronous flush", async () => { + const updates: any[] = []; + const unsub = subscribeEntityStates( + conn, + (entities) => updates.push(entities), + { throttleUpdates: true }, + ); + + conn.mockEvent("subscribe_entities", { + a: { + [MOCK_LIGHT.entity_id]: modernEntity(MOCK_LIGHT.entity_id, "on", 1), + }, + }); + + assert.strictEqual(updates.length, 0); + flushEntityStates(conn); + assert.strictEqual(updates.length, 1); + assert.strictEqual(updates[0][MOCK_LIGHT.entity_id].state, "on"); + + // Microtask does not double-flush + await Promise.resolve(); + assert.strictEqual(updates.length, 1); + + unsub(); + conn.fireEvent("disconnected"); + await Promise.resolve(); + + // No-op after teardown + flushEntityStates(conn); + assert.strictEqual(updates.length, 1); + }); + + it("should warn when throttleUpdates does not match the existing collection", () => { + const warn = console.warn; + const warnings: unknown[][] = []; + console.warn = (...args: unknown[]) => { + warnings.push(args); + }; + try { + entityStatesColl(conn, { throttleUpdates: true }); + entityStatesColl(conn); + entityStatesColl(conn, { throttleUpdates: true }); + entityStatesColl(conn, { throttleUpdates: {} }); + assert.strictEqual(warnings.length, 0); + + entityStatesColl(conn, { throttleUpdates: false }); + assert.strictEqual(warnings.length, 1); + + entityStatesColl(conn, { throttleUpdates: { maxIntervalMs: 500 } }); + assert.strictEqual(warnings.length, 2); + + const conn2 = new MockConnection(); + conn2.haVersion = "2026.4.0"; + entityStatesColl(conn2); + entityStatesColl(conn2, { throttleUpdates: false }); + assert.strictEqual(warnings.length, 2); + entityStatesColl(conn2, { throttleUpdates: true }); + assert.strictEqual(warnings.length, 3); + } finally { + console.warn = warn; + } + }); + + it("should clean up listeners if subscribe_entities fails", async () => { + await withMockDocument(async (doc) => { + const socket = new FakeSocket(); + const realConn = new Connection(socket as any, { + setupRetry: 0, + createSocket: async () => new FakeSocket() as any, + }); + + const unsub = subscribeEntityStates(realConn, () => undefined, { + throttleUpdates: true, + }); + assert.strictEqual(doc.listeners.get("visibilitychange")?.size, 1); + assert.strictEqual(realConn.eventListeners.get("ready")?.length, 1); + + realConn.close(); + await wait(10); + + assert.strictEqual(doc.listeners.get("visibilitychange")?.size ?? 0, 0); + assert.strictEqual(realConn.eventListeners.get("ready")?.length ?? 0, 0); + unsub(); + }); + }); }); diff --git a/test/throttle.spec.ts b/test/throttle.spec.ts new file mode 100644 index 00000000..1b973496 --- /dev/null +++ b/test/throttle.spec.ts @@ -0,0 +1,736 @@ +import * as assert from "assert"; + +import { createStore } from "../dist/store.js"; +import { + createStateUpdateThrottler, + resolveThrottleOptions, + throttleOptionsEqual, +} from "../dist/throttle.js"; +import { notifyServiceCall } from "../dist/util.js"; +import { MockConnection } from "./util.ts"; + +const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); + +const makeEntity = ( + entity_id: string, + state: string, + userId: string | null = null, +) => ({ + entity_id, + state, + attributes: {}, + context: { id: "c1", parent_id: null, user_id: userId }, + last_changed: "2026-01-01T00:00:00.000Z", + last_updated: "2026-01-01T00:00:00.000Z", +}); + +const simpleApply = (state: Record, ev: any) => { + if (ev.a) { + Object.assign(state, ev.a); + } + if (ev.r) { + for (const id of ev.r) { + delete state[id]; + } + } + if (ev.c) { + for (const id in ev.c) { + if (state[id]) { + state[id] = { + ...state[id], + state: ev.c[id]["+"]?.s ?? state[id].state, + context: ev.c[id]["+"]?.c + ? typeof ev.c[id]["+"]?.c === "string" + ? { ...state[id].context, id: ev.c[id]["+"]?.c } + : { ...state[id].context, ...ev.c[id]["+"]?.c } + : state[id].context, + }; + } + } + } +}; + +const withFakeClock = async ( + run: (clock: { now: number; advance: (ms: number) => void }) => Promise, +) => { + const originalPerf = globalThis.performance; + const clock = { + now: 1000, + advance(ms: number) { + clock.now += ms; + }, + }; + Object.defineProperty(globalThis, "performance", { + configurable: true, + value: { now: () => clock.now }, + }); + try { + await run(clock); + } finally { + Object.defineProperty(globalThis, "performance", { + configurable: true, + value: originalPerf, + }); + } +}; + +const withNoMessageChannel = async (run: () => Promise) => { + const originalMC = globalThis.MessageChannel; + Object.defineProperty(globalThis, "MessageChannel", { + configurable: true, + value: undefined, + }); + try { + await run(); + } finally { + Object.defineProperty(globalThis, "MessageChannel", { + configurable: true, + value: originalMC, + }); + } +}; + +const withMockRaf = async ( + run: (raf: { + pending: Map void>; + cancelled: number[]; + flushOne: () => void; + }) => Promise, +) => { + const hadRaf = "requestAnimationFrame" in globalThis; + const hadCancel = "cancelAnimationFrame" in globalThis; + const originalRaf = (globalThis as any).requestAnimationFrame; + const originalCancel = (globalThis as any).cancelAnimationFrame; + + let nextId = 1; + const pending = new Map void>(); + const cancelled: number[] = []; + + Object.defineProperty(globalThis, "requestAnimationFrame", { + configurable: true, + value: (cb: () => void) => { + const id = nextId++; + pending.set(id, cb); + return id; + }, + }); + Object.defineProperty(globalThis, "cancelAnimationFrame", { + configurable: true, + value: (id: number) => { + cancelled.push(id); + pending.delete(id); + }, + }); + + try { + await run({ + pending, + cancelled, + flushOne() { + const first = pending.entries().next().value; + if (!first) { + return; + } + const [id, cb] = first; + pending.delete(id); + cb(); + }, + }); + } finally { + if (hadRaf) { + Object.defineProperty(globalThis, "requestAnimationFrame", { + configurable: true, + value: originalRaf, + }); + } else { + delete (globalThis as any).requestAnimationFrame; + } + if (hadCancel) { + Object.defineProperty(globalThis, "cancelAnimationFrame", { + configurable: true, + value: originalCancel, + }); + } else { + delete (globalThis as any).cancelAnimationFrame; + } + } +}; + +const withMockDocument = async ( + run: (doc: { + hidden: boolean; + listeners: Map void>>; + dispatchVisibilityChange: () => void; + }) => Promise, +) => { + const hadDoc = "document" in globalThis; + const originalDoc = (globalThis as any).document; + const listeners = new Map void>>(); + const doc = { + hidden: false, + listeners, + addEventListener(type: string, cb: () => void) { + let set = listeners.get(type); + if (!set) { + set = new Set(); + listeners.set(type, set); + } + set.add(cb); + }, + removeEventListener(type: string, cb: () => void) { + listeners.get(type)?.delete(cb); + }, + dispatchVisibilityChange() { + for (const cb of [...(listeners.get("visibilitychange") ?? [])]) { + cb(); + } + }, + }; + Object.defineProperty(globalThis, "document", { + configurable: true, + value: doc, + }); + try { + await run(doc); + } finally { + if (hadDoc) { + Object.defineProperty(globalThis, "document", { + configurable: true, + value: originalDoc, + }); + } else { + delete (globalThis as any).document; + } + } +}; + +describe("throttle options resolution", () => { + it("resolves defaults and falls back on invalid numbers", () => { + assert.strictEqual(resolveThrottleOptions(undefined), undefined); + assert.strictEqual(resolveThrottleOptions(false), undefined); + assert.deepStrictEqual(resolveThrottleOptions(true), { + targetDutyCycle: 0.12, + minIntervalMs: 16, + maxIntervalMs: 1000, + snapshotThresholdMsPer1k: 4.0, + userId: undefined, + pauseWhenHidden: true, + }); + assert.deepStrictEqual( + resolveThrottleOptions({ + targetDutyCycle: -1, + minIntervalMs: Number.NaN, + maxIntervalMs: Number.POSITIVE_INFINITY, + snapshotThresholdMsPer1k: -5, + pauseWhenHidden: false, + }), + { + targetDutyCycle: 0.12, + minIntervalMs: 16, + maxIntervalMs: 1000, + snapshotThresholdMsPer1k: 4.0, + userId: undefined, + pauseWhenHidden: false, + }, + ); + }); + + it("compares normalized options accurately", () => { + const defA = resolveThrottleOptions(true)!; + const defB = resolveThrottleOptions({})!; + const custom = resolveThrottleOptions({ maxIntervalMs: 500 })!; + assert.strictEqual(throttleOptionsEqual(false, false), true); + assert.strictEqual(throttleOptionsEqual(defA, defB), true); + assert.strictEqual(throttleOptionsEqual(defA, false), false); + assert.strictEqual(throttleOptionsEqual(defA, custom), false); + }); +}); + +describe("createStateUpdateThrottler", () => { + it("seeds EMA from slow Day-0 snapshot while publishing initial snapshot immediately", async () => { + await withFakeClock(async (clock) => { + await withNoMessageChannel(async () => { + const conn = new MockConnection(); + const store = createStore>(); + const published: any[] = []; + store.subscribe((s) => published.push(s)); + + const throttler = createStateUpdateThrottler( + conn, + store, + resolveThrottleOptions(true)!, + (state, ev) => { + simpleApply(state, ev); + // Simulate 10ms processing for 1000 entities -> msPer1k = 10 > 4.0 + if (ev.a && Object.keys(ev.a).length === 1000) { + clock.advance(10); + } + }, + ); + + const initial: Record = {}; + for (let i = 0; i < 1000; i++) { + initial[`sensor.s${i}`] = makeEntity(`sensor.s${i}`, "0"); + } + + throttler.handleEvent({ a: initial }); + + // Day-0 seed: emaCostMs = 10 * 1.4 = 14 -> raw = 14 / 0.12 = 116.67 -> 117ms + assert.strictEqual(throttler.emaCostMs, 14); + assert.strictEqual(throttler.throttleMs, 117); + + // Initial snapshot itself still flushes immediately in microtask + await Promise.resolve(); + assert.strictEqual(published.length, 1); + + // First incremental update right after snapshot is already protected by cooldown + clock.advance(5); + throttler.handleEvent({ c: { "sensor.s0": { "+": { s: "1" } } } }); + await Promise.resolve(); + assert.strictEqual(published.length, 1); + + throttler.destroy(); + }); + }); + }); + + it("does not seed Day-0 when snapshot is fast", async () => { + await withFakeClock(async (clock) => { + await withNoMessageChannel(async () => { + const conn = new MockConnection(); + const store = createStore>(); + const published: any[] = []; + store.subscribe((s) => published.push(s)); + + const throttler = createStateUpdateThrottler( + conn, + store, + resolveThrottleOptions(true)!, + (state, ev) => { + simpleApply(state, ev); + clock.advance(1); // 1ms for 1000 entities -> msPer1k = 1 <= 4.0 + }, + ); + + const initial: Record = {}; + for (let i = 0; i < 1000; i++) { + initial[`sensor.s${i}`] = makeEntity(`sensor.s${i}`, "0"); + } + + throttler.handleEvent({ a: initial }); + assert.strictEqual(throttler.emaCostMs, 0); + assert.strictEqual(throttler.throttleMs, 0); + + await Promise.resolve(); + assert.strictEqual(published.length, 1); + assert.strictEqual(throttler.throttleMs, 0); + + throttler.destroy(); + }); + }); + }); + + it("scales EMA with alpha=0.25 and winsorizes outlier samples at 200ms", async () => { + await withFakeClock(async (clock) => { + await withNoMessageChannel(async () => { + const conn = new MockConnection(); + const store = createStore>(); + let publishCost = 20; + store.subscribe(() => { + clock.advance(publishCost); + }); + + const throttler = createStateUpdateThrottler( + conn, + store, + resolveThrottleOptions({ + targetDutyCycle: 0.12, + minIntervalMs: 16, + maxIntervalMs: 1000, + })!, + simpleApply, + ); + + // Sample 1: 20ms -> ema = 20, throttle = Math.round(20 / 0.12) = 167 + throttler.handleEvent({ + a: { "light.a": makeEntity("light.a", "on") }, + }); + await Promise.resolve(); + assert.strictEqual(throttler.emaCostMs, 20); + assert.strictEqual(throttler.throttleMs, 167); + + // Sample 2: 5000ms outlier -> winsorized to 200ms -> ema = 0.25*200 + 0.75*20 = 65 + // throttle = Math.round(65 / 0.12) = 542 + publishCost = 5000; + clock.advance(200); + throttler.handleEvent({ c: { "light.a": { "+": { s: "off" } } } }); + await Promise.resolve(); + assert.strictEqual(throttler.emaCostMs, 65); + assert.strictEqual(throttler.throttleMs, 542); + + // Sample 3: 200ms -> ema = 0.25*200 + 0.75*65 = 98.75 -> 823ms + // Sample 4: 200ms -> ema = 0.25*200 + 0.75*98.75 = 124.0625 -> capped at maxIntervalMs (1000) + publishCost = 200; + clock.advance(600); + throttler.handleEvent({ c: { "light.a": { "+": { s: "on" } } } }); + await Promise.resolve(); + assert.strictEqual(throttler.throttleMs, 823); + + clock.advance(900); + throttler.handleEvent({ c: { "light.a": { "+": { s: "off" } } } }); + await Promise.resolve(); + assert.strictEqual(throttler.throttleMs, 1000); + + // Fast publishes decay EMA back toward 0ms throttle + publishCost = 0.5; + for (let i = 0; i < 20; i++) { + clock.advance(1100); + throttler.handleEvent({ + c: { "light.a": { "+": { s: i % 2 === 0 ? "on" : "off" } } }, + }); + await Promise.resolve(); + } + assert.strictEqual(throttler.throttleMs, 0); + + throttler.destroy(); + }); + }); + }); + + it("measures jsMs + paintMs via Split MessageChannel + rAF without vsync-wait bias", async () => { + await withFakeClock(async (clock) => { + await withMockRaf(async (raf) => { + const conn = new MockConnection(); + const store = createStore>(); + store.subscribe(() => { + // 4ms synchronous work + clock.advance(4); + // 2ms microtask Lit render work + Promise.resolve().then(() => { + clock.advance(2); + }); + }); + + const throttler = createStateUpdateThrottler( + conn, + store, + resolveThrottleOptions(true)!, + simpleApply, + ); + + throttler.handleEvent({ + a: { "light.a": makeEntity("light.a", "on") }, + }); + await Promise.resolve(); + + // Let mcA fire after microtasks (jsMs = 4 + 2 = 6ms), scheduling rAF + await wait(5); + assert.strictEqual(raf.pending.size, 1); + assert.strictEqual(throttler.emaCostMs, 0); + + // Simulate 14ms idle vsync wait before rAF fires (must NOT be counted!) + clock.advance(14); + raf.flushOne(); + + // Simulate 3ms browser style/layout/paint work before mcB completes + clock.advance(3); + await wait(5); + + // Total sample should be jsMs (6) + paintMs (3) = 9ms, NOT 6 + 14 + 3 = 23ms + assert.strictEqual(throttler.emaCostMs, 9); + assert.strictEqual(throttler.throttleMs, Math.round(9 / 0.12)); + + throttler.destroy(); + }); + }); + }); + + it("skips EMA measurement on hidden-tab resume flush and cancels in-flight rAF on hide", async () => { + await withFakeClock(async (clock) => { + await withMockDocument(async (doc) => { + await withMockRaf(async (raf) => { + const conn = new MockConnection(); + const store = createStore>(); + let publishCost = 10; + store.subscribe(() => { + clock.advance(publishCost); + }); + + const throttler = createStateUpdateThrottler( + conn, + store, + resolveThrottleOptions(true)!, + simpleApply, + ); + + // First publish starts probe -> mcA fires -> rAF is pending + throttler.handleEvent({ + a: { "light.a": makeEntity("light.a", "on") }, + }); + await Promise.resolve(); + await wait(5); + assert.strictEqual(raf.pending.size, 1); + + // Tab hides while probe is in flight -> rAF cancelled + doc.hidden = true; + doc.dispatchVisibilityChange(); + assert.strictEqual(raf.pending.size, 0); + assert.strictEqual(raf.cancelled.length, 1); + assert.strictEqual(throttler.emaCostMs, 0); + + // Update arrives while hidden, then resume flush takes 80ms -> must NOT pollute EMA + publishCost = 80; + throttler.handleEvent({ c: { "light.a": { "+": { s: "off" } } } }); + doc.hidden = false; + doc.dispatchVisibilityChange(); + await wait(5); + assert.strictEqual(raf.pending.size, 0); + assert.strictEqual(throttler.emaCostMs, 0); + + // Next normal visible publish runs probe cleanly (probeInFlight was properly reset) + publishCost = 12; + clock.advance(10); + throttler.handleEvent({ c: { "light.a": { "+": { s: "on" } } } }); + await Promise.resolve(); + await wait(5); + assert.strictEqual(raf.pending.size, 1); + raf.flushOne(); + await wait(5); + assert.strictEqual(throttler.emaCostMs, 12); + + throttler.destroy(); + }); + }); + }); + }); + + it("expires tracked call_service entity targets after 2000ms TTL and fast-paths removals", async () => { + await withFakeClock(async (clock) => { + await withNoMessageChannel(async () => { + const conn = new MockConnection(); + const store = createStore>(); + const published: any[] = []; + store.subscribe((s) => { + published.push(s); + clock.advance(18); // -> 150ms cooldown + }); + + const throttler = createStateUpdateThrottler( + conn, + store, + resolveThrottleOptions(true)!, + simpleApply, + ); + + throttler.handleEvent({ + a: { + "light.a": makeEntity("light.a", "on"), + "light.b": makeEntity("light.b", "on"), + }, + }); + await Promise.resolve(); + assert.strictEqual(published.length, 1); + assert.strictEqual(throttler.throttleMs, 150); + + // Record service call targeting light.a and light.b + notifyServiceCall(conn, { + type: "call_service", + domain: "light", + service: "turn_off", + target: { entity_id: ["light.a", "light.b"] }, + }); + + // Removal of targeted entity within 2000ms fast-paths during cooldown + clock.advance(10); + throttler.handleEvent({ r: ["light.b"] }); + await Promise.resolve(); + assert.strictEqual(published.length, 2); + assert.strictEqual(published[1]["light.b"], undefined); + + // Advance past 2000ms TTL, publish once on leading edge to start a fresh cooldown + clock.advance(2005); + throttler.handleEvent({ c: { "light.a": { "+": { s: "off" } } } }); + await Promise.resolve(); + assert.strictEqual(published.length, 3); + + // Now light.a target is expired -> does NOT fast-path during cooldown + clock.advance(10); + throttler.handleEvent({ c: { "light.a": { "+": { s: "on" } } } }); + await Promise.resolve(); + assert.strictEqual(published.length, 3); + + throttler.destroy(); + }); + }); + }); + + it("publishes while hidden when pauseWhenHidden is false without running EMA probe", async () => { + await withFakeClock(async (clock) => { + await withMockDocument(async (doc) => { + await withNoMessageChannel(async () => { + const conn = new MockConnection(); + const store = createStore>(); + const published: any[] = []; + store.subscribe((s) => { + published.push(s); + clock.advance(30); + }); + + const throttler = createStateUpdateThrottler( + conn, + store, + resolveThrottleOptions({ pauseWhenHidden: false })!, + simpleApply, + ); + + doc.hidden = true; + throttler.handleEvent({ + a: { "light.a": makeEntity("light.a", "on") }, + }); + await Promise.resolve(); + + assert.strictEqual(published.length, 1); + assert.strictEqual(throttler.emaCostMs, 0); + + throttler.destroy(); + }); + }); + }); + }); + + it("cleans up timers, rAF, MessageChannel ports, and listeners on destroy", async function () { + this.timeout(500); + await withFakeClock(async (clock) => { + await withMockDocument(async (doc) => { + await withMockRaf(async (raf) => { + const originalMC = globalThis.MessageChannel; + let closedPorts = 0; + + class TrackingMessageChannel { + port1: MessagePort; + port2: MessagePort; + constructor() { + const real = new originalMC(); + this.port1 = real.port1; + this.port2 = real.port2; + const close1 = real.port1.close.bind(real.port1); + const close2 = real.port2.close.bind(real.port2); + real.port1.close = () => { + closedPorts++; + close1(); + }; + real.port2.close = () => { + closedPorts++; + close2(); + }; + } + } + + Object.defineProperty(globalThis, "MessageChannel", { + configurable: true, + value: TrackingMessageChannel, + }); + + try { + const conn = new MockConnection(); + const store = createStore>(); + const published: any[] = []; + store.subscribe((s) => { + published.push(s); + clock.advance(12); + }); + + const throttler = createStateUpdateThrottler( + conn, + store, + resolveThrottleOptions(true)!, + simpleApply, + ); + + assert.strictEqual(doc.listeners.get("visibilitychange")?.size, 1); + + // Publish #1 -> starts mcA + rAF + mcB + throttler.handleEvent({ + a: { "light.a": makeEntity("light.a", "on") }, + }); + await Promise.resolve(); + await wait(5); + raf.flushOne(); + await wait(5); + assert.strictEqual(throttler.throttleMs, 100); + + // Publish #2 after cooldown -> starts probe with pending rAF + clock.advance(120); + throttler.handleEvent({ c: { "light.a": { "+": { s: "off" } } } }); + await Promise.resolve(); + await wait(5); + assert.strictEqual(raf.pending.size, 1); + + // Arm cooldown timer too + clock.advance(10); + throttler.handleEvent({ c: { "light.a": { "+": { s: "on" } } } }); + + throttler.destroy(); + + // Verify rAF cancelled, all 4 ports (mcA + mcB) closed, visibility listener removed + assert.strictEqual(raf.pending.size, 0); + assert.strictEqual(raf.cancelled.length, 1); + assert.strictEqual(closedPorts, 4); + assert.strictEqual(doc.listeners.get("visibilitychange")?.size, 0); + + // Cooldown timer must NOT fire after destroy + await wait(120); + assert.strictEqual(published.length, 2); + } finally { + Object.defineProperty(globalThis, "MessageChannel", { + configurable: true, + value: originalMC, + }); + } + }); + }); + }); + }); + + it("recovers cleanly if a subscriber throws during flush", async () => { + await withFakeClock(async (clock) => { + await withNoMessageChannel(async () => { + const conn = new MockConnection(); + const store = createStore>(); + let shouldThrow = true; + const received: any[] = []; + + store.subscribe((s) => { + if (shouldThrow) { + shouldThrow = false; + throw new Error("subscriber boom"); + } + received.push(s); + clock.advance(12); + }); + + const throttler = createStateUpdateThrottler( + conn, + store, + resolveThrottleOptions(true)!, + simpleApply, + ); + + throttler.handleEvent({ + a: { "light.a": makeEntity("light.a", "on") }, + }); + assert.throws(() => throttler.flush(), /subscriber boom/); + assert.strictEqual(throttler.emaCostMs, 0); + + // Next update publishes and probes normally + clock.advance(10); + throttler.handleEvent({ c: { "light.a": { "+": { s: "off" } } } }); + await Promise.resolve(); + assert.strictEqual(received.length, 1); + assert.strictEqual(throttler.emaCostMs, 12); + + throttler.destroy(); + }); + }); + }); +});