using System.Globalization; using System.Text.Json; using HomeAssistant.HistoryReplay.HomeAssistantClient; using Microsoft.Extensions.Logging; namespace HomeAssistant.HistoryReplay.HistoryData; public sealed class HomeAssistantHistoryProvider( IHomeAssistantApiClient client, ILogger logger) : IHistoryDataProvider { private const int MaxEntitiesPerBatch = 5; private const int MaxConcurrentRequests = 20; private const int MaxRetryAttempts = 3; private static readonly TimeSpan InitialRetryDelay = TimeSpan.FromSeconds(2); public Task FetchHistoryAsync( IReadOnlyList entityIds, DateTimeOffset startTime, DateTimeOffset endTime, CancellationToken cancellationToken = default) { return FetchHistoryAsync( minimalEntityIds: entityIds, fullEntityIds: [], startTime, endTime, cancellationToken); } public async Task FetchHistoryAsync( IReadOnlyList minimalEntityIds, IReadOnlyList fullEntityIds, DateTimeOffset startTime, DateTimeOffset endTime, CancellationToken cancellationToken = default) { var timeline = new HistoryTimeline(); var allEntityCount = minimalEntityIds.Count + fullEntityIds.Count; var minimalBatches = ChunkEntities(minimalEntityIds, MaxEntitiesPerBatch); var fullBatches = ChunkEntities(fullEntityIds, MaxEntitiesPerBatch); logger.LogInformation( "Fetching history in {MinBatchCount}+{FullBatchCount} batch(es) for {MinCount} minimal + {FullCount} full entities", minimalBatches.Count, fullBatches.Count, minimalEntityIds.Count, fullEntityIds.Count); var failedEntities = new List(); using var semaphore = new SemaphoreSlim(MaxConcurrentRequests); var minimalTasks = minimalBatches.Select(batch => FetchBatchThrottledAsync( batch, startTime, endTime, minimalResponse: true, semaphore, cancellationToken)); var fullTasks = fullBatches.Select(batch => FetchBatchThrottledAsync( batch, startTime, endTime, minimalResponse: false, semaphore, cancellationToken)); var results = await Task.WhenAll(minimalTasks.Concat(fullTasks)).ConfigureAwait(false); foreach (var batchResult in results) { foreach (var (entityId, entries) in batchResult.Entries) { timeline.AddEntriesBulk(entityId, entries); } failedEntities.AddRange(batchResult.FailedEntityIds); } if (failedEntities.Count > 0) { logger.LogWarning("Retrying {Count} failed entities individually: {Entities}", failedEntities.Count, string.Join(", ", failedEntities)); var individualResults = await FetchEntitiesIndividuallyAsync(failedEntities, startTime, endTime, cancellationToken); foreach (var (entityId, entries) in individualResults) { timeline.AddEntriesBulk(entityId, entries); } } timeline.FinalizeSort(); logger.LogInformation( "Fetched history for {EntityCount} entities: {EntryCount} total entries ({Start} to {End})", allEntityCount, timeline.TotalEntryCount, startTime, endTime); return timeline; } private async Task FetchBatchThrottledAsync( IReadOnlyList batch, DateTimeOffset startTime, DateTimeOffset endTime, bool minimalResponse, SemaphoreSlim semaphore, CancellationToken cancellationToken) { await semaphore.WaitAsync(cancellationToken); try { return await FetchBatchWithRetryAsync(batch, startTime, endTime, minimalResponse, cancellationToken); } finally { semaphore.Release(); } } private async Task FetchBatchWithRetryAsync( IReadOnlyList entityIds, DateTimeOffset startTime, DateTimeOffset endTime, bool minimalResponse, CancellationToken cancellationToken) { var entityIdsString = string.Join(",", entityIds); for (var attempt = 1; attempt <= MaxRetryAttempts; attempt++) { logger.LogDebug("Fetching history batch (attempt {Attempt}/{MaxAttempts}, minimal={Minimal}) for: {Entities}", attempt, MaxRetryAttempts, minimalResponse, entityIdsString); try { var response = await client.GetHistoryAsync( entityIdsString, startTime, endTime, minimalResponse, cancellationToken) .ConfigureAwait(false); var entries = new List<(string, List)>(); ParseHistoryResponse(response, entries); return new BatchFetchResult(entries, []); } catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { throw; } catch (Exception ex) when (IsTransientFailure(ex) && attempt < MaxRetryAttempts) { var delay = InitialRetryDelay * Math.Pow(2, attempt - 1); logger.LogWarning(ex, "Transient failure fetching batch (attempt {Attempt}/{MaxAttempts}), retrying in {Delay}s: {Entities}", attempt, MaxRetryAttempts, delay.TotalSeconds, entityIdsString); await Task.Delay(delay, cancellationToken).ConfigureAwait(false); } catch (Exception ex) { logger.LogError(ex, "Failed to fetch history batch after {Attempt} attempt(s): {Entities}", attempt, entityIdsString); return new BatchFetchResult([], entityIds.ToList()); } } return new BatchFetchResult([], entityIds.ToList()); } private async Task Entries)>> FetchEntitiesIndividuallyAsync( IReadOnlyList entityIds, DateTimeOffset startTime, DateTimeOffset endTime, CancellationToken cancellationToken) { var allEntries = new List<(string, List)>(); using var semaphore = new SemaphoreSlim(MaxConcurrentRequests); var tasks = entityIds.Select(async entityId => { await semaphore.WaitAsync(cancellationToken); try { return await FetchSingleEntityWithRetryAsync(entityId, startTime, endTime, cancellationToken); } finally { semaphore.Release(); } }); var results = await Task.WhenAll(tasks).ConfigureAwait(false); foreach (var result in results) { allEntries.AddRange(result); } return allEntries; } private async Task Entries)>> FetchSingleEntityWithRetryAsync( string entityId, DateTimeOffset startTime, DateTimeOffset endTime, CancellationToken cancellationToken) { for (var attempt = 1; attempt <= MaxRetryAttempts; attempt++) { try { var response = await client.GetHistoryAsync( entityId, startTime, endTime, minimalResponse: false, cancellationToken) .ConfigureAwait(false); var entries = new List<(string, List)>(); ParseHistoryResponse(response, entries); return entries; } catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { throw; } catch (Exception ex) when (IsTransientFailure(ex) && attempt < MaxRetryAttempts) { var delay = InitialRetryDelay * Math.Pow(2, attempt - 1); logger.LogWarning(ex, "Transient failure fetching {EntityId} (attempt {Attempt}/{MaxAttempts}), retrying in {Delay}s", entityId, attempt, MaxRetryAttempts, delay.TotalSeconds); await Task.Delay(delay, cancellationToken).ConfigureAwait(false); } catch (Exception ex) { logger.LogError(ex, "Failed to fetch history for entity {EntityId} after {Attempt} attempt(s)", entityId, attempt); return []; } } return []; } private static bool IsTransientFailure(Exception ex) => ex is HttpRequestException or TaskCanceledException or TimeoutException or IOException; private static void ParseHistoryResponse( JsonElement response, List<(string EntityId, List Entries)> result) { if (response.ValueKind != JsonValueKind.Array) { return; } foreach (var entityArray in response.EnumerateArray()) { if (entityArray.ValueKind != JsonValueKind.Array) { continue; } string? currentEntityId = null; var entries = new List(); foreach (var stateObj in entityArray.EnumerateArray()) { var entry = ParseStateEntry(stateObj, currentEntityId); if (entry is null) { continue; } currentEntityId ??= entry.EntityId; entries.Add(entry); } if (currentEntityId is not null && entries.Count > 0) { result.Add((currentEntityId, entries)); } } } private static HistoryStateEntry? ParseStateEntry(JsonElement stateObj, string? fallbackEntityId) { string? entityId = null; if (stateObj.TryGetProperty("entity_id", out var entityIdProp)) { entityId = entityIdProp.GetString(); } entityId ??= fallbackEntityId; if (string.IsNullOrEmpty(entityId)) { return null; } var state = stateObj.TryGetProperty("state", out var stateProp) ? stateProp.GetString() : null; if (!stateObj.TryGetProperty("last_changed", out var lastChangedProp)) { return null; } if (!DateTimeOffset.TryParse(lastChangedProp.GetString(), CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out var lastChanged)) { return null; } Dictionary? attributes = null; if (stateObj.TryGetProperty("attributes", out var attrProp) && attrProp.ValueKind == JsonValueKind.Object) { attributes = ParseAttributes(attrProp); } return new HistoryStateEntry { EntityId = entityId, State = state, LastChanged = lastChanged, Attributes = attributes }; } private static Dictionary ParseAttributes(JsonElement attrElement) { var attributes = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (var prop in attrElement.EnumerateObject()) { attributes[prop.Name] = prop.Value.ValueKind switch { JsonValueKind.String => prop.Value.GetString() ?? string.Empty, JsonValueKind.Number => prop.Value.GetDouble(), JsonValueKind.True => true, JsonValueKind.False => false, _ => prop.Value.GetRawText() }; } return attributes; } private static IReadOnlyList> ChunkEntities(IReadOnlyList entities, int chunkSize) { var chunks = new List>(); for (var i = 0; i < entities.Count; i += chunkSize) { chunks.Add(entities.Skip(i).Take(chunkSize).ToList()); } return chunks; } private sealed record BatchFetchResult( List<(string EntityId, List Entries)> Entries, List FailedEntityIds); }