From 3e14d825e3151077629f536d8d8128dd817641e5 Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Sat, 21 Jan 2023 18:16:52 -1000 Subject: [PATCH] Optimize purge of old live history data in the time window (#15153) from https://github.com/home-assistant/frontend/pull/15112#discussion_r1083382923 --- src/data/history.ts | 33 ++++++++++++++++++++------------- 1 file changed, 20 insertions(+), 13 deletions(-) diff --git a/src/data/history.ts b/src/data/history.ts index 1f95af2552..cbe57cc800 100644 --- a/src/data/history.ts +++ b/src/data/history.ts @@ -263,20 +263,27 @@ class HistoryStream { } // Remove old history if (entityId in this.combinedHistory) { - const entityHistory = newHistory[entityId]; - while (entityHistory[0].lu < purgeBeforePythonTime) { - if (entityHistory.length > 1) { - if (entityHistory[1].lu < purgeBeforePythonTime) { - newHistory[entityId].shift(); - continue; - } - } - // Update the first entry to the start time state - // as we need to preserve the start time state and - // only expire the rest of the history as it ages. - entityHistory[0].lu = purgeBeforePythonTime; - break; + const expiredStates = newHistory[entityId].filter( + (state) => state.lu < purgeBeforePythonTime + ); + if (!expiredStates.length) { + continue; } + newHistory[entityId] = newHistory[entityId].filter( + (state) => state.lu >= purgeBeforePythonTime + ); + if ( + newHistory[entityId].length && + newHistory[entityId][0].lu === purgeBeforePythonTime + ) { + continue; + } + // Update the first entry to the start time state + // as we need to preserve the start time state and + // only expire the rest of the history as it ages. + const lastExpiredState = expiredStates[expiredStates.length - 1]; + lastExpiredState.lu = purgeBeforePythonTime; + newHistory[entityId].unshift(lastExpiredState); } } this.combinedHistory = newHistory;