Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<T>` gain sealed `GetOrRevalidateAsync` overloads for conditional refresh. The generator receives a `RevalidationContext<T>` with the previous value and its `ETag` and `LastModified` validators, and returns a `RevalidatedValue<T>` 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.
Expand Down
58 changes: 58 additions & 0 deletions docs/how-to/choosing-a-get-or-add-overload.md
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,64 @@ its own name because a `GetOrAddAsync` overload taking `Func<CancellationToken,
every generator that only throws or returns `default` — `_ => 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<T>` and returns a `RevalidatedValue<T>`. 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<char>` 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
Expand Down
3 changes: 2 additions & 1 deletion docs/how-to/resilience.md
Original file line number Diff line number Diff line change
Expand Up @@ -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: { ... }`:

Expand Down
2 changes: 2 additions & 0 deletions docs/reference/glossary.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,4 +76,6 @@ Alphabetical lookup for terms used across the docs.

**Two surfaces** — `ICache<T>` / `IHashCache<T>` (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<T>.Modified`; a later `GetOrRevalidateAsync` generator receives them on its `RevalidationContext<T>` 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.
10 changes: 10 additions & 0 deletions docs/reference/interfaces.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,10 @@ public interface ICache<T>

ValueTask<T?> GetOrAddAsync(CacheKey cacheKey, Func<CancellationToken, Task<T?>> generator, DateTimeOffset expiration, CancellationToken token = default);

ValueTask<T?> GetOrRevalidateAsync(CacheKey cacheKey, Func<RevalidationContext<T>, CancellationToken, Task<RevalidatedValue<T>>> generator, CancellationToken token = default);

ValueTask<T?> GetOrRevalidateAsync<TState>(CacheKey cacheKey, TState state, Func<TState, RevalidationContext<T>, CancellationToken, Task<RevalidatedValue<T>>> generator, CancellationToken token = default);

ValueTask<KeyValuePair<TState, T?>[]> GetOrAddAsync<TState>(KeyValuePair<CacheKey, TState>[] entries, Func<TState[], CancellationToken, Task<KeyValuePair<TState, T?>[]>> generator, CancellationToken token = default) where TState : notnull;

ValueTask<KeyValuePair<TState, T?>[]> GetOrAddAsync<TState>(KeyValuePair<CacheKey, TState>[] entries, Func<TState[], CancellationToken, Task<KeyValuePair<TState, T?>[]>> generator, TimeSpan expiration, CancellationToken token = default) where TState : notnull;
Expand Down Expand Up @@ -130,6 +134,10 @@ public interface ICache : IDisposable

ValueTask<T?> GetOrAddAsync<T>(CacheKey cacheKey, Func<CancellationToken, Task<T?>> generator, DateTimeOffset expiration, CachePolicy? policy, CancellationToken token = default);

ValueTask<T?> GetOrRevalidateAsync<T>(CacheKey cacheKey, Func<RevalidationContext<T>, CancellationToken, Task<RevalidatedValue<T>>> generator, CachePolicy? policy, CancellationToken token = default);

ValueTask<T?> GetOrRevalidateAsync<T, TState>(CacheKey cacheKey, TState state, Func<TState, RevalidationContext<T>, CancellationToken, Task<RevalidatedValue<T>>> generator, CachePolicy? policy, CancellationToken token = default);

ValueTask<KeyValuePair<TState, T?>[]> GetOrAddAsync<T, TState>(KeyValuePair<CacheKey, TState>[] entries, Func<TState[], CancellationToken, Task<KeyValuePair<TState, T?>[]>> generator, CachePolicy? policy, CancellationToken token = default)
where TState : notnull;

Expand Down Expand Up @@ -185,6 +193,8 @@ public interface ICache : IDisposable

`ICache` is the dynamic-key, dynamic-type cache surface. Unlike `ICache<T>`, 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<T>`. `Modified` or `NotModified` returns a `RevalidatedValue<T>`, 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
Expand Down
56 changes: 56 additions & 0 deletions src/UiPath.Caching.Abstractions/CompatibilitySuppressions.xml
Original file line number Diff line number Diff line change
Expand Up @@ -421,6 +421,20 @@
<Right>lib/net10.0/UiPath.Caching.Abstractions.dll</Right>
<IsBaselineSuppression>true</IsBaselineSuppression>
</Suppression>
<Suppression>
<DiagnosticId>CP0006</DiagnosticId>
<Target>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)</Target>
<Left>lib/net10.0/UiPath.Caching.Abstractions.dll</Left>
<Right>lib/net10.0/UiPath.Caching.Abstractions.dll</Right>
<IsBaselineSuppression>true</IsBaselineSuppression>
</Suppression>
<Suppression>
<DiagnosticId>CP0006</DiagnosticId>
<Target>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)</Target>
<Left>lib/net10.0/UiPath.Caching.Abstractions.dll</Left>
<Right>lib/net10.0/UiPath.Caching.Abstractions.dll</Right>
<IsBaselineSuppression>true</IsBaselineSuppression>
</Suppression>
<Suppression>
<DiagnosticId>CP0006</DiagnosticId>
<Target>M:UiPath.Caching.ICache.RefreshAsync``1(UiPath.Caching.CacheKeyHandler@,System.DateTimeOffset,UiPath.Caching.CachePolicy,System.Threading.CancellationToken)</Target>
Expand Down Expand Up @@ -799,6 +813,20 @@
<Right>lib/net10.0/UiPath.Caching.Abstractions.dll</Right>
<IsBaselineSuppression>true</IsBaselineSuppression>
</Suppression>
<Suppression>
<DiagnosticId>CP0006</DiagnosticId>
<Target>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)</Target>
<Left>lib/net10.0/UiPath.Caching.Abstractions.dll</Left>
<Right>lib/net10.0/UiPath.Caching.Abstractions.dll</Right>
<IsBaselineSuppression>true</IsBaselineSuppression>
</Suppression>
<Suppression>
<DiagnosticId>CP0006</DiagnosticId>
<Target>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)</Target>
<Left>lib/net10.0/UiPath.Caching.Abstractions.dll</Left>
<Right>lib/net10.0/UiPath.Caching.Abstractions.dll</Right>
<IsBaselineSuppression>true</IsBaselineSuppression>
</Suppression>
<Suppression>
<DiagnosticId>CP0006</DiagnosticId>
<Target>M:UiPath.Caching.ICache`1.RefreshAsync(UiPath.Caching.CacheKeyHandler@,System.DateTimeOffset,System.Threading.CancellationToken)</Target>
Expand Down Expand Up @@ -1905,6 +1933,20 @@
<Right>lib/net8.0/UiPath.Caching.Abstractions.dll</Right>
<IsBaselineSuppression>true</IsBaselineSuppression>
</Suppression>
<Suppression>
<DiagnosticId>CP0006</DiagnosticId>
<Target>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)</Target>
<Left>lib/net8.0/UiPath.Caching.Abstractions.dll</Left>
<Right>lib/net8.0/UiPath.Caching.Abstractions.dll</Right>
<IsBaselineSuppression>true</IsBaselineSuppression>
</Suppression>
<Suppression>
<DiagnosticId>CP0006</DiagnosticId>
<Target>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)</Target>
<Left>lib/net8.0/UiPath.Caching.Abstractions.dll</Left>
<Right>lib/net8.0/UiPath.Caching.Abstractions.dll</Right>
<IsBaselineSuppression>true</IsBaselineSuppression>
</Suppression>
<Suppression>
<DiagnosticId>CP0006</DiagnosticId>
<Target>M:UiPath.Caching.ICache.RefreshAsync``1(UiPath.Caching.CacheKeyHandler@,System.DateTimeOffset,UiPath.Caching.CachePolicy,System.Threading.CancellationToken)</Target>
Expand Down Expand Up @@ -2283,6 +2325,20 @@
<Right>lib/net8.0/UiPath.Caching.Abstractions.dll</Right>
<IsBaselineSuppression>true</IsBaselineSuppression>
</Suppression>
<Suppression>
<DiagnosticId>CP0006</DiagnosticId>
<Target>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)</Target>
<Left>lib/net8.0/UiPath.Caching.Abstractions.dll</Left>
<Right>lib/net8.0/UiPath.Caching.Abstractions.dll</Right>
<IsBaselineSuppression>true</IsBaselineSuppression>
</Suppression>
<Suppression>
<DiagnosticId>CP0006</DiagnosticId>
<Target>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)</Target>
<Left>lib/net8.0/UiPath.Caching.Abstractions.dll</Left>
<Right>lib/net8.0/UiPath.Caching.Abstractions.dll</Right>
<IsBaselineSuppression>true</IsBaselineSuppression>
</Suppression>
<Suppression>
<DiagnosticId>CP0006</DiagnosticId>
<Target>M:UiPath.Caching.ICache`1.RefreshAsync(UiPath.Caching.CacheKeyHandler@,System.DateTimeOffset,System.Threading.CancellationToken)</Target>
Expand Down
15 changes: 15 additions & 0 deletions src/UiPath.Caching.Abstractions/ICache.GetOrAdd.cs
Original file line number Diff line number Diff line change
Expand Up @@ -393,4 +393,19 @@ sealed ValueTask<CacheResult<T>> GetOrAddResultAsync<T, TState>(ref CacheKeyHand
cacheKey.Return();
}
}

