Compare commits

...
Author SHA1 Message Date
Petar Petrov 5cc5f644e9 Add passive adaptive entity state throttling on slow devices 2026-12-04 10:13:12 +02:00
5 changed files with 429 additions and 3 deletions

No files matched your search

+1
View File
@@ -6,4 +6,5 @@ export interface WindowWithPreloads extends Window {
llConfProm?: Promise<LovelaceRawConfig>;
llResProm?: Promise<LovelaceResource[]>;
recorderInfoProm?: Promise<RecorderInfo>;
entityStateThrottleMs?: () => number;
}
+4 -2
View File
@@ -177,7 +177,10 @@ window.hassConnection.then(({ conn }) => {
const noop = () => {
// do nothing
};
subscribeEntityStates(conn, noop);
const preloadWindow = window as WindowWithPreloads;
subscribeEntityStates(conn, noop, {
throttleMs: () => preloadWindow.entityStateThrottleMs?.() ?? 0,
});
subscribeEntityRegistryDisplay(conn, noop);
subscribeDeviceRegistry(conn, noop);
subscribeAreaRegistry(conn, noop);
@@ -189,7 +192,6 @@ window.hassConnection.then(({ conn }) => {
subscribeUser(conn, noop);
subscribeRepairsIssueRegistry(conn, noop);
const preloadWindow = window as WindowWithPreloads;
preloadWindow.recorderInfoProm = getRecorderInfo(conn);
// "/" opens the default panel, which is not known yet, so only preload the
+86 -1
View File
@@ -3,11 +3,13 @@ import {
callService,
ERR_CONNECTION_LOST,
ERR_INVALID_AUTH,
flushEntityStates,
subscribeConfig,
subscribeEntityStates,
subscribeServices,
} from "home-assistant-js-websocket";
import { fireEvent } from "../common/dom/fire_event";
import { whenDocumentVisible } from "../common/dom/when-document-visible";
import { computeEntityNameDisplayWithoutContext } from "../common/entity/compute_entity_name_display";
import { promiseTimeout } from "../common/util/promise-timeout";
import type { AreaRegistryEntry } from "../data/area/area_registry";
@@ -40,6 +42,7 @@ import {
} from "../common/util/preserve-unchanged-record";
import type { FloorRegistryEntry } from "../data/floor_registry";
import { subscribeFloorRegistry } from "../data/ws-floor_registry";
import type { WindowWithPreloads } from "../data/preloads";
import { subscribePanels } from "../data/ws-panels";
import { translationMetadata } from "../resources/translations-metadata";
import type {
@@ -58,6 +61,7 @@ import { fetchWithAuth } from "../util/fetch-with-auth";
import { getState } from "../util/ha-pref-storage";
import hassCallApi, { hassCallApiRaw } from "../util/hass-call-api";
import { callWS, setDebugConnection } from "../util/websocket";
import { EntityStateThrottler } from "./entity-state-throttler";
import type { HassBaseEl } from "./hass-base-mixin";
export const connectionMixin = <T extends Constructor<HassBaseEl>>(
@@ -66,6 +70,25 @@ export const connectionMixin = <T extends Constructor<HassBaseEl>>(
class extends superClass {
private __backendPingInterval?: ReturnType<typeof setInterval>;
private __stateThrottler?: EntityStateThrottler;
private __cleanupStateThrottle?: () => void;
public connectedCallback() {
super.connectedCallback();
if (this.hass?.connection && !this.__stateThrottler) {
this._setupStateThrottle(this.hass.connection);
if (!document.hidden) {
flushEntityStates(this.hass.connection);
}
}
}
public disconnectedCallback() {
super.disconnectedCallback();
this.__cleanupStateThrottle?.();
}
protected initializeHass(auth: Auth, conn: Connection) {
const language = getLocalLanguage();
@@ -129,6 +152,7 @@ export const connectionMixin = <T extends Constructor<HassBaseEl>>(
);
}
try {
this.__stateThrottler?.markUserAction();
const response = (await callService(
conn,
domain,
@@ -273,7 +297,21 @@ export const connectionMixin = <T extends Constructor<HassBaseEl>>(
}
});
subscribeEntityStates(conn, (states) => this._updateHass({ states }));
const getThrottleMs = this._setupStateThrottle(conn);
subscribeEntityStates(
conn,
(states) => {
if (this.__stateThrottler) {
this.__stateThrottler.measureUpdate(() =>
this._updateHass({ states })
);
} else {
this._updateHass({ states });
}
},
"_ent" in conn ? undefined : { throttleMs: getThrottleMs }
);
// A refetch returns new objects for every entry. Putting the unchanged
// previous ones back into the store's list keeps one copy, shared with
// `hass`.
@@ -412,6 +450,53 @@ export const connectionMixin = <T extends Constructor<HassBaseEl>>(
this._startBackendPing();
}
private _setupStateThrottle(conn: Connection): () => number {
this.__cleanupStateThrottle?.();
const throttler = new EntityStateThrottler(
() => this.hass?.suspendWhenHidden !== false
);
this.__stateThrottler = throttler;
const getThrottleMs = () => this.__stateThrottler?.getThrottleMs() ?? 0;
const preloadWindow = window as WindowWithPreloads;
preloadWindow.entityStateThrottleMs = getThrottleMs;
let cancelVisibleCheck: (() => void) | undefined;
const onVisibilityChange = () => {
if (document.hidden) {
throttler.onHidden();
cancelVisibleCheck ??= whenDocumentVisible(() => {
cancelVisibleCheck = undefined;
throttler.onVisible();
flushEntityStates(conn);
});
} else {
cancelVisibleCheck?.();
cancelVisibleCheck = undefined;
throttler.onVisible();
flushEntityStates(conn);
}
};
document.addEventListener("visibilitychange", onVisibilityChange);
if (document.hidden) {
onVisibilityChange();
}
this.__cleanupStateThrottle = () => {
document.removeEventListener("visibilitychange", onVisibilityChange);
cancelVisibleCheck?.();
cancelVisibleCheck = undefined;
throttler.destroy();
if (preloadWindow.entityStateThrottleMs === getThrottleMs) {
preloadWindow.entityStateThrottleMs = undefined;
}
if (this.__stateThrottler === throttler) {
this.__stateThrottler = undefined;
}
this.__cleanupStateThrottle = undefined;
};
return getThrottleMs;
}
protected hassReconnected() {
super.hassReconnected();
+193
View File
@@ -0,0 +1,193 @@
const TARGET_DUTY_CYCLE = 0.12;
const MIN_INTERVAL_MS = 16;
const MAX_INTERVAL_MS = 1000;
const EMA_ALPHA = 0.25;
const MAX_SAMPLE_MS = 200;
const USER_ACTION_WINDOW_MS = 2000;
const closeChannel = (channel?: MessageChannel) => {
if (!channel) {
return;
}
channel.port1.onmessage = null;
channel.port2.onmessage = null;
channel.port1.close();
channel.port2.close();
};
export class EntityStateThrottler {
private _emaCostMs = 0;
private _hasSample = false;
private _throttleMs = 0;
private _seenInitial = false;
private _skipNextMeasure = false;
private _fastPathUntil = -Infinity;
private _probeInFlight = false;
private _probeToken = 0;
private _rafId?: number;
private _mcA?: MessageChannel;
private _mcB?: MessageChannel;
private _destroyed = false;
private _shouldPauseWhenHidden: () => boolean;
constructor(shouldPauseWhenHidden: () => boolean = () => true) {
this._shouldPauseWhenHidden = shouldPauseWhenHidden;
}
public getThrottleMs(): number {
if (document.hidden && this._shouldPauseWhenHidden()) {
return Infinity;
}
if (performance.now() < this._fastPathUntil) {
return 0;
}
return this._throttleMs;
}
public markUserAction(): void {
this._fastPathUntil = performance.now() + USER_ACTION_WINDOW_MS;
}
public onHidden(): void {
this._cancelProbe();
}
public onVisible(): void {
this._skipNextMeasure = true;
}
public recordSample(sampleMs: number): void {
const clamped = Math.min(MAX_SAMPLE_MS, Math.max(0, sampleMs));
this._emaCostMs = this._hasSample
? EMA_ALPHA * clamped + (1 - EMA_ALPHA) * this._emaCostMs
: clamped;
this._hasSample = true;
const raw = this._emaCostMs / TARGET_DUTY_CYCLE;
this._throttleMs =
raw < MIN_INTERVAL_MS ? 0 : Math.min(MAX_INTERVAL_MS, Math.round(raw));
}
public measureUpdate(run: () => void): void {
if (!this._seenInitial) {
this._seenInitial = true;
run();
return;
}
if (this._skipNextMeasure) {
this._skipNextMeasure = false;
run();
return;
}
if (this._destroyed || this._probeInFlight || document.hidden) {
run();
return;
}
const t0 = performance.now();
run();
if (!this._destroyed && !document.hidden) {
this._startProbe(t0);
}
}
public destroy(): void {
if (this._destroyed) {
return;
}
this._destroyed = true;
this._cancelProbe();
closeChannel(this._mcA);
closeChannel(this._mcB);
this._mcA = undefined;
this._mcB = undefined;
}
private _cancelProbe(): void {
this._probeToken++;
this._probeInFlight = false;
if (this._rafId !== undefined) {
cancelAnimationFrame(this._rafId);
this._rafId = undefined;
}
}
private _startProbe(t0: number): void {
if (typeof MessageChannel !== "function") {
this.recordSample(performance.now() - t0);
return;
}
this._probeInFlight = true;
const token = ++this._probeToken;
this._mcA ??= new MessageChannel();
this._mcA.port1.onmessage = (ev: MessageEvent) => {
if (ev.data !== token) {
return;
}
if (this._destroyed || token !== this._probeToken || document.hidden) {
if (token === this._probeToken) {
this._probeInFlight = false;
}
return;
}
const jsMs = Math.max(0, performance.now() - t0);
if (typeof requestAnimationFrame !== "function") {
this._probeInFlight = false;
this.recordSample(jsMs);
return;
}
let rafFired = false;
const id = requestAnimationFrame(() => {
rafFired = true;
this._rafId = undefined;
if (this._destroyed || token !== this._probeToken || document.hidden) {
if (token === this._probeToken) {
this._probeInFlight = false;
}
return;
}
const tRaf = performance.now();
this._mcB ??= new MessageChannel();
this._mcB.port1.onmessage = (ev2: MessageEvent) => {
if (ev2.data !== token) {
return;
}
if (
this._destroyed ||
token !== this._probeToken ||
document.hidden
) {
if (token === this._probeToken) {
this._probeInFlight = false;
}
return;
}
this._probeInFlight = false;
this.recordSample(jsMs + Math.max(0, performance.now() - tRaf));
};
this._mcB.port2.postMessage(token);
});
if (!rafFired) {
this._rafId = id;
}
};
this._mcA.port2.postMessage(token);
}
}
+145
View File
@@ -0,0 +1,145 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { EntityStateThrottler } from "../../src/state/entity-state-throttler";
const setHidden = (hidden: boolean) => {
Object.defineProperty(document, "hidden", {
configurable: true,
value: hidden,
});
};
describe("EntityStateThrottler", () => {
afterEach(() => {
setHidden(false);
vi.restoreAllMocks();
vi.unstubAllGlobals();
});
it("keeps fast devices unthrottled and scales slow devices within [16, 1000] ms", () => {
const throttler = new EntityStateThrottler();
expect(throttler.getThrottleMs()).toBe(0);
// 1.5 ms / 0.12 = 12.5 ms (< 16 ms deadband) -> stays 0
throttler.recordSample(1.5);
expect(throttler.getThrottleMs()).toBe(0);
// First slow sample updates EMA: 0.25 * 30 + 0.75 * 1.5 = 8.625 -> 72 ms
throttler.recordSample(30);
expect(throttler.getThrottleMs()).toBe(72);
// Large spike is winsorized at 200 ms and capped at 1000 ms
const slow = new EntityStateThrottler();
slow.recordSample(500);
expect(slow.getThrottleMs()).toBe(1000);
});
it("returns Infinity while hidden and skips measuring resume flushes", () => {
let now = 1000;
vi.spyOn(performance, "now").mockImplementation(() => now);
vi.stubGlobal("MessageChannel", undefined);
const throttler = new EntityStateThrottler();
// Initial snapshot render is not measured
throttler.measureUpdate(() => {
now += 150;
});
expect(throttler.getThrottleMs()).toBe(0);
// Hide then resume
setHidden(true);
expect(throttler.getThrottleMs()).toBe(Infinity);
throttler.onHidden();
// Respect opt-out when background suspension is disabled
const noSuspend = new EntityStateThrottler(() => false);
noSuspend.recordSample(24);
expect(noSuspend.getThrottleMs()).toBe(200);
setHidden(false);
throttler.onVisible();
// Resume flush should not pollute EMA
throttler.measureUpdate(() => {
now += 120;
});
expect(throttler.getThrottleMs()).toBe(0);
// Next normal update is measured
throttler.measureUpdate(() => {
now += 24;
});
expect(throttler.getThrottleMs()).toBe(200);
});
it("bypasses throttle during the user-action window", () => {
let now = 1000;
vi.spyOn(performance, "now").mockImplementation(() => now);
const throttler = new EntityStateThrottler();
throttler.recordSample(36);
expect(throttler.getThrottleMs()).toBe(300);
throttler.markUserAction();
expect(throttler.getThrottleMs()).toBe(0);
now += 1999;
expect(throttler.getThrottleMs()).toBe(0);
now += 1;
expect(throttler.getThrottleMs()).toBe(300);
});
it("measures JS + paint cost via split MessageChannel + rAF probe", () => {
let now = 100;
vi.spyOn(performance, "now").mockImplementation(() => now);
const portCallbacks: (() => void)[] = [];
class FakeMessageChannel {
port1: {
onmessage: ((ev: { data: unknown }) => void) | null;
close: ReturnType<typeof vi.fn>;
} = {
onmessage: null,
close: vi.fn(),
};
port2 = {
postMessage: (data: unknown) => {
portCallbacks.push(() => this.port1.onmessage?.({ data }));
},
close: vi.fn(),
};
}
let rafCb: FrameRequestCallback | undefined;
vi.stubGlobal("MessageChannel", FakeMessageChannel);
vi.stubGlobal(
"requestAnimationFrame",
vi.fn((cb: FrameRequestCallback) => {
rafCb = cb;
return 1;
})
);
vi.stubGlobal("cancelAnimationFrame", vi.fn());
const throttler = new EntityStateThrottler();
throttler.measureUpdate(() => undefined); // skip initial
throttler.measureUpdate(() => {
now += 10; // sync + Lit microtask work = 10 ms
});
// mcA fires after microtasks
now += 2; // +2 ms microtasks -> jsMs = 12
portCallbacks.shift()!();
// Waiting for vsync (8 ms idle wait — should NOT be counted!)
now += 8;
rafCb!(now);
// Paint takes 6 ms before mcB fires -> total = 12 + 6 = 18 ms -> 18 / 0.12 = 150 ms
now += 6;
portCallbacks.shift()!();
expect(throttler.getThrottleMs()).toBe(150);
throttler.destroy();
});
});