diff --git a/CHANGELOG.md b/CHANGELOG.md index 02ff284a6..375f26469 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) ### Added +- **Conditional refresh.** `ICache` and `ICache` gain sealed `GetOrRevalidateAsync` overloads for conditional refresh. The generator receives a `RevalidationContext` with the previous value and its `ETag` and `LastModified` validators, and returns a `RevalidatedValue` from `Modified` for a fresh value or `NotModified` to confirm the previous value and renew its expiration. Use `RehydrateEnabled` to revalidate live entries in the background and fail closed after expiry, or `FailSafeEnabled` to revalidate an expired value and use it as the fallback. This version supports single `CacheKey` calls only. See [Conditional refresh](docs/how-to/choosing-a-get-or-add-overload.md#conditional-refresh-with-getorrevalidateasync). - **Readable key move stages.** Stages are now off, preparing, switching, copying, copied and done. Reverse stages display as returning, copying-back and copied-back, then off after release. `StringFlagStageSource` accepts `off`, `copying`, `copied`, and `done`, case-insensitively, plus numeric strings `0` through `5`, ignoring surrounding whitespace. Intermediate, reverse and former stage names are rejected as flags. Numeric flags `1` and `2` still mean off. Integer flags and stored values remain compatible. - The inventory counters `cache.keymove.written_after_s3` and `cache.keymove.inventory_written_after_s3` are now `cache.keymove.written_after_copying` and `cache.keymove.inventory_written_after_copying`. - **The in-place write format does not switch while a group's keys move.** A group that asks for MessagePack during a key move (Preparing to Copied) keeps writing the envelope and waits to switch until the move is over; the wait counts `format_switch_held` (tags `group`, `pending`) and raises the key move alert of the same name. The switch then goes ahead on the next write, with no restart. diff --git a/docs/how-to/choosing-a-get-or-add-overload.md b/docs/how-to/choosing-a-get-or-add-overload.md index 21f2e8d9d..15376df27 100644 --- a/docs/how-to/choosing-a-get-or-add-overload.md +++ b/docs/how-to/choosing-a-get-or-add-overload.md @@ -214,6 +214,64 @@ its own name because a `GetOrAddAsync` overload taking `Func throw new InvalidOperationException()`, common in tests — ambiguous against the closure overload. +## Conditional refresh with `GetOrRevalidateAsync` + +Use `GetOrRevalidateAsync` when the source can confirm that a value is unchanged. +The generator receives a `RevalidationContext` and returns a `RevalidatedValue`. Return `context.Modified(value, etag, lastModified, +expiration)` for a new value, or `context.NotModified(expiration)` to confirm the previous value and store it with a fresh +expiration. A null expiration leaves the lifetime to the policy. + +The context's `HasPreviousValue` distinguishes a cached null from no previous value. `PreviousValue`, `ETag` and +`LastModified` hold that value and its validators when the cache has them. **Check `ETag` for null before making a +conditional call that uses it.** The first generation has no validators, and a previous value can be available without +them; in either case, fetch the full value and return `Modified`: + +```csharp +var document = await _cache.GetOrRevalidateAsync( + $"document:{id}", + (Self: this, Id: id), + static async (s, context, ct) => + { + if (!context.HasPreviousValue || context.ETag is null) + { + var initial = await s.Self._client.GetAsync(s.Id, ct); + return context.Modified(initial.Value, initial.ETag, initial.LastModified, initial.Expiration); + } + + var response = await s.Self._client.GetAsync(s.Id, context.ETag, ct); + return response.IsNotModified + ? context.NotModified() + : context.Modified(response.Value, response.ETag, response.LastModified, response.Expiration); + }, + ct); +``` + +`NotModified` preserves the previous value and both validators. It throws `InvalidOperationException` when +`HasPreviousValue` is false. Returning a confirmation saved from another context also fails with `InvalidOperationException`. +A source that uses modification times rather than entity tags can apply the same null check +to `LastModified` before a conditional call. + +Conditional refresh works on the InMemory and InMemoryRedis providers, and elsewhere the generator always gets an empty context. + +Choose the policy recipe that matches the behavior wanted when the source is unavailable: + +- **Fail-closed: revalidate a live entry.** Enable `RehydrateEnabled` and configure `Rehydrate`. Once an entry passes the + rehydration threshold, `GetOrRevalidateAsync` runs in the background with the live value and any validators the cache + has while foreground callers keep getting that value. A `NotModified` answer renews the entry. If the source stays down, calls + still succeed until the entry expires; a call after expiry ends in an error rather than serving the expired value. +- **Fail-open: revalidate an expired value.** Enable `FailSafeEnabled`. On the miss after expiry, the value kept by + fail-safe becomes the context's previous value, so the generator can revalidate it. A `NotModified` answer stores it + afresh. If the source fails or runs past `FailSafeTimeout`, the same value is also the fallback, subject to the other + [fail-safe settings and limits](resilience.md#fail-safe). + +The revalidation overloads take a single `CacheKey`. They have no batch or hash form, no `Span` or +`CacheKeyHandler` interpolated-key form, and no `GetOrAddResultAsync` counterpart. + +- The generator receives the validators the cache stored with the entry, even if application code or a custom entry + factory later edits the entry's metadata dictionary. +- With a custom `ICacheEntryFactory`, revalidation may store a copy of the factory's entry. `GetCacheEntryAsync` can + return a separate, equal entry. + ## Keys - **A constant key** is built once: `private static readonly CacheKey Key = "default";`. A constant string passed on diff --git a/docs/how-to/resilience.md b/docs/how-to/resilience.md index 7317387dd..e038e6145 100644 --- a/docs/how-to/resilience.md +++ b/docs/how-to/resilience.md @@ -74,7 +74,8 @@ entire acquire loop to a single attempt. ## Hydrating cache Refresh an entry in the background before it physically expires, so foreground callers never -block on a miss. +block on a miss. To let the source confirm that the existing value is unchanged, use +[conditional refresh with `GetOrRevalidateAsync`](choosing-a-get-or-add-overload.md#conditional-refresh-with-getorrevalidateasync). Enable via `CachePolicy.RehydrateEnabled: true` plus `Rehydrate: { ... }`: diff --git a/docs/reference/glossary.md b/docs/reference/glossary.md index 54b7faa22..a14d236f1 100644 --- a/docs/reference/glossary.md +++ b/docs/reference/glossary.md @@ -76,4 +76,6 @@ Alphabetical lookup for terms used across the docs. **Two surfaces** — `ICache` / `IHashCache` (typed, factory) vs `ICache` / `IHashCache` (dynamic-key, power-user). See [reference/interfaces.md](interfaces.md). +**Validators** — The `ETag` and `LastModified` values that identify the source version of a cached value. A revalidation generator returns them from `RevalidationContext.Modified`; a later `GetOrRevalidateAsync` generator receives them on its `RevalidationContext` when the cache has them. See [conditional refresh](../how-to/choosing-a-get-or-add-overload.md#conditional-refresh-with-getorrevalidateasync). + **Version / epoch** — A hash's version counts its writes, kept in the reserved `_version_` field. The high bits are the epoch, drawn when a write makes the hash; a hash made again after a removal, expiry or eviction has a new epoch. diff --git a/docs/reference/interfaces.md b/docs/reference/interfaces.md index 6d025a2ea..703b394ac 100644 --- a/docs/reference/interfaces.md +++ b/docs/reference/interfaces.md @@ -31,6 +31,10 @@ public interface ICache ValueTask GetOrAddAsync(CacheKey cacheKey, Func> generator, DateTimeOffset expiration, CancellationToken token = default); + ValueTask GetOrRevalidateAsync(CacheKey cacheKey, Func, CancellationToken, Task>> generator, CancellationToken token = default); + + ValueTask GetOrRevalidateAsync(CacheKey cacheKey, TState state, Func, CancellationToken, Task>> generator, CancellationToken token = default); + ValueTask[]> GetOrAddAsync(KeyValuePair[] entries, Func[]>> generator, CancellationToken token = default) where TState : notnull; ValueTask[]> GetOrAddAsync(KeyValuePair[] entries, Func[]>> generator, TimeSpan expiration, CancellationToken token = default) where TState : notnull; @@ -130,6 +134,10 @@ public interface ICache : IDisposable ValueTask GetOrAddAsync(CacheKey cacheKey, Func> generator, DateTimeOffset expiration, CachePolicy? policy, CancellationToken token = default); + ValueTask GetOrRevalidateAsync(CacheKey cacheKey, Func, CancellationToken, Task>> generator, CachePolicy? policy, CancellationToken token = default); + + ValueTask GetOrRevalidateAsync(CacheKey cacheKey, TState state, Func, CancellationToken, Task>> generator, CachePolicy? policy, CancellationToken token = default); + ValueTask[]> GetOrAddAsync(KeyValuePair[] entries, Func[]>> generator, CachePolicy? policy, CancellationToken token = default) where TState : notnull; @@ -185,6 +193,8 @@ public interface ICache : IDisposable `ICache` is the dynamic-key, dynamic-type cache surface. Unlike `ICache`, the value type is specified as a generic type argument on each method call rather than fixed at cache-creation time, and a `CachePolicy` can be supplied per call rather than resolved by `typeof(T).FullName`. It also exposes `GetCacheEntryAsync` for callers that need cache-entry metadata (hit/miss status, expiration) in addition to the value. `ICache` implements `IDisposable`, but instances returned by `ICacheFactory.CreateCache(...)` are provider-owned (typically singletons resolved through a `Lazy<>`); their lifetime is managed by the provider and the DI container, so callers should not dispose them per use. +Both interfaces offer sealed `GetOrRevalidateAsync` overloads for stateful and stateless generators. Their generator receives `HasPreviousValue`, `PreviousValue`, `ETag` and `LastModified` on `RevalidationContext`. `Modified` or `NotModified` returns a `RevalidatedValue`, whose `Value`, `Expiration`, `ETag`, `LastModified`, `IsNotModified` and `SkipFailSafe` describe the answer. Use the context supplied to the generator to confirm a previous value. `GetCacheEntryAsync` exposes validators through `Metadata` when at least one is present. See [Conditional refresh](../how-to/choosing-a-get-or-add-overload.md#conditional-refresh-with-getorrevalidateasync) for the call pattern, policy recipes and scope limits. + ### `IMigrationCache` ```csharp diff --git a/src/UiPath.Caching.Abstractions/CompatibilitySuppressions.xml b/src/UiPath.Caching.Abstractions/CompatibilitySuppressions.xml index 082ac9ef1..16057b78c 100644 --- a/src/UiPath.Caching.Abstractions/CompatibilitySuppressions.xml +++ b/src/UiPath.Caching.Abstractions/CompatibilitySuppressions.xml @@ -421,6 +421,20 @@ lib/net10.0/UiPath.Caching.Abstractions.dll true + + CP0006 + M:UiPath.Caching.ICache.GetOrRevalidateAsync``1(UiPath.Caching.CacheKey,System.Func{UiPath.Caching.RevalidationContext{``0},System.Threading.CancellationToken,System.Threading.Tasks.Task{UiPath.Caching.RevalidatedValue{``0}}},UiPath.Caching.CachePolicy,System.Threading.CancellationToken) + lib/net10.0/UiPath.Caching.Abstractions.dll + lib/net10.0/UiPath.Caching.Abstractions.dll + true + + + CP0006 + M:UiPath.Caching.ICache.GetOrRevalidateAsync``2(UiPath.Caching.CacheKey,``1,System.Func{``1,UiPath.Caching.RevalidationContext{``0},System.Threading.CancellationToken,System.Threading.Tasks.Task{UiPath.Caching.RevalidatedValue{``0}}},UiPath.Caching.CachePolicy,System.Threading.CancellationToken) + lib/net10.0/UiPath.Caching.Abstractions.dll + lib/net10.0/UiPath.Caching.Abstractions.dll + true + CP0006 M:UiPath.Caching.ICache.RefreshAsync``1(UiPath.Caching.CacheKeyHandler@,System.DateTimeOffset,UiPath.Caching.CachePolicy,System.Threading.CancellationToken) @@ -799,6 +813,20 @@ lib/net10.0/UiPath.Caching.Abstractions.dll true + + CP0006 + M:UiPath.Caching.ICache`1.GetOrRevalidateAsync(UiPath.Caching.CacheKey,System.Func{UiPath.Caching.RevalidationContext{`0},System.Threading.CancellationToken,System.Threading.Tasks.Task{UiPath.Caching.RevalidatedValue{`0}}},System.Threading.CancellationToken) + lib/net10.0/UiPath.Caching.Abstractions.dll + lib/net10.0/UiPath.Caching.Abstractions.dll + true + + + CP0006 + M:UiPath.Caching.ICache`1.GetOrRevalidateAsync``1(UiPath.Caching.CacheKey,``0,System.Func{``0,UiPath.Caching.RevalidationContext{`0},System.Threading.CancellationToken,System.Threading.Tasks.Task{UiPath.Caching.RevalidatedValue{`0}}},System.Threading.CancellationToken) + lib/net10.0/UiPath.Caching.Abstractions.dll + lib/net10.0/UiPath.Caching.Abstractions.dll + true + CP0006 M:UiPath.Caching.ICache`1.RefreshAsync(UiPath.Caching.CacheKeyHandler@,System.DateTimeOffset,System.Threading.CancellationToken) @@ -1905,6 +1933,20 @@ lib/net8.0/UiPath.Caching.Abstractions.dll true + + CP0006 + M:UiPath.Caching.ICache.GetOrRevalidateAsync``1(UiPath.Caching.CacheKey,System.Func{UiPath.Caching.RevalidationContext{``0},System.Threading.CancellationToken,System.Threading.Tasks.Task{UiPath.Caching.RevalidatedValue{``0}}},UiPath.Caching.CachePolicy,System.Threading.CancellationToken) + lib/net8.0/UiPath.Caching.Abstractions.dll + lib/net8.0/UiPath.Caching.Abstractions.dll + true + + + CP0006 + M:UiPath.Caching.ICache.GetOrRevalidateAsync``2(UiPath.Caching.CacheKey,``1,System.Func{``1,UiPath.Caching.RevalidationContext{``0},System.Threading.CancellationToken,System.Threading.Tasks.Task{UiPath.Caching.RevalidatedValue{``0}}},UiPath.Caching.CachePolicy,System.Threading.CancellationToken) + lib/net8.0/UiPath.Caching.Abstractions.dll + lib/net8.0/UiPath.Caching.Abstractions.dll + true + CP0006 M:UiPath.Caching.ICache.RefreshAsync``1(UiPath.Caching.CacheKeyHandler@,System.DateTimeOffset,UiPath.Caching.CachePolicy,System.Threading.CancellationToken) @@ -2283,6 +2325,20 @@ lib/net8.0/UiPath.Caching.Abstractions.dll true + + CP0006 + M:UiPath.Caching.ICache`1.GetOrRevalidateAsync(UiPath.Caching.CacheKey,System.Func{UiPath.Caching.RevalidationContext{`0},System.Threading.CancellationToken,System.Threading.Tasks.Task{UiPath.Caching.RevalidatedValue{`0}}},System.Threading.CancellationToken) + lib/net8.0/UiPath.Caching.Abstractions.dll + lib/net8.0/UiPath.Caching.Abstractions.dll + true + + + CP0006 + M:UiPath.Caching.ICache`1.GetOrRevalidateAsync``1(UiPath.Caching.CacheKey,``0,System.Func{``0,UiPath.Caching.RevalidationContext{`0},System.Threading.CancellationToken,System.Threading.Tasks.Task{UiPath.Caching.RevalidatedValue{`0}}},System.Threading.CancellationToken) + lib/net8.0/UiPath.Caching.Abstractions.dll + lib/net8.0/UiPath.Caching.Abstractions.dll + true + CP0006 M:UiPath.Caching.ICache`1.RefreshAsync(UiPath.Caching.CacheKeyHandler@,System.DateTimeOffset,System.Threading.CancellationToken) diff --git a/src/UiPath.Caching.Abstractions/ICache.GetOrAdd.cs b/src/UiPath.Caching.Abstractions/ICache.GetOrAdd.cs index ead1eb195..386a66f45 100644 --- a/src/UiPath.Caching.Abstractions/ICache.GetOrAdd.cs +++ b/src/UiPath.Caching.Abstractions/ICache.GetOrAdd.cs @@ -393,4 +393,19 @@ sealed ValueTask> GetOrAddResultAsync(ref CacheKeyHand cacheKey.Return(); } } + + /// Gets a cached value or runs a generator that can revalidate a previous value. + sealed ValueTask GetOrRevalidateAsync(CacheKey cacheKey, Func, CancellationToken, Task>> generator, CachePolicy? policy, CancellationToken token = default) => + GetOrRevalidateAsync, CancellationToken, Task>>>(cacheKey, generator, static (g, context, ct) => g(context, ct), policy, token); + + /// Gets a cached value or runs a stateful generator that can revalidate a previous value. + sealed ValueTask GetOrRevalidateAsync(CacheKey cacheKey, TState state, Func, CancellationToken, Task>> generator, CachePolicy? policy, CancellationToken token = default) => + this is IRevalidatingCache source + ? source.GetOrRevalidateAsync(cacheKey, state, generator, policy, token) + : GetOrAddWithExpirationAsync, CancellationToken, Task>> Generator)>( + cacheKey, + (state, generator), + static async (s, ct) => (await s.Generator(s.State, default, ct).ConfigureAwait(false)).ValidateContext(null).ToGenerated(), + policy, + token); } diff --git a/src/UiPath.Caching.Abstractions/ICacheOfT.GetOrAdd.cs b/src/UiPath.Caching.Abstractions/ICacheOfT.GetOrAdd.cs index 09b9d9567..3357aa514 100644 --- a/src/UiPath.Caching.Abstractions/ICacheOfT.GetOrAdd.cs +++ b/src/UiPath.Caching.Abstractions/ICacheOfT.GetOrAdd.cs @@ -200,6 +200,20 @@ public partial interface ICache } } + /// Gets a cached value or runs a generator that can revalidate a previous value. + sealed ValueTask GetOrRevalidateAsync(CacheKey cacheKey, Func, CancellationToken, Task>> generator, CancellationToken token = default) => + GetOrRevalidateAsync(cacheKey, generator, static (g, context, ct) => g(context, ct), token); + + /// Gets a cached value or runs a stateful generator that can revalidate a previous value. + sealed ValueTask GetOrRevalidateAsync(CacheKey cacheKey, TState state, Func, CancellationToken, Task>> generator, CancellationToken token = default) => + this is IRevalidatingCache source + ? source.GetOrRevalidateAsync(cacheKey, state, generator, token) + : GetOrAddWithExpirationAsync( + cacheKey, + (State: state, Generator: generator), + static async (s, ct) => (await s.Generator(s.State, default, ct).ConfigureAwait(false)).ValidateContext(null).ToGenerated(), + token); + /// Reads, and on a miss runs as GetOrAddAsync does; reports whether this call's generator produced the value and when the entry expires. sealed ValueTask> GetOrAddResultAsync(CacheKey cacheKey, Func> generator, CancellationToken token = default) { diff --git a/src/UiPath.Caching.Abstractions/IRevalidatingCache.cs b/src/UiPath.Caching.Abstractions/IRevalidatingCache.cs new file mode 100644 index 000000000..a0a7e03e0 --- /dev/null +++ b/src/UiPath.Caching.Abstractions/IRevalidatingCache.cs @@ -0,0 +1,6 @@ +namespace UiPath.Caching; + +internal interface IRevalidatingCache +{ + ValueTask GetOrRevalidateAsync(CacheKey cacheKey, TState state, Func, CancellationToken, Task>> generator, CachePolicy? policy, CancellationToken token); +} diff --git a/src/UiPath.Caching.Abstractions/IRevalidatingCacheOfT.cs b/src/UiPath.Caching.Abstractions/IRevalidatingCacheOfT.cs new file mode 100644 index 000000000..238cc59b6 --- /dev/null +++ b/src/UiPath.Caching.Abstractions/IRevalidatingCacheOfT.cs @@ -0,0 +1,6 @@ +namespace UiPath.Caching; + +internal interface IRevalidatingCache +{ + ValueTask GetOrRevalidateAsync(CacheKey cacheKey, TState state, Func, CancellationToken, Task>> generator, CancellationToken token); +} diff --git a/src/UiPath.Caching.Abstractions/InvalidRevalidationException.cs b/src/UiPath.Caching.Abstractions/InvalidRevalidationException.cs new file mode 100644 index 000000000..a23d0f619 --- /dev/null +++ b/src/UiPath.Caching.Abstractions/InvalidRevalidationException.cs @@ -0,0 +1,3 @@ +namespace UiPath.Caching; + +internal sealed class InvalidRevalidationException() : InvalidOperationException("The confirmation must come from the revalidation context given to the generator."); diff --git a/src/UiPath.Caching.Abstractions/PublicAPI.Unshipped.txt b/src/UiPath.Caching.Abstractions/PublicAPI.Unshipped.txt index bde9b9aed..1aec25c60 100644 --- a/src/UiPath.Caching.Abstractions/PublicAPI.Unshipped.txt +++ b/src/UiPath.Caching.Abstractions/PublicAPI.Unshipped.txt @@ -154,3 +154,25 @@ UiPath.Caching.IMigrationCache.TryCreateAsync(UiPath.Caching.CacheKey cacheKe UiPath.Caching.NullCache.TryCreateAsync(UiPath.Caching.CacheKey cacheKey, T? value, System.DateTimeOffset expiration, UiPath.Caching.CachePolicy? policy, System.Threading.CancellationToken token = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask UiPath.Caching.Broadcast.ITopic.Refused -> System.Action? UiPath.Caching.Broadcast.ITopic.Transport.get -> string? +UiPath.Caching.RevalidationContext +UiPath.Caching.RevalidationContext.RevalidationContext() -> void +UiPath.Caching.RevalidationContext.HasPreviousValue.get -> bool +UiPath.Caching.RevalidationContext.PreviousValue.get -> T? +UiPath.Caching.RevalidationContext.ETag.get -> string? +UiPath.Caching.RevalidationContext.LastModified.get -> System.DateTimeOffset? +UiPath.Caching.RevalidationContext.NotModified(System.DateTimeOffset? expiration = null) -> UiPath.Caching.RevalidatedValue +UiPath.Caching.RevalidationContext.Modified(T? value, string? etag = null, System.DateTimeOffset? lastModified = null, System.DateTimeOffset? expiration = null) -> UiPath.Caching.RevalidatedValue +static UiPath.Caching.RevalidationContext.WithPrevious(T? value, string? etag = null, System.DateTimeOffset? lastModified = null) -> UiPath.Caching.RevalidationContext +UiPath.Caching.RevalidatedValue +UiPath.Caching.RevalidatedValue.RevalidatedValue() -> void +UiPath.Caching.RevalidatedValue.Value.get -> T? +UiPath.Caching.RevalidatedValue.Expiration.get -> System.DateTimeOffset? +UiPath.Caching.RevalidatedValue.ETag.get -> string? +UiPath.Caching.RevalidatedValue.LastModified.get -> System.DateTimeOffset? +UiPath.Caching.RevalidatedValue.IsNotModified.get -> bool +UiPath.Caching.RevalidatedValue.SkipFailSafe.get -> bool +UiPath.Caching.RevalidatedValue.SkipFailSafe.init -> void +UiPath.Caching.ICache.GetOrRevalidateAsync(UiPath.Caching.CacheKey cacheKey, System.Func, System.Threading.CancellationToken, System.Threading.Tasks.Task>!>! generator, UiPath.Caching.CachePolicy? policy, System.Threading.CancellationToken token = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +UiPath.Caching.ICache.GetOrRevalidateAsync(UiPath.Caching.CacheKey cacheKey, TState state, System.Func, System.Threading.CancellationToken, System.Threading.Tasks.Task>!>! generator, UiPath.Caching.CachePolicy? policy, System.Threading.CancellationToken token = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +UiPath.Caching.ICache.GetOrRevalidateAsync(UiPath.Caching.CacheKey cacheKey, System.Func, System.Threading.CancellationToken, System.Threading.Tasks.Task>!>! generator, System.Threading.CancellationToken token = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +UiPath.Caching.ICache.GetOrRevalidateAsync(UiPath.Caching.CacheKey cacheKey, TState state, System.Func, System.Threading.CancellationToken, System.Threading.Tasks.Task>!>! generator, System.Threading.CancellationToken token = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask diff --git a/src/UiPath.Caching.Abstractions/RevalidatedValue.cs b/src/UiPath.Caching.Abstractions/RevalidatedValue.cs new file mode 100644 index 000000000..f29ab3dce --- /dev/null +++ b/src/UiPath.Caching.Abstractions/RevalidatedValue.cs @@ -0,0 +1,47 @@ +namespace UiPath.Caching; + +/// The value, expiration and validators returned by a revalidation generator. +public readonly struct RevalidatedValue +{ + internal RevalidatedValue(T? value, string? etag, DateTimeOffset? lastModified, DateTimeOffset? expiration, object? confirmed = null) + { + Value = value; + ETag = etag; + LastModified = lastModified; + Expiration = expiration; + Confirmed = confirmed; + } + + /// The new or confirmed value. + public T? Value { get; } + + /// When the value expires, or null to use the cache policy. + public DateTimeOffset? Expiration { get; } + + /// The entity tag of the value. + public string? ETag { get; } + + /// When the source last modified the value. + public DateTimeOffset? LastModified { get; } + + /// Whether the generator confirmed the previous value. + public bool IsNotModified => Confirmed is not null; + + /// + public bool SkipFailSafe { get; init; } + + /// The identity of the context the generator confirmed. + internal object? Confirmed { get; } + + internal RevalidatedValue ValidateContext(object? identity) + { + if (Confirmed is not null && !ReferenceEquals(Confirmed, identity)) + { + throw new InvalidRevalidationException(); + } + + return this; + } + + internal GeneratedValue ToGenerated() => new(Value, Expiration) { SkipFailSafe = SkipFailSafe }; +} diff --git a/src/UiPath.Caching.Abstractions/RevalidationContext.cs b/src/UiPath.Caching.Abstractions/RevalidationContext.cs new file mode 100644 index 000000000..6e9b98e33 --- /dev/null +++ b/src/UiPath.Caching.Abstractions/RevalidationContext.cs @@ -0,0 +1,47 @@ +namespace UiPath.Caching; + +/// The previous value and its validators, when available to a revalidation generator. +public readonly struct RevalidationContext +{ + internal RevalidationContext(T? previousValue, string? etag, DateTimeOffset? lastModified, object identity) + { + Identity = identity; + PreviousValue = previousValue; + ETag = etag; + LastModified = lastModified; + } + + /// Whether a previous value is available, including a cached null. + public bool HasPreviousValue => Identity is not null; + + /// The previous value. + public T? PreviousValue { get; } + + /// The entity tag of the previous value. + public string? ETag { get; } + + /// When the source last modified the previous value. + public DateTimeOffset? LastModified { get; } + + internal object? Identity { get; } + + /// Creates a context with a previous value and optional validators. + public static RevalidationContext WithPrevious(T? value, string? etag = null, DateTimeOffset? lastModified = null) => + new(value, etag, lastModified, new object()); + + /// Confirms the previous value and preserves its validators. + /// There is no previous value. + public RevalidatedValue NotModified(DateTimeOffset? expiration = null) + { + if (!HasPreviousValue) + { + throw new InvalidOperationException("There is no previous value to revalidate."); + } + + return new RevalidatedValue(PreviousValue, ETag, LastModified, expiration, Identity); + } + + /// Returns a new value with optional validators and expiration. + public RevalidatedValue Modified(T? value, string? etag = null, DateTimeOffset? lastModified = null, DateTimeOffset? expiration = null) => + new(value, etag, lastModified, expiration); +} diff --git a/src/UiPath.Caching/BackgroundWrites.cs b/src/UiPath.Caching/BackgroundWrites.cs index f24e8dda8..f2b699290 100644 --- a/src/UiPath.Caching/BackgroundWrites.cs +++ b/src/UiPath.Caching/BackgroundWrites.cs @@ -141,16 +141,17 @@ public bool RunAppending(string key, TState state, Func lo RunCore(key, state, local, work, false, !fill, dropped, overtaken) ?? false; /// Starts watching the key for changes by anything but a fill; the token it returns is what takes. - public long BeginFill(string key, bool timed = false) => _fills.Begin(key, timed ? Math.Max(1, clock.GetTimestamp()) : 0); + public long BeginFill(string key, bool timed = false, bool independentTiming = false) => + _fills.Begin(key, timed ? Math.Max(1, clock.GetTimestamp()) : 0, timed && independentTiming); /// How long the watch of the key has run, for a watch begun timed and a token that was taken; null otherwise. public TimeSpan? FillElapsed(string key, long token) => - token != Untracked && _fills.Started(key) is var started && started != 0 ? clock.GetElapsedTime(started) : null; + token != Untracked && _fills.Started(key, token) is var started && started != 0 ? clock.GetElapsedTime(started) : null; - public void EndFill(string key) => _fills.End(key); + public void EndFill(string key, long token = Untracked) => _fills.End(key, token); /// Keeps a watch running past its fill, for a write that checks it later; each retain is ended by an . - public void RetainFill(string key) => _fills.Retain(key); + public void RetainFill(string key, long token = Untracked) => _fills.Retain(key, token); /// True when nothing but a fill has changed the key since was taken; a token that was not taken stands for no watch. public bool FillIntact(string key, long token) => token == Untracked || _fills.Intact(key, token); diff --git a/src/UiPath.Caching/CacheEntryFactory.cs b/src/UiPath.Caching/CacheEntryFactory.cs index accded3c0..e1f43f7e2 100644 --- a/src/UiPath.Caching/CacheEntryFactory.cs +++ b/src/UiPath.Caching/CacheEntryFactory.cs @@ -25,6 +25,8 @@ private struct Marks : IEquatable private sealed record CacheEntry : ICacheEntry, ILocalEntry { + private readonly IDictionary? _storedMetadata; + // Not part of the entry's value: every copy of an entry equals the others. private Marks _marks; @@ -32,14 +34,16 @@ public CacheEntry(T? value, DateTimeOffset? expiration = null, IDictionary? Metadata { get; private set; } + public IDictionary? Metadata => _storedMetadata is EntryValidators validators ? validators.Shown : _storedMetadata; + + EntryValidators? ILocalEntry.Validators => _storedMetadata as EntryValidators; object? ICacheEntry.Value => Value; @@ -91,6 +95,6 @@ void ILocalEntry.MarkRead(int nowSeconds) } public ICacheEntry NewEntry(DateTimeOffset? expiration = null, IDictionary? metadata = null) => - new CacheEntry(Value, expiration, metadata); + new CacheEntry(Value, expiration, metadata ?? (_storedMetadata as EntryValidators)); } } diff --git a/src/UiPath.Caching/CacheEventPublisher.cs b/src/UiPath.Caching/CacheEventPublisher.cs index 840694ad4..6564763b5 100644 --- a/src/UiPath.Caching/CacheEventPublisher.cs +++ b/src/UiPath.Caching/CacheEventPublisher.cs @@ -39,7 +39,7 @@ public ValueTask MetadataUpdatedAsync(ICacheEntryOptions options, Type? en { Dictionary properties = new() { - [KnownFieldNames.MetadataKey] = options.Metadata, + [KnownFieldNames.MetadataKey] = EventMetadata(options.Metadata), [KnownFieldNames.ExpirationKey] = options.Expiration, }; return RaiseEventAsync(options, KnownEventTypes.CacheRefreshed, entryType, properties); @@ -96,7 +96,7 @@ internal ValueTask MetadataUpdatedAsync(TOptions options, Type? { Dictionary properties = new() { - [KnownFieldNames.MetadataKey] = options.Metadata, + [KnownFieldNames.MetadataKey] = EventMetadata(options.Metadata), [KnownFieldNames.ExpirationKey] = options.Expiration, }; return RaiseEventAsync(options, KnownEventTypes.CacheRefreshed, entryType, properties); @@ -117,9 +117,9 @@ internal ValueTask CacheSetAsync(TOptions options, Type? entryTy [KnownFieldNames.PeerFieldsKey] = fields, [KnownFieldNames.PeerExpirationKey] = options.Expiration, }; - if (options.Metadata is not null) + if (EventMetadata(options.Metadata) is { } metadata) { - properties[KnownFieldNames.PeerMetadataKey] = options.Metadata; + properties[KnownFieldNames.PeerMetadataKey] = metadata; } return RaiseEventAsync(options, KnownEventTypes.CacheSet, entryType, properties); @@ -141,6 +141,9 @@ internal ValueTask CacheRemovedAsync(TOptions options, Type? ent where TOptions : struct, ICacheEntryOptions => RaiseEventAsync(options, KnownEventTypes.CacheRemoved, entryType); + private static IDictionary? EventMetadata(IDictionary? metadata) => + metadata is EntryValidators ? null : metadata; + private ValueTask RaiseEventAsync(TOptions options, string eventType, Type? entryType, IDictionary? properties = null) where TOptions : ICacheEntryOptions { diff --git a/src/UiPath.Caching/CacheOfT.cs b/src/UiPath.Caching/CacheOfT.cs index ec61e0193..9f4386f04 100644 --- a/src/UiPath.Caching/CacheOfT.cs +++ b/src/UiPath.Caching/CacheOfT.cs @@ -1,7 +1,7 @@ namespace UiPath.Caching; [ExcludeFromCodeCoverage] -public class Cache : ICache, ISpanKeyCache, IResultCache +public class Cache : ICache, ISpanKeyCache, IResultCache, IRevalidatingCache { private readonly ICache _cache; private readonly ISpanKeyCache? _spanCache; @@ -418,6 +418,9 @@ public ValueTask> GetOrAddResultAsync(CacheKey cacheKey, : _cache.GetOrAddResultAsync(GetCacheKey(cacheKey), state, generator, expiration, Policy, token); } + ValueTask IRevalidatingCache.GetOrRevalidateAsync(CacheKey cacheKey, TState state, Func, CancellationToken, Task>> generator, CancellationToken token) => + _cache.GetOrRevalidateAsync(GetCacheKey(cacheKey), state, generator, Policy, token); + ValueTask> IResultCache.GetOrAddResultAsync(Span cacheKey, Func> generator, CancellationToken token) { Span buffer = _cacheKeyStrategy is DefaultCacheKeyStrategy ? default : stackalloc char[SpanKey.MaxLength]; diff --git a/src/UiPath.Caching/EntryValidators.cs b/src/UiPath.Caching/EntryValidators.cs new file mode 100644 index 000000000..04c37dfbf --- /dev/null +++ b/src/UiPath.Caching/EntryValidators.cs @@ -0,0 +1,257 @@ +using System.Collections; +using System.Collections.ObjectModel; +using System.Globalization; + +namespace UiPath.Caching; + +internal class EntryValidators : IDictionary +{ + public const string ETagKey = "etag"; + public const string LastModifiedKey = "last-modified"; + + private static readonly ReadOnlyCollection NoKeys = new([]); + private static readonly ReadOnlyCollection ETagKeys = new([ETagKey]); + private static readonly ReadOnlyCollection LastModifiedKeys = new([LastModifiedKey]); + private static readonly ReadOnlyCollection BothKeys = new([ETagKey, LastModifiedKey]); + + private EntryValidators(string? etag, DateTimeOffset? lastModified, TimeSpan? lifetime) + { + ETag = etag; + LastModified = lastModified; + Lifetime = lifetime; + } + + public string? ETag { get; } + + public DateTimeOffset? LastModified { get; } + + public TimeSpan? Lifetime { get; } + + /// The metadata an entry holding these validators shows: none without validators. + public virtual IDictionary? Shown => Count == 0 ? null : this; + + public int Count => (ETag is null ? 0 : 1) + (LastModified is null ? 0 : 1); + + public bool IsReadOnly => true; + + public ICollection Keys => (ETag is not null, LastModified.HasValue) switch + { + (true, true) => BothKeys, + (true, false) => ETagKeys, + (false, true) => LastModifiedKeys, + _ => NoKeys, + }; + + public ICollection Values => new ValueView(this); + + public string? this[string key] + { + get => TryGetValue(key, out var value) ? value : throw new KeyNotFoundException(); + set => throw new NotSupportedException(); + } + + public static EntryValidators? From(string? etag, DateTimeOffset? lastModified, TimeSpan? lifetime = null) => + etag is null && lastModified is null && lifetime is null ? null : new EntryValidators(etag, lastModified, lifetime); + + public static EntryValidators? OfEntry(ICacheEntry entry) => + entry is ILocalEntry { Validators: { } validators } ? validators : Of(entry.Metadata); + + public static TimeSpan? LifetimeOfEntry(ICacheEntry entry) => entry switch + { + ILocalEntry local => local.Validators?.Lifetime, + EntryWithLifetime stored => stored.Lifetime, + _ => Of(entry.Metadata)?.Lifetime, + }; + + public static ICacheEntry CreateEntry(ICacheEntryFactory factory, T value, DateTimeOffset expiration, EntryValidators? validators) + { + if (validators is not { Lifetime: { } lifetime } || factory is CacheEntryFactory) + { + return factory.Create(value, expiration, validators); + } + + var entry = factory.Create(value, expiration, validators.Count == 0 ? null : validators); + return entry switch + { + ILocalEntry { Validators: var held } when ReferenceEquals(held, validators) => entry, + + // A built-in entry from a custom factory keeps the lifetime in a copy of its own, so its local bookkeeping stays visible. + ILocalEntry => (ICacheEntry)entry.NewEntry(entry.Expiration, Keeping(entry.Metadata, lifetime)), + _ => new EntryWithLifetime(entry, lifetime), + }; + } + + public static ICacheEntry PublicEntry(ICacheEntry entry) => + entry is EntryWithLifetime stored ? stored.Entry : entry; + + public static ICacheEntry PublicEntry(ICacheEntry entry) => + entry is EntryWithLifetime stored ? (ICacheEntry)stored.Entry : entry; + + public static EntryValidators? Of(IDictionary? metadata) + { + if (metadata is null || metadata is EntryValidators) + { + return (EntryValidators?)metadata; + } + + metadata.TryGetValue(ETagKey, out var etag); + metadata.TryGetValue(LastModifiedKey, out var text); + var lastModified = DateTimeOffset.TryParseExact(text, "O", CultureInfo.InvariantCulture, DateTimeStyles.None, out var parsed) + ? parsed + : (DateTimeOffset?)null; + return From(etag, lastModified); + } + + public EntryValidators WithLifetime(TimeSpan? lifetime) => new(ETag, LastModified, lifetime); + + public bool ContainsKey(string key) + { + ArgumentNullException.ThrowIfNull(key); + return key switch + { + ETagKey => ETag is not null, + LastModifiedKey => LastModified.HasValue, + _ => false, + }; + } + + public bool TryGetValue(string key, out string? value) + { + ArgumentNullException.ThrowIfNull(key); + value = key switch + { + ETagKey => ETag, + LastModifiedKey => LastModified?.ToUniversalTime().ToString("O", CultureInfo.InvariantCulture), + _ => null, + }; + return value is not null; + } + + public bool Contains(KeyValuePair item) => + TryGetValue(item.Key, out var value) && value == item.Value; + + public void CopyTo(KeyValuePair[] array, int arrayIndex) + { + ArgumentNullException.ThrowIfNull(array); + ArgumentOutOfRangeException.ThrowIfNegative(arrayIndex); + ArgumentOutOfRangeException.ThrowIfGreaterThan(arrayIndex, array.Length); + if (array.Length - arrayIndex < Count) + { + throw new ArgumentException("The destination array has insufficient space.", nameof(array)); + } + + foreach (var pair in this) + { + array[arrayIndex++] = pair; + } + } + + public IEnumerator> GetEnumerator() + { + if (ETag is not null) + { + yield return new KeyValuePair(ETagKey, ETag); + } + + if (TryGetValue(LastModifiedKey, out var lastModified)) + { + yield return new KeyValuePair(LastModifiedKey, lastModified); + } + } + + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + + public void Add(string key, string? value) => throw new NotSupportedException(); + + public void Add(KeyValuePair item) => throw new NotSupportedException(); + + public bool Remove(string key) => throw new NotSupportedException(); + + public bool Remove(KeyValuePair item) => throw new NotSupportedException(); + + public void Clear() => throw new NotSupportedException(); + + /// Validators that hold and show , the metadata the factory gave its entry. + private static EntryValidators Keeping(IDictionary? shown, TimeSpan lifetime) => shown switch + { + null => new EntryValidators(null, null, lifetime), + EntryValidators validators => validators.WithLifetime(lifetime), + _ => new ShownValidators(Of(shown), shown, lifetime), + }; + + private sealed class ShownValidators(EntryValidators? validators, IDictionary shown, TimeSpan lifetime) + : EntryValidators(validators?.ETag, validators?.LastModified, lifetime) + { + public override IDictionary? Shown => shown; + } + + // A custom factory can return the same entry for several writes with different lifetimes. + private abstract class EntryWithLifetime(ICacheEntry entry, TimeSpan lifetime) + { + public ICacheEntry Entry { get; } = entry; + + public TimeSpan Lifetime { get; } = lifetime; + } + + private sealed class EntryWithLifetime(ICacheEntry entry, TimeSpan lifetime) : EntryWithLifetime(entry, lifetime), ICacheEntry + { + public T? Value => entry.Value; + + object? ICacheEntry.Value => Entry.Value; + + public DateTimeOffset Expiration => entry.Expiration; + + public IDictionary? Metadata => entry.Metadata; + + public bool Found => entry.Found; + + public ICacheEntry NewEntry(DateTimeOffset? expiration = null, IDictionary? metadata = null) + { + var copy = entry.NewEntry(expiration, metadata); + return metadata is null && copy is ICacheEntry typed ? new EntryWithLifetime(typed, Lifetime) : copy; + } + } + + private sealed class ValueView(EntryValidators owner) : ICollection + { + public int Count => owner.Count; + + public bool IsReadOnly => true; + + public bool Contains(string? item) => + (owner.ETag is not null && owner.ETag == item) + || (owner.TryGetValue(LastModifiedKey, out var lastModified) && lastModified == item); + + public void CopyTo(string?[] array, int arrayIndex) + { + ArgumentNullException.ThrowIfNull(array); + ArgumentOutOfRangeException.ThrowIfNegative(arrayIndex); + ArgumentOutOfRangeException.ThrowIfGreaterThan(arrayIndex, array.Length); + if (array.Length - arrayIndex < Count) + { + throw new ArgumentException("The destination array has insufficient space.", nameof(array)); + } + + foreach (var value in this) + { + array[arrayIndex++] = value; + } + } + + public IEnumerator GetEnumerator() + { + foreach (var pair in owner) + { + yield return pair.Value; + } + } + + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + + public void Add(string? item) => throw new NotSupportedException(); + + public bool Remove(string? item) => throw new NotSupportedException(); + + public void Clear() => throw new NotSupportedException(); + } +} diff --git a/src/UiPath.Caching/FillWatches.cs b/src/UiPath.Caching/FillWatches.cs index f77839339..ce8ff0cc6 100644 --- a/src/UiPath.Caching/FillWatches.cs +++ b/src/UiPath.Caching/FillWatches.cs @@ -13,8 +13,8 @@ internal sealed class FillWatches public bool Any => Volatile.Read(ref _watched) != 0; - /// Starts a watch of the key, or joins the one running; the token is what takes. is the first fill's timestamp, 0 for none. - public long Begin(string key, long started = 0) + /// Starts or joins a key watch. With independent timing, the token carries this fill's start while sharing the key's change tracking. + public long Begin(string key, long started = 0, bool independentTiming = false) { var shard = ShardOf(key); lock (shard.Gate) @@ -28,12 +28,20 @@ public long Begin(string key, long started = 0) } watch.Count++; - return watch.Version + shard.Epoch; + var version = watch.Version + shard.Epoch; + if (!independentTiming) + { + return version; + } + + var token = --shard.RetrySequence; + (shard.Retries ??= []).Add(token, new TimedRetry(version, started)); + return token; } } /// Another hold on the running watch of the key, which gives back; none when the key is not watched. - public void Retain(string key) + public void Retain(string key, long token = BackgroundWrites.Untracked) { var shard = ShardOf(key); lock (shard.Gate) @@ -42,15 +50,26 @@ public void Retain(string key) if (!Unsafe.IsNullRef(ref watch)) { watch.Count++; + ref var retry = ref FindRetry(shard, token); + if (!Unsafe.IsNullRef(ref retry)) + { + retry.Count++; + } } } } - public void End(string key) + public void End(string key, long token = BackgroundWrites.Untracked) { var shard = ShardOf(key); lock (shard.Gate) { + ref var retry = ref FindRetry(shard, token); + if (!Unsafe.IsNullRef(ref retry) && --retry.Count == 0) + { + shard.Retries!.Remove(token); + } + ref var watch = ref CollectionsMarshal.GetValueRefOrNullRef(shard.Watches, key); if (!Unsafe.IsNullRef(ref watch) && --watch.Count == 0) { @@ -66,17 +85,34 @@ public bool Intact(string key, long token) var shard = ShardOf(key); lock (shard.Gate) { + if (token < BackgroundWrites.Untracked) + { + ref var retry = ref FindRetry(shard, token); + if (Unsafe.IsNullRef(ref retry)) + { + return false; + } + + token = retry.Version; + } + ref var watch = ref CollectionsMarshal.GetValueRefOrNullRef(shard.Watches, key); return !Unsafe.IsNullRef(ref watch) && watch.Version + shard.Epoch == token; } } - /// The timestamp the watch of the key began at, 0 when the key is not watched or its watch was not timed. - public long Started(string key) + /// The token's independent start or the shared watch's start; 0 for an ended or untimed watch. + public long Started(string key, long token) { var shard = ShardOf(key); lock (shard.Gate) { + if (token < BackgroundWrites.Untracked) + { + ref var retry = ref FindRetry(shard, token); + return Unsafe.IsNullRef(ref retry) ? 0 : retry.Started; + } + ref var watch = ref CollectionsMarshal.GetValueRefOrNullRef(shard.Watches, key); return Unsafe.IsNullRef(ref watch) ? 0 : watch.Started; } @@ -117,6 +153,11 @@ public void ChangedAll() } } + private static ref TimedRetry FindRetry(Shard shard, long token) => + ref (token < BackgroundWrites.Untracked && shard.Retries is { } retries + ? ref CollectionsMarshal.GetValueRefOrNullRef(retries, token) + : ref Unsafe.NullRef()); + private static Shard[] CreateShards() { var shards = new Shard[Shards]; @@ -137,6 +178,13 @@ private struct Watch public long Started; } + private struct TimedRetry(long version, long started) + { + public readonly long Version = version; + public readonly long Started = started; + public int Count = 1; + } + private sealed class Shard { public readonly Lock Gate = new(); @@ -145,5 +193,9 @@ private sealed class Shard // Under Gate: the last version a watch began at, and the changes of every key at once. public long Sequence; public long Epoch; + + // Negative retry tokens are separate from the shared watch versions and the untracked token. + public long RetrySequence = BackgroundWrites.Untracked; + public Dictionary? Retries; } } diff --git a/src/UiPath.Caching/IConfirmedRun.cs b/src/UiPath.Caching/IConfirmedRun.cs new file mode 100644 index 000000000..63cfd1999 --- /dev/null +++ b/src/UiPath.Caching/IConfirmedRun.cs @@ -0,0 +1,11 @@ +namespace UiPath.Caching; + +/// What a NotModified of the miss path confirmed, and how to ask again. +internal interface IConfirmedRun +{ + /// The kept value the NotModified confirmed. + StaleValue Kept { get; } + + /// Runs the generator with an empty context, under its own factory timeout. + Task> RegenerateAsync(CancellationToken token); +} diff --git a/src/UiPath.Caching/ILayeredOptions.cs b/src/UiPath.Caching/ILayeredOptions.cs index 44399b95a..4ab6d2a52 100644 --- a/src/UiPath.Caching/ILayeredOptions.cs +++ b/src/UiPath.Caching/ILayeredOptions.cs @@ -4,6 +4,8 @@ namespace UiPath.Caching; internal interface ILayeredOptions : ICacheEntryOptions where TSelf : struct, ILayeredOptions { + new IDictionary? Metadata { get; set; } + CancellationToken Token { get; } TSelf WithToken(CancellationToken token); diff --git a/src/UiPath.Caching/ILayeredShape.cs b/src/UiPath.Caching/ILayeredShape.cs index 171ed02f9..6331132fc 100644 --- a/src/UiPath.Caching/ILayeredShape.cs +++ b/src/UiPath.Caching/ILayeredShape.cs @@ -20,6 +20,8 @@ internal interface ILayeredShape /// Whether a store after a generator can compare against what saw. bool CanStamp { get; } + IStampedTier? StampedTier { get; } + /// Whether the value is nothing a caller could use: null for a plain entry, null or no fields for a hash. bool IsEmpty(TValue? value); diff --git a/src/UiPath.Caching/ILocalEntry.cs b/src/UiPath.Caching/ILocalEntry.cs index d7a71e79c..266e83f78 100644 --- a/src/UiPath.Caching/ILocalEntry.cs +++ b/src/UiPath.Caching/ILocalEntry.cs @@ -22,6 +22,9 @@ internal interface ILocalEntry /// The deadline of the last local write of the entry; when none. DateTimeOffset LocalDeadline { get; set; } + /// Validators and lifetime, including entries without public metadata. + EntryValidators? Validators { get; } + /// The entry's change token fired: a peer's removal, invalidation or write reached the key while the entry was, or was being, stored. bool TokenChanged { get; } diff --git a/src/UiPath.Caching/IStampedTier.cs b/src/UiPath.Caching/IStampedTier.cs index b880424ea..e0501bdea 100644 --- a/src/UiPath.Caching/IStampedTier.cs +++ b/src/UiPath.Caching/IStampedTier.cs @@ -6,6 +6,9 @@ internal interface IStampedTier /// The snapshot and its stamp; the stamp is null when the key held nothing. ValueTask<(SnapshotRead Snapshot, object? Stamp)> ReadStampedAsync(CacheKey cacheKey, CachePolicy? policy, CancellationToken token); + /// Whether the stamp matches the bytes the tier would write for this value. + bool Holds(object? stamp, T? value, CachePolicy? policy); + /// Writes the value if the key still holds what stands for, or is still absent when it is null. ValueTask WriteIfStampAsync(CacheKey cacheKey, T? value, DateTimeOffset expiration, CachePolicy? policy, object? stamp, CancellationToken token); } diff --git a/src/UiPath.Caching/MemoryCacheSetter.cs b/src/UiPath.Caching/MemoryCacheSetter.cs index 0de9cf5d3..df6ee1061 100644 --- a/src/UiPath.Caching/MemoryCacheSetter.cs +++ b/src/UiPath.Caching/MemoryCacheSetter.cs @@ -98,7 +98,7 @@ public bool Set(TOptions options, ICacheEntry item, Type entryType, Ti if (memoryCacheOptions.SizeLimit.HasValue) { - entry.Size = size = SizeProvider.GetSize(item); + entry.Size = size = SizeProvider.GetSize(EntryValidators.PublicEntry(item)); } if (kept is not null) diff --git a/src/UiPath.Caching/MultilayerCache.Background.cs b/src/UiPath.Caching/MultilayerCache.Background.cs index e5761eda1..d19ccf463 100644 --- a/src/UiPath.Caching/MultilayerCache.Background.cs +++ b/src/UiPath.Caching/MultilayerCache.Background.cs @@ -23,7 +23,7 @@ private bool FillInBackground(CacheEntryOptions options, T? value, CachePolic var watched = fill != BackgroundWrites.Untracked; if (watched) { - _background.RetainFill(name); + _background.RetainFill(name, fill); } var queued = _background.RunWithoutEvent( diff --git a/src/UiPath.Caching/MultilayerCache.FailSafe.cs b/src/UiPath.Caching/MultilayerCache.FailSafe.cs index 14e0a07d9..10e91e150 100644 --- a/src/UiPath.Caching/MultilayerCache.FailSafe.cs +++ b/src/UiPath.Caching/MultilayerCache.FailSafe.cs @@ -1,4 +1,3 @@ -using UiPath.Caching.Config; using UiPath.Caching.Telemetry; namespace UiPath.Caching; @@ -11,9 +10,6 @@ internal sealed partial class MultilayerCache private const string ReasonError = "error"; private const string ReasonTimeout = "timeout"; - // Per policy instance, so a value that skips fail-safe is written under an equal policy without it and allocates nothing after the first. - private static readonly ConditionalWeakTable FailSafeOff = []; - // The kept value a late store replaces and how long its generator had run (read at that time: the generator's watch has ended, and its fill still compares with a tombstone), in that store's flow; the count of late stores spares other writes the lookup. private static readonly AsyncLocal LateOf = new(); @@ -52,12 +48,11 @@ protected override void Dispose(bool disposing) } } - /// with fail-safe off and every other field as it is. - private static CachePolicy WithoutFailSafe(CachePolicy policy) => - policy.FailSafeEnabled != true ? policy : FailSafeOff.GetValue(policy, static p => CachePolicyMerger.Merge(new CachePolicy { FailSafeEnabled = false }, p)); - private static void CancelGenerator(object? source) => ((CancellationTokenSource)source!).Cancel(); + private static bool CanFallBack(Exception error, CancellationToken token) => + error is not InvalidRevalidationException && !(error is OperationCanceledException && token.IsCancellationRequested); + /// A run under a fail-safe policy: as the ordinary run, with the kept value in place of a generator that failed or runs late. /// Stores a generated result, as the ordinary run of its shape does. private async ValueTask RunOrStaleAsync( @@ -120,7 +115,7 @@ private static CachePolicy WithoutFailSafe(CachePolicy policy) => { return (await FactoryTimeout.RunAsync(state, generator, policy.FactoryTimeout, options.CacheKey, Name, Telemetry, scope.Token, clock: _clock).ConfigureAwait(false), null); } - catch (Exception ex) when (!(ex is OperationCanceledException && scope.Token.IsCancellationRequested) && TryGetStale(name, policy, out var current, out var kept)) + catch (Exception ex) when (CanFallBack(ex, scope.Token) && TryGetStale(name, policy, out var current, out var kept)) { return (default!, ServeStale(Logged(options, typeof(T)), current, kept, policy, ReasonError, ex)); } @@ -165,9 +160,9 @@ private static CachePolicy WithoutFailSafe(CachePolicy policy) => late = true; // For a caller that joined the run without fail-safe; observed here, since such a caller may stop waiting for it. - var answer = LateEntryAsync(generation, entryOf, options.Expiration); + var finished = StartLateFinish(generation, own, options, typeof(T), policy, localOnly, replaced, _background.FillElapsed(name, scope.Fill), store); + var answer = LateEntryAsync(generation, finished, entryOf, options.Expiration); answer.Forget(); - StartLateFinish(generation, own, options, typeof(T), policy, localOnly, replaced, _background.FillElapsed(name, scope.Fill), store); return (default!, ServeStale(Logged(options, typeof(T)), current, kept, policy, ReasonTimeout, null, answer)); } } @@ -179,7 +174,7 @@ private static CachePolicy WithoutFailSafe(CachePolicy policy) => { return (await generation.ConfigureAwait(false), null); } - catch (Exception ex) when (!(ex is OperationCanceledException && scope.Token.IsCancellationRequested) && TryGetStale(name, policy, out var current, out var kept)) + catch (Exception ex) when (CanFallBack(ex, scope.Token) && TryGetStale(name, policy, out var current, out var kept)) { return (default!, ServeStale(Logged(options, typeof(T)), current, kept, policy, ReasonError, ex)); } @@ -198,9 +193,14 @@ private static CachePolicy WithoutFailSafe(CachePolicy policy) => } } - /// The late generator's own answer: the entry a run would have made of its result, an expiration the result names included. - private async Task> LateEntryAsync(Task generation, Func> entryOf, DateTimeOffset expiration) => - entryOf(this, await generation.ConfigureAwait(false), expiration); + /// A late confirmation answers a joined caller only after the guarded store accepts it. + private async Task?> LateEntryAsync(Task generation, Task?> finished, Func> entryOf, DateTimeOffset expiration) + { + var result = await generation.ConfigureAwait(false); + return result is RevalidatedValue { Confirmed: not null } + ? await finished.ConfigureAwait(false) + : entryOf(this, result, expiration); + } /// /// Whether , which a run fell back to, answers a caller that joined the run: false when the caller gets what the run @@ -222,10 +222,12 @@ private static CachePolicy WithoutFailSafe(CachePolicy policy) => return StaleOrNull?.IsCurrent(name, kept) == true ? false : null; } - private void StartLateFinish(Task generation, CancellationTokenSource own, CacheEntryOptions options, Type entryType, CachePolicy policy, bool localOnly, StaleValue replaced, TimeSpan? ran, Func>> store) + private Task?> StartLateFinish(Task generation, CancellationTokenSource own, CacheEntryOptions options, Type entryType, CachePolicy policy, bool localOnly, StaleValue replaced, TimeSpan? ran, Func>> store) { Interlocked.Increment(ref _lateGenerations); - FinishLateAsync(generation, own, options.WithToken(CancellationToken.None), entryType, policy, localOnly, replaced, ran is { } elapsed ? (elapsed, _clock.GetTimestamp()) : null, store).Forget(); + var finished = FinishLateAsync(generation, own, options.WithToken(CancellationToken.None), entryType, policy, localOnly, replaced, ran is { } elapsed ? (elapsed, _clock.GetTimestamp()) : null, store); + finished.Forget(); + return finished; } /// From here only the cache's disposal cancels the generator, at once when it has begun. @@ -269,7 +271,7 @@ private CancellationToken LateShutdown() return won.Token; } - private async Task FinishLateAsync(Task generation, CancellationTokenSource own, CacheEntryOptions options, Type entryType, CachePolicy policy, bool localOnly, StaleValue replaced, (TimeSpan Elapsed, long At)? ran, Func>> store) + private async Task?> FinishLateAsync(Task generation, CancellationTokenSource own, CacheEntryOptions options, Type entryType, CachePolicy policy, bool localOnly, StaleValue replaced, (TimeSpan Elapsed, long At)? ran, Func>> store) { var outcome = "failed"; var shutdown = default(CancellationTokenRegistration); @@ -278,27 +280,27 @@ private async Task FinishLateAsync(Task generation, Cancell // Inside the try, so the generation is awaited and cleaned up whatever a cancellation that runs here throws. shutdown = CancelOnShutdown(own); var result = await generation.ConfigureAwait(false); - if (!Disposed && StillKept(options.CacheKey.Name, replaced)) + if (Disposed || !StillKept(options.CacheKey.Name, replaced)) { - LateStoreStarting?.Invoke(); - // The write checks again in the key's turn; this check only spares a store that cannot be kept. - Interlocked.Increment(ref _lateStores); - LateOf.Value = new LateStore(replaced, ran); - try - { - await store(this, options, result, policy, new GenerationScope(null, options.Token), localOnly).ConfigureAwait(false); - } - finally - { - LateOf.Value = null; - Interlocked.Decrement(ref _lateStores); - } + outcome = "discarded"; + return null; + } - outcome = "stored"; + // The write checks again in the key's turn. + LateStoreStarting?.Invoke(); + var late = new LateStore(replaced, ran); + Interlocked.Increment(ref _lateStores); + LateOf.Value = late; + try + { + var entry = await store(this, options, result, policy, new GenerationScope(null, options.Token), localOnly).ConfigureAwait(false); + outcome = late.Written ? "stored" : "discarded"; + return late.AcceptedConfirmation ? entry : null; } - else + finally { - outcome = "discarded"; + LateOf.Value = null; + Interlocked.Decrement(ref _lateStores); } } catch (Exception ex) when (!Disposed) @@ -317,6 +319,8 @@ private async Task FinishLateAsync(Task generation, Cancell Interlocked.Decrement(ref _lateGenerations); Telemetry.TryTrackEvent(FailSafeBackgroundEvent, [new(FailSafeTagCacheName, Name), new(FailSafeTagOutcome, outcome)]); } + + return null; } /// How long the generator of a late store had run by now, which a fill compares with a tombstone; null for any other write. @@ -327,6 +331,14 @@ private async Task FinishLateAsync(Task generation, Cancell private bool LateStillCurrent(in CacheEntryOptions options) => Volatile.Read(ref _lateStores) == 0 || LateOf.Value is not { } late || (!Disposed && StillKept(options.CacheKey.Name, late.Replaced)); + private void RecordLateWrite(bool written) + { + if (Volatile.Read(ref _lateStores) != 0 && LateOf.Value is { } late) + { + late.Written = written; + } + } + /// Drops the key's kept value for a generator answer the cache does not store, unless a write since the generator started kept it: a late answer drops only the value its generator replaced, any other only a value with no live entry. private void DropKeptForUnstored(string name) { @@ -357,5 +369,14 @@ private async ValueTask StoreLateAndAnnounceAsync(CacheEntryOptions opt [LoggerMessage(Level = LogLevel.Warning, Message = "The generator of {CacheKey} that fail-safe stopped waiting for failed.")] private partial void LogLateGenerationFailed(Exception ex, LoggedKey cacheKey); - private readonly record struct LateStore(StaleValue Replaced, (TimeSpan Elapsed, long At)? Ran); + private sealed class LateStore(StaleValue replaced, (TimeSpan Elapsed, long At)? ran) + { + public StaleValue Replaced { get; } = replaced; + + public (TimeSpan Elapsed, long At)? Ran { get; } = ran; + + public bool Written { get; set; } + + public bool AcceptedConfirmation { get; set; } + } } diff --git a/src/UiPath.Caching/MultilayerCache.Fill.cs b/src/UiPath.Caching/MultilayerCache.Fill.cs index 52ce3c479..f4d1b8f6b 100644 --- a/src/UiPath.Caching/MultilayerCache.Fill.cs +++ b/src/UiPath.Caching/MultilayerCache.Fill.cs @@ -209,7 +209,7 @@ private bool CanFill(CacheEntryOptions options, T? value, CachePolicy policy) return held is ILocalEntry { LocalDeadline: var deadline } && deadline > DateTimeOffset.MinValue && deadline != held.Expiration ? (ICacheEntry)held.NewEntry(deadline, held.Metadata) - : held; + : EntryValidators.PublicEntry(held); } /// The options a local-only entry is written with; the expiration is the deadline the local tier gives it. diff --git a/src/UiPath.Caching/MultilayerCache.Generate.cs b/src/UiPath.Caching/MultilayerCache.Generate.cs index 3e9670859..985be7e06 100644 --- a/src/UiPath.Caching/MultilayerCache.Generate.cs +++ b/src/UiPath.Caching/MultilayerCache.Generate.cs @@ -151,7 +151,7 @@ private bool TryGetLocalEntry(CacheEntryOptions options, [MaybeNullWhen(false // The batch or TryAdd that held the key gave it up: it is up for taking again, after a wait that makes the caller's miss stale. pending = StartRun(options, generator, policy, generate, seen, innerMissed: false, token, out _); } - catch (Exception ex) when (!(ex is OperationCanceledException && token.IsCancellationRequested) && TryGetStale(options.CacheKey.Name, policy, out var current, out var kept)) + catch (Exception ex) when (CanFallBack(ex, token) && TryGetStale(options.CacheKey.Name, policy, out var current, out var kept)) { // The run's starter may not have opted in to fail-safe: this caller did, and falls back as a starter would. return ServeStale(Logged(options, typeof(T)), current, kept, policy, ReasonError, ex); @@ -216,13 +216,14 @@ private bool TryGetLocalEntry(CacheEntryOptions options, [MaybeNullWhen(false private async ValueTask> StoreGeneratedEntryAsync(CacheEntryOptions cacheEntryOptions, T? ret, CachePolicy policy, GenerationScope scope, bool localOnly = false) { // One entry for the local tier and the caller: both see the same value and deadline. - var entry = _cacheEntryFactory.Create(ret, cacheEntryOptions.Expiration); + var entry = EntryValidators.CreateEntry(_cacheEntryFactory, ret, cacheEntryOptions.Expiration, cacheEntryOptions.Metadata as EntryValidators); if (TryPrepareGeneratedStore(cacheEntryOptions, ret, policy, scope, localOnly, entry, out var store, out var innerCacheDisconnected)) { if (innerCacheDisconnected) { - await StoreGeneratedForegroundAsync(store, ret, true, policy, entry).ConfigureAwait(false); + var written = await StoreGeneratedForegroundAsync(store, ret, true, policy, entry).ConfigureAwait(false); + RecordLateWrite(written); } else { @@ -236,6 +237,7 @@ private bool TryGetLocalEntry(CacheEntryOptions options, [MaybeNullWhen(false if (won && InLateStore) { await Layered().PublishSetAsync(store).ConfigureAwait(false); + RecordLateWrite(true); } } } @@ -271,7 +273,7 @@ private bool TryPrepareGeneratedStore( disconnected = GetInnerCacheDisconnected(); if (localOnly && !disconnected) { - KeepGeneratedLocally(options, value, policy, entry); + RecordLateWrite(KeepGeneratedLocally(options, value, policy, entry)); return false; } @@ -296,15 +298,16 @@ private ValueTask StoreGeneratedForegroundAsync(CacheEntryOptions store : Layered().InternalSetAsync(store, value, disconnected, policy, keepRefused: true, entry); /// Keeps a generated value as a written one is kept, for the connected lifetime; a failure is logged and the caller still gets the value. - private void KeepGeneratedLocally(CacheEntryOptions options, T? value, CachePolicy policy, ICacheEntry entry) + private bool KeepGeneratedLocally(CacheEntryOptions options, T? value, CachePolicy policy, ICacheEntry entry) { try { - ApplyLocal(options.CacheKey.Name, (Cache: this, Options: options, Value: value, Policy: policy, Entry: entry), static s => s.Cache.MemorySet(s.Options, s.Value, s.Cache.ConnectedLifetime(s.Policy), s.Entry, s.Policy)); + return ApplyLocal(options.CacheKey.Name, (Cache: this, Options: options, Value: value, Policy: policy, Entry: entry), static s => s.Cache.MemorySet(s.Options, s.Value, s.Cache.ConnectedLifetime(s.Policy), s.Entry, s.Policy)); } catch (Exception ex) { LogInnerCacheSetError(ex, Logged(options, typeof(T))); + return false; } } diff --git a/src/UiPath.Caching/MultilayerCache.Layered.cs b/src/UiPath.Caching/MultilayerCache.Layered.cs index 20ba1cb88..3af6db506 100644 --- a/src/UiPath.Caching/MultilayerCache.Layered.cs +++ b/src/UiPath.Caching/MultilayerCache.Layered.cs @@ -14,7 +14,9 @@ private readonly struct CacheShape(MultilayerCache cache) : ILayeredShape cache._innerCache is IMigrationCache; - public bool CanStamp => cache._innerCache is IStampedTier; + public bool CanStamp => StampedTier is not null; + + public IStampedTier? StampedTier => cache._innerCache as IStampedTier; public bool IsEmpty(T? value) => value is null; diff --git a/src/UiPath.Caching/MultilayerCache.Read.cs b/src/UiPath.Caching/MultilayerCache.Read.cs index 32745750b..8afd8e19f 100644 --- a/src/UiPath.Caching/MultilayerCache.Read.cs +++ b/src/UiPath.Caching/MultilayerCache.Read.cs @@ -51,7 +51,7 @@ internal sealed partial class MultilayerCache var probe = token.IsCancellationRequested ? LocalProbe.Unavailable : ProbeLocal(cacheKey, token, out local); if (probe == LocalProbe.Hit) { - return new ValueTask>(local!); + return new ValueTask>(EntryValidators.PublicEntry(local!)); } if (probe == LocalProbe.Miss && !_sharedInner) @@ -67,7 +67,7 @@ internal sealed partial class MultilayerCache NotCacheableException.ThrowIfNotCacheable(); if (!token.IsCancellationRequested && TryGetLocal(cacheKey, token, out var local)) { - return new ValueTask>(local); + return new ValueTask>(EntryValidators.PublicEntry(local)); } return GetCacheEntryAsync(new CacheKey(cacheKey), policy, token); @@ -78,7 +78,14 @@ internal sealed partial class MultilayerCache NotCacheableException.ThrowIfNotCacheable(); policy ??= _defaultPolicy; var options = Array.ConvertAll(cacheKeys, k => _entryBuilder.BuildEntryOptions(k, default, token)); - return await GetCacheEntriesInnerAsync(options, policy, token).ConfigureAwait(false); + var entries = await GetCacheEntriesInnerAsync(options, policy, token).ConfigureAwait(false); + for (var index = 0; index < entries.Length; index++) + { + var entry = entries[index]; + entries[index] = new KeyValuePair>(entry.Key, EntryValidators.PublicEntry(entry.Value)); + } + + return entries; } [OverloadResolutionPriority(1)] @@ -249,7 +256,8 @@ public ValueTask ContainsAsync(Span cacheKey, CancellationToken t { policy ??= _defaultPolicy; var options = _entryBuilder.BuildEntryOptions(cacheKey, _clock.ToDateTimeOffset(_multiLayerCacheOptions.DefaultExpiration), token); - return await GetCacheEntryInnerAsync(options, policy).ConfigureAwait(false); + var entry = await GetCacheEntryInnerAsync(options, policy).ConfigureAwait(false); + return EntryValidators.PublicEntry(entry); } private async ValueTask>[]> GetCacheEntriesInnerAsync(CacheEntryOptions[] options, CachePolicy policy, CancellationToken token = default) diff --git a/src/UiPath.Caching/MultilayerCache.Revalidate.cs b/src/UiPath.Caching/MultilayerCache.Revalidate.cs new file mode 100644 index 000000000..082b77c58 --- /dev/null +++ b/src/UiPath.Caching/MultilayerCache.Revalidate.cs @@ -0,0 +1,344 @@ +namespace UiPath.Caching; + +internal sealed partial class MultilayerCache +{ + private const string NotModifiedEvent = "cache.revalidation.not_modified"; + private const string RevalidationTagKind = "kind"; + private const string KindMiss = "miss"; + private const string KindRehydrate = "rehydrate"; + + /// Runs as a revalidation run starts, before it reads the kept value; tests land a write there. + internal Action? RevalidationStarting { get; set; } + + /// Runs just before the store of a confirmed value; tests land a removal there. + internal Action? ConfirmedStoreStarting { get; set; } + + public ValueTask GetOrRevalidateAsync(CacheKey cacheKey, TState state, Func, CancellationToken, Task>> generator, CachePolicy? policy, CancellationToken token) + { + ArgumentNullException.ThrowIfNull(generator); + return GetOrRevalidateCoreAsync(cacheKey, state, generator, policy ?? _defaultPolicy, _localMemorySetter.Writes, token); + } + + private async ValueTask GetOrRevalidateCoreAsync(CacheKey cacheKey, TState state, Func, CancellationToken, Task>> generator, CachePolicy policy, long seen, CancellationToken token) + { + NotCacheableException.ThrowIfNotCacheable(); + var localMissed = false; + if (!_sharedInner && !token.IsCancellationRequested) + { + var probe = ProbeLocal(cacheKey, token, out var local); + if (probe == LocalProbe.Hit && local!.Found) + { + TryRevalidateOnRehydrate(cacheKey, local, state, generator, policy); + return local.Value; + } + + localMissed = probe == LocalProbe.Miss; + } + + var cacheEntryOptions = _entryBuilder.BuildEntryOptions(cacheKey, GetExpiration(policy), token); + if (TryGetCooling(cacheEntryOptions.CacheKey.Name, policy, out var cooling)) + { + return cooling.Value; + } + + if (localMissed && !_sharedInner) + { + var run = new RevalidationRun(this, cacheEntryOptions.CacheKey, policy, state, generator); + var kept = (ICacheEntry)(await GetOrGenerateEntryAsync>(cacheEntryOptions, run, policy, static (cache, options, r, p, scope) => cache.RunRevalidatedAndStoreEntryAsync(options, r, p, scope, localOnly: true), seen, localMissed, token).ConfigureAwait(false))!; + return kept.Value; + } + + var entry = localMissed + ? await Layered().FetchInnerAsync(cacheEntryOptions, policy).ConfigureAwait(false) + : await GetCacheEntryInnerAsync(cacheEntryOptions, policy).ConfigureAwait(false); + if (entry.Found) + { + TryRevalidateOnRehydrate(cacheKey, entry, state, generator, policy); + return entry.Value; + } + + var miss = new RevalidationRun(this, cacheEntryOptions.CacheKey, policy, state, generator); + var result = (ICacheEntry)(await GetOrGenerateEntryAsync>(cacheEntryOptions, miss, policy, static (cache, options, r, p, scope) => cache.RunRevalidatedAndStoreEntryAsync(options, r, p, scope, localOnly: false), seen, localMissed, token).ConfigureAwait(false))!; + return result.Value; + } + + private void TryRevalidateOnRehydrate(CacheKey key, ICacheEntry local, TState state, Func, CancellationToken, Task>> generator, CachePolicy policy) + { + if (policy.RehydrateEnabled != true) + { + return; + } + + var layered = Layered(); + var duration = EntryValidators.LifetimeOfEntry(local) ?? ResolveDuration(policy); + if (layered.ShouldRehydrate(local.Value, policy, duration) && _rehydrator.PastThreshold(local.Expiration, policy, duration)) + { + var run = new RevalidationRehydrate(this, local, state, generator); + layered.TriggerRehydrate(key, local.Expiration, run.RunAsync, policy, duration, policy.JitterMaxDuration, run); + } + } + + private ValueTask RunRevalidatedAndStoreEntryAsync(CacheEntryOptions cacheEntryOptions, RevalidationRun run, CachePolicy policy, GenerationScope scope, bool localOnly) => + policy.FailSafeEnabled == true + ? RunOrStaleAsync, RevalidatedValue>(cacheEntryOptions, run, static (r, ct) => r.InvokeAsync(ct), policy, scope, localOnly, static (c, r, expiration) => c._cacheEntryFactory.Create(r.Value, r.Expiration ?? expiration), static (c, o, r, p, s, l) => c.StoreRevalidatedAsync(o, r, p, s, l)) + : RunOrdinaryRevalidatedAsync(cacheEntryOptions, run, policy, scope, localOnly); + + /// As , for a revalidation run. + private async ValueTask RunOrdinaryRevalidatedAsync(CacheEntryOptions cacheEntryOptions, RevalidationRun run, CachePolicy policy, GenerationScope scope, bool localOnly) + { + ICacheEntry entry; + scope = BeginFill(cacheEntryOptions, scope, localOnly); + try + { + LogCacheMissed(Logged(cacheEntryOptions, typeof(T))); + var result = await FactoryTimeout.RunAsync(run, static (r, ct) => r.InvokeAsync(ct), policy.FactoryTimeout, cacheEntryOptions.CacheKey, Name, Telemetry, scope.Token, clock: _clock).ConfigureAwait(false); + entry = await StoreRevalidatedAsync(cacheEntryOptions, result, policy, scope, localOnly).ConfigureAwait(false); + } + catch (Exception ex) + { + scope.Fail(ex); + throw; + } + finally + { + EndFill(cacheEntryOptions.CacheKey.Name, scope); + } + + scope.Complete(entry); + return entry; + } + + /// Stores a revalidated value with its validators: a confirmed one only while it is still the kept value, any other as a generated value. + private ValueTask> StoreRevalidatedAsync(CacheEntryOptions options, RevalidatedValue result, CachePolicy policy, GenerationScope scope, bool localOnly) + { + var original = options; + options.Expiration = result.Expiration ?? options.Expiration; + var now = _clock.GetUtcNow(); + options.Metadata = EntryValidators.From(result.ETag, result.LastModified, options.Expiration == DateTimeOffset.MaxValue ? null : options.Expiration - now); + if (result.Confirmed is not IConfirmedRun run) + { + return StoreGeneratedValueAsync(options, result.ToGenerated(), policy, scope, localOnly); + } + + if (options.Expiration <= now) + { + return ServeElapsedConfirmationAsync(original, options, result.Value, run, policy, scope, localOnly); + } + + var stored = result.SkipFailSafe ? WithoutFailSafe(policy) : policy; + return StoreConfirmedAsync(original, options, result.Value, run, stored, policy, scope, localOnly); + } + + private ValueTask> ServeElapsedConfirmationAsync(CacheEntryOptions original, CacheEntryOptions options, T? value, IConfirmedRun run, CachePolicy policy, GenerationScope scope, bool localOnly) + { + var late = InLateStore ? LateOf.Value : null; + var name = options.CacheKey.Name; + var current = late is null ? StillKept(name, run.Kept) : LateStillCurrent(options); + if (!current && late is null) + { + return RegenerateAndStoreAsync(original, run, policy, scope, localOnly); + } + + if (current && !scope.IsAbandoned) + { + StaleOrNull?.Drop(name, run.Kept); + if (late is not null) + { + // The late confirmation can answer a joiner even though its deadline prevents a write. + late.AcceptedConfirmation = true; + } + } + + return new(_cacheEntryFactory.Create(value, options.Expiration)); + } + + /// + /// Stores a confirmed value under the guard of a late store, so every write site checks in the key's write turn that it is still the kept value. + /// When nothing was written and it is no longer kept, the generator runs again with an empty context and its answer is stored and returned. + /// + private async ValueTask> StoreConfirmedAsync(CacheEntryOptions original, CacheEntryOptions options, T? value, IConfirmedRun run, CachePolicy stored, CachePolicy policy, GenerationScope scope, bool localOnly) + { + ConfirmedStoreStarting?.Invoke(); + var name = options.CacheKey.Name; + if (InLateStore && LateOf.Value is { } late) + { + var (entry, accepted, written, removed) = await WriteConfirmedAsync(options, value, stored, scope, localOnly).ConfigureAwait(false); + if (removed) + { + StaleOrNull?.Drop(name, run.Kept); + } + + late.Written = written; + late.AcceptedConfirmation = accepted; + return entry; + } + + (ICacheEntry Entry, bool Accepted, bool Written, bool Removed) answer; + Interlocked.Increment(ref _lateStores); + LateOf.Value = new LateStore(run.Kept, null); + try + { + answer = await WriteConfirmedAsync(options, value, stored, scope, localOnly).ConfigureAwait(false); + } + finally + { + LateOf.Value = null; + Interlocked.Decrement(ref _lateStores); + } + + if (answer.Removed) + { + StaleOrNull?.Drop(name, run.Kept); + } + else if (answer.Accepted || StillKept(name, run.Kept)) + { + return answer.Entry; + } + + return await RegenerateAndStoreAsync(original, run, policy, scope, localOnly).ConfigureAwait(false); + } + + private async ValueTask> RegenerateAndStoreAsync(CacheEntryOptions options, IConfirmedRun run, CachePolicy policy, GenerationScope scope, bool localOnly) + { + var fresh = BeginFill(options, scope with { Fill = BackgroundWrites.Untracked }, localOnly, independentTiming: true); + try + { + var again = await run.RegenerateAsync(fresh.Token).ConfigureAwait(false); + return await StoreRevalidatedAsync(options, again, policy, fresh, localOnly).ConfigureAwait(false); + } + finally + { + EndFill(options.CacheKey.Name, fresh); + } + } + + /// Returns what the guarded write accepted, including an existing entry the fill could use. + private async ValueTask<(ICacheEntry Entry, bool Accepted, bool Written, bool Removed)> WriteConfirmedAsync(CacheEntryOptions options, T? value, CachePolicy policy, GenerationScope scope, bool localOnly) + { + var entry = EntryValidators.CreateEntry(_cacheEntryFactory, value, options.Expiration, options.Metadata as EntryValidators); + if (localOnly && (value is not null || _multiLayerCacheOptions.CacheNullValues) && !scope.IsAbandoned && !GetInnerCacheDisconnected()) + { + var written = KeepGeneratedLocally(options, value, policy, entry); + return (entry, written, written, false); + } + + if (!TryPrepareGeneratedStore(options, value, policy, scope, localOnly, entry, out var store, out var disconnected)) + { + return (entry, false, false, false); + } + + if (disconnected) + { + var written = await StoreGeneratedForegroundAsync(store, value, true, policy, entry).ConfigureAwait(false); + return (entry, written, written, false); + } + + var filled = await FillInnerAsync(store, value, policy, entry, scope.Fill).ConfigureAwait(false); + if (filled.Won) + { + // Peers in a cooldown serve the value this one replaces, and need the event. + await Layered().PublishSetAsync(store).ConfigureAwait(false); + } + + return (filled.Adopted ?? entry, filled.Won || filled.Adopted is not null, filled.Won, filled.Removed); + } + + private void TrackNotModified(string kind = KindMiss) => + Telemetry.TryTrackEvent(NotModifiedEvent, [new(FailSafeTagCacheName, Name), new(RevalidationTagKind, kind)]); + + private sealed class RevalidationRehydrate(MultilayerCache cache, ICacheEntry local, TState state, Func, CancellationToken, Task>> generator) : RehydrateOverride + { + private RevalidationContext _context; + + public override void Saw(RehydrateSource source, ICacheEntry? seen, object? stamp, IStampedTier? tier, CachePolicy policy) + { + if (source == RehydrateSource.Local) + { + LocalEntry = local; + var validators = EntryValidators.OfEntry(local); + _context = new RevalidationContext(local.Value, validators?.ETag, validators?.LastModified, this); + } + else if (source == RehydrateSource.Stamped && seen is ICacheEntry entry) + { + var validators = EntryValidators.OfEntry(entry); + if (validators is null or { ETag: null, LastModified: null } + && EntryValidators.OfEntry(local) is { } localValidators + && (localValidators.ETag is not null || localValidators.LastModified is not null) + && tier!.Holds(stamp, local.Value, policy)) + { + validators = localValidators; + } + + _context = new RevalidationContext(entry.Value, validators?.ETag, validators?.LastModified, this); + } + } + + public override void BeforeConfirmedStore() => cache.ConfirmedStoreStarting?.Invoke(); + + public async Task RunAsync(CancellationToken token) + { + cache.RevalidationStarting?.Invoke(); + var result = (await generator(state, _context, token).ConfigureAwait(false)).ValidateContext(_context.Identity); + Expiration = result.Expiration; + SkipFailSafe = result.SkipFailSafe; + NotModified = result.IsNotModified; + if (NotModified) + { + cache.TrackNotModified(KindRehydrate); + Metadata = EntryValidators.From(_context.ETag, _context.LastModified); + return _context.PreviousValue; + } + + Metadata = EntryValidators.From(result.ETag, result.LastModified); + return result.Value; + } + } + + /// One miss of a revalidation call: builds the generator's context from the kept value when the generator runs. + private sealed class RevalidationRun(MultilayerCache cache, CacheKey cacheKey, CachePolicy policy, TState state, Func, CancellationToken, Task>> generator) + { + /// + /// A NotModified carries the attempt that supplied the kept value. If that value is gone, ask again with an empty context. + /// + public async Task> InvokeAsync(CancellationToken token) + { + cache.RevalidationStarting?.Invoke(); + Confirmation? attempt = null; + var context = default(RevalidationContext); + if (cache.TryGetStale(cacheKey.Name, policy, out var kept, out var entry)) + { + attempt = new Confirmation(kept, this); + var validators = EntryValidators.OfEntry(entry); + context = new RevalidationContext(entry.Value, validators?.ETag, validators?.LastModified, attempt); + } + + var result = (await generator(state, context, token).ConfigureAwait(false)).ValidateContext(context.Identity); + if (!result.IsNotModified) + { + return result; + } + + cache.TrackNotModified(); + if (attempt is not null && cache.StillKept(cacheKey.Name, attempt.Kept)) + { + return result; + } + + return await GenerateEmptyAsync(token).ConfigureAwait(false); + } + + private Task> RegenerateAsync(CancellationToken token) => + FactoryTimeout.RunAsync(this, static (r, ct) => r.GenerateEmptyAsync(ct), policy.FactoryTimeout, cacheKey, cache.Name, cache.Telemetry, token, clock: cache._clock); + + private async Task> GenerateEmptyAsync(CancellationToken token) => + (await generator(state, default, token).ConfigureAwait(false)).ValidateContext(null); + + // A joiner can reuse its run after a fallback is overtaken. The confirmation and its store guard belong to this attempt. + private sealed class Confirmation(StaleValue kept, RevalidationRun run) : IConfirmedRun + { + public StaleValue Kept { get; } = kept; + + public Task> RegenerateAsync(CancellationToken token) => run.RegenerateAsync(token); + } + } +} diff --git a/src/UiPath.Caching/MultilayerCache.SafeFill.cs b/src/UiPath.Caching/MultilayerCache.SafeFill.cs index ef23e57a1..c4adb35a8 100644 --- a/src/UiPath.Caching/MultilayerCache.SafeFill.cs +++ b/src/UiPath.Caching/MultilayerCache.SafeFill.cs @@ -6,7 +6,7 @@ private static long BatchToken(Dictionary watched, string name) => watched.TryGetValue(name, out var token) ? token : BackgroundWrites.Untracked; /// Listens for peers' writes of the key and watches it for changes until ; none with no inner tier to fill. - private GenerationScope BeginFill(CacheEntryOptions options, GenerationScope scope, bool localOnly) + private GenerationScope BeginFill(CacheEntryOptions options, GenerationScope scope, bool localOnly, bool independentTiming = false) { if (localOnly || !_sharedInner) { @@ -14,7 +14,7 @@ private GenerationScope BeginFill(CacheEntryOptions options, GenerationScope sco } MarkInnerRead(options.CacheKey.Name, options.TopicKey); - return scope with { Fill = _background.BeginFill(options.CacheKey.Name, _fencedInner) }; + return scope with { Fill = _background.BeginFill(options.CacheKey.Name, _fencedInner, independentTiming) }; } private void EndFill(string name, in GenerationScope scope) => EndFill(name, scope.Fill); @@ -23,7 +23,7 @@ private void EndFill(string name, long fill) { if (fill != BackgroundWrites.Untracked) { - _background.EndFill(name); + _background.EndFill(name, fill); } } @@ -146,7 +146,7 @@ private Filled KeepFilled(FillArgs s, FillResult filled, BackgroundW case FillOutcome.Removed: // Removed while the generator ran: the value is returned, and no node keeps it. _background.FillSuperseded(); - return default; + return new Filled(null, false) { Removed = true }; default: // As a refused write is kept: for the disconnected cap, unless the caller left. if (!s.Options.Token.IsCancellationRequested) @@ -383,5 +383,8 @@ private bool RemoveHeld(string name) private readonly record struct FillArgs(MultilayerCache Cache, CacheEntryOptions Options, T? Value, CachePolicy Policy, ICacheEntry? Entry, long Fill); - private readonly record struct Filled(ICacheEntry? Adopted, bool Won); + private readonly record struct Filled(ICacheEntry? Adopted, bool Won) + { + public bool Removed { get; init; } + } } diff --git a/src/UiPath.Caching/MultilayerCache.Write.cs b/src/UiPath.Caching/MultilayerCache.Write.cs index ea442f57c..5050cd599 100644 --- a/src/UiPath.Caching/MultilayerCache.Write.cs +++ b/src/UiPath.Caching/MultilayerCache.Write.cs @@ -537,7 +537,7 @@ private bool MemorySet(CacheEntryOptions options, T value, TimeSpan? maxExpir return false; } - item ??= _cacheEntryFactory.Create(value, options.Expiration); + item ??= EntryValidators.CreateEntry(_cacheEntryFactory, value, options.Expiration, options.Metadata as EntryValidators); var target = RefreshTarget(RefreshReader.Instance, policy, item); Track(item, target is not null); if (target is not null && read) diff --git a/src/UiPath.Caching/MultilayerCache.cs b/src/UiPath.Caching/MultilayerCache.cs index 838f17cd8..ccdd8577b 100644 --- a/src/UiPath.Caching/MultilayerCache.cs +++ b/src/UiPath.Caching/MultilayerCache.cs @@ -3,7 +3,7 @@ namespace UiPath.Caching; -internal sealed partial class MultilayerCache : MultilayerCacheBase, ICache, ISpanKeyCache, IResultCache, IMigrationCache +internal sealed partial class MultilayerCache : MultilayerCacheBase, ICache, ISpanKeyCache, IResultCache, IMigrationCache, IRevalidatingCache { private readonly ICache _innerCache; diff --git a/src/UiPath.Caching/MultilayerCacheBase.LayeredEntry.cs b/src/UiPath.Caching/MultilayerCacheBase.LayeredEntry.cs index 707609159..3c5e2f734 100644 --- a/src/UiPath.Caching/MultilayerCacheBase.LayeredEntry.cs +++ b/src/UiPath.Caching/MultilayerCacheBase.LayeredEntry.cs @@ -1,3 +1,5 @@ +using System.Runtime.CompilerServices; + namespace UiPath.Caching; public abstract partial class MultilayerCacheBase @@ -32,7 +34,6 @@ public bool ShouldRehydrate(TValue? currentValue, CachePolicy policy, TimeSpan d /// Hands the rehydration to the coordinator; apart from so its early returns do not allocate the closure. public void TriggerRehydrate(CacheKey originalCacheKey, DateTimeOffset entryExpiration, Func> generator, CachePolicy policy, TimeSpan duration, TimeSpan? rehydrateJitter) { - // A struct's lambda cannot capture its own members. var flow = this; cache._rehydrator.TryTrigger( originalCacheKey, @@ -44,6 +45,20 @@ public void TriggerRehydrate(CacheKey originalCacheKey, DateTimeOffset entryExpi entryType: shape.EntryType); } + public void TriggerRehydrate(CacheKey originalCacheKey, DateTimeOffset entryExpiration, Func> generator, CachePolicy policy, TimeSpan duration, TimeSpan? rehydrateJitter, RehydrateOverride shaped) + { + // A struct's lambda cannot capture its own members. + var flow = this; + cache._rehydrator.TryTrigger( + originalCacheKey, + entryExpiration, + policy, + duration, + kind: shape.Kind, + rehydrateAsync: (run, ct) => flow.RehydrateAsync(originalCacheKey, entryExpiration, generator, policy, duration, rehydrateJitter, run, ct, shaped), + entryType: shape.EntryType); + } + /// Reads the inner tier and keeps a hit locally; concurrent reads of one key share one inner read. The null inner tier has nothing to share or keep. public ValueTask> FetchInnerAsync(TOptions options, CachePolicy policy) => shape.InnerIsNull @@ -188,36 +203,39 @@ private bool Keep(TOptions options, CachePolicy policy, ICacheEntry fetc return FillFromInnerRead(options, mark, shape.Present(fetched.Value), policy); } - private async ValueTask RehydrateAsync(CacheKey originalCacheKey, DateTimeOffset entryExpiration, Func> generator, CachePolicy policy, TimeSpan duration, TimeSpan? rehydrateJitter, RehydrateRun run, CancellationToken ct) + private async ValueTask RehydrateAsync(CacheKey originalCacheKey, DateTimeOffset entryExpiration, Func> generator, CachePolicy policy, TimeSpan duration, TimeSpan? rehydrateJitter, RehydrateRun run, CancellationToken ct, RehydrateOverride? shaped = null) { // What the adoption read saw, so the store below can refuse to overwrite a write that landed while the generator ran. var stamp = new StampBox(); - if (await TryAdoptInnerAsync(originalCacheKey, entryExpiration, policy, duration, run, stamp, ct).ConfigureAwait(false)) + var adoption = shaped is null ? null : new StrongBox<(bool Local, ICacheEntry? Entry)>(); + if (await TryAdoptInnerAsync(originalCacheKey, entryExpiration, policy, duration, run, stamp, ct, adoption).ConfigureAwait(false)) { return; } + var stamped = shaped is not null && SetRehydrateSource(shaped, adoption!.Value, stamp, policy); + var newValue = await generator(ct).ConfigureAwait(false); var empty = shape.IsEmpty(newValue); if (empty && !cache._multiLayerCacheOptions.CacheNullValues) { return; } - // Factory transitions to empty: preserve the original deadline so the marker doesn't get a fresh TTL window. - var rehydrateExpiration = empty - ? entryExpiration - : cache._clock.ToDateTimeOffset(ApplyJitter(duration, rehydrateJitter)); + var rehydrateExpiration = RehydrateExpiration(entryExpiration, policy, duration, rehydrateJitter, empty, shaped); var rehydrateOptions = shape.BuildOptions(originalCacheKey, rehydrateExpiration, ct); - var disconnected = cache.GetInnerCacheDisconnected(); - // An adoption read that failed or timed out saw nothing to compare against: the value then fills only an absent key. - if (!disconnected && shape.CanStamp && shape.CanAdopt && !shape.InnerIsNull && !stamp.TryGet(out _)) + if (shaped is not null) { - stamp.Record(null); + var validators = EntryValidators.Of(shaped.Metadata); + var lifetime = rehydrateExpiration == DateTimeOffset.MaxValue ? (TimeSpan?)null : rehydrateExpiration - cache._clock.GetUtcNow(); + rehydrateOptions.Metadata = EntryValidators.From(validators?.ETag, validators?.LastModified, lifetime); + policy = shaped.SkipFailSafe ? WithoutFailSafe(policy) : policy; } - var stored = !disconnected && shape.CanStamp && stamp.TryGet(out _) - ? await StoreIfUnchangedAsync(originalCacheKey, entryExpiration, rehydrateOptions, shape.Present(newValue), policy, duration, run, stamp, ct).ConfigureAwait(false) - : await StoreAsync(rehydrateOptions, shape.Present(newValue), disconnected, policy).ConfigureAwait(false); + var value = shape.Present(newValue); + var confirmStamp = stamped ? stamp : null; + var stored = shaped?.NotModified == true + ? await StoreConfirmedAsync(originalCacheKey, entryExpiration, rehydrateOptions, value, policy, duration, run, confirmStamp, shaped, ct).ConfigureAwait(false) + : await StoreRehydratedAsync(originalCacheKey, entryExpiration, rehydrateOptions, value, policy, duration, run, stamp, ct).ConfigureAwait(false); if (!stored) { // A run timeout that ended the store is the coordinator's to report, not a write failure. @@ -226,6 +244,80 @@ private async ValueTask RehydrateAsync(CacheKey originalCacheKey, DateTimeOffset } } + private DateTimeOffset RehydrateExpiration(DateTimeOffset entryExpiration, CachePolicy policy, TimeSpan duration, TimeSpan? jitter, bool empty, RehydrateOverride? shaped) + { + // A transition to empty preserves the original deadline. A confirmation renews the observed entry. + if (empty && shaped?.NotModified != true) + { + return entryExpiration; + } + + var lifetime = shaped is null ? duration : cache.ResolveDuration(policy); + return shaped?.Expiration ?? cache._clock.ToDateTimeOffset(ApplyJitter(lifetime, jitter)); + } + + private ValueTask StoreRehydratedAsync(CacheKey originalCacheKey, DateTimeOffset entryExpiration, TOptions options, TValue value, CachePolicy policy, TimeSpan duration, RehydrateRun run, StampBox stamp, CancellationToken ct) + { + var disconnected = cache.GetInnerCacheDisconnected(); + // An adoption read that failed or timed out saw nothing to compare against: the value then fills only an absent key. + if (!disconnected && shape.CanStamp && shape.CanAdopt && !shape.InnerIsNull && !stamp.TryGet(out _)) + { + stamp.Record(null); + } + + return !disconnected && shape.CanStamp && stamp.TryGet(out _) + ? StoreIfUnchangedAsync(originalCacheKey, entryExpiration, options, value, policy, duration, run, stamp, ct) + : StoreAsync(options, value, disconnected, policy); + } + + private bool SetRehydrateSource(RehydrateOverride shaped, (bool Local, ICacheEntry? Entry) adoption, StampBox stamp, CachePolicy policy) + { + if (adoption.Local) + { + // Start taking local turns before the generator can overlap a write or removal. + cache._background.Track(); + shaped.Saw(RehydrateSource.Local, null, null, null, policy); + return false; + } + + if (adoption.Entry is { Found: true } seen && shape.StampedTier is { } tier && stamp.TryGet(out var held) && held is not null) + { + shaped.Saw(RehydrateSource.Stamped, seen, held, tier, policy); + return true; + } + + shaped.Saw(RehydrateSource.None, null, null, null, policy); + return false; + } + + private ValueTask StoreConfirmedAsync(CacheKey originalCacheKey, DateTimeOffset entryExpiration, TOptions options, TValue value, CachePolicy policy, TimeSpan duration, RehydrateRun run, StampBox? stamp, RehydrateOverride shaped, CancellationToken ct) + { + shaped.BeforeConfirmedStore(); + ct.ThrowIfCancellationRequested(); + if (shaped.LocalEntry is { } local) + { + var disconnected = !shape.InnerIsNull || cache.GetInnerCacheDisconnected(); + var max = disconnected ? cache.DisconnectedLifetime(policy) : cache.ConnectedLifetime(policy); + var current = false; + var stored = cache.ApplyLocal(options.CacheKey.Name, + (Cache: cache, Shape: shape, Options: options, Value: value, Policy: policy, Max: max, Local: local, Disconnected: disconnected), + s => + { + current = s.Cache.IsLocalEntry(s.Options.CacheKey.Name, s.Local); + return !current || (s.Disconnected + ? s.Shape.KeepWhileDisconnected(s.Options, s.Value, s.Max, null, s.Policy) + : s.Shape.KeepLocal(s.Options, s.Value, s.Max, s.Policy)); + }); + return current && stored && !disconnected + ? PublishSetAsync(options) + : new ValueTask(stored); + } + + return stamp is not null + ? StoreIfUnchangedAsync(originalCacheKey, entryExpiration, options, value, policy, duration, run, stamp, ct, again: true) + : new ValueTask(true); + } + /// Writes the value over what the adoption read saw; when a write has landed since, that one stands and is kept here instead, and nothing is announced. private async ValueTask StoreIfUnchangedAsync(CacheKey originalCacheKey, DateTimeOffset entryExpiration, TOptions options, TValue value, CachePolicy policy, TimeSpan duration, RehydrateRun run, StampBox stamp, CancellationToken ct, bool again = false) { @@ -256,9 +348,19 @@ private async ValueTask StoreIfUnchangedAsync(CacheKey originalCacheKey, D } /// Keeps the inner tier's copy when another node already refreshed it, so the generator is not run again; true only when the copy was kept. - private async ValueTask TryAdoptInnerAsync(CacheKey originalCacheKey, DateTimeOffset entryExpiration, CachePolicy policy, TimeSpan duration, RehydrateRun run, StampBox stamp, CancellationToken ct) + private async ValueTask TryAdoptInnerAsync(CacheKey originalCacheKey, DateTimeOffset entryExpiration, CachePolicy policy, TimeSpan duration, RehydrateRun run, StampBox stamp, CancellationToken ct, StrongBox<(bool Local, ICacheEntry? Entry)>? adoption = null) { - if (shape.InnerIsNull || !shape.CanAdopt || cache.GetInnerCacheDisconnected()) + if (shape.InnerIsNull || cache.GetInnerCacheDisconnected()) + { + if (adoption is not null) + { + adoption.Value = (true, null); + } + + return false; + } + + if (!shape.CanAdopt) { return false; } @@ -282,22 +384,16 @@ private async ValueTask TryAdoptInnerAsync(CacheKey originalCacheKey, Date { await read.CancelAsync().ConfigureAwait(false); reading?.Observe(); - var timedOut = ex is TimeoutException or OperationCanceledException; - var logged = LoggedKey.For(cache._masker, originalCacheKey, shape.EntryType); - if (timedOut) - { - cache.LogRehydrateInnerReadTimedOut(logged); - } - else - { - cache.LogRehydrateInnerReadFailed(ex, logged); - } - - cache._rehydrator.TrackAdoptReadFailed(rehydrate, shape.Kind, originalCacheKey, timedOut ? "timeout" : "error"); + ReportAdoptReadFailed(ex, originalCacheKey, rehydrate); return false; } ct.ThrowIfCancellationRequested(); + if (adoption is not null) + { + adoption.Value = (false, fetched); + } + if (!fetched.Found || !InnerCopyFreshEnough(fetched.Expiration, cache._clock.GetUtcNow(), rehydrate.Threshold, duration)) { return false; @@ -319,5 +415,21 @@ private async ValueTask TryAdoptInnerAsync(CacheKey originalCacheKey, Date run.Adopt(originalCacheKey); return true; } + + private void ReportAdoptReadFailed(Exception ex, CacheKey originalCacheKey, RehydrateOptions rehydrate) + { + var timedOut = ex is TimeoutException or OperationCanceledException; + var logged = LoggedKey.For(cache._masker, originalCacheKey, shape.EntryType); + if (timedOut) + { + cache.LogRehydrateInnerReadTimedOut(logged); + } + else + { + cache.LogRehydrateInnerReadFailed(ex, logged); + } + + cache._rehydrator.TrackAdoptReadFailed(rehydrate, shape.Kind, originalCacheKey, timedOut ? "timeout" : "error"); + } } } diff --git a/src/UiPath.Caching/MultilayerCacheBase.cs b/src/UiPath.Caching/MultilayerCacheBase.cs index 731891d23..2bad30adf 100644 --- a/src/UiPath.Caching/MultilayerCacheBase.cs +++ b/src/UiPath.Caching/MultilayerCacheBase.cs @@ -52,6 +52,7 @@ public abstract partial class MultilayerCacheBase : IDisposable DistributedLockSkipReread = false, }, }; + private static readonly ConditionalWeakTable FailSafeOff = []; private readonly PeerWriteGuard? _peerWrites; private readonly IDistributedLock _distributedLock; private readonly IDistributedLockKeyStrategy _lockKeyStrategy; @@ -295,6 +296,9 @@ private protected static void LinkRefresh(object? from, object? to) } } + private protected static CachePolicy WithoutFailSafe(CachePolicy policy) => + policy.FailSafeEnabled != true ? policy : FailSafeOff.GetValue(policy, static p => CachePolicyMerger.Merge(new CachePolicy { FailSafeEnabled = false }, p)); + /// A timeout a cancellation source takes: CancelAfter throws beyond milliseconds, so a misconfigured Lock.LocalSingleFlightTimeout degrades to that. private protected static TimeSpan BoundedTimeout(TimeSpan timeout) => timeout.TotalMilliseconds > int.MaxValue ? TimeSpan.FromMilliseconds(int.MaxValue) : timeout; @@ -495,7 +499,7 @@ private protected bool TryGetCooling(string name, CachePolicy policy, [NotNul /// Returns the key's fail-safe value in place of a generation, and starts its cooldown. /// The generator's own answer when fail-safe stopped waiting for it, for a joined caller that did not opt in. - private protected ICacheEntry ServeStale(LoggedKey key, StaleValue value, ICacheEntry entry, CachePolicy policy, string reason, Exception? failure, Task>? late = null) + private protected ICacheEntry ServeStale(LoggedKey key, StaleValue value, ICacheEntry entry, CachePolicy policy, string reason, Exception? failure, Task?>? late = null) { value.Cool(_clock, policy.FailSafeCooldown ?? StaleValues.DefaultCooldown); Telemetry.TryTrackEvent(FailSafeServedEvent, [new(FailSafeTagCache, Name), new(FailSafeTagReason, reason)]); diff --git a/src/UiPath.Caching/MultilayerHashCache.Layered.cs b/src/UiPath.Caching/MultilayerHashCache.Layered.cs index 9366a299f..3e9eb4976 100644 --- a/src/UiPath.Caching/MultilayerHashCache.Layered.cs +++ b/src/UiPath.Caching/MultilayerHashCache.Layered.cs @@ -16,6 +16,8 @@ private readonly struct HashShape(MultilayerHashCache cache) : ILayeredShape< public bool CanStamp => false; + public IStampedTier? StampedTier => null; + public bool IsEmpty(IDictionary? value) => IsNullOrEmpty(value); public IDictionary Present(IDictionary? value) => value ?? Empty(); diff --git a/src/UiPath.Caching/Redis/RedisCache.Stamped.cs b/src/UiPath.Caching/Redis/RedisCache.Stamped.cs index d0b8682a8..d8b748db2 100644 --- a/src/UiPath.Caching/Redis/RedisCache.Stamped.cs +++ b/src/UiPath.Caching/Redis/RedisCache.Stamped.cs @@ -25,6 +25,37 @@ public ValueTask WriteIfStampAsync(CacheKey cacheKey, T? value, : WriteIfStampCoreAsync(cacheKey, redisKey, value, expiration, expected, format, token); } + public bool Holds(object? stamp, T? value, CachePolicy? policy) + { + if (stamp is not RedisValue expected || expected.IsNull) + { + return false; + } + + try + { + if (IsDefault(value)) + { + return expected == RedisValue.EmptyString; + } + + var format = FormatFor(policy, forWrite: true, alsoReads: true); + var (serialized, payload) = format.IsDefault + ? SerializeValue(value, default(PlainFormat)) + : SerializeValue(value, format); + using (payload) + { + ReadOnlyMemory held = expected; + ReadOnlyMemory candidate = serialized; + return held.Span.SequenceEqual(candidate.Span); + } + } + catch (Exception) + { + return false; + } + } + private async ValueTask<(SnapshotRead Snapshot, object? Stamp)> ReadStampedCoreAsync(CacheKey cacheKey, TFormat format, CancellationToken token) where TFormat : struct, IValueFormat { diff --git a/src/UiPath.Caching/RehydrateOverride.cs b/src/UiPath.Caching/RehydrateOverride.cs new file mode 100644 index 000000000..56a033a52 --- /dev/null +++ b/src/UiPath.Caching/RehydrateOverride.cs @@ -0,0 +1,18 @@ +namespace UiPath.Caching; + +internal abstract class RehydrateOverride +{ + public DateTimeOffset? Expiration { get; set; } + + public IDictionary? Metadata { get; set; } + + public bool SkipFailSafe { get; set; } + + public bool NotModified { get; set; } + + public ICacheEntry? LocalEntry { get; protected set; } + + public abstract void Saw(RehydrateSource source, ICacheEntry? seen, object? stamp, IStampedTier? tier, CachePolicy policy); + + public abstract void BeforeConfirmedStore(); +} diff --git a/src/UiPath.Caching/RehydrateSource.cs b/src/UiPath.Caching/RehydrateSource.cs new file mode 100644 index 000000000..7bbb39bb2 --- /dev/null +++ b/src/UiPath.Caching/RehydrateSource.cs @@ -0,0 +1,8 @@ +namespace UiPath.Caching; + +internal enum RehydrateSource +{ + None, + Local, + Stamped, +} diff --git a/src/UiPath.Caching/RehydrationCoordinator.cs b/src/UiPath.Caching/RehydrationCoordinator.cs index b20f82a0a..347f5db36 100644 --- a/src/UiPath.Caching/RehydrationCoordinator.cs +++ b/src/UiPath.Caching/RehydrationCoordinator.cs @@ -61,6 +61,11 @@ public bool TryTrigger( entryType, out _); + public bool PastThreshold(DateTimeOffset entryExpiration, CachePolicy? policy, TimeSpan duration) => + policy is { RehydrateEnabled: true, Rehydrate: { } rehydrate } + && duration > TimeSpan.Zero + && PastThreshold(entryExpiration, rehydrate.Threshold, duration); + public bool TryTriggerBatch( IReadOnlyList<(CacheKey Key, DateTimeOffset Expiration)> candidates, CachePolicy? policy, @@ -144,6 +149,18 @@ private static TimeSpan ComputeCooldown(TimeSpan baseCooldown, TimeSpan maxCoold return TimeSpan.FromTicks(Math.Min(product, maxCooldown.Ticks)); } + private bool PastThreshold(DateTimeOffset entryExpiration, double threshold, TimeSpan duration) + { + var remaining = entryExpiration - clock.GetUtcNow(); + if (remaining <= TimeSpan.Zero) + { + return false; + } + + var elapsedFraction = (duration - remaining).TotalMilliseconds / duration.TotalMilliseconds; + return !(elapsedFraction < threshold); + } + /// Reserves the candidates past that this coordinator can claim. private List ReserveKeysPastThreshold( IReadOnlyList<(CacheKey Key, DateTimeOffset Expiration)> candidates, @@ -153,13 +170,7 @@ private List ReserveKeysPastThreshold( var reserved = new List(candidates.Count); foreach (var (key, entryExpiration) in candidates) { - var remaining = entryExpiration - clock.GetUtcNow(); - if (remaining <= TimeSpan.Zero) - { - continue; - } - var elapsedFraction = (duration - remaining).TotalMilliseconds / duration.TotalMilliseconds; - if (elapsedFraction < threshold) + if (!PastThreshold(entryExpiration, threshold, duration)) { continue; } diff --git a/src/UiPath.Caching/StaleEntry.cs b/src/UiPath.Caching/StaleEntry.cs index b9f686007..5517c74a9 100644 --- a/src/UiPath.Caching/StaleEntry.cs +++ b/src/UiPath.Caching/StaleEntry.cs @@ -5,7 +5,7 @@ namespace UiPath.Caching; /// A value fail-safe returned in place of a generation: never stored, and reported as not generated and with no live expiration. /// The generator's error, when fail-safe answered it. /// The generator's own answer, when fail-safe stopped waiting for it. -internal sealed class StaleEntry(StaleValue value, ICacheEntry kept, Exception? failure = null, Task>? late = null) : ICacheEntry, IStaleEntry +internal sealed class StaleEntry(StaleValue value, ICacheEntry kept, Exception? failure = null, Task?>? late = null) : ICacheEntry, IStaleEntry { public T? Value => kept.Value; @@ -29,6 +29,7 @@ internal sealed class StaleEntry(StaleValue value, ICacheEntry kept, Exce ExceptionDispatchInfo.Throw(failure); } - return late is null ? kept : await late.WaitAsync(token).ConfigureAwait(false); + // A discarded confirmation leaves this caller to take another run. + return late is null ? kept : await late.WaitAsync(token).ConfigureAwait(false) ?? throw new InFlightAbandonedException(); } } diff --git a/tests/UiPath.Caching.Analyzers.Tests/CapturingGeneratorTests.cs b/tests/UiPath.Caching.Analyzers.Tests/CapturingGeneratorTests.cs index cfa34a66e..af6f4a90d 100644 --- a/tests/UiPath.Caching.Analyzers.Tests/CapturingGeneratorTests.cs +++ b/tests/UiPath.Caching.Analyzers.Tests/CapturingGeneratorTests.cs @@ -98,6 +98,13 @@ public Task Instance_method_group_of_a_field_passes_the_field() => Fixture.Service("""ValueTask Get(CancellationToken token) => _cache.GetOrAddAsync("k", _repo, static (repo, ct) => repo.LoadAsync(ct), token);"""), Verify.Diagnostic(0, "is the instance method group 'LoadAsync' and allocates a delegate", "pass its target as state and call it from a static lambda")); + [Fact] + public Task A_capturing_revalidation_lambda_is_reported() => + Verify.FixAsync( + Fixture.Service("""ValueTask Get(int id) => _untyped.GetOrRevalidateAsync("k", {|#0:async (context, ct) => context.Modified(await LoadAsync(id, ct))|}, _policy);"""), + Fixture.Service("""ValueTask Get(int id) => _untyped.GetOrRevalidateAsync("k", (Self: this, Id: id), static async (s, context, ct) => context.Modified(await s.Self.LoadAsync(s.Id, ct)), _policy);"""), + Verify.Diagnostic(0, "captures 'this' and 'id' and allocates a closure", PassThem)); + [Fact] public Task Static_lambda_is_not_reported() => Verify.NoDiagnosticAsync(Fixture.Service("""ValueTask Get(CancellationToken token) => _cache.GetOrAddAsync("k", this, static (self, ct) => self.LoadAsync(ct), token);""")); diff --git a/tests/UiPath.Caching.Analyzers.Tests/FixSafetyTests.cs b/tests/UiPath.Caching.Analyzers.Tests/FixSafetyTests.cs index 601b8125f..a1781662a 100644 --- a/tests/UiPath.Caching.Analyzers.Tests/FixSafetyTests.cs +++ b/tests/UiPath.Caching.Analyzers.Tests/FixSafetyTests.cs @@ -60,6 +60,13 @@ public Task Anonymous_method_without_parameters_gets_distinct_names() => Fixture.Service("""ValueTask[]> Get(CancellationToken token) => _cache.GetOrAddAsync(_entries, this, static (self, arg, ct) => { return self.LoadManyAsync(new[] { self._offset }, CancellationToken.None); }, token);"""), Verify.Diagnostic(0, "captures 'this' and allocates a delegate", "pass it as the argument and make the lambda static")); + [Fact] + public Task The_fix_keeps_the_context_parameter() => + Verify.FixAsync( + Fixture.Service("""ValueTask Get(int id, CancellationToken token) => _cache.GetOrRevalidateAsync("k", {|#0:async (context, ct) => context.Modified(await LoadStaticAsync(id, ct))|}, token);"""), + Fixture.Service("""ValueTask Get(int id, CancellationToken token) => _cache.GetOrRevalidateAsync("k", id, static async (id, context, ct) => context.Modified(await LoadStaticAsync(id, ct)), token);"""), + Verify.Diagnostic(0, "captures 'id' and allocates a closure", PassIt)); + [Fact] public Task Method_group_on_a_possibly_null_target_gets_no_fix() { diff --git a/tests/UiPath.Caching.Analyzers.Tests/GetOrAddOverloadBindingTests.cs b/tests/UiPath.Caching.Analyzers.Tests/GetOrAddOverloadBindingTests.cs new file mode 100644 index 000000000..54dd91229 --- /dev/null +++ b/tests/UiPath.Caching.Analyzers.Tests/GetOrAddOverloadBindingTests.cs @@ -0,0 +1,82 @@ +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Xunit; + +namespace UiPath.Caching.Analyzers.Tests; + +public sealed class GetOrAddOverloadBindingTests +{ + private const string Source = """ + using System; + using System.Threading; + using System.Threading.Tasks; + using UiPath.Caching; + + public static class Caller + { + public static async Task RunAsync(ICache cache, ICache typed, CacheKey key, string id, CancellationToken ct) + { + await typed.GetOrAddAsync(key, async delegate { await Task.Yield(); return default; }, ct); + await typed.GetOrAddAsync(key, id, async delegate { await Task.Yield(); return default; }, ct); + await cache.GetOrAddAsync(key, async delegate { await Task.Yield(); return default; }, policy: null); + await cache.GetOrAddAsync(key, id, async delegate { await Task.Yield(); return default; }, policy: null); + await cache.GetOrAddAsync(key, delegate { throw new InvalidOperationException(); }); + await cache.GetOrAddAsync($"key:{id}", async delegate { await Task.Yield(); return default; }); + await cache.GetOrAddAsync($"key:{id}", LoadAsync, TimeSpan.FromMinutes(1), policy: null, token: ct); + await cache.GetOrAddAsync(key, static token => Task.FromResult(null), token: ct); + await cache.GetOrAddAsync(key, id, static (state, token) => Task.FromResult(state), token: ct); + await typed.GetOrAddAsync($"key:{id}", LoadAsync, TimeSpan.FromMinutes(1), ct); + await typed.GetOrAddAsync($"key:{id}", id, static (state, token) => Task.FromResult(state), ct); + await typed.GetOrAddAsync(key, static token => Task.FromResult(null), ct); + } + + private static Task LoadAsync(CancellationToken token) => Task.FromResult(null); + } + """; + + // Original method definitions captured on origin/main, in source order. + private static readonly string[] OriginMainTargets = + [ + "UiPath.Caching.ICache.GetOrAddAsync(UiPath.Caching.CacheKey, System.Func>, System.Threading.CancellationToken)", + "UiPath.Caching.ICache.GetOrAddAsync(UiPath.Caching.CacheKey, TState, System.Func>, System.Threading.CancellationToken)", + "UiPath.Caching.ICache.GetOrAddAsync(UiPath.Caching.CacheKey, System.Func>, UiPath.Caching.CachePolicy?, System.Threading.CancellationToken)", + "UiPath.Caching.ICache.GetOrAddAsync(UiPath.Caching.CacheKey, TState, System.Func>, UiPath.Caching.CachePolicy?, System.Threading.CancellationToken)", + "UiPath.Caching.CacheExtensions.GetOrAddAsync(UiPath.Caching.ICache, UiPath.Caching.CacheKey, System.Func>, System.Threading.CancellationToken)", + "UiPath.Caching.CacheExtensions.GetOrAddAsync(UiPath.Caching.ICache, UiPath.Caching.CacheKey, System.Func>, System.Threading.CancellationToken)", + "UiPath.Caching.ICache.GetOrAddAsync(ref UiPath.Caching.CacheKeyHandler, System.Func>, System.TimeSpan, UiPath.Caching.CachePolicy?, System.Threading.CancellationToken)", + "UiPath.Caching.CacheExtensions.GetOrAddAsync(UiPath.Caching.ICache, UiPath.Caching.CacheKey, System.Func>, System.Threading.CancellationToken)", + "UiPath.Caching.StatefulCacheExtensions.GetOrAddAsync(UiPath.Caching.ICache, UiPath.Caching.CacheKey, TState, System.Func>, System.Threading.CancellationToken)", + "UiPath.Caching.ICache.GetOrAddAsync(ref UiPath.Caching.CacheKeyHandler, System.Func>, System.TimeSpan, System.Threading.CancellationToken)", + "UiPath.Caching.ICache.GetOrAddAsync(ref UiPath.Caching.CacheKeyHandler, TState, System.Func>, System.Threading.CancellationToken)", + "UiPath.Caching.ICache.GetOrAddAsync(UiPath.Caching.CacheKey, System.Func>, System.Threading.CancellationToken)", + ]; + + [Theory] + [InlineData(LanguageVersion.CSharp12)] + [InlineData(LanguageVersion.CSharp13)] + public void Existing_GetOrAddAsync_calls_keep_their_overloads(LanguageVersion version) + { + var token = TestContext.Current.CancellationToken; + var tree = CSharpSyntaxTree.ParseText(Source, new CSharpParseOptions(version), cancellationToken: token); + var compilation = CSharpCompilation.Create( + "GetOrAddBindings", + [tree], + Verify.RuntimeReferences, + new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, nullableContextOptions: NullableContextOptions.Enable)); + Assert.Empty(compilation.GetDiagnostics(token).Where(diagnostic => diagnostic.Severity == DiagnosticSeverity.Error)); + + var model = compilation.GetSemanticModel(tree); + var targets = tree.GetRoot(token).DescendantNodes().OfType() + .Where(call => call.Expression is MemberAccessExpressionSyntax { Name.Identifier.ValueText: "GetOrAddAsync" }) + .Select(call => Describe(model.GetSymbolInfo(call, token).Symbol)); + + Assert.Equal(OriginMainTargets, targets); + } + + private static string Describe(ISymbol? symbol) + { + var method = Assert.IsType(symbol, exactMatch: false); + return (method.ReducedFrom ?? method).OriginalDefinition.ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageFormat); + } +} diff --git a/tests/UiPath.Caching.Analyzers.Tests/StateSiblingTests.cs b/tests/UiPath.Caching.Analyzers.Tests/StateSiblingTests.cs index 5efd742fc..7e42bbe37 100644 --- a/tests/UiPath.Caching.Analyzers.Tests/StateSiblingTests.cs +++ b/tests/UiPath.Caching.Analyzers.Tests/StateSiblingTests.cs @@ -42,6 +42,23 @@ public void A_lookup_for_another_parameter_does_not_answer_for_the_generator() Assert.NotNull(methods.StateSibling(closure, generatorOrdinal: 1)); } + [Theory] + [InlineData("UiPath.Caching.ICache")] + [InlineData("UiPath.Caching.ICache`1")] + public void The_state_sibling_of_GetOrRevalidateAsync_is_found(string cacheType) + { + var compilation = CSharpCompilation.Create("revalidate", [], Verify.RuntimeReferences, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); + var closure = compilation.GetTypeByMetadataName(cacheType)!.GetMembers("GetOrRevalidateAsync").OfType() + .Single(method => method.Parameters[1].Type.Name == "Func"); + + var sibling = CacheMethods.Create(compilation)!.StateSibling(closure, generatorOrdinal: 1); + + Assert.NotNull(sibling); + Assert.Equal("state", sibling.ParameterName); + Assert.True(sibling.StateTypeIsLast); + Assert.True(sibling.IsInterfaceMember); + } + private static void AssertSibling(string members, bool onlyTheInterfaceOne) { var sibling = CacheMethods.Create(Compile(members, out var closure))!.StateSibling(closure, generatorOrdinal: 1); diff --git a/tests/UiPath.Caching.Migration.Tests/CacheDefaultMemberTests.cs b/tests/UiPath.Caching.Migration.Tests/CacheDefaultMemberTests.cs index 83c2d02d9..d9b6d12d2 100644 --- a/tests/UiPath.Caching.Migration.Tests/CacheDefaultMemberTests.cs +++ b/tests/UiPath.Caching.Migration.Tests/CacheDefaultMemberTests.cs @@ -84,6 +84,8 @@ private static Dictionary, Task>> BuildCalls() ["GetOrAddResultAsync(ref CacheKeyHandler, TState, Func>, TimeSpan, CancellationToken)"] = c => { var k = Key(); return c.GetOrAddResultAsync(ref k, 1, Made, span, Ct).AsTask(); }, ["GetOrAddWithExpirationAsync(ref CacheKeyHandler, Func>>, CancellationToken)"] = c => { var k = Key(); return c.GetOrAddWithExpirationAsync(ref k, MakeExpiring, Ct).AsTask(); }, ["GetOrAddWithExpirationAsync(ref CacheKeyHandler, TState, Func>>, CancellationToken)"] = c => { var k = Key(); return c.GetOrAddWithExpirationAsync(ref k, 1, MadeExpiring, Ct).AsTask(); }, + ["GetOrRevalidateAsync(CacheKey, Func,CancellationToken,Task>>, CancellationToken)"] = c => c.GetOrRevalidateAsync("k", static (context, _) => Task.FromResult(context.Modified(null)), Ct).AsTask(), + ["GetOrRevalidateAsync(CacheKey, TState, Func,CancellationToken,Task>>, CancellationToken)"] = c => c.GetOrRevalidateAsync("k", item, static (value, context, _) => Task.FromResult(context.Modified(value)), Ct).AsTask(), ["RefreshAsync(ref CacheKeyHandler, CancellationToken)"] = c => { var k = Key(); return c.RefreshAsync(ref k, Ct).AsTask(); }, ["RefreshAsync(ref CacheKeyHandler, DateTimeOffset, CancellationToken)"] = c => { var k = Key(); return c.RefreshAsync(ref k, at, Ct).AsTask(); }, ["RefreshAsync(ref CacheKeyHandler, TimeSpan, CancellationToken)"] = c => { var k = Key(); return c.RefreshAsync(ref k, span, Ct).AsTask(); }, diff --git a/tests/UiPath.Caching.Tests/CacheEventPublisherValidatorsTests.cs b/tests/UiPath.Caching.Tests/CacheEventPublisherValidatorsTests.cs new file mode 100644 index 000000000..ce7a8feb2 --- /dev/null +++ b/tests/UiPath.Caching.Tests/CacheEventPublisherValidatorsTests.cs @@ -0,0 +1,70 @@ +using Microsoft.Extensions.Logging.Abstractions; + +namespace UiPath.Caching.Tests; + +public class CacheEventPublisherValidatorsTests +{ + [Fact] + public async Task A_set_event_never_carries_validators() + { + var published = await PublishMetadata(EntryValidators.From("tag", null)!, PublishPeerSet); + + published.Properties.Should().NotContainKey(KnownFieldNames.PeerMetadataKey); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task A_metadata_update_event_never_carries_validators(bool viaInterface) + { + var published = await PublishMetadata( + EntryValidators.From("tag", null)!, + (publisher, options) => PublishMetadataUpdate(publisher, options, viaInterface)); + + published.Properties![KnownFieldNames.MetadataKey].Should().BeNull(); + } + + [Fact] + public async Task Other_metadata_is_published_as_before() + { + var metadata = new Dictionary { ["etag"] = "user metadata" }; + + var set = await PublishMetadata(metadata, PublishPeerSet); + var updated = await PublishMetadata(metadata, (publisher, options) => PublishMetadataUpdate(publisher, options, viaInterface: false)); + var updatedViaInterface = await PublishMetadata(metadata, (publisher, options) => PublishMetadataUpdate(publisher, options, viaInterface: true)); + + set.Properties![KnownFieldNames.PeerMetadataKey].Should().BeSameAs(metadata); + updated.Properties![KnownFieldNames.MetadataKey].Should().BeSameAs(metadata); + updatedViaInterface.Properties![KnownFieldNames.MetadataKey].Should().BeSameAs(metadata); + } + + private static ValueTask PublishPeerSet(CacheEventPublisher publisher, CacheEntryOptions options) => + publisher.CacheSetAsync(options, typeof(string), 1, new Dictionary()); + + private static ValueTask PublishMetadataUpdate(CacheEventPublisher publisher, CacheEntryOptions options, bool viaInterface) => + viaInterface ? publisher.MetadataUpdatedAsync((ICacheEntryOptions)options, typeof(string)) : publisher.MetadataUpdatedAsync(options, typeof(string)); + + private static async Task PublishMetadata( + IDictionary metadata, + Func> publish) + { + CacheEventData? published = null; + var factory = Substitute.For(); + factory.Create("cache", Arg.Any(), Arg.Do(data => published = data)) + .Returns(Substitute.For()); + var topics = Substitute.For(); + topics.Create(Arg.Any()).PublishAsync(Arg.Any(), Arg.Any()).Returns(true); + var publisher = new CacheEventPublisher("cache", topics, factory, NullLogger.Instance); + var options = new CacheEntryOptions + { + CacheKey = new CacheKey("key"), + TopicKey = "topic", + Metadata = metadata, + }; + + (await publish(publisher, options)).Should().BeTrue(); + + Assert.NotNull(published); + return published; + } +} diff --git a/tests/UiPath.Caching.Tests/EntryValidatorsTests.cs b/tests/UiPath.Caching.Tests/EntryValidatorsTests.cs new file mode 100644 index 000000000..e57a08105 --- /dev/null +++ b/tests/UiPath.Caching.Tests/EntryValidatorsTests.cs @@ -0,0 +1,91 @@ +namespace UiPath.Caching.Tests; + +public class EntryValidatorsTests +{ + [Fact] + public void It_reads_as_a_dictionary_of_the_validators_it_has() + { +#pragma warning disable CA1859 // The test reads the validators through the dictionary view callers see. + IDictionary metadata = EntryValidators.From("tag", null)!; +#pragma warning restore CA1859 + + metadata.Count.Should().Be(1); + metadata["etag"].Should().Be("tag"); + metadata.Keys.Should().Equal("etag"); + metadata.Values.Should().Equal("tag"); + Assert.Single(metadata).Should().Be(new KeyValuePair("etag", "tag")); + } + + [Fact] + public void It_refuses_changes() + { +#pragma warning disable CA1859 // The test reads the validators through the dictionary view callers see. + IDictionary metadata = EntryValidators.From("tag", null)!; +#pragma warning restore CA1859 + var pair = new KeyValuePair("etag", "other"); + + Assert.Throws(() => metadata.Add("etag", "other")); + Assert.Throws(() => { metadata["etag"] = "other"; }); + Assert.Throws(() => metadata.Remove("etag")); + Assert.Throws(metadata.Clear); + Assert.Throws(() => metadata.Add(pair)); + Assert.Throws(() => metadata.Remove(pair)); + metadata.IsReadOnly.Should().BeTrue(); + } + + [Fact] + public void From_returns_null_for_nothing() + { + EntryValidators.From(null, null).Should().BeNull(); + } + + [Fact] + public void Of_reads_the_two_keys_from_any_dictionary() + { + var metadata = new Dictionary + { + ["etag"] = "tag", + ["last-modified"] = "2030-01-02T03:04:05.0000000+02:00", + }; + + var validators = EntryValidators.Of(metadata); + + validators.Should().NotBeNull(); + validators!.ETag.Should().Be("tag"); + validators.LastModified.Should().Be(new DateTimeOffset(2030, 1, 2, 1, 4, 5, TimeSpan.Zero)); + validators["last-modified"].Should().Be("2030-01-02T01:04:05.0000000+00:00"); + EntryValidators.Of(validators).Should().BeSameAs(validators); + } + + [Fact] + public void Lifetime_can_change_without_becoming_a_dictionary_key() + { + var original = EntryValidators.From(null, null, TimeSpan.FromSeconds(10)); + + original.Should().NotBeNull(); + var updated = original!.WithLifetime(TimeSpan.FromSeconds(20)); + + original.Lifetime.Should().Be(TimeSpan.FromSeconds(10)); + updated.Lifetime.Should().Be(TimeSpan.FromSeconds(20)); + updated.Should().BeEmpty(); + } + + [Fact] + public void A_rebuilt_entry_keeps_its_validators() + { + var validators = EntryValidators.From("tag", null); + var entry = new CacheEntryFactory().Create("value", DateTimeOffset.MaxValue, validators); + + entry.NewEntry(DateTimeOffset.MinValue).Metadata.Should().BeSameAs(validators); + } + + [Fact] + public void A_rebuilt_entry_given_metadata_takes_that_metadata() + { + var validators = EntryValidators.From("tag", null); + var entry = new CacheEntryFactory().Create("value", DateTimeOffset.MaxValue, validators); + var metadata = new Dictionary { ["other"] = "value" }; + + entry.NewEntry(DateTimeOffset.MinValue, metadata).Metadata.Should().BeSameAs(metadata); + } +} diff --git a/tests/UiPath.Caching.Tests/Fakes/CachePeers.cs b/tests/UiPath.Caching.Tests/Fakes/CachePeers.cs index c3ef67abb..b73c20777 100644 --- a/tests/UiPath.Caching.Tests/Fakes/CachePeers.cs +++ b/tests/UiPath.Caching.Tests/Fakes/CachePeers.cs @@ -5,6 +5,7 @@ using Microsoft.Extensions.Primitives; using UiPath.Caching.Config; using UiPath.Caching.Locking; +using UiPath.Caching.Redis; using UiPath.Caching.Telemetry; using UiPath.Caching.Tests.Broadcast; using UiPath.Caching.Tests.Telemetry; @@ -430,6 +431,8 @@ public event EventHandler? OnReconnected /// Whether a fill of the key finds a tombstone written after its generator started. public Func? RemovedWhileLoading { get; set; } + public Func? ReadTombstone { get; set; } + bool IFencedFillTier.IsFenced => Fenced; public TestSignal Changed { get; } = new(); @@ -517,7 +520,7 @@ ValueTask> IFencedFillTier.TryFillAfterAsync(CacheKey cacheKey, where T : default { GeneratorAges.Enqueue(generatorElapsed); - return RemovedWhileLoading?.Invoke(cacheKey) == true ? new(new FillResult(FillOutcome.Removed, default)) : FillOneAsync(cacheKey, value); + return RemovedDuringFill(cacheKey, generatorElapsed) ? new(new FillResult(FillOutcome.Removed, default)) : FillOneAsync(cacheKey, value); } async ValueTask<(SnapshotRead Snapshot, object? Stamp)> IStampedTier.ReadStampedAsync(CacheKey cacheKey, CachePolicy? policy, CancellationToken token) @@ -534,6 +537,10 @@ ValueTask> IFencedFillTier.TryFillAfterAsync(CacheKey cacheKey, : (new SnapshotRead(SnapshotOutcome.Absent, null), null); } + bool IStampedTier.Holds(object? stamp, T? value, CachePolicy? policy) + where T : default => + stamp is Seen seen && Equals(seen.Value, value); + async ValueTask IStampedTier.WriteIfStampAsync(CacheKey cacheKey, T? value, DateTimeOffset expiration, CachePolicy? policy, object? stamp, CancellationToken token) where T : default { @@ -561,7 +568,7 @@ ValueTask[]> IFillManyTier.TryFillManyAsync(KeyValuePair[entries.Length]; for (var i = 0; i < entries.Length; i++) { - results[i] = RemovedWhileLoading?.Invoke(entries[i].Key) == true ? new FillResult(FillOutcome.Removed, default) : FillOneAsync(entries[i].Key, entries[i].Value).AsTask().Result; + results[i] = RemovedDuringFill(entries[i].Key, generatorElapsed) ? new FillResult(FillOutcome.Removed, default) : FillOneAsync(entries[i].Key, entries[i].Value).AsTask().Result; } return new(results); @@ -698,6 +705,11 @@ private ValueTask> FillString(CacheKey key, string? value) : new(new FillResult(FillOutcome.Added, null)); } + private bool RemovedDuringFill(CacheKey key, TimeSpan? elapsed) => + RemovedWhileLoading?.Invoke(key) == true + || (ReadTombstone?.Invoke(key) is { } tombstone + && TombstoneValue.Judge(tombstone.GraceMilliseconds, tombstone.Remaining, elapsed is { } age ? (long)Math.Ceiling(age.TotalMilliseconds) : null) != TombstoneVerdict.Replace); + private ValueTask> FillOneAsync(CacheKey key, T? value) { Interlocked.Increment(ref _fills); diff --git a/tests/UiPath.Caching.Tests/FillWatchesTests.cs b/tests/UiPath.Caching.Tests/FillWatchesTests.cs index 7ed815d78..a0486faab 100644 --- a/tests/UiPath.Caching.Tests/FillWatchesTests.cs +++ b/tests/UiPath.Caching.Tests/FillWatchesTests.cs @@ -44,6 +44,33 @@ public void Fills_of_one_key_share_a_watch_until_the_last_ends() watches.Intact("k", second).Should().BeFalse("a key nobody watches stands for no fill"); } + [Fact] + public void A_timed_retry_uses_its_own_start_and_retains_it_for_a_queued_write() + { + var watches = new FillWatches(); + var first = watches.Begin("k", started: 1); + var retry = watches.Begin("k", started: 2, independentTiming: true); + var next = watches.Begin("k", started: 3, independentTiming: true); + watches.Retain("k", retry); + watches.End("k", retry); + + watches.Started("k", first).Should().Be(1); + watches.Started("k", retry).Should().Be(2); + watches.Started("k", next).Should().Be(3); + watches.Intact("k", retry).Should().BeTrue(); + watches.Changed("k"); + watches.Intact("k", first).Should().BeFalse(); + watches.Intact("k", retry).Should().BeFalse(); + watches.Intact("k", next).Should().BeFalse(); + + watches.End("k", retry); + watches.Started("k", retry).Should().Be(0); + watches.Started("k", next).Should().Be(3); + watches.End("k", next); + watches.End("k", first); + watches.Any.Should().BeFalse(); + } + [Fact] public void A_token_of_a_finished_watch_is_never_intact_in_a_later_one() { diff --git a/tests/UiPath.Caching.Tests/MockableInterfaceTests.cs b/tests/UiPath.Caching.Tests/MockableInterfaceTests.cs index 3f1b3665f..377aedb8c 100644 --- a/tests/UiPath.Caching.Tests/MockableInterfaceTests.cs +++ b/tests/UiPath.Caching.Tests/MockableInterfaceTests.cs @@ -54,6 +54,17 @@ public void A_commonly_mocked_interface_has_no_overridable_default_member(Type t defaults.Should().BeEmpty(); } + [Theory] + [InlineData(typeof(ICache))] + [InlineData(typeof(ICache<>))] + public void Both_revalidation_overloads_are_sealed(Type cacheType) + { + var overloads = cacheType.GetMethods() + .Where(method => method.Name == nameof(ICache.GetOrRevalidateAsync)); + + overloads.Should().HaveCount(2).And.OnlyContain(method => !method.IsAbstract && !method.IsVirtual); + } + private static bool IsRefStruct(Type type) => (type.IsByRef ? type.GetElementType()! : type).IsByRefLike; private static IEnumerable LibraryAssemblies() => diff --git a/tests/UiPath.Caching.Tests/MultilayerCacheRevalidationFailSafeTests.cs b/tests/UiPath.Caching.Tests/MultilayerCacheRevalidationFailSafeTests.cs new file mode 100644 index 000000000..8bea372cf --- /dev/null +++ b/tests/UiPath.Caching.Tests/MultilayerCacheRevalidationFailSafeTests.cs @@ -0,0 +1,541 @@ +using Microsoft.Extensions.Logging.Abstractions; +using UiPath.Caching.Config; +using UiPath.Caching.Locking; +using UiPath.Caching.Tests.Fakes; +using UiPath.Caching.Tests.Telemetry; + +namespace UiPath.Caching.Tests; + +/// Revalidation under fail-safe on the memory-only multilayer cache: the kept value is the previous value and the fallback, and a NotModified never puts back a value that is no longer kept. +public sealed class MultilayerCacheRevalidationFailSafeTests : IDisposable +{ + private static readonly TimeSpan Lifetime = TimeSpan.FromMinutes(1); + private static readonly CachePolicy FailSafe = new() { DistributedExpiration = Lifetime, FailSafeEnabled = true, FailSafeMaxStaleAge = TimeSpan.FromHours(1), FailSafeCooldown = TimeSpan.FromSeconds(30) }; + private static readonly CachePolicy SoftTimeout = CachePolicyMerger.Merge(new CachePolicy { FailSafeTimeout = TimeSpan.FromSeconds(2) }, FailSafe); + private static readonly CacheKey Key = new("k"); + private static readonly DateTimeOffset Modified1 = new(2025, 6, 1, 0, 0, 0, TimeSpan.Zero); + private static readonly DateTimeOffset Modified2 = new(2025, 7, 1, 0, 0, 0, TimeSpan.Zero); + + private readonly ManualTimeProvider _clock = new(new DateTimeOffset(2026, 1, 1, 0, 0, 0, TimeSpan.Zero)); + private readonly RecordingTelemetryProvider _telemetry = new(); + private readonly List> _contexts = []; + private readonly MultilayerCache _cache; + + public MultilayerCacheRevalidationFailSafeTests() => _cache = Build(new InMemoryCacheOptions()); + + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + private IEnumerable NotModifiedEvents => _telemetry.Events.Where(e => e.Name == "cache.revalidation.not_modified"); + + [Fact] + public async Task After_expiry_the_kept_value_and_its_validators_reach_the_generator() + { + await WarmAsync(); + _clock.Advance(Lifetime * 2); + + (await _cache.GetOrRevalidateAsync(Key, 0, Answering(c => c.Modified("v2")), FailSafe, Ct)).Should().Be("v2"); + + var context = _contexts.Should().ContainSingle().Subject; + context.HasPreviousValue.Should().BeTrue(); + context.PreviousValue.Should().Be("v1"); + context.ETag.Should().Be("e1"); + context.LastModified.Should().Be(Modified1); + } + + [Fact] + public async Task NotModified_stores_the_previous_value_with_a_fresh_expiration() + { + await WarmAsync(); + _clock.Advance(Lifetime * 2); + + (await _cache.GetOrRevalidateAsync(Key, 0, Answering(c => c.NotModified()), FailSafe, Ct)).Should().Be("v1"); + + (await _cache.GetOrRevalidateAsync(Key, 0, Answering(_ => throw new InvalidOperationException("ran on a hit")), FailSafe, Ct)).Should().Be("v1"); + var entry = await _cache.GetCacheEntryAsync(Key, FailSafe, Ct); + entry.Found.Should().BeTrue(); + entry.Expiration.Should().Be(_clock.GetUtcNow() + Lifetime); + entry.Metadata!["etag"].Should().Be("e1", "the validators are unchanged"); + NotModifiedEvents.Should().ContainSingle() + .Which.Properties.Should().Contain("kind", "miss").And.Contain("cache.name", KnownCacheProviderNames.InMemory); + } + + [Fact] + public async Task A_NotModified_saved_from_an_earlier_call_fails_without_storing() + { + await WarmAsync(); + _clock.Advance(Lifetime * 2); + RevalidatedValue saved = default; + var replacing = Answering(context => + { + saved = context.NotModified(); + return context.Modified("v2", "e2"); + }); + await _cache.GetOrRevalidateAsync(Key, 0, replacing, FailSafe, Ct); + _clock.Advance(Lifetime * 2); + + var act = async () => await _cache.GetOrRevalidateAsync(Key, 0, Answering(_ => saved), FailSafe, Ct); + + await act.Should().ThrowAsync(); + _contexts[^1].PreviousValue.Should().Be("v2"); + (await _cache.GetCacheEntryAsync(Key, FailSafe, Ct)).Found.Should().BeFalse(); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task A_retry_rejects_the_NotModified_from_its_first_context(bool removeAtStore) + { + await WarmAsync(); + _clock.Advance(Lifetime * 2); + RevalidatedValue saved = default; + if (removeAtStore) + { + _cache.ConfirmedStoreStarting = () => _cache.RemoveAsync(Key, Ct).AsTask().GetAwaiter().GetResult(); + } + + async Task> Generate(int state, RevalidationContext context, CancellationToken token) + { + _contexts.Add(context); + if (context.HasPreviousValue) + { + saved = context.NotModified(); + if (!removeAtStore) + { + await _cache.RemoveAsync(Key, token); + } + } + + return saved; + } + + var act = async () => await _cache.GetOrRevalidateAsync(Key, 0, Generate, FailSafe, Ct); + + await act.Should().ThrowAsync(); + _contexts.Should().HaveCount(2); + _contexts[1].HasPreviousValue.Should().BeFalse(); + (await _cache.GetCacheEntryAsync(Key, FailSafe, Ct)).Found.Should().BeFalse(); + } + + [Fact] + public async Task Modified_replaces_the_value_and_the_validators() + { + await WarmAsync(); + _clock.Advance(Lifetime * 2); + + (await _cache.GetOrRevalidateAsync(Key, 0, Answering(c => c.Modified("v2", "e2", Modified2)), FailSafe, Ct)).Should().Be("v2"); + + var entry = await _cache.GetCacheEntryAsync(Key, FailSafe, Ct); + entry.Value.Should().Be("v2"); + entry.Metadata!["etag"].Should().Be("e2"); + _clock.Advance(Lifetime * 2); + (await _cache.GetOrRevalidateAsync(Key, 0, Answering(c => c.Modified("v3")), FailSafe, Ct)).Should().Be("v3"); + _contexts[^1].ETag.Should().Be("e2"); + _contexts[^1].LastModified.Should().Be(Modified2); + } + + [Fact] + public async Task A_failing_generator_falls_back_to_the_kept_value() + { + await WarmAsync(); + _clock.Advance(Lifetime * 2); + + (await _cache.GetOrRevalidateAsync(Key, 0, Answering(_ => throw new InvalidOperationException("down")), FailSafe, Ct)).Should().Be("v1"); + + _telemetry.Events.Should().ContainSingle(e => e.Name == "cache.fail_safe.served") + .Which.Properties.Should().Contain("reason", "error"); + } + + [Fact] + public async Task SkipFailSafe_drops_the_kept_value() + { + await WarmAsync(); + _clock.Advance(Lifetime * 2); + (await _cache.GetOrRevalidateAsync(Key, 0, Answering(c => c.Modified("v2") with { SkipFailSafe = true }), FailSafe, Ct)).Should().Be("v2"); + _clock.Advance(Lifetime * 2); + + var act = async () => await _cache.GetOrRevalidateAsync(Key, 0, Answering(_ => throw new InvalidOperationException("down")), FailSafe, Ct); + + await act.Should().ThrowAsync("nothing was kept to fall back to"); + _contexts[^1].HasPreviousValue.Should().BeFalse(); + } + + [Fact] + public async Task Past_the_soft_timeout_the_caller_gets_the_kept_value_and_a_late_NotModified_is_stored() + { + await WarmAsync(SoftTimeout); + _clock.Advance(Lifetime * 2); + var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var called = _clock.GetUtcNow(); + + var pending = _cache.GetOrRevalidateAsync(Key, 0, Gated(release, c => c.NotModified()), SoftTimeout, Ct).AsTask(); + await _clock.WhenTimerScheduledAsync(); + _clock.Advance(TimeSpan.FromSeconds(2)); + (await pending).Should().Be("v1"); + _cache.LateGenerations.Should().Be(1); + + release.SetResult(); + await _telemetry.Signal.UntilAsync(() => _cache.LateGenerations == 0, Ct); + + await _telemetry.Signal.UntilAsync(() => _telemetry.Events.Any(e => e.Name == "cache.fail_safe.background"), Ct); + _telemetry.Events.Should().Contain(e => e.Name == "cache.fail_safe.background" && e.Properties!["outcome"] == "stored"); + var entry = await _cache.GetCacheEntryAsync(Key, SoftTimeout, Ct); + entry.Value.Should().Be("v1"); + entry.Expiration.Should().Be(called + Lifetime, "a late value keeps the deadline its call drew, as any late value does"); + entry.Metadata!["etag"].Should().Be("e1"); + } + + [Fact] + public async Task A_late_elapsed_NotModified_answers_a_joiner_without_reporting_a_store() + { + await WarmAsync(SoftTimeout); + _clock.Advance(Lifetime * 2); + var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var past = _clock.GetUtcNow().AddSeconds(-1); + var pending = _cache.GetOrRevalidateAsync(Key, 0, Gated(release, c => c.NotModified(past)), SoftTimeout, Ct).AsTask(); + await _clock.WhenTimerScheduledAsync(); + var plain = new CachePolicy { DistributedExpiration = Lifetime }; + var joined = _cache.GetOrAddAsync(Key, static _ => throw new InvalidOperationException("The confirmation should answer the joiner."), plain, Ct).AsTask(); + _clock.Advance(TimeSpan.FromSeconds(2)); + (await pending).Should().Be("v1"); + + release.SetResult(); + (await joined).Should().Be("v1"); + (await _cache.GetCacheEntryAsync(Key, plain, Ct)).Found.Should().BeFalse(); + _telemetry.Events.Should().ContainSingle(e => e.Name == "cache.fail_safe.background") + .Which.Properties.Should().Contain("outcome", "discarded"); + } + + [Fact] + public async Task A_late_NotModified_after_a_removal_is_discarded() + { + await WarmAsync(SoftTimeout); + _clock.Advance(Lifetime * 2); + var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + // Confirms a previous value and fetches in full without one, as a conditional request does. + var pending = _cache.GetOrRevalidateAsync(Key, 0, Gated(release, c => c.HasPreviousValue ? c.NotModified() : c.Modified("fetched")), SoftTimeout, Ct).AsTask(); + await _clock.WhenTimerScheduledAsync(); + _clock.Advance(TimeSpan.FromSeconds(2)); + (await pending).Should().Be("v1"); + + await _cache.RemoveAsync(Key, Ct); + release.SetResult(); + await _telemetry.Signal.UntilAsync(() => _cache.LateGenerations == 0, Ct); + await _telemetry.Signal.UntilAsync(() => _telemetry.Events.Any(e => e.Name == "cache.fail_safe.background"), Ct); + + _telemetry.Events.Should().Contain(e => e.Name == "cache.fail_safe.background" && e.Properties!["outcome"] == "discarded"); + (await _cache.GetOrRevalidateAsync(Key, 0, Answering(c => c.Modified("v2")), SoftTimeout, Ct)).Should().Be("v2"); + _contexts[^1].HasPreviousValue.Should().BeFalse("the removal dropped the kept value and the late NotModified did not put it back"); + } + + [Fact] + public async Task During_the_cooldown_the_generator_does_not_run() + { + await WarmAsync(); + _clock.Advance(Lifetime * 2); + (await _cache.GetOrRevalidateAsync(Key, 0, Answering(_ => throw new InvalidOperationException("down")), FailSafe, Ct)).Should().Be("v1"); + var calls = _contexts.Count; + + (await _cache.GetOrRevalidateAsync(Key, 0, Answering(c => c.Modified("v2")), FailSafe, Ct)).Should().Be("v1"); + + _contexts.Should().HaveCount(calls); + } + + [Fact] + public async Task A_NotModified_whose_previous_value_was_removed_meanwhile_runs_the_generator_again_with_no_previous_value() + { + await WarmAsync(); + _clock.Advance(Lifetime * 2); + var started = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + + var call = _cache.GetOrRevalidateAsync(Key, 0, FirstGated(started, release, c => c.NotModified(), c => c.Modified("v2")), FailSafe, Ct).AsTask(); + await started.Task.WaitAsync(TimeSpan.FromSeconds(10), Ct); + await _cache.RemoveAsync(Key, Ct); + release.SetResult(); + + (await call).Should().Be("v2"); + _contexts.Should().HaveCount(2); + _contexts[0].HasPreviousValue.Should().BeTrue(); + _contexts[1].HasPreviousValue.Should().BeFalse(); + (await _cache.GetAsync(Key, FailSafe, Ct)).Should().Be("v2"); + NotModifiedEvents.Should().ContainSingle(); + } + + [Fact] + public async Task A_NotModified_whose_previous_value_a_write_replaced_meanwhile_runs_the_generator_again() + { + await WarmAsync(); + _clock.Advance(Lifetime * 2); + var started = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + + var call = _cache.GetOrRevalidateAsync(Key, 0, FirstGated(started, release, c => c.NotModified(), c => c.Modified("v2")), FailSafe, Ct).AsTask(); + await started.Task.WaitAsync(TimeSpan.FromSeconds(10), Ct); + (await _cache.SetAsync(Key, "written", Lifetime, FailSafe, Ct)).Should().BeTrue(); + release.SetResult(); + + (await call).Should().Be("v2", "the confirmed value is no longer the one kept"); + _contexts.Should().HaveCount(2); + _contexts[1].HasPreviousValue.Should().BeFalse(); + } + + [Fact] + public async Task A_second_NotModified_with_no_previous_value_fails_the_call() + { + await WarmAsync(); + _clock.Advance(Lifetime * 2); + var started = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + + var call = _cache.GetOrRevalidateAsync(Key, 0, FirstGated(started, release, c => c.NotModified(), c => c.NotModified()), FailSafe, Ct).AsTask(); + await started.Task.WaitAsync(TimeSpan.FromSeconds(10), Ct); + await _cache.RemoveAsync(Key, Ct); + release.SetResult(); + + await call.Invoking(c => c).Should().ThrowAsync(); + _contexts.Should().HaveCount(2); + (await _cache.GetCacheEntryAsync(Key, FailSafe, Ct)).Found.Should().BeFalse(); + } + + [Fact] + public async Task A_removal_between_the_generators_answer_and_the_store_runs_the_generator_again() + { + await WarmAsync(); + _clock.Advance(Lifetime * 2); + _cache.ConfirmedStoreStarting = () => + { + _cache.ConfirmedStoreStarting = null; + _cache.RemoveAsync(Key, Ct).AsTask().GetAwaiter().GetResult(); + }; + var calls = 0; + + var value = await _cache.GetOrRevalidateAsync(Key, 0, Answering(c => ++calls == 1 ? c.NotModified() : c.Modified("v2")), FailSafe, Ct); + + value.Should().Be("v2", "the caller never gets the confirmed value once it is no longer kept"); + _contexts.Should().HaveCount(2); + _contexts[1].HasPreviousValue.Should().BeFalse(); + (await _cache.GetAsync(Key, FailSafe, Ct)).Should().Be("v2"); + } + + [Fact] + public async Task A_removal_before_the_store_whose_second_generation_fails_fails_the_call() + { + await WarmAsync(); + _clock.Advance(Lifetime * 2); + _cache.ConfirmedStoreStarting = () => + { + _cache.ConfirmedStoreStarting = null; + _cache.RemoveAsync(Key, Ct).AsTask().GetAwaiter().GetResult(); + }; + var calls = 0; + + var act = async () => await _cache.GetOrRevalidateAsync(Key, 0, Answering(c => ++calls == 1 ? c.NotModified() : throw new InvalidOperationException("second")), FailSafe, Ct); + + await act.Should().ThrowAsync().WithMessage("second"); + calls.Should().Be(2); + (await _cache.GetCacheEntryAsync(Key, FailSafe, Ct)).Found.Should().BeFalse(); + } + + [Fact] + public async Task A_joiner_without_fail_safe_fetches_its_own_value_when_the_late_confirmation_is_refused() + { + await WarmAsync(SoftTimeout); + _clock.Advance(Lifetime * 2); + var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var plain = new CachePolicy { DistributedExpiration = Lifetime }; + var starter = _cache.GetOrRevalidateAsync(Key, 0, Gated(release, c => c.NotModified()), SoftTimeout, Ct).AsTask(); + await _clock.WhenTimerScheduledAsync(); + var joined = _cache.GetOrRevalidateAsync(Key, 0, Answering(c => c.Modified("joined-own")), plain, Ct).AsTask(); + joined.IsCompleted.Should().BeFalse(); + _clock.Advance(TimeSpan.FromSeconds(2)); + (await starter).Should().Be("v1"); + _cache.LateStoreStarting = () => _cache.RemoveAsync(Key, Ct).AsTask().GetAwaiter().GetResult(); + + release.SetResult(); + await _telemetry.Signal.UntilAsync(() => _telemetry.Events.Any(e => e.Name == "cache.fail_safe.background"), Ct); + (await joined).Should().Be("joined-own"); + _contexts.Should().HaveCount(2); + _contexts[1].HasPreviousValue.Should().BeFalse(); + (await _cache.GetAsync(Key, plain, Ct)).Should().Be("joined-own"); + } + + [Fact] + public async Task A_joiner_rejects_a_NotModified_from_its_first_attempt_after_two_overtaken_fallbacks() + { + await _cache.SetAsync(Key, "initial", Lifetime, FailSafe, Ct); + _clock.Advance(Lifetime * 2); + var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var starter = _cache.GetOrRevalidateAsync(Key, 0, Gated(release, _ => throw new InvalidOperationException("first fallback")), FailSafe, Ct).AsTask(); + RevalidatedValue saved = default; + var answer = Answering(context => + { + if (context.PreviousValue == "v1") + { + saved = context.NotModified(); + throw new InvalidOperationException("second fallback"); + } + + context.PreviousValue.Should().Be("v2"); + return saved; + }); + var joined = _cache.GetOrRevalidateAsync(Key, 0, answer, FailSafe, Ct).AsTask(); + + var fallbacks = 0; + _telemetry.EventRecorded += record => + { + if (record.Name == "cache.fail_safe.served" && ++fallbacks <= 2) + { + // Replace the kept value after it was chosen but before it reaches the joiner. + _cache.SetAsync(Key, $"v{fallbacks}", Lifetime, FailSafe, Ct).AsTask().GetAwaiter().GetResult(); + _clock.Advance(Lifetime * 2); + } + }; + joined.IsCompleted.Should().BeFalse(); + release.SetResult(); + + (await starter).Should().Be("initial"); + var act = async () => await joined; + await act.Should().ThrowAsync(); + _contexts.Select(context => context.PreviousValue).Should().Equal("initial", "v1", "v2"); + fallbacks.Should().Be(2); + (await _cache.GetCacheEntryAsync(Key, FailSafe, Ct)).Found.Should().BeFalse(); + } + + [Fact] + public async Task An_elapsed_NotModified_whose_value_was_removed_before_the_store_fetches_a_fresh_value() + { + var clock = new HookedClock(_clock); + using var cache = Build(new InMemoryCacheOptions(), clock); + await cache.GetOrRevalidateAsync(Key, 0, Answering(c => c.Modified("v1")), FailSafe, Ct); + _contexts.Clear(); + _clock.Advance(Lifetime * 2); + var removed = false; + var past = _clock.GetUtcNow().AddSeconds(-1); + + var generator = Answering(c => + { + if (!c.HasPreviousValue) + { + return c.Modified("v2"); + } + + clock.OnNow = () => + { + if (Environment.StackTrace.Contains("StoreRevalidatedAsync", StringComparison.Ordinal)) + { + clock.OnNow = null; + cache.RemoveAsync(Key, Ct).AsTask().GetAwaiter().GetResult(); + removed = true; + } + }; + return c.NotModified(past); + }); + var value = await cache.GetOrRevalidateAsync(Key, 0, generator, FailSafe, Ct); + + removed.Should().BeTrue(); + value.Should().Be("v2"); + _contexts.Should().HaveCount(2); + _contexts[1].HasPreviousValue.Should().BeFalse(); + } + + [Fact] + public async Task A_late_NotModified_whose_value_is_replaced_before_the_write_is_discarded() + { + await WarmAsync(SoftTimeout); + _clock.Advance(Lifetime * 2); + var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + + var pending = _cache.GetOrRevalidateAsync(Key, 0, Gated(release, c => c.NotModified(_clock.GetUtcNow().AddHours(1))), SoftTimeout, Ct).AsTask(); + await _clock.WhenTimerScheduledAsync(); + _clock.Advance(TimeSpan.FromSeconds(2)); + (await pending).Should().Be("v1"); + _cache.LateStoreStarting = () => _cache.SetAsync(Key, "written", Lifetime, SoftTimeout, Ct).AsTask().GetAwaiter().GetResult(); + release.SetResult(); + await _telemetry.Signal.UntilAsync(() => _cache.LateGenerations == 0, Ct); + await _telemetry.Signal.UntilAsync(() => _telemetry.Events.Any(e => e.Name == "cache.fail_safe.background"), Ct); + + _contexts.Should().ContainSingle().Which.PreviousValue.Should().Be("v1"); + _telemetry.Events.Should().Contain(e => e.Name == "cache.fail_safe.background" && e.Properties!["outcome"] == "discarded"); + var entry = await _cache.GetCacheEntryAsync(Key, SoftTimeout, Ct); + entry.Value.Should().Be("written"); + entry.Expiration.Should().BeBefore(_clock.GetUtcNow().AddHours(1), "the late NotModified was not stored"); + } + + public void Dispose() => _cache.Dispose(); + + /// Stores v1 with its validators; the contexts recorded so far are cleared. + private async Task WarmAsync(CachePolicy? policy = null) + { + (await _cache.GetOrRevalidateAsync(Key, 0, Answering(c => c.Modified("v1", "e1", Modified1)), policy ?? FailSafe, Ct)).Should().Be("v1"); + _contexts.Clear(); + } + + private Func, CancellationToken, Task>> Answering(Func, RevalidatedValue> answer) => + (_, context, _) => + { + _contexts.Add(context); + return Task.FromResult(answer(context)); + }; + + private Func, CancellationToken, Task>> Gated(TaskCompletionSource release, Func, RevalidatedValue> answer) => + async (_, context, _) => + { + _contexts.Add(context); + await release.Task; + return answer(context); + }; + + /// The first call signals, waits for the release and answers with ; later calls answer at once with . + private Func, CancellationToken, Task>> FirstGated(TaskCompletionSource started, TaskCompletionSource release, Func, RevalidatedValue> first, Func, RevalidatedValue> then) + { + var calls = 0; + return async (_, context, _) => + { + _contexts.Add(context); + if (++calls > 1) + { + return then(context); + } + + started.SetResult(); + await release.Task; + return first(context); + }; + } + + private MultilayerCache Build(InMemoryCacheOptions options, TimeProvider? clock = null) + { + clock ??= _clock; + options.TrackStatistics = false; + return RunTables.Track(new MultilayerCache( + KnownCacheProviderNames.InMemory, + NullCache.Instance, + new MemoryCacheFactory(clock, NullLoggerFactory.Instance), + NullChangeTokenFactory.Instance, + NullTopicFactory.Instance, + NullCacheEventFactory.Instance, + _telemetry, + options, + options, + new CacheOptions { AppShortName = "test" }, + distributedLock: NullDistributedLock.Instance, + policyFactory: NullCachePolicyFactory.Instance, + clock: clock, + logger: NullLogger.Instance)); + } + + private sealed class HookedClock(ManualTimeProvider inner) : TimeProvider + { + public Action? OnNow { get; set; } + + public override long TimestampFrequency => inner.TimestampFrequency; + + public override DateTimeOffset GetUtcNow() + { + OnNow?.Invoke(); + return inner.GetUtcNow(); + } + + public override long GetTimestamp() => inner.GetTimestamp(); + } +} diff --git a/tests/UiPath.Caching.Tests/MultilayerCacheRevalidationPeerTests.cs b/tests/UiPath.Caching.Tests/MultilayerCacheRevalidationPeerTests.cs new file mode 100644 index 000000000..f12f9c908 --- /dev/null +++ b/tests/UiPath.Caching.Tests/MultilayerCacheRevalidationPeerTests.cs @@ -0,0 +1,180 @@ +using UiPath.Caching.Config; +using UiPath.Caching.Tests.Fakes; +using UiPath.Caching.Tests.Telemetry; + +namespace UiPath.Caching.Tests; + +/// Revalidation across nodes that share an inner tier and a bus: a peer's removal fences a NotModified, and its store writes in the foreground. +public class MultilayerCacheRevalidationPeerTests +{ + private static readonly CacheKey Key = new("k"); + private static readonly TimeSpan LocalLifetime = TimeSpan.FromMilliseconds(100); + private static readonly CachePolicy FailSafe = new() { FailSafeEnabled = true, LocalExpiration = LocalLifetime, FailSafeCooldown = TimeSpan.Zero }; + private static readonly CachePolicy Background = CachePolicyMerger.Merge(new CachePolicy { BackgroundDistributedWrite = true }, FailSafe); + + private readonly ManualTimeProvider _clock = new(new DateTimeOffset(2026, 1, 1, 0, 0, 0, TimeSpan.Zero)); + private readonly List> _contexts = []; + + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + [Fact] + public async Task A_NotModified_whose_previous_value_a_peer_event_dropped_runs_the_generator_again() + { + using var peers = new CachePeers(); + var a = peers.Add("a", clock: _clock, localClock: _clock); + var b = peers.Add("b", clock: _clock, localClock: _clock); + await WarmAsync(a, FailSafe); + Expire(peers); + var started = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + + var call = a.Cache.GetOrRevalidateAsync(Key, 0, FirstGated(started, release), FailSafe, Ct).AsTask(); + await started.Task.WaitAsync(TimeSpan.FromSeconds(10), Ct); + await b.Cache.RemoveAsync(Key, Ct); + await a.Settled(); + release.SetResult(); + + (await call).Should().Be("v2"); + _contexts.Should().HaveCount(2); + _contexts[0].PreviousValue.Should().Be("v1"); + _contexts[1].HasPreviousValue.Should().BeFalse("the peer's removal dropped the kept value the NotModified confirmed"); + } + + [Fact] + public Task A_confirmed_miss_refused_by_a_tombstone_fetches_a_fresh_value() => AssertFencedRegenerationAsync(FailSafe); + + [Fact] + public Task A_regeneration_after_a_tombstone_is_stored_by_a_background_fill() => AssertFencedRegenerationAsync(Background); + + [Fact] + public async Task A_removal_between_the_generators_answer_and_the_store_runs_the_generator_again_and_fills_the_shared_tier() + { + using var peers = new CachePeers(); + var a = peers.Add("a", clock: _clock, localClock: _clock); + await WarmAsync(a, FailSafe); + Expire(peers); + a.Cache.ConfirmedStoreStarting = () => a.Cache.RemoveAsync(Key, Ct).AsTask().GetAwaiter().GetResult(); + + await AssertRegeneratesAndFillsAsync(peers, a); + } + + [Fact] + public async Task A_NotModified_store_writes_in_the_foreground_under_BackgroundDistributedWrite() + { + using var peers = new CachePeers(); + var a = peers.Add("a", clock: _clock, localClock: _clock); + await WarmAsync(a, Background); + await CachePeers.Until(() => !CachePeers.WriteInFlight(a.Cache, "k")); + Expire(peers); + var hold = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + a.Inner.AfterWrite = hold.Task; + + var call = a.Cache.GetOrRevalidateAsync(Key, 0, (_, context, _) => Task.FromResult(context.NotModified()), Background, Ct).AsTask(); + await peers.Store.Changes.WaitUntil(() => peers.Store.Values.TryGetValue("k", out var stored) && Equals(stored, "v1")).WaitAsync(TimeSpan.FromSeconds(10), Ct); + + call.IsCompleted.Should().BeFalse("the caller waits for the inner write of a NotModified, which runs under the late-store guard"); + hold.SetResult(); + (await call).Should().Be("v1"); + } + + [Fact] + public async Task An_entry_from_a_delegating_factory_not_read_within_the_idle_window_is_dropped_on_a_peer_write() + { + using var peers = new CachePeers(_clock); + var telemetry = new RecordingTelemetryProvider(); + var clock = new ManualTimeProvider(_clock.GetUtcNow()); + var window = new CachePolicy { LocalExpiration = TimeSpan.FromMinutes(10) }; + var a = peers.Add("a"); + var b = peers.Add("b", new InMemoryRedisCacheOptions { EntryFactory = new DelegatingCacheEntryFactory() }, telemetry, clock); + (await b.Cache.GetOrRevalidateAsync(Key, 0, static (_, context, _) => Task.FromResult(context.Modified("old", "e1")), window, Ct)).Should().Be("old"); + await b.Settled(); + var before = b.Inner.SingleReads; + peers.AutoDeliver = false; + await a.Cache.SetAsync(Key, "new", null, Ct); + var set = a.Published[^1]; + + clock.Advance(TimeSpan.FromMinutes(11)); + peers.Deliver(b, set); + await b.Settled(outcomes: 1).WaitAsync(TimeSpan.FromSeconds(10), Ct); + + b.Local.TryGetValue(Key, out _).Should().BeFalse(); + b.Inner.SingleReads.Should().Be(before, "an idle entry starts no refresh read"); + telemetry.Metrics.Where(m => m.Name == "cache.peer_refresh.dropped").Select(m => m.Properties!["reason"]).Should().Equal("idle"); + } + + private static async Task WarmAsync(CachePeers.Node node, CachePolicy policy) + { + (await node.Cache.GetOrRevalidateAsync(Key, 0, static (_, context, _) => Task.FromResult(context.Modified("v1", "e1")), policy, Ct)).Should().Be("v1"); + await node.Settled(); + } + + private async Task AssertFencedRegenerationAsync(CachePolicy policy) + { + using var peers = new CachePeers { Fenced = true }; + var a = peers.Add("a", clock: _clock, localClock: _clock); + await WarmAsync(a, FailSafe); + Expire(peers); + var warmFills = a.Inner.GeneratorAges.Count; + var grace = TimeSpan.FromSeconds(30); + DateTimeOffset? removedAt = null; + a.Inner.ReadTombstone = _ => removedAt is { } removed ? ((long)grace.TotalMilliseconds, grace - (_clock.GetUtcNow() - removed)) : null; + + void RemoveDuringConfirmation() + { + _clock.Advance(TimeSpan.FromSeconds(3)); + removedAt = _clock.GetUtcNow(); + _clock.Advance(TimeSpan.FromSeconds(2)); + } + + await AssertRegeneratesAndFillsAsync(peers, a, policy, RemoveDuringConfirmation, () => _clock.Advance(TimeSpan.FromSeconds(1))); + + a.Inner.GeneratorAges.Skip(warmFills).Should().Equal(TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(1)); + } + + private async Task AssertRegeneratesAndFillsAsync(CachePeers peers, CachePeers.Node node, CachePolicy? policy = null, Action? beforeConfirmation = null, Action? beforeRegeneration = null) + { + Task> Generate(int _, RevalidationContext context, CancellationToken token) + { + _contexts.Add(context); + if (_contexts.Count == 1) + { + beforeConfirmation?.Invoke(); + return Task.FromResult(context.NotModified()); + } + + beforeRegeneration?.Invoke(); + return Task.FromResult(context.Modified("v2")); + } + + var value = await node.Cache.GetOrRevalidateAsync(Key, 0, Generate, policy ?? FailSafe, Ct); + await node.Settled(); + + value.Should().Be("v2"); + _contexts.Should().HaveCount(2); + _contexts[0].PreviousValue.Should().Be("v1"); + _contexts[1].HasPreviousValue.Should().BeFalse(); + peers.Store.Values.Should().ContainKey("k").WhoseValue.Should().Be("v2"); + } + + /// The value leaves the inner tier quietly and its local copy expires, as both lifetimes ending would. + private void Expire(CachePeers peers) + { + peers.Store.Values.Clear(); + _clock.Advance(LocalLifetime * 2); + } + + /// The first call signals, waits for the release and answers NotModified; a later call answers a new value at once. + private Func, CancellationToken, Task>> FirstGated(TaskCompletionSource started, TaskCompletionSource release) => + async (_, context, _) => + { + _contexts.Add(context); + if (_contexts.Count > 1) + { + return context.Modified("v2"); + } + + started.SetResult(); + await release.Task; + return context.NotModified(); + }; +} diff --git a/tests/UiPath.Caching.Tests/MultilayerCacheRevalidationRehydrateTests.cs b/tests/UiPath.Caching.Tests/MultilayerCacheRevalidationRehydrateTests.cs new file mode 100644 index 000000000..24ea1307c --- /dev/null +++ b/tests/UiPath.Caching.Tests/MultilayerCacheRevalidationRehydrateTests.cs @@ -0,0 +1,275 @@ +using Microsoft.Extensions.DependencyInjection; +using UiPath.Caching.Broadcast; +using UiPath.Caching.Config; +using UiPath.Caching.Telemetry; +using UiPath.Caching.Tests.Telemetry; + +namespace UiPath.Caching.Tests; + +public sealed class MultilayerCacheRevalidationRehydrateTests : IDisposable +{ + private const string Succeeded = "cache.rehydrate.succeeded"; + private const string Triggered = "cache.rehydrate.triggered"; + private static readonly CacheKey Key = new("k"); + private static readonly TimeSpan Lifetime = TimeSpan.FromHours(1); + private static readonly CachePolicy Policy = new() + { + DistributedExpiration = Lifetime, + RehydrateEnabled = true, + Rehydrate = new RehydrateOptions { Threshold = 0.8 }, + }; + + private readonly ManualTimeProvider _clock = new(); + private readonly RecordingTelemetryProvider _telemetry = new(); + private readonly ServiceProvider _services; + private readonly MultilayerCache _cache; + + public MultilayerCacheRevalidationRehydrateTests() + { + _services = new ServiceCollection().AddSingleton(_clock) + .AddSingleton(_telemetry) + .AddCaching(b => b.AddMemory(o => o.TrackStatistics = false), o => o.AppShortName = "rh") + .BuildServiceProvider(); + _cache = (MultilayerCache)_services.GetRequiredService().CreateCache(KnownCacheProviderNames.InMemory); + } + + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + [Fact] + public async Task A_hit_past_the_threshold_revalidates_in_the_background_with_the_live_entry() + { + await SeedAsync(); + Age(); + var entered = new TaskCompletionSource>(TaskCreationOptions.RunContinuationsAsynchronously); + var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + try + { + (await RevalidateAsync(async (context, token) => + { + entered.SetResult(context); + await release.Task.WaitAsync(token); + return context.NotModified(); + })).Should().Be("old"); + _telemetry.Events.Should().Contain(e => e.Name == Triggered); + var context = await entered.Task.WaitAsync(Ct); + context.HasPreviousValue.Should().BeTrue(); + context.PreviousValue.Should().Be("old"); + context.ETag.Should().Be("old-tag"); + } + finally + { + release.SetResult(); + } + + await FinishedAsync(); + } + + [Fact] + public async Task A_background_NotModified_extends_the_entry_and_keeps_its_validators() + { + await SeedAsync(); + Age(); + await RevalidateAsync(static (context, _) => Task.FromResult(context.NotModified())); + await FinishedAsync(); + + var entry = await ReadAsync(); + entry.Value.Should().Be("old"); + entry.Expiration.Should().Be(_clock.GetUtcNow() + Lifetime); + entry.Metadata!["etag"].Should().Be("old-tag"); + entry.Metadata.Should().ContainKey("last-modified"); + _telemetry.Events.Should().Contain(e => e.Name == "cache.revalidation.not_modified" && e.Properties!["kind"] == "rehydrate"); + } + + [Fact] + public async Task A_background_NotModified_draws_its_lifetime_from_the_policy_and_jitter() + { + var durations = new CachePolicy + { + DistributedExpiration = TimeSpan.FromSeconds(60), + JitterMaxDuration = TimeSpan.FromSeconds(10), + }; + var policy = CachePolicyMerger.Merge(durations, Policy); + var initialExpiration = _clock.GetUtcNow().AddMinutes(2); + await _cache.GetOrRevalidateAsync(Key, initialExpiration, static (expiration, context, _) => Task.FromResult(context.Modified("old", expiration: expiration)), policy, Ct); + + _clock.Advance(TimeSpan.FromSeconds(115)); + await _cache.GetOrRevalidateAsync(Key, 0, static (_, context, _) => Task.FromResult(context.NotModified()), policy, Ct); + await FinishedAsync(); + + var renewed = await ReadAsync(); + (renewed.Expiration - _clock.GetUtcNow()).Should().BeGreaterThanOrEqualTo(TimeSpan.FromSeconds(60)).And.BeLessThanOrEqualTo(TimeSpan.FromSeconds(70)); + } + + [Fact] + public async Task A_background_NotModified_announces_a_successful_local_write() + { + var factory = Substitute.For(); + var provider = Substitute.For(); + var topic = Substitute.For>(); + factory.Get(Arg.Any()).Returns(provider); + provider.Create(Arg.Any()).Returns(topic); +#pragma warning disable CA2012 // NSubstitute setups call ValueTask-returning members without consuming the result. + topic.PublishAsync(Arg.Any(), Arg.Any()).Returns(true); +#pragma warning restore CA2012 + using var services = new ServiceCollection() + .AddSingleton(_clock) + .AddSingleton(_telemetry) + .AddSingleton(factory) + .AddSingleton() + .AddCaching(b => b.AddMemory(o => o.BroadcastEnable = true), o => o.AppShortName = "rh") + .BuildServiceProvider(); + var broadcasting = services.GetRequiredService().CreateCache(KnownCacheProviderNames.InMemory); + await broadcasting.GetOrRevalidateAsync(Key, 0, static (_, context, _) => Task.FromResult(context.Modified("old")), Policy, Ct); + topic.ClearReceivedCalls(); + Age(); + + await broadcasting.GetOrRevalidateAsync(Key, 0, static (_, context, _) => Task.FromResult(context.NotModified()), Policy, Ct); + await FinishedAsync(); + + await topic.Received(1).PublishAsync(Arg.Is(e => e.Type == KnownEventTypes.CacheSet), Arg.Any()); + } + + [Fact] + public async Task A_background_Modified_replaces_value_and_validators() + { + await SeedAsync(); + Age(); + var deadline = _clock.GetUtcNow().AddSeconds(20); + await RevalidateAsync((context, _) => Task.FromResult(context.Modified("new", "new-tag", expiration: deadline))); + await FinishedAsync(); + + var entry = await ReadAsync(); + entry.Value.Should().Be("new"); + entry.Expiration.Should().Be(deadline); + entry.Metadata!["etag"].Should().Be("new-tag"); + entry.Metadata.Should().NotContainKey("last-modified"); + } + + [Fact] + public async Task A_generator_expiration_sets_the_threshold_of_the_next_rehydrate() + { + var deadline = _clock.GetUtcNow().AddSeconds(10); + await RevalidateAsync((context, _) => Task.FromResult(context.Modified("old", expiration: deadline))); + (await ReadAsync()).Metadata.Should().BeNull(); + _clock.Advance(TimeSpan.FromSeconds(1)); + await RevalidateAsync(static (context, _) => Task.FromResult(context.NotModified())); + _telemetry.Events.Should().NotContain(e => e.Name == Triggered); + + _clock.Advance(TimeSpan.FromSeconds(8)); + await RevalidateAsync(static (context, _) => Task.FromResult(context.NotModified())); + await FinishedAsync(); + _telemetry.Events.Count(e => e.Name == Triggered).Should().Be(1); + } + + [Fact] + public async Task A_background_confirmation_from_another_context_leaves_the_entry_untouched() + { + await SeedAsync(); + var expiration = (await ReadAsync()).Expiration; + Age(); + var saved = RevalidationContext.WithPrevious("old", "old-tag").NotModified(); + + (await RevalidateAsync((_, _) => Task.FromResult(saved))).Should().Be("old"); + await _telemetry.Signal.UntilAsync(() => _telemetry.Events.Any(e => e.Name is Succeeded or "cache.rehydrate.failed"), Ct); + + _telemetry.Events.Should().Contain(e => e.Name == "cache.rehydrate.failed"); + (await ReadAsync()).Expiration.Should().Be(expiration); + } + + [Fact] + public async Task A_failed_background_revalidation_leaves_the_entry_until_it_expires() + { + await SeedAsync(); + Age(); + + (await RevalidateAsync(Fail)).Should().Be("old"); + await FinishedAsync("cache.rehydrate.failed"); + (await ReadAsync()).Value.Should().Be("old"); + + _clock.Advance(TimeSpan.FromMinutes(7)); + var expired = async () => await RevalidateAsync(Fail); + await expired.Should().ThrowAsync().WithMessage("origin failed"); + + static Task> Fail(RevalidationContext _, CancellationToken token) => + Task.FromException>(new InvalidOperationException("origin failed")); + } + + [Fact] + public async Task A_hit_before_the_threshold_starts_nothing() + { + await SeedAsync(); + _clock.Advance(TimeSpan.FromMinutes(47)); + + (await RevalidateAsync(static (_, _) => throw new InvalidOperationException("unexpected generator"))).Should().Be("old"); + _telemetry.Events.Should().NotContain(e => e.Name == Triggered); + } + + [Fact] + public async Task A_background_NotModified_after_a_removal_stores_nothing() + { + await WhileGeneratingAsync(confirm: true, async () => await _cache.RemoveAsync(Key, Ct)); + + (await ReadAsync()).Found.Should().BeFalse(); + } + + [Fact] + public async Task A_background_NotModified_after_a_write_keeps_the_written_value() + { + await WhileGeneratingAsync(confirm: true, async () => { await _cache.SetAsync(Key, "peer", Policy, Ct); }); + + (await ReadAsync()).Value.Should().Be("peer"); + } + + [Fact] + public async Task A_background_Modified_after_a_removal_stores_as_it_does_today() + { + await WhileGeneratingAsync(confirm: false, async () => await _cache.RemoveAsync(Key, Ct)); + + (await ReadAsync()).Value.Should().Be("new"); + } + + public void Dispose() => _services.Dispose(); + + private async Task WhileGeneratingAsync(bool confirm, Func change) + { + await SeedAsync(); + Age(); + var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + try + { + await RevalidateAsync(async (context, token) => + { + entered.SetResult(); + await release.Task.WaitAsync(token); + return confirm ? context.NotModified() : context.Modified("new"); + }); + _telemetry.Events.Should().Contain(e => e.Name == Triggered); + await entered.Task.WaitAsync(Ct); + await change(); + } + finally + { + release.SetResult(); + } + + await FinishedAsync(); + } + + private ValueTask SeedAsync(DateTimeOffset? expiration = null) => + RevalidateAsync((context, _) => Task.FromResult(context.Modified("old", "old-tag", _clock.GetUtcNow(), expiration))); + + private ValueTask RevalidateAsync(Func, CancellationToken, Task>> generator) => + _cache.GetOrRevalidateAsync, CancellationToken, Task>>>( + Key, generator, static (run, context, token) => run(context, token), Policy, Ct); + + private ValueTask> ReadAsync() => _cache.GetCacheEntryAsync(Key, Policy, Ct); + + private void Age() => _clock.Advance(TimeSpan.FromMinutes(54)); + + private Task FinishedAsync(string name = Succeeded) + { + _telemetry.Events.Should().Contain(e => e.Name == Triggered); + return _telemetry.Signal.UntilAsync(() => _telemetry.Events.Any(e => e.Name == name), Ct); + } +} diff --git a/tests/UiPath.Caching.Tests/MultilayerCacheRevalidationTests.cs b/tests/UiPath.Caching.Tests/MultilayerCacheRevalidationTests.cs new file mode 100644 index 000000000..6cf988138 --- /dev/null +++ b/tests/UiPath.Caching.Tests/MultilayerCacheRevalidationTests.cs @@ -0,0 +1,292 @@ +using Microsoft.Extensions.Logging.Abstractions; +using UiPath.Caching.Config; +using UiPath.Caching.Locking; +using UiPath.Caching.Tests.Fakes; +using UiPath.Caching.Tests.Telemetry; + +namespace UiPath.Caching.Tests; + +/// Revalidation on the memory-only multilayer cache without fail-safe: the generator gets no previous value, and its validators are stored with the value. +public sealed class MultilayerCacheRevalidationTests : IDisposable +{ + private static readonly TimeSpan Lifetime = TimeSpan.FromMinutes(1); + private static readonly CachePolicy Policy = new() { DistributedExpiration = Lifetime }; + private static readonly CacheKey Key = new("k"); + private static readonly DateTimeOffset Modified1 = new(2025, 6, 1, 0, 0, 0, TimeSpan.Zero); + + private readonly ManualTimeProvider _clock = new(new DateTimeOffset(2026, 1, 1, 0, 0, 0, TimeSpan.Zero)); + private readonly RecordingTelemetryProvider _telemetry = new(); + private readonly List> _contexts = []; + private readonly MultilayerCache _cache; + + public MultilayerCacheRevalidationTests() => _cache = Build(new InMemoryCacheOptions()); + + public enum Factory + { + Custom, + Delegating, + Relabeling, + } + + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + [Fact] + public async Task The_first_call_runs_the_generator_with_no_previous_value() + { + var value = await _cache.GetOrRevalidateAsync(Key, "v1", Recording, Policy, Ct); + + value.Should().Be("v1"); + _contexts.Should().ContainSingle().Which.HasPreviousValue.Should().BeFalse(); + } + + [Fact] + public async Task A_hit_does_not_run_the_generator() + { + (await _cache.GetOrRevalidateAsync(Key, "v1", Recording, Policy, Ct)).Should().Be("v1"); + + (await _cache.GetOrRevalidateAsync(Key, "v2", Recording, Policy, Ct)).Should().Be("v1"); + + _contexts.Should().ContainSingle(); + } + + [Fact] + public async Task After_expiry_without_fail_safe_the_context_is_empty() + { + (await _cache.GetOrRevalidateAsync(Key, "v1", Recording, Policy, Ct)).Should().Be("v1"); + _clock.Advance(Lifetime * 2); + + (await _cache.GetOrRevalidateAsync(Key, "v2", Recording, Policy, Ct)).Should().Be("v2"); + + _contexts.Should().HaveCount(2); + _contexts[1].HasPreviousValue.Should().BeFalse("the expired entry is gone and nothing kept it"); + } + + [Fact] + public async Task Modified_stores_the_value_and_its_validators() + { + (await _cache.GetOrRevalidateAsync(Key, "v1", Recording, Policy, Ct)).Should().Be("v1"); + + var entry = await _cache.GetCacheEntryAsync(Key, Policy, Ct); + + entry.Value.Should().Be("v1"); + entry.Metadata.Should().NotBeNull(); + entry.Metadata!["etag"].Should().Be("e:v1"); + entry.Metadata.Should().ContainKey("last-modified"); + } + + [Theory] + [InlineData(Factory.Custom)] + [InlineData(Factory.Delegating)] + [InlineData(Factory.Relabeling)] + public async Task Modified_without_validators_passes_null_metadata_to_a_custom_factory(Factory factory) + { + var label = new Dictionary { ["tenant"] = "t1" }; + ICacheEntryFactory entries = factory switch + { + Factory.Custom => new TestCacheEntryFactory(), + Factory.Delegating => new DelegatingCacheEntryFactory(), + _ => new DelegatingCacheEntryFactory(label), + }; + var shown = factory == Factory.Relabeling ? label : null; + using var cache = Build(new InMemoryCacheOptions { EntryFactory = entries }); + var policy = new CachePolicy + { + DistributedExpiration = TimeSpan.FromHours(1), + RehydrateEnabled = true, + Rehydrate = new RehydrateOptions { Threshold = 0.8 }, + }; + var deadline = _clock.GetUtcNow() + Lifetime; + await cache.GetOrRevalidateAsync(Key, deadline, static (expiration, context, _) => Task.FromResult(context.Modified("v1", expiration: expiration)), policy, Ct); + + var entry = await cache.GetCacheEntryAsync(Key, policy, Ct); + entry.Value.Should().Be("v1"); + entry.Metadata.Should().BeSameAs(shown); + + _clock.Advance(TimeSpan.FromSeconds(30)); + static Task> Refresh(int _, RevalidationContext context, CancellationToken token) => Task.FromResult(context.Modified("v2")); + (await cache.GetOrRevalidateAsync(Key, 0, Refresh, policy, Ct)).Should().Be("v1"); + _telemetry.Events.Should().NotContain(e => e.Name == "cache.rehydrate.triggered"); + + _clock.Advance(TimeSpan.FromSeconds(20)); + (await cache.GetOrRevalidateAsync(Key, 0, Refresh, policy, Ct)).Should().Be("v1"); + await _telemetry.Signal.UntilAsync(() => _telemetry.Events.Any(e => e.Name is "cache.rehydrate.succeeded" or "cache.rehydrate.failed"), Ct); + var refreshed = await cache.GetCacheEntryAsync(Key, policy, Ct); + refreshed.Value.Should().Be("v2"); + refreshed.Metadata.Should().BeSameAs(shown); + } + + [Fact] + public async Task A_snapshot_through_a_delegating_factory_reports_the_local_cap() + { + var cap = TimeSpan.FromMinutes(1); + var policy = new CachePolicy { DistributedExpiration = TimeSpan.FromHours(1) }; + using var cache = Build(new InMemoryCacheOptions { EntryFactory = new DelegatingCacheEntryFactory(), LocalMaxExpiration = cap }); + var capped = _clock.GetUtcNow() + cap; + (await cache.GetOrRevalidateAsync(Key, "v1", Recording, policy, Ct)).Should().Be("v1"); + _clock.Advance(TimeSpan.FromSeconds(1)); + + var snapshot = await cache.ReadSnapshotAsync(Key, policy, Ct); + + snapshot.Outcome.Should().Be(SnapshotOutcome.Found); + var entry = snapshot.Entry!; + entry.Value.Should().Be("v1"); + entry.Expiration.Should().Be(capped); + entry.Metadata!["etag"].Should().Be("e:v1"); + entry.GetType().Should().Be(new CacheEntryFactory().Create("v1", capped).GetType(), "a public read returns the factory's own entry type"); + } + + [Fact] + public async Task Interned_entries_keep_the_rehydrate_lifetime_of_each_key() + { + var factory = new InterningEntryFactory(_clock.GetUtcNow().AddSeconds(10)); + using var cache = Build(new InMemoryCacheOptions { EntryFactory = factory }); + var policy = new CachePolicy + { + DistributedExpiration = Lifetime, + RehydrateEnabled = true, + Rehydrate = new RehydrateOptions { Threshold = 0.8 }, + }; + CacheKey first = "a"; + CacheKey second = "b"; + await cache.GetOrRevalidateAsync(first, factory.Deadline, Seed, policy, Ct); + _clock.Advance(TimeSpan.FromSeconds(5)); + await cache.GetOrRevalidateAsync(second, factory.Deadline, Seed, policy, Ct); + + _clock.Advance(TimeSpan.FromSeconds(3.5)); + (await cache.GetOrRevalidateAsync(second, 0, Refresh, policy, Ct)).Should().Be("seed"); + _telemetry.Events.Should().NotContain(e => e.Name == "cache.rehydrate.triggered"); + (await cache.GetOrRevalidateAsync(first, 0, Refresh, policy, Ct)).Should().Be("seed"); + _telemetry.Events.Should().ContainSingle(e => e.Name == "cache.rehydrate.triggered"); + await _telemetry.Signal.UntilAsync(() => _telemetry.Events.Any(e => e.Name is "cache.rehydrate.succeeded" or "cache.rehydrate.failed"), Ct); + + var refreshed = await cache.GetCacheEntryAsync(first, policy, Ct); + refreshed.Value.Should().Be("refreshed"); + refreshed.Metadata.Should().BeNull(); + var held = await cache.GetCacheEntryAsync(second, policy, Ct); + held.Should().BeSameAs(factory.SharedEntry); + held.Metadata.Should().BeNull(); + (await cache.GetCacheEntryAsync(second.Name.ToCharArray(), policy, Ct)).Should().BeSameAs(held); + var batch = await cache.GetCacheEntriesAsync([first, second], policy, Ct); + batch[1].Value.Should().BeSameAs(held); + + static Task> Seed(DateTimeOffset expiration, RevalidationContext context, CancellationToken token) => + Task.FromResult(context.Modified("seed", expiration: expiration)); + + static Task> Refresh(int _, RevalidationContext context, CancellationToken token) => + Task.FromResult(context.Modified("refreshed")); + } + + [Fact] + public async Task A_generator_expiration_wins_over_the_policy_duration() + { + var deadline = _clock.GetUtcNow().AddSeconds(10); + var calls = 0; + Task> Generate(DateTimeOffset expiration, RevalidationContext context, CancellationToken token) + { + calls++; + return Task.FromResult(context.Modified("v1", expiration: expiration)); + } + + (await _cache.GetOrRevalidateAsync(Key, deadline, Generate, Policy, Ct)).Should().Be("v1"); + + (await _cache.GetCacheEntryAsync(Key, Policy, Ct)).Expiration.Should().Be(deadline); + _clock.Advance(TimeSpan.FromSeconds(11)); + (await _cache.GetOrRevalidateAsync(Key, deadline.AddMinutes(1), Generate, Policy, Ct)).Should().Be("v1"); + calls.Should().Be(2, "the entry expired at the generator's deadline, well before the policy duration"); + } + + [Theory] + [InlineData(false, 2)] + [InlineData(true, 1)] + public async Task A_null_from_Modified_follows_CacheNullValues(bool cacheNullValues, int expectedCalls) + { + using var cache = Build(new InMemoryCacheOptions { CacheNullValues = cacheNullValues }); + var calls = 0; + Task> Generate(int _, RevalidationContext context, CancellationToken token) + { + calls++; + return Task.FromResult(context.Modified(null)); + } + + (await cache.GetOrRevalidateAsync(Key, 0, Generate, Policy, Ct)).Should().BeNull(); + (await cache.GetOrRevalidateAsync(Key, 0, Generate, Policy, Ct)).Should().BeNull(); + + calls.Should().Be(expectedCalls); + } + + [Fact] + public async Task Joined_callers_share_one_generator_run() + { + var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var calls = 0; + async Task> Generate(int _, RevalidationContext context, CancellationToken token) + { + Interlocked.Increment(ref calls); + await release.Task.WaitAsync(token); + return context.Modified("v1"); + } + + var first = _cache.GetOrRevalidateAsync(Key, 0, Generate, Policy, Ct).AsTask(); + var second = _cache.GetOrRevalidateAsync(Key, 0, Generate, Policy, Ct).AsTask(); + release.SetResult(); + + (await first).Should().Be("v1"); + (await second).Should().Be("v1"); + calls.Should().Be(1); + } + + [Fact] + public async Task NotModified_without_a_previous_value_fails_the_call_and_stores_nothing() + { + var act = async () => await _cache.GetOrRevalidateAsync(Key, 0, static (_, context, _) => Task.FromResult(context.NotModified()), Policy, Ct); + + await act.Should().ThrowAsync(); + (await _cache.GetCacheEntryAsync(Key, Policy, Ct)).Found.Should().BeFalse(); + } + + public void Dispose() => _cache.Dispose(); + + private Task> Recording(string value, RevalidationContext context, CancellationToken token) + { + _contexts.Add(context); + return Task.FromResult(context.Modified(value, "e:" + value, Modified1)); + } + + private MultilayerCache Build(InMemoryCacheOptions options) + { + options.TrackStatistics = false; + return RunTables.Track(new MultilayerCache( + KnownCacheProviderNames.InMemory, + NullCache.Instance, + new MemoryCacheFactory(_clock, NullLoggerFactory.Instance), + NullChangeTokenFactory.Instance, + NullTopicFactory.Instance, + NullCacheEventFactory.Instance, + _telemetry, + options, + options, + new CacheOptions { AppShortName = "test" }, + distributedLock: NullDistributedLock.Instance, + policyFactory: NullCachePolicyFactory.Instance, + clock: _clock, + logger: NullLogger.Instance)); + } + + private sealed class InterningEntryFactory(DateTimeOffset deadline) : ICacheEntryFactory + { + public DateTimeOffset Deadline { get; } = deadline; + + public TestCacheEntry? SharedEntry { get; private set; } + + public ICacheEntry Create(T value, DateTimeOffset expiration, IDictionary? properties = null) + { + if (typeof(T) == typeof(string) && value is "seed" && expiration == Deadline) + { + SharedEntry ??= new TestCacheEntry { Value = "seed", Expiration = expiration, Metadata = properties }; + return (ICacheEntry)SharedEntry; + } + + return new TestCacheEntry { Value = value, Expiration = expiration, Metadata = properties }; + } + } +} diff --git a/tests/UiPath.Caching.Tests/Redis/RedisCacheHoldsTests.cs b/tests/UiPath.Caching.Tests/Redis/RedisCacheHoldsTests.cs new file mode 100644 index 000000000..b55bbde94 --- /dev/null +++ b/tests/UiPath.Caching.Tests/Redis/RedisCacheHoldsTests.cs @@ -0,0 +1,90 @@ +using Microsoft.Extensions.DependencyInjection; +using UiPath.Caching.Config; +using UiPath.Caching.Tests.Fakes; + +namespace UiPath.Caching.Tests.Redis; + +[Collection("RedisIntegration")] +[Trait("Category", "Integration")] +public sealed class RedisCacheHoldsTests(RedisContainerFixture fixture) +{ + private static readonly CachePolicy Registered = new() { Serializer = new SerializerPolicy { Write = "registered" } }; + private static readonly CachePolicy Throwing = new() { Serializer = new SerializerPolicy { Write = "throwing" } }; + + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + [Theory] + [InlineData("value", false)] + [InlineData("value", true)] + [InlineData(null, false)] + public async Task It_is_true_for_the_bytes_of_the_same_value(string? value, bool registered) + { + using var provider = Build(); + var policy = registered ? Registered : null; + var (tier, stamp) = await StampAsync(provider, value, policy); + + tier.Holds(stamp, value, policy).Should().BeTrue(); + } + + [Fact] + public async Task It_is_false_for_another_value() + { + using var provider = Build(); + var (tier, stamp) = await StampAsync(provider, "held"); + + tier.Holds(stamp, "other", null).Should().BeFalse(); + } + + [Fact] + public void It_is_false_for_a_null_stamp() + { + using var provider = Build(); + var tier = (IStampedTier)Cache(provider); + + tier.Holds(null, null, null).Should().BeFalse(); + } + + [Fact] + public async Task It_is_false_when_the_serializer_throws() + { + using var provider = Build(); + var (tier, stamp) = await StampAsync(provider, "held"); + + tier.Holds(stamp, "held", Throwing).Should().BeFalse(); + } + + private static ICache Cache(ServiceProvider provider) => + provider.GetRequiredService().CreateCache(KnownCacheProviderNames.Redis); + + private static async Task<(IStampedTier Tier, object Stamp)> StampAsync(ServiceProvider provider, string? value, CachePolicy? policy = null) + { + var cache = Cache(provider); + var tier = (IStampedTier)cache; + CacheKey key = new($"holds-{Guid.NewGuid():N}"); + (await cache.SetAsync(key, value, policy, Ct)).Should().BeTrue(); + var (snapshot, stamp) = await tier.ReadStampedAsync(key, policy, Ct); + snapshot.Outcome.Should().Be(SnapshotOutcome.Found); + stamp.Should().NotBeNull(); + return (tier, stamp!); + } + + private ServiceProvider Build() + { + Assert.SkipUnless(fixture.Enabled, "Set RUN_REDIS_INTEGRATION_TESTS=1 to run."); + return new ServiceCollection() + .AddCaching( + b => + { + b.AddRedisConnection(o => o.ConnectionString = fixture.ConnectionString); + b.AddRedis(o => + { + o.CacheNullValues = true; + o.FormatNegotiation.Mode = FormatNegotiationMode.Force; + }); + b.AddValueSerializer("registered", [0x10], _ => new PassthroughValueSerializer(0x10)); + b.AddValueSerializer("throwing", [0x11], _ => new ThrowingValueSerializer(0x11)); + }, + o => o.AppShortName = "holds") + .BuildServiceProvider(); + } +} diff --git a/tests/UiPath.Caching.Tests/Redis/RevalidationRehydrateIntegrationTests.cs b/tests/UiPath.Caching.Tests/Redis/RevalidationRehydrateIntegrationTests.cs new file mode 100644 index 000000000..37196d4c0 --- /dev/null +++ b/tests/UiPath.Caching.Tests/Redis/RevalidationRehydrateIntegrationTests.cs @@ -0,0 +1,254 @@ +using Microsoft.Extensions.DependencyInjection; +using StackExchange.Redis; +using UiPath.Caching.Config; +using UiPath.Caching.Locking; +using UiPath.Caching.Telemetry; +using UiPath.Caching.Tests.Telemetry; + +namespace UiPath.Caching.Tests.Redis; + +[Collection("RedisIntegration")] +[Trait("Category", "Integration")] +public sealed class RevalidationRehydrateIntegrationTests(RedisContainerFixture fixture) : IDisposable +{ + private const string Triggered = "cache.rehydrate.triggered"; + private static readonly TimeSpan Lifetime = TimeSpan.FromMinutes(10); + private static readonly CachePolicy Policy = new() + { + DistributedExpiration = Lifetime, + RehydrateEnabled = true, + Rehydrate = new RehydrateOptions { Threshold = 0.8 }, + }; + + private readonly CacheKey _key = new($"rh-{Guid.NewGuid():N}"); + private readonly string _app = $"rh{Guid.NewGuid():N}"[..10]; + private readonly ManualTimeProvider _clock = new(fixture.TimeOrigin); + private readonly RecordingTelemetryProvider _telemetry = new(); + private readonly List _nodes = []; + + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + [Fact] + public async Task A_background_NotModified_that_lost_its_compare_and_set_does_not_fill_the_absent_key() + { + await using var raw = await ConnectAsync(); + var a = Node("a"); + var b = Node("b"); + var key = await SeedAgedAsync(a, raw); + var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + try + { + (await RevalidateAsync(a, async (context, token) => + { + entered.SetResult(); + await release.Task.WaitAsync(token); + return context.NotModified(); + })).Should().Be("A"); + _telemetry.Events.Should().Contain(e => e.Name == Triggered); + await entered.Task.WaitAsync(Ct); + await b.RemoveAsync(_key, Ct); + } + finally + { + release.SetResult(); + } + + await FinishedAsync(); + (await raw.GetDatabase().KeyExistsAsync(key)).Should().BeFalse(); + } + + [Fact] + public async Task A_background_run_over_an_absent_key_gets_an_empty_context_and_fills_the_key() + { + await using var raw = await ConnectAsync(); + var a = Node("a"); + var b = Node("b", sharedOnly: true); + await SeedAgedAsync(a, raw); + await b.RemoveAsync(_key, Ct); + var context = await RefreshAsync(a, static context => context.Modified("full")); + + context.HasPreviousValue.Should().BeFalse(); + (await b.GetAsync(_key, Policy, Ct)).Should().Be("full"); + } + + [Fact] + public async Task A_background_run_whose_adoption_read_failed_gets_an_empty_context() + { + await using var raw = await ConnectAsync(); + var a = Node("a"); + await SeedAgedAsync(a, raw); + var key = RawKey(raw); + var db = raw.GetDatabase(); + await db.KeyDeleteAsync(key); + await db.HashSetAsync(key, "unexpected-field", "value"); + await db.KeyExpireAsync(key, Lifetime); + + var context = await RefreshAsync(a, static context => context.Modified(null)); + + context.HasPreviousValue.Should().BeFalse(); + _telemetry.Events.Should().Contain(e => e.Name == "cache.rehydrate.adopt_read_failed" && e.Properties!["reason"] == "error"); + } + + [Fact] + public async Task A_background_NotModified_over_the_value_it_saw_extends_it_in_Redis() + { + await using var raw = await ConnectAsync(); + var a = Node("a"); + var key = await SeedAgedAsync(a, raw); + var context = await RefreshAsync(a, static context => context.NotModified()); + + context.PreviousValue.Should().Be("A"); + (await raw.GetDatabase().KeyTimeToLiveAsync(key)).Should().BeGreaterThan(TimeSpan.FromMinutes(9)); + } + + [Fact] + public async Task A_background_context_takes_the_local_validators_when_Redis_holds_the_same_bytes() + { + await using var raw = await ConnectAsync(); + var a = Node("a"); + await SeedAgedAsync(a, raw); + var context = await RefreshAsync(a, static context => context.NotModified()); + + context.HasPreviousValue.Should().BeTrue(); + context.PreviousValue.Should().Be("A"); + context.ETag.Should().Be("tag-A"); + } + + [Fact] + public async Task A_background_run_over_a_different_Redis_value_confirms_that_value_and_never_the_local_one() + { + await using var raw = await ConnectAsync(); + var a = Node("a"); + var b = Node("b", sharedOnly: true); + var key = await SeedAgedAsync(a, raw); + (await b.SetAsync(_key, "B", _clock.GetUtcNow().AddMinutes(1), Policy, Ct)).Should().BeTrue(); + var expiration = _clock.GetUtcNow().AddMinutes(4); + var context = await RefreshAsync(a, context => context.NotModified(expiration)); + + context.HasPreviousValue.Should().BeTrue(); + context.PreviousValue.Should().Be("B"); + context.ETag.Should().BeNull(); + var local = await a.GetCacheEntryAsync(_key, Policy, Ct); + local.Value.Should().Be("B"); + local.Expiration.Should().Be(expiration); + (await b.GetAsync(_key, Policy, Ct)).Should().Be("B"); + (await raw.GetDatabase().KeyTimeToLiveAsync(key)).Should().BeGreaterThan(TimeSpan.FromMinutes(3)); + } + + [Fact] + public async Task A_background_NotModified_of_a_cached_null_uses_the_confirmed_expiration() + { + await using var raw = await ConnectAsync(); + var a = Node("a", cacheNullValues: true); + var b = Node("b", sharedOnly: true, cacheNullValues: true); + await SeedAgedAsync(a, raw); + (await b.SetAsync(_key, null, _clock.GetUtcNow().AddMinutes(1), Policy, Ct)).Should().BeTrue(); + var expiration = _clock.GetUtcNow().AddMinutes(4); + + var context = await RefreshAsync(a, context => context.NotModified(expiration)); + + context.HasPreviousValue.Should().BeTrue(); + context.PreviousValue.Should().BeNull(); + var local = await a.GetCacheEntryAsync(_key, Policy, Ct); + local.Found.Should().BeTrue(); + local.Value.Should().BeNull(); + local.Expiration.Should().Be(expiration); + (await raw.GetDatabase().KeyTimeToLiveAsync(RawKey(raw))).Should().BeGreaterThan(TimeSpan.FromMinutes(3)); + } + + [Fact] + public async Task A_background_Modified_still_fills_an_absent_key() + { + await using var raw = await ConnectAsync(); + var a = Node("a"); + var b = Node("b", sharedOnly: true); + await SeedAgedAsync(a, raw); + await RefreshAsync(a, async context => + { + await b.RemoveAsync(_key, Ct); + return context.Modified("full"); + }); + + (await b.GetAsync(_key, Policy, Ct)).Should().Be("full"); + } + + public void Dispose() + { + foreach (var node in _nodes) + { + node.Dispose(); + } + } + + private Task> RefreshAsync(ICache a, Func, RevalidatedValue> generate) => + RefreshAsync(a, context => Task.FromResult(generate(context))); + + private async Task> RefreshAsync(ICache a, Func, Task>> generate) + { + var observed = new TaskCompletionSource>(TaskCreationOptions.RunContinuationsAsynchronously); + (await RevalidateAsync(a, (context, _) => + { + observed.SetResult(context); + return generate(context); + })).Should().Be("A"); + await FinishedAsync(); + return await observed.Task.WaitAsync(Ct); + } + + private async Task FinishedAsync() + { + _telemetry.Events.Should().Contain(e => e.Name == Triggered); + await _telemetry.Signal.UntilAsync( + () => _telemetry.Events.Any(e => e.Name is "cache.rehydrate.succeeded" or "cache.rehydrate.failed"), Ct); + _telemetry.Events.Should().Contain(e => e.Name == "cache.rehydrate.succeeded"); + } + + private async Task SeedAgedAsync(ICache a, ConnectionMultiplexer raw) + { + await RevalidateAsync(a, static (context, _) => Task.FromResult(context.Modified("A", "tag-A"))); + var key = RawKey(raw); + _clock.Advance(TimeSpan.FromMinutes(9)); + (await raw.GetDatabase().KeyExpireAsync(key, TimeSpan.FromMinutes(1))).Should().BeTrue(); + return key; + } + + private RedisKey RawKey(ConnectionMultiplexer raw) => RedisTestKeys.Keys(raw, $"*{_key.Name}").Single(); + + private ValueTask RevalidateAsync(ICache cache, Func, CancellationToken, Task>> generator) => + cache.GetOrRevalidateAsync, CancellationToken, Task>>>( + _key, generator, static (run, context, token) => run(context, token), Policy, Ct); + + private Task ConnectAsync() + { + Assert.SkipUnless(fixture.Enabled, "Set RUN_REDIS_INTEGRATION_TESTS=1 to run."); + return ConnectionMultiplexer.ConnectAsync(fixture.ConnectionString); + } + + private ICache Node(string name, bool sharedOnly = false, bool cacheNullValues = false) + { + var provider = new ServiceCollection().AddSingleton(_clock) + .AddSingleton(_telemetry) + .AddSingleton(NullDistributedLock.Instance) + .AddCaching( + b => + { + b.AddRedisConnection(o => o.ConnectionString = fixture.ConnectionString); + b.AddRedis(); + b.AddInMemoryRedis(o => + { + o.BroadcastEnable = false; + o.ClearLocalOnReconnect = false; + o.CacheNullValues = cacheNullValues; + }); + }, + o => + { + o.AppShortName = _app; + o.SourceUri = new Uri($"urn:{name}-{_app}"); + }) + .BuildServiceProvider(); + _nodes.Add(provider); + return provider.GetRequiredService().CreateCache(sharedOnly ? KnownCacheProviderNames.Redis : KnownCacheProviderNames.InMemoryRedis); + } +} diff --git a/tests/UiPath.Caching.Tests/RehydrationCoordinatorTests.cs b/tests/UiPath.Caching.Tests/RehydrationCoordinatorTests.cs index 94498653d..645dbd564 100644 --- a/tests/UiPath.Caching.Tests/RehydrationCoordinatorTests.cs +++ b/tests/UiPath.Caching.Tests/RehydrationCoordinatorTests.cs @@ -44,12 +44,15 @@ public void TryTrigger_returns_false_when_duration_is_zero_or_negative() sut.TryTrigger((CacheKey)"k", _clock.GetUtcNow().Add(Duration), RehydratePolicy(), TimeSpan.FromSeconds(-1), "cache", (_, _) => ValueTask.CompletedTask).Should().BeFalse(); } - [Fact] - public void TryTrigger_returns_false_when_entry_is_already_expired() + [Theory] + [InlineData(false)] + [InlineData(true)] + public void TryTrigger_returns_false_when_entry_is_already_expired(bool unboundedDuration) { var sut = NewCoordinator(); + var duration = unboundedDuration ? TimeSpan.MaxValue : Duration; - var triggered = sut.TryTrigger((CacheKey)"k", _clock.GetUtcNow().AddMinutes(-5), RehydratePolicy(), Duration, "cache", (_, _) => ValueTask.CompletedTask); + var triggered = sut.TryTrigger((CacheKey)"k", _clock.GetUtcNow().AddMinutes(-5), RehydratePolicy(), duration, "cache", (_, _) => ValueTask.CompletedTask); triggered.Should().BeFalse(); } diff --git a/tests/UiPath.Caching.Tests/RevalidationAllocationTests.cs b/tests/UiPath.Caching.Tests/RevalidationAllocationTests.cs new file mode 100644 index 000000000..3d794d82d --- /dev/null +++ b/tests/UiPath.Caching.Tests/RevalidationAllocationTests.cs @@ -0,0 +1,161 @@ +using Microsoft.Extensions.DependencyInjection; +using UiPath.Caching.Config; +using UiPath.Caching.Tests.Fakes; + +namespace UiPath.Caching.Tests; + +[Collection(AllocationCollection.Name)] +public sealed class RevalidationAllocationTests +{ + private const int Hits = 1000; + // Bytes per ordinary hit before the rehydrate threshold, measured on the base branch. + private const long OrdinaryRehydrateHitBytes = 432; + // Includes the revalidation run, validator metadata, suspended write frames, and fake inner-tier allocations up to the blocked write. + private const long MissBytes = 4528; + private static readonly CacheKey Key = new("k"); + private static readonly TimeSpan Lifetime = TimeSpan.FromHours(1); + private static readonly Task> Generated = Task.FromResult(default(RevalidationContext).Modified("v", "tag")); + private static readonly Func, CancellationToken, Task>> UnexpectedGenerator = + static (_, _, _) => throw new InvalidOperationException("A hit must not call the generator."); + + [Fact] + public Task A_hit_allocates_nothing() => AssertHitAllocationsAsync(rehydrate: false); + + [Fact] + public Task A_hit_before_the_rehydrate_threshold_allocates_nothing() => AssertHitAllocationsAsync(rehydrate: true); + + [Fact] + public async Task The_first_conditional_hit_on_an_ordinary_entry_allocates_nothing() + { + // Warm the hit path with an entry that already carries its lifetime. + await AssertHitAllocationsAsync(rehydrate: true); + var clock = new ManualTimeProvider(); + using var services = new ServiceCollection().AddSingleton(clock) + .AddCaching(b => b.AddMemory(o => o.TrackStatistics = false), o => o.AppShortName = "alloc") + .BuildServiceProvider(); + var cache = services.GetRequiredService().CreateCache(KnownCacheProviderNames.InMemory); + var policy = new CachePolicy + { + DistributedExpiration = Lifetime, + RehydrateEnabled = true, + Rehydrate = new RehydrateOptions { Threshold = 0.8 }, + }; + var token = TestContext.Current.CancellationToken; + await cache.SetAsync(Key, "v", policy, token); + + var before = GC.GetAllocatedBytesForCurrentThread(); + var hit = cache.GetOrRevalidateAsync(Key, 0, UnexpectedGenerator, policy, token); + var allocated = GC.GetAllocatedBytesForCurrentThread() - before; + + hit.IsCompletedSuccessfully.Should().BeTrue(); + (await hit).Should().Be("v"); + allocated.Should().Be(0); + } + + [Fact] + public async Task A_miss_stays_within_its_pinned_bytes() + { + using var peers = new CachePeers(); + var node = peers.Add("a"); + var policy = new CachePolicy(); + var token = TestContext.Current.CancellationToken; + var written = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + node.Inner.AfterWrite = written.Task; + var pending = new List(); + var fewest = long.MaxValue; + + try + { + for (var round = 0; round < 200; round++) + { + CacheKey key = $"r:{round:D3}"; + var before = GC.GetAllocatedBytesForCurrentThread(); + var miss = node.Cache.GetOrRevalidateAsync(key, 0, static (_, _, _) => Generated, policy, token); + var allocated = GC.GetAllocatedBytesForCurrentThread() - before; + miss.IsCompleted.Should().BeFalse(); + pending.Add(miss.AsTask()); + fewest = Math.Min(fewest, allocated); + } + } + finally + { + written.SetResult(); + await Task.WhenAll(pending); + } + + fewest.Should().BeLessThanOrEqualTo(MissBytes); + } + + [Fact] + public async Task An_ordinary_hit_before_the_rehydrate_threshold_stays_within_its_pinned_bytes() + { + var clock = new ManualTimeProvider(); + using var services = new ServiceCollection().AddSingleton(clock) + .AddCaching(b => b.AddMemory(o => o.TrackStatistics = false), o => o.AppShortName = "alloc") + .BuildServiceProvider(); + var cache = services.GetRequiredService().CreateCache(KnownCacheProviderNames.InMemory); + var policy = new CachePolicy + { + DistributedExpiration = Lifetime, + RehydrateEnabled = true, + Rehydrate = new RehydrateOptions { Threshold = 0.8 }, + }; + var token = TestContext.Current.CancellationToken; + await cache.GetOrAddAsync(Key, static _ => Task.FromResult("v"), policy, token); + clock.Advance(TimeSpan.FromMinutes(47)); + + MeasureHits(); + MeasureHits().Should().Be(Hits * OrdinaryRehydrateHitBytes); + + long MeasureHits() + { + var before = GC.GetAllocatedBytesForCurrentThread(); + for (var i = 0; i < Hits; i++) + { + var hit = cache.GetOrAddAsync(Key, static _ => throw new InvalidOperationException("A hit must not call the generator."), policy, token); + if (!hit.IsCompletedSuccessfully || hit.Result != "v") + { + throw new InvalidOperationException("A local hit must return the kept value synchronously."); + } + } + + return GC.GetAllocatedBytesForCurrentThread() - before; + } + } + + private static async Task AssertHitAllocationsAsync(bool rehydrate) + { + var clock = new ManualTimeProvider(); + using var services = new ServiceCollection().AddSingleton(clock) + .AddCaching(b => b.AddMemory(o => o.TrackStatistics = false), o => o.AppShortName = "alloc") + .BuildServiceProvider(); + var cache = services.GetRequiredService().CreateCache(KnownCacheProviderNames.InMemory); + var policy = new CachePolicy + { + DistributedExpiration = Lifetime, + RehydrateEnabled = rehydrate, + Rehydrate = new RehydrateOptions { Threshold = 0.8 }, + }; + var token = TestContext.Current.CancellationToken; + await cache.GetOrRevalidateAsync(Key, 0, static (_, _, _) => Generated, policy, token); + clock.Advance(TimeSpan.FromMinutes(47)); + + HitBytes(cache, policy, token); + HitBytes(cache, policy, token).Should().Be(0); + } + + private static long HitBytes(ICache cache, CachePolicy policy, CancellationToken token) + { + var before = GC.GetAllocatedBytesForCurrentThread(); + for (var i = 0; i < Hits; i++) + { + var hit = cache.GetOrRevalidateAsync(Key, 0, UnexpectedGenerator, policy, token); + if (!hit.IsCompletedSuccessfully || hit.Result != "v") + { + throw new InvalidOperationException("A local hit must return the kept value synchronously."); + } + } + + return GC.GetAllocatedBytesForCurrentThread() - before; + } +} diff --git a/tests/UiPath.Caching.Tests/RevalidationContextTests.cs b/tests/UiPath.Caching.Tests/RevalidationContextTests.cs new file mode 100644 index 000000000..04d9a7c4b --- /dev/null +++ b/tests/UiPath.Caching.Tests/RevalidationContextTests.cs @@ -0,0 +1,75 @@ +namespace UiPath.Caching.Tests; + +public sealed class RevalidationContextTests +{ + private static readonly ManualTimeProvider Clock = new(DateTimeOffset.UnixEpoch); + + [Fact] + public void A_default_context_has_no_previous_value() + { + var context = default(RevalidationContext); + + context.HasPreviousValue.Should().BeFalse(); + context.PreviousValue.Should().BeNull(); + context.ETag.Should().BeNull(); + context.LastModified.Should().BeNull(); + } + + [Fact] + public void NotModified_without_a_previous_value_throws() + { + var act = () => default(RevalidationContext).NotModified(); + + act.Should().Throw(); + } + + [Fact] + public void NotModified_returns_the_previous_value_and_its_validators() + { + var lastModified = Clock.GetUtcNow(); + var context = RevalidationContext.WithPrevious("v", "e1", lastModified); + + var result = context.NotModified(); + + context.HasPreviousValue.Should().BeTrue(); + result.Value.Should().Be("v"); + result.ETag.Should().Be("e1"); + result.LastModified.Should().Be(lastModified); + result.IsNotModified.Should().BeTrue(); + result.Expiration.Should().BeNull(); + } + + [Fact] + public void NotModified_takes_an_expiration() + { + var expiration = Clock.GetUtcNow().AddMinutes(1); + var context = RevalidationContext.WithPrevious("v"); + + context.NotModified(expiration).Expiration.Should().Be(expiration); + } + + [Fact] + public void Modified_carries_the_new_value_validators_and_expiration() + { + var lastModified = Clock.GetUtcNow(); + var expiration = lastModified.AddMinutes(1); + var context = RevalidationContext.WithPrevious("old", "old-tag", lastModified.AddMinutes(-1)); + + var result = context.Modified("new", "new-tag", lastModified, expiration); + + result.Value.Should().Be("new"); + result.ETag.Should().Be("new-tag"); + result.LastModified.Should().Be(lastModified); + result.Expiration.Should().Be(expiration); + result.IsNotModified.Should().BeFalse(); + } + + [Fact] + public void A_default_result_is_a_modified_null() + { + var result = default(RevalidatedValue); + + result.IsNotModified.Should().BeFalse(); + result.Value.Should().BeNull(); + } +} diff --git a/tests/UiPath.Caching.Tests/RevalidationFallbackTests.cs b/tests/UiPath.Caching.Tests/RevalidationFallbackTests.cs new file mode 100644 index 000000000..c1c44070f --- /dev/null +++ b/tests/UiPath.Caching.Tests/RevalidationFallbackTests.cs @@ -0,0 +1,136 @@ +using UiPath.Caching.Tests.Fakes; +using TypedFallbackState = (UiPath.Caching.RevalidatedValue State, System.Func, UiPath.Caching.RevalidationContext, System.Threading.CancellationToken, System.Threading.Tasks.Task>> Generator); + +namespace UiPath.Caching.Tests; + +public sealed class RevalidationFallbackTests +{ + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task A_cache_without_the_capability_runs_the_generator_with_no_previous_value(bool useNullCache) + { + using ICache cache = useNullCache ? NullCache.Instance : new RecordingCache(); + + var value = await cache.GetOrRevalidateAsync( + "k", + (context, token) => + { + context.HasPreviousValue.Should().BeFalse(); + token.Should().Be(Ct); + return Task.FromResult(context.Modified("v")); + }, + policy: null, + token: Ct); + + value.Should().Be("v"); + } + + [Fact] + public async Task The_fallback_passes_the_generator_expiration_and_SkipFailSafe_on() + { + using var recording = new RecordingCache(); + ICache cache = recording; + var clock = new ManualTimeProvider(DateTimeOffset.UnixEpoch); + var expiration = clock.GetUtcNow().AddMinutes(1); + + await cache.GetOrRevalidateAsync( + "k", + "v", + (value, context, _) => Task.FromResult(context.Modified(value, expiration: expiration) with { SkipFailSafe = true }), + policy: null, + token: Ct); + + var generated = recording.Generated.Should().BeOfType>().Subject; + generated.Value.Should().Be("v"); + generated.Expiration.Should().Be(expiration); + generated.SkipFailSafe.Should().BeTrue(); + } + + [Fact] + public async Task The_fallback_rejects_a_NotModified_from_another_context() + { + using var recording = new RecordingCache(); + ICache cache = recording; + var saved = RevalidationContext.WithPrevious("old").NotModified(); + + var act = async () => await cache.GetOrRevalidateAsync>( + "k", + saved, + static (result, _, _) => Task.FromResult(result), + policy: null, + token: Ct); + + await act.Should().ThrowAsync(); + recording.Generated.Should().BeNull(); + } + + [Fact] + public async Task The_typed_fallback_rejects_a_NotModified_from_another_context() + { + var cache = Substitute.For>(); + using var store = new DictionaryCache(); + CacheKey key = "k"; + var saved = RevalidationContext.WithPrevious("old").NotModified(); +#pragma warning disable CA2012 // Returns configures the substitute's call. The placeholder ValueTask is never consumed. + cache.GetOrAddWithExpirationAsync( + key, + Arg.Any(), + Arg.Any>>>(), + Ct) + .Returns(call => GenerateAndStoreAsync(call.Arg(), call.Arg>>>())); +#pragma warning restore CA2012 + + async ValueTask GenerateAndStoreAsync(TypedFallbackState state, Func>> generator) + { + var generated = await generator(state, Ct); + store.Seed(key, generated.Value); + return generated.Value; + } + + var act = async () => await cache.GetOrRevalidateAsync(key, saved, static (result, _, _) => Task.FromResult(result), Ct); + + await act.Should().ThrowAsync(); + store.Contains(key).Should().BeFalse(); + } + + [Fact] + public async Task The_typed_cache_passes_its_policy_and_its_key_strategy() + { + using var recording = new RecordingCache(); + using var cacheFactory = Substitute.For(); + cacheFactory.CreateCache().Returns(recording); + var policyFactory = Substitute.For(); + var policy = new CachePolicy { LocalExpiration = TimeSpan.FromMinutes(3) }; + policyFactory.Resolve("named").Returns(policy); + ICache cache = new Cache(cacheFactory, new PrefixCacheKeyStrategy("custom", ':'), policyFactory, "named"); + + await cache.GetOrRevalidateAsync("k", "v", static (value, context, _) => Task.FromResult(context.Modified(value)), Ct); + + recording.Key.Name.Should().Be("custom:k"); + recording.Policy.Should().BeSameAs(policy); + } + + private sealed class RecordingCache : DictionaryCache, ICache + { + public CacheKey Key { get; private set; } + public CachePolicy? Policy { get; private set; } + public object? Generated { get; private set; } + + async ValueTask ICache.GetOrAddWithExpirationAsync( + CacheKey cacheKey, + TState state, + Func>> generator, + CachePolicy? policy, + CancellationToken token) where T : default + { + Key = cacheKey; + Policy = policy; + var generated = await generator(state, token); + Generated = generated; + return generated.Value; + } + } +} diff --git a/tests/UiPath.Caching.Tests/SpanKeyDefaultWriteTests.cs b/tests/UiPath.Caching.Tests/SpanKeyDefaultWriteTests.cs index 527396755..3acfc6c5d 100644 --- a/tests/UiPath.Caching.Tests/SpanKeyDefaultWriteTests.cs +++ b/tests/UiPath.Caching.Tests/SpanKeyDefaultWriteTests.cs @@ -169,6 +169,8 @@ public void Every_single_key_member_of_a_cache_interface_has_an_interpolated_for var interpolatedForms = methods.Where(m => m.GetParameters().Any(p => p.ParameterType.GetElementType() == typeof(CacheKeyHandler))).Select(m => Shape(m, typeof(CacheKeyHandler))).ToHashSet(); var missing = methods + // Revalidation is single-key and has no interpolated form. + .Where(m => m.Name != nameof(ICache.GetOrRevalidateAsync)) .Where(m => m.GetParameters().Any(p => p.ParameterType == typeof(CacheKey))) .Select(m => Shape(m, typeof(CacheKey))) .Where(shape => !interpolatedForms.Contains(shape)) diff --git a/tests/UiPath.Caching.Tests/TestCacheEntryFactory.cs b/tests/UiPath.Caching.Tests/TestCacheEntryFactory.cs index f50bf979b..d0dfa193f 100644 --- a/tests/UiPath.Caching.Tests/TestCacheEntryFactory.cs +++ b/tests/UiPath.Caching.Tests/TestCacheEntryFactory.cs @@ -5,3 +5,12 @@ internal class TestCacheEntryFactory : ICacheEntryFactory public ICacheEntry Create(T value, DateTimeOffset expiration, IDictionary? properties = default) => new TestCacheEntry { Expiration = expiration, Value = value, Metadata = properties }; } + +/// Hands every entry to the built-in factory; , when given, replaces the supplied properties. +internal sealed class DelegatingCacheEntryFactory(IDictionary? metadata = null) : ICacheEntryFactory +{ + private readonly CacheEntryFactory _inner = new(); + + public ICacheEntry Create(T value, DateTimeOffset expiration, IDictionary? properties = default) => + _inner.Create(value, expiration, metadata ?? properties); +}