Fix Kafka retry seek, bound buffers, and cut hot-path CPU/memory waste (Phases 41–44).
Stop consumers from committing past failed offsets, harden Rabbit/DataLake/gateway backpressure, dispose JsonDocument/MinIO correctly, and batch expensive DB/HTTP paths. Track progress in docs/performance.
This commit is contained in:
@@ -41,27 +41,45 @@ public class TrendDetector
|
||||
|
||||
var cache = _redis.GetDatabase();
|
||||
var key = TrendCalculator.HistoryKey(encounterId, observationCode);
|
||||
var lockKey = key + ":lock";
|
||||
|
||||
// Append new entry to history list
|
||||
List<TrendHistoryEntry> history;
|
||||
var entry = new TrendHistoryEntry(value, recordedAt);
|
||||
var historyJson = await cache.StringGetAsync(key);
|
||||
var history = historyJson.HasValue
|
||||
? JsonSerializer.Deserialize<List<TrendHistoryEntry>>(historyJson!) ?? new()
|
||||
: new List<TrendHistoryEntry>();
|
||||
|
||||
history.Add(entry);
|
||||
|
||||
// Trim to max entries and evict entries outside window
|
||||
var cutoff = recordedAt.AddMinutes(-_options.WindowMinutes);
|
||||
history = history
|
||||
.Where(e => e.RecordedAt >= cutoff)
|
||||
.TakeLast(_options.MaxHistoryEntries)
|
||||
.ToList();
|
||||
|
||||
await cache.StringSetAsync(
|
||||
key,
|
||||
JsonSerializer.Serialize(history),
|
||||
TimeSpan.FromSeconds(_options.HistoryTtlSeconds));
|
||||
// Short Redis lock so concurrent observations for the same key do not lose history.
|
||||
var locked = false;
|
||||
for (var attempt = 0; attempt < 8 && !locked; attempt++)
|
||||
{
|
||||
locked = await cache.StringSetAsync(
|
||||
lockKey, "1", TimeSpan.FromSeconds(2), When.NotExists);
|
||||
if (!locked)
|
||||
await Task.Delay(15, ct);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var historyJson = await cache.StringGetAsync(key);
|
||||
history = historyJson.HasValue
|
||||
? JsonSerializer.Deserialize<List<TrendHistoryEntry>>(historyJson!) ?? new()
|
||||
: new List<TrendHistoryEntry>();
|
||||
|
||||
history.Add(entry);
|
||||
history = history
|
||||
.Where(e => e.RecordedAt >= cutoff)
|
||||
.TakeLast(_options.MaxHistoryEntries)
|
||||
.ToList();
|
||||
|
||||
await cache.StringSetAsync(
|
||||
key,
|
||||
JsonSerializer.Serialize(history),
|
||||
TimeSpan.FromSeconds(_options.HistoryTtlSeconds));
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (locked)
|
||||
await cache.KeyDeleteAsync(lockKey);
|
||||
}
|
||||
|
||||
if (history.Count < 2)
|
||||
return new TrendResult(TrendOutcome.InsufficientHistory, observationCode);
|
||||
|
||||
Reference in New Issue
Block a user