diff --git a/lib/states.ts b/lib/states.ts index 79ecc4bf..a8178230 100644 --- a/lib/states.ts +++ b/lib/states.ts @@ -210,6 +210,9 @@ const subscribeUpdates = async ( try { const unsub = await conn.subscribeMessage( (ev) => { + // The collection was torn down, but the subscription is still being + // removed: don't bring the states back. + if (!replace && store.state === undefined) return; const state = applyUpdates( replace ? undefined : store.state, ev, diff --git a/test/states.spec.ts b/test/states.spec.ts index 531d80eb..17a3e5fa 100644 --- a/test/states.spec.ts +++ b/test/states.spec.ts @@ -324,6 +324,56 @@ describe("subscribeEntityStates", () => { assert.strictEqual(entityStatesColl(conn).state, undefined); }); + for (const batchUpdates of [false, true]) { + it(`should ignore messages that arrive after teardown (batchUpdates: ${batchUpdates})`, async () => { + const unsubscribe = subscribeEntityStates(conn, () => undefined, { + batchUpdates, + }); + conn.mockEvent("subscribe_entities", { + a: { + [MOCK_LIGHT.entity_id]: modernEntity(MOCK_LIGHT.entity_id, "on", 1), + }, + }); + await Promise.resolve(); + unsubscribe(); + conn.fireEvent("disconnected"); + assert.strictEqual(entityStatesColl(conn).state, undefined); + + // The mock keeps calling the callback after it unsubscribed, like a + // subscription that waits for Home Assistant to confirm the unsubscribe. + conn.mockEvent("subscribe_entities", { + c: { [MOCK_LIGHT.entity_id]: { "+": { s: "off", lc: 2 } } }, + }); + conn.mockEvent("subscribe_entities", { r: [MOCK_LIGHT.entity_id] }); + conn.mockEvent("subscribe_entities", { + a: { + [MOCK_SWITCH.entity_id]: modernEntity(MOCK_SWITCH.entity_id, "on", 2), + }, + }); + await Promise.resolve(); + + assert.strictEqual(entityStatesColl(conn).state, undefined); + + // A new subscription still gets its snapshot. + const updates: unknown[] = []; + subscribeEntityStates(conn, (entities) => updates.push(entities), { + batchUpdates, + }); + conn.mockEvent("subscribe_entities", { + a: { + [MOCK_SWITCH.entity_id]: modernEntity(MOCK_SWITCH.entity_id, "on", 3), + }, + }); + await Promise.resolve(); + + assert.deepStrictEqual(updates, [ + { + [MOCK_SWITCH.entity_id]: modernState(MOCK_SWITCH.entity_id, "on", 3), + }, + ]); + }); + } + it("should not apply a later snapshot on top of a message that failed", () => { const updates: unknown[] = []; subscribeEntityStates(conn, (entities) => updates.push(entities));