2e52a02b85
ApiKeyVerifier no longer awaits IApiKeyStore.MarkUsedAsync per verification. A new ApiKeyUsageRecorder keeps key id -> latest use time in memory and a background PeriodicTimer writes each key at most once per ApiKeyOptions.LastUsedWriteIntervalSeconds (default 60; 0 = old inline write), plus a final flush on dispose. ApiKeyVerifier is now IAsyncDisposable/IDisposable and owned by the DI container. Failed stamps are counted (FailedWrites + meter counter zb.auth.apikey.last_used.write_failures) and logged, never surfaced. last_used_utc is now accurate to the interval. Version 0.6.0, unpublished. Closes #61.
195 lines
7.4 KiB
C#
195 lines
7.4 KiB
C#
using System.Collections.Concurrent;
|
|
using System.Diagnostics.Metrics;
|
|
using Microsoft.Extensions.Logging;
|
|
using Microsoft.Extensions.Logging.Abstractions;
|
|
using ZB.MOM.WW.Auth.Abstractions.ApiKeys;
|
|
|
|
namespace ZB.MOM.WW.Auth.ApiKeys;
|
|
|
|
/// <summary>
|
|
/// Coalesces API-key "last used" stamps and writes them off the request path (scadaproj#61).
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// <para>
|
|
/// <see cref="Record"/> only updates an in-memory map (key id → latest use time) and never touches
|
|
/// the store, so a verification is never slowed by the store's write lock, a slow fsync or a busy
|
|
/// timeout. A background loop, started on the first <see cref="Record"/>, calls
|
|
/// <see cref="IApiKeyStore.MarkUsedAsync"/> once per pending key every interval with the latest use
|
|
/// time seen for it; <see cref="DisposeAsync"/> stops the loop and writes whatever is still pending.
|
|
/// </para>
|
|
/// <para>
|
|
/// A failed write is never surfaced to a caller: it is counted (<see cref="FailedWrites"/> and the
|
|
/// <c>zb.auth.apikey.last_used.write_failures</c> counter on the <c>ZB.MOM.WW.Auth.ApiKeys</c> meter)
|
|
/// and logged at Warning, and the stamp is dropped (the next use of the key queues a fresh one).
|
|
/// </para>
|
|
/// </remarks>
|
|
public sealed class ApiKeyUsageRecorder : IAsyncDisposable, IDisposable
|
|
{
|
|
/// <summary>Name of the <see cref="Meter"/> this type reports on.</summary>
|
|
public const string MeterName = "ZB.MOM.WW.Auth.ApiKeys";
|
|
|
|
private static readonly Meter Meter = new(MeterName);
|
|
|
|
private static readonly Counter<long> WriteFailuresCounter =
|
|
Meter.CreateCounter<long>("zb.auth.apikey.last_used.write_failures", description:
|
|
"API-key last-used writes that failed (the verification itself succeeded).");
|
|
|
|
private readonly IApiKeyStore _store;
|
|
private readonly TimeSpan _interval;
|
|
private readonly TimeProvider _timeProvider;
|
|
private readonly ILogger _logger;
|
|
private readonly ConcurrentDictionary<string, DateTimeOffset> _pending = new(StringComparer.Ordinal);
|
|
private readonly SemaphoreSlim _flushGate = new(1, 1);
|
|
private readonly CancellationTokenSource _stopping = new();
|
|
private readonly object _startLock = new();
|
|
private Task? _loop;
|
|
private long _failedWrites;
|
|
private long _completedWrites;
|
|
private int _disposed;
|
|
|
|
/// <summary>Creates a recorder that flushes to <paramref name="store"/> every <paramref name="interval"/>.</summary>
|
|
/// <param name="store">The store whose <see cref="IApiKeyStore.MarkUsedAsync"/> receives the stamps.</param>
|
|
/// <param name="interval">Flush period; must be positive.</param>
|
|
/// <param name="timeProvider">Clock for the flush timer; defaults to <see cref="TimeProvider.System"/>.</param>
|
|
/// <param name="logger">Receives a Warning per failed write; optional.</param>
|
|
public ApiKeyUsageRecorder(
|
|
IApiKeyStore store,
|
|
TimeSpan interval,
|
|
TimeProvider? timeProvider = null,
|
|
ILogger<ApiKeyUsageRecorder>? logger = null)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(store);
|
|
ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(interval, TimeSpan.Zero);
|
|
_store = store;
|
|
_interval = interval;
|
|
_timeProvider = timeProvider ?? TimeProvider.System;
|
|
_logger = (ILogger?)logger ?? NullLogger.Instance;
|
|
}
|
|
|
|
/// <summary>Number of last-used writes that failed since this recorder was created.</summary>
|
|
public long FailedWrites => Interlocked.Read(ref _failedWrites);
|
|
|
|
/// <summary>Number of last-used writes that completed since this recorder was created.</summary>
|
|
public long CompletedWrites => Interlocked.Read(ref _completedWrites);
|
|
|
|
/// <summary>Number of keys with a stamp waiting for the next flush.</summary>
|
|
public int PendingCount => _pending.Count;
|
|
|
|
/// <summary>
|
|
/// Notes that <paramref name="keyId"/> was used at <paramref name="whenUtc"/>. Never blocks on and
|
|
/// never throws from the store. Ignored once the recorder is disposed.
|
|
/// </summary>
|
|
public void Record(string keyId, DateTimeOffset whenUtc)
|
|
{
|
|
ArgumentException.ThrowIfNullOrWhiteSpace(keyId);
|
|
if (Volatile.Read(ref _disposed) != 0)
|
|
{
|
|
return;
|
|
}
|
|
|
|
_pending.AddOrUpdate(keyId, whenUtc, (_, existing) => whenUtc > existing ? whenUtc : existing);
|
|
EnsureStarted();
|
|
}
|
|
|
|
/// <summary>
|
|
/// Writes every pending stamp now. The background loop calls this each interval; hosts and tests
|
|
/// may call it directly. Write failures are counted and logged, never thrown.
|
|
/// </summary>
|
|
public async Task FlushAsync(CancellationToken ct = default)
|
|
{
|
|
await _flushGate.WaitAsync(ct).ConfigureAwait(false);
|
|
try
|
|
{
|
|
foreach (string keyId in _pending.Keys)
|
|
{
|
|
if (!_pending.TryRemove(keyId, out DateTimeOffset whenUtc))
|
|
{
|
|
continue;
|
|
}
|
|
|
|
try
|
|
{
|
|
await _store.MarkUsedAsync(keyId, whenUtc, ct).ConfigureAwait(false);
|
|
Interlocked.Increment(ref _completedWrites);
|
|
}
|
|
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
|
{
|
|
// Put the stamp back (unless a newer one arrived) so a final flush can still write it.
|
|
_pending.AddOrUpdate(keyId, whenUtc, (_, existing) => existing > whenUtc ? existing : whenUtc);
|
|
throw;
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Interlocked.Increment(ref _failedWrites);
|
|
WriteFailuresCounter.Add(1);
|
|
_logger.LogWarning(ex,
|
|
"API key {KeyId}: last-used write failed; verification was not affected", keyId);
|
|
}
|
|
}
|
|
}
|
|
finally
|
|
{
|
|
_flushGate.Release();
|
|
}
|
|
}
|
|
|
|
private void EnsureStarted()
|
|
{
|
|
if (Volatile.Read(ref _loop) is not null)
|
|
{
|
|
return;
|
|
}
|
|
|
|
lock (_startLock)
|
|
{
|
|
if (_loop is null && Volatile.Read(ref _disposed) == 0)
|
|
{
|
|
Volatile.Write(ref _loop, Task.Run(RunAsync));
|
|
}
|
|
}
|
|
}
|
|
|
|
private async Task RunAsync()
|
|
{
|
|
using PeriodicTimer timer = new(_interval, _timeProvider);
|
|
try
|
|
{
|
|
while (await timer.WaitForNextTickAsync(_stopping.Token).ConfigureAwait(false))
|
|
{
|
|
await FlushAsync(_stopping.Token).ConfigureAwait(false);
|
|
}
|
|
}
|
|
catch (OperationCanceledException) when (_stopping.IsCancellationRequested)
|
|
{
|
|
// Disposal; the final flush happens in DisposeAsync.
|
|
}
|
|
}
|
|
|
|
/// <summary>Stops the background loop and writes every pending stamp.</summary>
|
|
public async ValueTask DisposeAsync()
|
|
{
|
|
if (Interlocked.Exchange(ref _disposed, 1) != 0)
|
|
{
|
|
return;
|
|
}
|
|
|
|
Task? loop;
|
|
lock (_startLock)
|
|
{
|
|
loop = _loop;
|
|
}
|
|
|
|
await _stopping.CancelAsync().ConfigureAwait(false);
|
|
if (loop is not null)
|
|
{
|
|
await loop.ConfigureAwait(false);
|
|
}
|
|
|
|
await FlushAsync(CancellationToken.None).ConfigureAwait(false);
|
|
_stopping.Dispose();
|
|
}
|
|
|
|
/// <summary>Synchronous counterpart of <see cref="DisposeAsync"/>; blocks until the final flush completes.</summary>
|
|
public void Dispose() => DisposeAsync().AsTask().GetAwaiter().GetResult();
|
|
}
|