/// <summary>Gets a cached value or runs a generator that can revalidate a previous value.</summary>
sealed ValueTask<T?> GetOrRevalidateAsync<T>(CacheKey cacheKey, Func<RevalidationContext<T>, CancellationToken, Task<RevalidatedValue<T>>> generator, CachePolicy? policy, CancellationToken token = default) =>
GetOrRevalidateAsync<T, Func<RevalidationContext<T>, CancellationToken, Task<RevalidatedValue<T>>>>(cacheKey, generator, static (g, context, ct) => g(context, ct), policy, token);

/// <summary>Gets a cached value or runs a stateful generator that can revalidate a previous value.</summary>
sealed ValueTask<T?> GetOrRevalidateAsync<T, TState>(CacheKey cacheKey, TState state, Func<TState, RevalidationContext<T>, CancellationToken, Task<RevalidatedValue<T>>> generator, CachePolicy? policy, CancellationToken token = default) =>
this is IRevalidatingCache source
? source.GetOrRevalidateAsync(cacheKey, state, generator, policy, token)
: GetOrAddWithExpirationAsync<T, (TState State, Func<TState, RevalidationContext<T>, CancellationToken, Task<RevalidatedValue<T>>> Generator)>(
cacheKey,
(state, generator),
static async (s, ct) => (await s.Generator(s.State, default, ct).ConfigureAwait(false)).ValidateContext(null).ToGenerated(),
policy,
token);
}
14 changes: 14 additions & 0 deletions src/UiPath.Caching.Abstractions/ICacheOfT.GetOrAdd.cs
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,20 @@ public partial interface ICache<T>
}
}

