Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions lib/states.ts
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,9 @@ const subscribeUpdates = async (
try {
const unsub = await conn.subscribeMessage<StatesUpdates>(
(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,
Expand Down
50 changes: 50 additions & 0 deletions test/states.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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));
Expand Down