This commit is contained in:
2026-06-28 13:58:35 +03:00
parent 8f45028715
commit e6bf8258bb
114 changed files with 4365 additions and 874 deletions
@@ -9,63 +9,230 @@ public sealed class HomeAssistantHistoryProvider(
IHomeAssistantApiClient client,
ILogger<HomeAssistantHistoryProvider> logger) : IHistoryDataProvider
{
private const int MaxEntitiesPerRequest = 10;
private const int MaxEntitiesPerBatch = 5;
private const int MaxConcurrentRequests = 20;
private const int MaxRetryAttempts = 3;
private static readonly TimeSpan InitialRetryDelay = TimeSpan.FromSeconds(2);
public async Task<HistoryTimeline> FetchHistoryAsync(
public Task<HistoryTimeline> FetchHistoryAsync(
IReadOnlyList<string> entityIds,
DateTimeOffset startTime,
DateTimeOffset endTime,
CancellationToken cancellationToken = default)
{
return FetchHistoryAsync(
minimalEntityIds: entityIds,
fullEntityIds: [],
startTime, endTime, cancellationToken);
}
public async Task<HistoryTimeline> FetchHistoryAsync(
IReadOnlyList<string> minimalEntityIds,
IReadOnlyList<string> fullEntityIds,
DateTimeOffset startTime,
DateTimeOffset endTime,
CancellationToken cancellationToken = default)
{
var timeline = new HistoryTimeline();
var batches = ChunkEntities(entityIds, MaxEntitiesPerRequest);
var allEntityCount = minimalEntityIds.Count + fullEntityIds.Count;
var tasks = batches.Select(batch => FetchBatchAsync(batch, startTime, endTime, cancellationToken));
var results = await Task.WhenAll(tasks).ConfigureAwait(false);
var minimalBatches = ChunkEntities(minimalEntityIds, MaxEntitiesPerBatch);
var fullBatches = ChunkEntities(fullEntityIds, MaxEntitiesPerBatch);
foreach (var batchTimeline in results)
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<string>();
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 in batchTimeline.GetEntityIds())
foreach (var (entityId, entries) in batchResult.Entries)
{
timeline.AddEntries(entityId, batchTimeline.GetEntityHistory(entityId));
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})",
entityIds.Count, timeline.TotalEntryCount, startTime, endTime);
allEntityCount, timeline.TotalEntryCount, startTime, endTime);
return timeline;
}
private async Task<HistoryTimeline> FetchBatchAsync(
private async Task<BatchFetchResult> FetchBatchThrottledAsync(
IReadOnlyList<string> 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<BatchFetchResult> FetchBatchWithRetryAsync(
IReadOnlyList<string> 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<HistoryStateEntry>)>();
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<List<(string EntityId, List<HistoryStateEntry> Entries)>> FetchEntitiesIndividuallyAsync(
IReadOnlyList<string> entityIds,
DateTimeOffset startTime,
DateTimeOffset endTime,
CancellationToken cancellationToken)
{
var timeline = new HistoryTimeline();
var entityIdsString = string.Join(",", entityIds);
var allEntries = new List<(string, List<HistoryStateEntry>)>();
using var semaphore = new SemaphoreSlim(MaxConcurrentRequests);
logger.LogDebug("Fetching history batch for: {Entities}", entityIdsString);
try
var tasks = entityIds.Select(async entityId =>
{
var result = await client.GetHistoryAsync(
entityIdsString, startTime, endTime, minimalResponse: false, cancellationToken)
.ConfigureAwait(false);
await semaphore.WaitAsync(cancellationToken);
try
{
return await FetchSingleEntityWithRetryAsync(entityId, startTime, endTime, cancellationToken);
}
finally
{
semaphore.Release();
}
});
ParseHistoryResponse(result, timeline);
}
catch (Exception ex)
var results = await Task.WhenAll(tasks).ConfigureAwait(false);
foreach (var result in results)
{
logger.LogError(ex, "Failed to fetch history for entities: {Entities}", entityIdsString);
allEntries.AddRange(result);
}
return timeline;
return allEntries;
}
private void ParseHistoryResponse(JsonElement response, HistoryTimeline timeline)
private async Task<List<(string EntityId, List<HistoryStateEntry> 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<HistoryStateEntry>)>();
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<HistoryStateEntry> Entries)> result)
{
if (response.ValueKind != JsonValueKind.Array)
{
@@ -79,25 +246,37 @@ public sealed class HomeAssistantHistoryProvider(
continue;
}
string? currentEntityId = null;
var entries = new List<HistoryStateEntry>();
foreach (var stateObj in entityArray.EnumerateArray())
{
var entry = ParseStateEntry(stateObj);
if (entry is not null)
var entry = ParseStateEntry(stateObj, currentEntityId);
if (entry is null)
{
timeline.AddEntries(entry.EntityId, [entry]);
continue;
}
currentEntityId ??= entry.EntityId;
entries.Add(entry);
}
if (currentEntityId is not null && entries.Count > 0)
{
result.Add((currentEntityId, entries));
}
}
}
private HistoryStateEntry? ParseStateEntry(JsonElement stateObj)
private static HistoryStateEntry? ParseStateEntry(JsonElement stateObj, string? fallbackEntityId)
{
if (!stateObj.TryGetProperty("entity_id", out var entityIdProp))
string? entityId = null;
if (stateObj.TryGetProperty("entity_id", out var entityIdProp))
{
return null;
entityId = entityIdProp.GetString();
}
var entityId = entityIdProp.GetString();
entityId ??= fallbackEntityId;
if (string.IsNullOrEmpty(entityId))
{
return null;
@@ -105,16 +284,13 @@ public sealed class HomeAssistantHistoryProvider(
var state = stateObj.TryGetProperty("state", out var stateProp) ? stateProp.GetString() : null;
DateTimeOffset lastChanged;
if (stateObj.TryGetProperty("last_changed", out var lastChangedProp))
if (!stateObj.TryGetProperty("last_changed", out var lastChangedProp))
{
if (!DateTimeOffset.TryParse(lastChangedProp.GetString(), CultureInfo.InvariantCulture,
DateTimeStyles.RoundtripKind, out lastChanged))
{
return null;
}
return null;
}
else
if (!DateTimeOffset.TryParse(lastChangedProp.GetString(), CultureInfo.InvariantCulture,
DateTimeStyles.RoundtripKind, out var lastChanged))
{
return null;
}
@@ -159,10 +335,13 @@ public sealed class HomeAssistantHistoryProvider(
for (var i = 0; i < entities.Count; i += chunkSize)
{
var chunk = entities.Skip(i).Take(chunkSize).ToList();
chunks.Add(chunk);
chunks.Add(entities.Skip(i).Take(chunkSize).ToList());
}
return chunks;
}
private sealed record BatchFetchResult(
List<(string EntityId, List<HistoryStateEntry> Entries)> Entries,
List<string> FailedEntityIds);
}