/// <summary>Gets a cached value or runs a generator that can revalidate a previous value.</summary>
sealed ValueTask<T?> GetOrRevalidateAsync(CacheKey cacheKey, Func<RevalidationContext<T>, CancellationToken, Task<RevalidatedValue<T>>> generator, CancellationToken token = default) =>
GetOrRevalidateAsync(cacheKey, generator, static (g, context, ct) => g(context, ct), token);

/// <summary>Gets a cached value or runs a stateful generator that can revalidate a previous value.</summary>
sealed ValueTask<T?> GetOrRevalidateAsync<TState>(CacheKey cacheKey, TState state, Func<TState, RevalidationContext<T>, CancellationToken, Task<RevalidatedValue<T>>> generator, CancellationToken token = default) =>
this is IRevalidatingCache<T> 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);

/// <summary>Reads, and on a miss runs <paramref name="generator"/> as <c>GetOrAddAsync</c> does; reports whether this call's generator produced the value and when the entry expires.</summary>
sealed ValueTask<CacheResult<T>> GetOrAddResultAsync(CacheKey cacheKey, Func<CancellationToken, Task<T?>> generator, CancellationToken token = default)
{
Expand Down
6 changes: 6 additions & 0 deletions src/UiPath.Caching.Abstractions/IRevalidatingCache.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
namespace UiPath.Caching;

internal interface IRevalidatingCache
{
ValueTask<T?> GetOrRevalidateAsync<T, TState>(CacheKey cacheKey, TState state, Func<TState, RevalidationContext<T>, CancellationToken, Task<RevalidatedValue<T>>> generator, CachePolicy? policy, CancellationToken token);
}
Loading