using System.Collections.Concurrent;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.InboundApi;
namespace ZB.MOM.WW.ScadaBridge.InboundAPI;
///
/// WP2.6b (arch-review misc — Inbound API per-request SQL): a short-TTL cache of
/// resolved ApiMethod rows, sitting in front of IInboundApiRepository.GetMethodByNameAsync
/// so a repeated POST /api/{methodName} burst for the same method does not each pay a
/// database round-trip.
///
/// Two invalidation paths, by design:
///
///
/// - Fast path. calls
/// for every name in an ApiMethod
/// ScriptArtifactsChanged notification (bundle-import changes today).
/// - Fallback. Every entry — including a negative (not-found) result —
/// expires after regardless of whether an
/// invalidation notification ever arrives. This is what keeps an operator edit via the
/// Management API/UI (which does not publish to the change bus) correct within a bounded
/// window, and is also the correctness backstop for the bus's at-least-once/in-process-only
/// contract — a missed or duplicate notification is harmless.
///
///
/// A negative (method not found) result is cached too — bounded by the same short TTL — so a
/// caller with a provisioned-but-nonexistent method scope (a real misconfiguration case, not an
/// enumeration probe: EndpointExtensions only reaches this cache after the in-memory
/// scope check already passed) does not repeatedly pay a miss query.
///
///
public sealed class ApiMethodCache
{
private sealed record Entry(ApiMethod? Method, DateTimeOffset ExpiresAtUtc);
private readonly ConcurrentDictionary _entries = new(StringComparer.Ordinal);
private readonly TimeSpan _ttl;
private readonly TimeProvider _timeProvider;
/// Initializes the cache.
/// How long a resolved (or not-found) entry stays valid.
/// Optional time source; defaults to .
public ApiMethodCache(TimeSpan ttl, TimeProvider? timeProvider = null)
{
if (ttl <= TimeSpan.Zero)
throw new ArgumentOutOfRangeException(nameof(ttl), ttl, "ApiMethodCache TTL must be positive.");
_ttl = ttl;
_timeProvider = timeProvider ?? TimeProvider.System;
}
///
/// Returns the cached entry for if it has not expired;
/// otherwise invokes , caches the result (found or not-found), and
/// returns it. Concurrent callers on a cache miss for the SAME name may each invoke
/// once (last write wins) — an acceptable, rare race in exchange
/// for not serializing every miss behind a lock; the point of the cache is to absorb
/// repeated hits, not to fully dedupe a first-request thundering herd.
///
/// The method name to resolve.
/// Loads the current row from the repository on a cache miss.
/// Cancellation token for the fetch.
public async Task GetOrFetchAsync(
string methodName,
Func> fetch,
CancellationToken cancellationToken)
{
var now = _timeProvider.GetUtcNow();
if (_entries.TryGetValue(methodName, out var cached) && cached.ExpiresAtUtc > now)
{
return cached.Method;
}
var method = await fetch(cancellationToken).ConfigureAwait(false);
_entries[methodName] = new Entry(method, now + _ttl);
return method;
}
/// Drops the cached entry for one method name. Safe to call for an unknown name.
/// The method name to invalidate.
public void Invalidate(string methodName) => _entries.TryRemove(methodName, out _);
/// Diagnostic helper — the number of currently-cached entries (including expired-but-not-evicted ones).
internal int Count => _entries.Count;
}