diff --git a/CHANGELOG.md b/CHANGELOG.md index 375f2646..4c53c8e2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -41,7 +41,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) - **The router hosts a bridge to the older client's invalidation channel.** `RouterBuilder.UseChannelBridge(IChannelBridge)` takes the application's adapter. Every key write, delete and create the router commits, and every clear, is published on it as a `BridgeMessage` (`Key`, `Clear`) carrying the router's identity, on either path and in `BypassLibrary`, since the bridge needs no started library. A received `Key` message evicts that key's local copy, a `Clear` drops the cache's local copies and a `Tag` drops every cache's, since the router keeps no tags; a message carrying the router's own identity is ignored, and nothing received is published again, so no echo can start. A publish runs off the caller's thread and is cancelled at the source timeout, at most 16 run at once by default (more are dropped; `PublishAsync` must not block), a throwing `Subscribe` is retried in the background, and every failure is counted (`bridge`), never thrown; the local cap bounds how long a peer serves its copy. The adapter for a real older client is the application's. See [Router](docs/how-to/router.md). - **A router group can be pinned to the library path, and a switch is durable.** `RouterBuilder.UsePinWhen` pins groups (polled about once a second): a pinned group ignores bypass and the group predicate and never falls to the source, answering unavailable instead. A node advertises `pin=` only after calls that started on the old path have ended, with an `ap` token naming its application so applications sharing one node hash do not count each other. The switch state of a group is a durable Redis key, `{prefix}mg:{app:group}:sw`, recorded by a script when a format write needs it and only while every live node's acknowledgement record is unchanged, and a withdrawal is recorded in the same step as the read that confirms it (the pin needs scripts); a switched group stays on the library or unavailable through a restart, a failed library start, a throwing predicate and bypass, which changes the router's rule that a throwing predicate means the source. State is read before the first call and refreshed; an unknown state fails a group that is not pinned closed. `IFormatWriteGate` is a new seam: a registered gate holds non-JSON value writes while it returns a reason, as part of the existing hold, including on a custom serializer proxy, and a gate that closes, even briefly, restarts the hold. The router's gate opens only when every group is pinned. Counter path reasons `pin` and `pin_state_unknown`. See [Router](docs/how-to/router.md). - **The stream maintainer removes the consumer groups of departed nodes.** A group is named for its node, so the maintainer checks the node list once per pass (only when a stream has a group with consumers) and quarantines, then deletes, a group whose node left (`left=1`), whose entry is older than the gone window, or, on Redis 7.2 and later in a fleet that advertises, whose entry was pruned and whose consumers have all been idle past the gone window and the quarantine. Everything else is kept, as is every group while the node list cannot be read. Metric `Caching.Stats.DepartedGroupDeleted` by reason. Before this, groups of crashed nodes stayed on quiet streams for good. See [Broadcast](docs/how-to/broadcast.md). -- **An inventory by reason and a bounded sweep of stored values.** `RedisCacheProvider.CountFormatsByReasonAsync(keyPattern, token)` (or `(keyPattern, group, token)`, which sets the `group` tag) returns a `FormatInventoryReport` (`ByFormat`, `ByReason`, `Scanned`) whose reasons are `format_json`, `format_`, `format_unknown`, `empty`, `oversize`, `no_ttl` and `hash_sampled`; each string costs a `PTTL` and a headerless one a `STRLEN`, so it is for an operator and not for a request. `SweepFormatsAsync(keyPattern, options, token)` rewrites strings stored in another format into the default policy's write format in place, with the conversion of `MigrateOnRead`: lossless check, compare-and-set that keeps the exact TTL, transaction when scripts are refused, no origin call and no event, so a writer or a delete that comes meanwhile wins and no key is created. It takes its own `FormatSweepOptions.RatePerSecond`, shares the one-minute claim window and byte budget of `MigrateOnRead`, asks the node list again for each key (the first refusal ends the pass), and a `Budget` and a `Cursor` make it resumable (`FormatSweepReport.NextCursor`, `Completed`). It leaves the empty, `default(T)`, oversize and lossy values and reports each under its reason; hashes are never swept (only the inventory reports them, as `hash_sampled`). Metrics `cache.format.sweep{outcome,group}` and `cache.format.inventory{reason,group}`. `CountFormatsAsync` and `CountFormatsByKeyAsync` are unchanged. See [concepts](docs/concepts.md#counting-by-reason-and-sweeping-what-reads-do-not-reach). +- **An inventory by reason and a bounded sweep of stored values.** `RedisCacheProvider.CountFormatsByReasonAsync(keyPattern, token)` (or `(keyPattern, group, token)`, which sets the `group` tag) returns a `FormatInventoryReport` (`ByFormat`, `ByReason`, `Scanned`) whose reasons are `format_json`, `format_`, `format_unknown`, `empty`, `oversize`, `no_ttl` and `hash_sampled`; each string costs a `PTTL` and a headerless one a `STRLEN`, so it is for an operator and not for a request. `SweepFormatsAsync(keyPattern, options, token)` rewrites strings stored in another format into the default policy's write format in place, with the conversion of `MigrateOnRead`: lossless check, compare-and-set that keeps the exact TTL, transaction when scripts are refused, no origin call and no event, so a writer or a delete that comes meanwhile wins and no key is created. It takes its own `FormatSweepOptions.RatePerSecond`, shares the one-minute claim window and byte budget of `MigrateOnRead`, asks the node list again for each key (the first refusal ends the pass), and a `Budget` and a `Cursor` make it resumable (`FormatSweepReport.NextCursor`, `Completed`). It leaves the empty, `default(T)`, oversize and lossy values and reports each under its reason; hashes are never swept (only the inventory reports them, as `hash_sampled`). Metrics `cache.format.sweep{outcome,group}` and `cache.format.inventory{reason,group}`. `CountFormatsAsync` and `CountFormatsByKeyAsync` are unchanged. Every inventory counts an entry frame as `frame`, and one with a stale window as `frame_windowed` too; the sweep leaves frames as they are and counts them in `FormatSweepReport.Framed`. See [concepts](docs/concepts.md#counting-by-reason-and-sweeping-what-reads-do-not-reach). - **`IHeaderFreeSerializerProxy`** marks a custom byte serializer proxy whose values never start with a format header byte. Such a proxy is treated as the default JSON proxy is: reads tell its values from a registered format by the first byte under every policy, the node advertises the formats it reads instead of `nosniff`, a write the format negotiation holds back falls back to the proxy's bytes, and `MigrateOnRead` converts its values when the proxy writes the value back byte for byte. The router marks its envelope this way, and an envelope write whose first byte would read as a header fails with `InvalidOperationException`. - **A router group can write MessagePack while the others keep the envelope.** `RouterBuilder.UseValueSerializers` registers value serializers in the router's stack and `UseWriteFormatWhen(group => "messagepack" | "json" | null)` is a live setting read on every library write; both need `UsePinWhen`. A group writes MessagePack only while it is pinned, acknowledged and switched and the gate is open, and the envelope otherwise, including when the setting throws or names an unknown format. The gate now covers the groups that ask for MessagePack, so a group that does not ask holds nothing and is never recorded as switched; with no `UseWriteFormatWhen`, the gate is over every group as before. With `UseWriteFormatWhen`, the stack's format negotiation takes `Redis:FormatNegotiation` from the router's configuration section, as the pin already validated it; a router without it keeps the stack's own defaults, so a malformed section still only skips the advertisement. A setting that throws clears the group's wanted bit, so the group holds the gate no longer, and a read of a group that is not switched and durable carries the envelope policy, so a default `MigrateOnRead` never rewrites it. See [Router](docs/how-to/router.md). - **`CacheKey.Verbatim(name)`** builds a key whose name is exactly the text given: no trim, no casing change, whatever `CacheKey.DefaultCasing` is. It reports the new `CacheKeyCasing.Verbatim` value (code that treats "not `Sensitive`" as insensitive must handle it), which `WithName` and the library's key strategies carry over, so the Redis key, local key and event key hold the given name. A key prefix is still lowercased by `PrefixCacheKeyStrategy` and `PrefixRedisKeyStrategy`, so the guarantee covers the name only. A custom `ICacheKeyStrategy` must build its result with `WithName` to keep it. A null, empty or whitespace-only name throws `ArgumentException`; `WithName` with whitespace on a verbatim key throws too, where other modes return an empty key. `Verbatim` is not a valid `CacheOptions.KeyCasing`. Peer events now match a key by ordinal comparison, so keys that differ only in case no longer share invalidations. `RedisCacheProvider.CountFormatsByKeyAsync(CacheKey)` counts a verbatim pattern. `CacheKeyComparer.Insensitive` folds verbatim keys too. A strategy that returns verbatim keys must decline the span path (`ISpanCacheKeyStrategy.TryGetCacheKey` returns false), and the `IDistributedCache` adapter trims the caller's key before its strategy runs. @@ -81,7 +81,9 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) - **`GeneratedValue` equality and `ToString` include `SkipFailSafe`.** Two values that differ only in it are no longer equal. -- **A value serializer declares its format ids when it is registered.** `AddValueSerializer(name, formatIds, factory)` checks the ids at the call: `0x01`-`0x0F` (except `0x09`, `0x0A`, `0x0D`), `0x10`-`0x1E` or `0x100`-`0x1FF`, one header length, none claimed twice, and a failing call registers nothing. The serializer's `FormatIds` must then equal them as a set, with no id repeated, or the registry build throws an `InvalidOperationException` that names both lists. The ids `0x01`-`0x0F` are allocated by the table in [docs/reference/format-ids.md](docs/reference/format-ids.md) and open to any serializer, not only this repository's own. The core names no serializer package: `MessagePackFormats` in `UiPath.Caching.MessagePack` holds `Value` (`0x02`), `ValueLz4` (`0x03`), `Event` (`0x02`) and `ValueIds`. A body that starts with any format header byte, not only `0x02`, `0x03` and the consumer ids, counts as a format this node cannot read: a Pub/Sub or stream event with such a first byte is a topic loss instead of being skipped. `ICacheValueSerializer` documents that `Serialize` must be deterministic. +- **A value serializer declares its format ids when it is registered.** `AddValueSerializer(name, formatIds, factory)` checks the ids at the call: `0x01`-`0x0C` (except `0x09` and `0x0A`), `0x10`-`0x1E` or `0x100`-`0x1FF`, one header length, none claimed twice, and a failing call registers nothing. The serializer's `FormatIds` must then equal them as a set, with no id repeated, or the registry build throws an `InvalidOperationException` that names both lists. Any serializer can claim an allocated id listed in the [format id table](docs/reference/format-ids.md). The library reserves `0x0E` for the entry frame and `0x0F` for a remove tombstone. The core names no serializer package: `MessagePackFormats` in `UiPath.Caching.MessagePack` holds `Value` (`0x02`), `ValueLz4` (`0x03`), `Event` (`0x02`) and `ValueIds`. A body that starts with any format header byte, not only `0x02`, `0x03` and the consumer ids, counts as a format this node cannot read: a Pub/Sub or stream event with such a first byte is a topic loss instead of being skipped. `ICacheValueSerializer` documents that `Serialize` must be deterministic. + +- **A peer drops its local copy on a refresh event.** On an `InMemoryRedis` cache, a node that receives another node's refresh or metadata update for a key it holds no longer renews its local copy with the expiration the event carries, which Redis may not have accepted. It drops the copy, and its next read of the key takes the value and its expiration from Redis. That costs one Redis read per node that held the key and reads it again, and the dropped copy takes its `ETag` and `LastModified` validators with it. The `InMemory` provider and the hash caches renew the copy as before. ### Added diff --git a/benchmarks/UiPath.Caching.Benchmarks/DistributedCacheBenchmark.cs b/benchmarks/UiPath.Caching.Benchmarks/DistributedCacheBenchmark.cs index 5b07aa35..a5f56415 100644 --- a/benchmarks/UiPath.Caching.Benchmarks/DistributedCacheBenchmark.cs +++ b/benchmarks/UiPath.Caching.Benchmarks/DistributedCacheBenchmark.cs @@ -7,6 +7,7 @@ using UiPath.Caching.Config; namespace UiPath.Caching.Benchmarks; +#if NET9_0_OR_GREATER [MemoryDiagnoser] [GroupBenchmarksBy(BenchmarkLogicalGroupRule.ByCategory)] @@ -67,3 +68,4 @@ public ValueTask TryGet() [Benchmark, BenchmarkCategory("Write")] public ValueTask SetSequence() => _buffered.SetAsync(Key, _sequence, _options); } +#endif diff --git a/benchmarks/UiPath.Caching.Benchmarks/FakeRedisConnector.cs b/benchmarks/UiPath.Caching.Benchmarks/FakeRedisConnector.cs index afe113d6..0c3f98fe 100644 --- a/benchmarks/UiPath.Caching.Benchmarks/FakeRedisConnector.cs +++ b/benchmarks/UiPath.Caching.Benchmarks/FakeRedisConnector.cs @@ -59,6 +59,15 @@ public void ForgetLastWrite() } } + /// Wraps the value most recently SET in a windowed frame and gives its key a TTL, for the anchored read. + public void FrameLastWrite(DateTimeOffset expiration, TimeSpan window, TimeSpan timeToLive) + { + var key = _store.LastSet!.Value; + var inner = (byte[])_store.Values[key]!; + _store.Values[key] = EntryFrame.Write(inner, expiration, window, validators: null); + _store.TimeToLives[key] = timeToLive; + } + public void ForceReconnect() { } @@ -72,6 +81,7 @@ internal sealed class FakeRedisStore : IDisposable { public readonly ConcurrentDictionary Values = new(); public readonly ConcurrentDictionary Hashes = new(); + public readonly ConcurrentDictionary TimeToLives = new(); public long GetCount; public RedisKey? LastSet; private readonly BlockingCollection<(TaskCompletionSource Reply, RedisValue Value)> _replies = []; @@ -125,6 +135,21 @@ public static T Create(FakeRedisStore store) return _store.Get(key); } + if (method.Name == "KeyTimeToLiveAsync" && args is [RedisKey ttlKey, ..]) + { + return Task.FromResult(_store.TimeToLives.TryGetValue(ttlKey, out var ttl) ? (TimeSpan?)ttl : null); + } + + if (method.Name == "CreateTransaction") + { + return FakeProxy.Create(_store); + } + + if (method.Name == "ExecuteAsync" && typeof(T) == typeof(ITransaction)) + { + return Task.FromResult(true); + } + if (method.Name == "HashGetAllAsync" && args is [RedisKey hashKey, ..]) { return Task.FromResult(_store.Hashes.TryGetValue(hashKey, out var entries) ? entries : []); diff --git a/benchmarks/UiPath.Caching.Benchmarks/ObservedHitBenchmark.cs b/benchmarks/UiPath.Caching.Benchmarks/ObservedHitBenchmark.cs new file mode 100644 index 00000000..f568ff5a --- /dev/null +++ b/benchmarks/UiPath.Caching.Benchmarks/ObservedHitBenchmark.cs @@ -0,0 +1,91 @@ +using BenchmarkDotNet.Attributes; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.Hosting; +using UiPath.Caching.Config; +using UiPath.Caching.Redis; + +namespace UiPath.Caching.Benchmarks; + +/// A local hit on an observed entry: the layered cache adopted a windowed frame with a TTL of one day, by key and by the span form. +[MemoryDiagnoser] +[MarkdownExporterAttribute.GitHub] +public class ObservedHitBenchmark +{ + private const string KeyText = "observed:42"; + private static readonly CacheKey Key = KeyText; + + private readonly FakeRedisConnector _redis = new(); + private IHost _writerHost = default!; + private IHost _host = default!; + private ICache _cache = default!; + + [GlobalSetup] + public async Task Setup() + { + _writerHost = await StartAsync(KnownCacheProviderNames.Redis); + _host = await StartAsync(KnownCacheProviderNames.InMemoryRedis); + var writer = _writerHost.Services.GetRequiredService().CreateCache(KnownCacheProviderNames.Redis); + await writer.SetAsync(Key, "value", TimeSpan.FromDays(1), policy: null); + _redis.FrameLastWrite(DateTimeOffset.UtcNow.AddDays(1), TimeSpan.FromHours(1), TimeSpan.FromDays(1)); + _cache = _host.Services.GetRequiredService>(); + + // The first read goes to the fake and adopts the frame; the next ones are local. + if (await ByKey() != "value" || _redis.Gets == 0) + { + throw new InvalidOperationException("The fake connector did not serve the framed value"); + } + + var gets = _redis.Gets; + if (await ByKey() != "value" || await BySpan() != "value" || _redis.Gets != gets) + { + throw new InvalidOperationException("A measured call was not a local hit"); + } + + if (!await IsObservedAsync()) + { + throw new InvalidOperationException("The local entry is not an observed one"); + } + } + + [GlobalCleanup] + public async Task Cleanup() + { + var gets = _redis.Gets; + await ByKey(); + await _host.StopAsync(); + await _writerHost.StopAsync(); + _host.Dispose(); + _writerHost.Dispose(); + _redis.Dispose(); + if (_redis.Gets != gets) + { + throw new InvalidOperationException("A measured call reached the fake connector"); + } + } + + [Benchmark] + public ValueTask ByKey() => _cache.GetAsync(Key); + + [Benchmark] + public ValueTask BySpan() + { + Span buffer = stackalloc char[KeyText.Length]; + KeyText.CopyTo(buffer); + return ((ISpanKeyCache)_cache).GetAsync(buffer); + } + + private async Task IsObservedAsync() + { + var layered = _host.Services.GetRequiredService().CreateCache(KnownCacheProviderNames.InMemoryRedis); + return await layered.GetCacheEntryAsync(Key, policy: null) is ObservedEntry; + } + + private async Task StartAsync(string cache) + { + var extra = new Dictionary { { "Caching:Connections:Redis:ConnectionString", "fake:6379,abortConnect=false" }, { "Caching:BroadcastEnabled", "false" } }; + var host = HostHelper.GetHost(0, cache: cache, topic: "RedisPubSub", extra: extra, configure: b => b.Services.Replace(ServiceDescriptor.Singleton(_redis))); + await host.StartAsync(); + return host; + } +} diff --git a/benchmarks/UiPath.Caching.Benchmarks/PlainHitGateBenchmark.cs b/benchmarks/UiPath.Caching.Benchmarks/PlainHitGateBenchmark.cs new file mode 100644 index 00000000..a63bd188 --- /dev/null +++ b/benchmarks/UiPath.Caching.Benchmarks/PlainHitGateBenchmark.cs @@ -0,0 +1,80 @@ +using BenchmarkDotNet.Attributes; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using UiPath.Caching.Config; + +namespace UiPath.Caching.Benchmarks; + +/// A local hit on a plain entry of a layered cache with no Redis: the string cache, the hash cache and a get-or-add with an explicit expiration. Public members only, so the file builds against the base too. +[MemoryDiagnoser] +[MarkdownExporterAttribute.GitHub] +public class PlainHitGateBenchmark +{ + private const string KeyText = "user:42"; + private const string HashKeyText = "hash:42"; + private const string Field = "name"; + private static readonly CacheKey Key = KeyText; + private static readonly CacheKey HashKey = HashKeyText; + private static readonly DateTimeOffset Expiration = DateTimeOffset.UtcNow.AddDays(1); + + private IHost _host = default!; + private ICache _cache = default!; + private IHashCache _hash = default!; + + [GlobalSetup] + public async Task Setup() + { + _host = HostHelper.GetHost(0, cache: KnownCacheProviderNames.InMemory); + await _host.StartAsync(); + _cache = _host.Services.GetRequiredService>(); + _hash = _host.Services.GetRequiredService>(); + await _cache.SetAsync(Key, "value", Expiration); + await _hash.SetAsync(HashKey, new Dictionary { [Field] = "value" }, new HashCacheEntryOptions(Expiration, null, null, HashCacheSetOption.HashReplace)); + + if (await R1() != "value" || await R2() != "value" || await R3() != "value" || await R4() != "value" || (await R5()).Count != 1 || await R6() != "value") + { + throw new InvalidOperationException("A measured call did not answer from the local tier"); + } + } + + [GlobalCleanup] + public async Task Cleanup() + { + await _host.StopAsync(); + _host.Dispose(); + } + + /// The string cache by key. + [Benchmark] + public ValueTask R1() => _cache.GetAsync(Key); + + /// The string cache by the public span form. On .NET 8 the call takes the key-path fallback. + [Benchmark] + public ValueTask R2() + { + Span buffer = stackalloc char[KeyText.Length]; + KeyText.CopyTo(buffer); + return ((ISpanKeyCache)_cache).GetAsync(buffer); + } + + /// A hash field by key. + [Benchmark] + public ValueTask R3() => _hash.GetItemAsync(HashKey, Field); + + /// A hash field by the public span form. On .NET 8 the call takes the key-path fallback. + [Benchmark] + public ValueTask R4() + { + Span buffer = stackalloc char[HashKeyText.Length]; + HashKeyText.CopyTo(buffer); + return ((ISpanKeyHashCache)_hash).GetItemAsync(buffer, Field); + } + + /// A whole hash by key. + [Benchmark] + public ValueTask> R5() => _hash.GetAsync(HashKey); + + /// A get-or-add hit with an explicit expiration, by key. + [Benchmark] + public ValueTask R6() => _cache.GetOrAddAsync(Key, static _ => throw new InvalidOperationException("miss"), Expiration); +} diff --git a/benchmarks/UiPath.Caching.Benchmarks/UiPath.Caching.Benchmarks.csproj b/benchmarks/UiPath.Caching.Benchmarks/UiPath.Caching.Benchmarks.csproj index 859a164b..f844783d 100644 --- a/benchmarks/UiPath.Caching.Benchmarks/UiPath.Caching.Benchmarks.csproj +++ b/benchmarks/UiPath.Caching.Benchmarks/UiPath.Caching.Benchmarks.csproj @@ -1,7 +1,7 @@ - net10.0 + $(TargetFrameworks) false true UiPath.Caching.Benchmarks.Program diff --git a/docs/concepts.md b/docs/concepts.md index 9dd0e3e3..419f98b6 100644 --- a/docs/concepts.md +++ b/docs/concepts.md @@ -168,6 +168,13 @@ that arrive meanwhile join the run and share its value. When L2 refuses the write, the generated value is kept in L1 for `LocalMaxExpirationDisconnected`, so callers that come after reuse it instead of each running the generator again. +A refresh event from another node, sent by `RefreshAsync` or a metadata update, +drops this node's L1 copy of the key when an L2 tier sits below it. The node does +not renew the copy with the expiration the event carries, since L2 may not have +taken it, and its next read takes the value and its expiration from L2. On the +`InMemory` provider, which has no L2, and in the hash caches, the event renews +the L1 copy with the expiration it carries. + Why split into two tiers at all? L1 eliminates Redis latency and bandwidth on the hot path — for a busy service, removing the network hop from cache reads can have a measurable throughput impact. L2 makes the cache survive a process @@ -499,7 +506,8 @@ because a write of the key, or of a key sharing its stripe, is still in flight d Outcomes are reported as metrics per drained batch, tagged with the cache name: `cache.peer_refresh.started` (keys read), `.kept`, `.discarded` (a newer local write won) and `.dropped` (tagged `reason`: `idle`, `expired`, `timed_out`, `failed`, -`not_found`, `still_dirty`, `declined`, `overflow`), plus `.read_ms` per read. A drop with reason `timed_out` or `failed` also +`not_found`, `still_dirty`, `declined`, `overflow`, `not_kept`: a reread the cache may not keep, such as an entry without its +bounds from an inner cache the library does not know, which drops the held copy), plus `.read_ms` per read. A drop with reason `timed_out` or `failed` also raises a `cache.peer_refresh.dropped` event. Opt out per policy (`RefreshLocalOnPeerWrite: false`) for read-after-peer-write data such as revocations. @@ -725,7 +733,7 @@ Two readings, taken together: // { "json": 18234, "messagepack": 1203412 } ("unknown" is CacheValueFormats.UnknownName) ``` - A headerless value counts as `json` (`CacheValueFormats.JsonName`), a registered id under its serializer's name, and anything else as `unknown`. A string counts once. A hash is counted once under each format any of its user fields is in, so a hash with fields in two formats appears under both, the counts can add up to more than the keys, and `json` at zero means no field is left in JSON (the question a drain asks); `_version_` and `_metadata_` are not looked at. A hash is sampled, not counted whole: its first 256 user fields in HSCAN order, a hundred to a page, so one of more than 256 fields can still hold JSON in a field the inventory did not reach. A pattern is a SCAN glob over the names, so `*` and `?` match as they do in Redis, and the glob characters of what the key strategy adds (the connector's key prefix, the application name, the separators) are escaped, so an application called `app[1]` is not read as `app1`. The scan runs on every primary, one after the other, with at most 32 commands in flight, and walks the whole keyspace of each twice (once for strings, once for hashes, 500 keys a page); run it off peak. The token is checked between pages. Other key types and empty values are not counted, and a key that moves between shards during a reshard can be counted twice. The obsolete shard-tag key strategy needs a pattern that carries its own `{tag}`. + A headerless value counts as `json` (`CacheValueFormats.JsonName`), a registered id under its serializer's name, an entry frame as `frame` (and as `frame_windowed` too when it has a stale window), and anything else as `unknown`. A string counts once. A hash is counted once under each format any of its user fields is in, so a hash with fields in two formats appears under both, the counts can add up to more than the keys, and `json` at zero means no field is left in JSON (the question a drain asks); `_version_` and `_metadata_` are not looked at. A hash is sampled, not counted whole: its first 256 user fields in HSCAN order, a hundred to a page, so one of more than 256 fields can still hold JSON in a field the inventory did not reach. A pattern is a SCAN glob over the names, so `*` and `?` match as they do in Redis, and the glob characters of what the key strategy adds (the connector's key prefix, the application name, the separators) are escaped, so an application called `app[1]` is not read as `app1`. The scan runs on every primary, one after the other, with at most 32 commands in flight, and walks the whole keyspace of each twice (once for strings, once for hashes, 500 keys a page); run it off peak. The token is checked between pages. Other key types and empty values are not counted, and a key that moves between shards during a reshard can be counted twice. The obsolete shard-tag key strategy needs a pattern that carries its own `{tag}`. - **What is still read.** `cache.serializer.read` with `format` `json` falls to zero as the values are rewritten or expire. It shows what the fleet depends on now, which a scan taken once does not. The old format is drained when the inventory shows no `json` and `cache.serializer.read` shows none over a window as long as your longest `DistributedExpiration`. Values that are `lossy`, equal to `default(T)`, or over the size limit leave only by a write or by expiry; when only those remain, stop waiting, since they read as they always did. Draining does not retire the JSON decoder: under `Auto`, `Read` must keep `json`, because the writer falls back to it. @@ -734,10 +742,10 @@ The old format is drained when the inventory shows no `json` and `cache.serializ `MigrateOnRead` moves only what a read finds. A value nobody reads, a key with no TTL and a key that was skipped stay in the old format, so two more calls on `RedisCacheProvider` work through them. Both are for an operator and run off the request path: they cost commands per key that a request never pays. -- **`CountFormatsByReasonAsync(CacheKey keyPattern, token)`** is the inventory with the reason a value is where it is, as a `FormatInventoryReport` (`ByFormat` is what `CountFormatsAsync` returns, `ByReason`, `Scanned`). The reasons are `format_json`, `format_` for a registered serializer, `format_unknown`, `empty` (the cached-null marker), `oversize` (a headerless string over 256 KiB), `no_ttl` (a string with no lifetime) and `hash_sampled` (a hash, which is sampled at its first 256 user fields and never swept). One key can have several reasons. Each string costs a `PTTL`, and a headerless one a `STRLEN`, besides the two-byte read. A value equal to `default(T)` or one that would not come out the same needs the type, so only the sweep reports those. The count of each reason is also tracked as `cache.format.inventory{reason,group}`, with `group` set to `default` or to the `group` argument of the overload `CountFormatsByReasonAsync(keyPattern, group, token)`, so inventories of two sets of keys do not replace each other's gauge. +- **`CountFormatsByReasonAsync(CacheKey keyPattern, token)`** is the inventory with the reason a value is where it is, as a `FormatInventoryReport` (`ByFormat` is what `CountFormatsAsync` returns, `ByReason`, `Scanned`). The reasons are `format_json`, `format_` for a registered serializer, `format_unknown`, `format_frame` (a value stored in an entry frame), `format_frame_windowed` (a frame with a stale window, also counted as `format_frame`), `empty` (the cached-null marker), `oversize` (a headerless string over 256 KiB), `no_ttl` (a string with no lifetime) and `hash_sampled` (a hash, which is sampled at its first 256 user fields and never swept). One key can have several reasons. Each string costs a `PTTL`, and a headerless one a `STRLEN`, besides the three-byte read. A value equal to `default(T)` or one that would not come out the same needs the type, so only the sweep reports those. The count of each reason is also tracked as `cache.format.inventory{reason,group}`, with `group` set to `default` or to the `group` argument of the overload `CountFormatsByReasonAsync(keyPattern, group, token)`, so inventories of two sets of keys do not replace each other's gauge. - **`SweepFormatsAsync(CacheKey keyPattern, FormatSweepOptions options, token)`** rewrites the strings under the pattern into the format the default policy writes, in place, by the same conversion a read's rewrite uses: the lossless check, the compare-and-set that keeps the exact expiry (a transaction when the server refuses scripts), and no event. A writer or a delete that comes between the read and the write wins, and a deleted key is never created. It never calls the origin. It looks at strings only, on every primary one after another, and it throws `InvalidOperationException` when no serializer is registered or the default policy writes JSON. A key already in the target format costs one two-byte read and is not paced. - **Limits.** `RatePerSecond` (50 by default) paces the keys taken in full (a current, recent or oversize key is not paced); the read rate of `MigrateOnRead` is separate. The sweep shares that feature's one-minute window per key and its byte budget, so a key a read offered a moment ago is skipped, and a key found lossy is not looked at again for an hour. `MaxValueBytes` (256 KiB, never more) leaves a bigger value as oversize. The node list is asked again for each key, and the first refusal ends the pass, so a node that joins without the format stops it. `Budget` ends a pass before the next key it would take in full once it has passed (an overrun of at most one key's turn; a pass always takes one key, so each one moves on), and `NextCursor` of the report, passed back as `Cursor`, continues from the start of the page it stopped in, whose finished keys are then current. A Redis error that is not the key's own (a timeout, a dropped connection, a busy or loading server) ends the pass the same way, with the report and a cursor, instead of throwing; `Completed` is true when every primary has been scanned to its end. Cancelling throws and leaves what was written as it is. -- **Reading the report.** `Converted` and `Changed` (a writer got there first) are the writes; `Lossy`, `DefaultOrEmpty`, `Oversize` are the residue that leaves only by a write or by expiry; `Held` means the node list does not allow the format now (the pass ends) or the byte budget was full (counted, and the pass goes on); `Current`, `Unreadable` (an id nobody registered) and `Recent` are skipped. Each outcome is tracked as `cache.format.sweep{outcome,group}`; `FormatSweepOptions.Group` names the group tag. +- **Reading the report.** `Converted` and `Changed` (a writer got there first) are the writes; `Lossy`, `DefaultOrEmpty`, `Oversize` are the residue that leaves only by a write or by expiry; `Held` means the node list does not allow the format now (the pass ends) or the byte budget was full (counted, and the pass goes on); `Current`, `Unreadable` (an id nobody registered), `Framed` (a value stored in an entry frame, which a sweep leaves as it is) and `Recent` are skipped. Each outcome is tracked as `cache.format.sweep{outcome,group}`; `FormatSweepOptions.Group` names the group tag. Run a pass off peak, at a rate the Redis server can spare, and run the inventory again after it: what is left in `format_json` should be the residue reasons only. diff --git a/docs/how-to/extending.md b/docs/how-to/extending.md index ef9edf62..a9ba8fce 100644 --- a/docs/how-to/extending.md +++ b/docs/how-to/extending.md @@ -370,10 +370,11 @@ The library writes and strips the format header; the serializer only produces an builder.AddValueSerializer("fast", [0x10], _ => new MyValueSerializer()); ``` -`formatIds` are the ids the serializer writes and reads, checked at the call: each is `0x01`-`0x0E` (except `0x09`, `0x0A`, `0x0D`), `0x10`-`0x1E` or +`formatIds` are the ids the serializer writes and reads, checked at the call: each is `0x01`-`0x0C` (except `0x09` and `0x0A`), `0x10`-`0x1E` or `0x100`-`0x1FF`, all of one header length, none used twice or claimed by another serializer. A call that fails registers nothing. The serializer's own -`FormatIds` must equal them as a set, which is checked when the registry is built. The ids `0x01`-`0x0E` are allocated (`0x0F` is reserved for a remove tombstone and is refused): use one only if it has a row in -[format ids](../reference/format-ids.md); an application's own serializer takes `0x10`-`0x1E` or `0x100`-`0x1FF`. +`FormatIds` must equal them as a set, which is checked when the registry is built. Use an allocated id only if it has a row in +[format ids](../reference/format-ids.md). An application's own serializer takes `0x10`-`0x1E` or `0x100`-`0x1FF`. +The library reserves `0x0E` for the entry frame and `0x0F` for a remove tombstone. The registry owns whatever the factory returns and disposes it with the container, through `DisposeAsync` when the serializer has one and `Dispose` otherwise. So the factory must return a new instance, not one resolved from @@ -409,7 +410,7 @@ With `write: true` and `FormatNegotiation:Mode` `Auto` the node writes JSON unti A plugin is a package that calls `AddValueSerializer`, `AddEventFormat` or both, through public API only; the first-party MessagePack package is built the same way. `tests/UiPath.Caching.PluginContract.Tests` holds a fake third-party plugin that exercises every seam: registration, round trip, `Read` lists, `MigrateOnRead`, the inventory, the negotiated switch, named stacks and the JSON decoder next to a plugin's events. It runs against the library, not against your plugin, but it is the one to copy from. -- **Value ids.** Take two-byte ids, `0x100`-`0x17F`, and ask for a row in [format ids](../reference/format-ids.md) by pull request. `0x01`-`0x0E` (except `0x09`, `0x0A`, `0x0D`) is allocated by that table and `0x0F` is reserved for a remove tombstone and `0x10`-`0x1E` is for an application's own serializers. Make the ids an option with the row as default, so an application can move a plugin whose ids clash with its own. A second id of your own is how a plugin keeps a variant, such as a compressed one; the library never looks inside the payload. +- **Value ids.** Take two-byte ids, `0x100`-`0x17F`, and ask for a row in [format ids](../reference/format-ids.md) by pull request. `0x01`-`0x0C` (except `0x09` and `0x0A`) is allocated by that table. The library reserves `0x0E` for the entry frame and `0x0F` for a remove tombstone. The range `0x10`-`0x1E` is for an application's own serializers. Make the ids an option with the row as default, so an application can move a plugin whose ids clash with its own. A second id of your own is how a plugin keeps a variant, such as a compressed one; the library never looks inside the payload. - **Event id.** One byte, `0x01`-`0x0F` (except `0x09`, `0x0A`, `0x0D`) or `0x10`-`0x1E`. A published plugin takes it from the allocated range by a row, like a value id; value and event ids are separate. The fake plugin uses the application-private `0x11` for its events because it is never published. - **Round trip.** `Deserialize(Serialize(x))` must give back `x`, and `Serialize` must give the same bytes for the same value on every call. `MigrateOnRead` rewrites a value only when that holds and counts one that fails it as lossy. `Deserialize` throws on an id it does not own and on corrupt or truncated input, never returning part of a value; the reader turns the throw into a miss and keeps the key. - **Ids declared once.** `FormatIds` must equal the ids passed to `AddValueSerializer`; a mismatch throws when the registry is built, on first cache use, and disposes what was built. An event `Encode` must start with `formatId`; one that does not is written as JSON and logged once as an error, so an invalidation is never lost. @@ -524,8 +525,8 @@ Rules a serializer follows: - **Format ids.** A serializer lists the ids it writes in `FormatIds`, all with the same header length. Application-private serializers take `0x10`-`0x1E` (one byte) or `0x100`-`0x1FF` (the marker byte `0x1F`, then the low - byte). `0x01`-`0x0E`, except `0x09`, `0x0A` and `0x0D`, are allocated by the table in - [format ids](../reference/format-ids.md), and `0x0F` is reserved for a remove tombstone. Every other first byte, + byte). `0x01`-`0x0C`, except `0x09` and `0x0A`, are allocated by the table in + [format ids](../reference/format-ids.md). The library reserves `0x0E` for the entry frame and `0x0F` for a remove tombstone. Every other first byte, including `0x00`, JSON whitespace (`0x09`, `0x0A`, `0x0D`) and `0x20` onward, is JSON, which has no header. An id is never reused: a leftover value written under a retired id would be misread by whatever took it over. - **`Serialize` returns the id it wrote**, one of `FormatIds`; a serializer that picks between a plain and a diff --git a/docs/how-to/resilience.md b/docs/how-to/resilience.md index e038e614..15bd7b90 100644 --- a/docs/how-to/resilience.md +++ b/docs/how-to/resilience.md @@ -624,6 +624,22 @@ How it behaves: - **Not covered:** batch `GetOrAdd` (a failed batch generator still throws), hash caches and the Redis-only provider; the fields are ignored there. +**Values read from a stale window.** A value that a node stored in Redis with a stale window stays +bound to its key's life on this node's monotonic clock once it is read. Its local copy stops being a +hit at the key's logical end as the read saw it, and a value fail-safe kept from it is served no +later than the end of the key's window, and no older than the caller's `FailSafeMaxStaleAge` counted +from that logical end. A system clock set back after the read extends neither. The `Expiration` the +entry shows is this node's view at the read. A custom `EntryFactory` is not asked for such a value: +the library's own entry holds the bounds. Once a cache has read such a value, a fill that lost to a +stored value, or a `SetIfChangedAsync` that answers `Unchanged`, keeps no local copy, and the next read +of the key goes to Redis. A cache of the application's own placed between the layered cache and +Redis counts as one that may hold such values: the layered cache above it keeps a local copy only of +what this node wrote or generated, and of an entry handed up as it came out of the frame, so every +other read goes to that cache. A hash cache never answers from an entry that a string cache read out +of a stale window, when a custom `IMemoryCacheFactory` hands both one store. A key move's router keeps +no local copy of such a value. A plain value, and a framed value without a window, keep their +expiration as an instant on the system clock. + **Opting one value out.** A negative result or a placeholder should not outlive its own expiration. Return it from `GetOrAddWithExpirationAsync` with `SkipFailSafe`: it is cached as usual, is not kept for fail-safe, and drops the value kept before it. diff --git a/docs/reference/format-ids.md b/docs/reference/format-ids.md index 1c8c2294..b0f5ab3a 100644 --- a/docs/reference/format-ids.md +++ b/docs/reference/format-ids.md @@ -6,12 +6,13 @@ It checks one builder, including the serializers a named stack inherits, and can | Range | Use | |---|---| -| `0x01`-`0x0E`, except `0x09`, `0x0A`, `0x0D` | Allocated: an id is taken only by a row in the table below | +| `0x01`-`0x0C`, except `0x09` and `0x0A` | Allocated: an id is taken only by a row in the table below | +| `0x0E` | Reserved for the entry frame | | `0x0F` | Reserved: the first byte of a remove tombstone (`RedisCacheOptions.RemoveTombstone`), never the id of a value serializer | | `0x10`-`0x1E` | Application-private serializers | | `0x100`-`0x1FF` | Two-byte ids, written as `0x1F` then the low byte: published plugins by convention in `0x100`-`0x17F`, application-private in `0x180`-`0x1FF` | -`0x09`, `0x0A` and `0x0D` are never ids: they begin JSON whitespace. Value ids and event ids are separate namespaces, so one number may be both. An event id must be one byte, because an event body starts with it: `0x01`-`0x0F` allocated (`0x0F` is reserved for values only: a tombstone is never an event), `0x10`-`0x1E` application-private. The `0x100`-`0x17F` advice for published plugins applies to value ids only. +`0x09`, `0x0A` and `0x0D` are never ids: they begin JSON whitespace. Value ids and event ids are separate namespaces, so one number may be both. An event id must be one byte, because an event body starts with it: `0x01`-`0x0F` allocated (the reservations for `0x0E` and `0x0F` apply only to value ids), `0x10`-`0x1E` application-private. The `0x100`-`0x17F` advice for published plugins applies to value ids only. A published plugin makes its ids an option with the row as the default, so an application can move a plugin whose ids clash with its own. @@ -21,4 +22,5 @@ A published plugin makes its ids an option with the row as the default, so an ap |---|---|---|---| | `0x02` | Value | `UiPath.Caching.MessagePack` | `MessagePackFormats.Value` | | `0x03` | Value | `UiPath.Caching.MessagePack` | `MessagePackFormats.ValueLz4` | +| `0x0E` | Value | `Core` | `Entry frame` | | `0x02` | Event | `UiPath.Caching.MessagePack` | `MessagePackFormats.Event` | diff --git a/docs/reference/settings.md b/docs/reference/settings.md index 7faf7316..c578a1f9 100644 --- a/docs/reference/settings.md +++ b/docs/reference/settings.md @@ -198,7 +198,7 @@ Per-topic overrides: add entries to `Topics[]` under `Broadcast:RedisPubSub`. Ea | `DistributedLockExpiry` | `TimeSpan?` | `00:00:05` | Per-provider | Redis key TTL for the distributed lock (safety expiry to prevent deadlocks). | | `DistributedLockSkipReread` | `bool?` | `null` | Per-provider | `null` = `false`. On a local miss that just read Redis and missed, a lock free at the first attempt skips the second Redis read under it: one round trip less per locked miss, but a peer's write landing within that round trip can then be generated twice. | -*Code-only seams:* `EntryFactory`, `CacheKeyStrategy`, `TopicKeyStrategy`, `SizeProvider`, `LockKeyStrategy`. +*Code-only seams:* `EntryFactory`, `CacheKeyStrategy`, `TopicKeyStrategy`, `SizeProvider`, `LockKeyStrategy`. `EntryFactory` is not asked for a value read from a frame with a stale window: the library's own entry carries the bounds that keep that value within its key's life on the monotonic clock (see [Fail-safe](../how-to/resilience.md#fail-safe)). --- @@ -228,7 +228,7 @@ Per-topic overrides: add entries to `Topics[]` under `Broadcast:RedisPubSub`. Ea | `FormatNegotiation:MaxViewAge` | `TimeSpan` | `00:02:00` | Per-provider | While Redis cannot be read, the last decision stands for this long since the last good read, then values are written as JSON; a decision older than this is never used, even if a read hangs. After an outage shorter than this, the decision is also kept for two `AdvertiseInterval`s of successful ticks, so peers can advertise again, unless an advertisement says a node cannot read the format. Must be positive. | | `FormatNegotiation:AssumeAllNodesCanRead` | `bool` | `false` | Per-provider | Attests that the nodes that say nothing read the desired formats: a live Streams consumer group with no advertisement, a Pub/Sub subscriber no advertisement accounts for (a pattern subscriber included, which `PUBSUB NUMPAT` counts for the whole server, other apps' too), a Pub/Sub deployment where `PUBSUB NUMSUB` is refused, and, for an app with `BroadcastEnabled` off, with neither a Streams nor a Pub/Sub topic, or with no Redis connection, the nodes it cannot see at all. For an app that can list its peers, an advertisement that lacks the format still stops the writes. Without a Streams or Pub/Sub transport the node neither advertises nor reads advertisements, so nothing can stop the switch once `UpgradeHold` has passed, counted from the first decision. Without the setting such an app writes JSON. | -*Code-only seams:* `EntryFactory`, `CacheKeyStrategy`, `RedisKeyStrategyFactory`. +*Code-only seams:* `EntryFactory`, `CacheKeyStrategy`, `RedisKeyStrategyFactory`. `EntryFactory` is not asked for a value read from a frame with a stale window: the library's own entry carries the bounds that keep that value within its key's life on the monotonic clock (see [Fail-safe](../how-to/resilience.md#fail-safe)). --- diff --git a/src/UiPath.Caching.Migration/Decoded.cs b/src/UiPath.Caching.Migration/Decoded.cs index e98b8833..7b53d385 100644 --- a/src/UiPath.Caching.Migration/Decoded.cs +++ b/src/UiPath.Caching.Migration/Decoded.cs @@ -3,5 +3,11 @@ namespace UiPath.Caching.Migration; internal readonly record struct Decoded(DecodeClass Class, T? Value) where T : class { + /// The frame expiration: for "never", null without a window. + public DateTimeOffset? ExpiresAt { get; init; } + + /// The stale window of a windowed frame; null for a value that is not framed or a frame without a window. + public TimeSpan? StaleWindow { get; init; } + public static Decoded Of(T value) => new(DecodeClass.Ok, value); } diff --git a/src/UiPath.Caching.Migration/FillBox.cs b/src/UiPath.Caching.Migration/FillBox.cs index a38f95cf..a9cf1bc2 100644 --- a/src/UiPath.Caching.Migration/FillBox.cs +++ b/src/UiPath.Caching.Migration/FillBox.cs @@ -15,6 +15,9 @@ internal sealed class FillBox /// The key holds bytes the cache cannot read. public bool Unreadable { get; set; } + /// The stored value may have come out of a frame with a window, so the router keeps no local copy of it. + public bool Uncached { get; set; } + /// When the stored value expires, as the winner's own read reported it; null for none. public DateTimeOffset? StoredExpiration { get; set; } } diff --git a/src/UiPath.Caching.Migration/InPlaceMoveSide.cs b/src/UiPath.Caching.Migration/InPlaceMoveSide.cs index 9e516111..069de47e 100644 --- a/src/UiPath.Caching.Migration/InPlaceMoveSide.cs +++ b/src/UiPath.Caching.Migration/InPlaceMoveSide.cs @@ -46,8 +46,16 @@ public async ValueTask SnapshotAsync(string logical, CancellationTo return KeyMoveSnap.Of(ReadOutcome.Absent); } + var bytes = (byte[]?)read.Value ?? []; + + // A windowed frame is read again in one transaction, and only that snap is handed on. + if (KeyMoveFrameRead.Needed(bytes)) + { + return await KeyMoveFrameRead.AtomicSnapAsync(data.Db, Key(logical), _clock).ConfigureAwait(false); + } + var ttl = read.Expiry is { } left ? (long)Math.Ceiling(left.TotalMilliseconds) : MoveScripts.NoExpiry; - return new KeyMoveSnap(ReadOutcome.Found, (byte[]?)read.Value ?? [], ttl, _clock.GetUtcNow()); + return new KeyMoveSnap(ReadOutcome.Found, bytes, ttl, _clock.GetUtcNow()); } catch (RedisServerException ex) when (ex.Message.Contains("WRONGTYPE", StringComparison.OrdinalIgnoreCase)) { diff --git a/src/UiPath.Caching.Migration/KeyMoveClient.Batch.cs b/src/UiPath.Caching.Migration/KeyMoveClient.Batch.cs index c1922ce6..b2140ffe 100644 --- a/src/UiPath.Caching.Migration/KeyMoveClient.Batch.cs +++ b/src/UiPath.Caching.Migration/KeyMoveClient.Batch.cs @@ -101,9 +101,13 @@ private async Task> ProbeBatchAsync(KeyMoveData data, List missing = [.. missing.Where((_, i) => !failed.Contains(i))]; } + // A windowed frame takes no PTTL of the batch: it is read again, value and TTL together. var hits = Enumerable.Range(0, missing.Count).Where(i => !values[i].IsNull).ToArray(); - var lives = await ReadBatchLifetimesAsync(data, missing, hits, replica, cancellationToken).ConfigureAwait(false); - var still = RecordBatchHits(missing, values, hits.Zip(lives).ToDictionary(p => p.First, p => p.Second), result); + var framed = hits.Where(i => KeyMoveFrameRead.Needed((byte[]?)values[i])).ToArray(); + var plain = hits.Except(framed).ToArray(); + var lives = await ReadBatchLifetimesAsync(data, missing, plain, replica, cancellationToken).ConfigureAwait(false); + var again = await ReadFramesAgainAsync(data, missing, framed, cancellationToken).ConfigureAwait(false); + var still = RecordBatchHits(missing, values, plain.Zip(lives).ToDictionary(p => p.First, p => p.Second), again, result); missing = still; } @@ -129,12 +133,37 @@ private async Task> ProbeBatchAsync(KeyMoveData data, List })).ConfigureAwait(false); } - private List RecordBatchHits(List missing, RedisValue[] values, Dictionary life, Dictionary> result) + // One transaction per key, all sent together after their own schedule point; a read that fails makes its key unavailable. + private async Task> ReadFramesAgainAsync(KeyMoveData data, List missing, int[] framed, CancellationToken cancellationToken) + { + if (framed.Length == 0) + { + return []; + } + + await At(SchedulePointStep.ReadFrameAgain).ConfigureAwait(false); + var snaps = await Task.WhenAll(framed.Select(async i => + { + try + { + return await KeyMoveFrameRead.AtomicSnapAsync(data.Db, Key(Standard(missing[i])), _p.Clock).ConfigureAwait(false); + } + catch (Exception ex) when (ex is not OperationCanceledException || !cancellationToken.IsCancellationRequested) + { + return KeyMoveSnap.Of(ReadOutcome.Unavailable); + } + })).ConfigureAwait(false); + return framed.Zip(snaps).ToDictionary(p => p.First, p => p.Second); + } + + private List RecordBatchHits(List missing, RedisValue[] values, Dictionary life, Dictionary again, Dictionary> result) { var still = new List(); for (var i = 0; i < missing.Count; i++) { - var read = BatchHit(values[i], values[i].IsNull ? -2 : life[i]); + var read = again.TryGetValue(i, out var snap) + ? Interpret(snap, _p.Standard, authoritativeNull: true) + : BatchHit(values[i], values[i].IsNull ? -2 : life[i]); if (read.FallsThrough) { still.Add(missing[i]); diff --git a/src/UiPath.Caching.Migration/KeyMoveClient.Fill.cs b/src/UiPath.Caching.Migration/KeyMoveClient.Fill.cs index f943c5c6..83cf5ada 100644 --- a/src/UiPath.Caching.Migration/KeyMoveClient.Fill.cs +++ b/src/UiPath.Caching.Migration/KeyMoveClient.Fill.cs @@ -39,11 +39,13 @@ private static void KeepFillWinner(FillBox box, PathRead held) { box.Stored = held.Value; box.StoredExpiration = held.Expiration; + box.Uncached = held.Uncached; } else { box.Stored = null; box.StoredExpiration = null; + box.Uncached = false; } } diff --git a/src/UiPath.Caching.Migration/KeyMoveFrameRead.cs b/src/UiPath.Caching.Migration/KeyMoveFrameRead.cs new file mode 100644 index 00000000..1dad53a2 --- /dev/null +++ b/src/UiPath.Caching.Migration/KeyMoveFrameRead.cs @@ -0,0 +1,46 @@ +using StackExchange.Redis; +using UiPath.Caching.Redis; + +namespace UiPath.Caching.Migration; + +/// The second read of a snap that holds a windowed frame: the value and its TTL from one transaction on the master. +internal static class KeyMoveFrameRead +{ + private const CommandFlags Master = CommandFlags.DemandMaster; + + /// Whether the first three bytes look like a windowed frame: a hint to read again, never a verdict. + public static bool Needed(byte[]? bytes) => bytes is not null && EntryFrame.LooksWindowed(bytes); + + /// MULTI, GET, PTTL, EXEC on the master. The TTL is the answered one less the time since the send, and At is the time the reply was processed. + public static async ValueTask AtomicSnapAsync(IDatabase db, RedisKey key, TimeProvider clock) + { + var transaction = db.CreateTransaction(); + var value = transaction.StringGetAsync(key, Master); + var ttl = transaction.KeyTimeToLiveAsync(key, Master); + var sent = clock.GetTimestamp(); + if (!await transaction.ExecuteAsync(Master).ConfigureAwait(false)) + { + return Atomic(KeyMoveSnap.Of(ReadOutcome.Unavailable)); + } + + var bytes = (byte[]?)await value.ConfigureAwait(false); + var left = await ttl.ConfigureAwait(false); + var elapsed = clock.GetElapsedTime(sent); + var at = clock.GetUtcNow(); + if (bytes is null) + { + return Atomic(KeyMoveSnap.Of(ReadOutcome.Absent)); + } + + if (left is not { } life) + { + return new KeyMoveSnap(ReadOutcome.Found, bytes, -1, at) { Atomic = true }; + } + + // The elapsed time holds the wait before the server ran the command too, so this is the least life the key may have left. + var ttlMs = (long)Math.Floor((life - elapsed).TotalMilliseconds); + return ttlMs < 1 ? Atomic(KeyMoveSnap.Of(ReadOutcome.Absent)) : new KeyMoveSnap(ReadOutcome.Found, bytes, ttlMs, at) { Atomic = true }; + } + + private static KeyMoveSnap Atomic(KeyMoveSnap snap) => snap with { Atomic = true }; +} diff --git a/src/UiPath.Caching.Migration/KeyMoveSnap.cs b/src/UiPath.Caching.Migration/KeyMoveSnap.cs index 78bd142b..33ce0dc1 100644 --- a/src/UiPath.Caching.Migration/KeyMoveSnap.cs +++ b/src/UiPath.Caching.Migration/KeyMoveSnap.cs @@ -3,5 +3,8 @@ namespace UiPath.Caching.Migration; /// One string read of a primary: the bytes and the remaining life in milliseconds (-1 for none), taken together. internal readonly record struct KeyMoveSnap(ReadOutcome Kind, byte[]? Bytes, long TtlMs, DateTimeOffset At) { + /// True only for a snap whose value and TTL came from one transaction on the master. + public bool Atomic { get; init; } + public static KeyMoveSnap Of(ReadOutcome kind) => new(kind, null, -1, default); } diff --git a/src/UiPath.Caching.Migration/KeyPromotion.cs b/src/UiPath.Caching.Migration/KeyPromotion.cs index 7d6ef1b5..ba584de5 100644 --- a/src/UiPath.Caching.Migration/KeyPromotion.cs +++ b/src/UiPath.Caching.Migration/KeyPromotion.cs @@ -49,13 +49,21 @@ public static PathRead Interpret(KeyMoveSnap snap, IKeyMoveCodec codec, bo return PathRead.Of(ReadOutcome.Unreadable); } + // A windowed frame is judged on a matched pair only: a snap that is not one transaction publishes no life and serves no value. + if (decoded.StaleWindow is not null && !snap.Atomic) + { + return PathRead.Of(ReadOutcome.Unavailable); + } + + var life = MovedLife.Of(snap.TtlMs, snap.At, decoded); return decoded.Class switch { + _ when life.Expired => PathRead.Of(ReadOutcome.Absent), DecodeClass.Null when authoritativeNull && codec.EncodeNull() is not null => new PathRead(ReadOutcome.Absent, null, null) { Stops = true }, DecodeClass.Expired or DecodeClass.Null => PathRead.Of(ReadOutcome.Absent), DecodeClass.Unreadable => PathRead.Of(ReadOutcome.Unreadable), _ when decoded.Value is null => PathRead.Of(ReadOutcome.Unreadable), - _ => new PathRead(ReadOutcome.Found, decoded.Value, snap.TtlMs < 0 ? null : snap.At.AddMilliseconds(snap.TtlMs)), + _ => new PathRead(ReadOutcome.Found, decoded.Value, Deadline(snap, life), decoded.StaleWindow is not null), }; } @@ -76,8 +84,16 @@ public async ValueTask SnapAsync(string key, bool replica, Schedule return KeyMoveSnap.Of(ReadOutcome.Absent); } + var bytes = (byte[]?)read.Value ?? []; + + // The value and the TTL of a windowed frame are read again together, and only that second snap is handed on. + if (KeyMoveFrameRead.Needed(bytes)) + { + return await KeyMoveFrameRead.AtomicSnapAsync(data.Db, key, _p.Clock).ConfigureAwait(false); + } + var ttl = read.Expiry is { } left ? (long)Math.Ceiling(left.TotalMilliseconds) : -1; - return new KeyMoveSnap(ReadOutcome.Found, (byte[]?)read.Value ?? [], ttl, _p.Clock.GetUtcNow()); + return new KeyMoveSnap(ReadOutcome.Found, bytes, ttl, _p.Clock.GetUtcNow()); } catch (RedisServerException ex) when (ex.Message.Contains("WRONGTYPE", StringComparison.OrdinalIgnoreCase)) { @@ -129,7 +145,7 @@ public async ValueTask> RunAsync(string key, MoverFlavor? mov var snap = await SourceSnapAsync(key, cancellationToken, mover?.ObserveSourceTtl).ConfigureAwait(false); var replied = _p.Clock.GetTimestamp(); - var (served, skipped) = await ReadSourceAsync(run, snap, cancellationToken).ConfigureAwait(false); + var (served, skipped, life) = await ReadSourceAsync(run, snap, cancellationToken).ConfigureAwait(false); var deleteStaleTarget = _reverse && mover is not null && skipped is { Kind: PromotionKind.TooLarge }; if (skipped is { } skip && !deleteStaleTarget) { @@ -137,7 +153,7 @@ public async ValueTask> RunAsync(string key, MoverFlavor? mov } var uncached = served with { Uncached = true }; - if (AbandonReason(data, events, started, replied, snap.TtlMs) is { } reason) + if (AbandonReason(data, events, started, replied, life.TtlMs) is { } reason) { return new PromotionResult(PromotionKind.Abandoned, uncached, Reason: reason); } @@ -159,7 +175,7 @@ public async ValueTask> RunAsync(string key, MoverFlavor? mov } using var format = lease; - var (drained, unpublished) = await PublishAsync(run, capture, encoded, snap.TtlMs, uncached, cancellationToken).ConfigureAwait(false); + var (drained, unpublished) = await PublishAsync(run, capture, encoded, life.TtlMs, uncached, cancellationToken).ConfigureAwait(false); if (unpublished is { } stop) { return stop; @@ -210,6 +226,9 @@ private static Decoded Decode(IKeyMoveCodec codec, KeyMoveSnap snap) } } + // The served deadline: the snap's instant plus the moved life; null for no expiry. + private static DateTimeOffset? Deadline(KeyMoveSnap snap, MovedLife life) => life.TtlMs < 0 ? null : snap.At.AddMilliseconds(life.TtlMs); + private static bool IsShort(KeyMoveSnap snap, MoverFlavor mover) => snap.TtlMs >= 0 && snap.TtlMs < mover.MinTtl.TotalMilliseconds; private static string UnfoundClass(ReadOutcome kind) => kind switch @@ -305,24 +324,32 @@ private async ValueTask> SupersededAsync(PromotionRun run, IS }; } - // Reads the snapshot of L into the value to serve, or the result that ends the run before publishing. A cached null serves as a miss and goes on as the other side's null. - private async ValueTask<(PathRead Served, PromotionResult? Skipped)> ReadSourceAsync(PromotionRun run, KeyMoveSnap snap, CancellationToken cancellationToken) + // Reads the snapshot of L into the value to serve and the life it moves with, or the result that ends the run before publishing. A cached null serves as a miss and goes on as the other side's null. + private async ValueTask<(PathRead Served, PromotionResult? Skipped, MovedLife Life)> ReadSourceAsync(PromotionRun run, KeyMoveSnap snap, CancellationToken cancellationToken) { if (snap.Kind != ReadOutcome.Found) { - return (default, Unfound(snap.Kind)); + return (default, Unfound(snap.Kind), default); } var decoded = Decode(_source.Codec, snap); + + // As Interpret: a windowed frame in a snap that is not one transaction moves nothing. + if (decoded.StaleWindow is not null && !snap.Atomic) + { + return (default, Unfound(ReadOutcome.Unavailable), default); + } + if (decoded.Class == DecodeClass.Unreadable || decoded is { Class: not (DecodeClass.Expired or DecodeClass.Null), Value: null }) { - return (default, await UnreadableSourceAsync(run, snap, cancellationToken).ConfigureAwait(false)); + return (default, await UnreadableSourceAsync(run, snap, cancellationToken).ConfigureAwait(false), default); } - if (decoded.Class == DecodeClass.Expired) + var life = MovedLife.Of(snap.TtlMs, snap.At, decoded); + if (decoded.Class == DecodeClass.Expired || life.Expired) { - return (default, PromotionResult.Of(PromotionKind.Expired, ReadOutcome.Absent)); + return (default, PromotionResult.Of(PromotionKind.Expired, ReadOutcome.Absent), default); } // Only forward read-through can drop an oversized value or a null the target cannot store. @@ -333,18 +360,17 @@ private async ValueTask> SupersededAsync(PromotionRun run, IS { return (default, droppable ? await DroppedAsync(run, snap, PromotionResult.Of(PromotionKind.SourceAbsent), cancellationToken).ConfigureAwait(false) - : PromotionResult.Of(PromotionKind.NullNotCached)); + : PromotionResult.Of(PromotionKind.NullNotCached), life); } - var expiration = snap.TtlMs < 0 ? (DateTimeOffset?)null : snap.At.AddMilliseconds(snap.TtlMs); - var served = isNull ? PathRead.Of(ReadOutcome.Absent) : new PathRead(ReadOutcome.Found, decoded.Value, expiration); + var served = isNull ? PathRead.Of(ReadOutcome.Absent) : new PathRead(ReadOutcome.Found, decoded.Value, Deadline(snap, life), decoded.StaleWindow is not null); var unmoved = Unmoved(run, snap, decoded.Class, served); if (unmoved is { } stop && droppable) { unmoved = await DroppedAsync(run, snap, stop, cancellationToken).ConfigureAwait(false); } - return (served, unmoved); + return (served, unmoved, life); } private PromotionResult Unfound(ReadOutcome kind) @@ -546,7 +572,7 @@ private async ValueTask ProbeDecodedAsync(string key, MoverFlavor m // Only the mover and the key of the run are read on this path: it never fences, publishes or deletes. var run = new PromotionRun(key, _p.StandardKey(key), default, mover, null!, null!, 0, AlwaysOwned.Instance, Quiet: true); var bytes = snap.Bytes?.Length ?? 0; - var (served, skipped) = await ReadSourceAsync(run, snap, cancellationToken).ConfigureAwait(false); + var (served, skipped, _) = await ReadSourceAsync(run, snap, cancellationToken).ConfigureAwait(false); if (skipped is { } stop) { return new DryRunProbe(SkippedClass(stop.Kind), bytes, null, Decoded: true); diff --git a/src/UiPath.Caching.Migration/LibraryKeyMoveCodec.cs b/src/UiPath.Caching.Migration/LibraryKeyMoveCodec.cs index bf4e458c..26cbfc7c 100644 --- a/src/UiPath.Caching.Migration/LibraryKeyMoveCodec.cs +++ b/src/UiPath.Caching.Migration/LibraryKeyMoveCodec.cs @@ -33,13 +33,18 @@ public Decoded Decode(byte[] bytes) { try { - // Quiet: a scan over junk counts it as a move class, not as a read miss. A null is the empty value and TooLarge is the stored length over the cap, as the inventory judges by length alone. Never Expired: an envelope's own deadline is not the library's to know. - return cache.Decode(bytes, null, quiet: true) switch + // A frame is split off first and the switch runs on the value inside it; TooLarge still judges the stored length. + var framed = cache.TryUnframe(bytes, out var frame); + var inner = framed ? frame.Inner : bytes; + + // Quiet: a scan over junk counts it as a move class, not as a read miss. A null is the empty value and TooLarge is the stored length over the cap, as the inventory judges by length alone. Never Expired: the move judges a frame's life from its snap. + var decoded = cache.Decode(inner, null, quiet: true) switch { (SnapshotOutcome.Found, { } value) => bytes.Length > maxValueBytes ? new Decoded(DecodeClass.TooLarge, value) : Decoded.Of(value), - (SnapshotOutcome.Found or SnapshotOutcome.Absent, _) when bytes.Length == 0 => new Decoded(DecodeClass.Null, null), + (SnapshotOutcome.Found or SnapshotOutcome.Absent, _) when inner.Length == 0 => new Decoded(DecodeClass.Null, null), _ => new Decoded(DecodeClass.Unreadable, null), }; + return framed ? decoded with { ExpiresAt = frame.Expiration, StaleWindow = frame.Window } : decoded; } catch (Exception ex) when (ex is not OutOfMemoryException) { diff --git a/src/UiPath.Caching.Migration/LibraryPathClient.cs b/src/UiPath.Caching.Migration/LibraryPathClient.cs index fb6905af..caec8594 100644 --- a/src/UiPath.Caching.Migration/LibraryPathClient.cs +++ b/src/UiPath.Caching.Migration/LibraryPathClient.cs @@ -5,6 +5,8 @@ namespace UiPath.Caching.Migration; internal sealed class LibraryPathClient(IMigrationCache store, IConnectionState connection, Func redisKey, Func settleWithin, Func? writePolicy = null, Func? readPolicy = null) : IPathClient where T : class { + // Asked once: a library cache that keeps no bounds may hand up an entry it built anew from a windowed frame. + private readonly bool _keepsBounds = FrameTiers.KeepsBounds(store); private ILibraryBatch? _batch; public LibraryPathClient(IMigrationCache store, IConnectionState connection, Func redisKey, TimeSpan settleWithin) @@ -36,7 +38,7 @@ public async ValueTask> ReadAsync(string key, CancellationToken canc var read = await store.ReadSnapshotAsync(CacheKey.Verbatim(redisKey(key)), readPolicy?.Invoke(), cancellationToken).ConfigureAwait(false); return read.Outcome switch { - SnapshotOutcome.Found when read.Entry is { } entry && (entry.Value is not null || CacheNulls) => new PathRead(ReadOutcome.Found, entry.Value, entry.Expiration == DateTimeOffset.MaxValue ? null : entry.Expiration), + SnapshotOutcome.Found when read.Entry is { } entry && (entry.Value is not null || CacheNulls) => new PathRead(ReadOutcome.Found, entry.Value, entry.Expiration == DateTimeOffset.MaxValue ? null : entry.Expiration, entry is ObservedEntry || !_keepsBounds), SnapshotOutcome.Found or SnapshotOutcome.Absent => PathRead.Of(ReadOutcome.Absent), SnapshotOutcome.Unreadable => PathRead.Of(ReadOutcome.Unreadable), _ => PathRead.Of(ReadOutcome.Unavailable), @@ -172,6 +174,7 @@ public async ValueTask FillAsync(string key, T value, DateTimeOffse stored.Stored = fill.Existing; stored.CachedNull = fill.Existing is null; stored.StoredExpiration = fill.Expiration; + stored.Uncached = FrameTiers.MayHaveMet(Cache); return WriteOutcome.NotSent; case FillOutcome.Unreadable when stored is not null: stored.Lost = true; diff --git a/src/UiPath.Caching.Migration/MovedLife.cs b/src/UiPath.Caching.Migration/MovedLife.cs new file mode 100644 index 00000000..93889a95 --- /dev/null +++ b/src/UiPath.Caching.Migration/MovedLife.cs @@ -0,0 +1,34 @@ +namespace UiPath.Caching.Migration; + +/// The life a moved value may have: "no expiry" and "expired" are two answers, never one number. +/// -1 for no expiry, else a count of at least 1 ms; meaningless when . +internal readonly record struct MovedLife(bool Expired, long TtlMs) +{ + private static readonly MovedLife Over = new(true, 0); + + /// The life of on a key with left (negative: no expiry) at (L1 to L5). + public static MovedLife Of(long keyTtlMs, DateTimeOffset at, in Decoded decoded) + where T : class + { + // L1: a plain value or a frame without a window keeps the key's TTL, and no expiry stays no expiry. + if (decoded.StaleWindow is not { } window) + { + return new(false, keyTtlMs < 0 ? -1 : keyTtlMs); + } + + // L2, L4: a windowed frame on a key with no expiry is never fresh. + if (keyTtlMs < 0) + { + return Over; + } + + // L3, L5: the key's TTL less the window, and no later than the frame expiration. + var life = keyTtlMs - (long)Math.Ceiling(window.TotalMilliseconds); + if (decoded.ExpiresAt is { } expiration && expiration != DateTimeOffset.MaxValue) + { + life = Math.Min(life, (long)Math.Floor((expiration - at).TotalMilliseconds)); + } + + return life < 1 ? Over : new(false, life); + } +} diff --git a/src/UiPath.Caching.Migration/PathRead.cs b/src/UiPath.Caching.Migration/PathRead.cs index fbd3c01c..4aa876f7 100644 --- a/src/UiPath.Caching.Migration/PathRead.cs +++ b/src/UiPath.Caching.Migration/PathRead.cs @@ -1,6 +1,6 @@ namespace UiPath.Caching.Migration; -/// Served but not for the local tier: a promotion that was abandoned. +/// Served but not for the local tier: a promotion that was abandoned, a value that came out of a frame with a window, or a read from a cache that keeps no bounds. internal readonly record struct PathRead(ReadOutcome Kind, T? Value, DateTimeOffset? Expiration, bool Uncached = false) where T : class { diff --git a/src/UiPath.Caching.Migration/RoutedCacheOfT.cs b/src/UiPath.Caching.Migration/RoutedCacheOfT.cs index 2dd40523..9649b94e 100644 --- a/src/UiPath.Caching.Migration/RoutedCacheOfT.cs +++ b/src/UiPath.Caching.Migration/RoutedCacheOfT.cs @@ -379,8 +379,12 @@ private bool TryKeepFillWinner(LocalKey local, FillMark mark, FillBox? fill, return fill.CachedNull; } - // Keep the winner only under the original fill mark. - KeepStored(local, mark, stored, fill.StoredExpiration); + // Keep the winner only under the original fill mark, and never one that may have come out of a windowed frame. + if (!fill.Uncached) + { + KeepStored(local, mark, stored, fill.StoredExpiration); + } + winner = stored; return true; } diff --git a/src/UiPath.Caching/BoundToken.cs b/src/UiPath.Caching/BoundToken.cs new file mode 100644 index 00000000..2eb4a8ac --- /dev/null +++ b/src/UiPath.Caching/BoundToken.cs @@ -0,0 +1,23 @@ +using Microsoft.Extensions.Primitives; + +namespace UiPath.Caching; + +/// Ends a local copy of an observed value at its freshness bound on the monotonic clock: the store asks it on a lookup and on a scan, and drops the entry once it has changed. It carries no safety; every hit tests the entry it got back. +internal sealed class BoundToken(TimeProvider clock, long freshUntil) : IChangeToken +{ + public bool HasChanged => clock.GetTimestamp() >= freshUntil; + + public bool ActiveChangeCallbacks => false; + + public IDisposable RegisterChangeCallback(Action callback, object? state) => NoRegistration.Instance; + + private sealed class NoRegistration : IDisposable + { + public static readonly NoRegistration Instance = new(); + + public void Dispose() + { + // Nothing was registered: the token has no active callbacks. + } + } +} diff --git a/src/UiPath.Caching/CacheEntryFactory.cs b/src/UiPath.Caching/CacheEntryFactory.cs index e1f43f7e..778d633f 100644 --- a/src/UiPath.Caching/CacheEntryFactory.cs +++ b/src/UiPath.Caching/CacheEntryFactory.cs @@ -7,6 +7,10 @@ public sealed class CacheEntryFactory : ICacheEntryFactory public ICacheEntry Create(T value, DateTimeOffset expiration, IDictionary? properties = null) => new CacheEntry(value, expiration, properties); + /// The library's own entry for a value that came out of a frame with a window; a custom factory is never asked for one, since only this entry holds the bounds. + internal static ICacheEntry CreateObserved(T value, DateTimeOffset expiration, ObservedLife observed, IDictionary? properties = null) => + new ObservedCacheEntry(value, expiration, observed, properties); + private struct Marks : IEquatable { public int Read; @@ -16,11 +20,36 @@ private struct Marks : IEquatable public long Replaces; public long LocalDeadline; + public bool IsTracked => Volatile.Read(ref Read) != Untracked; + + public int LastRead => Math.Max(Volatile.Read(ref Read), ILocalEntry.NeverRead); + public readonly bool Equals(Marks other) => true; public override readonly bool Equals(object? obj) => obj is Marks; public override readonly int GetHashCode() => 0; + + public void Track(bool tracked) + { + if (!tracked) + { + Volatile.Write(ref Read, Untracked); + } + else if (Volatile.Read(ref Read) == Untracked) + { + Volatile.Write(ref Read, ILocalEntry.NeverRead); + } + } + + public void MarkRead(int nowSeconds) + { + var last = Volatile.Read(ref Read); + if (last != nowSeconds && last != Untracked) + { + Volatile.Write(ref Read, nowSeconds); + } + } } private sealed record CacheEntry : ICacheEntry, ILocalEntry @@ -47,9 +76,9 @@ public CacheEntry(T? value, DateTimeOffset? expiration = null, IDictionary Value; - int ILocalEntry.LastRead => Math.Max(Volatile.Read(ref _marks.Read), ILocalEntry.NeverRead); + int ILocalEntry.LastRead => _marks.LastRead; - bool ILocalEntry.IsTracked => Volatile.Read(ref _marks.Read) != Untracked; + bool ILocalEntry.IsTracked => _marks.IsTracked; long ILocalEntry.ReplacedBy { @@ -73,28 +102,74 @@ DateTimeOffset ILocalEntry.LocalDeadline void ILocalEntry.MarkTokenChanged() => Volatile.Write(ref _marks.TokenChanged, 1); - void ILocalEntry.Track(bool tracked) + void ILocalEntry.Track(bool tracked) => _marks.Track(tracked); + + void ILocalEntry.MarkRead(int nowSeconds) => _marks.MarkRead(nowSeconds); + + public ICacheEntry NewEntry(DateTimeOffset? expiration = null, IDictionary? metadata = null) => + new CacheEntry(Value, expiration, metadata ?? (_storedMetadata as EntryValidators)); + } + + /// The entry of : the plain entry with the bounds of its judgment, which a rebuild keeps. + private sealed record ObservedCacheEntry : ObservedEntry, ICacheEntry, ILocalEntry + { + private readonly IDictionary? _storedMetadata; + + // Not part of the entry's value: every copy of an entry equals the others. + private Marks _marks; + + public ObservedCacheEntry(T? value, DateTimeOffset expiration, ObservedLife observed, IDictionary? metadata) + : base(observed) { - if (!tracked) - { - Volatile.Write(ref _marks.Read, Untracked); - } - else if (Volatile.Read(ref _marks.Read) == Untracked) - { - Volatile.Write(ref _marks.Read, ILocalEntry.NeverRead); - } + Value = value; + Expiration = expiration; + _storedMetadata = metadata; } - void ILocalEntry.MarkRead(int nowSeconds) + public T? Value { get; } + + public DateTimeOffset Expiration { get; } + + public IDictionary? Metadata => _storedMetadata is EntryValidators { Count: 0 } ? null : _storedMetadata; + + EntryValidators? ILocalEntry.Validators => _storedMetadata as EntryValidators; + + object? ICacheEntry.Value => Value; + + int ILocalEntry.LastRead => _marks.LastRead; + + bool ILocalEntry.IsTracked => _marks.IsTracked; + + long ILocalEntry.ReplacedBy { - var last = Volatile.Read(ref _marks.Read); - if (last != nowSeconds && last != Untracked) - { - Volatile.Write(ref _marks.Read, nowSeconds); - } + get => Volatile.Read(ref _marks.ReplacedBy); + set => Volatile.Write(ref _marks.ReplacedBy, value); } + long ILocalEntry.Replaces + { + get => Volatile.Read(ref _marks.Replaces); + set => Volatile.Write(ref _marks.Replaces, value); + } + + DateTimeOffset ILocalEntry.LocalDeadline + { + get => Volatile.Read(ref _marks.LocalDeadline) is var ticks and > 0 ? new DateTimeOffset(ticks, TimeSpan.Zero) : DateTimeOffset.MinValue; + set => Volatile.Write(ref _marks.LocalDeadline, value.UtcTicks); + } + + bool ILocalEntry.TokenChanged => Volatile.Read(ref _marks.TokenChanged) == 1; + + ObservedLife ILocalEntry.Observed => Observed; + + void ILocalEntry.MarkTokenChanged() => Volatile.Write(ref _marks.TokenChanged, 1); + + void ILocalEntry.Track(bool tracked) => _marks.Track(tracked); + + void ILocalEntry.MarkRead(int nowSeconds) => _marks.MarkRead(nowSeconds); + + /// Keeps the bounds, so a rebuild cannot widen them. public ICacheEntry NewEntry(DateTimeOffset? expiration = null, IDictionary? metadata = null) => - new CacheEntry(Value, expiration, metadata ?? (_storedMetadata as EntryValidators)); + new ObservedCacheEntry(Value, expiration ?? DateTimeOffset.MaxValue, Observed, metadata ?? (_storedMetadata as EntryValidators)); } } diff --git a/src/UiPath.Caching/FrameInfo.cs b/src/UiPath.Caching/FrameInfo.cs new file mode 100644 index 00000000..53cb4ddc --- /dev/null +++ b/src/UiPath.Caching/FrameInfo.cs @@ -0,0 +1,4 @@ +namespace UiPath.Caching; + +/// An entry frame split off stored bytes: the inner value, and the frame expiration and stale window, both null for a frame without a window. +internal readonly record struct FrameInfo(byte[] Inner, DateTimeOffset? Expiration, TimeSpan? Window); diff --git a/src/UiPath.Caching/FrameTiers.cs b/src/UiPath.Caching/FrameTiers.cs new file mode 100644 index 00000000..f1c2d072 --- /dev/null +++ b/src/UiPath.Caching/FrameTiers.cs @@ -0,0 +1,11 @@ +namespace UiPath.Caching; + +/// The answers for any tier: one the library does not know may have met a windowed frame, and keeps no bounds. +internal static class FrameTiers +{ + /// Asked after an answer arrived, on every use; never stored. + public static bool MayHaveMet(object tier) => tier is not IFrameTier known || known.MetWindowedFrame; + + /// Asked once, when a cache or a path client is built. + public static bool KeepsBounds(object tier) => tier is IFrameTier { KeepsBounds: true }; +} diff --git a/src/UiPath.Caching/GlobalUsings.cs b/src/UiPath.Caching/GlobalUsings.cs index f2232612..c6d9cdd3 100644 --- a/src/UiPath.Caching/GlobalUsings.cs +++ b/src/UiPath.Caching/GlobalUsings.cs @@ -21,4 +21,6 @@ // Castle DynamicProxy (used by NSubstitute via AutoFixture in Caching.Tests) needs access to the // internal concrete cache classes to generate dynamic proxies for closed generics like // ILogger. Without this, mocking those proxies fails at test fixture time. +// A substitute that implements more than one interface, one of them internal, is built in the unsigned proxy assembly. +[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("DynamicProxyGenAssembly2")] [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("DynamicProxyGenAssembly2, PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7")] diff --git a/src/UiPath.Caching/IByteCodecCache.cs b/src/UiPath.Caching/IByteCodecCache.cs index cff2b79b..c3a9995a 100644 --- a/src/UiPath.Caching/IByteCodecCache.cs +++ b/src/UiPath.Caching/IByteCodecCache.cs @@ -11,4 +11,7 @@ internal interface IByteCodecCache /// What ReadSnapshotAsync makes of ; unreadable bytes are an outcome, and only a null argument or an uncacheable throws. It queues no rewrite, and also logs and counts nothing. (SnapshotOutcome Outcome, T? Value) Decode(byte[] stored, CachePolicy? policy, bool quiet = false); + + /// Splits a frame off stored bytes; false when they are not a frame. + bool TryUnframe(byte[] stored, out FrameInfo info); } diff --git a/src/UiPath.Caching/IFrameTier.cs b/src/UiPath.Caching/IFrameTier.cs new file mode 100644 index 00000000..7d36f5bd --- /dev/null +++ b/src/UiPath.Caching/IFrameTier.cs @@ -0,0 +1,11 @@ +namespace UiPath.Caching; + +/// A tier of the library that says whether one of its answers can have come out of a frame with a window, and whether it bounds every such entry it hands up. +internal interface IFrameTier +{ + /// Whether an answer of this tier can have come out of a frame with a window; once true, never false again. + bool MetWindowedFrame { get; } + + /// Whether every entry this tier hands up that came out of a frame with a window carries its bounds; fixed when the tier is built. + bool KeepsBounds { get; } +} diff --git a/src/UiPath.Caching/ILayeredShape.cs b/src/UiPath.Caching/ILayeredShape.cs index 6331132f..45ee4eb5 100644 --- a/src/UiPath.Caching/ILayeredShape.cs +++ b/src/UiPath.Caching/ILayeredShape.cs @@ -46,6 +46,9 @@ internal interface ILayeredShape /// Writes the value to the local tier, no longer than ; says whether a peer's write refreshes it. bool KeepLocal(TOptions options, TValue value, TimeSpan? maxExpiration, CachePolicy policy); + /// As , for a value read with its bounds: the local item is the library's observed entry, so the bounds stay with the copy. + bool KeepObserved(TOptions options, TValue value, ObservedLife observed, TimeSpan? maxExpiration, CachePolicy policy); + /// Writes the value to the inner tier; a write that throws counts as refused, not as failed, only when . ValueTask WriteInnerAsync(TOptions options, TValue value, CachePolicy policy, bool keepRefused, BackgroundWrites.Keeper keeper); diff --git a/src/UiPath.Caching/ILocalEntry.cs b/src/UiPath.Caching/ILocalEntry.cs index 266e83f7..6348df73 100644 --- a/src/UiPath.Caching/ILocalEntry.cs +++ b/src/UiPath.Caching/ILocalEntry.cs @@ -28,6 +28,9 @@ internal interface ILocalEntry /// 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; } + /// The bounds of a value that came out of a frame with a window; default for every entry but the library's observed one. + ObservedLife Observed => default; + /// Marks the entry's change token as fired; set from the token's own change callback, which runs at once on a token that fired before it registered. void MarkTokenChanged(); diff --git a/src/UiPath.Caching/InnerTier.cs b/src/UiPath.Caching/InnerTier.cs index 088ec2df..42ad4854 100644 --- a/src/UiPath.Caching/InnerTier.cs +++ b/src/UiPath.Caching/InnerTier.cs @@ -5,9 +5,10 @@ namespace UiPath.Caching; /// What the cache under a multilayer cache is and can do, decided once when that cache is built. internal abstract class InnerTier { - private protected InnerTier(bool isShared, ISharedTier? shared, ISharedHashTier? versioned, PeerFieldLimits peerLimits, IConnectionState? connection) + private protected InnerTier(bool isShared, ISharedTier? shared, ISharedHashTier? versioned, PeerFieldLimits peerLimits, IConnectionState? connection, bool keepsBounds = true) { IsShared = isShared; + KeepsBounds = keepsBounds; Shared = shared; Versioned = versioned; PeerLimits = peerLimits; @@ -32,6 +33,12 @@ private protected InnerTier(bool isShared, ISharedTier? shared, ISharedHashTier? /// The tier's own connection state, when it reports one. public IConnectionState? Connection { get; } + /// Whether every entry the tier hands up that came out of a frame with a window carries its bounds; no tier does, and a shared one answers once, when it is built. + public bool KeepsBounds { get; } + + /// Whether an answer of the tier can have come out of a frame with a window; no tier cannot, and a shared one is asked on every call. + public virtual bool MayHaveMetWindowedFrame => false; + /// The null caches stand for no tier; any other cache is a shared (distributed) inner tier, Redis or any other cache. public static InnerTier For(object cache, IMultilayerCacheOptions? options = null) => cache is NullCache or NullHashCache ? None : new SharedInnerTier(cache, options as InMemoryRedisCacheOptions); diff --git a/src/UiPath.Caching/KeyMove/SchedulePointStep.cs b/src/UiPath.Caching/KeyMove/SchedulePointStep.cs index 7407c24d..3243d1a2 100644 --- a/src/UiPath.Caching/KeyMove/SchedulePointStep.cs +++ b/src/UiPath.Caching/KeyMove/SchedulePointStep.cs @@ -30,4 +30,5 @@ internal enum SchedulePointStep : byte StandardWrite, FenceObserve, ReadLife, + ReadFrameAgain, } diff --git a/src/UiPath.Caching/MemoryCacheSetter.cs b/src/UiPath.Caching/MemoryCacheSetter.cs index df6ee106..9e96d07c 100644 --- a/src/UiPath.Caching/MemoryCacheSetter.cs +++ b/src/UiPath.Caching/MemoryCacheSetter.cs @@ -45,6 +45,9 @@ internal abstract class MemoryCacheSetter( /// Takes a peer's write to a held key for a background refresh; false drops the entry. internal Func? PeerRefresh { get; init; } + /// On a layered string cache with a shared tier: an event never rebuilds the entry it changes. + internal bool DropsOnRefreshEvent { get; init; } + /// Told when the token of an entry a peer's write refreshes changes, for any reason. internal Action? PeerRefreshChanged { get; init; } @@ -110,6 +113,11 @@ public bool Set(TOptions options, ICacheEntry item, Type entryType, Ti { // In place, not on a copy: the stored entry is compared by reference. A promoted item is rewritten in its key's turn, and the later write wins. recorded.LocalDeadline = deadline; + if (recorded.Observed is { IsSet: true } observed) + { + // Every store of the item carries it again, so the copy leaves at its bound however often it is rewritten. + entry.ExpirationTokens.Add(new BoundToken(Clock, observed.FreshUntil)); + } } entry.Value = item; @@ -226,7 +234,8 @@ private void RefreshMetadata(RefreshMetadataState metadataState) Invalidations?.Invalidated(metadataState.CacheKey); } - if (!token.MetadataHasChanged && token.Expiration == null) + // Over a shared tier the copy is dropped, as on a removal: the next read takes the tier's own expiration. + if (DropsOnRefreshEvent || (!token.MetadataHasChanged && token.Expiration == null)) { return; } diff --git a/src/UiPath.Caching/MultilayerCache.Fill.cs b/src/UiPath.Caching/MultilayerCache.Fill.cs index f4d1b8f6..d240fdc0 100644 --- a/src/UiPath.Caching/MultilayerCache.Fill.cs +++ b/src/UiPath.Caching/MultilayerCache.Fill.cs @@ -91,7 +91,8 @@ private async ValueTask> TryFillCoreAsync(CacheKey cacheKey, T? case FillOutcome.Added: Layered().FillFromInnerRead(options, mark, value, policy); break; - case FillOutcome.Existed when filled.Expiration is { } deadline && deadline > _clock.GetUtcNow(): + // Asked after the answer arrived: once the tier may have met a windowed frame, the deadline may be one no bound comes with. + case FillOutcome.Existed when filled.Expiration is { } deadline && deadline > _clock.GetUtcNow() && !_innerTier.MayHaveMetWindowedFrame: Layered().FillFromInnerRead(options with { Expiration = deadline }, mark, filled.Existing, policy); break; case FillOutcome.Existed: @@ -153,7 +154,7 @@ private async ValueTask> SetIfChangedCoreAsync(CacheKey cache case ChangeOutcome.Filled: Layered().FillFromInnerRead(options, mark, value, policy); break; - case ChangeOutcome.Unchanged when changed.Expiration is { } deadline && deadline > _clock.GetUtcNow(): + case ChangeOutcome.Unchanged when changed.Expiration is { } deadline && deadline > _clock.GetUtcNow() && !_innerTier.MayHaveMetWindowedFrame: Layered().FillFromInnerRead(options with { Expiration = deadline }, mark, changed.Current, policy); break; case ChangeOutcome.Replaced: @@ -197,7 +198,7 @@ private bool CanFill(CacheEntryOptions options, T? value, CachePolicy policy) } private ICacheEntry? HeldLocally(string name) => - _memoryCache.TryGetValue(name, out ICacheEntry? held) && held!.Found ? held : null; + _memoryCache.TryGetValue(name, out ICacheEntry? held) && held!.Found && Live(held) ? held : null; /// The held entry as of its local deadline, which is when this tier evicts it. private ICacheEntry? LocalSnapshot(string name) @@ -230,7 +231,13 @@ private FillResult FillLocally(CacheEntryOptions options, T? value, CacheP return new(FillOutcome.Added, default); } - return HeldLocally(name) is { } existing ? new(FillOutcome.Existed, existing.Value) : default; + if (HeldLocally(name) is not { } existing) + { + return default; + } + + LatchObserved(existing); + return new(FillOutcome.Existed, existing.Value); } private async ValueTask> ChangeLocallyAsync(CacheEntryOptions options, T? value, IEqualityComparer comparer, CachePolicy policy) @@ -244,6 +251,7 @@ private async ValueTask> ChangeLocallyAsync(CacheEntryOptions // The comparer never runs in the key's turn: a slow one would stall every key of the stripe. if (seen is not null && ChangeComparison.AreEqual(comparer, seen.Value, value)) { + LatchObserved(seen); return new(ChangeOutcome.Unchanged, seen.Value); } @@ -274,6 +282,15 @@ private async ValueTask> ChangeLocallyAsync(CacheEntryOptions return default; } + /// An answer from an observed entry tells whoever asks this cache from then on that it may have met a windowed frame. + private void LatchObserved(object answered) + { + if (answered is ObservedEntry && !_answeredObserved) + { + _answeredObserved = true; + } + } + private bool TryStoreLocalChange(CacheEntryOptions options, T? value, CachePolicy policy, ICacheEntry? seen, bool last, LocalChange change) { var current = HeldLocally(options.CacheKey.Name); diff --git a/src/UiPath.Caching/MultilayerCache.Generate.cs b/src/UiPath.Caching/MultilayerCache.Generate.cs index 985be7e0..4835ce33 100644 --- a/src/UiPath.Caching/MultilayerCache.Generate.cs +++ b/src/UiPath.Caching/MultilayerCache.Generate.cs @@ -5,7 +5,7 @@ internal sealed partial class MultilayerCache /// A local hit only, never the inner tier: for a caller that has just taken a key, where the only thing that can have changed is a run of this process. private bool TryGetLocalEntry(CacheEntryOptions options, [MaybeNullWhen(false)] out ICacheEntry entry) { - if ((_connectionState.IsConnected || _useLocalOnlyWhenDisconnected) && _memoryCache.TryGetValue(options.CacheKey.Name, out entry) && entry!.Found) + if ((_connectionState.IsConnected || _useLocalOnlyWhenDisconnected) && _memoryCache.TryGetValue(options.CacheKey.Name, out entry) && entry!.Found && Live(entry)) { MarkRead(entry); return true; diff --git a/src/UiPath.Caching/MultilayerCache.Layered.cs b/src/UiPath.Caching/MultilayerCache.Layered.cs index 3af6db50..e687a693 100644 --- a/src/UiPath.Caching/MultilayerCache.Layered.cs +++ b/src/UiPath.Caching/MultilayerCache.Layered.cs @@ -72,6 +72,9 @@ public async ValueTask StoreStampedAsync(CacheEntryOptions options public bool KeepLocal(CacheEntryOptions options, T? value, TimeSpan? maxExpiration, CachePolicy policy) => cache.MemorySet(options, value, maxExpiration, null, policy, read: true); + public bool KeepObserved(CacheEntryOptions options, T? value, ObservedLife observed, TimeSpan? maxExpiration, CachePolicy policy) => + cache.MemorySet(options, value, maxExpiration, CacheEntryFactory.CreateObserved(value, options.Expiration, observed, options.Metadata as EntryValidators), policy, read: true); + public bool KeepWhileDisconnected(CacheEntryOptions options, T? value, TimeSpan? maxExpiration, ICacheEntry? entry, CachePolicy policy) => cache.MemorySet(options, value, maxExpiration, entry, read: true, failSafe: policy); diff --git a/src/UiPath.Caching/MultilayerCache.Nested.cs b/src/UiPath.Caching/MultilayerCache.Nested.cs index 1986b5f0..624478bb 100644 --- a/src/UiPath.Caching/MultilayerCache.Nested.cs +++ b/src/UiPath.Caching/MultilayerCache.Nested.cs @@ -58,7 +58,10 @@ public PeerKeep Keep(MultilayerCacheBase cache, RefreshMetadataState held, PeerR return false; } - var item = o._cacheEntryFactory.Create(entry.Value, options.Expiration); + // A reread that came out of a frame with a window keeps its bounds in the item. + var item = entry is ObservedEntry observed + ? CacheEntryFactory.CreateObserved(entry.Value, options.Expiration, observed.Observed) + : o._cacheEntryFactory.Create(entry.Value, options.Expiration); InheritRead(held.CacheEntity, item); LinkRefresh(held.CacheEntity, item); if (!o.MemorySet(options, entry.Value, o.LocalLifetime(policy), item, policy, read: false)) diff --git a/src/UiPath.Caching/MultilayerCache.Read.cs b/src/UiPath.Caching/MultilayerCache.Read.cs index 8afd8e19..58fd434c 100644 --- a/src/UiPath.Caching/MultilayerCache.Read.cs +++ b/src/UiPath.Caching/MultilayerCache.Read.cs @@ -100,7 +100,7 @@ public async ValueTask ContainsAsync(CacheKey cacheKey, CancellationTok var cacheEntryOptions = _entryBuilder.BuildEntryOptions(cacheKey, default, token); try { - return _memoryCache.TryGetValue(cacheEntryOptions.CacheKey.Name, out _) || await _innerCache.ContainsAsync(cacheEntryOptions.CacheKey, cacheEntryOptions.Token).ConfigureAwait(false); + return (_memoryCache.TryGetValue(cacheEntryOptions.CacheKey.Name, out var held) && Live(held)) || await _innerCache.ContainsAsync(cacheEntryOptions.CacheKey, cacheEntryOptions.Token).ConfigureAwait(false); } catch (Exception ex) when (!(ex is OperationCanceledException && cacheEntryOptions.Token.IsCancellationRequested)) { @@ -121,8 +121,8 @@ public ValueTask ContainsAsync(Span cacheKey, CancellationToken t { NotCacheableException.ThrowIfNotCacheable(); var cacheEntryOptions = _entryBuilder.BuildEntryOptions(cacheKey, default, token); - return _memoryCache.TryGetValue(cacheEntryOptions.CacheKey.Name, out var value) - ? value?.Expiration.Subtract(_clock.GetUtcNow()) + return _memoryCache.TryGetValue(cacheEntryOptions.CacheKey.Name, out var value) && Live(value) + ? LocalTimeToLive(value) : await _innerCache.TimeToLiveAsync(cacheEntryOptions.CacheKey, token); } @@ -130,7 +130,7 @@ public ValueTask ContainsAsync(Span cacheKey, CancellationToken t { NotCacheableException.ThrowIfNotCacheable(); return !token.IsCancellationRequested && TryGetLocal(cacheKey, token, out var local) - ? new ValueTask(local.Expiration.Subtract(_clock.GetUtcNow())) + ? new ValueTask(LocalTimeToLive(local)) : TimeToLiveAsync(new CacheKey(cacheKey), token); } @@ -139,8 +139,8 @@ public ValueTask ContainsAsync(Span cacheKey, CancellationToken t NotCacheableException.ThrowIfNotCacheable(); var cacheEntryOptions = _entryBuilder.BuildEntryOptions(cacheKey, default, token); - return _memoryCache.TryGetValue(cacheEntryOptions.CacheKey.Name, out var value) - ? value?.Expiration + return _memoryCache.TryGetValue(cacheEntryOptions.CacheKey.Name, out var value) && Live(value) + ? LocalExpireTime(value) : await _innerCache.ExpireTimeAsync(cacheEntryOptions.CacheKey, token); } @@ -148,7 +148,7 @@ public ValueTask ContainsAsync(Span cacheKey, CancellationToken t { NotCacheableException.ThrowIfNotCacheable(); return !token.IsCancellationRequested && TryGetLocal(cacheKey, token, out var local) - ? new ValueTask(local.Expiration) + ? new ValueTask(LocalExpireTime(local)) : ExpireTimeAsync(new CacheKey(cacheKey), token); } @@ -163,13 +163,35 @@ public ValueTask ContainsAsync(Span cacheKey, CancellationToken t return default; } + /// The life left of a local entry; for an observed one, no longer than its freshness bound on the monotonic clock. + private TimeSpan? LocalTimeToLive(ICacheEntry? entry) + { + if (entry is null) + { + return null; + } + + var left = entry.Expiration.Subtract(_clock.GetUtcNow()); + if (entry is ObservedEntry observed) + { + var bound = _clock.GetElapsedTime(_clock.GetTimestamp(), observed.Observed.FreshUntil); + return bound < left ? bound : left; + } + + return left; + } + + /// The expiration of a local entry; for an observed one, now plus . + private DateTimeOffset? LocalExpireTime(ICacheEntry? entry) => + entry is ObservedEntry ? _clock.GetUtcNow() + LocalTimeToLive(entry) : entry?.Expiration; + private async ValueTask[]> GetInnerAsync(CacheEntryOptions[] options, CachePolicy policy, CancellationToken token = default) { List> results = []; List cacheEntriesToFetch = []; foreach (var option in options) { - if (_memoryCache.TryGetValue>(option.CacheKey.Name, out var entry)) + if (_memoryCache.TryGetValue>(option.CacheKey.Name, out var entry) && Live(entry)) { LogFoundLocal(Logged(option, typeof(T))); if (_connectionState.IsConnected) @@ -218,7 +240,7 @@ public ValueTask ContainsAsync(Span cacheKey, CancellationToken t LogFoundInnerCacheCopy(LoggedComposed(key, typeof(T))); var option = cacheEntriesToFetch[i]; option.Expiration = entry.Expiration; - Layered().FillFromInnerRead(option, marks?[i] ?? 0, entry.Value, policy); + Layered().KeepFetched(option, marks?[i] ?? 0, entry, policy); } return results.ToArray(); @@ -226,7 +248,7 @@ public ValueTask ContainsAsync(Span cacheKey, CancellationToken t private async ValueTask GetInnerAsync(CacheEntryOptions options, CachePolicy policy) { - if (_memoryCache.TryGetValue>(options.CacheKey.Name, out var entry)) + if (_memoryCache.TryGetValue>(options.CacheKey.Name, out var entry) && Live(entry)) { LogFoundLocal(Logged(options, typeof(T))); if(_connectionState.IsConnected) @@ -268,7 +290,7 @@ public ValueTask ContainsAsync(Span cacheKey, CancellationToken t for (int i = 0; i < options.Length; i++) { var option = options[i]; - if (_memoryCache.TryGetValue>(option.CacheKey.Name, out var entry)) + if (_memoryCache.TryGetValue>(option.CacheKey.Name, out var entry) && Live(entry)) { LogFoundLocal(Logged(option, typeof(T))); if (_connectionState.IsConnected || _useLocalOnlyWhenDisconnected) @@ -316,7 +338,7 @@ public ValueTask ContainsAsync(Span cacheKey, CancellationToken t LogFoundInnerCacheCopy(LoggedComposed(key, typeof(T))); var option = cacheEntriesToFetch[j]; option.Expiration = entry.Expiration; - Layered().FillFromInnerRead(option, marks?[j] ?? 0, entry.Value, policy); + Layered().KeepFetched(option, marks?[j] ?? 0, entry, policy); } return results; @@ -324,7 +346,7 @@ public ValueTask ContainsAsync(Span cacheKey, CancellationToken t private async ValueTask> GetCacheEntryInnerAsync(CacheEntryOptions options, CachePolicy policy) { - if (_memoryCache.TryGetValue>(options.CacheKey.Name, out var entry)) + if (_memoryCache.TryGetValue>(options.CacheKey.Name, out var entry) && Live(entry)) { LogFoundLocal(Logged(options, typeof(T))); if (_connectionState.IsConnected || _useLocalOnlyWhenDisconnected) diff --git a/src/UiPath.Caching/MultilayerCache.Rehydrate.cs b/src/UiPath.Caching/MultilayerCache.Rehydrate.cs index 821519a6..22d2ae0e 100644 --- a/src/UiPath.Caching/MultilayerCache.Rehydrate.cs +++ b/src/UiPath.Caching/MultilayerCache.Rehydrate.cs @@ -231,7 +231,7 @@ private bool TryKeepAdopted(CacheEntryOptions target, long mark, ICacheEntry< { LogFoundInnerCacheCopy(LoggedComposed(target.CacheKey, typeof(T))); target.Expiration = entry.Expiration; - return Layered().FillFromInnerRead(target, mark, entry.Value, policy); + return Layered().KeepFetched(target, mark, entry, policy); } catch (Exception ex) when (!(ex is OperationCanceledException && token.IsCancellationRequested)) { diff --git a/src/UiPath.Caching/MultilayerCache.SafeFill.cs b/src/UiPath.Caching/MultilayerCache.SafeFill.cs index c4adb35a..2cfdfe2c 100644 --- a/src/UiPath.Caching/MultilayerCache.SafeFill.cs +++ b/src/UiPath.Caching/MultilayerCache.SafeFill.cs @@ -137,7 +137,7 @@ private Filled KeepFilled(FillArgs s, FillResult filled, BackgroundW case FillOutcome.Existed: var deadline = filled.Expiration ?? s.Options.Expiration; var adopted = _cacheEntryFactory.Create(filled.Existing, deadline); - if (filled.Expiration is not null && deadline > _clock.GetUtcNow()) + if (filled.Expiration is not null && deadline > _clock.GetUtcNow() && !_innerTier.MayHaveMetWindowedFrame) { KeepIfIntact(keeper, s, s.Options with { Expiration = deadline }, filled.Existing, adopted, ConnectedLifetime(s.Policy)); } @@ -364,7 +364,8 @@ private async ValueTask FillDetachedAsync(CacheEntryOptions options, T? private void SwapForStored(CacheEntryOptions options, CachePolicy policy, ICacheEntry kept, FillResult filled) { var name = options.CacheKey.Name; - if (filled.Expiration is not { } deadline || deadline <= _clock.GetUtcNow()) + // Once the tier may have met a windowed frame, the stored value's deadline may be one no bound comes with: the generated value only goes. + if (filled.Expiration is not { } deadline || deadline <= _clock.GetUtcNow() || _innerTier.MayHaveMetWindowedFrame) { ApplyLocal(name, (Cache: this, Name: name, Kept: kept), static s => s.Cache.IsLocalEntry(s.Name, s.Kept) && s.Cache.RemoveHeld(s.Name)); return; diff --git a/src/UiPath.Caching/MultilayerCache.SpanRead.cs b/src/UiPath.Caching/MultilayerCache.SpanRead.cs index 4192c740..dfb9112a 100644 --- a/src/UiPath.Caching/MultilayerCache.SpanRead.cs +++ b/src/UiPath.Caching/MultilayerCache.SpanRead.cs @@ -34,7 +34,7 @@ private LocalProbe ProbeLocal(ReadOnlySpan cacheKey, CancellationToken return LocalProbe.Unavailable; } - if (!memoryCache.TryGetValue(composed[..written], out var cached) || cached is not ICacheEntry found) + if (!memoryCache.TryGetValue(composed[..written], out var cached) || cached is not ICacheEntry found || !Live(found)) { return LocalProbe.Miss; } @@ -87,7 +87,7 @@ private LocalProbe ProbeLocalByName(CacheKey cacheKey, out ICacheEntry? en return LocalProbe.Unavailable; } - if (!_memoryCache.TryGetValue(cacheKey.Name, out var cached) || cached is not ICacheEntry found) + if (!_memoryCache.TryGetValue(cacheKey.Name, out var cached) || cached is not ICacheEntry found || !Live(found)) { return LocalProbe.Miss; } diff --git a/src/UiPath.Caching/MultilayerCache.Write.cs b/src/UiPath.Caching/MultilayerCache.Write.cs index 5050cd59..6b109e76 100644 --- a/src/UiPath.Caching/MultilayerCache.Write.cs +++ b/src/UiPath.Caching/MultilayerCache.Write.cs @@ -195,7 +195,7 @@ private async ValueTask WaitForRunAsync(InFlightKey key, TimeSpan timeout, /// private async ValueTask TryAddUnderLocalLockAsync(CacheEntryOptions options, T? value, CachePolicy policy, TimeSpan? localMaxExpiration) { - if (_memoryCache.TryGetValue(options.CacheKey.Name, out _)) + if (_memoryCache.TryGetValue(options.CacheKey.Name, out var held) && Live(held)) { return false; } diff --git a/src/UiPath.Caching/MultilayerCache.cs b/src/UiPath.Caching/MultilayerCache.cs index ccdd8577..22eedb31 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, IRevalidatingCache +internal sealed partial class MultilayerCache : MultilayerCacheBase, ICache, ISpanKeyCache, IResultCache, IMigrationCache, IRevalidatingCache, IFrameTier { private readonly ICache _innerCache; @@ -19,6 +19,9 @@ internal sealed partial class MultilayerCache : MultilayerCacheBase, ICache, ISp private readonly LocalMemorySetter _localMemorySetter; + // Set when an Existed or Unchanged answer came from an observed entry in the local tier, before the answer leaves; never cleared. + private volatile bool _answeredObserved; + public MultilayerCache( string cacheName, ICache innerCache, @@ -50,13 +53,23 @@ public MultilayerCache( PeerRefreshChanged = _peerRefresher is { } changed ? changed.TokenChanged : null, // A keep that lands while a peer's event is dispatched is heard by the entry's token, not by the store. TokenChanged = (name, entry) => StaleOrNull?.Drop(name, entry), + DropsOnRefreshEvent = _innerTier.IsShared, }; _sharedInner = _innerTier.IsShared; } + /// Its own latch, or the live answer of its inner tier. + public bool MetWindowedFrame => _answeredObserved || _innerTier.MayHaveMetWindowedFrame; + + /// The answer of its inner tier, fixed when the cache was built. + public bool KeepsBounds => _innerTier.KeepsBounds; + /// The tier told of received invalidations: the inner cache when it tracks them; tests check the wiring. internal ISharedTier? Invalidations => _localMemorySetter.Invalidations; /// Runs, inner reads and generators fail-safe stopped waiting for, still going; tests check they drain once callers are done. internal int RunsInFlight => _innerReads.Count + _generations.Count + _background.InFlight + (_peerRefresher?.Pending ?? 0) + LateGenerations; + + /// An observed entry carries its bounds above any tier; any other entry is kept only from a tier that keeps bounds. + private protected override bool Keeps(object fetched) => fetched is ObservedEntry || _innerTier.KeepsBounds; } diff --git a/src/UiPath.Caching/MultilayerCacheBase.LayeredEntry.cs b/src/UiPath.Caching/MultilayerCacheBase.LayeredEntry.cs index 3c5e2f73..082603a2 100644 --- a/src/UiPath.Caching/MultilayerCacheBase.LayeredEntry.cs +++ b/src/UiPath.Caching/MultilayerCacheBase.LayeredEntry.cs @@ -80,6 +80,37 @@ public bool FillFromInnerRead(TOptions options, long mark, TValue value, CachePo return kept == true; } + /// The twin of that only an observed entry enters: the local item is built with its bounds. + /// Whether the value was kept locally. + public bool FillObserved(TOptions options, long mark, ICacheEntry fetched, CachePolicy policy, bool advance = false) + { + var observed = ((ObservedEntry)fetched).Observed; + var state = (Cache: cache, Shape: shape, Options: options, Value: shape.Present(fetched.Value), Observed: observed, Max: cache.LocalLifetime(policy), Policy: policy); + var kept = advance + ? cache._background.FillAdvancing(options.CacheKey.Name, mark, state, static s => s.Shape.KeepObserved(s.Options, s.Value, s.Observed, s.Max, s.Policy)) + : cache._background.Fill(options.CacheKey.Name, mark, state, static s => s.Shape.KeepObserved(s.Options, s.Value, s.Observed, s.Max, s.Policy)); + if (kept is null) + { + cache.LogInnerCopyNotKept(LoggedKey.For(cache._masker, options.CallerKey, options.CacheKey.Name, shape.EntryType)); + } + + return kept == true; + } + + /// The one adoption decision for an entry read from the inner tier: an observed entry is kept with its bounds, any other through , and none when the cache does not keep it. + /// False when no local copy is made. + public bool KeepFetched(TOptions options, long mark, ICacheEntry fetched, CachePolicy policy, bool advance = false) + { + if (!cache.Keeps(fetched)) + { + return false; + } + + return fetched is ObservedEntry + ? FillObserved(options, mark, fetched, policy, advance) + : FillFromInnerRead(options, mark, shape.Present(fetched.Value), policy, advance); + } + /// Stores and announces the value, or only keeps it locally while the inner tier is disconnected. public async ValueTask StoreAsync(TOptions options, TValue value, bool disconnected, CachePolicy policy) { @@ -200,7 +231,7 @@ private bool Keep(TOptions options, CachePolicy policy, ICacheEntry fetc { shape.LogFoundInner(options); shape.Adopt(ref options, fetched); - return FillFromInnerRead(options, mark, shape.Present(fetched.Value), policy); + return KeepFetched(options, mark, fetched, policy); } private async ValueTask RehydrateAsync(CacheKey originalCacheKey, DateTimeOffset entryExpiration, Func> generator, CachePolicy policy, TimeSpan duration, TimeSpan? rehydrateJitter, RehydrateRun run, CancellationToken ct, RehydrateOverride? shaped = null) diff --git a/src/UiPath.Caching/MultilayerCacheBase.PeerRefresh.cs b/src/UiPath.Caching/MultilayerCacheBase.PeerRefresh.cs index 7077d8b5..7e764200 100644 --- a/src/UiPath.Caching/MultilayerCacheBase.PeerRefresh.cs +++ b/src/UiPath.Caching/MultilayerCacheBase.PeerRefresh.cs @@ -109,11 +109,12 @@ private protected sealed partial class PeerRefresher(MultilayerCacheBase cache) private const string ReasonOverflow = "overflow"; private const string ReasonStillDirty = "still_dirty"; private const string ReasonExpired = "expired"; + private const string ReasonNotKept = "not_kept"; // Where Reasons lists it. private const int IdleIndex = 0; - private static readonly string[] Reasons = [ReasonIdle, ReasonNotFound, ReasonFailed, ReasonTimedOut, ReasonDeclined, ReasonOverflow, ReasonStillDirty, ReasonExpired]; + private static readonly string[] Reasons = [ReasonIdle, ReasonNotFound, ReasonFailed, ReasonTimedOut, ReasonDeclined, ReasonOverflow, ReasonStillDirty, ReasonExpired, ReasonNotKept]; // Outcomes are counted as they happen and reported per drained batch, and at intervals while only idle drops arrive. private static readonly TimeSpan FlushInterval = TimeSpan.FromSeconds(10); @@ -543,6 +544,11 @@ private void Settle(Taken taken, PeerRead? read, string? failure, Exception? err { End(item, ReasonNotFound); } + else if (!cache.Keeps(found.Entry!)) + { + // The peer's write made the held entry out of date, and the reread may not take its place. + End(item, ReasonNotKept); + } else { Keep(item, found, taken.Mark); diff --git a/src/UiPath.Caching/MultilayerCacheBase.cs b/src/UiPath.Caching/MultilayerCacheBase.cs index 2bad30ad..b32bc7a7 100644 --- a/src/UiPath.Caching/MultilayerCacheBase.cs +++ b/src/UiPath.Caching/MultilayerCacheBase.cs @@ -303,6 +303,16 @@ private protected static CachePolicy WithoutFailSafe(CachePolicy policy) => private protected static TimeSpan BoundedTimeout(TimeSpan timeout) => timeout.TotalMilliseconds > int.MaxValue ? TimeSpan.FromMilliseconds(int.MaxValue) : timeout; + /// Whether an entry a hash lookup returned is an observed one, which the hash cache never answers from; reads no clock. + private protected static bool Foreign(object? entry) => entry is ObservedEntry; + + /// Whether an entry a lookup returned may answer as a hit: false only for an observed entry whose freshness ended on the monotonic clock, whatever the store did meanwhile. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private protected bool Live(object? entry) => entry is not ObservedEntry observed || FreshNow(observed); + + /// Whether an entry read from the inner tier may be kept locally: an entry without bounds only from a tier that keeps bounds. + private protected abstract bool Keeps(object fetched); + /// Notes a local hit, so a peer's write to the entry refreshes it rather than drops it while the read is recent. private protected void MarkRead(object? entry) { @@ -697,4 +707,8 @@ private IConnectionState GetConnectionMonitor(params object?[] connectionStates) var lst = connectionStates.OfType().ToArray(); return lst.Length == 0 ? NullConnectionStateMonitor.Instance : new ConnectionStateMonitor(Telemetry, _multiLayerCacheOptions.ConnectionMonitorPeriod ?? TimeSpan.FromSeconds(5), _clock, lst); } + + /// The clock read of , out of line so a hit on a plain entry inlines only the class test. + [MethodImpl(MethodImplOptions.NoInlining)] + private bool FreshNow(ObservedEntry observed) => observed.Observed.Fresh(_clock.GetTimestamp()); } diff --git a/src/UiPath.Caching/MultilayerHashCache.GetOrAdd.cs b/src/UiPath.Caching/MultilayerHashCache.GetOrAdd.cs index f63dd729..3911ccf0 100644 --- a/src/UiPath.Caching/MultilayerHashCache.GetOrAdd.cs +++ b/src/UiPath.Caching/MultilayerHashCache.GetOrAdd.cs @@ -277,7 +277,7 @@ internal sealed partial class MultilayerHashCache /// A local hit only, never the inner tier: for a caller that has just taken a key, where the only thing that can have changed is a run of this process. private bool TryGetLocalEntry(InternalHashCacheEntryOptions options, [MaybeNullWhen(false)] out ICacheEntry> entry) { - if ((_connectionState.IsConnected || _useLocalOnlyWhenDisconnected) && _memoryCache.TryGetValue(options.CacheKey.Name, out entry) && entry!.Found) + if ((_connectionState.IsConnected || _useLocalOnlyWhenDisconnected) && _memoryCache.TryGetValue(options.CacheKey.Name, out entry) && entry!.Found && !Foreign(entry)) { MarkRead(entry); return true; diff --git a/src/UiPath.Caching/MultilayerHashCache.Inspect.cs b/src/UiPath.Caching/MultilayerHashCache.Inspect.cs index 9f5ce8c0..ac692262 100644 --- a/src/UiPath.Caching/MultilayerHashCache.Inspect.cs +++ b/src/UiPath.Caching/MultilayerHashCache.Inspect.cs @@ -14,7 +14,7 @@ public async ValueTask ContainsAsync(CacheKey cacheKey, CancellationTok var cacheEntryOptions = _entryBuilder.BuildEntryOptions(cacheKey, default, token: token); try { - return _memoryCache.TryGetValue(cacheEntryOptions.CacheKey.Name, out _) || await _innerCache.ContainsAsync(cacheEntryOptions.CacheKey, cacheEntryOptions.Token).ConfigureAwait(false); + return (_memoryCache.TryGetValue(cacheEntryOptions.CacheKey.Name, out var held) && !Foreign(held)) || await _innerCache.ContainsAsync(cacheEntryOptions.CacheKey, cacheEntryOptions.Token).ConfigureAwait(false); } catch (Exception ex) when (!(ex is OperationCanceledException && cacheEntryOptions.Token.IsCancellationRequested)) { @@ -35,7 +35,7 @@ public ValueTask ContainsAsync(Span cacheKey, CancellationToken t { NotCacheableException.ThrowIfNotCacheable(); var cacheEntryOptions = _entryBuilder.BuildEntryOptions(cacheKey, default, token: token); - return _memoryCache.TryGetValue(cacheEntryOptions.CacheKey.Name, out var value) + return _memoryCache.TryGetValue(cacheEntryOptions.CacheKey.Name, out var value) && !Foreign(value) ? value?.Expiration.Subtract(_clock.GetUtcNow()) : await _innerCache.TimeToLiveAsync(cacheEntryOptions.CacheKey, token); } @@ -52,7 +52,7 @@ public ValueTask ContainsAsync(Span cacheKey, CancellationToken t { NotCacheableException.ThrowIfNotCacheable(); var cacheEntryOptions = _entryBuilder.BuildEntryOptions(cacheKey, default, token: token); - return _memoryCache.TryGetValue(cacheEntryOptions.CacheKey.Name, out var value) + return _memoryCache.TryGetValue(cacheEntryOptions.CacheKey.Name, out var value) && !Foreign(value) ? value?.Expiration : await _innerCache.ExpireTimeAsync(cacheEntryOptions.CacheKey, token); } @@ -69,7 +69,7 @@ public ValueTask ContainsAsync(Span cacheKey, CancellationToken t { NotCacheableException.ThrowIfNotCacheable(); var options = _entryBuilder.BuildEntryOptions(cacheKey, _clock.ToDateTimeOffset(_multiLayerCacheOptions.DefaultExpiration), token: token); - return _memoryCache.TryGetValue(options.CacheKey.Name, out var entry) + return _memoryCache.TryGetValue(options.CacheKey.Name, out var entry) && !Foreign(entry) ? (entry?.Metadata) : await _innerCache.GetMetadataAsync(options.CacheKey, token).ConfigureAwait(false); } @@ -119,7 +119,7 @@ public async ValueTask SetMetadataAsync(CacheKey cacheKey, IDictionary< return false; } - if(_memoryCache.TryGetValue(cacheEntryOptions.CacheKey.Name, out var entry) && entry != null) + if(_memoryCache.TryGetValue(cacheEntryOptions.CacheKey.Name, out var entry) && entry != null && !Foreign(entry)) { cacheEntryOptions.Expiration = entry.Expiration; } diff --git a/src/UiPath.Caching/MultilayerHashCache.Layered.cs b/src/UiPath.Caching/MultilayerHashCache.Layered.cs index 3e9eb497..169fc2d8 100644 --- a/src/UiPath.Caching/MultilayerHashCache.Layered.cs +++ b/src/UiPath.Caching/MultilayerHashCache.Layered.cs @@ -45,6 +45,9 @@ public void Adopt(ref InternalHashCacheEntryOptions options, ICacheEntry value, TimeSpan? maxExpiration, CachePolicy policy) => cache.MemorySet(options, value, maxExpiration, policy: policy, read: true); + /// Never reached: the hash cache keeps no observed entry. + public bool KeepObserved(InternalHashCacheEntryOptions options, IDictionary value, ObservedLife observed, TimeSpan? maxExpiration, CachePolicy policy) => false; + public bool KeepWhileDisconnected(InternalHashCacheEntryOptions options, IDictionary value, TimeSpan? maxExpiration, ICacheEntry>? entry, CachePolicy policy) => cache.MemorySet(options, value, maxExpiration, keepWhenAbsent: true, read: true); diff --git a/src/UiPath.Caching/MultilayerHashCache.PeerUpdate.cs b/src/UiPath.Caching/MultilayerHashCache.PeerUpdate.cs index 9c4ccef0..abfbe06d 100644 --- a/src/UiPath.Caching/MultilayerHashCache.PeerUpdate.cs +++ b/src/UiPath.Caching/MultilayerHashCache.PeerUpdate.cs @@ -192,7 +192,7 @@ private void MarkDropped(string name) private bool TryMergeLocal(ref InternalHashCacheEntryOptions options, IDictionary fields, [MaybeNullWhen(false)] out IDictionary merged) { if (!_memoryCache.TryGetValue(options.CacheKey.Name, out ICacheEntry>? held) || held is null || !held.Found || held.Value is null - || _awaitingRefresh.TryGetValue(held, out _)) + || Foreign(held) || _awaitingRefresh.TryGetValue(held, out _)) { merged = null; options.Version = 0; diff --git a/src/UiPath.Caching/MultilayerHashCache.Read.cs b/src/UiPath.Caching/MultilayerHashCache.Read.cs index dcced677..2dc53a2b 100644 --- a/src/UiPath.Caching/MultilayerHashCache.Read.cs +++ b/src/UiPath.Caching/MultilayerHashCache.Read.cs @@ -109,7 +109,7 @@ internal sealed partial class MultilayerHashCache private async ValueTask>> GetCacheEntryAsync(InternalHashCacheEntryOptions options, CachePolicy policy, bool localMissed = false) { - if (!localMissed && _memoryCache.TryGetValue>>(options.CacheKey.Name, out var cacheEntry)) + if (!localMissed && _memoryCache.TryGetValue>>(options.CacheKey.Name, out var cacheEntry) && !Foreign(cacheEntry)) { LogFoundLocal(Logged(options, typeof(T))); if (_connectionState.IsConnected) diff --git a/src/UiPath.Caching/MultilayerHashCache.SafeFill.cs b/src/UiPath.Caching/MultilayerHashCache.SafeFill.cs index c17e7759..0e03ca2e 100644 --- a/src/UiPath.Caching/MultilayerHashCache.SafeFill.cs +++ b/src/UiPath.Caching/MultilayerHashCache.SafeFill.cs @@ -162,7 +162,7 @@ private void KeepIfIntact(BackgroundWrites.Keeper keeper, InternalHashCacheEn var adopted = options; shape.Adopt(ref adopted, stored); - Layered().FillFromInnerRead(adopted, mark, stored.Value ?? Empty(), policy); + Layered().KeepFetched(adopted, mark, stored, policy); return stored; } diff --git a/src/UiPath.Caching/MultilayerHashCache.SpanRead.cs b/src/UiPath.Caching/MultilayerHashCache.SpanRead.cs index 98f8add0..4b2756fb 100644 --- a/src/UiPath.Caching/MultilayerHashCache.SpanRead.cs +++ b/src/UiPath.Caching/MultilayerHashCache.SpanRead.cs @@ -70,7 +70,7 @@ private LocalProbe ProbeLocal(ReadOnlySpan cacheKey, out ICacheEntry> found) + if (!memoryCache.TryGetValue(composed[..written], out var cached) || cached is not ICacheEntry> found || Foreign(found)) { return LocalProbe.Miss; } @@ -122,7 +122,7 @@ private LocalProbe ProbeLocalByName(CacheKey cacheKey, out ICacheEntry> found) + if (!_memoryCache.TryGetValue(cacheKey.Name, out var cached) || cached is not ICacheEntry> found || Foreign(found)) { return LocalProbe.Miss; } diff --git a/src/UiPath.Caching/MultilayerHashCache.cs b/src/UiPath.Caching/MultilayerHashCache.cs index 88a4240a..75e5f909 100644 --- a/src/UiPath.Caching/MultilayerHashCache.cs +++ b/src/UiPath.Caching/MultilayerHashCache.cs @@ -4,7 +4,7 @@ namespace UiPath.Caching; -internal sealed partial class MultilayerHashCache : MultilayerCacheBase, IHashCache, ISpanKeyHashCache +internal sealed partial class MultilayerHashCache : MultilayerCacheBase, IHashCache, ISpanKeyHashCache, IFrameTier { // A hash that stays a write short for long, such as when a write of this node was never laid over it, must not hold every write since. private const int MaxOwnWritesAhead = 32; @@ -62,6 +62,12 @@ public MultilayerHashCache( }; } + /// The live answer of its inner tier: the hash cache never answers from an observed entry, so it has no latch. + public bool MetWindowedFrame => _innerTier.MayHaveMetWindowedFrame; + + /// The answer of its inner tier, fixed when the cache was built. + public bool KeepsBounds => _innerTier.KeepsBounds; + /// The tier told of received invalidations: the inner cache when it tracks them; tests check the wiring. internal ISharedTier? Invalidations => _localMemorySetter.Invalidations; @@ -73,6 +79,9 @@ public MultilayerHashCache( private bool OnlyTier => !_sharedInner; + /// An observed entry is kept nowhere in the hash cache, and an entry without bounds only from a tier that keeps bounds. + private protected override bool Keeps(object fetched) => fetched is not ObservedEntry && _innerTier.KeepsBounds; + private static bool IsNullOrEmpty(IDictionary? value) => value is null || value.Count == 0; diff --git a/src/UiPath.Caching/ObservedEntry.cs b/src/UiPath.Caching/ObservedEntry.cs new file mode 100644 index 00000000..fd31a9c0 --- /dev/null +++ b/src/UiPath.Caching/ObservedEntry.cs @@ -0,0 +1,10 @@ +namespace UiPath.Caching; + +/// The non-generic base of the library's entry for a value that came out of a frame with a window: a lookup tests it with one class test, with no type argument and no interface call. +internal abstract record ObservedEntry +{ + private protected ObservedEntry(ObservedLife observed) => Observed = observed; + + /// The bounds the judgment handed on. + public ObservedLife Observed { get; } +} diff --git a/src/UiPath.Caching/ObservedLife.cs b/src/UiPath.Caching/ObservedLife.cs new file mode 100644 index 00000000..00dfedb1 --- /dev/null +++ b/src/UiPath.Caching/ObservedLife.cs @@ -0,0 +1,38 @@ +namespace UiPath.Caching; + +/// The two bounds an anchored judgment of a frame with a window hands on, as timestamps of the cache's monotonic clock; default when the value was not observed so. +/// The timestamp at which the value stops being fresh. +/// The timestamp at which the value may no longer be served as stale: plus the window. +internal readonly record struct ObservedLife(long FreshUntil, long KeptUntil) +{ + public bool IsSet => KeptUntil != 0; + + /// The bounds of a judgment made at , whose logical expiration lay ahead of its UTC reading; negative for an expired frame inside its window. + public static ObservedLife From(TimeProvider clock, long judgedAt, TimeSpan logicalLeft, TimeSpan window) + { + var frequency = clock.TimestampFrequency; + var freshUntil = Add(judgedAt, Units(logicalLeft, frequency)); + return new ObservedLife(freshUntil, Add(freshUntil, Units(window, frequency))); + } + + public bool Fresh(long timestamp) => timestamp < FreshUntil; + + public bool Kept(long timestamp) => timestamp < KeptUntil; + + /// The time since ; negative while the value is fresh. + public TimeSpan Age(TimeProvider clock, long timestamp) => clock.GetElapsedTime(FreshUntil, timestamp); + + /// A length of time in timestamp units, rounded down, so a bound never lands later than the length allows. + private static Int128 Units(TimeSpan span, long frequency) + { + var scaled = (Int128)span.Ticks * frequency; + var units = scaled / TimeSpan.TicksPerSecond; + return scaled < 0 && units * TimeSpan.TicksPerSecond != scaled ? units - 1 : units; + } + + private static long Add(long timestamp, Int128 units) + { + var sum = timestamp + units; + return sum > long.MaxValue ? long.MaxValue : sum < long.MinValue ? long.MinValue : (long)sum; + } +} diff --git a/src/UiPath.Caching/PublicAPI.Unshipped.txt b/src/UiPath.Caching/PublicAPI.Unshipped.txt index 010bc219..2df32498 100644 --- a/src/UiPath.Caching/PublicAPI.Unshipped.txt +++ b/src/UiPath.Caching/PublicAPI.Unshipped.txt @@ -101,6 +101,8 @@ UiPath.Caching.Redis.FormatSweepReport.DefaultOrEmpty.init -> void UiPath.Caching.Redis.FormatSweepReport.Failed.get -> long UiPath.Caching.Redis.FormatSweepReport.Failed.init -> void UiPath.Caching.Redis.FormatSweepReport.FormatSweepReport() -> void +UiPath.Caching.Redis.FormatSweepReport.Framed.get -> long +UiPath.Caching.Redis.FormatSweepReport.Framed.init -> void UiPath.Caching.Redis.FormatSweepReport.Held.get -> long UiPath.Caching.Redis.FormatSweepReport.Held.init -> void UiPath.Caching.Redis.FormatSweepReport.Lossy.get -> long diff --git a/src/UiPath.Caching/Redis/EntryFrame.cs b/src/UiPath.Caching/Redis/EntryFrame.cs new file mode 100644 index 00000000..30f4c16e --- /dev/null +++ b/src/UiPath.Caching/Redis/EntryFrame.cs @@ -0,0 +1,279 @@ +using System.Buffers.Binary; +using System.Text; +using UiPath.Caching.Serialization; + +namespace UiPath.Caching.Redis; + +internal readonly struct EntryFrame +{ + public const byte Header = FormatIdRules.FrameId; + public const byte Version = 1; + public const int ExpirationOffset = 3; + public const int HeadLength = 15; + public const int MaxETagBytes = 1024; + + private const int WindowOffset = ExpirationOffset + sizeof(long); + private const byte WindowFlag = 1; + private const byte LastModifiedFlag = 2; + private const byte ETagFlag = 4; + private const byte AllFlags = WindowFlag | LastModifiedFlag | ETagFlag; + + private static readonly UTF8Encoding Utf8 = new(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true); + private static readonly long MinUnixMilliseconds = DateTimeOffset.MinValue.ToUnixTimeMilliseconds(); + private static readonly long MaxUnixMilliseconds = DateTimeOffset.MaxValue.ToUnixTimeMilliseconds(); + + private EntryFrame(DateTimeOffset expiration, TimeSpan window, string? etag, DateTimeOffset? lastModified, ReadOnlyMemory inner) + { + Expiration = expiration; + Window = window; + ETag = etag; + LastModified = lastModified; + Inner = inner; + } + + public bool HasWindow => Window > TimeSpan.Zero; + + public DateTimeOffset Expiration { get; } + + public TimeSpan Window { get; } + + public string? ETag { get; } + + public DateTimeOffset? LastModified { get; } + + public ReadOnlyMemory Inner { get; } + + public static bool TryRead(ReadOnlyMemory stored, out EntryFrame frame) + { + frame = default; + var bytes = stored.Span; + if (bytes.Length < ExpirationOffset || bytes[0] != Header || bytes[1] != Version || bytes[2] is 0 or > AllFlags) + { + return false; + } + + var flags = bytes[2]; + var offset = ExpirationOffset; + var expiration = DateTimeOffset.MaxValue; + var window = TimeSpan.Zero; + if ((flags & WindowFlag) != 0) + { + if (bytes.Length < HeadLength) + { + return false; + } + + var seconds = BinaryPrimitives.ReadUInt32LittleEndian(bytes[WindowOffset..]); + if (seconds == 0) + { + return false; + } + + window = TimeSpan.FromTicks((long)seconds * TimeSpan.TicksPerSecond); + var milliseconds = BinaryPrimitives.ReadInt64LittleEndian(bytes[ExpirationOffset..]); + if (milliseconds != long.MaxValue) + { + // Keep the wire classification structural when a timestamp exceeds the range of DateTimeOffset. + expiration = DateTimeOffset.FromUnixTimeMilliseconds(Math.Clamp(milliseconds, MinUnixMilliseconds, MaxUnixMilliseconds)); + } + + offset = HeadLength; + } + + DateTimeOffset? lastModified = null; + if ((flags & LastModifiedFlag) != 0) + { + if (bytes.Length - offset < sizeof(long)) + { + return false; + } + + var milliseconds = BinaryPrimitives.ReadInt64LittleEndian(bytes[offset..]); + if (milliseconds >= MinUnixMilliseconds && milliseconds <= MaxUnixMilliseconds) + { + lastModified = DateTimeOffset.FromUnixTimeMilliseconds(milliseconds); + } + + offset += sizeof(long); + } + + ReadOnlySpan etag = default; + if ((flags & ETagFlag) != 0) + { + if (bytes.Length - offset < sizeof(ushort)) + { + return false; + } + + var length = BinaryPrimitives.ReadUInt16LittleEndian(bytes[offset..]); + offset += sizeof(ushort); + if (length is 0 or > MaxETagBytes || length > bytes.Length - offset) + { + return false; + } + + etag = bytes.Slice(offset, length); + offset += length; + } + + if (StartsWithReservedHeader(bytes[offset..])) + { + return false; + } + + frame = new EntryFrame(expiration, window, DecodeETag(etag), lastModified, stored[offset..]); + return true; + } + + /// Whether the first bytes are those of a frame: the header, the version and, when there, known flags. + public static bool LooksFramed(ReadOnlySpan head) => + head.Length >= 2 && head[0] == Header && head[1] == Version && (head.Length == 2 || head[2] is > 0 and <= AllFlags); + + /// Splits a frame off : the inner value as a copy, and the expiration and window of bit 0. + public static bool TryUnframe(byte[] stored, out FrameInfo info) + { + if (!TryRead(stored, out var frame)) + { + info = default; + return false; + } + + info = frame.HasWindow ? new FrameInfo(frame.Inner.ToArray(), frame.Expiration, frame.Window) : new FrameInfo(frame.Inner.ToArray(), null, null); + return true; + } + + public static bool LooksWindowed(ReadOnlySpan firstThree) => + firstThree.Length >= ExpirationOffset && firstThree[0] == Header && firstThree[1] == Version && (firstThree[2] & WindowFlag) != 0; + + public static bool Needed(TimeSpan window, EntryValidators? validators) => + window > TimeSpan.Zero || validators?.LastModified is not null || ETagLength(validators?.ETag) != 0; + + public static byte[] Write(ReadOnlySpan inner, DateTimeOffset expiration, TimeSpan window, EntryValidators? validators) + { + if (StartsWithReservedHeader(inner)) + { + throw new ArgumentException("An entry frame cannot contain a frame or tombstone header.", nameof(inner)); + } + + var etag = validators?.ETag; + var etagLength = ETagLength(etag); + var lastModified = validators?.LastModified; + var hasWindow = window > TimeSpan.Zero; + var length = hasWindow ? HeadLength : ExpirationOffset; + byte flags = hasWindow ? WindowFlag : (byte)0; + if (lastModified.HasValue) + { + flags |= LastModifiedFlag; + length += sizeof(long); + } + + if (etagLength != 0) + { + flags |= ETagFlag; + length += sizeof(ushort) + etagLength; + } + + if (flags == 0) + { + throw new ArgumentException("An entry frame requires a window or a validator.", nameof(validators)); + } + + var result = new byte[checked(length + inner.Length)]; + var bytes = result.AsSpan(); + bytes[0] = Header; + bytes[1] = Version; + bytes[2] = flags; + + var offset = ExpirationOffset; + if (hasWindow) + { + var milliseconds = expiration == DateTimeOffset.MaxValue ? long.MaxValue : expiration.ToUnixTimeMilliseconds(); + var seconds = (uint)Math.Clamp(window.Ticks / TimeSpan.TicksPerSecond, 1L, uint.MaxValue); + BinaryPrimitives.WriteInt64LittleEndian(bytes[ExpirationOffset..], milliseconds); + BinaryPrimitives.WriteUInt32LittleEndian(bytes[WindowOffset..], seconds); + offset = HeadLength; + } + + if (lastModified is { } modified) + { + BinaryPrimitives.WriteInt64LittleEndian(bytes[offset..], modified.ToUnixTimeMilliseconds()); + offset += sizeof(long); + } + + if (etagLength != 0) + { + BinaryPrimitives.WriteUInt16LittleEndian(bytes[offset..], (ushort)etagLength); + offset += sizeof(ushort); + Utf8.GetBytes(etag.AsSpan(), bytes.Slice(offset, etagLength)); + offset += etagLength; + } + + inner.CopyTo(bytes[offset..]); + return result; + } + + public DateTimeOffset LogicalExpiration(DateTimeOffset? keyDeadline) + { + if (!HasWindow) + { + return keyDeadline ?? DateTimeOffset.MaxValue; + } + + if (keyDeadline is not { } deadline) + { + return DateTimeOffset.MinValue; + } + + var keyBound = Math.Max(0, deadline.UtcTicks - Window.Ticks); + return new DateTimeOffset(Math.Min(Expiration.UtcTicks, keyBound), TimeSpan.Zero); + } + + public DateTimeOffset StaleUntil(DateTimeOffset? keyDeadline) + { + if (keyDeadline is not { } deadline) + { + return DateTimeOffset.MinValue; + } + + var until = LogicalExpiration(deadline).UtcTicks + Window.Ticks; + return new DateTimeOffset(Math.Min(until, deadline.UtcTicks), TimeSpan.Zero); + } + + private static bool StartsWithReservedHeader(ReadOnlySpan inner) => + !inner.IsEmpty && inner[0] is Header or FormatIdRules.TombstoneId; + + private static int ETagLength(string? etag) + { + if (etag is null || etag.Length is 0 or > MaxETagBytes) + { + return 0; + } + + try + { + var length = Utf8.GetByteCount(etag); + return length <= MaxETagBytes ? length : 0; + } + catch (EncoderFallbackException) + { + return 0; + } + } + + private static string? DecodeETag(ReadOnlySpan etag) + { + if (etag.IsEmpty) + { + return null; + } + + try + { + return Utf8.GetString(etag); + } + catch (DecoderFallbackException) + { + return null; + } + } +} diff --git a/src/UiPath.Caching/Redis/FormatInventory.cs b/src/UiPath.Caching/Redis/FormatInventory.cs index 7a01be50..90c87da1 100644 --- a/src/UiPath.Caching/Redis/FormatInventory.cs +++ b/src/UiPath.Caching/Redis/FormatInventory.cs @@ -28,8 +28,14 @@ internal sealed class FormatInventory( internal const string NoTtlReason = "no_ttl"; internal const string HashSampledReason = "hash_sampled"; + /// Every value stored in an entry frame, whatever the format inside it. + internal const string FrameName = "frame"; + + /// The frames with a stale window, counted under as well. + internal const string FrameWindowedName = "frame_windowed"; + private const string StringType = "string"; - private const int HeadLength = 2; + private const int HeadLength = 3; private const int HashPage = 100; private static readonly UTF8Encoding StrictUtf8 = new(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true); @@ -69,9 +75,22 @@ public Task> CountAsync(CacheKey keyPattern, C return null; } + if (formatId == FormatIdRules.FrameId && EntryFrame.LooksFramed(head)) + { + return FrameName; + } + return formatId < 0 || !registry.TryGetByFormat(formatId, out _) ? CacheValueFormats.UnknownName : registry.NameOf(formatId); } + /// The formats a value is counted under: its own, and as well for a frame with a window. + internal static IReadOnlyCollection FormatsOf(ReadOnlySpan head, ValueSerializerRegistry registry) => Classify(head, registry) switch + { + null => [], + FrameName when EntryFrame.LooksWindowed(head) => [FrameName, FrameWindowedName], + var format => [format], + }; + /// The inventory reason of a value stored in , one of 's answers: format_json, format_<name> or format_unknown. internal static string FormatReason(string format) => "format_" + format; @@ -88,7 +107,7 @@ public Task> CountAsync(CacheKey keyPattern, C /// Every reason an inventory can give: the fixed ones, and a format reason for json, unknown and each registered format, so a reading that has gone to zero can still be told. internal IReadOnlyCollection KnownReasons() => [ - .. new[] { EmptyReason, OversizeReason, NoTtlReason, HashSampledReason, FormatReason(CacheValueFormats.JsonName), FormatReason(CacheValueFormats.UnknownName) } + .. new[] { EmptyReason, OversizeReason, NoTtlReason, HashSampledReason, FormatReason(CacheValueFormats.JsonName), FormatReason(CacheValueFormats.UnknownName), FormatReason(FrameName), FormatReason(FrameWindowedName) } .Concat(registry.Entries.Select(static entry => FormatReason(entry.Name))) .Distinct(StringComparer.Ordinal), ]; @@ -268,7 +287,7 @@ private async Task> StringFormatsAsync(IDatabase rea try { var head = (byte[]?)await reader.StringGetRangeAsync(key, 0, HeadLength - 1, CommandFlags.DemandMaster).ConfigureAwait(false); - return head is not null && Classify(head, registry) is { } format ? [format] : []; + return head is null ? [] : FormatsOf(head, registry); } catch (RedisServerException ex) when (ex.Message.StartsWith("WRONGTYPE", StringComparison.OrdinalIgnoreCase)) { @@ -291,9 +310,9 @@ private async Task> HashFormatsAsync(IDatabase reade } var value = (byte[]?)entry.Value; - if (value is not null && Classify(value.AsSpan(0, Math.Min(value.Length, HeadLength)), registry) is { } format) + if (value is not null) { - formats.Add(format); + formats.UnionWith(FormatsOf(value.AsSpan(0, Math.Min(value.Length, HeadLength)), registry)); } if (++seen >= MaxHashFields) @@ -318,10 +337,9 @@ private async Task StringReasonsAsync(IDatabase reader, RedisKey key var ttlTask = reader.KeyTimeToLiveAsync(key, CommandFlags.DemandMaster); var head = (byte[]?)await headTask.ConfigureAwait(false); var ttl = await ttlTask.ConfigureAwait(false); - List formats = []; List reasons = []; - var format = head is null ? null : Classify(head, registry); - if (format is null) + var formats = head is null ? [] : FormatsOf(head, registry); + if (formats.Count == 0) { // An empty string is the cached-null marker; a key that went away since the scan answers empty too, so it is told by asking for it. if (!await reader.KeyExistsAsync(key, CommandFlags.DemandMaster).ConfigureAwait(false)) @@ -333,9 +351,8 @@ private async Task StringReasonsAsync(IDatabase reader, RedisKey key } else { - formats.Add(format); - reasons.Add(FormatReason(format)); - if (format == CacheValueFormats.JsonName && await reader.StringLengthAsync(key, CommandFlags.DemandMaster).ConfigureAwait(false) > maxValueBytes) + reasons.AddRange(formats.Select(FormatReason)); + if (formats.Contains(CacheValueFormats.JsonName) && await reader.StringLengthAsync(key, CommandFlags.DemandMaster).ConfigureAwait(false) > maxValueBytes) { reasons.Add(OversizeReason); } diff --git a/src/UiPath.Caching/Redis/FormatSweepReport.cs b/src/UiPath.Caching/Redis/FormatSweepReport.cs index 17899a82..632caf4f 100644 --- a/src/UiPath.Caching/Redis/FormatSweepReport.cs +++ b/src/UiPath.Caching/Redis/FormatSweepReport.cs @@ -30,6 +30,9 @@ public sealed class FormatSweepReport /// Strings in a format no registered serializer owns, which are left. public long Unreadable { get; init; } + /// Strings stored in an entry frame, which a sweep leaves as they are. + public long Framed { get; init; } + /// Strings offered within the last minute, by a read or an earlier pass, and skipped. public long Recent { get; init; } diff --git a/src/UiPath.Caching/Redis/FormatSweeper.cs b/src/UiPath.Caching/Redis/FormatSweeper.cs index b0ab2324..a13c1db7 100644 --- a/src/UiPath.Caching/Redis/FormatSweeper.cs +++ b/src/UiPath.Caching/Redis/FormatSweeper.cs @@ -279,6 +279,13 @@ private async Task SweepKeyAsync(IDatabase database, RedisKey key, byte[]? return await CountEmptyAsync(database, key, tally).ConfigureAwait(false); } + // A frame is left as it is in this version, and counted apart from an id nobody owns. + if (EntryFrame.LooksFramed(head)) + { + tally.Framed++; + return true; + } + if (ValueHeader.TryRead(head, out var formatId, out _)) { if (!registry.TryGetByFormat(formatId, out var source)) @@ -377,6 +384,12 @@ private async Task ConvertAsync(IDatabase database, RedisKey key, int limi if (!migration.Wants(target, stored)) { // A header means a writer or another sweep converted it since the scan; it is not held back as lossy. + if (EntryFrame.LooksFramed(stored)) + { + tally.Framed++; + return true; + } + if (ValueHeader.TryRead(stored, out var formatId, out _)) { CountHeaded(formatId, tally); @@ -466,6 +479,7 @@ private void Report(FormatSweepReport report, string group) Track("current", report.Current, group); Track("unreadable", report.Unreadable, group); Track("recent", report.Recent, group); + Track("framed", report.Framed, group); } private void Track(string outcome, long count, string group) @@ -532,6 +546,8 @@ private sealed class Tally public long Recent { get; set; } + public long Framed { get; set; } + public long Scanned { get; set; } public FormatSweepReport ToReport(string? next, bool completed) => new() @@ -546,6 +562,7 @@ private sealed class Tally Current = Current, Unreadable = Unreadable, Recent = Recent, + Framed = Framed, Scanned = Scanned, NextCursor = completed ? null : next, Completed = completed, diff --git a/src/UiPath.Caching/Redis/FrameRead.cs b/src/UiPath.Caching/Redis/FrameRead.cs new file mode 100644 index 00000000..8ec346cd --- /dev/null +++ b/src/UiPath.Caching/Redis/FrameRead.cs @@ -0,0 +1,6 @@ +namespace UiPath.Caching.Redis; + +/// What a read learned from a frame; default for a value that was not framed, except under an anchored read. +/// The value was a frame with a window, whatever the verdict. +/// The bounds of a frame with a window that an anchored read judged fresh or a stale candidate; default otherwise. +internal readonly record struct FrameRead(bool Framed, bool Windowed, bool ReadAgain, bool Expired, DateTimeOffset? LogicalExpiration, EntryValidators? Validators, ObservedLife Observed = default); diff --git a/src/UiPath.Caching/Redis/KeyLife.cs b/src/UiPath.Caching/Redis/KeyLife.cs new file mode 100644 index 00000000..858b091e --- /dev/null +++ b/src/UiPath.Caching/Redis/KeyLife.cs @@ -0,0 +1,60 @@ +namespace UiPath.Caching.Redis; + +/// What the caller knows about a key's remaining life when it interprets a value. +internal readonly struct KeyLife +{ + private const byte LateKind = 1; + private const byte AnchoredKind = 2; + private const byte JudgedKind = 3; + + private readonly long _ticks; + private readonly long _sentAt; + private readonly byte _kind; + private readonly bool _bounded; + + private KeyLife(byte kind, long ticks, long sentAt, bool bounded) + { + _kind = kind; + _ticks = ticks; + _sentAt = sentAt; + _bounded = bounded; + } + + /// A value-only read: a frame with a window cannot be judged. + public static KeyLife Unknown => default; + + /// The value came from a judged read, which judged it from its own send and dropped the deadline. + public static KeyLife Judged { get; } = new(JudgedKind, 0, 0, false); + + public bool IsLate => _kind == LateKind; + + public bool IsAnchored => _kind == AnchoredKind; + + public bool IsJudged => _kind == JudgedKind; + + /// The deadline of a late read; null for a key without a TTL. + public DateTimeOffset? Deadline => IsLate && _bounded ? new DateTimeOffset(_ticks, TimeSpan.Zero) : null; + + /// A read that added the TTL to its own clock on receipt; or null is no TTL. + public static KeyLife Late(DateTimeOffset? deadline) => + deadline is { } at && at != DateTimeOffset.MaxValue ? new(LateKind, at.UtcTicks, 0, true) : new(LateKind, 0, 0, false); + + /// An anchored atomic read: the TTL of the same atomic step, and the timestamp taken before the send; null is no TTL. + public static KeyLife Of(TimeSpan? timeToLive, long sentAt) => new(AnchoredKind, timeToLive?.Ticks ?? 0, sentAt, timeToLive.HasValue); + + /// The TTL less the time since the send, on the monotonic clock; null for a key without a TTL or a read that is not anchored. + public TimeSpan? Remaining(TimeProvider clock) => Remaining(clock, out _); + + /// As ; is the timestamp the time since the send was measured to. + public TimeSpan? Remaining(TimeProvider clock, out long judgedAt) + { + judgedAt = 0; + if (!IsAnchored || !_bounded) + { + return null; + } + + judgedAt = clock.GetTimestamp(); + return TimeSpan.FromTicks(_ticks) - clock.GetElapsedTime(_sentAt, judgedAt); + } +} diff --git a/src/UiPath.Caching/Redis/RedisCache.ByteCodec.cs b/src/UiPath.Caching/Redis/RedisCache.ByteCodec.cs index 2ea81b06..91eddacf 100644 --- a/src/UiPath.Caching/Redis/RedisCache.ByteCodec.cs +++ b/src/UiPath.Caching/Redis/RedisCache.ByteCodec.cs @@ -23,8 +23,14 @@ public byte[] Encode(T value, CachePolicy? policy) NotCacheableException.ThrowIfNotCacheable(); var format = FormatFor(policy, forWrite: false); return format.Sniff - ? InterpretStored(default, stored, format, offerRewrite: false, quiet) - : InterpretStored(default, stored, default, offerRewrite: false, quiet); + ? InterpretStored(default, stored, KeyLife.Unknown, format, offerRewrite: false, out _, quiet) + : InterpretStored(default, stored, KeyLife.Unknown, default, offerRewrite: false, out _, quiet); + } + + public bool TryUnframe(byte[] stored, out FrameInfo info) + { + ArgumentNullException.ThrowIfNull(stored); + return EntryFrame.TryUnframe(stored, out info); } private byte[] Stored(T value, TFormat format) diff --git a/src/UiPath.Caching/Redis/RedisCache.Fill.cs b/src/UiPath.Caching/Redis/RedisCache.Fill.cs index 139ed2f2..94536bde 100644 --- a/src/UiPath.Caching/Redis/RedisCache.Fill.cs +++ b/src/UiPath.Caching/Redis/RedisCache.Fill.cs @@ -282,7 +282,8 @@ private async ValueTask> TryFillInternalAsync(CacheKey } /// The fill when its plain NX lost, or when scripts are on and the script decides: the stored value is the answer. - private async ValueTask> FillAfterNxAsync(CacheKey cacheKey, RedisKey redisKey, RedisValue serialized, DateTimeOffset deadline, bool lost, TFormat format, FillFence fence, CancellationToken token) + /// False once a fresh frame was read again: a second one fails the fill. + private async ValueTask> FillAfterNxAsync(CacheKey cacheKey, RedisKey redisKey, RedisValue serialized, DateTimeOffset deadline, bool lost, TFormat format, FillFence fence, CancellationToken token, bool reread = true) where TFormat : struct, IValueFormat { var raw = await _write.ExecuteAsync(static (s, token) => FillAfterAsync(s.Self, s.Key, s.Serialized, s.Deadline, s.Lost, s.Fence, token), @@ -307,16 +308,58 @@ private async ValueTask> FillAfterNxAsync(CacheKey cac return default; } - return stored.Added ? new(FillOutcome.Added, default, deadline) : ExistingEntry(redisKey, stored, format); + if (stored.Added) + { + return new(FillOutcome.Added, default, deadline); + } + + var existing = ExistingEntry(redisKey, stored, format, out var frame); + if (!frame.ReadAgain) + { + return existing; + } + + return reread ? await ExistingAgainAsync(cacheKey, redisKey, serialized, deadline, format, fence, token).ConfigureAwait(false) : default; } - /// A stored value as a read sees it; one its serializer throws on is logged and unreadable. - private (bool Found, T? Value) ReadStored(RedisKey redisKey, RedisValue stored, TFormat format) + /// A fill that met a fresh frame with a window on a late read: the winner again through the anchored read, whose answer alone is the fill's. A key gone by then is a lost race, and the fill tries once more. + private async ValueTask> ExistingAgainAsync(CacheKey cacheKey, RedisKey redisKey, RedisValue serialized, DateTimeOffset deadline, TFormat format, FillFence fence, CancellationToken token) where TFormat : struct, IValueFormat { + var (value, life) = await ReadAtomicAsync(redisKey, token, onMaster: true).ConfigureAwait(false); + if (!life.IsAnchored) + { + return default; + } + + var (found, deserialized) = ReadStored(redisKey, value, life, format, out var frame); + if (found) + { + return new(FillOutcome.Existed, deserialized, frame.LogicalExpiration ?? DateTimeOffset.MaxValue); + } + + if (frame.Expired) + { + // Nothing is stored and nothing is repaired over an expired frame. + return default; + } + + if (IsAlive(value, life) && !TombstoneValue.Is(value)) + { + return new(FillOutcome.Unreadable, default); + } + + return await FillAfterNxAsync(cacheKey, redisKey, serialized, deadline, lost: false, format, fence, token, reread: false).ConfigureAwait(false); + } + + /// A stored value as a read sees it, judged by ; one its serializer throws on is logged and unreadable. + private (bool Found, T? Value) ReadStored(RedisKey redisKey, RedisValue stored, KeyLife life, TFormat format, out FrameRead frame) + where TFormat : struct, IValueFormat + { + frame = default; try { - var (found, deserialized, _) = InterpretReadResult(redisKey, stored, format); + var (found, deserialized, _) = InterpretReadResult(redisKey, stored, life, format, out _, out frame); return (found, deserialized); } catch (Exception ex) when (ex is not (OperationCanceledException or OutOfMemoryException)) @@ -326,11 +369,17 @@ private async ValueTask> FillAfterNxAsync(CacheKey cac } } - private FillResult ExistingEntry(RedisKey redisKey, FillRaw stored, TFormat format) + /// The fill's answer from a winner that a late read found. A frame with a window it met is read again (), or is expired, which stores nothing. + private FillResult ExistingEntry(RedisKey redisKey, FillRaw stored, TFormat format, out FrameRead frame) where TFormat : struct, IValueFormat { - var (found, deserialized) = ReadStored(redisKey, stored.Value, format); - return found ? new(FillOutcome.Existed, deserialized, stored.Expiration) : new(FillOutcome.Unreadable, default); + var (found, deserialized) = ReadStored(redisKey, stored.Value, KeyLife.Late(stored.Expiration), format, out frame); + if (found) + { + return new(FillOutcome.Existed, deserialized, frame.LogicalExpiration ?? stored.Expiration); + } + + return frame.ReadAgain || frame.Expired ? default : new(FillOutcome.Unreadable, default); } private async ValueTask> SetIfChangedInternalAsync(CacheKey cacheKey, RedisKey redisKey, T? value, IEqualityComparer comparer, DateTimeOffset deadline, TFormat format, CancellationToken token) @@ -431,9 +480,23 @@ private async ValueTask> ChangeWithRetriesAsync(Cach return (ChangeStep.Stopped, default); } - if (UnchangedAgainst(redisKey, snapshot, value, comparer, format, run) is { } unchanged) + var unchanged = UnchangedAgainst(redisKey, snapshot, KeyLife.Late(snapshot.Expiration), value, comparer, format, run, out var frame); + if (frame.ReadAgain) + { + // A late read never accepts a frame with a window: the attempt goes on with the anchored read alone, its value, its bytes and its deadline. + var (again, life) = await ReadAtomicAsync(redisKey, token, onMaster: true).ConfigureAwait(false); + if (!life.IsAnchored) + { + return (ChangeStep.Stopped, default); + } + + snapshot = (again, DateTimeOffset.MaxValue); + unchanged = UnchangedAgainst(redisKey, snapshot, life, value, comparer, format, run, out _); + } + + if (unchanged is { } same) { - return (ChangeStep.Settled, unchanged); + return (ChangeStep.Settled, same); } // An unreadable stored value is replaced like a different one, which is the only way it ever heals. @@ -467,15 +530,17 @@ private async ValueTask> ChangeWithRetriesAsync(Cach return (ChangeStep.Settled, new ChangeResult(snapshot.Value.IsNull || (_tombstoneGrace is not null && TombstoneValue.Is(snapshot.Value)) ? ChangeOutcome.Filled : ChangeOutcome.Replaced, value, deadline)); } - private ChangeResult? UnchangedAgainst(RedisKey redisKey, (RedisValue Value, DateTimeOffset Expiration) snapshot, T? value, IEqualityComparer comparer, TFormat format, ChangeRun run) + /// The unchanged answer, or null for a write. An expired frame counts as absent and the comparer is not called; a frame the read cannot judge answers nothing yet (). + private ChangeResult? UnchangedAgainst(RedisKey redisKey, (RedisValue Value, DateTimeOffset Expiration) snapshot, KeyLife life, T? value, IEqualityComparer comparer, TFormat format, ChangeRun run, out FrameRead frame) where TFormat : struct, IValueFormat { + frame = default; if (snapshot.Value.IsNull) { return null; } - var (found, deserialized) = ReadStored(redisKey, snapshot.Value, format); + var (found, deserialized) = ReadStored(redisKey, snapshot.Value, life, format, out frame); if (!found) { return null; @@ -484,7 +549,7 @@ private async ValueTask> ChangeWithRetriesAsync(Cach run.Comparing = true; var equal = ChangeComparison.AreEqual(comparer, deserialized, value); run.Comparing = false; - return equal ? new ChangeResult(ChangeOutcome.Unchanged, deserialized, snapshot.Expiration) : null; + return equal ? new ChangeResult(ChangeOutcome.Unchanged, deserialized, frame.LogicalExpiration ?? snapshot.Expiration) : null; } private async ValueTask StoreIfAbsentAsync(RedisKey key, RedisValue serialized, TimeSpan remaining) => diff --git a/src/UiPath.Caching/Redis/RedisCache.FillMany.cs b/src/UiPath.Caching/Redis/RedisCache.FillMany.cs index 5cbc8006..2ce0877b 100644 --- a/src/UiPath.Caching/Redis/RedisCache.FillMany.cs +++ b/src/UiPath.Caching/Redis/RedisCache.FillMany.cs @@ -155,7 +155,11 @@ private async ValueTask[]> TryFillManyInternalAsync(Ke null, LogRedisCacheException).ConfigureAwait(false); - ReadFillSlotResults(entries, redisKeys, storable, groups, slots, deadline, format, results, ref ok); + var again = ReadFillSlotResults(entries, redisKeys, storable, groups, slots, deadline, format, results, ref ok); + if (again is not null) + { + ok &= await ExistingManyAgainAsync(redisKeys, again, format, results, token).ConfigureAwait(false); + } operation.Stop(); } @@ -185,7 +189,26 @@ private async ValueTask[]> TryFillManyInternalAsync(Ke return results; } - private void ReadFillSlotResults( + /// The winners a late read found as fresh frames with a window, read again through the anchored read, whose answers alone are the fills'. An expired frame or a key gone by then fails its fill. + private async ValueTask ExistingManyAgainAsync(RedisKey[] redisKeys, List again, TFormat format, FillResult[] results, CancellationToken token) + where TFormat : struct, IValueFormat + { + var positions = again.ToArray(); + var (values, lives) = await ReadManyAtomicAsync(Pick(redisKeys, positions), token).ConfigureAwait(false); + var ok = true; + for (var k = 0; k < positions.Length; k++) + { + FrameRead frame = default; + var (found, deserialized) = lives[k].IsAnchored ? ReadStored(redisKeys[positions[k]], values[k], lives[k], format, out frame) : default; + results[positions[k]] = found ? new FillResult(FillOutcome.Existed, deserialized, frame.LogicalExpiration ?? DateTimeOffset.MaxValue) : default; + ok &= found; + } + + return ok; + } + + /// The positions whose winner is a frame with a window that the late read could not judge; null when there are none. + private List? ReadFillSlotResults( KeyValuePair[] entries, RedisKey[] redisKeys, bool[] storable, @@ -198,6 +221,7 @@ private void ReadFillSlotResults( where TFormat : struct, IValueFormat { ok = true; + List? again = null; for (var g = 0; g < groups.Length; g++) { for (var j = 0; j < groups[g].Length; j++) @@ -208,17 +232,26 @@ private void ReadFillSlotResults( continue; } + FrameRead frame = default; results[i] = slots[g]?[j] switch { { IsLapsed: true } => LapsedFill(entries[i].Key, redisKeys[i]), { IsRemoved: true } => RemovedFill(entries[i].Key, redisKeys[i]), { Added: true } => new FillResult(FillOutcome.Added, default, deadline), - { } stored => ExistingEntry(redisKeys[i], stored, format), + { } stored => ExistingEntry(redisKeys[i], stored, format, out frame), _ => default, }; + if (frame.ReadAgain) + { + (again ??= []).Add(i); + continue; + } + ok &= results[i].Outcome is not (FillOutcome.Failed or FillOutcome.Unreadable); } } + + return again; } private FillResult RemovedFill(CacheKey cacheKey, RedisKey redisKey) diff --git a/src/UiPath.Caching/Redis/RedisCache.Frame.cs b/src/UiPath.Caching/Redis/RedisCache.Frame.cs new file mode 100644 index 00000000..da4f36cb --- /dev/null +++ b/src/UiPath.Caching/Redis/RedisCache.Frame.cs @@ -0,0 +1,343 @@ +using UiPath.Caching.Serialization; + +namespace UiPath.Caching.Redis; + +internal sealed partial class RedisCache +{ + private static readonly RedisValue[] AnchoredScriptArgs = [1]; + + private volatile bool _metWindowedFrame; + + /// Set the first time the tier interprets a frame with a window, and never cleared. + public bool MetWindowedFrame => _metWindowedFrame; + + /// Every entry the tier builds from a frame with a window is the observed one. + public bool KeepsBounds => true; + + /// Runs before an anchored read is sent; tests write the key there. + internal Func? BeforeAnchoredRead { get; set; } + + /// Runs when an anchored read's reply has arrived and before it is judged; tests move a clock or write the key there. + internal Func? AfterAnchoredRead { get; set; } + + /// Runs before a fill reads again the unreadable bytes it is about to replace; tests write the key there. + internal Func? BeforeUnreadableReread { get; set; } + + private static bool TryReadFrame(in RedisValue value, out EntryFrame frame) + { + frame = default; + if (value.IsNull || value.Length() < EntryFrame.ExpirationOffset) + { + return false; + } + + ReadOnlyMemory bytes = value; + return bytes.Span[0] == EntryFrame.Header && EntryFrame.TryRead(bytes, out frame); + } + + private static (RedisValue Value, TimeSpan? TimeToLive) AnchoredReply(RedisResult reply) + { + if (reply.IsNull) + { + return (RedisValue.Null, null); + } + + var parts = ((RedisResult[]?)reply)!; + var timeToLive = (long)parts[2]; + return ((RedisValue)parts[0], timeToLive < 0 ? null : TimeSpan.FromMilliseconds(timeToLive)); + } + + /// One attempt at the anchored read: the read script, or its own transaction on the master. + private static async ValueTask<(RedisValue Value, KeyLife Life)> ReadAtomicOnceAsync(RedisCache self, RedisKey key, bool onMaster, CancellationToken token) + { + token.ThrowIfCancellationRequested(); + if (self.BeforeAnchoredRead is { } before) + { + await before().ConfigureAwait(false); + } + + var sentAt = self.Clock.GetTimestamp(); + RedisValue value; + TimeSpan? timeToLive; + if (!onMaster && await self.TryReadScriptAsync(ReadWithExpirationScript, [key], self._logReadScriptUnavailable, AnchoredScriptArgs).ConfigureAwait(false) is { } reply) + { + (value, timeToLive) = AnchoredReply(reply); + } + else + { + sentAt = self.Clock.GetTimestamp(); + var transaction = self.Database.CreateTransaction(); + var get = transaction.StringGetAsync(key, CommandFlags.DemandMaster); + var ttl = transaction.KeyTimeToLiveAsync(key, CommandFlags.DemandMaster); + try + { + if (!await transaction.ExecuteAsync(CommandFlags.DemandMaster).ConfigureAwait(false)) + { + throw new InvalidOperationException("The read transaction was not committed"); + } + + value = await get.ConfigureAwait(false); + timeToLive = await ttl.ConfigureAwait(false); + } + catch + { + get.Observe(); + ttl.Observe(); + throw; + } + } + + if (self.AfterAnchoredRead is { } after) + { + await after().ConfigureAwait(false); + } + + return (value, KeyLife.Of(timeToLive, sentAt)); + } + + /// One attempt at the batch anchored read: one read script or one transaction per slot group, all in one round trip, with one timestamp. + private static async ValueTask<(RedisValue[] Values, KeyLife[] Lives)> ReadManyAtomicOnceAsync(RedisCache self, RedisKey[] keys, CancellationToken token) + { + token.ThrowIfCancellationRequested(); + var groups = self.SlotGroups(keys, self._logger); + if (self.BeforeAnchoredRead is { } before) + { + await before().ConfigureAwait(false); + } + + var values = new RedisValue[keys.Length]; + var timesToLive = new TimeSpan?[keys.Length]; + var sentAt = self.Clock.GetTimestamp(); + if (!await TryReadManyByScriptAsync(self, keys, groups, values, timesToLive).ConfigureAwait(false)) + { + sentAt = self.Clock.GetTimestamp(); + await ReadManyByTransactionAsync(self, keys, groups, values, timesToLive).ConfigureAwait(false); + } + + if (self.AfterAnchoredRead is { } after) + { + await after().ConfigureAwait(false); + } + + var lives = new KeyLife[keys.Length]; + for (var i = 0; i < lives.Length; i++) + { + lives[i] = KeyLife.Of(timesToLive[i], sentAt); + } + + return (values, lives); + } + + private static async ValueTask TryReadManyByScriptAsync(RedisCache self, RedisKey[] keys, int[][] groups, RedisValue[] values, TimeSpan?[] timesToLive) + { + var replies = new Task[groups.Length]; + for (var g = 0; g < groups.Length; g++) + { + replies[g] = self.TryReadScriptAsync(ReadManyWithExpirationScript, Pick(keys, groups[g]), self._logReadScriptUnavailable, AnchoredScriptArgs).AsTask(); + } + + var answers = await Task.WhenAll(replies).ConfigureAwait(false); + if (Array.Exists(answers, answer => answer is null)) + { + return false; + } + + for (var g = 0; g < groups.Length; g++) + { + var group = groups[g]; + var parts = ((RedisResult[]?)answers[g])!; + for (var j = 0; j < group.Length; j++) + { + values[group[j]] = (RedisValue)parts[2 * j]; + var timeToLive = (long)parts[(2 * group.Length) + j]; + timesToLive[group[j]] = timeToLive < 0 ? null : TimeSpan.FromMilliseconds(timeToLive); + } + } + + return true; + } + + private static async ValueTask ReadManyByTransactionAsync(RedisCache self, RedisKey[] keys, int[][] groups, RedisValue[] values, TimeSpan?[] timesToLive) + { + var commits = new Task[groups.Length]; + var gets = new Task[groups.Length]; + var ttls = new Task[keys.Length]; + for (var g = 0; g < groups.Length; g++) + { + var group = groups[g]; + var transaction = self.Database.CreateTransaction(); + gets[g] = transaction.StringGetAsync(Pick(keys, group), CommandFlags.DemandMaster); + foreach (var i in group) + { + ttls[i] = transaction.KeyTimeToLiveAsync(keys[i], CommandFlags.DemandMaster); + } + + commits[g] = transaction.ExecuteAsync(CommandFlags.DemandMaster); + } + + bool[] committed; + try + { + committed = await Task.WhenAll(commits).ConfigureAwait(false); + } + catch + { + Array.ForEach(gets, TaskObservation.Observe); + Array.ForEach(ttls, TaskObservation.Observe); + throw; + } + + if (Array.IndexOf(committed, false) >= 0) + { + Array.ForEach(gets, TaskObservation.Observe); + Array.ForEach(ttls, TaskObservation.Observe); + throw new InvalidOperationException("The read transaction was not committed"); + } + + for (var g = 0; g < groups.Length; g++) + { + var group = groups[g]; + var read = await gets[g].ConfigureAwait(false); + for (var j = 0; j < group.Length; j++) + { + values[group[j]] = read[j]; + timesToLive[group[j]] = await ttls[group[j]].ConfigureAwait(false); + } + } + } + + /// The anchored atomic read: the read script when it runs, else its own transaction on the master; always takes the transaction. A read the pipeline gave up on answers no value and a life that is not anchored. + private ValueTask<(RedisValue Value, KeyLife Life)> ReadAtomicAsync(RedisKey redisKey, CancellationToken token, bool onMaster = false) => + _read.ExecuteAsync( + static (s, token) => ReadAtomicOnceAsync(s.Self, s.Key, s.OnMaster, token), + (Self: this, Key: redisKey, OnMaster: onMaster), + (RedisValue.Null, KeyLife.Unknown), + token); + + /// The batch form of , one timestamp for its round trip. + private ValueTask<(RedisValue[] Values, KeyLife[] Lives)> ReadManyAtomicAsync(RedisKey[] redisKeys, CancellationToken token) => + _read.ExecuteAsync( + static (s, token) => ReadManyAtomicOnceAsync(s.Self, s.Keys, token), + (Self: this, Keys: redisKeys), + (new RedisValue[redisKeys.Length], new KeyLife[redisKeys.Length]), + token); + + /// The anchored read that keeps the verdict alone: null for an absent key, for a frame with a window that is not fresh and for any other value whose key ended before the judgment. + private async ValueTask ReadJudgedAsync(RedisKey redisKey, CancellationToken token) + { + var (value, life) = await ReadAtomicAsync(redisKey, token).ConfigureAwait(false); + return IsAlive(value, life) ? value : RedisValue.Null; + } + + /// The batch form of . + private async ValueTask ReadManyJudgedAsync(RedisKey[] redisKeys, CancellationToken token) + { + var (values, lives) = await ReadManyAtomicAsync(redisKeys, token).ConfigureAwait(false); + for (var i = 0; i < values.Length; i++) + { + if (!IsAlive(values[i], lives[i])) + { + values[i] = RedisValue.Null; + } + } + + return values; + } + + /// Whether an anchored answer is alive at its judgment: a frame with a window while it is fresh, any other value while its key has life left. + private bool IsAlive(in RedisValue value, KeyLife life) + { + if (value.IsNull || !life.IsAnchored) + { + return false; + } + + var deadline = AnchoredDeadline(life, out var now); + if (TryReadFrame(value, out var frame) && frame.HasWindow) + { + return frame.LogicalExpiration(deadline) > now; + } + + return deadline is not { } end || end > now; + } + + /// The key's deadline at the judgment: the UTC clock now plus the life left, with one reading of each clock; null for a key without a TTL. + private DateTimeOffset? AnchoredDeadline(KeyLife life, out DateTimeOffset now) => AnchoredDeadline(life, out now, out _); + + /// The timestamp of the judgment: the life left was measured to it. + private DateTimeOffset? AnchoredDeadline(KeyLife life, out DateTimeOffset now, out long judgedAt) + { + var remaining = life.Remaining(Clock, out judgedAt); + now = Clock.GetUtcNow(); + return remaining is { } left ? now + left : null; + } + + /// Judges a frame by what the caller knows of the key's life; false when the read stops here, true when it goes on with the inner value. + private bool JudgeFrame(in EntryFrame entry, KeyLife life, out FrameRead frame) + { + var validators = EntryValidators.From(entry.ETag, entry.LastModified); + if (!entry.HasWindow) + { + DateTimeOffset? expiration = null; + if (life.IsAnchored && AnchoredDeadline(life, out var at) is { } end) + { + if (end <= at) + { + frame = new FrameRead(true, false, false, false, null, validators); + return false; + } + + expiration = end; + } + + frame = new FrameRead(true, false, false, false, expiration, validators); + return true; + } + + // Before any answer that came out of the frame leaves the tier. + if (!_metWindowedFrame) + { + _metWindowedFrame = true; + } + + if (life.IsJudged) + { + frame = new FrameRead(true, true, false, false, null, validators); + return true; + } + + if (life.IsAnchored) + { + var deadline = AnchoredDeadline(life, out var now, out var judgedAt); + var logical = entry.LogicalExpiration(deadline); + var fresh = logical > now; + // The bounds count from the judgment on the monotonic clock, so no later reading of the UTC clock moves them. + var observed = fresh || now < entry.StaleUntil(deadline) ? ObservedLife.From(Clock, judgedAt, logical - now, entry.Window) : default; + frame = new FrameRead(true, true, false, !fresh, fresh ? logical : null, validators, observed); + return fresh; + } + + // A late deadline is never too early, so it may end the frame; it never proves it fresh. Unknown proves nothing. + var expired = life.IsLate && entry.LogicalExpiration(life.Deadline) <= Clock.GetUtcNow(); + frame = new FrameRead(true, true, !expired, expired, null, validators); + return false; + } + + /// Judges a value that is no frame on an anchored read: a hit while its key has life left. False for a key that ended before the judgment. + private bool JudgePlain(KeyLife life, out FrameRead frame) + { + frame = default; + if (!life.IsAnchored || AnchoredDeadline(life, out var now) is not { } end) + { + return true; + } + + if (end <= now) + { + return false; + } + + frame = new FrameRead(false, false, false, false, end, null); + return true; + } +} diff --git a/src/UiPath.Caching/Redis/RedisCache.GetOrAdd.cs b/src/UiPath.Caching/Redis/RedisCache.GetOrAdd.cs index cef93a07..7be108e0 100644 --- a/src/UiPath.Caching/Redis/RedisCache.GetOrAdd.cs +++ b/src/UiPath.Caching/Redis/RedisCache.GetOrAdd.cs @@ -169,7 +169,15 @@ internal sealed partial class RedisCache try { var value = await ReadStringAsync(redisKey, token).ConfigureAwait(false); - (found, cached, var unreadable) = InterpretReadResult(redisKey, value, format); + (found, cached, var unreadable) = InterpretReadResult(redisKey, value, KeyLife.Unknown, format, out _, out var frame); + if (frame.ReadAgain) + { + value = await ReadJudgedAsync(redisKey, token).ConfigureAwait(false); + (found, cached, unreadable) = InterpretReadResult(redisKey, value, KeyLife.Judged, format, out _, out frame); + } + + // A value out of a frame with a window has no deadline a later read could prove, so a joined result call reads none. + run.ExpirationUnread = found && !frame.Windowed; if (unreadable != 0) { await RemoveUnreadableAsync(redisKey, value, unreadable, token).ConfigureAwait(false); @@ -195,8 +203,7 @@ internal sealed partial class RedisCache if (found) { - // The probe reads no TTL; a result call that joined this run reads it itself. - run.ExpirationUnread = true; + // The probe reads no TTL; a result call that joined this run reads it itself, unless the value came out of a frame with a window. ret = cached; } else @@ -253,11 +260,11 @@ internal sealed partial class RedisCache try { var token = run.Token; - var (found, cached) = await ReadGetOrAddProbeAsync(redisKey, format, token).ConfigureAwait(false); + var (found, cached, windowed) = await ReadGetOrAddProbeAsync(redisKey, format, token).ConfigureAwait(false); if (found) { - // The probe reads no TTL; a result call that joined this run reads it itself. - run.ExpirationUnread = true; + // The probe reads no TTL; a result call that joined this run reads it itself, unless the value came out of a frame with a window. + run.ExpirationUnread = !windowed; ret = cached; } else diff --git a/src/UiPath.Caching/Redis/RedisCache.Read.cs b/src/UiPath.Caching/Redis/RedisCache.Read.cs index 054a3da3..29b29079 100644 --- a/src/UiPath.Caching/Redis/RedisCache.Read.cs +++ b/src/UiPath.Caching/Redis/RedisCache.Read.cs @@ -72,7 +72,8 @@ private static (RedisKey Key, bool Hit)[] InitReads(RedisKey[] redisKeys) return reads; } - private static (RedisValue Value, DateTimeOffset? Expiration) ReadReply(RedisResult reply) + /// The script's answer as today's read takes it; a value that starts with the frame header carries its PTTL, which is added to this node's now on receipt, so its deadline is late. + private static (RedisValue Value, DateTimeOffset? Expiration) ReadReply(RedisResult reply, TimeProvider clock) { if (reply.IsNull) { @@ -80,19 +81,33 @@ private static (RedisValue Value, DateTimeOffset? Expiration) ReadReply(RedisRes } var parts = ((RedisResult[]?)reply)!; + var value = (RedisValue)parts[0]; + if (parts.Length > 2) + { + return (value, LateDeadline((long)parts[2], clock)); + } + var expireAt = (long)parts[1]; // PEXPIRETIME answers -1 for a key without a TTL, as EXPIRETIME does for KeyExpireTimeAsync. - return ((RedisValue)parts[0], expireAt < 0 ? null : DateTimeOffset.FromUnixTimeMilliseconds(expireAt)); + return (value, expireAt < 0 ? null : DateTimeOffset.FromUnixTimeMilliseconds(expireAt)); } - private static (RedisValue[] Values, DateTimeOffset?[] Expirations) ReadManyReply(RedisResult reply, int count) + /// As , for the batch script: the pairs, then one PTTL per key when any value starts with the frame header. + private static (RedisValue[] Values, DateTimeOffset?[] Expirations) ReadManyReply(RedisResult reply, int count, TimeProvider clock) { var parts = ((RedisResult[]?)reply)!; + var withTimesToLive = parts.Length >= 3 * count; var values = new RedisValue[count]; var expirations = new DateTimeOffset?[count]; for (var i = 0; i < count; i++) { values[i] = (RedisValue)parts[2 * i]; + if (withTimesToLive && StartsLikeFrame(values[i])) + { + expirations[i] = LateDeadline((long)parts[(2 * count) + i], clock); + continue; + } + var expireAt = (long)parts[(2 * i) + 1]; expirations[i] = expireAt < 0 ? null : DateTimeOffset.FromUnixTimeMilliseconds(expireAt); } @@ -100,6 +115,12 @@ private static (RedisValue[] Values, DateTimeOffset?[] Expirations) ReadManyRepl return (values, expirations); } + private static DateTimeOffset? LateDeadline(long timeToLive, TimeProvider clock) => + timeToLive < 0 ? null : clock.ToDateTimeOffset(TimeSpan.FromMilliseconds(timeToLive)); + + private static bool StartsLikeFrame(in RedisValue value) => + !value.IsNull && value.Length() > 0 && ((ReadOnlyMemory)value).Span[0] == EntryFrame.Header; + /// One attempt at the read: the snapshot transaction, the script, or a GET with a PTTL. private static async Task ReadOnceAsync(RedisCache self, RedisKey key, StrongBox?> read, bool atomic) { @@ -119,7 +140,7 @@ private static async Task ReadOnceAsync(RedisCache self, RedisKey key, StrongBox if (await self.TryReadScriptAsync(ReadWithExpirationScript, [key], self._logReadScriptUnavailable).ConfigureAwait(false) is { } reply) { - Interlocked.CompareExchange(ref read.Value, new(ReadReply(reply)), null); + Interlocked.CompareExchange(ref read.Value, new(ReadReply(reply, self.Clock)), null); return; } @@ -147,7 +168,7 @@ private static async ValueTask ReadManyAsync((RedisCache Self, RedisKey[] token.ThrowIfCancellationRequested(); if (await s.Self.TryReadScriptAsync(ReadManyWithExpirationScript, s.Keys, s.Self._logReadScriptUnavailable).ConfigureAwait(false) is { } reply) { - Interlocked.CompareExchange(ref s.Read.Value, new(ReadManyReply(reply, s.Keys.Length)), null); + Interlocked.CompareExchange(ref s.Read.Value, new(ReadManyReply(reply, s.Keys.Length, s.Self.Clock)), null); return true; } @@ -187,20 +208,48 @@ private static async ValueTask ReadManyAsync((RedisCache Self, RedisKey[] /// private (bool Found, T? Value, int Unreadable) InterpretReadResult(RedisKey key, RedisValue value, TFormat format) where TFormat : struct, IValueFormat => - InterpretReadResult(key, value, format, out _); + InterpretReadResult(key, value, KeyLife.Unknown, format, out _, out _); /// Stored bytes were present but gave no value. /// False for bytes that were never read from , which no rewrite may be queued for. /// True for a decode that is not a read: a miss is not logged or counted, and no serializer read is counted. private (bool Found, T? Value, int Unreadable) InterpretReadResult(RedisKey key, RedisValue value, TFormat format, out bool undecoded, bool offerRewrite = true, bool quiet = false) + where TFormat : struct, IValueFormat => + InterpretReadResult(key, value, KeyLife.Unknown, format, out undecoded, out _, offerRewrite, quiet); + + /// As the overloads above, judging a frame by : null, then a tombstone, then the frame, then the inner value. + /// What the read learned from a frame; see . + private (bool Found, T? Value, int Unreadable) InterpretReadResult(RedisKey key, RedisValue value, KeyLife life, TFormat format, out bool undecoded, out FrameRead frame, bool offerRewrite = true, bool quiet = false) where TFormat : struct, IValueFormat { undecoded = false; + frame = default; if (value.IsNull || (_tombstoneGrace is not null && TombstoneValue.Is(value))) { return (false, default, 0); } + if (TryReadFrame(value, out var entry)) + { + // A frame is never offered for a rewrite; an expired one, or one that cannot be judged here, is no unreadable value. + return JudgeFrame(entry, life, out frame) + ? DecodeStored(key, entry.Inner, format, out undecoded, offerRewrite: false, quiet) + : (false, default, 0); + } + + if (life.IsAnchored && !JudgePlain(life, out frame)) + { + return (false, default, 0); + } + + return DecodeStored(key, value, format, out undecoded, offerRewrite, quiet); + } + + /// The bytes of a value as today's read decodes them. + private (bool Found, T? Value, int Unreadable) DecodeStored(RedisKey key, RedisValue value, TFormat format, out bool undecoded, bool offerRewrite, bool quiet) + where TFormat : struct, IValueFormat + { + undecoded = false; T? deserialized; byte[]? stored = null; if (value.Length() == 0) @@ -292,10 +341,10 @@ private void ReportReadMiss(ReadOutcome outcome) } /// As , for one value of a batch: a format no serializer owns joins , which the batch drops after it has reported. - private (bool Found, T? Value) InterpretBatchRead(RedisKey redisKey, RedisValue value, TFormat format, ref List<(RedisKey Key, RedisValue Read, int FormatId)>? unreadableKeys) + private (bool Found, T? Value) InterpretBatchRead(RedisKey redisKey, RedisValue value, KeyLife life, TFormat format, ref List<(RedisKey Key, RedisValue Read, int FormatId)>? unreadableKeys, out FrameRead frame) where TFormat : struct, IValueFormat { - var (found, deserialized, unreadable) = InterpretReadResult(redisKey, value, format); + var (found, deserialized, unreadable) = InterpretReadResult(redisKey, value, life, format, out _, out frame); if (unreadable != 0) { (unreadableKeys ??= []).Add((redisKey, value, unreadable)); @@ -315,23 +364,32 @@ private ValueTask ReadStringAsync(RedisKey redisKey, CancellationTok token); // GenerateAndStoreAsync carries an inlined copy of this read; a change to one goes in both. - private async ValueTask<(bool Found, T? Value)> ReadGetOrAddProbeAsync(RedisKey redisKey, TFormat format, CancellationToken token) + /// Windowed: the value came out of a frame with a window, which a run reports with no deadline. + private async ValueTask<(bool Found, T? Value, bool Windowed)> ReadGetOrAddProbeAsync(RedisKey redisKey, TFormat format, CancellationToken token) where TFormat : struct, IValueFormat { token.ThrowIfCancellationRequested(); if (!IsConnected) { - return (false, default); + return (false, default, false); } var operation = StartOperation(nameof(GetOrAddAsync)); bool found = false; T? deserialized = default; + var windowed = false; try { var value = await ReadStringAsync(redisKey, token).ConfigureAwait(false); - (found, deserialized, var unreadable) = InterpretReadResult(redisKey, value, format); + (found, deserialized, var unreadable) = InterpretReadResult(redisKey, value, KeyLife.Unknown, format, out _, out var frame); + if (frame.ReadAgain) + { + value = await ReadJudgedAsync(redisKey, token).ConfigureAwait(false); + (found, deserialized, unreadable) = InterpretReadResult(redisKey, value, KeyLife.Judged, format, out _, out frame); + } + + windowed = frame.Windowed; if (unreadable != 0) { await RemoveUnreadableAsync(redisKey, value, unreadable, token).ConfigureAwait(false); @@ -354,7 +412,7 @@ private ValueTask ReadStringAsync(RedisKey redisKey, CancellationTok TrackRead(operation, found, redisKey); } - return (found, deserialized); + return (found, deserialized, windowed); } private async ValueTask GetAsync(RedisKey redisKey, TFormat format, CancellationToken token) @@ -374,7 +432,13 @@ private ValueTask ReadStringAsync(RedisKey redisKey, CancellationTok try { var value = await ReadStringAsync(redisKey, token).ConfigureAwait(false); - (found, ret, var unreadable) = InterpretReadResult(redisKey, value, format); + (found, ret, var unreadable) = InterpretReadResult(redisKey, value, KeyLife.Unknown, format, out _, out var frame); + if (frame.ReadAgain) + { + value = await ReadJudgedAsync(redisKey, token).ConfigureAwait(false); + (found, ret, unreadable) = InterpretReadResult(redisKey, value, KeyLife.Judged, format, out _, out _); + } + if (unreadable != 0) { await RemoveUnreadableAsync(redisKey, value, unreadable, token).ConfigureAwait(false); @@ -435,6 +499,7 @@ private ValueTask ReadStringAsync(RedisKey redisKey, CancellationTok [], LogRedisCacheException).ConfigureAwait(false); retValues = GetDefaultValues(keys); + List? again = null; for (var g = 0; g < groups.Length; g++) { var (group, values) = (groups[g], groupValues[g]); @@ -447,11 +512,30 @@ private ValueTask ReadStringAsync(RedisKey redisKey, CancellationTok for (var j = 0; j < group.Length; j++) { var i = group[j]; - var (found, obj) = InterpretBatchRead(redisKeys[i], values[j], format, ref unreadableKeys); + var (found, obj) = InterpretBatchRead(redisKeys[i], values[j], KeyLife.Unknown, format, ref unreadableKeys, out var frame); + reads[i].Hit = found; + retValues[i] = new KeyValuePair(keys[i], obj); + if (frame.ReadAgain) + { + (again ??= []).Add(i); + } + } + } + + if (again is not null) + { + // A frame with a window that MGET cannot judge: those keys again, through the judged read. + var positions = again.ToArray(); + var judged = await ReadManyJudgedAsync(Pick(redisKeys, positions), token).ConfigureAwait(false); + for (var k = 0; k < positions.Length; k++) + { + var i = positions[k]; + var (found, obj) = InterpretBatchRead(redisKeys[i], judged[k], KeyLife.Judged, format, ref unreadableKeys, out _); reads[i].Hit = found; retValues[i] = new KeyValuePair(keys[i], obj); } } + operation.Stop(); } catch (OperationCanceledException) when (token.IsCancellationRequested) @@ -512,10 +596,18 @@ private ValueTask ReadStringAsync(RedisKey redisKey, CancellationTok } var (value, expiration) = result.Value; - var (found, deserialized, unreadable) = InterpretReadResult(redisKey, value, format); + var (found, deserialized, unreadable) = InterpretReadResult(redisKey, value, KeyLife.Late(expiration), format, out _, out var frame); + if (frame.ReadAgain) + { + // A late read never accepts a frame with a window: the key again, through the anchored read, whose answer alone makes the entry. + (value, var life) = await ReadAtomicAsync(redisKey, token).ConfigureAwait(false); + expiration = null; + (found, deserialized, unreadable) = InterpretReadResult(redisKey, value, life, format, out _, out frame); + } + if (found) { - ret = _cacheEntryFactory.Create(deserialized, Clock.ToDateTimeOffset(expiration)); + ret = EntryOf(deserialized, frame.LogicalExpiration ?? Clock.ToDateTimeOffset(expiration), frame); } if (unreadable != 0) @@ -585,12 +677,25 @@ private async ValueTask> ReadSnapshotInternalAsync(C } var (value, expiration) = result.Value; + var snapshot = InterpretSnapshot(redisKey, value, KeyLife.Late(expiration), Clock.ToDateTimeOffset(expiration), format, out var frame); + if (frame.ReadAgain) + { + // The answer comes from the anchored read alone: its value, its bytes and its deadline. + (value, var life) = await ReadAtomicAsync(redisKey, token, onMaster: true).ConfigureAwait(false); + if (!life.IsAnchored) + { + operation.Stop(); + return default; + } + + snapshot = InterpretSnapshot(redisKey, value, life, DateTimeOffset.MaxValue, format, out _); + } + if (raw is not null) { raw.Value = value; } - var snapshot = InterpretSnapshot(redisKey, value, Clock.ToDateTimeOffset(expiration), format); found = snapshot.Outcome == SnapshotOutcome.Found; operation.Stop(); return snapshot; @@ -612,25 +717,32 @@ private async ValueTask> ReadSnapshotInternalAsync(C } } - private SnapshotRead InterpretSnapshot(RedisKey key, RedisValue value, DateTimeOffset expiration, TFormat format) + /// The entry of a read: the library's observed entry when the frame handed on bounds, which no custom factory can hold, else the factory's. + private ICacheEntry EntryOf(T? value, DateTimeOffset expiration, in FrameRead frame) => + frame.Observed.IsSet + ? CacheEntryFactory.CreateObserved(value, expiration, frame.Observed, frame.Validators) + : _cacheEntryFactory.Create(value, expiration, frame.Validators); + + private SnapshotRead InterpretSnapshot(RedisKey key, RedisValue value, KeyLife life, DateTimeOffset expiration, TFormat format, out FrameRead frame) where TFormat : struct, IValueFormat { - var (outcome, deserialized) = InterpretStored(key, value, format, offerRewrite: true); + var (outcome, deserialized) = InterpretStored(key, value, life, format, offerRewrite: true, out frame); return outcome == SnapshotOutcome.Found - ? new SnapshotRead(SnapshotOutcome.Found, _cacheEntryFactory.Create(deserialized, expiration)) + ? new SnapshotRead(SnapshotOutcome.Found, EntryOf(deserialized, frame.LogicalExpiration ?? expiration, frame)) : new SnapshotRead(outcome, null); } - /// What a snapshot read makes of stored bytes; the codec seam reads through it too, so the two cannot differ. - private (SnapshotOutcome Outcome, T? Value) InterpretStored(RedisKey key, RedisValue value, TFormat format, bool offerRewrite, bool quiet = false) + /// What a snapshot read makes of stored bytes; the codec seam reads through it too, so the two cannot differ. A frame that is expired or cannot be judged is absent, not unreadable. + private (SnapshotOutcome Outcome, T? Value) InterpretStored(RedisKey key, RedisValue value, KeyLife life, TFormat format, bool offerRewrite, out FrameRead frame, bool quiet = false) where TFormat : struct, IValueFormat { bool found; T? deserialized; bool undecoded; + frame = default; try { - (found, deserialized, _) = InterpretReadResult(key, value, format, out undecoded, offerRewrite, quiet); + (found, deserialized, _) = InterpretReadResult(key, value, life, format, out undecoded, out frame, offerRewrite, quiet); } catch (Exception ex) when (ex is not OutOfMemoryException && ex is not OperationCanceledException) { @@ -672,6 +784,7 @@ private SnapshotRead InterpretSnapshot(RedisKey key, RedisValue v { await EnsureConnectedAsync(_read, token).ConfigureAwait(false); var groups = SlotGroups(redisKeys, _logger); + List? again = null; var groupReads = await PerSlotAsync( groups, (Self: this, Keys: redisKeys, Token: token), @@ -701,7 +814,12 @@ static async (s, group) => for (var j = 0; j < group.Length; j++) { var i = group[j]; - var (found, deserialized) = InterpretBatchRead(redisKeys[i], values[j], format, ref unreadableKeys); + var (found, deserialized) = InterpretBatchRead(redisKeys[i], values[j], KeyLife.Late(expirations[j]), format, ref unreadableKeys, out var frame); + if (frame.ReadAgain) + { + (again ??= []).Add(i); + } + if (!found) { continue; @@ -709,9 +827,27 @@ static async (s, group) => reads[i].Hit = true; retValues[i] = new KeyValuePair>( keys[i], - _cacheEntryFactory.Create(deserialized, Clock.ToDateTimeOffset(expirations[j]))); + EntryOf(deserialized, frame.LogicalExpiration ?? Clock.ToDateTimeOffset(expirations[j]), frame)); } } + + if (again is not null) + { + // A late read never accepts a frame with a window: those keys again, through the anchored read, whose answers alone make the entries. + var positions = again.ToArray(); + var (values, lives) = await ReadManyAtomicAsync(Pick(redisKeys, positions), token).ConfigureAwait(false); + for (var k = 0; k < positions.Length; k++) + { + var i = positions[k]; + var (found, deserialized) = InterpretBatchRead(redisKeys[i], values[k], lives[k], format, ref unreadableKeys, out var frame); + if (found) + { + reads[i].Hit = true; + retValues[i] = new KeyValuePair>(keys[i], EntryOf(deserialized, frame.LogicalExpiration ?? DateTimeOffset.MaxValue, frame)); + } + } + } + operation.Stop(); } catch (OperationCanceledException) when (token.IsCancellationRequested) diff --git a/src/UiPath.Caching/Redis/RedisCache.Stamped.cs b/src/UiPath.Caching/Redis/RedisCache.Stamped.cs index d8b748db..8d28b2b0 100644 --- a/src/UiPath.Caching/Redis/RedisCache.Stamped.cs +++ b/src/UiPath.Caching/Redis/RedisCache.Stamped.cs @@ -34,9 +34,11 @@ public bool Holds(object? stamp, T? value, CachePolicy? policy) try { + // A frame holds the value as its inner bytes. + ReadOnlyMemory held = TryReadFrame(expected, out var frame) ? frame.Inner : expected; if (IsDefault(value)) { - return expected == RedisValue.EmptyString; + return held.IsEmpty; } var format = FormatFor(policy, forWrite: true, alsoReads: true); @@ -45,7 +47,6 @@ public bool Holds(object? stamp, T? value, CachePolicy? policy) : SerializeValue(value, format); using (payload) { - ReadOnlyMemory held = expected; ReadOnlyMemory candidate = serialized; return held.Span.SequenceEqual(candidate.Span); } diff --git a/src/UiPath.Caching/Redis/RedisCache.Tombstone.cs b/src/UiPath.Caching/Redis/RedisCache.Tombstone.cs index b52d4939..f8321817 100644 --- a/src/UiPath.Caching/Redis/RedisCache.Tombstone.cs +++ b/src/UiPath.Caching/Redis/RedisCache.Tombstone.cs @@ -301,8 +301,22 @@ private async ValueTask ReplaceUnreadableAsync(Ca NoteWritten(redisKey); try { - var held = await Database.StringGetAsync(redisKey, CommandFlags.DemandMaster).ConfigureAwait(false); - if (held.IsNull || TombstoneValue.Is(held) || ReadStored(redisKey, held, format).Found) + if (BeforeUnreadableReread is { } reread) + { + await reread().ConfigureAwait(false); + } + + // Value and TTL in one transaction, so a frame with a window, expired or not, is told from unreadable bytes. + var read = new StrongBox?>(); + await ReadOnceAsync(this, redisKey, read, atomic: true).ConfigureAwait(false); + var (held, expiration) = read.Value!.Value; + if (held.IsNull || TombstoneValue.Is(held)) + { + return UnreadableReplace.Changed; + } + + var (found, _) = ReadStored(redisKey, held, KeyLife.Late(expiration), format, out var frame); + if (found || frame.ReadAgain || frame.Expired) { return UnreadableReplace.Changed; } diff --git a/src/UiPath.Caching/Redis/RedisCache.cs b/src/UiPath.Caching/Redis/RedisCache.cs index 8dfd1dcb..854d4714 100644 --- a/src/UiPath.Caching/Redis/RedisCache.cs +++ b/src/UiPath.Caching/Redis/RedisCache.cs @@ -6,13 +6,13 @@ namespace UiPath.Caching.Redis; -internal sealed partial class RedisCache : RedisCacheBase, ICache, ISharedTier, IMigrationCache +internal sealed partial class RedisCache : RedisCacheBase, ICache, ISharedTier, IMigrationCache, IFrameTier { - /// Value and absolute expiration in one atomic read-only call. - private const string ReadWithExpirationScript = "local v = redis.call('GET', KEYS[1]) if not v then return false end return {v, redis.call('PEXPIRETIME', KEYS[1])}"; + /// Value and absolute expiration in one atomic read-only call; also the PTTL for a value that starts with the frame header, or for every value when ARGV[1] is 1 (an anchored read). + private const string ReadWithExpirationScript = "local v = redis.call('GET', KEYS[1]) if not v then return false end if ARGV[1] == '1' or string.byte(v, 1) == 14 then return {v, redis.call('PEXPIRETIME', KEYS[1]), redis.call('PTTL', KEYS[1])} end return {v, redis.call('PEXPIRETIME', KEYS[1])}"; - /// Each key's value and absolute expiration, flat: a missing key answers a null value and -2. - private const string ReadManyWithExpirationScript = "local r = {} for i, k in ipairs(KEYS) do r[2 * i - 1] = redis.call('GET', k) r[2 * i] = redis.call('PEXPIRETIME', k) end return r"; + /// Each key's value and absolute expiration, flat: a missing key answers a null value and -2. Then one PTTL per key when any value starts with the frame header, or when ARGV[1] is 1. + private const string ReadManyWithExpirationScript = "local r = {} local n = #KEYS local t = ARGV[1] == '1' for i, k in ipairs(KEYS) do local v = redis.call('GET', k) r[2 * i - 1] = v r[2 * i] = redis.call('PEXPIRETIME', k) if v and string.byte(v, 1) == 14 then t = true end end if t then for i, k in ipairs(KEYS) do r[2 * n + i] = redis.call('PTTL', k) end end return r"; private readonly ISerializerProxy _serializer; diff --git a/src/UiPath.Caching/Redis/RedisCacheProvider.cs b/src/UiPath.Caching/Redis/RedisCacheProvider.cs index 7ee1cd56..b7547b62 100644 --- a/src/UiPath.Caching/Redis/RedisCacheProvider.cs +++ b/src/UiPath.Caching/Redis/RedisCacheProvider.cs @@ -109,7 +109,7 @@ public Task> CountFormatsByKeyAsync(CacheKey k /// /// As , with the reason each value is where it is as well as its format: see . - /// Each string costs a PTTL and a headerless one a STRLEN besides the two-byte read, so run it off the request path, as the sweep is. + /// Each string costs a PTTL and a headerless one a STRLEN besides the three-byte read, so run it off the request path, as the sweep is. /// public Task CountFormatsByReasonAsync(CacheKey keyPattern, CancellationToken token = default) => CountFormatsByReasonAsync(keyPattern, DefaultSweepGroup, token); diff --git a/src/UiPath.Caching/Redis/RedisHashCache.cs b/src/UiPath.Caching/Redis/RedisHashCache.cs index d39c274e..37c47040 100644 --- a/src/UiPath.Caching/Redis/RedisHashCache.cs +++ b/src/UiPath.Caching/Redis/RedisHashCache.cs @@ -6,7 +6,7 @@ namespace UiPath.Caching.Redis; -internal sealed partial class RedisHashCache : RedisCacheBase, IHashCache, ISpanKeyHashCache, ISharedHashTier +internal sealed partial class RedisHashCache : RedisCacheBase, IHashCache, ISpanKeyHashCache, ISharedHashTier, IFrameTier { /// All fields and the absolute expiration in one atomic read-only call. private const string ReadWithExpirationScript = "local n = redis.call('HLEN', KEYS[1]) if n > tonumber(ARGV[1]) then return {n, redis.call('PEXPIRETIME', KEYS[1])} end return {redis.call('HGETALL', KEYS[1]), redis.call('PEXPIRETIME', KEYS[1])}"; @@ -71,6 +71,11 @@ public RedisHashCache( public string Name => KnownCacheProviderNames.Redis; + /// A hash reads no frame. + public bool MetWindowedFrame => false; + + public bool KeepsBounds => true; + internal ValueSerializerRegistry ValueSerializers { get => _valueSerializers; diff --git a/src/UiPath.Caching/Serialization/FormatIdRules.cs b/src/UiPath.Caching/Serialization/FormatIdRules.cs index 0346fd07..8f65a975 100644 --- a/src/UiPath.Caching/Serialization/FormatIdRules.cs +++ b/src/UiPath.Caching/Serialization/FormatIdRules.cs @@ -6,8 +6,11 @@ internal static class FormatIdRules /// The header byte of a remove tombstone: no value serializer may claim it, so no value reads as one. public const int TombstoneId = 0x0F; + /// The header byte of an entry frame. + public const int FrameId = 0x0E; + public static bool IsAllowed(int id) => - id is >= 0x01 and <= 0x0F and not 0x09 and not 0x0A and not 0x0D and not TombstoneId + id is >= 0x01 and <= 0x0F and not 0x09 and not 0x0A and not 0x0D and not FrameId and not TombstoneId or >= CacheValueFormats.FirstConsumer and <= CacheValueFormats.LastConsumer or >= CacheValueFormats.FirstExtended and <= CacheValueFormats.LastExtended; @@ -33,7 +36,7 @@ public static bool IsEventId(int id) => { return new( true, - $"Value serializer '{name}' declares format id {Hex(id)}, which is not one of 0x01-0x0E (except 0x09, 0x0A, 0x0D), 0x10-0x1E or 0x100-0x1FF; 0x0F is reserved for a remove tombstone."); + $"Value serializer '{name}' declares format id {Hex(id)}, which is not one of 0x01-0x0C (except 0x09 and 0x0A), 0x10-0x1E or 0x100-0x1FF. 0x0E is reserved for the entry frame and 0x0F is reserved for a remove tombstone."); } if ((id >= CacheValueFormats.FirstExtended) != extended) diff --git a/src/UiPath.Caching/Serialization/ValueMigration.cs b/src/UiPath.Caching/Serialization/ValueMigration.cs index 9ce17959..8069552f 100644 --- a/src/UiPath.Caching/Serialization/ValueMigration.cs +++ b/src/UiPath.Caching/Serialization/ValueMigration.cs @@ -1,4 +1,5 @@ using UiPath.Caching.Negotiation; +using UiPath.Caching.Redis; using UiPath.Caching.Telemetry; namespace UiPath.Caching.Serialization; @@ -38,7 +39,8 @@ internal sealed class ValueMigration(FormatMigrator migrator, ValueRewriter rewr /// public bool Wants(ICacheValueSerializer target, ReadOnlySpan stored) { - if (stored.IsEmpty || stored.Length > MaxValueBytes || !Allows(target)) + // A framed value is left as it is: a rewrite would drop its frame. + if (stored.IsEmpty || stored.Length > MaxValueBytes || EntryFrame.LooksFramed(stored) || !Allows(target)) { return false; } diff --git a/src/UiPath.Caching/SharedInnerTier.cs b/src/UiPath.Caching/SharedInnerTier.cs index 55910083..986b1d71 100644 --- a/src/UiPath.Caching/SharedInnerTier.cs +++ b/src/UiPath.Caching/SharedInnerTier.cs @@ -5,11 +5,16 @@ namespace UiPath.Caching; /// A shared (distributed) inner tier, Redis or any other cache, with the capabilities it implements. internal sealed class SharedInnerTier : InnerTier { + private readonly object _cache; + public SharedInnerTier(object cache, InMemoryRedisCacheOptions? options = null) - : base(true, cache as ISharedTier, VersionedFor(cache, options), LimitsFor(options), cache as IConnectionState) + : base(true, cache as ISharedTier, VersionedFor(cache, options), LimitsFor(options), cache as IConnectionState, FrameTiers.KeepsBounds(cache)) { + _cache = cache; } + public override bool MayHaveMetWindowedFrame => FrameTiers.MayHaveMet(_cache); + private static ISharedHashTier? VersionedFor(object cache, InMemoryRedisCacheOptions? options) => options is { PeerFieldUpdates: true } ? cache as ISharedHashTier : null; diff --git a/src/UiPath.Caching/StaleValue.cs b/src/UiPath.Caching/StaleValue.cs index 876f2559..7dcc0be7 100644 --- a/src/UiPath.Caching/StaleValue.cs +++ b/src/UiPath.Caching/StaleValue.cs @@ -14,8 +14,23 @@ internal sealed class StaleValue(ICacheEntry entry, long size, DateTimeOffset lo public long Epoch { get; } = epoch; /// Whether a caller that allows may be answered with the value: the writer's stale age bounds how long it is kept, each caller's own what it is served. - public bool Within(DateTimeOffset now, TimeSpan maxStaleAge) => - now < Until && now.UtcTicks - localDeadline.UtcTicks < maxStaleAge.Ticks; + /// A value read with its bounds is also served only before its key's own end and within the caller's age counted from its freshness bound, both on the monotonic clock; neither pair can extend the other. + public bool Within(TimeProvider clock, TimeSpan maxStaleAge) + { + var now = clock.GetUtcNow(); + if (now >= Until || now.UtcTicks - localDeadline.UtcTicks >= maxStaleAge.Ticks) + { + return false; + } + + if (Entry is not ObservedEntry { Observed: var observed }) + { + return true; + } + + var timestamp = clock.GetTimestamp(); + return observed.Kept(timestamp) && observed.Age(clock, timestamp) < maxStaleAge; + } public bool Cooling(TimeProvider clock) => clock.GetTimestamp() < Volatile.Read(ref _cooldownUntil); diff --git a/src/UiPath.Caching/StaleValues.cs b/src/UiPath.Caching/StaleValues.cs index a8747078..aac1b075 100644 --- a/src/UiPath.Caching/StaleValues.cs +++ b/src/UiPath.Caching/StaleValues.cs @@ -114,7 +114,7 @@ public void Advance(string name) /// The value kept for the key, while neither the stale age it was written under nor the caller's has passed. public bool TryGet(string name, TimeSpan maxStaleAge, [NotNullWhen(true)] out StaleValue? value, [NotNullWhen(true)] out ICacheEntry? entry) { - if (Find(name) is { Entry: ICacheEntry typed } kept && kept.Within(_clock.GetUtcNow(), maxStaleAge)) + if (Find(name) is { Entry: ICacheEntry typed } kept && kept.Within(_clock, maxStaleAge)) { value = kept; entry = typed; @@ -220,7 +220,7 @@ public void Settle(string name, StaleValue kept, ICacheEntry entry, bool local, return; } - if (reason.Value == EvictionReason.Expired) + if (Leaving(entry, reason.Value) == EvictionReason.Expired) { Charge(name, entry); } @@ -278,8 +278,19 @@ private void Store(KeptKey key, StaleValue value, long size, CacheItemPriority p } } + /// How the entry left, for its kept value: an observed entry that left on its bound has expired, unless a peer's change fired its token, which drops the value on its own road. + /// The UTC and the monotonic clock drift apart by slew, so the bound can fire a moment before the UTC deadline, and always first after a backward step. + private EvictionReason Leaving(ICacheEntry entry, EvictionReason reason) => + reason == EvictionReason.TokenExpired + && entry is ObservedEntry { Observed: var observed } + && !observed.Fresh(_clock.GetTimestamp()) + && entry is ILocalEntry { TokenChanged: false } + ? EvictionReason.Expired + : reason; + private void Left(string name, ICacheEntry entry, EvictionReason reason) { + reason = Leaving(entry, reason); // Recorded first, for a keep that has not run yet. _left.AddOrUpdate(entry, new StrongBox(reason)); diff --git a/tests/UiPath.Caching.Migration.Tests/HashRegistrationTests.cs b/tests/UiPath.Caching.Migration.Tests/HashRegistrationTests.cs index 505e0d8a..efbe0d71 100644 --- a/tests/UiPath.Caching.Migration.Tests/HashRegistrationTests.cs +++ b/tests/UiPath.Caching.Migration.Tests/HashRegistrationTests.cs @@ -313,6 +313,8 @@ private sealed class Strings : IByteCodecCache public byte[] Encode(T value, CachePolicy? policy) => throw new NotSupportedException(); public (SnapshotOutcome Outcome, T? Value) Decode(byte[] stored, CachePolicy? policy, bool quiet = false) => throw new NotSupportedException(); + + public bool TryUnframe(byte[] stored, out FrameInfo info) => throw new NotSupportedException(); } private sealed class Hashes : IByteHashCodecCache diff --git a/tests/UiPath.Caching.Migration.Tests/KeyMove/ForwardingCache.cs b/tests/UiPath.Caching.Migration.Tests/KeyMove/ForwardingCache.cs new file mode 100644 index 00000000..182c217c --- /dev/null +++ b/tests/UiPath.Caching.Migration.Tests/KeyMove/ForwardingCache.cs @@ -0,0 +1,70 @@ +using System.Reflection; +using System.Runtime.ExceptionServices; + +namespace UiPath.Caching.Migration.Tests.KeyMove; + +/// An and that forwards every call to another cache and implements no interface of the library's own. +public interface IForwardingCache : ICache, IMigrationCache +{ + /// How many times the member of that name was called. + int Count(string name); +} + +/// The forwarding proxy; with each snapshot entry it reads leaves as an entry the plain factory built anew. +public class ForwardingCache : DispatchProxy +{ + private static readonly MethodInfo RebuildMethod = typeof(ForwardingCache).GetMethod(nameof(RebuildAsync), BindingFlags.Static | BindingFlags.NonPublic)!; + private readonly List _calls = []; + + private object Target { get; set; } = default!; + + private bool Rebuild { get; set; } + + public static IForwardingCache Over(ICache target, bool rebuild = false) + { + var proxy = Create(); + var forwarding = (ForwardingCache)(object)proxy; + forwarding.Target = target; + forwarding.Rebuild = rebuild; + return proxy; + } + + protected override object? Invoke(MethodInfo? targetMethod, object?[]? args) + { + if (targetMethod!.DeclaringType == typeof(IForwardingCache)) + { + lock (_calls) + { + return _calls.Count(call => call == (string)args![0]!); + } + } + + lock (_calls) + { + _calls.Add(targetMethod.Name); + } + + object? answer; + try + { + answer = targetMethod.Invoke(Target, args); + } + catch (TargetInvocationException ex) + { + ExceptionDispatchInfo.Throw(ex.InnerException!); + throw; + } + + return Rebuild && targetMethod.Name == nameof(IMigrationCache.ReadSnapshotAsync) + ? RebuildMethod.MakeGenericMethod(targetMethod.GetGenericArguments()[0]).Invoke(null, [answer]) + : answer; + } + + private static async ValueTask> RebuildAsync(ValueTask> read) + { + var snapshot = await read; + return snapshot.Entry is { } entry + ? snapshot with { Entry = new CacheEntryFactory().Create(entry.Value, entry.Expiration) } + : snapshot; + } +} diff --git a/tests/UiPath.Caching.Migration.Tests/KeyMove/FrameLibraryRig.cs b/tests/UiPath.Caching.Migration.Tests/KeyMove/FrameLibraryRig.cs new file mode 100644 index 00000000..16cefae6 --- /dev/null +++ b/tests/UiPath.Caching.Migration.Tests/KeyMove/FrameLibraryRig.cs @@ -0,0 +1,112 @@ +using Microsoft.Extensions.DependencyInjection; +using StackExchange.Redis; +using UiPath.Caching.Config; +using UiPath.Caching.Migration.Tests.Support; +using UiPath.Caching.Redis; + +namespace UiPath.Caching.Migration.Tests.KeyMove; + +/// The library's caches over one Redis, on a clock that the test moves: the cache a router reads, and the frames it meets. +internal sealed class FrameLibraryRig : IAsyncDisposable +{ + public static readonly TimeSpan Window = TimeSpan.FromSeconds(60); + + private readonly ConnectionMultiplexer _mux; + private readonly ServiceProvider _provider; + private readonly Dictionary _raw = []; + + private FrameLibraryRig(ConnectionMultiplexer mux, ServiceProvider provider, ManualTimeProvider clock, string prefix) + { + _mux = mux; + _provider = provider; + Clock = clock; + Prefix = prefix; + } + + public ManualTimeProvider Clock { get; } + + public string Prefix { get; } + + public IDatabase Db => _mux.GetDatabase(); + + public ICacheFactory Factory => _provider.GetRequiredService(); + + public RedisCache Redis => (RedisCache)Factory.CreateCache(KnownCacheProviderNames.Redis); + + /// A layered cache over Redis. + public ICache Layered => Factory.CreateCache(KnownCacheProviderNames.InMemoryRedis); + + /// A layered cache with no shared tier. + public ICache InMemory => Factory.CreateCache(KnownCacheProviderNames.InMemory); + + public static async Task CreateAsync(RedisFixture fixture, Func? memory = null) + { + Assert.SkipUnless(fixture.Enabled, "Set RUN_REDIS_INTEGRATION_TESTS=1 and REDIS_CONNECTION_STRING to run."); + var mux = await ConnectionMultiplexer.ConnectAsync(fixture.ConnectionString + ",allowAdmin=true"); + var run = Guid.NewGuid().ToString("N")[..10]; + var clock = new ManualTimeProvider(await KeyMoveKit.ServerTimeAsync(mux.GetDatabase())); + var services = new ServiceCollection().AddLogging().AddSingleton(clock); + if (memory is not null) + { + services.AddSingleton(memory(clock)); + } + + var provider = services + .AddCaching( + builder => + { + builder.AddRedisConnection(o => o.ConnectionString = fixture.ConnectionString); + builder.AddRedis(_ => { }); + builder.AddInMemoryRedis(o => o.LocalMaxExpiration = TimeSpan.FromHours(2)); + builder.AddMemory(_ => { }); + }, + o => o.AppShortName = "fs" + run) + .BuildServiceProvider(); + return new FrameLibraryRig(mux, provider, clock, $"fs{run}"); + } + + public string RedisKey(string key) => $"{Prefix}:{key}"; + + /// The key as Redis holds it: the library's key strategy wraps the router's verbatim key, so a seed write finds it. + public async Task RawKeyAsync(string key) + { + if (_raw.TryGetValue(key, out var raw)) + { + return raw; + } + + await Redis.SetAsync(CacheKey.Verbatim(RedisKey(key)), new Item("seed"), TimeSpan.FromMinutes(10)); + var name = RedisKey(key); + raw = _mux.GetServers().Where(s => !s.IsReplica).SelectMany(s => s.Keys(pattern: $"*{name}*")).Single(k => ((string)k!).EndsWith(name, StringComparison.Ordinal)); + _raw[key] = raw; + return raw; + } + + public LibraryPathClient Path(ICache cache) => + new((IMigrationCache)cache, new FakeConnection(), RedisKey, TimeSpan.FromSeconds(30)) { Cache = cache }; + + public byte[] Encode(string name) => Redis.Encode(new Item(name), null); + + public async Task StorePlainAsync(string key, string name, TimeSpan ttl) => await Db.StringSetAsync(await RawKeyAsync(key), Encode(name), ttl); + + /// A frame with a window of that expires from the clock, on a key with left. + public async Task StoreFrameAsync(string key, string name, TimeSpan expiresIn, TimeSpan keyTtl) => + await Db.StringSetAsync(await RawKeyAsync(key), EntryFrame.Write(Encode(name), Clock.GetUtcNow() + expiresIn, Window, null), keyTtl); + + /// Sets the life left of the key as Redis holds it. + public async Task ExpireAsync(string key, TimeSpan ttl) => await Db.KeyExpireAsync(await RawKeyAsync(key), ttl); + + public async ValueTask DisposeAsync() + { + foreach (var server in _mux.GetServers().Where(s => !s.IsReplica)) + { + foreach (var key in server.Keys(pattern: $"*{Prefix}*").ToArray()) + { + await Db.KeyDeleteAsync(key); + } + } + + await _provider.DisposeAsync(); + await _mux.DisposeAsync(); + } +} diff --git a/tests/UiPath.Caching.Migration.Tests/KeyMove/FrameReadDatabase.cs b/tests/UiPath.Caching.Migration.Tests/KeyMove/FrameReadDatabase.cs new file mode 100644 index 00000000..3296364a --- /dev/null +++ b/tests/UiPath.Caching.Migration.Tests/KeyMove/FrameReadDatabase.cs @@ -0,0 +1,160 @@ +using System.Reflection; +using System.Runtime.ExceptionServices; +using StackExchange.Redis; + +namespace UiPath.Caching.Migration.Tests.KeyMove; + +// Logs the string reads of a key move as their commands, can answer the paired read with a substitute, and can hold or fail a transaction's reply. +public class FrameReadDatabase : DispatchProxy +{ + private readonly object _gate = new(); + private readonly List _log = []; + private IDatabase? _inner; + + public IReadOnlyList Log + { + get + { + lock (_gate) + { + return [.. _log]; + } + } + } + + /// A substitute answer of the paired read (PTTL then GET) of a key; null sends the real one. + public Func? PairedRead { get; set; } + + /// Runs once EXEC has answered and before the reply is handed on. + public Action? AtExecReply { get; set; } + + /// Fails the EXEC of a transaction that reads this key. + public Func? FailExec { get; set; } + + public static IDatabase Over(IDatabase inner, out FrameReadDatabase spy) + { + var proxy = Create(); + spy = (FrameReadDatabase)(object)proxy; + spy._inner = inner; + return proxy; + } + + public void Clear() + { + lock (_gate) + { + _log.Clear(); + } + } + + internal void Add(string command, object?[]? args) + { + var flags = args?.OfType().FirstOrDefault() ?? CommandFlags.None; + lock (_gate) + { + _log.Add(flags == CommandFlags.None ? command : $"{command} {flags}"); + } + } + + protected override object? Invoke(MethodInfo? targetMethod, object?[]? args) + { + ArgumentNullException.ThrowIfNull(targetMethod); + switch (targetMethod.Name) + { + case nameof(IDatabase.StringGetWithExpiryAsync): + Add("PTTL+GET", args); + if (PairedRead?.Invoke((RedisKey)args![0]!) is { } answer) + { + return Task.FromResult(answer); + } + + break; + case nameof(IDatabase.StringGetAsync) when args is [RedisKey[], ..]: + Add("MGET", args); + break; + case nameof(IDatabase.ExecuteAsync) when args is ["PTTL", ..]: + Add("PTTL", args); + break; + case nameof(IDatabase.CreateTransaction): + Add("MULTI", null); + return FrameTransaction.Over((ITransaction)Forward(targetMethod, args)!, this); + } + + return Forward(targetMethod, args); + } + + private object? Forward(MethodInfo method, object?[]? args) + { + try + { + return method.Invoke(_inner, args); + } + catch (TargetInvocationException ex) when (ex.InnerException is not null) + { + ExceptionDispatchInfo.Throw(ex.InnerException); + throw; + } + } +} + +// The transaction of a second read: logs what it queues, and lets the spy hold or fail its EXEC. +public class FrameTransaction : DispatchProxy +{ + private readonly List _keys = []; + private ITransaction? _inner; + private FrameReadDatabase? _spy; + + public static ITransaction Over(ITransaction inner, FrameReadDatabase spy) + { + var proxy = Create(); + var transaction = (FrameTransaction)(object)proxy; + transaction._inner = inner; + transaction._spy = spy; + return proxy; + } + + protected override object? Invoke(MethodInfo? targetMethod, object?[]? args) + { + ArgumentNullException.ThrowIfNull(targetMethod); + switch (targetMethod.Name) + { + case nameof(ITransaction.StringGetAsync) when args is [RedisKey key, ..]: + _keys.Add(key); + _spy!.Add("GET", args); + break; + case nameof(ITransaction.KeyTimeToLiveAsync): + _spy!.Add("PTTL", args); + break; + case nameof(ITransaction.ExecuteAsync) when args is [CommandFlags]: + _spy!.Add("EXEC", args); + if (_spy.FailExec is { } fail && _keys.Any(fail)) + { + return Task.FromException(new RedisException("The test failed the transaction.")); + } + + return HoldAsync((Task)Forward(targetMethod, args)!); + } + + return Forward(targetMethod, args); + } + + private async Task HoldAsync(Task exec) + { + var done = await exec; + _spy!.AtExecReply?.Invoke(); + return done; + } + + private object? Forward(MethodInfo method, object?[]? args) + { + try + { + return method.Invoke(_inner, args); + } + catch (TargetInvocationException ex) when (ex.InnerException is not null) + { + ExceptionDispatchInfo.Throw(ex.InnerException); + throw; + } + } +} diff --git a/tests/UiPath.Caching.Migration.Tests/KeyMove/FramedItemCache.cs b/tests/UiPath.Caching.Migration.Tests/KeyMove/FramedItemCache.cs new file mode 100644 index 00000000..012bea3c --- /dev/null +++ b/tests/UiPath.Caching.Migration.Tests/KeyMove/FramedItemCache.cs @@ -0,0 +1,28 @@ +using System.Text; +using UiPath.Caching.Migration.Tests.Support; +using UiPath.Caching.Redis; + +namespace UiPath.Caching.Migration.Tests.KeyMove; + +// A library codec cache over Item: the name as UTF-8 text, a cached null as the empty value, and the library's own frame split. +internal sealed class FramedItemCache : IByteCodecCache +{ + public bool CachesNulls => true; + + public static LibraryKeyMoveCodec Codec() => new(new FramedItemCache(), 1024 * 1024); + + public static byte[] Windowed(string name, DateTimeOffset expiration, TimeSpan window) => EntryFrame.Write(Encoding.UTF8.GetBytes(name), expiration, window, null); + + public static byte[] Validated(string name) => EntryFrame.Write(Encoding.UTF8.GetBytes(name), DateTimeOffset.MaxValue, TimeSpan.Zero, EntryValidators.From("v1", null)); + + public byte[] Encode(T value, CachePolicy? policy) => Encoding.UTF8.GetBytes(((Item)(object)value!).Name); + + public (SnapshotOutcome Outcome, T? Value) Decode(byte[] stored, CachePolicy? policy, bool quiet = false) => stored switch + { + [] => (SnapshotOutcome.Absent, default), + [EntryFrame.Header, ..] => (SnapshotOutcome.Unreadable, default), + _ => (SnapshotOutcome.Found, (T)(object)new Item(Encoding.UTF8.GetString(stored))), + }; + + public bool TryUnframe(byte[] stored, out FrameInfo info) => EntryFrame.TryUnframe(stored, out info); +} diff --git a/tests/UiPath.Caching.Migration.Tests/KeyMove/KeyMoveHashClassesTests.cs b/tests/UiPath.Caching.Migration.Tests/KeyMove/KeyMoveHashClassesTests.cs index a5f27a21..7a2fe35b 100644 --- a/tests/UiPath.Caching.Migration.Tests/KeyMove/KeyMoveHashClassesTests.cs +++ b/tests/UiPath.Caching.Migration.Tests/KeyMove/KeyMoveHashClassesTests.cs @@ -152,6 +152,8 @@ private sealed class Strings : IByteCodecCache public byte[] Encode(T value, CachePolicy? policy) => throw new NotSupportedException(); public (SnapshotOutcome Outcome, T? Value) Decode(byte[] stored, CachePolicy? policy, bool quiet = false) => throw new NotSupportedException(); + + public bool TryUnframe(byte[] stored, out FrameInfo info) => throw new NotSupportedException(); } private sealed class Hashes(bool cachesNulls) : IByteHashCodecCache diff --git a/tests/UiPath.Caching.Migration.Tests/KeyMove/KeyMoveInPlaceFormatTests.cs b/tests/UiPath.Caching.Migration.Tests/KeyMove/KeyMoveInPlaceFormatTests.cs index c44d8332..2e8bb207 100644 --- a/tests/UiPath.Caching.Migration.Tests/KeyMove/KeyMoveInPlaceFormatTests.cs +++ b/tests/UiPath.Caching.Migration.Tests/KeyMove/KeyMoveInPlaceFormatTests.cs @@ -274,6 +274,12 @@ public byte[] Encode(T value, CachePolicy? policy) } public (SnapshotOutcome Outcome, T? Value) Decode(byte[] stored, CachePolicy? policy, bool quiet = false) => (SnapshotOutcome.Absent, default); + + public bool TryUnframe(byte[] stored, out FrameInfo info) + { + info = default; + return false; + } } private sealed class RecordingHashCodecCache : IByteHashCodecCache diff --git a/tests/UiPath.Caching.Migration.Tests/KeyMoveFrameSnapTests.cs b/tests/UiPath.Caching.Migration.Tests/KeyMoveFrameSnapTests.cs new file mode 100644 index 00000000..584faf6a --- /dev/null +++ b/tests/UiPath.Caching.Migration.Tests/KeyMoveFrameSnapTests.cs @@ -0,0 +1,614 @@ +using System.Text; +using Microsoft.Extensions.Caching.Memory; +using Microsoft.Extensions.Logging.Abstractions; +using StackExchange.Redis; +using UiPath.Caching.KeyMove; +using UiPath.Caching.Migration.Tests.KeyMove; +using UiPath.Caching.Migration.Tests.Support; + +namespace UiPath.Caching.Migration.Tests; + +// MR1 to MR6: a windowed frame is judged on a matched pair only, the value and the TTL of one transaction on the master, timed from its send. +[Collection("RedisIntegration")] +[Trait("Category", "Integration")] +public sealed class KeyMoveFrameSnapTests(RedisFixture fixture) +{ + private static readonly TimeSpan Window = TimeSpan.FromSeconds(60); + private static readonly TimeSpan Slack = TimeSpan.FromSeconds(2); + + // The roads that hand the router a found value: the read of a move that served the value, the library path, and the two fills that meet a stored value. + public enum Road + { + ServedRead, + LibraryRead, + LibraryFill, + MoveFill, + } + + // The library cache of a routed fill that meets a stored value. + public enum Library + { + Forwarded, + LayeredBefore, + LayeredAfter, + RedisBefore, + } + + // KS1: the snap of a key move client, on a replica first or on the master. KS2: the snapshot of the in-place side. KS3: the batch read. + public enum Site + { + ReplicaSnap, + MasterSnap, + SideSnapshot, + Batch, + } + + public static TheoryData Sites => [Site.ReplicaSnap, Site.SideSnapshot, Site.Batch]; + + public static TheoryData SingleKeySites => [Site.ReplicaSnap, Site.MasterSnap, Site.SideSnapshot]; + + public static TheoryData RoadsAndFrames => [.. from road in Enum.GetValues() from framed in new[] { true, false } select (road, framed)]; + + public static TheoryData AskedAndChanged => [.. from asked in new[] { false, true } from change in new[] { false, true } select (asked, change)]; + + public static TheoryData SitesAndSteps => [.. from site in new[] { Site.ReplicaSnap, Site.SideSnapshot, Site.Batch } from step in new[] { -10, 10, 0 } select (site, step)]; + + public static TheoryData SitesAndValues => [.. from site in new[] { Site.ReplicaSnap, Site.SideSnapshot, Site.Batch } from framed in new[] { false, true } select (site, framed)]; + + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + [Theory] + [InlineData(30, 600)] + [InlineData(59, 3_599)] + public async Task A_batch_read_never_pairs_a_frame_with_a_later_ttl(int keyTtlSeconds, int expiresInSeconds) + { + await using var kit = await CreateAsync(); + var now = kit.Clock.GetUtcNow(); + await PrepareAsync(kit); + await kit.Db.StringSetAsync(kit.N("k"), FramedItemCache.Windowed("old", now.AddSeconds(expiresInSeconds), Window), TimeSpan.FromSeconds(keyTtlSeconds)); + kit.Schedule.Hook = async (step, _) => + { + if (step == SchedulePointStep.ReadLife) + { + await kit.Db.StringSetAsync(kit.N("k"), "new", TimeSpan.FromMinutes(10)); + } + }; + + var read = (await kit.Client.ReadManyAsync(["k"], Ct))["k"]; + + read.Value.Should().NotBe(new Item("old")); + if (read.Kind == ReadOutcome.Found) + { + read.Value.Should().Be(new Item("new")); + read.Expiration!.Value.Should().BeCloseTo(now.AddMinutes(10), Slack); + } + else + { + read.Kind.Should().Be(ReadOutcome.Absent); + } + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task A_batch_read_rewritten_before_the_second_read_is_judged_by_the_second_read(bool toExpiredFrame) + { + await using var kit = await CreateAsync(); + var now = kit.Clock.GetUtcNow(); + await PrepareAsync(kit); + await kit.Db.StringSetAsync(kit.N("k"), FramedItemCache.Windowed("old", now.AddMinutes(10), Window), TimeSpan.FromMinutes(11)); + kit.Schedule.Hook = async (step, _) => + { + if (step == SchedulePointStep.ReadFrameAgain) + { + await (toExpiredFrame + ? kit.Db.StringSetAsync(kit.N("k"), FramedItemCache.Windowed("expired", now.AddMinutes(10), Window), TimeSpan.FromSeconds(30)) + : kit.Db.StringSetAsync(kit.N("k"), "new", TimeSpan.FromMinutes(5))); + } + }; + + var read = (await kit.Client.ReadManyAsync(["k"], Ct))["k"]; + + kit.Schedule.Steps.Should().Contain(SchedulePointStep.ReadFrameAgain); + if (toExpiredFrame) + { + read.Kind.Should().Be(ReadOutcome.Absent); + } + else + { + read.Value.Should().Be(new Item("new")); + read.Expiration!.Value.Should().BeCloseTo(now.AddMinutes(5), Slack); + } + } + + [Theory] + [MemberData(nameof(SingleKeySites))] + public async Task A_single_key_snap_never_pairs_a_frame_with_an_earlier_ttl(Site site) + { + FrameReadDatabase? spy = null; + await using var kit = await CreateAsync(db => FrameReadDatabase.Over(db, out spy)); + var now = kit.Clock.GetUtcNow(); + var expired = FramedItemCache.Windowed("expired", now.AddMinutes(10), Window); + var fresh = FramedItemCache.Windowed("fresh", now.AddMinutes(10), Window); + var key = KeyOf(kit, site); + + foreach (var (stored, storedTtl, answered, answeredTtl) in new[] { (fresh, TimeSpan.FromMinutes(11), expired, TimeSpan.FromSeconds(30)), (expired, TimeSpan.FromSeconds(30), fresh, TimeSpan.FromMinutes(11)) }) + { + await kit.Db.StringSetAsync(key, stored, storedTtl); + spy!.PairedRead = k => k == key ? new RedisValueWithExpiry(answered, answeredTtl) : null; + + var snap = await SnapAsync(kit, site); + + snap.Atomic.Should().BeTrue(); + snap.Bytes.Should().Equal(stored, "the snap is the transaction's"); + snap.TtlMs.Should().BeCloseTo((long)storedTtl.TotalMilliseconds, 2_000); + } + } + + [Theory] + [MemberData(nameof(Sites))] + public async Task A_windowed_frame_is_read_again_in_one_transaction_on_the_master(Site site) + { + FrameReadDatabase? spy = null; + await using var kit = await CreateAsync(db => FrameReadDatabase.Over(db, out spy)); + var now = kit.Clock.GetUtcNow(); + await PrepareAsync(kit, "k", "j"); + foreach (var key in new[] { "k", "j" }) + { + await kit.Db.StringSetAsync(site == Site.SideSnapshot ? kit.L(key) : kit.N(key), FramedItemCache.Windowed(key, now.AddMinutes(10), Window), TimeSpan.FromMinutes(11)); + } + + spy!.Clear(); + if (site == Site.Batch) + { + await kit.Client.ReadManyAsync(["k", "j"], Ct); + } + else + { + await SnapAsync(kit, site); + } + + var transaction = new[] { "MULTI", "GET DemandMaster", "PTTL DemandMaster", "EXEC DemandMaster" }; + var log = spy.Log.Where(c => c is not "MGET PreferReplica" and not "MGET DemandMaster").ToList(); + if (site == Site.Batch) + { + spy.Log.Should().Contain(c => c.StartsWith("MGET", StringComparison.Ordinal)); + log.Should().Equal([.. transaction, .. transaction], "one transaction per key, and no PTTL of the batch for a framed hit"); + } + else + { + log.Should().Equal([site == Site.ReplicaSnap ? "PTTL+GET PreferReplica" : "PTTL+GET DemandMaster", .. transaction]); + } + } + + [Theory] + [MemberData(nameof(Sites))] + public async Task The_second_read_takes_its_time_before_it_sends(Site site) + { + FrameReadDatabase? spy = null; + await using var kit = await CreateAsync(db => FrameReadDatabase.Over(db, out spy)); + spy!.AtExecReply = () => kit.Time.Manual.Advance(TimeSpan.FromSeconds(5)); + await PrepareAsync(kit); + + foreach (var ttl in new[] { 61, 70 }) + { + var sent = kit.Clock.GetUtcNow(); + var read = await JudgedReadAsync(kit, site, FramedItemCache.Windowed("v", sent.AddHours(1), Window), TimeSpan.FromSeconds(ttl)); + + if (ttl == 61) + { + read.Kind.Should().Be(ReadOutcome.Absent, "61 s less the 5 s of the reply is inside the window"); + } + else + { + read.Value.Should().Be(new Item("v")); + read.Expiration!.Value.Should().BeCloseTo(sent.AddSeconds(10), Slack); + read.Expiration.Value.Should().BeOnOrBefore(sent.AddSeconds(10)); + } + } + } + + [Theory] + [MemberData(nameof(SitesAndSteps))] + public async Task A_step_of_the_UTC_clock_during_the_second_read_never_extends_a_moved_life(Site site, int stepSeconds) + { + FrameReadDatabase? spy = null; + await using var kit = await CreateAsync(db => FrameReadDatabase.Over(db, out spy)); + spy!.AtExecReply = () => + { + kit.Time.Manual.Advance(TimeSpan.FromSeconds(5)); + kit.Time.Manual.StepUtc(TimeSpan.FromSeconds(stepSeconds)); + }; + await PrepareAsync(kit); + + foreach (var ttl in new[] { 61, 70 }) + { + var expiration = kit.Clock.GetUtcNow().AddHours(1); + var read = await JudgedReadAsync(kit, site, FramedItemCache.Windowed("v", expiration, Window), TimeSpan.FromSeconds(ttl)); + var judged = kit.Clock.GetUtcNow(); + + if (ttl == 61) + { + read.Kind.Should().Be(ReadOutcome.Absent); + } + else + { + read.Value.Should().Be(new Item("v")); + read.Expiration!.Value.Should().BeCloseTo(judged.AddSeconds(5), Slack, "the life is 5 s from the snap's At, whatever the UTC clock did"); + read.Expiration.Value.Should().BeOnOrBefore(judged.AddSeconds(5)); + } + } + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task A_second_snap_whose_key_ended_before_the_reply_is_absent(bool replacedByPlain) + { + FrameReadDatabase? spy = null; + await using var kit = await CreateAsync(db => FrameReadDatabase.Over(db, out spy)); + spy!.AtExecReply = () => kit.Time.Manual.Advance(TimeSpan.FromSeconds(5)); + var now = kit.Clock.GetUtcNow(); + var frame = FramedItemCache.Windowed("v", now.AddHours(1), Window); + await kit.Db.StringSetAsync(kit.N("k"), replacedByPlain ? "plain"u8.ToArray() : frame, TimeSpan.FromSeconds(4)); + spy.PairedRead = _ => new RedisValueWithExpiry(frame, TimeSpan.FromMinutes(5)); + + var snap = await SnapAsync(kit, Site.MasterSnap); + + snap.Kind.Should().Be(ReadOutcome.Absent, "the read shows no life left once the reply's wait is taken off"); + snap.Atomic.Should().BeTrue(); + } + + [Theory] + [MemberData(nameof(SitesAndValues))] + public async Task A_plain_value_and_a_frame_without_a_window_are_not_read_again(Site site, bool framed) + { + FrameReadDatabase? spy = null; + await using var kit = await CreateAsync(db => FrameReadDatabase.Over(db, out spy)); + await PrepareAsync(kit); + var stored = framed ? FramedItemCache.Validated("v") : "v"u8.ToArray(); + await kit.Db.StringSetAsync(KeyOf(kit, site), stored, TimeSpan.FromMinutes(10)); + + spy!.Clear(); + var read = site == Site.Batch ? (await kit.Client.ReadManyAsync(["k"], Ct))["k"] : KeyPromotion.Interpret(await SnapAsync(kit, site), FramedItemCache.Codec()); + + read.Value.Should().Be(new Item("v")); + spy.Log.Should().NotContain("MULTI"); + spy.Log.Should().Equal(site == Site.Batch ? ["MGET PreferReplica", "PTTL PreferReplica"] : [site == Site.ReplicaSnap ? "PTTL+GET PreferReplica" : "PTTL+GET DemandMaster"]); + } + + [Theory] + [InlineData("forward", false)] + [InlineData("forward", true)] + [InlineData("reverse", false)] + [InlineData("reverse", true)] + [InlineData("batch", false)] + [InlineData("batch", true)] + public async Task A_promoted_frame_carries_the_life_of_the_value_that_was_read(string path, bool thenC) + { + FrameReadDatabase? spy = null; + await using var kit = await CreateAsync(db => FrameReadDatabase.Over(db, out spy)); + var writer = kit.Clock.GetUtcNow().AddHours(1); + var b = FramedItemCache.Windowed("B", writer.AddSeconds(1), Window); + var c = FramedItemCache.Windowed("C", writer.AddSeconds(600), Window); + var reverse = path != "forward"; + var source = reverse ? kit.N("k") : kit.L("k"); + var target = reverse ? kit.L("k") : kit.N("k"); + await kit.PrepareAsync("k"); + await kit.SetStateAsync("S3", direction: reverse ? "rev" : "fwd"); + + // A had 660 s left; B landed between the PTTL and the GET of the paired read, and C, when there, after it. + await kit.Db.StringSetAsync(source, thenC ? c : b, thenC ? TimeSpan.FromSeconds(660) : TimeSpan.FromSeconds(61)); + spy!.PairedRead = k => k == source ? new RedisValueWithExpiry(b, TimeSpan.FromSeconds(660)) : null; + + _ = path == "batch" ? (await kit.Client.ReadManyAsync(["k"], Ct))["k"] : await kit.Client.ReadAsync("k", Ct); + + var held = (byte[]?)await kit.Db.StringGetAsync(target); + var left = await kit.Db.KeyTimeToLiveAsync(target); + if (held is not null) + { + var name = Encoding.UTF8.GetString(held); + name.Should().BeOneOf("B", "C"); + left!.Value.Should().BeLessThanOrEqualTo(name == "B" ? TimeSpan.FromSeconds(1) : TimeSpan.FromSeconds(600)); + } + } + + [Fact] + public void Interpret_refuses_a_windowed_frame_in_a_snap_that_is_not_atomic() + { + var at = new DateTimeOffset(2030, 1, 1, 0, 0, 0, TimeSpan.Zero); + var snap = new KeyMoveSnap(ReadOutcome.Found, FramedItemCache.Windowed("v", at.AddHours(1), Window), 70_000, at); + + KeyPromotion.Interpret(snap, FramedItemCache.Codec()).Kind.Should().Be(ReadOutcome.Unavailable); + KeyPromotion.Interpret(snap with { Atomic = true }, FramedItemCache.Codec()).Should().Be(new PathRead(ReadOutcome.Found, new Item("v"), at.AddSeconds(10), Uncached: true)); + KeyPromotion.Interpret(snap with { Bytes = FramedItemCache.Validated("v") }, FramedItemCache.Codec()).Kind.Should().Be(ReadOutcome.Found, "a frame without a window keeps today's pair"); + } + + [Fact] + public async Task A_failed_second_read_makes_the_key_unavailable_and_an_absent_key_absent() + { + FrameReadDatabase? spy = null; + await using var kit = await CreateAsync(db => FrameReadDatabase.Over(db, out spy)); + var now = kit.Clock.GetUtcNow(); + await PrepareAsync(kit, "failed", "gone", "kept"); + foreach (var key in new[] { "failed", "gone", "kept" }) + { + await kit.Db.StringSetAsync(kit.N(key), FramedItemCache.Windowed(key, now.AddMinutes(10), Window), TimeSpan.FromMinutes(11)); + } + + spy!.FailExec = k => k == (RedisKey)kit.N("failed"); + kit.Schedule.Hook = async (step, _) => + { + if (step == SchedulePointStep.ReadFrameAgain) + { + await kit.Db.KeyDeleteAsync(kit.N("gone")); + } + }; + + var read = await kit.Client.ReadManyAsync(["failed", "gone", "kept"], Ct); + + read["failed"].Kind.Should().Be(ReadOutcome.Unavailable); + read["gone"].Kind.Should().Be(ReadOutcome.Absent); + read["kept"].Value.Should().Be(new Item("kept")); + } + + [Theory] + [InlineData(true, false)] + [InlineData(true, true)] + [InlineData(false, false)] + [InlineData(false, true)] + public async Task The_router_TTL_commands_answer_from_the_key_while_a_move_is_on(bool sourceSide, bool windowed) + { + await using var kit = await CreateAsync(); + var now = kit.Clock.GetUtcNow(); + await PrepareAsync(kit); + var stored = windowed ? FramedItemCache.Windowed("v", now.AddMinutes(1), TimeSpan.FromHours(1)) : "v"u8.ToArray(); + var physical = windowed ? TimeSpan.FromMinutes(61) : TimeSpan.FromMinutes(10); + await kit.Db.StringSetAsync(sourceSide ? kit.L("k") : kit.N("k"), stored, physical); + + var ttl = await kit.Client.TimeToLiveAsync("k", Ct); + var expires = await kit.Client.ExpireTimeAsync("k", Ct); + + // I-KM8: the documented limit. A windowed frame answers its physical life, window included, as PTTL does on the library path. + ttl!.Value.Should().BeCloseTo(physical, TimeSpan.FromSeconds(5)); + expires!.Value.Should().BeCloseTo(now + physical, TimeSpan.FromSeconds(5)); + } + + [Theory] + [MemberData(nameof(RoadsAndFrames))] + public async Task The_router_keeps_no_local_copy_of_a_value_from_a_windowed_frame(Road road, bool framed) + { + var (node, replace, rig) = await RoadAsync(road, framed); + await using var _ = rig; + await using var __ = node; + + (await node.Cache.TryGetAsync("k", Ct)).Should().Be(new Item("v")); + await replace(); + + // A frame leaves no copy, so the next call reads the key again; a plain value is kept as before. + node.IsLocal("k").Should().Be(!framed); + (await node.Cache.TryGetAsync("k", Ct)).Should().Be(new Item(framed ? "w" : "v")); + } + + [Theory] + [InlineData(Library.Forwarded)] + [InlineData(Library.LayeredBefore)] + [InlineData(Library.LayeredAfter)] + [InlineData(Library.RedisBefore)] + public async Task The_router_keeps_no_stored_value_from_a_cache_it_cannot_ask(Library library) + { + await using var rig = await FrameLibraryRig.CreateAsync(fixture); + ICache cache = library switch + { + Library.Forwarded => ForwardingCache.Over(rig.Redis), + Library.RedisBefore => rig.Redis, + _ => rig.Layered, + }; + if (library == Library.LayeredAfter) + { + await MeetFrameAsync(rig, cache); + } + + FrameTiers.MayHaveMet(cache).Should().Be(library is Library.Forwarded or Library.LayeredAfter); + await using var node = TestNode.Create(new FakeBus(), rig.Clock, [], "frs" + rig.Prefix, library: rig.Path(cache)); + + var served = await node.Cache.GetOrAddAsync( + "k", + async _ => + { + await rig.StorePlainAsync("k", "stored", TimeSpan.FromMinutes(10)); + return new Item("mine"); + }, + default, + Ct); + + served.Should().Be(new Item("stored")); + node.IsLocal("k").Should().Be(library is Library.LayeredBefore or Library.RedisBefore); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task The_router_keeps_no_read_from_a_cache_that_does_not_keep_bounds(bool framed) + { + await using var rig = await FrameLibraryRig.CreateAsync(fixture); + var wrapper = ForwardingCache.Over(rig.Redis, rebuild: true); + await using var node = TestNode.Create(new FakeBus(), rig.Clock, [], "frs" + rig.Prefix, library: rig.Path(wrapper)); + if (framed) + { + await rig.StoreFrameAsync("k", "v", TimeSpan.FromHours(1), Window + TimeSpan.FromSeconds(1)); + } + else + { + await rig.StorePlainAsync("k", "v", Window + TimeSpan.FromSeconds(1)); + } + + (await rig.Path(wrapper).ReadAsync("k", Ct)).Uncached.Should().BeTrue("the library cannot tell the rebuilt entry from a plain one"); + var reads = wrapper.Count(nameof(IMigrationCache.ReadSnapshotAsync)); + + (await node.Cache.TryGetAsync("k", Ct)).Should().Be(new Item("v")); + node.IsLocal("k").Should().BeFalse(); + await node.Cache.TryGetAsync("k", Ct); + wrapper.Count(nameof(IMigrationCache.ReadSnapshotAsync)).Should().Be(reads + 2, "every routed read asks the library cache"); + + if (framed) + { + // The wall clock steps back and 5 s pass; the key has 5 s less on the server, whose clock did not step. + rig.Clock.StepUtc(TimeSpan.FromSeconds(-10)); + rig.Clock.Advance(TimeSpan.FromSeconds(5)); + await rig.ExpireAsync("k", Window - TimeSpan.FromSeconds(4)); + (await node.Cache.TryGetAsync("k", Ct)).Should().BeNull(); + } + + // Control: a cache that keeps bounds leaves a plain value in the router's tier. + await using var kept = TestNode.Create(new FakeBus(), rig.Clock, [], "frc" + rig.Prefix, library: rig.Path(rig.Redis)); + await rig.StorePlainAsync("c", "v", TimeSpan.FromMinutes(10)); + await kept.Cache.TryGetAsync("c", Ct); + kept.IsLocal("c").Should().BeTrue(); + } + + [Theory] + [MemberData(nameof(AskedAndChanged))] + public async Task A_library_cache_with_no_shared_tier_flags_a_value_from_a_shared_store(bool asked, bool change) + { + await using var rig = await FrameLibraryRig.CreateAsync(fixture, clock => new OneStore(new MemoryCacheFactory(clock, NullLoggerFactory.Instance))); + var reader = rig.Layered; + var library = rig.InMemory; + await using var node = TestNode.Create(new FakeBus(), rig.Clock, [], "frs" + rig.Prefix, library: rig.Path(library)); + await rig.StoreFrameAsync("k", "v", TimeSpan.FromMinutes(10), Window + TimeSpan.FromSeconds(10)); + var key = CacheKey.Verbatim(rig.RedisKey("k")); + if (asked) + { + FrameTiers.MayHaveMet(library).Should().BeFalse("nothing has landed in the shared store yet"); + } + + if (change) + { + await reader.GetAsync(key, null, Ct); + + var result = await ((ICache)node.Cache).SetIfChangedAsync("k", new Item("v"), EqualityComparer.Default, TimeSpan.FromMinutes(5), Ct); + + result.Outcome.Should().Be(ChangeOutcome.Unchanged); + node.IsLocal("k").Should().BeFalse(); + FrameTiers.MayHaveMet(library).Should().BeTrue(); + return; + } + + // The first cache reads the frame between the router's miss and its fill, so the observed entry lands in the shared store. + var served = await node.Cache.GetOrAddAsync( + "k", + async _ => + { + await reader.GetAsync(key, null, Ct); + return new Item("mine"); + }, + default, + Ct); + + served.Should().Be(new Item("v")); + node.IsLocal("k").Should().BeFalse(); + FrameTiers.MayHaveMet(library).Should().BeTrue(); + + // The monotonic clock passes the fresh bound: the library cache refuses the entry (HS6), and the read misses. + rig.Clock.Advance(TimeSpan.FromSeconds(11)); + (await node.Cache.TryGetAsync("k", Ct)).Should().BeNull(); + } + + private static async Task MeetFrameAsync(FrameLibraryRig rig, ICache cache) + { + await rig.StoreFrameAsync("w", "w", TimeSpan.FromHours(1), TimeSpan.FromHours(1) + Window); + var key = CacheKey.Verbatim(rig.RedisKey("w")); + await cache.GetAsync(key, null, Ct); + (await cache.TryFillAsync(key, new Item("x"), DateTimeOffset.MaxValue, null, Ct)).Outcome.Should().Be(FillOutcome.Existed); + } + + private static async Task PrepareAsync(KeyMoveKit kit, params string[] keys) + { + await kit.PrepareAsync(keys is [] ? ["k"] : keys); + await kit.SetStateAsync("S3"); + } + + private static string KeyOf(KeyMoveKit kit, Site site) => site == Site.SideSnapshot ? kit.L("k") : kit.N("k"); + + private static ValueTask SnapAsync(KeyMoveKit kit, Site site) => site switch + { + Site.SideSnapshot => new InPlaceMoveSide(kit.Plane, kit.Group, kit.L, FramedItemCache.Codec(), null, kit.Clock).SnapshotAsync("k", Ct), + _ => new KeyPromotion(kit.Client.Parts, new InPlaceMoveSide(kit.Plane, kit.Group, kit.L, FramedItemCache.Codec(), null, kit.Clock)) + .SnapAsync(kit.N("k"), replica: site == Site.ReplicaSnap, SchedulePointStep.ReadDestination, Ct), + }; + + // The read of each site as its caller judges it: the batch answer, or the interpreted snap. + private static async Task> JudgedReadAsync(KeyMoveKit kit, Site site, byte[] stored, TimeSpan ttl) + { + await kit.Db.StringSetAsync(KeyOf(kit, site), stored, ttl); + return site == Site.Batch + ? (await kit.Client.ReadManyAsync(["k"], Ct))["k"] + : KeyPromotion.Interpret(await SnapAsync(kit, site), FramedItemCache.Codec()); + } + + // A routed node over the road, the call that replaces what the key holds, and what to dispose. + private async Task<(TestNode Node, Func Replace, IAsyncDisposable Dispose)> RoadAsync(Road road, bool framed) + { + if (road is Road.LibraryRead or Road.LibraryFill) + { + var rig = await FrameLibraryRig.CreateAsync(fixture); + var node = TestNode.Create(new FakeBus(), rig.Clock, [], "frs" + rig.Prefix, library: rig.Path(rig.Redis)); + Task Store(string name) => framed ? rig.StoreFrameAsync("k", name, TimeSpan.FromHours(1), TimeSpan.FromMinutes(61)) : rig.StorePlainAsync("k", name, TimeSpan.FromMinutes(61)); + if (road == Road.LibraryRead) + { + await Store("v"); + } + else + { + await node.Cache.GetOrAddAsync( + "k", + async _ => + { + await Store("v"); + return new Item("mine"); + }, + default, + Ct); + } + + return (node, () => Store("w"), rig); + } + + var kit = await CreateAsync(); + await PrepareAsync(kit); + var now = kit.Clock.GetUtcNow(); + var key = road == Road.ServedRead ? kit.L("k") : kit.N("k"); + var routed = TestNode.Create(new FakeBus(), kit.Time.Manual, [], "frs" + kit.Unique, library: kit.Client); + Task Put(string name) => kit.Db.StringSetAsync(key, framed ? FramedItemCache.Windowed(name, now.AddHours(1), Window) : Encoding.UTF8.GetBytes(name), TimeSpan.FromMinutes(61)); + if (road == Road.MoveFill) + { + await routed.Cache.GetOrAddAsync( + "k", + async _ => + { + await Put("v"); + return new Item("mine"); + }, + default, + Ct); + } + else + { + await Put("v"); + } + + // A promoted value lands plain on the native key. + return (routed, () => kit.Db.StringSetAsync(kit.N("k"), "w"u8.ToArray(), TimeSpan.FromMinutes(5)), kit); + } + + private Task CreateAsync(Func? interceptDb = null) => + KeyMoveKit.CreateAsync(fixture, inPlace: FramedItemCache.Codec(), standard: FramedItemCache.Codec(), interceptDb: interceptDb); + + // Every layered cache that asks for a memory cache gets the same one. + private sealed class OneStore(IMemoryCacheFactory inner) : IMemoryCacheFactory + { + private IMemoryCache? _cache; + + public IMemoryCache Get(IMemoryCacheOptions memoryOptions) => _cache ??= inner.Get(memoryOptions); + } +} diff --git a/tests/UiPath.Caching.Migration.Tests/KeyPromotionFrameTests.cs b/tests/UiPath.Caching.Migration.Tests/KeyPromotionFrameTests.cs new file mode 100644 index 00000000..f387a59d --- /dev/null +++ b/tests/UiPath.Caching.Migration.Tests/KeyPromotionFrameTests.cs @@ -0,0 +1,214 @@ +using System.Text; +using StackExchange.Redis; +using UiPath.Caching.Migration.Tests.KeyMove; +using UiPath.Caching.Migration.Tests.Support; +using UiPath.Caching.Redis; + +namespace UiPath.Caching.Migration.Tests; + +// A framed value moves as a plain value with its logical life (L1 to L5): never the key's TTL, which holds the stale window too. +[Collection("RedisIntegration")] +[Trait("Category", "Integration")] +public sealed class KeyPromotionFrameTests(RedisFixture fixture) +{ + private static readonly TimeSpan Slack = TimeSpan.FromSeconds(5); + + public enum FramePath + { + Direct, + Batch, + Forward, + Reverse, + } + + public static TheoryData EachPath => [.. from flag in new[] { false, true } from path in Enum.GetValues() select (flag, path)]; + + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + [Fact] + public async Task A_forward_promotion_publishes_the_logical_life_not_the_key_ttl() + { + await using var kit = await CreateAsync(); + var now = kit.Clock.GetUtcNow(); + + var (read, target) = await ReadAsync(kit, FramePath.Forward, FramedItemCache.Windowed("v1", now.AddMinutes(1), TimeSpan.FromHours(1)), TimeSpan.FromMinutes(61)); + + read.Value.Should().Be(new Item("v1")); + await ShouldHoldPlainAsync(kit, target, "v1", TimeSpan.FromMinutes(1)); + (await kit.ExistsAsync(kit.L("k"))).Should().BeFalse(); + } + + [Fact] + public async Task A_reverse_promotion_does_the_same() + { + await using var kit = await CreateAsync(); + var now = kit.Clock.GetUtcNow(); + + var (read, target) = await ReadAsync(kit, FramePath.Reverse, FramedItemCache.Windowed("v1", now.AddMinutes(1), TimeSpan.FromHours(1)), TimeSpan.FromMinutes(61)); + + read.Value.Should().Be(new Item("v1")); + await ShouldHoldPlainAsync(kit, target, "v1", TimeSpan.FromMinutes(1)); + (await kit.ExistsAsync(kit.N("k"))).Should().BeFalse(); + } + + [Theory] + [InlineData(FramePath.Forward)] + [InlineData(FramePath.Reverse)] + public async Task An_expired_frame_is_not_promoted(FramePath path) + { + await using var kit = await CreateAsync(); + var now = kit.Clock.GetUtcNow(); + + var (read, target) = await ReadAsync(kit, path, FramedItemCache.Windowed("v1", now.AddSeconds(-1), TimeSpan.FromMinutes(10)), TimeSpan.FromMinutes(50)); + + read.Kind.Should().Be(ReadOutcome.Absent, "an expired source is a miss"); + read.Value.Should().BeNull(); + (await kit.ExistsAsync(target)).Should().BeFalse(); + } + + [Fact] + public async Task A_promoted_value_is_served_until_its_logical_deadline() + { + await using var kit = await CreateAsync(); + var now = kit.Clock.GetUtcNow(); + + var (read, target) = await ReadAsync(kit, FramePath.Forward, FramedItemCache.Windowed("v1", now.AddMinutes(1), TimeSpan.FromHours(1)), TimeSpan.FromMinutes(61)); + + read.Expiration!.Value.Should().BeCloseTo(now.AddMinutes(1), Slack); + read.Expiration.Value.Should().BeOnOrBefore(now.AddMinutes(1)); + read.Uncached.Should().BeTrue("a value out of a windowed frame is served for the router to keep no copy of"); + await ShouldHoldPlainAsync(kit, target, "v1", TimeSpan.FromMinutes(1)); + + // The target key ends at the moved deadline, so a read after it is a miss. + var ends = await kit.Db.KeyExpireTimeAsync(target); + ends!.Value.Should().BeCloseTo(read.Expiration.Value.UtcDateTime, Slack); + } + + [Theory] + [InlineData(FramePath.Forward)] + [InlineData(FramePath.Reverse)] + public async Task A_framed_null_promotes_as_a_cached_null(FramePath path) + { + await using var kit = await CreateAsync(); + var now = kit.Clock.GetUtcNow(); + + var (read, target) = await ReadAsync(kit, path, EntryFrame.Write([], now.AddMinutes(1), TimeSpan.FromHours(1), null), TimeSpan.FromMinutes(61)); + + read.Kind.Should().Be(ReadOutcome.Absent); + if (path == FramePath.Reverse) + { + (await kit.ExistsAsync(target)).Should().BeFalse("a reverse read promotes no cached null, framed or plain"); + return; + } + + ((byte[]?)await kit.Db.StringGetAsync(target)).Should().BeEmpty("the target caches nulls as the empty value"); + (await kit.Db.KeyTimeToLiveAsync(target))!.Value.Should().BeCloseTo(TimeSpan.FromMinutes(1), Slack); + } + + [Fact] + public async Task A_batch_read_takes_the_logical_life() + { + await using var kit = await CreateAsync(); + var now = kit.Clock.GetUtcNow(); + + var (read, _) = await ReadAsync(kit, FramePath.Batch, FramedItemCache.Windowed("v1", now.AddMinutes(1), TimeSpan.FromHours(1)), TimeSpan.FromMinutes(61)); + + read.Value.Should().Be(new Item("v1")); + read.Expiration!.Value.Should().BeCloseTo(now.AddMinutes(1), Slack); + } + + [Theory] + [InlineData(FramePath.Forward)] + [InlineData(FramePath.Reverse)] + public async Task A_plain_value_promotes_with_the_key_ttl_as_before(FramePath path) + { + await using var kit = await CreateAsync(); + + var (read, target) = await ReadAsync(kit, path, "v1"u8.ToArray(), TimeSpan.FromMinutes(10)); + + read.Value.Should().Be(new Item("v1")); + await ShouldHoldPlainAsync(kit, target, "v1", TimeSpan.FromMinutes(10)); + } + + [Theory] + [MemberData(nameof(EachPath))] + public async Task A_persistent_value_promotes_with_no_expiry(bool framed, FramePath path) + { + await using var kit = await CreateAsync(); + var stored = framed ? FramedItemCache.Validated("v1") : "v1"u8.ToArray(); + + var (read, target) = await ReadAsync(kit, path, stored, null); + + read.Value.Should().Be(new Item("v1")); + read.Expiration.Should().BeNull(); + (await kit.Db.KeyTimeToLiveAsync(target)).Should().BeNull(); + if (path is FramePath.Forward or FramePath.Reverse) + { + ((byte[]?)await kit.Db.StringGetAsync(target)).Should().Equal("v1"u8.ToArray()); + } + } + + [Theory] + [MemberData(nameof(EachPath))] + public async Task A_windowed_frame_on_a_key_without_ttl_is_not_promoted(bool neverExpires, FramePath path) + { + await using var kit = await CreateAsync(); + var expiration = neverExpires ? DateTimeOffset.MaxValue : kit.Clock.GetUtcNow().AddHours(1); + + var (read, target) = await ReadAsync(kit, path, FramedItemCache.Windowed("v1", expiration, TimeSpan.FromMinutes(1)), null); + + read.Kind.Should().Be(ReadOutcome.Absent, "a windowed frame on a key with no TTL is never fresh (FR4, P1)"); + if (path is FramePath.Forward or FramePath.Reverse) + { + (await kit.ExistsAsync(target)).Should().BeFalse(); + } + } + + [Theory] + [InlineData(FramePath.Direct)] + [InlineData(FramePath.Batch)] + [InlineData(FramePath.Forward)] + [InlineData(FramePath.Reverse)] + public async Task A_frame_that_never_expires_on_a_key_with_a_ttl_moves_with_the_ttl_less_the_window(FramePath path) + { + await using var kit = await CreateAsync(); + var now = kit.Clock.GetUtcNow(); + + var (read, target) = await ReadAsync(kit, path, FramedItemCache.Windowed("v1", DateTimeOffset.MaxValue, TimeSpan.FromSeconds(60)), TimeSpan.FromSeconds(70)); + + read.Value.Should().Be(new Item("v1")); + read.Expiration!.Value.Should().BeCloseTo(now.AddSeconds(10), Slack); + read.Expiration.Value.Should().BeOnOrBefore(now.AddSeconds(10)); + if (path is FramePath.Forward or FramePath.Reverse) + { + await ShouldHoldPlainAsync(kit, target, "v1", TimeSpan.FromSeconds(10)); + } + } + + internal static async Task<(PathRead Read, string Target)> ReadAsync(KeyMoveKit kit, FramePath path, byte[] stored, TimeSpan? ttl) + { + await kit.PrepareAsync("k"); + await kit.SetStateAsync("S3", direction: path == FramePath.Reverse ? "rev" : "fwd"); + var holder = path == FramePath.Forward ? kit.L("k") : kit.N("k"); + await (ttl is { } life ? kit.Db.StringSetAsync(holder, stored, life) : kit.Db.StringSetAsync(holder, stored)); + var read = path == FramePath.Batch ? (await kit.Client.ReadManyAsync(["k"], Ct))["k"] : await kit.Client.ReadAsync("k", Ct); + var target = path switch + { + FramePath.Forward => kit.N("k"), + FramePath.Reverse => kit.L("k"), + _ => holder, + }; + return (read, target); + } + + private static async Task ShouldHoldPlainAsync(KeyMoveKit kit, string target, string name, TimeSpan life) + { + ((byte[]?)await kit.Db.StringGetAsync(target)).Should().Equal(Encoding.UTF8.GetBytes(name), "the target value is encoded plain"); + var left = await kit.Db.KeyTimeToLiveAsync(target); + left!.Value.Should().BeCloseTo(life, Slack); + left.Value.Should().BeLessThanOrEqualTo(life); + } + + private Task CreateAsync(Func? interceptDb = null) => + KeyMoveKit.CreateAsync(fixture, inPlace: FramedItemCache.Codec(), standard: FramedItemCache.Codec(), interceptDb: interceptDb); +} diff --git a/tests/UiPath.Caching.Migration.Tests/LibraryKeyMoveCodecFrameTests.cs b/tests/UiPath.Caching.Migration.Tests/LibraryKeyMoveCodecFrameTests.cs new file mode 100644 index 00000000..a8722b52 --- /dev/null +++ b/tests/UiPath.Caching.Migration.Tests/LibraryKeyMoveCodecFrameTests.cs @@ -0,0 +1,65 @@ +using UiPath.Caching.Migration.Tests.KeyMove; +using UiPath.Caching.Migration.Tests.Support; + +namespace UiPath.Caching.Migration.Tests; + +// The library codec of a key move unframes first, then decodes the inner value as it decodes a plain one. +public sealed class LibraryKeyMoveCodecFrameTests +{ + private static readonly DateTimeOffset Expiration = new(2030, 1, 1, 0, 0, 0, TimeSpan.Zero); + + [Fact] + public void A_framed_value_decodes_with_its_expiration_and_window() + { + var decoded = FramedItemCache.Codec().Decode(FramedItemCache.Windowed("v1", Expiration, TimeSpan.FromHours(1))); + + decoded.Class.Should().Be(DecodeClass.Ok); + decoded.Value.Should().Be(new Item("v1")); + decoded.ExpiresAt.Should().Be(Expiration); + decoded.StaleWindow.Should().Be(TimeSpan.FromHours(1)); + } + + [Fact] + public void A_frame_that_never_expires_decodes_with_the_largest_expiration() + { + var decoded = FramedItemCache.Codec().Decode(FramedItemCache.Windowed("v1", DateTimeOffset.MaxValue, TimeSpan.FromMinutes(1))); + + decoded.ExpiresAt.Should().Be(DateTimeOffset.MaxValue); + decoded.StaleWindow.Should().Be(TimeSpan.FromMinutes(1)); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void A_framed_cached_null_decodes_as_Null(bool windowed) + { + var bytes = windowed + ? Redis.EntryFrame.Write([], Expiration, TimeSpan.FromMinutes(1), null) + : Redis.EntryFrame.Write([], DateTimeOffset.MaxValue, TimeSpan.Zero, EntryValidators.From("v1", null)); + + var decoded = FramedItemCache.Codec().Decode(bytes); + + decoded.Class.Should().Be(DecodeClass.Null); + decoded.Value.Should().BeNull(); + decoded.StaleWindow.Should().Be(windowed ? TimeSpan.FromMinutes(1) : null); + } + + [Fact] + public void A_frame_without_a_window_decodes_without_an_expiration() + { + var decoded = FramedItemCache.Codec().Decode(FramedItemCache.Validated("v1")); + + decoded.Class.Should().Be(DecodeClass.Ok); + decoded.Value.Should().Be(new Item("v1")); + decoded.ExpiresAt.Should().BeNull(); + decoded.StaleWindow.Should().BeNull(); + } + + [Fact] + public void A_plain_value_decodes_as_before() + { + var decoded = FramedItemCache.Codec().Decode("v1"u8.ToArray()); + + decoded.Should().Be(Decoded.Of(new Item("v1"))); + } +} diff --git a/tests/UiPath.Caching.Migration.Tests/MovedLifeTests.cs b/tests/UiPath.Caching.Migration.Tests/MovedLifeTests.cs new file mode 100644 index 00000000..0e4a0b45 --- /dev/null +++ b/tests/UiPath.Caching.Migration.Tests/MovedLifeTests.cs @@ -0,0 +1,54 @@ +using UiPath.Caching.Migration.Tests.Support; + +namespace UiPath.Caching.Migration.Tests; + +// L1 to L5: the life a moved value may have, from the key's TTL and the frame of the value. +public sealed class MovedLifeTests +{ + private static readonly DateTimeOffset At = new(2030, 1, 1, 0, 0, 0, TimeSpan.Zero); + + public static TheoryData Cases => new() + { + // case, key TTL (ms), frame expiration after At (ms; null: never), window (s; null: no window), expired, TTL (ms) + { "L1 plain with a TTL", 5_000, null, null, false, 5_000 }, + { "L1 plain without a TTL", -1, null, null, false, -1 }, + { "L2 never on a key without a TTL", -1, null, 60, true, 0 }, + { "L3 never on a key with a TTL", 70_000, null, 60, false, 10_000 }, + { "L3 at 1 ms", 60_001, null, 60, false, 1 }, + { "L3 below 1 ms", 60_000, null, 60, true, 0 }, + { "L4 finite on a key without a TTL", -1, 30_000, 60, true, 0 }, + { "L5 the frame ends first", 3_660_000, 60_000, 3_600, false, 60_000 }, + { "L5 the key ends first", 70_000, 3_600_000, 60, false, 10_000 }, + { "L5 at 1 ms", 3_660_000, 1, 3_600, false, 1 }, + { "L5 below 1 ms", 3_660_000, 0, 3_600, true, 0 }, + { "L5 past", 3_660_000, -5_000, 3_600, true, 0 }, + }; + + [Theory] + [MemberData(nameof(Cases))] + public void Each_case_gives_its_life(string name, long keyTtlMs, long? expiresAfterMs, int? windowSeconds, bool expired, long ttlMs) + { + var decoded = Decoded.Of(new Item(name)) with + { + ExpiresAt = windowSeconds is null ? null : expiresAfterMs is { } after ? At.AddMilliseconds(after) : DateTimeOffset.MaxValue, + StaleWindow = windowSeconds is { } seconds ? TimeSpan.FromSeconds(seconds) : null, + }; + + var life = MovedLife.Of(keyTtlMs, At, decoded); + + life.Expired.Should().Be(expired); + if (!expired) + { + life.TtlMs.Should().Be(ttlMs); + } + } + + [Fact] + public void A_frame_without_a_window_keeps_the_key_ttl() + { + var decoded = Decoded.Of(new Item("v")) with { ExpiresAt = null, StaleWindow = null }; + + MovedLife.Of(-1, At, decoded).Should().Be(new MovedLife(false, -1)); + MovedLife.Of(42, At, decoded).Should().Be(new MovedLife(false, 42)); + } +} diff --git a/tests/UiPath.Caching.Migration.Tests/Support/FakeMigrationCache.cs b/tests/UiPath.Caching.Migration.Tests/Support/FakeMigrationCache.cs index 3bf3d9c4..cf018746 100644 --- a/tests/UiPath.Caching.Migration.Tests/Support/FakeMigrationCache.cs +++ b/tests/UiPath.Caching.Migration.Tests/Support/FakeMigrationCache.cs @@ -30,11 +30,16 @@ internal sealed class FakeConnection : IConnectionState #pragma warning restore CS0067 /// The library cache as a script: a read answers a value, a or nothing (absent), and a write answers a . -internal sealed class FakeMigrationCache(TimeProvider? clock = null) : IMigrationCache +internal sealed class FakeMigrationCache(TimeProvider? clock = null) : IMigrationCache, IFrameTier { /// Returned by for a key that holds a cached null. public static readonly object StoredNull = new(); + /// The double stands for a Redis tier that has met no windowed frame and keeps bounds. + public bool MetWindowedFrame => false; + + public bool KeepsBounds => true; + public Func> Read { get; set; } = (_, _) => Task.FromResult(null); public Func> Write { get; set; } = (_, _) => Task.FromResult(StoreOutcome.Committed); diff --git a/tests/UiPath.Caching.Migration.Tests/Support/ManualTimeProvider.cs b/tests/UiPath.Caching.Migration.Tests/Support/ManualTimeProvider.cs index 494f0f2c..5060f994 100644 --- a/tests/UiPath.Caching.Migration.Tests/Support/ManualTimeProvider.cs +++ b/tests/UiPath.Caching.Migration.Tests/Support/ManualTimeProvider.cs @@ -61,6 +61,9 @@ public void JumpWall(TimeSpan by) } } + /// Moves the UTC clock alone, forward or back: the timestamp stays and no timer fires. + public void StepUtc(TimeSpan by) => JumpWall(by); + public override long GetTimestamp() { lock (_gate) diff --git a/tests/UiPath.Caching.Tests/Config/ValueSerializerRegistrationTests.cs b/tests/UiPath.Caching.Tests/Config/ValueSerializerRegistrationTests.cs index d8e284ed..d29f1db1 100644 --- a/tests/UiPath.Caching.Tests/Config/ValueSerializerRegistrationTests.cs +++ b/tests/UiPath.Caching.Tests/Config/ValueSerializerRegistrationTests.cs @@ -10,6 +10,25 @@ public class ValueSerializerRegistrationTests { private static readonly Func Factory = _ => new FakeValueSerializer(0x10); + [Fact] + public void The_frame_id_is_refused_for_a_value_serializer() + { + var (builder, services) = Create(); + var before = services.Count; + + var act = () => builder.AddValueSerializer("frame", [0x0E], _ => new FakeValueSerializer(0x0E)); + + act.Should().Throw().WithParameterName("formatIds") + .WithMessage("*0x0E is reserved for the entry frame*"); + services.Count.Should().Be(before); + } + + [Fact] + public void The_frame_id_is_still_an_event_id() + { + FormatIdRules.IsEventId(0x0E).Should().BeTrue(); + } + [Theory] [InlineData(0x00), InlineData(0x09), InlineData(0x0A), InlineData(0x0D), InlineData(0x1F), InlineData(0x20), InlineData(0x200), InlineData(-1)] public void An_id_outside_the_allowed_ranges_is_refused(int id) diff --git a/tests/UiPath.Caching.Tests/Fakes/AdoptionProxy.cs b/tests/UiPath.Caching.Tests/Fakes/AdoptionProxy.cs index df2341c8..fd5f594d 100644 --- a/tests/UiPath.Caching.Tests/Fakes/AdoptionProxy.cs +++ b/tests/UiPath.Caching.Tests/Fakes/AdoptionProxy.cs @@ -7,10 +7,15 @@ namespace UiPath.Caching.Tests.Fakes; /// An inner cache, as a proxy, that also offers a snapshot read for adoption. /// Over a target it forwards every call, and answers a read for adoption with the target's own read; otherwise and answer. /// -internal abstract class AdoptionProxyBase : DispatchProxy +internal abstract class AdoptionProxyBase : DispatchProxy, IFrameTier { private readonly List _calls = []; + /// Stands for a Redis tier: it has met no windowed frame and keeps bounds. + public bool MetWindowedFrame => false; + + public bool KeepsBounds => true; + /// The cache that answers every call, when the proxy only adds the snapshot read to it. public object? Target { get; set; } diff --git a/tests/UiPath.Caching.Tests/Fakes/CachePeers.cs b/tests/UiPath.Caching.Tests/Fakes/CachePeers.cs index b73c2077..f3ae8af4 100644 --- a/tests/UiPath.Caching.Tests/Fakes/CachePeers.cs +++ b/tests/UiPath.Caching.Tests/Fakes/CachePeers.cs @@ -30,10 +30,12 @@ internal sealed class CachePeers(TimeProvider? defaultClock = null) : IDisposabl /// The cache's clock; a manual clock when null. /// The local tier's clock; the cache's clock when null. - public Node Add(string name, InMemoryRedisCacheOptions? options = null, RecordingTelemetryProvider? telemetry = null, TimeProvider? clock = null, TimeProvider? localClock = null, ICachePolicyFactory? policies = null) + /// Wraps the node's change token factory, as a custom factory would. + /// False builds the node over no inner tier, as the InMemory provider does: the bus is all it shares. + public Node Add(string name, InMemoryRedisCacheOptions? options = null, RecordingTelemetryProvider? telemetry = null, TimeProvider? clock = null, TimeProvider? localClock = null, ICachePolicyFactory? policies = null, Func? tokens = null, bool shared = true) { clock ??= defaultClock ?? new ManualTimeProvider(localClock?.GetUtcNow() ?? DateTimeOffset.UnixEpoch); - var node = new Node(this, name, options ?? new InMemoryRedisCacheOptions(), telemetry, clock, localClock ?? defaultClock ?? clock, policies); + var node = new Node(this, name, options ?? new InMemoryRedisCacheOptions(), telemetry, clock, localClock ?? defaultClock ?? clock, policies, tokens, shared); _nodes.Add(node); return node; } @@ -130,7 +132,7 @@ internal sealed class Node : IDisposable private readonly RecordingTelemetryProvider _telemetry; private int _evicted; - public Node(CachePeers peers, string name, InMemoryRedisCacheOptions options, RecordingTelemetryProvider? telemetry, TimeProvider clock, TimeProvider localClock, ICachePolicyFactory? policies = null) + public Node(CachePeers peers, string name, InMemoryRedisCacheOptions options, RecordingTelemetryProvider? telemetry, TimeProvider clock, TimeProvider localClock, ICachePolicyFactory? policies = null, Func? customTokens = null, bool shared = true) { Name = name; _telemetry = telemetry ?? new RecordingTelemetryProvider(); @@ -142,7 +144,8 @@ public Node(CachePeers peers, string name, InMemoryRedisCacheOptions options, Re Inner.Fenced = peers.Fenced; var events = new CacheEventFactory(Options.Create(cacheOptions)); - var tokens = new ChangeTokenFactory(Options.Create(cacheOptions), new SystemJsonByteSerializerProxy(), NullLoggerFactory.Instance, Substitute.For()); + IChangeTokenFactory tokens = new ChangeTokenFactory(Options.Create(cacheOptions), new SystemJsonByteSerializerProxy(), NullLoggerFactory.Instance, Substitute.For()); + tokens = customTokens?.Invoke(tokens) ?? tokens; Topic = new NodeTopic(this, peers); var provider = Substitute.For(); provider.Enabled.Returns(true); @@ -150,8 +153,8 @@ public Node(CachePeers peers, string name, InMemoryRedisCacheOptions options, Re var topics = Substitute.For(); topics.Get(Arg.Any()).Returns(provider); Cache = RunTables.Track(new MultilayerCache( - KnownCacheProviderNames.InMemoryRedis, - inner, + shared ? KnownCacheProviderNames.InMemoryRedis : KnownCacheProviderNames.InMemory, + shared ? inner : NullCache.Instance, new KeptMemoryCacheFactory(this, localClock), tokens, topics, @@ -391,7 +394,7 @@ public void Dispose() } /// The inner tier of a node over the shared store: counts its reads, can hold or fail them, and reports a connection state the test sets. - internal class NodeInner : DispatchProxy, IConnectionState, ISharedTier, IMigrationCache, IStampedTier, IFillManyTier, IFencedFillTier + internal class NodeInner : DispatchProxy, IConnectionState, ISharedTier, IMigrationCache, IStampedTier, IFillManyTier, IFencedFillTier, IFrameTier { private static readonly MethodInfo ReadOne = typeof(NodeInner).GetMethod(nameof(ReadOneAsync), BindingFlags.Instance | BindingFlags.NonPublic)!; private static readonly MethodInfo ReadMany = typeof(NodeInner).GetMethod(nameof(ReadManyAsync), BindingFlags.Instance | BindingFlags.NonPublic)!; @@ -477,6 +480,9 @@ public Task? AfterNextRead } #pragma warning restore S2292 + /// Answers with the key and expiration it was asked; unset, the call is not supported. + public Func>? OnRefresh { get; set; } + /// What and answer, once they have applied a committed one to the store. public StoreOutcome MigrationOutcome { get; set; } = StoreOutcome.Committed; @@ -495,6 +501,11 @@ public Task? AfterNextRead /// How many times the connection state was read. public int ConnectedReads => Volatile.Read(ref _connectedReads); + /// Stands for a Redis tier: it has met no windowed frame and keeps bounds. + public bool MetWindowedFrame => false; + + public bool KeepsBounds => true; + public bool IsConnected { get @@ -651,6 +662,8 @@ IDisposable ISharedTier.DemandMaster() case nameof(ICache.SetAsync): WriteMany.MakeGenericMethod(targetMethod.GetGenericArguments()).Invoke(null, [Store, args[0]]); return new ValueTask(true); + case nameof(ICache.RefreshAsync) when OnRefresh is { } refresh && args![1] is DateTimeOffset expiration: + return new ValueTask(refresh((CacheKey)args[0]!, expiration)); case nameof(ICache.RemoveAsync) when args![0] is CacheKey key: return RemoveAfter([key]); case nameof(ICache.RemoveAsync): diff --git a/tests/UiPath.Caching.Tests/Fakes/ObservedFakes.cs b/tests/UiPath.Caching.Tests/Fakes/ObservedFakes.cs new file mode 100644 index 00000000..57777d19 --- /dev/null +++ b/tests/UiPath.Caching.Tests/Fakes/ObservedFakes.cs @@ -0,0 +1,416 @@ +using System.Collections.Concurrent; +using System.Reflection; +using Microsoft.Extensions.Caching.Memory; +using Microsoft.Extensions.Logging.Abstractions; +using Microsoft.Extensions.Primitives; + +namespace UiPath.Caching.Tests.Fakes; + +/// A store the test can reach, to write beside the cache. +internal interface IHeldStore +{ + IMemoryCache Store { get; } +} + +/// A clock over a that counts its timestamp readings and can hold the next caller inside until the test lets it go. +internal sealed class CallClock(ManualTimeProvider time) : TimeProvider +{ + private readonly ManualResetEventSlim _release = new(true); + private TaskCompletionSource _entered = new(TaskCreationOptions.RunContinuationsAsynchronously); + private int _armed; + private int _calls; + + public ManualTimeProvider Time => time; + + /// How many timestamp readings were made. + public int Calls => Volatile.Read(ref _calls); + + /// Completes when a caller is held. + public Task Entered => Volatile.Read(ref _entered).Task; + + public override long TimestampFrequency => time.TimestampFrequency; + + public override DateTimeOffset GetUtcNow() => time.GetUtcNow(); + + public override ITimer CreateTimer(TimerCallback callback, object? state, TimeSpan dueTime, TimeSpan period) => time.CreateTimer(callback, state, dueTime, period); + + public override long GetTimestamp() + { + Interlocked.Increment(ref _calls); + if (Interlocked.CompareExchange(ref _armed, 0, 1) == 1) + { + Volatile.Read(ref _entered).TrySetResult(); + _release.Wait(TestContext.Current.CancellationToken); + } + + return time.GetTimestamp(); + } + + /// Holds the next timestamp reading, whichever thread makes it. + public void Hold() + { + _release.Reset(); + Volatile.Write(ref _entered, new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously)); + Volatile.Write(ref _armed, 1); + } + + /// Lets the held caller go. + public void Let() + { + Volatile.Write(ref _armed, 0); + _release.Set(); + } + + public void ResetCalls() => Interlocked.Exchange(ref _calls, 0); +} + +/// A plain , which a span lookup can use, that the test can reach. +internal sealed class OpenMemoryCacheFactory(TimeProvider clock) : IMemoryCacheFactory, IHeldStore +{ + public IMemoryCache Store { get; private set; } = null!; + + public IMemoryCache Get(IMemoryCacheOptions memoryOptions) => + Store ??= new MemoryCacheFactory(clock, NullLoggerFactory.Instance).Get(memoryOptions); +} + +/// A real that tells the test every eviction: the value, and why it left. +internal sealed class LoggedMemoryCacheFactory(TimeProvider clock) : IMemoryCacheFactory, IHeldStore +{ + private readonly object _gate = new(); + private readonly List<(object? Value, EvictionReason Reason)> _evictions = []; + + public AsyncTestSignal Changes { get; } = new(); + + public IMemoryCache Store { get; private set; } = null!; + + public IReadOnlyList<(object? Value, EvictionReason Reason)> Evictions + { + get + { + lock (_gate) + { + return [.. _evictions]; + } + } + } + + public IMemoryCache Get(IMemoryCacheOptions memoryOptions) => + Store ??= new Logged(new MemoryCacheFactory(clock, NullLoggerFactory.Instance).Get(memoryOptions), this); + + private void Left(object? value, EvictionReason reason) + { + lock (_gate) + { + _evictions.Add((value, reason)); + } + + Changes.Pulse(); + } + + private sealed class Logged(IMemoryCache inner, LoggedMemoryCacheFactory owner) : IMemoryCache + { + public Microsoft.Extensions.Caching.Memory.ICacheEntry CreateEntry(object key) => new LoggedEntry(inner.CreateEntry(key), owner); + + public void Remove(object key) => inner.Remove(key); + + public bool TryGetValue(object key, out object? value) => inner.TryGetValue(key, out value); + + public void Dispose() => inner.Dispose(); + } + + /// Registers the log as the last eviction callback, so the cache's own callbacks have run when the log shows the leaving. + private sealed class LoggedEntry(Microsoft.Extensions.Caching.Memory.ICacheEntry inner, LoggedMemoryCacheFactory owner) : Microsoft.Extensions.Caching.Memory.ICacheEntry + { + public object Key => inner.Key; + + public object? Value + { + get => inner.Value; + set => inner.Value = value; + } + + public DateTimeOffset? AbsoluteExpiration + { + get => inner.AbsoluteExpiration; + set => inner.AbsoluteExpiration = value; + } + + public TimeSpan? AbsoluteExpirationRelativeToNow + { + get => inner.AbsoluteExpirationRelativeToNow; + set => inner.AbsoluteExpirationRelativeToNow = value; + } + + public TimeSpan? SlidingExpiration + { + get => inner.SlidingExpiration; + set => inner.SlidingExpiration = value; + } + + public IList ExpirationTokens => inner.ExpirationTokens; + + public IList PostEvictionCallbacks => inner.PostEvictionCallbacks; + + public CacheItemPriority Priority + { + get => inner.Priority; + set => inner.Priority = value; + } + + public long? Size + { + get => inner.Size; + set => inner.Size = value; + } + + public void Dispose() + { + inner.RegisterPostEvictionCallback(static (_, value, reason, state) => ((LoggedMemoryCacheFactory)state!).Left(value, reason), owner); + inner.Dispose(); + } + } +} + +/// A store that asks no token and expires nothing: it holds what it was given until a removal names the key. +internal sealed class PlainMemoryCacheFactory : IMemoryCacheFactory, IHeldStore +{ + public PlainMemoryCache Store { get; } = new(); + + IMemoryCache IHeldStore.Store => Store; + + public IMemoryCache Get(IMemoryCacheOptions memoryOptions) => Store; +} + +/// The store of . +internal sealed class PlainMemoryCache : IMemoryCache +{ + private readonly ConcurrentDictionary _values = new(); + private readonly ConcurrentQueue _removed = new(); + private readonly ConcurrentDictionary _tokens = new(); + private int _hidden; + + /// The keys a removal was sent for, in order. + public IReadOnlyCollection Removed => _removed; + + /// Puts a value under a key, as another cache on the store would. + public void Put(object key, object? value) => _values[key] = value; + + /// How many expiration tokens the entry committed under held. + public int TokensOf(object key) => _tokens[key]; + + public Microsoft.Extensions.Caching.Memory.ICacheEntry CreateEntry(object key) => new Entry(this, key); + + public void Remove(object key) + { + _removed.Enqueue(key); + _values.TryRemove(key, out _); + } + + public bool TryGetValue(object key, out object? value) + { + if (Volatile.Read(ref _hidden) > 0 && Interlocked.Decrement(ref _hidden) >= 0) + { + value = null; + return false; + } + + return _values.TryGetValue(key, out value); + } + + /// Answers that the next lookups find nothing, whatever the store holds. + public void HideFor(int lookups) => Volatile.Write(ref _hidden, lookups); + + public void Dispose() + { + } + + private sealed class Entry(PlainMemoryCache owner, object key) : Microsoft.Extensions.Caching.Memory.ICacheEntry + { + public object Key => key; + + public object? Value { get; set; } + + public DateTimeOffset? AbsoluteExpiration { get; set; } + + public TimeSpan? AbsoluteExpirationRelativeToNow { get; set; } + + public TimeSpan? SlidingExpiration { get; set; } + + public IList ExpirationTokens { get; } = []; + + public IList PostEvictionCallbacks { get; } = []; + + public CacheItemPriority Priority { get; set; } + + public long? Size { get; set; } + + public void Dispose() + { + owner._tokens[key] = ExpirationTokens.Count; + owner._values[key] = Value; + } + } +} + +/// An inner tier that implements no interface of the library's own, counts every call by member and answers a miss, or the entry the test holds out for it. +internal class TierDouble : DispatchProxy +{ + private readonly ConcurrentQueue _calls = new(); + + /// The entry a read answers; a miss when null. Its value must be of the type the read asks for. + public ICacheEntry? Held { get; set; } + + /// Runs on each call, with the member's name, before the tier answers. + public Action? OnCall { get; set; } + + /// The members called, in order. + public IReadOnlyCollection Calls => _calls; + + public int Total => _calls.Count; + + /// The tier as an , and the object that counts. + public static (T Cache, TProxy Tier) Make() + where T : class + where TProxy : TierDouble + { + var proxy = Create(); + return (proxy, (TProxy)(object)proxy); + } + + public int Count(string member) => _calls.Count(call => call == member); + + protected override object? Invoke(MethodInfo? targetMethod, object?[]? args) + { + var method = targetMethod!; + _calls.Enqueue(method.Name); + OnCall?.Invoke(method.Name); + if (method.Name is "get_Name") + { + return "Tier"; + } + + if (method.ReturnType == typeof(void)) + { + return null; + } + + if (method.ReturnType == typeof(ValueTask)) + { + return new ValueTask(method.Name is not nameof(ICache.ContainsAsync)); + } + + var result = method.ReturnType.GetGenericArguments()[0]; + var answer = method.Name is nameof(IHashCache.GetMetadataAsync) ? null : Miss(result, args!); + // By the constructor that takes the result: a null answer matches the task and source constructors too. + return typeof(ValueTask<>).MakeGenericType(result).GetConstructor([result])!.Invoke([answer]); + } + + private static object Absent(Type entry) => + Activator.CreateInstance(typeof(TestCacheEntry<>).MakeGenericType(entry.GetGenericArguments()[0]))!; + + private object? Miss(Type result, object?[] args) + { + if (result.IsGenericType && result.GetGenericTypeDefinition() == typeof(ICacheEntry<>)) + { + return Held is { } held && result.IsInstanceOfType(held) ? held : Absent(result); + } + + if (result.IsArray && result.GetElementType() is { IsGenericType: true } pair && pair.GetGenericTypeDefinition() == typeof(KeyValuePair<,>)) + { + var keys = (CacheKey[])args[0]!; + var values = Array.CreateInstance(pair, keys.Length); + var valueType = pair.GetGenericArguments()[1]; + for (var i = 0; i < keys.Length; i++) + { + var answer = valueType.IsGenericType && valueType.GetGenericTypeDefinition() == typeof(ICacheEntry<>) ? Miss(valueType, args) : null; + values.SetValue(Activator.CreateInstance(pair, keys[i], answer), i); + } + + return values; + } + + if (result.IsGenericType && result.GetGenericTypeDefinition() == typeof(IDictionary<,>) && result.GetGenericArguments()[0] == typeof(string)) + { + return Activator.CreateInstance(typeof(Dictionary<,>).MakeGenericType(result.GetGenericArguments())); + } + + return result.IsValueType ? Activator.CreateInstance(result) : null; + } +} + +/// A that implements the library's frame-tier interface. +internal class FrameTierDouble : TierDouble, IFrameTier +{ + public bool MetWindowedFrame { get; set; } + + public bool KeepsBounds { get; set; } = true; + + /// The tier as an , and the object that counts. + public static (ICache Cache, FrameTierDouble Tier) ForCache(bool keepsBounds = true) + { + var (cache, tier) = Make(); + tier.KeepsBounds = keepsBounds; + return (cache, tier); + } + + /// The tier as an , and the object that counts. + public static (IHashCache Cache, FrameTierDouble Tier) ForHashCache(bool keepsBounds = true) + { + var (cache, tier) = Make(); + tier.KeepsBounds = keepsBounds; + return (cache, tier); + } +} + +/// A string layered cache with no peers over a , on a clock a test moves; the cache adopts the observed entries the tier is told to hand up. +internal sealed class ObservedHarness : IDisposable +{ + public const string Key = "k"; + + private static readonly DateTimeOffset Start = new(2026, 1, 1, 0, 0, 0, TimeSpan.Zero); + + public ObservedHarness(Func? memory = null, IChangeTokenFactory? tokens = null, bool keepsBounds = true, bool shared = true) + { + Time = new ManualTimeProvider(Start); + Clock = new CallClock(Time); + (Inner, Tier) = FrameTierDouble.ForCache(keepsBounds); + Memory = memory?.Invoke(Clock); + Cache = InMemoryMultilayer.Cache(inner: shared ? Inner : null, clock: Clock, memory: Memory, tokens: tokens); + } + + public ManualTimeProvider Time { get; } + + public CallClock Clock { get; } + + public ICache Inner { get; } + + public FrameTierDouble Tier { get; } + + public IMemoryCacheFactory? Memory { get; } + + public MultilayerCache Cache { get; } + + /// The store the cache holds its entries in. + public IMemoryCache Store => ((IHeldStore)Memory!).Store; + + /// The bounds of a judgment made now. + public ObservedLife Life(TimeSpan fresh, TimeSpan window) => ObservedLife.From(Clock, Clock.GetTimestamp(), fresh, window); + + /// An observed entry whose bounds were judged now and whose UTC expiration is from now; the fresh length when left out. + public ICacheEntry Observed(string value, TimeSpan fresh, TimeSpan window, TimeSpan? utcLeft = null) => + CacheEntryFactory.CreateObserved(value, Clock.GetUtcNow() + (utcLeft ?? fresh), Life(fresh, window)); + + /// Has the cache read from its inner tier and adopt it, then lets the tier answer a miss again. + public async Task AdoptAsync(ICacheEntry entry, CachePolicy policy) + { + Tier.Held = entry; + (await Cache.GetAsync(Key, policy, TestContext.Current.CancellationToken)).Should().Be(entry.Value); + Tier.Held = null; + } + + public void Dispose() + { + Clock.Let(); + Cache.Dispose(); + } +} diff --git a/tests/UiPath.Caching.Tests/Fakes/PeerCluster.cs b/tests/UiPath.Caching.Tests/Fakes/PeerCluster.cs index 9b99423c..4f4da04a 100644 --- a/tests/UiPath.Caching.Tests/Fakes/PeerCluster.cs +++ b/tests/UiPath.Caching.Tests/Fakes/PeerCluster.cs @@ -402,7 +402,7 @@ public void Dispose() } /// The inner tier of a node: a stand-in for the Redis hash cache, which proxies cannot be made to look like because its counting interface is internal. - internal class PeerInner : DispatchProxy, ISpanKeyHashCache, IConnectionState, ISharedHashTier + internal class PeerInner : DispatchProxy, ISpanKeyHashCache, IConnectionState, ISharedHashTier, IFrameTier { private volatile bool _connected = true; private int _reads; @@ -452,6 +452,11 @@ public event EventHandler? OnReconnected public bool HeldReadSnapshots { get; set; } /// Read only by a node that monitors its connection. + /// Stands for a Redis tier: it has met no windowed frame and keeps bounds. + public bool MetWindowedFrame => false; + + public bool KeepsBounds => true; + public bool IsConnected { get => _connected; @@ -468,6 +473,9 @@ public bool IsConnected /// When set, a counted write does not reach the store and answers that it was not written. public bool Refuses { get; set; } + /// When set, hands up what it makes of each entry the store answers, as a tier that reads frames would. + public Func>, ICacheEntry>>? Shape { get; set; } + /// When set, a counted write reaches the store and is counted, yet answers that it was not written. public bool ReportsUnwritten { get; set; } @@ -566,7 +574,7 @@ public bool TryDecodeFields(IReadOnlyDictionary encoded, Cac ValueTask>> ISharedHashTier.ReadForAdoptionAsync(CacheKey cacheKey, CachePolicy? policy, CancellationToken token) where T : default { - var entry = ReadHold is { } hold ? ReadAfterAsync(hold, cacheKey.Name) : Task.FromResult(Store.Read(cacheKey.Name)); + var entry = ReadHold is { } hold ? ReadAfterAsync(hold, cacheKey.Name) : Task.FromResult(ReadStore(cacheKey.Name)); Interlocked.Increment(ref _reads); Broadcast.OperationSignals.Shared.Completed(); Changes.Pulse(); @@ -586,7 +594,7 @@ public bool TryDecodeFields(IReadOnlyDictionary encoded, Cac var key = ((CacheKey)args![0]!).Name; var read = ReadHold is { } hold ? new ValueTask>>(ReadAfterAsync(hold, key)) - : new ValueTask>>(Store.Read(key)); + : new ValueTask>>(ReadStore(key)); Interlocked.Increment(ref _reads); Broadcast.OperationSignals.Shared.Completed(); Changes.Pulse(); @@ -595,6 +603,8 @@ public bool TryDecodeFields(IReadOnlyDictionary encoded, Cac case nameof(IHashCache.SetMetadataAsync): Store.SetMetadata((IDictionary)args![1]!); return new ValueTask(true); + case nameof(IHashCache.RefreshAsync): + return new ValueTask(true); case nameof(IHashCache.ExpireTimeAsync): return new ValueTask(Store.Expiration()); case nameof(IHashCache.RemoveAsync): @@ -653,11 +663,14 @@ async Task LaterAsync() } } + private ICacheEntry> ReadStore(string key) => + Store.Read(key) is var entry && Shape is { } shape ? shape(entry) : entry; + private async Task>> ReadAfterAsync(Task hold, string key) { - var snapshot = HeldReadSnapshots ? Store.Read(key) : null; + var snapshot = HeldReadSnapshots ? ReadStore(key) : null; await hold; - return snapshot ?? Store.Read(key); + return snapshot ?? ReadStore(key); } } } diff --git a/tests/UiPath.Caching.Tests/Fakes/RedisLikeTier.cs b/tests/UiPath.Caching.Tests/Fakes/RedisLikeTier.cs new file mode 100644 index 00000000..607bb1bd --- /dev/null +++ b/tests/UiPath.Caching.Tests/Fakes/RedisLikeTier.cs @@ -0,0 +1,42 @@ +// The fixture's proxies implement RedisLikeTier.ICacheTier, which is internal to this assembly. +[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("DynamicProxyGenAssembly2")] + +namespace UiPath.Caching.Tests.Fakes; + +/// Makes a double that stands for a Redis tier one the library knows: it has met no windowed frame and keeps bounds, so the layered cache keeps its reads as over Redis. +internal static class RedisLikeTier +{ + /// A Redis-like tier for a fixture that builds its own substitutes: the fixture fills the members of as before, and the test sets . + public interface ICacheTier : ICache, IFrameTier + { + } + + /// A substitute for that also answers as such a tier. + public static T For() + where T : class + { + var tier = Substitute.For(); + ((IFrameTier)tier).KeepsBounds.Returns(true); + return tier; + } + + /// As , with a second interface. + public static T For() + where T : class + where T2 : class + { + var tier = Substitute.For([typeof(T), typeof(T2), typeof(IFrameTier)], []); + ((IFrameTier)tier).KeepsBounds.Returns(true); + return (T)tier; + } + + /// Freezes a Redis-like in , filled by it as a frozen would be. + public static ICache Freeze(AutoFixture.IFixture fixture) + { + var tier = AutoFixture.FixtureFreezer.Freeze(fixture); + tier.MetWindowedFrame.Returns(false); + tier.KeepsBounds.Returns(true); + AutoFixture.FixtureRegistrar.Inject(fixture, tier); + return tier; + } +} diff --git a/tests/UiPath.Caching.Tests/FillPrimitivesTests.cs b/tests/UiPath.Caching.Tests/FillPrimitivesTests.cs index 7acd4b61..d44989fe 100644 --- a/tests/UiPath.Caching.Tests/FillPrimitivesTests.cs +++ b/tests/UiPath.Caching.Tests/FillPrimitivesTests.cs @@ -163,7 +163,7 @@ public async Task A_fill_that_finds_a_value_reports_it_and_keeps_it_locally() [Fact] public async Task A_fill_the_shared_tier_could_not_answer_is_a_failure_that_keeps_the_value_locally() { - var shared = Substitute.For(); + var shared = RedisLikeTier.For(); shared.TryFillAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) .Returns(new FillResult(FillOutcome.Failed, null)); using var sut = Layered(shared); @@ -177,7 +177,7 @@ public async Task A_fill_the_shared_tier_could_not_answer_is_a_failure_that_keep [Fact] public async Task A_shared_tier_that_throws_is_a_failure_not_an_exception() { - var shared = Substitute.For(); + var shared = RedisLikeTier.For(); shared.TryFillAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) .Returns>(_ => throw new InvalidOperationException("down")); shared.SetIfChangedAsync(Arg.Any(), Arg.Any(), Arg.Any>(), Arg.Any(), Arg.Any(), Arg.Any()) @@ -263,7 +263,7 @@ public async Task A_snapshot_reads_the_shared_tier_and_not_the_local_copy() public async Task The_typed_cache_forwards_with_its_policy_and_key_mapping() { var policy = new CachePolicy { DistributedExpiration = TimeSpan.FromMinutes(11) }; - var inner = Substitute.For(); + var inner = RedisLikeTier.For(); var keyStrategy = Substitute.For(); keyStrategy.GetCacheKey(Arg.Any()).Returns((CacheKey)"ns:k"); var sut = new Cache(inner, keyStrategy, policy); @@ -775,8 +775,13 @@ private sealed class NonNullComparer : IEqualityComparer public int GetHashCode(string obj) => obj.GetHashCode(StringComparison.Ordinal); } - private sealed class FillStore : DictionaryCache, ICache, IMigrationCache + /// Stands for the shared Redis tier: it has met no windowed frame and keeps bounds. + private sealed class FillStore : DictionaryCache, ICache, IMigrationCache, IFrameTier { + public bool MetWindowedFrame => false; + + public bool KeepsBounds => true; + /// Runs after the store acted and before it answers. public Action? During { get; set; } diff --git a/tests/UiPath.Caching.Tests/InnerTierOutageTests.cs b/tests/UiPath.Caching.Tests/InnerTierOutageTests.cs index ef2fe63e..0df73849 100644 --- a/tests/UiPath.Caching.Tests/InnerTierOutageTests.cs +++ b/tests/UiPath.Caching.Tests/InnerTierOutageTests.cs @@ -20,7 +20,7 @@ public class InnerTierOutageTests [Fact] public async Task Concurrent_cold_reads_of_one_key_share_one_inner_read() { - var inner = Substitute.For(); + var inner = RedisLikeTier.For(); var release = new TaskCompletionSource>(TaskCreationOptions.RunContinuationsAsynchronously); var reads = 0; inner.GetCacheEntryAsync(Arg.Any(), Arg.Any(), Arg.Any()) @@ -39,7 +39,7 @@ public async Task Concurrent_cold_reads_of_one_key_share_one_inner_read() [Fact] public async Task Concurrent_cold_reads_with_different_policies_read_separately() { - var inner = Substitute.For(); + var inner = RedisLikeTier.For(); var release = new TaskCompletionSource>(TaskCreationOptions.RunContinuationsAsynchronously); var reads = 0; inner.GetCacheEntryAsync(Arg.Any(), Arg.Any(), Arg.Any()) @@ -58,7 +58,7 @@ public async Task Concurrent_cold_reads_with_different_policies_read_separately( [Fact] public async Task Concurrent_cold_reads_with_equivalent_policies_share_one_inner_read() { - var inner = Substitute.For(); + var inner = RedisLikeTier.For(); var release = new TaskCompletionSource>(TaskCreationOptions.RunContinuationsAsynchronously); var reads = 0; inner.GetCacheEntryAsync(Arg.Any(), Arg.Any(), Arg.Any()) @@ -77,7 +77,7 @@ public async Task Concurrent_cold_reads_with_equivalent_policies_share_one_inner [Fact] public async Task Concurrent_cold_hash_reads_of_different_fields_share_one_inner_read() { - var inner = Substitute.For(); + var inner = RedisLikeTier.For(); var release = new TaskCompletionSource>>(TaskCreationOptions.RunContinuationsAsynchronously); var reads = 0; inner.GetCacheEntryAsync(Arg.Any(), Arg.Any(), Arg.Any()) @@ -100,7 +100,7 @@ public async Task Concurrent_cold_hash_reads_of_different_fields_share_one_inner [Fact] public async Task Concurrent_misses_run_the_generator_once_when_the_inner_tier_refuses_the_write() { - var inner = Substitute.For(); + var inner = RedisLikeTier.For(); inner.GetCacheEntryAsync(Arg.Any(), Arg.Any(), Arg.Any()) .Returns(new ValueTask>(new TestCacheEntry { Expiration = DateTimeOffset.MinValue })); inner.TryFillAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) @@ -125,7 +125,7 @@ public async Task Concurrent_misses_run_the_generator_once_when_the_inner_tier_r [Fact] public async Task Concurrent_hash_misses_run_the_generator_once_when_the_inner_tier_refuses_the_write() { - var inner = Substitute.For(); + var inner = RedisLikeTier.For(); inner.GetCacheEntryAsync(Arg.Any(), Arg.Any(), Arg.Any()) .Returns(new ValueTask>>(new TestCacheEntry> { Expiration = DateTimeOffset.MinValue })); inner.SetAsync(Arg.Any(), Arg.Any>(), Arg.Any(), Arg.Any(), Arg.Any()) @@ -150,7 +150,7 @@ public async Task Concurrent_hash_misses_run_the_generator_once_when_the_inner_t [Fact] public async Task Concurrent_misses_run_the_generator_once_when_the_inner_write_throws() { - var inner = Substitute.For(); + var inner = RedisLikeTier.For(); inner.GetCacheEntryAsync(Arg.Any(), Arg.Any(), Arg.Any()) .Returns(new ValueTask>(new TestCacheEntry { Expiration = DateTimeOffset.MinValue })); inner.TryFillAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) @@ -244,7 +244,7 @@ public async Task A_miss_canceled_during_the_inner_write_keeps_nothing_local(boo if (hash) { - var inner = Substitute.For(); + var inner = RedisLikeTier.For(); inner.GetCacheEntryAsync(Arg.Any(), Arg.Any(), Arg.Any()) .Returns(new ValueTask>>(new TestCacheEntry> { Expiration = DateTimeOffset.MinValue })); inner.SetAsync(Arg.Any(), Arg.Any>(), Arg.Any(), Arg.Any(), Arg.Any()) @@ -261,7 +261,7 @@ public async Task A_miss_canceled_during_the_inner_write_keeps_nothing_local(boo } else { - var inner = Substitute.For(); + var inner = RedisLikeTier.For(); inner.GetCacheEntryAsync(Arg.Any(), Arg.Any(), Arg.Any()) .Returns(new ValueTask>(new TestCacheEntry { Expiration = DateTimeOffset.MinValue })); inner.TryFillAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) @@ -295,7 +295,7 @@ public async Task A_local_write_failure_after_an_accepted_inner_write_is_not_ret var options = new InMemoryCacheOptions { SizeLimit = 1_000, SizeProvider = sizeProvider }; if (hash) { - var inner = Substitute.For(); + var inner = RedisLikeTier.For(); inner.GetCacheEntryAsync(Arg.Any(), Arg.Any(), Arg.Any()) .Returns(new ValueTask>>(new TestCacheEntry> { Expiration = DateTimeOffset.MinValue })); inner.SetAsync(Arg.Any(), Arg.Any>(), Arg.Any(), Arg.Any(), Arg.Any()) @@ -305,7 +305,7 @@ public async Task A_local_write_failure_after_an_accepted_inner_write_is_not_ret } else { - var inner = Substitute.For(); + var inner = RedisLikeTier.For(); inner.GetCacheEntryAsync(Arg.Any(), Arg.Any(), Arg.Any()) .Returns(new ValueTask>(new TestCacheEntry { Expiration = DateTimeOffset.MinValue })); inner.TryFillAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) @@ -320,7 +320,7 @@ public async Task A_local_write_failure_after_an_accepted_inner_write_is_not_ret [Fact] public async Task A_cold_read_during_an_outage_is_kept_for_the_disconnected_cap() { - var inner = Substitute.For(); + var inner = RedisLikeTier.For(); var state = (IConnectionState)inner; state.IsConnected.Returns(false); inner.GetCacheEntryAsync(Arg.Any(), Arg.Any(), Arg.Any()) @@ -343,7 +343,7 @@ public async Task A_cold_read_during_an_outage_is_kept_for_the_disconnected_cap( [Fact] public async Task Concurrent_cold_reads_with_different_disconnected_caps_read_separately() { - var inner = Substitute.For(); + var inner = RedisLikeTier.For(); var release = new TaskCompletionSource>(TaskCreationOptions.RunContinuationsAsynchronously); var reads = 0; inner.GetCacheEntryAsync(Arg.Any(), Arg.Any(), Arg.Any()) @@ -364,7 +364,7 @@ public async Task Concurrent_cold_reads_with_different_disconnected_caps_read_se [InlineData(true)] public async Task A_cold_batch_read_during_an_outage_is_kept_for_the_disconnected_cap(bool entries) { - var inner = Substitute.For(); + var inner = RedisLikeTier.For(); var state = (IConnectionState)inner; state.IsConnected.Returns(false); inner.GetCacheEntriesAsync(Arg.Any(), Arg.Any(), Arg.Any()) @@ -401,7 +401,7 @@ public async Task A_cold_batch_read_during_an_outage_is_kept_for_the_disconnecte [Fact] public async Task A_disconnected_tier_serves_the_local_copy_by_default() { - var inner = Substitute.For(); + var inner = RedisLikeTier.For(); var state = (IConnectionState)inner; state.IsConnected.Returns(true); inner.SetAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()).Returns(true); @@ -469,7 +469,7 @@ public async Task A_custom_token_factory_keeps_entries_over_a_subscription_gap_w [Fact] public async Task A_restored_connection_keeps_the_local_tier_when_no_broadcast_could_be_missed() { - var inner = Substitute.For(); + var inner = RedisLikeTier.For(); var state = (IConnectionState)inner; state.IsConnected.Returns(true); StubReadOnce(inner); @@ -520,7 +520,7 @@ private static async Task IgnoreCancellation(Func call) /// An inner tier that holds the value for the first read only, so a later hit can only come from the local tier. private static ICache ReadOnce() { - var inner = Substitute.For(); + var inner = RedisLikeTier.For(); StubReadOnce(inner); return inner; } @@ -562,7 +562,7 @@ private static ValueTask> CancelFill(CancellationTokenSource private static ICache BatchMissInner(out FillManyInner many) { - var inner = Substitute.For(); + var inner = RedisLikeTier.For(); inner.GetCacheEntriesAsync(Arg.Any(), Arg.Any(), Arg.Any()) .Returns(ci => new ValueTask>[]>(Array.ConvertAll( ci.Arg(), diff --git a/tests/UiPath.Caching.Tests/MemoryCacheSetterTests.cs b/tests/UiPath.Caching.Tests/MemoryCacheSetterTests.cs index 8121f9d2..fa22f24b 100644 --- a/tests/UiPath.Caching.Tests/MemoryCacheSetterTests.cs +++ b/tests/UiPath.Caching.Tests/MemoryCacheSetterTests.cs @@ -9,6 +9,8 @@ namespace UiPath.Caching.Tests; public class MemoryCacheSetterTests : IAsyncLifetime { + private const string RefreshFailed = $"Caching.{nameof(MemoryCacheSetter)}.{nameof(MemoryCacheSetter.RefreshMetadata)}.Failed"; + private readonly IFixture _fixture = AutoFixtureCreator.NSubstitute(); private readonly TimeProvider _clock = new FakeTimeProvider(DateTimeOffset.UnixEpoch); @@ -234,6 +236,53 @@ public void A_renewed_copy_keeps_whether_the_entry_it_replaces_takes_read_marks( ((ILocalEntry)held!).IsTracked.Should().Be(tracked); } + [Theory] + [InlineData(true, false)] + [InlineData(false, true)] + [InlineData(true, true)] + public void With_DropsOnRefreshEvent_a_changed_token_sets_no_entry(bool expiration, bool metadata) + { + var (setter, token) = Held(drops: true); + + Change(token, expiration, metadata); + + _memoryCache.TryGetValue(_cacheKey.Name, out _).Should().BeFalse(); + setter.Creates.Should().Be(0); + _telemetryProvider.Events.Should().NotContain(e => e.Name == RefreshFailed); + } + + [Fact] + public void With_DropsOnRefreshEvent_the_callbacks_before_the_rebuild_still_run() + { + var changed = new List(); + var peerChanged = new List(); + var invalidations = new RecordingInvalidations(); + var (_, token) = Held(drops: true, changed, peerChanged, invalidations); + + Change(token, expiration: true, metadata: false); + + changed.Should().Equal(_cacheKey.Name); + peerChanged.Should().ContainSingle().Which.CacheKey.Should().Be(_cacheKey); + invalidations.Keys.Should().Equal(_cacheKey.Name); + _memoryCache.TryGetValue(_cacheKey.Name, out _).Should().BeFalse(); + } + + [Fact] + public void Without_DropsOnRefreshEvent_the_entry_is_rebuilt_as_today() + { + var (setter, token) = Held(drops: false); + var expiration = _clock.GetUtcNow().AddMinutes(5); + + Change(token, expiration: true, metadata: false, at: expiration); + + _memoryCache.TryGetValue(_cacheKey.Name, out var held).Should().BeTrue(); + var entry = held.Should().BeAssignableTo>().Subject; + entry.Value.Should().Be("v"); + entry.Expiration.Should().Be(expiration); + setter.Creates.Should().Be(1); + _telemetryProvider.Events.Should().NotContain(e => e.Name == RefreshFailed); + } + public ValueTask DisposeAsync() { GC.SuppressFinalize(this); @@ -282,4 +331,75 @@ public ValueTask InitializeAsync() ); return ValueTask.CompletedTask; } + + /// A local tier that holds v under the returned token; the token its rebuild would take never changes. + private (CountingSetter Setter, TestChangeToken Token) Held(bool drops, List? changed = null, List? peerChanged = null, ISharedTier? invalidations = null) + { + _memoryCache = new MemoryCacheFactory(_clock, NullLoggerFactory.Instance).Get(_options); + var token = new TestChangeToken { ActiveChangeCallbacks = true }; + _changeTokenFactory.Create(Arg.Any(), Arg.Any>(), Arg.Any(), Arg.Any()) + .Returns(token, new TestChangeToken { ActiveChangeCallbacks = true }); + var setter = new CountingSetter(_changeTokenFactory, _topicProvider, _memoryCache, _clock, _options, _telemetryProvider) + { + DropsOnRefreshEvent = drops, + TokenChanged = changed is null ? null : (name, _) => changed.Add(name), + PeerRefreshChanged = peerChanged is null ? null : peerChanged.Add, + Invalidations = invalidations, + }; + var options = new CacheEntryOptions { CacheKey = _cacheKey, CallerKey = _cacheKey, TopicKey = _topicKey, Expiration = _clock.GetUtcNow().AddMinutes(1) }; + PeerRefreshTarget? refresh = peerChanged is null ? null : new PeerRefreshTarget(new NoReader(), new CachePolicy()); + setter.Set(options, new CacheEntryFactory().Create("v", options.Expiration), typeof(string), TimeSpan.FromHours(1), refresh).Should().BeTrue(); + _memoryCache.TryGetValue(_cacheKey.Name, out _).Should().BeTrue(); + return (setter, token); + } + + /// Changes the token as an event that carries an expiration, metadata or both changes it. + private void Change(TestChangeToken token, bool expiration, bool metadata, DateTimeOffset? at = null) + { + token.Expiration = expiration ? at ?? _clock.GetUtcNow().AddMinutes(5) : null; + token.MetadataHasChanged = metadata; + token.Metadata = metadata ? new Dictionary { ["m"] = "1" } : null; + token.HasChanged = true; + token.InvokeCallbacks(); + } + + private sealed class RecordingInvalidations : ISharedTier + { + public List Keys { get; } = []; + + public void Invalidated(CacheKey key) => Keys.Add(key.Name); + + public void InvalidatedAll() => throw new NotSupportedException(); + + public IDisposable DemandMaster() => Fakes.NoMasterScope.Instance; + } + + /// A refresh target no test reads through. + private sealed class NoReader : IPeerRefreshReader + { + public ValueTask ReadAsync(MultilayerCacheBase cache, CacheKey[] keys, CachePolicy policy, CancellationToken token) => throw new NotSupportedException(); + + public PeerKeep Keep(MultilayerCacheBase cache, RefreshMetadataState held, PeerRead read, long mark, out object? installed) => throw new NotSupportedException(); + } + + /// Builds the rebuilt entry as the layered string cache does, and counts the rebuilds. + private sealed class CountingSetter(IChangeTokenFactory tokens, ITopicProvider topics, IMemoryCache memoryCache, TimeProvider clock, InMemoryRedisCacheOptions options, ICachingTelemetryProvider telemetry) + : MemoryCacheSetter("test", tokens, topics, memoryCache, NullLogger.Instance, clock, options, options, telemetry) + { + public int Creates { get; private set; } + + protected override ICacheEntryOptions CreateEntry(RefreshMetadataState metadataState, CancellationToken cancellationToken) + { + Creates++; + return new CacheEntryOptions + { + CacheKey = metadataState.CacheKey, + CallerKey = metadataState.CallerKey, + TopicKey = metadataState.TopicKey, + Token = cancellationToken, + Expiration = Clock.ToDateTimeOffset(metadataState.Token.Expiration), + Metadata = metadataState.Token.Metadata, + }; + } + } } diff --git a/tests/UiPath.Caching.Tests/MultilayerCacheBackgroundWriteTests.cs b/tests/UiPath.Caching.Tests/MultilayerCacheBackgroundWriteTests.cs index 35624025..7423af21 100644 --- a/tests/UiPath.Caching.Tests/MultilayerCacheBackgroundWriteTests.cs +++ b/tests/UiPath.Caching.Tests/MultilayerCacheBackgroundWriteTests.cs @@ -1072,7 +1072,7 @@ public Harness(InMemoryRedisCacheOptions? options = null, IDistributedLock? dist Clock = new ManualTimeProvider(); options ??= new InMemoryRedisCacheOptions(); _drainTimeout = options.BackgroundWriteDrainTimeout; - var inner = Substitute.For(); + var inner = RedisLikeTier.For(); Telemetry = Substitute.For(); Telemetry.When(t => t.TrackEvent(Arg.Any(), Arg.Any>(), Arg.Any>())).Do(_ => _changed.Pulse()); OnWrite = (value, _) => diff --git a/tests/UiPath.Caching.Tests/MultilayerCacheBatchRehydrateTests.cs b/tests/UiPath.Caching.Tests/MultilayerCacheBatchRehydrateTests.cs index 3a2f7a13..edf73fdf 100644 --- a/tests/UiPath.Caching.Tests/MultilayerCacheBatchRehydrateTests.cs +++ b/tests/UiPath.Caching.Tests/MultilayerCacheBatchRehydrateTests.cs @@ -751,7 +751,8 @@ public ValueTask InitializeAsync() _changeTokenFactory.Create(Arg.Any(), Arg.Any>(), Arg.Any(), Arg.Any()) .Returns(_ => new TestChangeToken { ActiveChangeCallbacks = true, HasChanged = false }); _memoryCache = new MemoryCache(Options.Create(new MemoryCacheOptions { Clock = new TimeProviderClock(_clock) })); - _innerCache = _fixture.Freeze(); + _innerCache = RedisLikeTier.For(); + _fixture.Inject(_innerCache); _fixture.Inject(AdoptionProxy.Over(_innerCache, batchBacked: true)); _telemetry = new RecordingTelemetryProvider(); _fixture.Inject(_telemetry); diff --git a/tests/UiPath.Caching.Tests/MultilayerCachePerNamePolicyWiringTests.cs b/tests/UiPath.Caching.Tests/MultilayerCachePerNamePolicyWiringTests.cs index b7270fa3..46e291ce 100644 --- a/tests/UiPath.Caching.Tests/MultilayerCachePerNamePolicyWiringTests.cs +++ b/tests/UiPath.Caching.Tests/MultilayerCachePerNamePolicyWiringTests.cs @@ -560,7 +560,7 @@ public ValueTask InitializeAsync() { _cacheKey = _fixture.Create(); _topicKey = _fixture.Create(); - _innerCache = _fixture.Freeze(); + _innerCache = RedisLikeTier.Freeze(_fixture); _memoryCache = _fixture.Freeze(); _fixture.Freeze(); _options = new InMemoryRedisCacheOptions diff --git a/tests/UiPath.Caching.Tests/MultilayerCacheRehydrateTests.cs b/tests/UiPath.Caching.Tests/MultilayerCacheRehydrateTests.cs index 1debd35c..1d76b1f8 100644 --- a/tests/UiPath.Caching.Tests/MultilayerCacheRehydrateTests.cs +++ b/tests/UiPath.Caching.Tests/MultilayerCacheRehydrateTests.cs @@ -665,7 +665,8 @@ public ValueTask InitializeAsync() _fixture.Inject(_clock); _cacheKey = _fixture.Create(); _topicKey = _fixture.Create(); - _innerCache = _fixture.Freeze(); + _innerCache = RedisLikeTier.For(); + _fixture.Inject(_innerCache); _fixture.Inject(AdoptionProxy.Over(_innerCache)); _memoryCache = _fixture.Freeze(); _distributedLock = _fixture.Freeze(); diff --git a/tests/UiPath.Caching.Tests/MultilayerCacheTests.cs b/tests/UiPath.Caching.Tests/MultilayerCacheTests.cs index ef83fd12..9442c020 100644 --- a/tests/UiPath.Caching.Tests/MultilayerCacheTests.cs +++ b/tests/UiPath.Caching.Tests/MultilayerCacheTests.cs @@ -1592,7 +1592,7 @@ public ValueTask InitializeAsync() _changeTokenFactory = _fixture.Freeze(); _memoryCache = _fixture.Freeze(); - _innerCache = _fixture.Freeze(); + _innerCache = RedisLikeTier.Freeze(_fixture); _logger = _fixture.Freeze(); _logger.IsEnabled(Arg.Any()).Returns(true); _clock = new TimeProviderClock(new ManualTimeProvider()); diff --git a/tests/UiPath.Caching.Tests/MultilayerHashCacheBackgroundWriteTests.cs b/tests/UiPath.Caching.Tests/MultilayerHashCacheBackgroundWriteTests.cs index 2fdcfd9c..7749c4bb 100644 --- a/tests/UiPath.Caching.Tests/MultilayerHashCacheBackgroundWriteTests.cs +++ b/tests/UiPath.Caching.Tests/MultilayerHashCacheBackgroundWriteTests.cs @@ -597,7 +597,7 @@ public Rig(InMemoryRedisCacheOptions? options = null, IDistributedLock? distribu _drainTimeout = options.BackgroundWriteDrainTimeout; Telemetry = Substitute.For(); Telemetry.When(t => t.TrackEvent(Arg.Any(), Arg.Any>(), Arg.Any>())).Do(_ => _changed.Pulse()); - var inner = Substitute.For(); + var inner = RedisLikeTier.For(); ValueTaskStubs.Returns( inner.SetAsync(Arg.Any(), Arg.Any>(), Arg.Any(), Arg.Any(), Arg.Any()), call => diff --git a/tests/UiPath.Caching.Tests/MultilayerHashCacheTests.cs b/tests/UiPath.Caching.Tests/MultilayerHashCacheTests.cs index cc2fa043..11f02127 100644 --- a/tests/UiPath.Caching.Tests/MultilayerHashCacheTests.cs +++ b/tests/UiPath.Caching.Tests/MultilayerHashCacheTests.cs @@ -1468,7 +1468,8 @@ public ValueTask InitializeAsync() _topicKeyStrategy.GetTopicKey().Returns(_topicKey); _changeTokenFactory = _fixture.Freeze(); _memoryCache = _fixture.Freeze(); - _innerCache = _fixture.Freeze(); + _innerCache = RedisLikeTier.For(); + _fixture.Inject(_innerCache); _clock = new TimeProviderClock(new ManualTimeProvider()); _fixture.Inject(new SystemClockTimeProvider(_clock)); diff --git a/tests/UiPath.Caching.Tests/ObservedEntryHashTests.cs b/tests/UiPath.Caching.Tests/ObservedEntryHashTests.cs new file mode 100644 index 00000000..7aa4e947 --- /dev/null +++ b/tests/UiPath.Caching.Tests/ObservedEntryHashTests.cs @@ -0,0 +1,503 @@ +using System.Reflection; +using Microsoft.Extensions.Caching.Memory; +using Microsoft.Extensions.Logging.Abstractions; +using Microsoft.Extensions.Options; +using NSubstitute; +using UiPath.Caching.Config; +using UiPath.Caching.Locking; +using UiPath.Caching.Telemetry; +using UiPath.Caching.Tests.Broadcast; +using UiPath.Caching.Tests.Fakes; +using UiPath.Caching.Tests.Telemetry; + +namespace UiPath.Caching.Tests; + +/// A string cache and a hash cache that get one store meet under one key: the hash cache takes no observed entry, fresh or not, and keeps none that its inner tier hands up. +public class ObservedEntryHashTests +{ + private const string Key = "k"; + + private static readonly TimeSpan Fresh = TimeSpan.FromSeconds(60); + private static readonly TimeSpan Window = TimeSpan.FromSeconds(120); + private static readonly TimeSpan Far = TimeSpan.FromHours(2); + private static readonly CachePolicy Local = new() { LocalExpiration = TimeSpan.FromHours(1) }; + private static readonly CachePolicy Locked = new() { LocalExpiration = TimeSpan.FromHours(1), Lock = new LockProfile { DistributedLockEnabled = true } }; + private static readonly HashCacheEntryOptions Merge = new(SetOption: HashCacheSetOption.HashReplace); + + public enum HashCall + { + GetItem, + Get, + GetFields, + Entry, + Contains, + TimeToLive, + ExpireTime, + Metadata, + GetOrAddBeforeTheKey, + GetOrAddUnderTheKey, + } + + public enum Replaced + { + ItemByKey, + ItemBySpan, + Entry, + TimeToLive, + } + + public enum Site + { + Read, + RereadAfterAPeersEvent, + } + + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + public static TheoryData Calls() + { + var data = new TheoryData(); + foreach (var call in Enum.GetValues()) + { + foreach (var span in call is HashCall.GetOrAddBeforeTheKey or HashCall.GetOrAddUnderTheKey ? new[] { false } : new[] { false, true }) + { + foreach (var moment in new[] { 59_000, 60_000, 65_000 }) + { + data.Add(call, span, moment); + } + } + } + + return data; + } + + public static TheoryData ControlCalls() + { + var data = new TheoryData(); + foreach (var call in Enum.GetValues()) + { + foreach (var span in call is HashCall.GetOrAddBeforeTheKey or HashCall.GetOrAddUnderTheKey ? new[] { false } : new[] { false, true }) + { + data.Add(call, span); + } + } + + return data; + } + + public static TheoryData LocalCalls() + { + var data = new TheoryData(); + foreach (var call in Enum.GetValues()) + { + foreach (var before in new[] { true, false }) + { + data.Add(call, before); + } + } + + return data; + } + + [Theory] + [MemberData(nameof(Calls))] + public async Task A_hash_cache_never_answers_from_an_observed_entry_in_a_shared_store(HashCall call, bool span, int momentMs) + { + var underTheKey = call == HashCall.GetOrAddUnderTheKey; + // The adoption keeps no metadata, so the metadata rows and the second probe write the entry into a plain store. + var plainStore = underTheKey || call == HashCall.Metadata; + using var harness = new Harness(clock => plainStore ? new PlainMemoryCacheFactory() : span ? new OpenMemoryCacheFactory(clock) : new LoggedMemoryCacheFactory(clock)); + var held = await harness.HoldObservedAsync(Fresh, Window, Far); + harness.Time.Advance(TimeSpan.FromMilliseconds(momentMs)); + if (underTheKey) + { + ((PlainMemoryCacheFactory)harness.Memory).Store.HideFor(1); + } + + var before = harness.HashTier.Total; + var generated = 0; + var fromTheEntry = await AnswersFromTheEntryAsync(harness.HashCache, call, span, () => generated++); + + fromTheEntry.Should().BeFalse(); + harness.HashTier.Total.Should().BeGreaterThan(before, "each call asks the inner tier"); + var present = harness.Store.TryGetValue(Key, out var stored); + if (call is HashCall.GetOrAddBeforeTheKey or HashCall.GetOrAddUnderTheKey) + { + present.Should().BeTrue(); + generated.Should().Be(1); + stored.Should().NotBeSameAs(held, "the generator's hash is stored over the key, as after an eviction"); + stored.Should().NotBeAssignableTo(); + } + else if (momentMs < Fresh.TotalMilliseconds) + { + present.Should().BeTrue(); + stored.Should().BeSameAs(held, "a read, an inspection command and a probe store nothing"); + } + + switch (harness.Memory) + { + case PlainMemoryCacheFactory plain: + plain.Store.Removed.Should().BeEmpty(); + break; + case LoggedMemoryCacheFactory logged: + logged.Evictions.Should().NotContain(e => e.Reason == EvictionReason.Removed); + break; + } + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task A_hash_SetMetadataAsync_publishes_the_expiration_the_inner_tier_answers_not_an_observed_entrys(bool observedHeld) + { + var plain = new PlainMemoryCacheFactory(); + using var harness = new Harness(_ => plain); + var innerExpiration = harness.Clock.GetUtcNow() + TimeSpan.FromMinutes(7); + var (inner, tier) = TierDouble.Make(); + tier.Expiration = innerExpiration; + var events = new List(); + using var cache = CapturingHashCache(inner, plain, harness.Clock, events); + var held = await harness.HoldObservedAsync(Fresh, Window, Far); + if (!observedHeld) + { + // The control: an ordinary entry under the key, whose expiration the publication keeps. + held = new CacheEntryFactory().Create>(new Dictionary { ["f"] = "A-f" }, harness.Clock.GetUtcNow() + Far); + plain.Store.Put(Key, held); + } + + (await cache.SetMetadataAsync(Key, new Dictionary { ["m"] = "1" }, Ct)).Should().BeTrue("the inner tier accepts the metadata"); + + tier.Count(nameof(IHashCache.SetMetadataAsync)).Should().Be(1); + var published = events.Where(e => e.Data?.Properties?.ContainsKey(KnownFieldNames.ExpirationKey) == true).Should().ContainSingle().Which; + var expiration = (DateTimeOffset)published.Data!.Properties![KnownFieldNames.ExpirationKey]!; + if (observedHeld) + { + tier.Count(nameof(IHashCache.ExpireTimeAsync)).Should().Be(1, "the observed entry is not read for its expiration"); + expiration.Should().Be(innerExpiration, "the inner tier's expiration, not A's"); + } + else + { + tier.Count(nameof(IHashCache.ExpireTimeAsync)).Should().Be(0); + expiration.Should().Be(((ICacheEntry)held!).Expiration, "an ordinary entry keeps its own"); + } + } + + [Theory] + [InlineData(Replaced.ItemByKey)] + [InlineData(Replaced.ItemBySpan)] + [InlineData(Replaced.Entry)] + [InlineData(Replaced.TimeToLive)] + public async Task A_hash_cache_refuses_a_replaced_observed_entry_and_leaves_the_newer_one(Replaced lookup) + { + using var harness = new Harness(clock => lookup == Replaced.ItemBySpan ? new OpenMemoryCacheFactory(clock) : new LoggedMemoryCacheFactory(clock)); + await harness.HoldObservedAsync(TimeSpan.FromSeconds(1), Window, TimeSpan.FromSeconds(1)); + harness.Time.StepUtc(TimeSpan.FromSeconds(-10)); + harness.Time.Advance(TimeSpan.FromSeconds(5)); + + harness.Clock.Hold(); + var read = Task.Run(async () => await ReadAsync(harness.HashCache, lookup), Ct); + await Task.WhenAny(harness.Clock.Entered, read); + harness.Clock.Entered.IsCompleted.Should().BeTrue("the bound is a token whose check reads the clock inside the lookup"); + var newer = new CacheEntryFactory().Create>(new Dictionary { ["f"] = "B-f" }, harness.Clock.GetUtcNow() + Far); + harness.Store.Set(Key, newer); + var before = harness.HashTier.Total; + harness.Clock.Let(); + var answer = await read; + + switch (lookup) + { + case Replaced.ItemByKey or Replaced.Entry: + answer.Should().Be("B-f"); + harness.HashTier.Total.Should().Be(before, "the second look finds B and sends nothing"); + break; + case Replaced.ItemBySpan: + answer.Should().NotBe("A-f"); + break; + default: + answer.Should().BeNull(); + harness.HashTier.Total.Should().Be(before + 1, "a call that looks once asks the inner tier"); + break; + } + + harness.Store.TryGetValue(Key, out var stored).Should().BeTrue(); + stored.Should().BeSameAs(newer); + if (lookup != Replaced.ItemBySpan) + { + var memory = (LoggedMemoryCacheFactory)harness.Memory; + await memory.Changes.WaitUntil(() => memory.Evictions.Count >= 1).WaitAsync(TimeSpan.FromSeconds(30), Ct); + memory.Evictions.Where(e => Text(e.Value) == "A-f").Should().ContainSingle().Which.Reason.Should().Be(EvictionReason.Replaced); + memory.Evictions.Where(e => Text(e.Value) == "B-f").Should().BeEmpty(); + } + } + + [Theory] + [MemberData(nameof(LocalCalls))] + public async Task A_hash_cache_refuses_an_observed_entry_whatever_the_store_does(HashCall call, bool beforeTheBound) + { + var plain = new PlainMemoryCacheFactory(); + using var harness = new Harness(_ => plain); + var held = await harness.HoldObservedAsync(Fresh, Window, Far); + harness.Time.Advance(beforeTheBound ? Fresh - TimeSpan.FromSeconds(1) : Fresh + TimeSpan.FromSeconds(1)); + if (call == HashCall.GetOrAddUnderTheKey) + { + plain.Store.HideFor(1); + } + + var before = harness.HashTier.Total; + var fromTheEntry = await AnswersFromTheEntryAsync(harness.HashCache, call, span: false, () => { }); + + fromTheEntry.Should().BeFalse(); + harness.HashTier.Total.Should().BeGreaterThan(before); + plain.Store.Removed.Should().BeEmpty(); + + // A field write merges nothing from the observed entry: what it stores holds the written fields only. + plain.Store.Put(Key, held); + await harness.HashCache.SetAsync(Key, new Dictionary { ["w"] = "1" }, Merge, Local, Ct); + plain.Store.TryGetValue(Key, out var stored).Should().BeTrue(); + if (stored is not ObservedEntry) + { + ((ICacheEntry)stored!).Value.Should().BeAssignableTo>().Which.Keys.Should().BeEquivalentTo(["w"]); + } + } + + [Theory] + [InlineData(Site.Read)] + [InlineData(Site.RereadAfterAPeersEvent)] + public async Task A_hash_cache_keeps_no_observed_entry_from_its_inner_tier(Site site) + { + if (site == Site.Read) + { + var plain = new PlainMemoryCacheFactory(); + using var harness = new Harness(_ => plain); + harness.HashTier.Held = harness.ObservedHash(Fresh, Window, Far); + + (await harness.HashCache.GetAsync(Key, Local, Ct)).Should().ContainKey("f"); + + plain.Store.TryGetValue(Key, out _).Should().BeFalse(); + return; + } + + using var cluster = new PeerCluster(new ManualTimeProvider(new DateTimeOffset(2026, 1, 1, 0, 0, 0, TimeSpan.Zero))); + var telemetry = new RecordingTelemetryProvider(); + var (a, b) = (cluster.Add("a"), cluster.Add("b", telemetry: telemetry)); + b.Inner.Shape = entry => entry.Found + ? CacheEntryFactory.CreateObserved(entry.Value!, entry.Expiration, new ObservedLife(long.MaxValue - 1, long.MaxValue), entry.Metadata) + : entry; + var policy = new CachePolicy { LocalExpiration = TimeSpan.FromMinutes(10), LocalExpirationDisconnected = TimeSpan.FromSeconds(30) }; + (await b.Cache.SetAsync(Key, new Dictionary { ["a"] = "1", ["b"] = "2" }, policy, Ct)).Should().BeTrue(); + b.Local.TryGetValue(Key, out _).Should().BeTrue(); + + cluster.Redis.WriteQuietly(("z", "0")); + (await a.Cache.SetAsync(Key, new Dictionary { ["c"] = "3" }, Merge, policy, Ct)).Should().BeTrue(); + await b.Settled(outcomes: 1); + + b.Local.TryGetValue(Key, out _).Should().BeFalse("the hash entry this node held is dropped"); + DroppedReasons(telemetry).Should().Equal("not_kept"); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task A_hash_cache_keeps_no_entry_from_a_tier_it_does_not_know(bool known) + { + var plain = new PlainMemoryCacheFactory(); + var time = new ManualTimeProvider(new DateTimeOffset(2026, 1, 1, 0, 0, 0, TimeSpan.Zero)); + var (inner, tier) = known ? FrameTierDouble.ForHashCache() : TierDouble.Make(); + tier.Held = new CacheEntryFactory().Create>(new Dictionary { ["f"] = "A-f" }, time.GetUtcNow() + Far); + using var cache = InMemoryMultilayer.HashCache(inner: inner, memory: plain, clock: time); + + for (var read = 0; read < 3; read++) + { + (await cache.GetAsync(Key, Local, Ct)).Should().ContainKey("f"); + } + + tier.Count(nameof(IHashCache.GetCacheEntryAsync)).Should().Be(known ? 1 : 3); + plain.Store.TryGetValue(Key, out _).Should().Be(known); + } + + [Theory] + [MemberData(nameof(ControlCalls))] + public async Task A_hash_entry_is_served_and_merged_as_today(HashCall call, bool span) + { + using var harness = new Harness(clock => new OpenMemoryCacheFactory(clock)); + var entry = new CacheEntryFactory().Create>( + new Dictionary { ["f"] = "A-f" }, + harness.Clock.GetUtcNow() + Far, + EntryValidators.From("A-tag", null)); + harness.Store.Set(Key, entry); + var before = harness.HashTier.Total; + var generated = 0; + + (await AnswersFromTheEntryAsync(harness.HashCache, call, span, () => generated++)).Should().BeTrue(); + + generated.Should().Be(0); + harness.HashTier.Total.Should().Be(before, "the call answers from the local entry and sends nothing"); + if (call == HashCall.Get) + { + await harness.HashCache.SetAsync(Key, new Dictionary { ["w"] = "1" }, Merge, Local, Ct); + harness.Store.TryGetValue(Key, out var merged).Should().BeTrue(); + ((ICacheEntry)merged!).Value.Should().BeAssignableTo>().Which.Keys.Should().BeEquivalentTo(["f", "w"]); + } + } + + private static MultilayerHashCache CapturingHashCache(IHashCache inner, IMemoryCacheFactory memory, TimeProvider clock, List events) + { + var options = new InMemoryCacheOptions(); + var cacheOptions = new CacheOptions { AppShortName = "test" }; + var topic = Substitute.For>(); + topic.PublishAsync(Arg.Any(), Arg.Any()).Returns(call => + { + lock (events) + { + events.Add(call.Arg()); + } + + return new ValueTask(true); + }); + var provider = Substitute.For(); + provider.Enabled.Returns(true); + provider.Create(Arg.Any()).Returns(topic); + var topics = Substitute.For(); + topics.Get(Arg.Any()).Returns(provider); + return RunTables.Track(new MultilayerHashCache( + KnownCacheProviderNames.InMemory, + inner, + memory, + NullChangeTokenFactory.Instance, + topics, + new CacheEventFactory(Options.Create(cacheOptions)), + NullTelemetryProvider.Instance, + options, + options, + cacheOptions, + NullDistributedLock.Instance, + NullCachePolicyFactory.Instance, + clock, + NullLogger.Instance)); + } + + private static string? Text(object? entry) => (entry as ICacheEntry)?.Value is IDictionary fields ? fields["f"] : null; + + private static string[] DroppedReasons(RecordingTelemetryProvider telemetry) => + [.. telemetry.Metrics.Where(m => m.Name == "cache.peer_refresh.dropped").SelectMany(m => Enumerable.Repeat(m.Properties!["reason"], (int)m.Value))]; + + private static async Task ReadAsync(MultilayerHashCache cache, Replaced lookup) => lookup switch + { + Replaced.ItemByKey => await cache.GetItemAsync(Key, "f", Local, Ct), + Replaced.ItemBySpan => SpanReads.ReadItem(cache, Key, "f", Ct), + Replaced.Entry => (await cache.GetCacheEntryAsync(Key, Local, Ct)).Value?["f"], + _ => await cache.TimeToLiveAsync(Key, Ct), + }; + + /// Whether the call's answer came out of the entry that the store holds: its field, its presence, its expiration or its metadata. + private static async Task AnswersFromTheEntryAsync(MultilayerHashCache cache, HashCall call, bool span, Action generated) + { + CacheKey key = Key; + string[] fields = ["f"]; + Task> Generate(CancellationToken token) + { + generated(); + return Task.FromResult>(new Dictionary { ["g"] = "G" }); + } + + switch (call) + { + case HashCall.GetItem: + return (span ? SpanReads.ReadItem(cache, Key, "f", Ct) : await cache.GetItemAsync(key, "f", Local, Ct)) == "A-f"; + case HashCall.Get: + return (span ? SpanReads.ReadAll(cache, Key, Ct) : await cache.GetAsync(key, Local, Ct)).ContainsKey("f"); + case HashCall.GetFields: + return (span ? SpanReads.ReadFields(cache, Key, fields, Ct) : await cache.GetAsync(key, fields, Local, Ct)).ContainsKey("f"); + case HashCall.Entry: + return (span ? SpanReads.Entry(cache, Key, Ct) : await cache.GetCacheEntryAsync(key, Local, Ct)).Found; + case HashCall.Contains: + return span ? SpanReads.Contains(cache, Key, Ct) : await cache.ContainsAsync(key, Ct); + case HashCall.TimeToLive: + return (span ? SpanReads.TimeToLive(cache, Key, Ct) : await cache.TimeToLiveAsync(key, Ct)) is not null; + case HashCall.ExpireTime: + return (span ? SpanReads.ExpireTime(cache, Key, Ct) : await cache.ExpireTimeAsync(key, Ct)) is not null; + case HashCall.Metadata: + return (span ? SpanReads.Metadata(cache, Key, Ct) : await cache.GetMetadataAsync(key, Ct)) is not null; + case HashCall.GetOrAddBeforeTheKey: + return (await cache.GetOrAddAsync(key, Generate, Local, Ct)).ContainsKey("f"); + default: + return (await cache.GetOrAddAsync(key, Generate, Locked, Ct)).ContainsKey("f"); + } + } + + /// A string cache and a hash cache on one store and one clock, each over a tier that counts its calls and answers a miss. + private sealed class Harness : IDisposable + { + public Harness(Func memory) + { + Time = new ManualTimeProvider(new DateTimeOffset(2026, 1, 1, 0, 0, 0, TimeSpan.Zero)); + Clock = new CallClock(Time); + Memory = memory(Clock); + (var stringInner, StringTier) = FrameTierDouble.ForCache(); + (var hashInner, HashTier) = FrameTierDouble.ForHashCache(); + StringCache = InMemoryMultilayer.Cache(inner: stringInner, clock: Clock, memory: Memory); + HashCache = InMemoryMultilayer.HashCache(inner: hashInner, memory: Memory, clock: Clock); + } + + public ManualTimeProvider Time { get; } + + public CallClock Clock { get; } + + public IMemoryCacheFactory Memory { get; } + + public FrameTierDouble StringTier { get; } + + public FrameTierDouble HashTier { get; } + + public MultilayerCache StringCache { get; } + + public MultilayerHashCache HashCache { get; } + + public IMemoryCache Store => ((IHeldStore)Memory).Store; + + /// An observed entry whose value is a dictionary of the hash's type, judged now. + public ICacheEntry> ObservedHash(TimeSpan fresh, TimeSpan window, TimeSpan utcLeft) => + CacheEntryFactory.CreateObserved>( + new Dictionary { ["f"] = "A-f" }, + Clock.GetUtcNow() + utcLeft, + ObservedLife.From(Clock, Clock.GetTimestamp(), fresh, window), + EntryValidators.From("A-tag", null)); + + /// Has the string cache hold an observed entry under the key, and returns the entry the store holds. + public async Task HoldObservedAsync(TimeSpan fresh, TimeSpan window, TimeSpan utcLeft) + { + var observed = ObservedHash(fresh, window, utcLeft); + if (Memory is PlainMemoryCacheFactory plain) + { + plain.Store.Put(Key, observed); + return observed; + } + + StringTier.Held = observed; + (await StringCache.GetAsync>(Key, Local, Ct)).Should().ContainKey("f"); + StringTier.Held = null; + Store.TryGetValue(Key, out var held).Should().BeTrue(); + held.Should().BeAssignableTo(); + return held; + } + + public void Dispose() + { + Clock.Let(); + HashCache.Dispose(); + StringCache.Dispose(); + } + } +} + +/// A frame-tier hash cache that answers a set expiration to ExpireTimeAsync. +internal class ExpiringHashTier : FrameTierDouble +{ + public DateTimeOffset Expiration { get; set; } + + protected override object? Invoke(MethodInfo? targetMethod, object?[]? args) + { + var answer = base.Invoke(targetMethod, args); + return targetMethod!.Name == nameof(IHashCache.ExpireTimeAsync) ? new ValueTask(Expiration) : answer; + } +} diff --git a/tests/UiPath.Caching.Tests/ObservedEntryLocalTests.cs b/tests/UiPath.Caching.Tests/ObservedEntryLocalTests.cs new file mode 100644 index 00000000..5d17ebc4 --- /dev/null +++ b/tests/UiPath.Caching.Tests/ObservedEntryLocalTests.cs @@ -0,0 +1,270 @@ +using Microsoft.Extensions.Caching.Memory; +using Microsoft.Extensions.Primitives; +using UiPath.Caching.Tests.Fakes; + +namespace UiPath.Caching.Tests; + +/// The local tier's side of the monotonic bounds of an observed value: the lookup that ends at the bound, the kept value that outlives it only as far as the bounds allow, and the plain entry that pays for none of it. +[Collection(AllocationCollection.Name)] +public class ObservedEntryLocalTests +{ + /// The allocated size of a plain entry on the base build: the header, its marks, the value, the expiration and the metadata. + private const long PlainEntryBytes = 80; + + private static readonly TimeSpan Fresh = TimeSpan.FromSeconds(60); + private static readonly TimeSpan Window = TimeSpan.FromSeconds(120); + private static readonly CachePolicy Local = new() { LocalExpiration = TimeSpan.FromHours(1) }; + private static readonly CachePolicy FailSafe = new() { LocalExpiration = TimeSpan.FromHours(1), FailSafeEnabled = true, FailSafeMaxStaleAge = TimeSpan.FromHours(2), FailSafeCooldown = TimeSpan.Zero }; + private static readonly CachePolicy TenSeconds = new() { LocalExpiration = TimeSpan.FromHours(1), FailSafeEnabled = true, FailSafeMaxStaleAge = TimeSpan.FromSeconds(10), FailSafeCooldown = TimeSpan.Zero }; + + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + [Fact] + public async Task MemoryCache_asks_a_token_without_callbacks_on_an_ordinary_lookup() + { + using var memory = new MemoryCache(new MemoryCacheOptions()); + var token = new AskedToken(); + var left = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + using (var entry = memory.CreateEntry("k")) + { + entry.Value = "A"; + entry.ExpirationTokens.Add(token); + entry.RegisterPostEvictionCallback((_, _, reason, _) => left.TrySetResult(reason)); + } + + var asked = token.Asked; + memory.TryGetValue("k", out _).Should().BeTrue(); + token.Asked.Should().Be(asked + 1); + memory.TryGetValue("k", out _).Should().BeTrue(); + token.Asked.Should().Be(asked + 2); + + token.Changed = true; + memory.TryGetValue("k", out _).Should().BeFalse(); + (await left.Task.WaitAsync(Ct)).Should().Be(EvictionReason.TokenExpired); + } + + [Fact] + public async Task MemoryCache_returns_a_replaced_entry_whose_token_has_changed() + { + using var memory = new MemoryCache(new MemoryCacheOptions()); + var token = new AskedToken(); + using (var entry = memory.CreateEntry("k")) + { + entry.Value = "A"; + entry.ExpirationTokens.Add(token); + } + + token.Block(); + var reader = Task.Run(() => memory.TryGetValue("k", out var value) ? value : null, Ct); + await token.Entered.WaitAsync(TimeSpan.FromSeconds(30), Ct); + memory.Set("k", "B"); + token.Changed = true; + token.Release(); + + (await reader).Should().Be("A"); + } + + [Fact] + public async Task A_plain_entry_gets_no_token_and_keeps_its_size() + { + var plain = new PlainMemoryCacheFactory(); + using var harness = new ObservedHarness(_ => plain); + + await harness.Cache.SetAsync(ObservedHarness.Key, "v", Local, Ct); + + plain.Store.TryGetValue(ObservedHarness.Key, out var stored).Should().BeTrue(); + ((ILocalEntry)stored!).Observed.Should().Be(default(ObservedLife)); + plain.Store.TokensOf(ObservedHarness.Key).Should().Be(0); + + var factory = new CacheEntryFactory(); + var expiration = DateTimeOffset.UnixEpoch.AddDays(1); + GC.KeepAlive(factory.Create("v", expiration)); + var before = GC.GetAllocatedBytesForCurrentThread(); + var entry = factory.Create("v", expiration); + var allocated = GC.GetAllocatedBytesForCurrentThread() - before; + GC.KeepAlive(entry); + allocated.Should().Be(PlainEntryBytes); + } + + [Theory] + [InlineData(0)] + [InlineData(-10)] + [InlineData(-3600)] + public async Task An_observed_entry_misses_once_its_monotonic_freshness_ends(int utcStepSeconds) + { + using var harness = new ObservedHarness(); + await harness.AdoptAsync(harness.Observed("A", Fresh, Window), Local); + harness.Time.StepUtc(TimeSpan.FromSeconds(utcStepSeconds)); + + harness.Time.Advance(Fresh - TimeSpan.FromSeconds(1)); + var before = harness.Tier.Total; + (await harness.Cache.GetAsync(ObservedHarness.Key, Local, Ct)).Should().Be("A"); + harness.Tier.Total.Should().Be(before, "1 second before FreshUntil the lookup hits"); + + harness.Time.Advance(TimeSpan.FromSeconds(1)); + (await harness.Cache.GetAsync(ObservedHarness.Key, Local, Ct)).Should().BeNull(); + harness.Tier.Total.Should().Be(before + 1, "at FreshUntil the lookup misses and asks the inner tier"); + } + + [Fact] + public async Task A_UTC_clock_set_forward_still_ends_an_observed_entry_early() + { + using var harness = new ObservedHarness(); + await harness.AdoptAsync(harness.Observed("A", Fresh, Window), Local); + + harness.Time.Advance(TimeSpan.FromSeconds(10)); + harness.Time.StepUtc(TimeSpan.FromHours(1)); + + var before = harness.Tier.Total; + (await harness.Cache.GetAsync(ObservedHarness.Key, Local, Ct)).Should().BeNull(); + harness.Tier.Total.Should().Be(before + 1); + } + + [Fact] + public void NewEntry_of_an_observed_entry_keeps_its_bounds() + { + var observed = new ObservedLife(100, 300); + var entry = CacheEntryFactory.CreateObserved("A", DateTimeOffset.UnixEpoch.AddDays(1), observed); + + var rebuilt = entry.NewEntry(DateTimeOffset.UnixEpoch.AddDays(2)); + + rebuilt.Should().BeAssignableTo().Which.Observed.Should().Be(observed); + rebuilt.Expiration.Should().Be(DateTimeOffset.UnixEpoch.AddDays(2)); + } + + [Theory] + [InlineData(-1)] + [InlineData(-3600 * 10_000_000L)] + public async Task An_observed_entry_that_leaves_on_its_bound_keeps_its_stale_value(long utcStepTicks) + { + using var harness = new ObservedHarness(clock => new LoggedMemoryCacheFactory(clock)); + var memory = (LoggedMemoryCacheFactory)harness.Memory!; + await harness.AdoptAsync(harness.Observed("A", Fresh, Window), FailSafe); + + harness.Time.Advance(Fresh); + harness.Time.StepUtc(TimeSpan.FromTicks(utcStepTicks)); + + var before = harness.Tier.Total; + (await harness.Cache.GetAsync(ObservedHarness.Key, FailSafe, Ct)).Should().BeNull(); + harness.Tier.Total.Should().Be(before + 1); + await memory.Changes.WaitUntil(() => memory.Evictions.Count >= 1).WaitAsync(TimeSpan.FromSeconds(30), Ct); + memory.Evictions[0].Reason.Should().Be(EvictionReason.TokenExpired); + + (await harness.Cache.GetOrAddAsync(ObservedHarness.Key, Throwing, Fresh, FailSafe, Ct)).Should().Be("A", "the bound is the entry's own end, and the kept value is charged as it is for an expiry"); + } + + [Fact] + public async Task A_peer_change_at_the_bound_still_drops_the_kept_value() + { + var token = new TestChangeToken { ActiveChangeCallbacks = true }; + using var harness = new ObservedHarness(tokens: new TestChangeTokenFactory((_, _) => token)); + await harness.AdoptAsync(harness.Observed("A", Fresh, Window), FailSafe); + + harness.Time.Advance(Fresh); + harness.Time.StepUtc(TimeSpan.FromHours(-1)); + token.HasChanged = true; + token.InvokeCallbacks(); + + (await harness.Cache.GetAsync(ObservedHarness.Key, FailSafe, Ct)).Should().BeNull(); + + var act = async () => await harness.Cache.GetOrAddAsync(ObservedHarness.Key, Throwing, Fresh, FailSafe, Ct); + await act.Should().ThrowAsync("a peer's change is no expiry, whatever the bound did"); + } + + [Fact] + public async Task A_kept_value_of_an_observed_entry_is_served_until_KeptUntil_and_not_after() + { + using var harness = new ObservedHarness(); + await harness.AdoptAsync(harness.Observed("A", Fresh, Window), FailSafe); + harness.Time.StepUtc(TimeSpan.FromHours(-1)); + + harness.Time.Advance(Fresh + TimeSpan.FromSeconds(1)); + (await harness.Cache.GetAsync(ObservedHarness.Key, FailSafe, Ct)).Should().BeNull("a read is never served a stale value"); + + harness.Time.Advance(Window - TimeSpan.FromSeconds(2)); + (await harness.Cache.GetOrAddAsync(ObservedHarness.Key, Throwing, Fresh, FailSafe, Ct)).Should().Be("A", "1 second before KeptUntil"); + (await harness.Cache.GetAsync(ObservedHarness.Key, FailSafe, Ct)).Should().BeNull(); + + harness.Time.Advance(TimeSpan.FromSeconds(1)); + var act = async () => await harness.Cache.GetOrAddAsync(ObservedHarness.Key, Throwing, Fresh, FailSafe, Ct); + await act.Should().ThrowAsync("at KeptUntil"); + } + + [Theory] + [InlineData(60)] + [InlineData(-4)] + public async Task A_callers_stale_age_counts_monotonic_time_since_FreshUntil(int freshSeconds) + { + using var harness = new ObservedHarness(); + var fresh = TimeSpan.FromSeconds(freshSeconds); + await harness.AdoptAsync(harness.Observed("A", fresh, Window), TenSeconds); + harness.Time.StepUtc(TimeSpan.FromHours(-1)); + + harness.Time.Advance(fresh + TimeSpan.FromSeconds(9)); + (await harness.Cache.GetAsync(ObservedHarness.Key, TenSeconds, Ct)).Should().BeNull(); + (await harness.Cache.GetOrAddAsync(ObservedHarness.Key, Throwing, Fresh, TenSeconds, Ct)).Should().Be("A", "9 seconds after FreshUntil"); + + harness.Time.Advance(TimeSpan.FromSeconds(2)); + var act = async () => await harness.Cache.GetOrAddAsync(ObservedHarness.Key, Throwing, Fresh, TenSeconds, Ct); + await act.Should().ThrowAsync("11 seconds after FreshUntil"); + } + + [Fact] + public async Task A_kept_value_of_a_plain_entry_is_bounded_as_today() + { + using var harness = new ObservedHarness(); + var policy = new CachePolicy { LocalExpiration = Fresh, FailSafeEnabled = true, FailSafeMaxStaleAge = TimeSpan.FromSeconds(10), FailSafeCooldown = TimeSpan.Zero }; + await harness.Cache.SetAsync(ObservedHarness.Key, "v", policy, Ct); + + harness.Time.Advance(Fresh + TimeSpan.FromSeconds(9)); + (await harness.Cache.GetOrAddAsync(ObservedHarness.Key, Throwing, Fresh, policy, Ct)).Should().Be("v"); + + harness.Time.Advance(TimeSpan.FromSeconds(2)); + var act = async () => await harness.Cache.GetOrAddAsync(ObservedHarness.Key, Throwing, Fresh, policy, Ct); + await act.Should().ThrowAsync(); + } + + private static Task Throwing(CancellationToken token) => throw new InvalidOperationException("The generator failed."); + + /// A token that counts how often it is asked and that can hold the next asker until the test lets it go. + private sealed class AskedToken : IChangeToken + { + private readonly ManualResetEventSlim _release = new(true); + private readonly TaskCompletionSource _entered = new(TaskCreationOptions.RunContinuationsAsynchronously); + private int _asked; + private int _blocking; + + public int Asked => Volatile.Read(ref _asked); + + public bool Changed { get; set; } + + public Task Entered => _entered.Task; + + public bool ActiveChangeCallbacks => false; + + public bool HasChanged + { + get + { + Interlocked.Increment(ref _asked); + if (Interlocked.CompareExchange(ref _blocking, 0, 1) == 1) + { + _entered.TrySetResult(); + _release.Wait(TestContext.Current.CancellationToken); + } + + return Changed; + } + } + + public void Block() + { + _release.Reset(); + Volatile.Write(ref _blocking, 1); + } + + public void Release() => _release.Set(); + + public IDisposable RegisterChangeCallback(Action callback, object? state) => throw new NotSupportedException(); + } +} diff --git a/tests/UiPath.Caching.Tests/ObservedEntryReplacementTests.cs b/tests/UiPath.Caching.Tests/ObservedEntryReplacementTests.cs new file mode 100644 index 00000000..96f8a599 --- /dev/null +++ b/tests/UiPath.Caching.Tests/ObservedEntryReplacementTests.cs @@ -0,0 +1,363 @@ +using Microsoft.Extensions.Caching.Memory; +using UiPath.Caching.Tests.Fakes; + +namespace UiPath.Caching.Tests; + +/// An observed entry that a lookup got back after it was replaced, or from a store that expires nothing, is refused once its bound has passed: the layered cache tests the entry itself and does not trust the store. +public class ObservedEntryReplacementTests +{ + private static readonly TimeSpan Fresh = TimeSpan.FromSeconds(60); + private static readonly TimeSpan Window = TimeSpan.FromSeconds(120); + private static readonly TimeSpan Far = TimeSpan.FromHours(2); + private static readonly CachePolicy Local = new() { LocalExpiration = TimeSpan.FromHours(1) }; + private static readonly CachePolicy Locked = new() { LocalExpiration = TimeSpan.FromHours(1), Lock = new LockProfile { DistributedLockEnabled = true } }; + + public enum Lookup + { + Key, + Span, + Entry, + Batch, + TimeToLive, + } + + public enum Call + { + Get, + Entry, + Batch, + Entries, + GetOrAddBeforeTheKey, + GetOrAddUnderTheKey, + GetOrAddBatch, + Contains, + TimeToLive, + ExpireTime, + TryAdd, + } + + public enum NoTier + { + Snapshot, + Fill, + Change, + } + + public enum Latching + { + Fill, + Change, + } + + public enum Held + { + Observed, + Plain, + Nothing, + } + + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + [Theory] + [InlineData(Lookup.Key, 10_000, 5_000, 1_000)] + [InlineData(Lookup.Key, 1, 1_000, 1_000)] + [InlineData(Lookup.Key, 0, 5_000, 60_000)] + [InlineData(Lookup.Span, 10_000, 5_000, 1_000)] + [InlineData(Lookup.Span, 1, 1_000, 1_000)] + [InlineData(Lookup.Span, 0, 5_000, 60_000)] + [InlineData(Lookup.Entry, 10_000, 5_000, 1_000)] + [InlineData(Lookup.Entry, 1, 1_000, 1_000)] + [InlineData(Lookup.Entry, 0, 5_000, 60_000)] + [InlineData(Lookup.Batch, 10_000, 5_000, 1_000)] + [InlineData(Lookup.Batch, 1, 1_000, 1_000)] + [InlineData(Lookup.Batch, 0, 5_000, 60_000)] + [InlineData(Lookup.TimeToLive, 10_000, 5_000, 1_000)] + [InlineData(Lookup.TimeToLive, 1, 1_000, 1_000)] + [InlineData(Lookup.TimeToLive, 0, 5_000, 60_000)] + public async Task A_replaced_observed_entry_is_not_returned_after_FreshUntil(Lookup lookup, int utcBackMs, int advanceMs, int utcLeftMs) + { + // The span form reads the store by span only when it is a MemoryCache itself, so that row has no eviction log. + using var harness = new ObservedHarness(clock => lookup == Lookup.Span ? new OpenMemoryCacheFactory(clock) : new LoggedMemoryCacheFactory(clock)); + await harness.AdoptAsync(harness.Observed("A", TimeSpan.FromSeconds(1), Window, TimeSpan.FromMilliseconds(utcLeftMs)), Local); + harness.Time.StepUtc(TimeSpan.FromMilliseconds(-utcBackMs)); + harness.Time.Advance(TimeSpan.FromMilliseconds(advanceMs)); + + harness.Clock.Hold(); + var read = Task.Run(() => ReadAsync(harness.Cache, lookup), Ct); + await Task.WhenAny(harness.Clock.Entered, read); + harness.Clock.Entered.IsCompleted.Should().BeTrue("the bound is a token whose check reads the clock inside the lookup"); + harness.Store.Set(ObservedHarness.Key, new CacheEntryFactory().Create("B", harness.Clock.GetUtcNow() + Far)); + var before = harness.Tier.Total; + harness.Clock.Let(); + var answer = await read; + + switch (lookup) + { + case Lookup.Key or Lookup.Entry: + answer.Should().Be("B"); + harness.Tier.Total.Should().Be(before, "the second look finds B and sends nothing"); + break; + case Lookup.Span: + answer.Should().NotBe("A"); + break; + default: + answer.Should().BeNull(); + harness.Tier.Total.Should().Be(before + 1, "a batch read and the TTL look once, and go on to the inner tier"); + break; + } + + var after = harness.Tier.Total; + (await harness.Cache.GetAsync(ObservedHarness.Key, Local, Ct)).Should().Be("B"); + harness.Tier.Total.Should().Be(after); + if (lookup != Lookup.Span) + { + var memory = (LoggedMemoryCacheFactory)harness.Memory!; + await memory.Changes.WaitUntil(() => memory.Evictions.Count >= 1).WaitAsync(TimeSpan.FromSeconds(30), Ct); + memory.Evictions.Where(e => Text(e.Value) == "A").Should().ContainSingle().Which.Reason.Should().Be(EvictionReason.Replaced); + memory.Evictions.Where(e => Text(e.Value) == "B").Should().BeEmpty(); + } + } + + [Theory] + [InlineData(Call.Get, true)] + [InlineData(Call.Get, false)] + [InlineData(Call.Entry, true)] + [InlineData(Call.Entry, false)] + [InlineData(Call.Batch, true)] + [InlineData(Call.Batch, false)] + [InlineData(Call.Entries, true)] + [InlineData(Call.Entries, false)] + [InlineData(Call.GetOrAddBeforeTheKey, true)] + [InlineData(Call.GetOrAddBeforeTheKey, false)] + [InlineData(Call.GetOrAddUnderTheKey, true)] + [InlineData(Call.GetOrAddUnderTheKey, false)] + [InlineData(Call.GetOrAddBatch, true)] + [InlineData(Call.GetOrAddBatch, false)] + [InlineData(Call.Contains, true)] + [InlineData(Call.Contains, false)] + [InlineData(Call.TimeToLive, true)] + [InlineData(Call.TimeToLive, false)] + [InlineData(Call.ExpireTime, true)] + [InlineData(Call.ExpireTime, false)] + [InlineData(Call.TryAdd, true)] + [InlineData(Call.TryAdd, false)] + public async Task Every_local_hit_site_refuses_a_post_bound_entry_whatever_the_store_does(Call call, bool beforeTheBound) + { + var plain = new PlainMemoryCacheFactory(); + using var harness = new ObservedHarness(_ => plain); + plain.Store.Put(ObservedHarness.Key, harness.Observed("A", Fresh, Window, Far)); + harness.Time.Advance(beforeTheBound ? Fresh - TimeSpan.FromSeconds(1) : Fresh + TimeSpan.FromSeconds(1)); + if (call == Call.GetOrAddUnderTheKey) + { + plain.Store.HideFor(1); + } + + var before = harness.Tier.Total; + var fromTheEntry = await AnswersFromTheEntryAsync(harness.Cache, call); + + fromTheEntry.Should().Be(beforeTheBound); + if (beforeTheBound) + { + if (call != Call.GetOrAddUnderTheKey) + { + harness.Tier.Total.Should().Be(before, "1 second before FreshUntil the call answers from the entry"); + } + } + else + { + harness.Tier.Total.Should().BeGreaterThan(before, "after FreshUntil the call goes on to the inner tier"); + plain.Store.Removed.Should().BeEmpty(); + } + } + + [Theory] + [InlineData(NoTier.Snapshot, true)] + [InlineData(NoTier.Snapshot, false)] + [InlineData(NoTier.Fill, true)] + [InlineData(NoTier.Fill, false)] + [InlineData(NoTier.Change, true)] + [InlineData(NoTier.Change, false)] + public async Task A_cache_with_no_shared_tier_refuses_a_post_bound_entry_too(NoTier call, bool beforeTheBound) + { + var plain = new PlainMemoryCacheFactory(); + using var harness = new ObservedHarness(_ => plain, shared: false); + plain.Store.Put(ObservedHarness.Key, harness.Observed("A", Fresh, Window, Far)); + harness.Time.Advance(beforeTheBound ? Fresh - TimeSpan.FromSeconds(1) : Fresh + TimeSpan.FromSeconds(1)); + var lifetime = TimeSpan.FromMinutes(5); + + switch (call) + { + case NoTier.Snapshot: + var snapshot = await harness.Cache.ReadSnapshotAsync(ObservedHarness.Key, Local, Ct); + snapshot.Outcome.Should().Be(beforeTheBound ? SnapshotOutcome.Found : SnapshotOutcome.Absent); + return; + case NoTier.Fill: + var fill = await harness.Cache.TryFillAsync(ObservedHarness.Key, "F", lifetime, Local, Ct); + fill.Outcome.Should().Be(beforeTheBound ? FillOutcome.Existed : FillOutcome.Added); + break; + default: + var change = await harness.Cache.SetIfChangedAsync(ObservedHarness.Key, "A", EqualityComparer.Default, lifetime, Local, Ct); + (change.Outcome == ChangeOutcome.Unchanged).Should().Be(beforeTheBound); + break; + } + + plain.Store.TryGetValue(ObservedHarness.Key, out var held).Should().BeTrue(); + if (!beforeTheBound) + { + held.Should().NotBeAssignableTo("the store holds the value of the fill or of the change"); + ((ICacheEntry)held!).Value.Should().Be(call == NoTier.Fill ? "F" : "A"); + } + } + + [Theory] + [InlineData(Latching.Fill, Held.Observed, true)] + [InlineData(Latching.Change, Held.Observed, true)] + [InlineData(Latching.Fill, Held.Plain, false)] + [InlineData(Latching.Change, Held.Plain, false)] + [InlineData(Latching.Fill, Held.Nothing, false)] + public async Task A_cache_with_no_shared_tier_latches_when_it_answers_from_an_observed_entry(Latching call, Held held, bool latches) + { + var plain = new PlainMemoryCacheFactory(); + using var harness = new ObservedHarness(_ => plain, shared: false); + var expiration = harness.Clock.GetUtcNow() + Far; + if (held == Held.Observed) + { + plain.Store.Put(ObservedHarness.Key, harness.Observed("A", Fresh, Window, Far)); + } + else if (held == Held.Plain) + { + plain.Store.Put(ObservedHarness.Key, new CacheEntryFactory().Create("A", expiration)); + } + + harness.Time.Advance(Fresh - TimeSpan.FromSeconds(1)); + FrameTiers.MayHaveMet(harness.Cache).Should().BeFalse(); + + var lifetime = TimeSpan.FromMinutes(5); + if (call == Latching.Fill) + { + await harness.Cache.TryFillAsync(ObservedHarness.Key, "F", lifetime, Local, Ct); + } + else + { + await harness.Cache.SetIfChangedAsync(ObservedHarness.Key, "A", EqualityComparer.Default, lifetime, Local, Ct); + } + + FrameTiers.MayHaveMet(harness.Cache).Should().Be(latches); + InnerTier.For(harness.Cache).MayHaveMetWindowedFrame.Should().Be(latches); + + plain.Store.Remove(ObservedHarness.Key); + FrameTiers.MayHaveMet(harness.Cache).Should().Be(latches, "the latch never goes back"); + } + + [Fact] + public async Task A_presence_test_leaves_a_newer_entry_alone() + { + using var harness = new ObservedHarness(clock => new OpenMemoryCacheFactory(clock)); + await harness.AdoptAsync(harness.Observed("A", TimeSpan.FromSeconds(1), Window, Far), Local); + harness.Time.Advance(TimeSpan.FromSeconds(5)); + var armed = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + harness.Tier.OnCall = member => + { + if (member == nameof(ICache.TryFillAsync)) + { + harness.Clock.Hold(); + armed.TrySetResult(); + } + }; + + // The inner fill fails, so the generated value is kept unless the key has an entry. + var fill = Task.Run(async () => await harness.Cache.TryFillAsync(ObservedHarness.Key, "G", TimeSpan.FromMinutes(5), Local, Ct), Ct); + try + { + // The hold is armed on the fill's thread, which replaces the task Entered answers: read it only after. + await Task.WhenAny(armed.Task, fill); + await Task.WhenAny(harness.Clock.Entered, fill); + harness.Clock.Entered.IsCompleted.Should().BeTrue("the bound is a token whose check reads the clock inside the presence lookup"); + harness.Store.Set(ObservedHarness.Key, new CacheEntryFactory().Create("B", harness.Clock.GetUtcNow() + Far)); + } + finally + { + // A failed assert must not leave a later reader held. + harness.Clock.Let(); + } + + await fill; + + var before = harness.Tier.Total; + (await harness.Cache.GetAsync(ObservedHarness.Key, Local, Ct)).Should().Be("B"); + harness.Tier.Total.Should().Be(before); + } + + [Fact] + public async Task A_plain_hit_reads_no_timestamp_and_an_observed_hit_reads_two() + { + using var harness = new ObservedHarness(); + await harness.Cache.SetAsync(ObservedHarness.Key, "plain", Local, Ct); + harness.Clock.ResetCalls(); + + (await harness.Cache.GetAsync(ObservedHarness.Key, Local, Ct)).Should().Be("plain"); + SpanReads.Read(harness.Cache, ObservedHarness.Key, Ct).Should().Be("plain"); + harness.Clock.Calls.Should().Be(0, "a plain hit reads no timestamp, by key and by span"); + + using var held = new ObservedHarness(); + await held.AdoptAsync(held.Observed("A", Fresh, Window, Far), Local); + held.Clock.ResetCalls(); + (await held.Cache.GetAsync(ObservedHarness.Key, Local, Ct)).Should().Be("A"); + held.Clock.Calls.Should().BeInRange(1, 2, "an observed hit reads the clock for its bound, and at most once more for the token"); + + using var hashes = new ObservedHarness(); + using var hash = InMemoryMultilayer.HashCache(clock: hashes.Clock); + await hash.SetAsync(ObservedHarness.Key, new Dictionary { ["f"] = "v" }, Local, Ct); + hashes.Clock.ResetCalls(); + (await hash.GetItemAsync(ObservedHarness.Key, "f", Local, Ct)).Should().Be("v"); + hashes.Clock.Calls.Should().Be(0, "a local hit of the hash cache reads no timestamp either"); + } + + private static string? Text(object? entry) => (entry as ICacheEntry)?.Value as string; + + private static async Task ReadAsync(MultilayerCache cache, Lookup lookup) => lookup switch + { + Lookup.Key => await cache.GetAsync(ObservedHarness.Key, Local, Ct), + Lookup.Span => SpanReads.Read(cache, ObservedHarness.Key, Ct), + Lookup.Entry => (await cache.GetCacheEntryAsync(ObservedHarness.Key, Local, Ct)).Value, + Lookup.Batch => (await cache.GetAsync([new CacheKey(ObservedHarness.Key)], Local, Ct))[0].Value, + _ => await cache.TimeToLiveAsync(ObservedHarness.Key, Ct), + }; + + /// Whether the call's answer came out of the entry that the store holds: the entry's value, its presence or its expiration. + private static async Task AnswersFromTheEntryAsync(MultilayerCache cache, Call call) + { + CacheKey key = ObservedHarness.Key; + switch (call) + { + case Call.Get: + return await cache.GetAsync(key, Local, Ct) == "A"; + case Call.Entry: + return await cache.GetCacheEntryAsync(key, Local, Ct) is { Found: true, Value: "A" }; + case Call.Batch: + return (await cache.GetAsync([key], Local, Ct))[0].Value == "A"; + case Call.Entries: + return (await cache.GetCacheEntriesAsync([key], Local, Ct))[0].Value is { Found: true, Value: "A" }; + case Call.GetOrAddBeforeTheKey: + return await cache.GetOrAddAsync(key, Generated, Local, Ct) == "A"; + case Call.GetOrAddUnderTheKey: + return await cache.GetOrAddAsync(key, Generated, Locked, Ct) == "A"; + case Call.GetOrAddBatch: + var added = await cache.GetOrAddAsync([new KeyValuePair(key, 1)], GeneratedBatch, Local, Ct); + return added[0].Value == "A"; + case Call.Contains: + return await cache.ContainsAsync(key, Ct); + case Call.TimeToLive: + return await cache.TimeToLiveAsync(key, Ct) is not null; + case Call.ExpireTime: + return await cache.ExpireTimeAsync(key, Ct) is not null; + default: + return !await cache.TryAddAsync(key, "N", Local, Ct); + } + } + + private static Task Generated(CancellationToken token) => Task.FromResult("G"); + + private static Task[]> GeneratedBatch(int[] states, CancellationToken token) => + Task.FromResult(states.Select(state => new KeyValuePair(state, "G")).ToArray()); +} diff --git a/tests/UiPath.Caching.Tests/ObservedLifeTests.cs b/tests/UiPath.Caching.Tests/ObservedLifeTests.cs new file mode 100644 index 00000000..2fda06d5 --- /dev/null +++ b/tests/UiPath.Caching.Tests/ObservedLifeTests.cs @@ -0,0 +1,67 @@ +namespace UiPath.Caching.Tests; + +/// The bounds an anchored judgment hands on count from the judgment on the monotonic clock, so no reading of the UTC clock lifts them past the key's own end. +public class ObservedLifeTests +{ + private static readonly TimeSpan Ttl = TimeSpan.FromSeconds(120); + private static readonly TimeSpan Window = TimeSpan.FromSeconds(60); + + public static TheoryData Judgments() + { + var data = new TheoryData(); + foreach (var utcStep in new[] { 0, 3600, -3600 }) + { + foreach (var elapsed in new[] { 0, 5 }) + { + foreach (var frameAhead in new[] { 86400, 1 }) + { + data.Add(utcStep, elapsed, frameAhead); + } + } + } + + return data; + } + + [Theory] + [MemberData(nameof(Judgments))] + public void The_bounds_never_pass_the_send_plus_the_ttl(int utcStepSeconds, int elapsedSeconds, int frameAheadSeconds) + { + var clock = new ManualTimeProvider(new DateTimeOffset(2026, 1, 1, 0, 0, 0, TimeSpan.Zero)); + var sentAt = clock.GetTimestamp(); + var frameExpiration = clock.GetUtcNow().AddSeconds(frameAheadSeconds); + clock.Advance(TimeSpan.FromSeconds(elapsedSeconds)); + clock.StepUtc(TimeSpan.FromSeconds(utcStepSeconds)); + + var observed = Judge(clock, Ttl - TimeSpan.FromSeconds(elapsedSeconds), Window, frameExpiration); + + var send = clock.TimestampFrequency; + observed.FreshUntil.Should().BeLessThanOrEqualTo(sentAt + (long)((Ttl - Window).TotalSeconds * send)); + observed.KeptUntil.Should().BeLessThanOrEqualTo(sentAt + (long)(Ttl.TotalSeconds * send)); + (observed.KeptUntil - observed.FreshUntil).Should().Be((long)(Window.TotalSeconds * send)); + } + + [Fact] + public void An_expired_frame_inside_its_window_is_aged_by_its_ttl_at_least() + { + var clock = new ManualTimeProvider(new DateTimeOffset(2026, 1, 1, 0, 0, 0, TimeSpan.Zero)); + var ttl = TimeSpan.FromSeconds(20); + var window = TimeSpan.FromSeconds(60); + var frameExpiration = clock.GetUtcNow().AddSeconds(10); + clock.StepUtc(TimeSpan.FromHours(-1)); + + var observed = Judge(clock, ttl, window, frameExpiration); + + observed.Age(clock, clock.GetTimestamp()).Should().BeGreaterThanOrEqualTo(TimeSpan.FromSeconds(40)); + } + + /// The judgment of RedisCache.JudgeFrame: the key's deadline is the UTC reading plus the life left, and the logical expiration is the frame's own, held under the deadline less the window. + private static ObservedLife Judge(TimeProvider clock, TimeSpan remaining, TimeSpan window, DateTimeOffset frameExpiration) + { + var judgedAt = clock.GetTimestamp(); + var now = clock.GetUtcNow(); + var deadline = now + remaining; + var logical = new DateTimeOffset(Math.Min(frameExpiration.UtcTicks, Math.Max(0, deadline.UtcTicks - window.Ticks)), TimeSpan.Zero); + return ObservedLife.From(clock, judgedAt, logical - now, window); + } +} diff --git a/tests/UiPath.Caching.Tests/PeerRefreshEventTests.cs b/tests/UiPath.Caching.Tests/PeerRefreshEventTests.cs new file mode 100644 index 00000000..c3186ddd --- /dev/null +++ b/tests/UiPath.Caching.Tests/PeerRefreshEventTests.cs @@ -0,0 +1,312 @@ +using Microsoft.Extensions.Caching.Memory; +using Microsoft.Extensions.Logging.Abstractions; +using Microsoft.Extensions.Options; +using UiPath.Caching.Tests.Fakes; + +namespace UiPath.Caching.Tests; + +/// An event that carries an expiration or metadata drops a peer's copy over a shared tier, so its next read asks that tier; with no shared tier, or in a hash, it renews the copy. +public class PeerRefreshEventTests +{ + private const string Key = "k"; + private static readonly DateTimeOffset Start = new(2026, 1, 1, 0, 0, 0, TimeSpan.Zero); + private static readonly CachePolicy HourCap = new() { LocalExpiration = TimeSpan.FromHours(1) }; + private static readonly CachePolicy TwoHourCap = new() { LocalExpiration = TimeSpan.FromHours(2) }; + + public enum Sender + { + CacheRefreshed, + MetadataUpdatedWithExpiration, + MetadataUpdatedWithMetadataAlone, + CacheSetWithExpiration, + CustomTokenFactory, + } + + public enum InnerRefresh + { + AnswersFalse, + Throws, + NeverAnswers, + } + + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + [Fact] + public async Task A_refresh_event_never_renews_a_peers_copy_on_a_shared_tier() + { + var clock = new ManualTimeProvider(Start); + using var shared = new CachePeers(clock); + var a = shared.Add("a"); + var b = shared.Add("b"); + shared.Store.Remaining[Key] = TimeSpan.FromSeconds(10); + await Holding(shared, b, HourCap); + a.Inner.OnRefresh = (_, _) => Task.FromResult(false); + shared.AutoDeliver = false; + + (await a.Cache.RefreshAsync(Key, TimeSpan.FromHours(1), null, Ct)).Should().BeFalse(); + shared.Deliver(b, RefreshEvent(a)); + + b.Local.TryGetValue(Key, out _).Should().BeFalse(); + clock.Advance(TimeSpan.FromSeconds(11)); + b.Local.TryGetValue(Key, out _).Should().BeFalse(); + shared.Store.RemoveQuietly(Key); + var before = b.Inner.SingleReads; + (await b.Cache.GetAsync(Key, HourCap, Ct)).Should().BeNull(); + b.Inner.SingleReads.Should().Be(before + 1); + } + + [Theory] + [InlineData(Sender.CacheRefreshed)] + [InlineData(Sender.MetadataUpdatedWithExpiration)] + [InlineData(Sender.MetadataUpdatedWithMetadataAlone)] + [InlineData(Sender.CacheSetWithExpiration)] + [InlineData(Sender.CustomTokenFactory)] + public async Task An_event_that_carries_an_expiration_or_metadata_drops_the_copy_whatever_its_type_or_sender(Sender sender) + { + using var peers = new CachePeers(new ManualTimeProvider(Start)); + var b = peers.Add("b", tokens: sender == Sender.CustomTokenFactory ? static inner => new CustomTokens(inner) : null); + await Holding(peers, b, HourCap); + var (publisher, sent, events) = Publisher(); + var options = new CacheEntryOptions { CacheKey = Key, CallerKey = Key, TopicKey = new TopicKey("topic"), Expiration = Start.AddHours(1) }; + + switch (sender) + { + case Sender.CacheRefreshed or Sender.CustomTokenFactory: + await publisher.CacheRefreshedAsync(options); + break; + case Sender.MetadataUpdatedWithExpiration: + await publisher.MetadataUpdatedAsync(options); + break; + case Sender.MetadataUpdatedWithMetadataAlone: + await publisher.MetadataUpdatedAsync(options with { Expiration = default, Metadata = new Dictionary { ["m"] = "1" } }); + break; + case Sender.CacheSetWithExpiration: + sent.Add(events.Create(KnownCacheProviderNames.InMemoryRedis, KnownEventTypes.CacheSet, new CacheEventData(Key, new Dictionary { [KnownFieldNames.ExpirationKey] = Start.AddHours(1) }))); + break; + } + + peers.Deliver(b, sent.Should().ContainSingle().Subject); + + b.Local.TryGetValue(Key, out _).Should().BeFalse(); + } + + [Fact] + public async Task After_a_refresh_that_landed_a_peer_takes_the_expiration_from_the_shared_tier() + { + using var peers = new CachePeers(new ManualTimeProvider(Start)); + var a = peers.Add("a"); + var b = peers.Add("b"); + await Holding(peers, b, TwoHourCap); + DateTimeOffset? asked = null; + a.Inner.OnRefresh = (_, expiration) => + { + asked = expiration; + peers.Store.Remaining[Key] = expiration.AddSeconds(-1) - Start; + return Task.FromResult(true); + }; + peers.AutoDeliver = false; + + (await a.Cache.RefreshAsync(Key, TimeSpan.FromHours(1), null, Ct)).Should().BeTrue(); + peers.Deliver(b, RefreshEvent(a)); + var before = b.Inner.SingleReads; + + (await b.Cache.GetAsync(Key, TwoHourCap, Ct)).Should().Be("v"); + b.Inner.SingleReads.Should().Be(before + 1); + b.Local.TryGetValue(Key, out ICacheEntry? held).Should().BeTrue(); + held!.Expiration.Should().Be(asked!.Value.AddSeconds(-1)); + } + + [Theory] + [InlineData(InnerRefresh.AnswersFalse)] + [InlineData(InnerRefresh.Throws)] + [InlineData(InnerRefresh.NeverAnswers)] + public async Task After_a_refresh_that_failed_no_node_holds_the_value(InnerRefresh outcome) + { + using var peers = new CachePeers(new ManualTimeProvider(Start)); + var a = peers.Add("a"); + var b = peers.Add("b"); + (await a.Cache.SetAsync(Key, "v", null, Ct)).Should().BeTrue(); + await Holding(peers, b, HourCap, write: false); + a.Local.TryGetValue(Key, out _).Should().BeTrue(); + var asked = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var never = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + a.Inner.OnRefresh = (_, _) => + { + asked.TrySetResult(); + return outcome switch + { + InnerRefresh.AnswersFalse => Task.FromResult(false), + InnerRefresh.Throws => Task.FromException(new InvalidOperationException("refresh failed")), + _ => never.Task, + }; + }; + peers.AutoDeliver = false; + + var call = a.Cache.RefreshAsync(Key, TimeSpan.FromHours(1), null, Ct).AsTask(); + await asked.Task.WaitAsync(TimeSpan.FromSeconds(30), Ct); + peers.Deliver(b, RefreshEvent(a)); + + a.Local.TryGetValue(Key, out _).Should().BeFalse(); + b.Local.TryGetValue(Key, out _).Should().BeFalse(); + never.TrySetResult(false); + (await call).Should().BeFalse(); + } + + [Fact] + public async Task The_node_that_refreshes_drops_its_own_copy_as_today() + { + using var peers = new CachePeers(new ManualTimeProvider(Start)); + var a = peers.Add("a"); + (await a.Cache.SetAsync(Key, "v", null, Ct)).Should().BeTrue(); + a.Local.TryGetValue(Key, out _).Should().BeTrue(); + a.Inner.OnRefresh = (_, _) => Task.FromResult(true); + + (await a.Cache.RefreshAsync(Key, TimeSpan.FromHours(1), null, Ct)).Should().BeTrue(); + + a.Local.TryGetValue(Key, out _).Should().BeFalse(); + } + + [Fact] + public async Task A_peers_write_is_still_reread_and_not_dropped() + { + using var peers = new CachePeers(new ManualTimeProvider(Start)); + var a = peers.Add("a"); + var b = peers.Add("b"); + (await a.Cache.SetAsync(Key, "old", null, Ct)).Should().BeTrue(); + (await b.Cache.GetAsync(Key, null, Ct)).Should().Be("old"); + (await b.Cache.GetAsync(Key, null, Ct)).Should().Be("old"); + var before = b.Inner.SingleReads; + + (await a.Cache.SetAsync(Key, "new", null, Ct)).Should().BeTrue(); + await b.Settled(); + + b.Inner.SingleReads.Should().Be(before + 1); + b.Local.TryGetValue(Key, out ICacheEntry? held).Should().BeTrue(); + held!.Value.Should().Be("new"); + } + + [Fact] + public async Task On_the_InMemory_provider_a_refresh_event_renews_the_copy_as_today() + { + using var peers = new CachePeers(new ManualTimeProvider(Start)); + var a = peers.Add("a", shared: false); + var b = peers.Add("b", shared: false); + (await b.Cache.SetAsync(Key, "v", null, Ct)).Should().BeTrue(); + peers.AutoDeliver = false; + + await a.Cache.RefreshAsync(Key, TimeSpan.FromMinutes(1), null, Ct); + var refreshed = RefreshEvent(a); + peers.Deliver(b, refreshed); + + b.Local.TryGetValue(Key, out ICacheEntry? held).Should().BeTrue(); + held!.Value.Should().Be("v"); + held.Expiration.Should().Be((DateTimeOffset)refreshed.Data!.Properties![KnownFieldNames.ExpirationKey]!); + } + + [Fact] + public async Task A_hash_cache_renews_on_a_refresh_event_as_today() + { + var policy = new CachePolicy { LocalExpiration = TimeSpan.FromMinutes(10) }; + using var cluster = new PeerCluster(new ManualTimeProvider(Start)); + var a = cluster.Add("a"); + var b = cluster.Add("b"); + var fields = new Dictionary { ["a"] = "1", ["b"] = "2" }; + (await a.Cache.SetAsync(Key, fields, policy, Ct)).Should().BeTrue(); + (await b.Cache.GetAsync(Key, policy, Ct)).Should().BeEquivalentTo(fields); + cluster.AutoDeliver = false; + + (await a.Cache.RefreshAsync(Key, TimeSpan.FromMinutes(1), policy, Ct)).Should().BeTrue(); + var refreshed = a.Published[^1]; + refreshed.Type.Should().Be(KnownEventTypes.CacheRefreshed); + cluster.Deliver(b, refreshed); + + b.Local.TryGetValue(Key, out ICacheEntry>? held).Should().BeTrue(); + held!.Value.Should().BeEquivalentTo(fields); + held.Expiration.Should().Be((DateTimeOffset)refreshed.Data!.Properties![KnownFieldNames.ExpirationKey]!); + } + + [Fact] + public async Task A_peer_that_held_validators_loses_them_with_the_entry() + { + var policy = new CachePolicy { FailSafeEnabled = true, LocalExpiration = TimeSpan.FromMinutes(10), FailSafeCooldown = TimeSpan.Zero }; + using var peers = new CachePeers(new ManualTimeProvider(Start)); + var a = peers.Add("a"); + var b = peers.Add("b"); + (await b.Cache.GetOrRevalidateAsync(Key, 0, static (_, context, _) => Task.FromResult(context.Modified("v1", "e1")), policy, Ct)).Should().Be("v1"); + await b.Settled(); + a.Inner.OnRefresh = (_, _) => Task.FromResult(true); + peers.AutoDeliver = false; + + (await a.Cache.RefreshAsync(Key, TimeSpan.FromHours(1), null, Ct)).Should().BeTrue(); + peers.Deliver(b, RefreshEvent(a)); + peers.Store.RemoveQuietly(Key); + var contexts = new List>(); + + Func, CancellationToken, Task>> recording = (_, context, _) => + { + contexts.Add(context); + return Task.FromResult(context.Modified("v2")); + }; + + (await b.Cache.GetOrRevalidateAsync(Key, 0, recording, policy, Ct)).Should().Be("v2"); + + contexts.Should().ContainSingle().Which.HasPreviousValue.Should().BeFalse(); + } + + /// Node reads v into its local tier; the store holds it unless is false. + private static async Task Holding(CachePeers peers, CachePeers.Node b, CachePolicy policy, bool write = true) + { + if (write) + { + peers.Store.WriteQuietly(Key, "v"); + } + + (await b.Cache.GetAsync(Key, policy, Ct)).Should().Be("v"); + b.Local.TryGetValue(Key, out _).Should().BeTrue(); + } + + private static ICacheEvent RefreshEvent(CachePeers.Node node) + { + var refreshed = node.Published[^1]; + refreshed.Type.Should().Be(KnownEventTypes.CacheRefreshed); + return refreshed; + } + + /// A publisher of another node, whose events the test collects and delivers. + private static (CacheEventPublisher Publisher, List Sent, CacheEventFactory Events) Publisher() + { + var sent = new List(); + var topic = Substitute.For>(); + topic.PublishAsync(Arg.Do(sent.Add), Arg.Any()).Returns(new ValueTask(true)); + var topics = Substitute.For(); + topics.Create(Arg.Any()).Returns(topic); + var events = new CacheEventFactory(Options.Create(new CacheOptions { AppShortName = "test", SourceUri = new Uri("urn:node:publisher") })); + return (new CacheEventPublisher(KnownCacheProviderNames.InMemoryRedis, topics, events, NullLogger.Instance), sent, events); + } + + /// A factory the cache knows nothing of, whose tokens only change. + private sealed class CustomTokens(IChangeTokenFactory inner) : IChangeTokenFactory + { + public ICacheChangeToken Create(string token, ITopic topic, string cacheName, Type entryType) => + new CustomToken(inner.Create(token, topic, cacheName, entryType)); + } + + private sealed class CustomToken(ICacheChangeToken inner) : ICacheChangeToken, IDisposable + { + public IDictionary? Metadata => inner.Metadata; + + public bool MetadataHasChanged => inner.MetadataHasChanged; + + public DateTimeOffset? Expiration => inner.Expiration; + + public string? TransportId => inner.TransportId; + + public bool HasChanged => inner.HasChanged; + + public bool ActiveChangeCallbacks => inner.ActiveChangeCallbacks; + + public IDisposable RegisterChangeCallback(Action callback, object? state) => inner.RegisterChangeCallback(callback, state); + + public void Dispose() => (inner as IDisposable)?.Dispose(); + } +} diff --git a/tests/UiPath.Caching.Tests/Redis/AdoptedFrameClockIntegrationTests.cs b/tests/UiPath.Caching.Tests/Redis/AdoptedFrameClockIntegrationTests.cs new file mode 100644 index 00000000..68bb5739 --- /dev/null +++ b/tests/UiPath.Caching.Tests/Redis/AdoptedFrameClockIntegrationTests.cs @@ -0,0 +1,536 @@ +using StackExchange.Redis; +using UiPath.Caching.Config; +using UiPath.Caching.Redis; +using UiPath.Caching.Tests.Fakes; +using static UiPath.Caching.Tests.Redis.EntryFrameReadIntegrationTests; +using Got = UiPath.Caching.Tests.Redis.FrameHarness.Got; + +namespace UiPath.Caching.Tests.Redis; + +// Frames are written raw. The UTC clock moves back before any time passes, so a wall-clock eviction cannot hide the +// defect. The key has a TTL of 61 seconds and a window of 60, so its logical life is one second; Redis counts the TTL +// on real time, so the seconds that only the fake clock saw are set on the key by hand. +[Collection("RedisIntegration")] +[Trait("Category", "Integration")] +public sealed class AdoptedFrameClockIntegrationTests(RedisContainerFixture fixture) +{ + private static readonly TimeSpan HalfSecond = TimeSpan.FromMilliseconds(500); + private static readonly TimeSpan Passed = TimeSpan.FromSeconds(5); + private static readonly TimeSpan Left = TimeSpan.FromSeconds(56); + private static readonly TimeSpan SoonDue = TimeSpan.FromSeconds(1.9); + + public enum Reading + { + Get, + Entry, + SpanGet, + SpanEntry, + BatchGet, + BatchEntry, + Probe, + BatchProbe, + } + + public enum Road + { + InnerEntry, + BatchRead, + PeerSetReread, + OuterLayeredCache, + RehydrateAdoption, + } + + public enum Answer + { + TryFill, + SetIfChanged, + GetOrAddFill, + BatchFill, + HealedUnreadable, + } + + public enum Generated + { + AValue, + Nothing, + } + + public enum FactoryOn + { + RedisTier, + LayeredCache, + Both, + } + + public enum Plain + { + PlainValue, + FrameWithoutBitZero, + } + + public static TheoryData AllReads => Cross(Enum.GetValues()); + + public static TheoryData AllRoads => Cross(Enum.GetValues()); + + public static TheoryData AllAnswers => Cross(Enum.GetValues()); + + public static TheoryData AllGenerated => Cross(Enum.GetValues()); + + public static TheoryData AllFactories => Cross(Enum.GetValues()); + + public static TheoryData AllPlains => Cross(Enum.GetValues()); + + public static TheoryData BothScripts => new() { Scripts.Off, Scripts.On }; + + internal static CancellationToken Ct => TestContext.Current.CancellationToken; + + // MB1, MB3, MB4: the reviewer's case. + [Theory] + [MemberData(nameof(AllReads))] + public async Task After_adoption_a_UTC_step_back_keeps_no_frame_past_its_logical_life(Reading read, Scripts scripts) + { + await using var h = await FrameHarness.StartAsync(fixture, scripts); + var cache = h.Layered; + var (key, raw) = await h.KeyAsync(); + await h.StoreWindowedAsync(raw, "A"); + var adopted = await ReadAsync(cache, read, key); + adopted.Value.Should().Be("A"); + if (adopted.Expiration is { } expiration) + { + expiration.Should().BeCloseTo(h.Time.GetUtcNow() + TimeSpan.FromSeconds(1), FrameHarness.Slack); + } + + h.StepBackThenAdvance(HalfSecond); + h.ClearLog(); + var held = await ReadAsync(cache, read, key); + + held.Should().Match(g => g.Value == "A" && !g.Generated); + h.TakeLog().Should().BeEmpty("with half a second gone the read is a local hit"); + + h.Time.Advance(Passed - HalfSecond); + await h.LeaveServerAsync(raw, Left); + await ShouldMissAsync(h, cache, read, key); + } + + // MB4 + [Theory] + [MemberData(nameof(BothScripts))] + public async Task After_adoption_the_TTL_commands_answer_from_the_bound(Scripts scripts) + { + await using var h = await FrameHarness.StartAsync(fixture, scripts); + var cache = h.Layered; + var (key, raw) = await h.KeyAsync(); + await h.StoreWindowedAsync(raw, "A"); + (await cache.GetAsync(key, null, Ct)).Should().Be("A"); + + h.StepBackThenAdvance(HalfSecond); + h.ClearLog(); + var ttl = await cache.TimeToLiveAsync(key, Ct); + var expires = await cache.ExpireTimeAsync(key, Ct); + + ttl.Should().NotBeNull().And.Subject.Should().BeLessThanOrEqualTo(HalfSecond); + expires.Should().BeCloseTo(h.Time.GetUtcNow() + ttl!.Value, TimeSpan.FromMilliseconds(50)); + h.TakeLog().Should().BeEmpty("both answer from the local entry"); + + h.Time.Advance(Passed - HalfSecond); + await h.LeaveServerAsync(raw, Left); + h.ClearLog(); + await cache.TimeToLiveAsync(key, Ct); + h.TakeLog().Should().NotBeEmpty("after the bound the TTL asks Redis"); + h.ClearLog(); + await cache.ExpireTimeAsync(key, Ct); + h.TakeLog().Should().NotBeEmpty("after the bound the expiration asks Redis"); + } + + // MB3 + [Theory] + [MemberData(nameof(AllRoads))] + public async Task A_copy_adopted_on_every_road_carries_its_bounds(Road road, Scripts scripts) + { + await using var h = await FrameHarness.StartAsync(fixture, scripts); + var (key, raw) = await h.KeyAsync(); + await h.StoreWindowedAsync(raw, "A"); + ICache cache; + switch (road) + { + case Road.InnerEntry: + cache = h.Build(h.Redis).Cache; + (await cache.GetCacheEntryAsync(key, null, Ct)).Value.Should().Be("A"); + break; + case Road.BatchRead: + cache = h.Build(h.Redis).Cache; + (await cache.GetAsync([key], null, Ct))[0].Value.Should().Be("A"); + break; + case Road.PeerSetReread: + var node = h.Build(h.Redis, broadcast: true); + cache = node.Cache; + (await cache.GetAsync(key, null, Ct)).Should().Be("A"); + await h.StoreWindowedAsync(raw, "B"); + node.Deliver(node.PeerEvents.Create(KnownCacheProviderNames.InMemoryRedis, KnownEventTypes.CacheSet, new CacheEventData(key.Name))); + await CachePeers.Reported(node.Cache, node.Telemetry, 1); + break; + case Road.RehydrateAdoption: + var rehydrating = h.Build(h.Redis); + cache = rehydrating.Cache; + await h.Db.KeyDeleteAsync(raw); + var shortLife = RehydratePolicy(TimeSpan.FromSeconds(2), 0.9); + (await cache.GetOrAddAsync(key, (Func>)(_ => Task.FromResult("G")), shortLife, Ct)).Should().Be("G"); + // The copy is due for a rehydrate and the key now holds the windowed frame, so the adoption read finds it. + await h.StoreWindowedAsync(raw, "A"); + h.Time.Advance(SoonDue); + var generatedAgain = 0; + Task Generate(CancellationToken _) + { + Interlocked.Increment(ref generatedAgain); + return Task.FromResult("generated"); + } + + (await cache.GetOrAddAsync(key, (Func>)Generate, shortLife, Ct)).Should().Be("G", "the local copy answers"); + await EventAsync(rehydrating, "cache.rehydrate.adopted"); + generatedAgain.Should().Be(0, "the rehydrate adopted the frame instead of generating"); + rehydrating.Entry(key).Should().BeAssignableTo("the adoption keeps the entry with its bounds"); + break; + default: + var inner = h.Build(h.Redis); + cache = h.Build(inner.Cache).Cache; + (await cache.GetCacheEntryAsync(key, null, Ct)).Value.Should().Be("A"); + break; + } + + h.StepBackThenAdvance(Passed); + await h.LeaveServerAsync(raw, Left); + await ShouldMissAsync(h, cache, Reading.Get, key); + } + + // MB3, LS1 to LS4 + [Theory] + [MemberData(nameof(AllAnswers))] + public async Task After_a_windowed_frame_an_Existed_or_Unchanged_answer_keeps_no_local_copy(Answer answer, Scripts scripts) + { + await using var h = await FrameHarness.StartAsync(fixture, scripts, redis: o => + { + o.RemoveTombstone = TimeSpan.FromSeconds(30); + o.RemoveUnreadable = false; + }); + var node = h.Build(h.Redis); + var cache = node.Cache; + var (key, raw) = await h.KeyAsync(); + string? caller = null; + DateTimeOffset? answered = null; + if (answer is Answer.TryFill or Answer.SetIfChanged) + { + await h.StoreWindowedAsync(raw, "A"); + } + else + { + await h.Db.KeyDeleteAsync(raw); + } + + switch (answer) + { + case Answer.TryFill: + var fill = await cache.TryFillAsync(key, "filler", FrameHarness.Long, null, Ct); + fill.Outcome.Should().Be(FillOutcome.Existed); + (caller, answered) = (fill.Existing, fill.Expiration); + break; + case Answer.SetIfChanged: + var change = await cache.SetIfChangedAsync(key, "A", StringComparer.Ordinal, FrameHarness.Long, null, Ct); + change.Outcome.Should().Be(ChangeOutcome.Unchanged); + (caller, answered) = (change.Current, change.Expiration); + break; + case Answer.GetOrAddFill: + caller = await cache.GetOrAddAsync(key, async _ => await GenerateOverAsync(h, raw), FrameHarness.Long, Ct); + break; + case Answer.BatchFill: + var batch = await cache.GetOrAddAsync([new(key, 1)], async (states, _) => [.. states.Select(s => new KeyValuePair(s, GenerateOverAsync(h, raw).GetAwaiter().GetResult()))], FrameHarness.Long, null, Ct); + caller = batch[0].Value; + break; + case Answer.HealedUnreadable: + // The generator leaves bytes no serializer reads, so the fill answers Unreadable and goes to heal them. The frame lands + // just before the heal's own read of the key, which then finds the winner and answers Existed. The fill's own read + // of the winner is a transaction too, unless its script answers, so the heal's is the first one after those. + var unreadable = false; + var transactions = 0; + var fillTransactions = h.Redis.RewriteScriptsOn ? 0 : 1; + var healed = 0; + h.Log.OnCommand = command => + { + if (command == "MULTI" && Volatile.Read(ref unreadable) && Interlocked.Increment(ref transactions) == fillTransactions + 1) + { + h.StoreWindowed(raw, "A"); + Interlocked.Increment(ref healed); + } + }; + try + { + caller = await cache.GetOrAddAsync( + key, + async _ => + { + await h.Db.StringSetAsync(raw, "not json{", TimeSpan.FromHours(1)); + Volatile.Write(ref unreadable, true); + return "generated"; + }, + FrameHarness.Long, + Ct); + } + finally + { + h.Log.OnCommand = null; + } + + healed.Should().Be(1, "the frame was stored before the heal's read of the key"); + break; + default: + throw new ArgumentOutOfRangeException(nameof(answer)); + } + + caller.Should().Be("A"); + + answered?.Should().BeCloseTo(h.Time.GetUtcNow() + TimeSpan.FromSeconds(1), FrameHarness.Slack, "the answer of the Redis tier still holds the logical expiration"); + node.Holds(key).Should().BeFalse(); + + h.ClearLog(); + (await cache.GetAsync(key, null, Ct)).Should().Be("A"); + // Today's read first; the anchored read follows only when that one cannot end the frame (Task 2.3, G3). + FrameHarness.ReadSends(h.TakeLog()).Should().BeInRange(1, 2, "the next read sends one entry read"); + node.Entry(key).Should().BeAssignableTo("and adopts with bounds"); + + h.StepBackThenAdvance(Passed); + await h.LeaveServerAsync(raw, Left); + await ShouldMissAsync(h, cache, Reading.Get, key); + } + + // MB3, KT1, the control + [Theory] + [MemberData(nameof(BothScripts))] + public async Task Before_any_windowed_frame_an_Existed_answer_is_adopted_as_today(Scripts scripts) + { + await using var h = await FrameHarness.StartAsync(fixture, scripts); + var node = h.Build(h.Redis); + var (key, raw) = await h.KeyAsync(); + await h.StorePlainAsync(raw, "A", TimeSpan.FromMinutes(30)); + + var fill = await node.Cache.TryFillAsync(key, "filler", FrameHarness.Long, null, Ct); + + fill.Outcome.Should().Be(FillOutcome.Existed); + ((IFrameTier)h.Redis).MetWindowedFrame.Should().BeFalse(); + node.Holds(key).Should().BeTrue("the copy is kept under the answer's deadline"); + h.ClearLog(); + var entry = await node.Cache.GetCacheEntryAsync(key, null, Ct); + entry.Value.Should().Be("A"); + entry.Expiration.Should().BeCloseTo(h.Time.GetUtcNow() + TimeSpan.FromMinutes(30), FrameHarness.Slack); + h.TakeLog().Should().BeEmpty(); + } + + // MB2, OD37 + [Theory] + [MemberData(nameof(AllFactories))] + public async Task With_a_custom_entry_factory_a_windowed_frame_still_gets_the_librarys_entry(FactoryOn on, Scripts scripts) + { + var factory = new CountingFactory(); + await using var h = await FrameHarness.StartAsync( + fixture, + scripts, + redis: o => o.EntryFactory = on is FactoryOn.RedisTier or FactoryOn.Both ? factory : null, + layered: o => o.EntryFactory = on is FactoryOn.LayeredCache or FactoryOn.Both ? factory : null); + var cache = h.Layered; + var (key, raw) = await h.KeyAsync(); + await h.StoreWindowedAsync(raw, "A"); + + var entry = await cache.GetCacheEntryAsync(key, null, Ct); + + entry.Value.Should().Be("A"); + entry.Should().BeAssignableTo("the factory is not asked for a windowed frame"); + h.StepBackThenAdvance(Passed); + await h.LeaveServerAsync(raw, Left); + await ShouldMissAsync(h, cache, Reading.Get, key); + + var (plainKey, plainRaw) = await h.KeyAsync(); + await h.StorePlainAsync(plainRaw, "P", TimeSpan.FromMinutes(30)); + (await cache.GetAsync(plainKey, null, Ct)).Should().Be("P"); + await cache.GetOrAddAsync((await h.KeyAsync()).Key, _ => Task.FromResult("G"), FrameHarness.Long, null, Ct); + factory.Created.Should().BeGreaterThan(0, "a plain value still gets the factory's entry"); + } + + // MB9, DA17, the control + [Theory] + [MemberData(nameof(AllPlains))] + public async Task A_plain_value_after_adoption_behaves_as_today(Plain plain, Scripts scripts) + { + await using var h = await FrameHarness.StartAsync(fixture, scripts); + var cache = h.Layered; + var (key, raw) = await h.KeyAsync(); + var inner = ((IByteCodecCache)h.Redis).Encode("A", null); + var bytes = plain == Plain.PlainValue ? inner : EntryFrame.Write(inner, DateTimeOffset.MaxValue, TimeSpan.Zero, EntryValidators.From("\"e\"", null)); + (await h.Db.StringSetAsync(raw, bytes)).Should().BeTrue(); + (await h.Db.KeyExpireAsync(raw, TimeSpan.FromSeconds(61))).Should().BeTrue(); + (await cache.GetAsync(key, null, Ct)).Should().Be("A"); + + h.StepBackThenAdvance(Passed); + h.Time.Advance(TimeSpan.FromSeconds(55)); + h.ClearLog(); + + (await cache.GetAsync(key, null, Ct)).Should().Be("A", "the UTC deadline has not come: the named limit DA17"); + h.TakeLog().Should().BeEmpty(); + } + + // MB8, OW3 + [Theory] + [MemberData(nameof(AllGenerated))] + public async Task A_rehydrate_of_an_observed_entry_writes_only_its_generators_value(Generated generated, Scripts scripts) + { + await using var h = await FrameHarness.StartAsync(fixture, scripts, layered: o => o.CacheNullValues = true); + var node = h.Build(h.Redis, configure: o => o.CacheNullValues = true); + var (key, raw) = await h.KeyAsync(); + await h.StoreWindowedAsync(raw, "A"); + var frame = (byte[])(await h.Db.StringGetAsync(raw))!; + var policy = RehydratePolicy(TimeSpan.FromSeconds(60), 0.5); + var ran = 0; + Task Generate(CancellationToken _) + { + Interlocked.Increment(ref ran); + return Task.FromResult(generated == Generated.AValue ? "generated" : null); + } + + var generate = (Func>)Generate; + (await node.Cache.GetOrAddAsync(key, generate, policy, Ct)).Should().Be("A"); + ran.Should().Be(0); + node.Entry(key).Should().BeAssignableTo("the local entry is the observed one"); + + h.StepBackThenAdvance(HalfSecond); + h.ClearLog(); + (await node.Cache.GetOrAddAsync(key, generate, policy, Ct)).Should().Be("A", "the local copy answers while the rehydrate runs"); + await EventAsync(node, "cache.rehydrate.succeeded"); + + ran.Should().Be(1); + var writes = h.TakeLog(writes: true).Where(c => c is "SET" or "EVAL" or "EVALSHA").ToList(); + writes.Should().ContainSingle("the generator's value is the only write"); + var stored = (byte[]?)await h.Db.StringGetAsync(raw); + stored.Should().NotEqual(frame, "the bytes that came out of the frame are written nowhere"); + if (generated == Generated.AValue) + { + stored.Should().Equal(((IByteCodecCache)h.Redis).Encode("generated", null)); + } + else + { + stored.Should().BeEmpty("the empty marker"); + } + } + + internal static CachePolicy RehydratePolicy(TimeSpan duration, double threshold) => new() + { + DistributedExpiration = duration, + RehydrateEnabled = true, + Rehydrate = new RehydrateOptions + { + Threshold = threshold, + BaseCooldown = TimeSpan.FromSeconds(1), + MaxCooldown = TimeSpan.FromMinutes(1), + TimeoutFraction = 0.5, + Name = "frame-test", + }, + }; + + /// Waits, bounded, until the node's telemetry holds the named event. + internal static Task EventAsync(FrameHarness.LayeredNode node, string name) => + node.Telemetry.Signal.UntilAsync(() => node.Telemetry.Events.Any(e => e.Name == name), Ct).WaitAsync(TimeSpan.FromSeconds(30), Ct); + + internal static TheoryData Cross(T[] values) + where T : notnull + { + var data = new TheoryData(); + foreach (var value in values) + { + data.Add(value, Scripts.Off); + data.Add(value, Scripts.On); + } + + return data; + } + + internal static async Task ReadAsync(ICache cache, Reading read, CacheKey key) + { + string? value; + switch (read) + { + case Reading.Get: + value = await cache.GetAsync(key, null, Ct); + return new Got(value is not null, value, false); + case Reading.SpanGet: + value = await SpanGetAsync(cache, key.Name); + return new Got(value is not null, value, false); + case Reading.BatchGet: + value = (await cache.GetAsync([key], null, Ct))[0].Value; + return new Got(value is not null, value, false); + case Reading.Entry: + return Of(await cache.GetCacheEntryAsync(key, null, Ct)); + case Reading.SpanEntry: + return Of(await SpanEntryAsync(cache, key.Name)); + case Reading.BatchEntry: + return Of((await cache.GetCacheEntriesAsync([key], null, Ct))[0].Value); + case Reading.Probe: + var ran = false; + value = await cache.GetOrAddAsync(key, _ => { ran = true; return Task.FromResult("generated"); }, FrameHarness.Long, null, Ct); + return new Got(!ran, ran ? null : value, ran); + default: + var batchRan = false; + var result = await cache.GetOrAddAsync([new(key, 1)], (states, _) => { batchRan = true; return Task.FromResult(states.Select(s => new KeyValuePair(s, "generated")).ToArray()); }, FrameHarness.Long, null, Ct); + return new Got(!batchRan, batchRan ? null : result[0].Value, batchRan); + } + } + + /// The read after the step: a miss, with one anchored read before anything it writes. + internal static async Task ShouldMissAsync(FrameHarness h, ICache cache, Reading read, CacheKey key) + { + h.ClearLog(); + var got = await ReadAsync(cache, read, key); + var log = h.TakeLog(); + + got.Found.Should().BeFalse("the key has 56 seconds left, inside the window"); + got.Generated.Should().Be(read is Reading.Probe or Reading.BatchProbe); + // Today's read first; the anchored read follows only when that one cannot end the frame (Task 2.3, G3). + FrameHarness.ReadSends(FrameHarness.ReadsOf(log)).Should().BeInRange(1, 2, "the local entry was not a hit: {0}", string.Join(",", log)); + } + + private static Got Of(ICacheEntry entry) => new(entry.Found, entry.Value, false, entry.Found ? entry.Expiration : null); + + private static ValueTask SpanGetAsync(ICache cache, string text) + { + var key = Handler(text); + return cache.GetAsync(ref key, null, Ct); + } + + private static ValueTask> SpanEntryAsync(ICache cache, string text) + { + var key = Handler(text); + return cache.GetCacheEntryAsync(ref key, null, Ct); + } + + private static CacheKeyHandler Handler(string text) + { + var handler = new CacheKeyHandler(text.Length, 0); + handler.AppendLiteral(text); + return handler; + } + + private static async Task GenerateOverAsync(FrameHarness h, RedisKey raw) + { + await h.StoreWindowedAsync(raw, "A"); + return "generated"; + } + + private sealed class CountingFactory : ICacheEntryFactory + { + private readonly CacheEntryFactory _inner = new(); + private int _created; + + public int Created => Volatile.Read(ref _created); + + public ICacheEntry Create(T value, DateTimeOffset expiration, IDictionary? properties = null) + { + Interlocked.Increment(ref _created); + return _inner.Create(value, expiration, properties); + } + } +} diff --git a/tests/UiPath.Caching.Tests/Redis/EntryFrameReadIntegrationTests.Anchor.cs b/tests/UiPath.Caching.Tests/Redis/EntryFrameReadIntegrationTests.Anchor.cs new file mode 100644 index 00000000..67c29861 --- /dev/null +++ b/tests/UiPath.Caching.Tests/Redis/EntryFrameReadIntegrationTests.Anchor.cs @@ -0,0 +1,737 @@ +using Microsoft.Extensions.DependencyInjection; +using StackExchange.Redis; +using UiPath.Caching.Policies; +using UiPath.Caching.Redis; + +namespace UiPath.Caching.Tests.Redis; + +// The anchored read (AN1, AN2): the TTL counts from a timestamp taken before the send, and the judgment reads each clock once. +// Until Task 3.2 gives a format a window, a value read sends its GET first and reaches the anchored read on a frame with a window. +public sealed partial class EntryFrameReadIntegrationTests +{ + private static readonly Read[] AnchoredReads = [Read.Get, Read.BatchGet, Read.Probe, Read.Entry, Read.BatchEntry, Read.Layered, Read.LayeredBatch, Read.Snapshot, Read.Fill, Read.Change]; + + public enum Bound + { + WriterTenSecondsAhead, + WriterOneHourAhead, + CutTtl, + } + + public enum Stored + { + Plain, + FrameWithoutWindow, + } + + public static TheoryData ValueReadsPastTheEnd => Cross3([Read.Get, Read.BatchGet, Read.Probe], [Scripts.Off, Scripts.On], Enum.GetValues()); + + public static TheoryData LateReplyReads => Cross([Read.Entry, Read.BatchEntry, Read.Layered, Read.LayeredBatch, Read.Snapshot, Read.Fill, Read.Change], [Scripts.Off, Scripts.On]); + + public static TheoryData AllAnchoredReads => Cross(AnchoredReads, [Scripts.Off, Scripts.On]); + + public static TheoryData UtcStepsDuringRead => Cross3(AnchoredReads, [Scripts.Off, Scripts.On], [-10, 10, 0]); + + public static TheoryData UtcStepsAlone => Cross3(AnchoredReads, [Scripts.Off, Scripts.On], [-10, 10]); + + public static TheoryData PlainOnAnchoredReads => Cross3([Read.Get, Read.BatchGet, Read.Probe, Read.Entry, Read.BatchEntry], [Scripts.Off, Scripts.On], Enum.GetValues()); + + public static TheoryData BothSidesReads => Cross([Read.Entry, Read.BatchEntry, Read.Result, Read.Layered, Read.LayeredBatch], [Scripts.Off, Scripts.On, Scripts.Refused]); + + // T1, AnchorAtSend (AN1; teeth-anchor-C9strict): a TTL added on receipt would keep the frame fresh one second after the hold. + [Theory] + [MemberData(nameof(ValueReadsPastTheEnd))] + public async Task A_value_read_whose_reply_waits_past_the_logical_end_is_a_miss(Read read, Scripts scripts, Bound bound) + { + var node = await NodeAsync(scripts); + var (key, raw) = await KeyAsync(node); + + await StoreOneSecondLeftAsync(node, raw, "A", bound); + node.ClearLog(); + OnceAfterReply(node, () => _time.Advance(Hold)); + var held = await ReadAsync(node, read, key); + + await StoreOneSecondLeftAsync(node, raw, "A", bound); + node.ClearLog(); + var prompt = await ReadAsync(node, read, key); + var log = node.Log(); + + held.Found.Should().BeFalse(); + held.Generated.Should().Be(read == Read.Probe, "the GetOrAdd runs its generator on the miss"); + prompt.Should().Be(new Answer(true, "A", null, false)); + log[0].Should().Be(read == Read.BatchGet ? "MGET" : "GET"); + var anchored = log.Skip(1).ToList(); + if (scripts == Scripts.On) + { + anchored.Should().ContainSingle().Which.Should().Match(c => IsScript(c)); + } + else + { + anchored.Should().Equal("MULTI", read == Read.BatchGet ? "MGET" : "GET", "PTTL", "EXEC"); + } + } + + [Fact] + public async Task Each_attempt_of_a_value_read_counts_from_its_own_send() + { + var node = await NodeAsync(services: s => s.AddSingleton(new RetryOnceProvider())); + var (key, raw) = await KeyAsync(node); + await StoreOneSecondLeftAsync(node, raw, "A", Bound.WriterOneHourAhead); + FailFirstAttemptAfter(node, TimeSpan.FromSeconds(3)); + + (await node.Cache.GetAsync(key, null, Ct)).Should().Be("A", "the second attempt sent again and answered at once"); + } + + [Fact] + public async Task A_batch_value_read_counts_every_key_from_one_send() + { + var node = await NodeAsync(); + var (first, firstRaw) = await KeyAsync(node); + var (second, secondRaw) = await KeyAsync(node); + await StoreFrameAsync(node, firstRaw, "A", TimeSpan.FromHours(1), keyTtl: Window + TimeSpan.FromSeconds(1)); + await StoreFrameAsync(node, secondRaw, "B", TimeSpan.FromHours(1), keyTtl: Window + TimeSpan.FromSeconds(10)); + node.ClearLog(); + OnceAfterReply(node, () => _time.Advance(Hold)); + + var values = await node.Cache.GetAsync([first, second], null, Ct); + + values[0].Value.Should().BeNull("one second of life was left at the send"); + values[1].Value.Should().Be("B", "ten seconds were left at the send"); + node.Log().Count(c => c == "EXEC").Should().Be(fixture.IsCluster ? 2 : 1, "one transaction per slot group, in one round trip"); + } + + [Theory] + [MemberData(nameof(ValueReadsPastTheEnd))] + public async Task A_key_replaced_around_a_value_read_never_returns_a_value_past_its_end(Read read, Scripts scripts, Bound bound) + { + var node = await NodeAsync(scripts); + var (key, raw) = await KeyAsync(node); + + await StoreFrameAsync(node, raw, "A", TimeSpan.FromSeconds(600)); + ReplaceAround(node, raw, bound, hold: true); + var held = await ReadAsync(node, read, key); + + await StoreFrameAsync(node, raw, "A", TimeSpan.FromSeconds(600)); + ReplaceAround(node, raw, bound, hold: false); + var prompt = await ReadAsync(node, read, key); + + held.Found.Should().BeFalse("B ended while its reply waited"); + prompt.Value.Should().Be("B"); + } + + [Theory] + [MemberData(nameof(PlainOnAnchoredReads))] + public async Task A_plain_value_whose_key_ended_before_the_reply_is_a_miss_on_an_anchored_read(Read read, Scripts scripts, Stored stored) + { + var node = await NodeAsync(scripts); + var (key, raw) = await KeyAsync(node); + + await ReplaceBeforeAnchoredReadAsync(node, raw, stored, TimeSpan.FromSeconds(4)); + OnceAfterReply(node, () => _time.Advance(Hold)); + var held = await ReadAsync(node, read, key); + + await ReplaceBeforeAnchoredReadAsync(node, raw, stored, TimeSpan.FromSeconds(10)); + var sent = _time.GetUtcNow(); + OnceAfterReply(node, () => _time.Advance(Hold)); + var prompt = await ReadAsync(node, read, key); + + held.Found.Should().BeFalse(); + held.Generated.Should().Be(read == Read.Probe); + prompt.Value.Should().Be("P"); + if (read is Read.Entry or Read.BatchEntry) + { + prompt.Expiration!.Value.Should().BeCloseTo(sent + TimeSpan.FromSeconds(10), Slack, "the entry counts from the send"); + } + } + + [Theory] + [InlineData(Read.Get)] + [InlineData(Read.Entry)] + [InlineData(Read.BatchEntry)] + public async Task A_plain_value_without_a_TTL_is_a_hit_however_long_the_reply_waits(Read read) + { + var node = await NodeAsync(); + var (key, raw) = await KeyAsync(node); + await ReplaceBeforeAnchoredReadAsync(node, raw, Stored.Plain, keyTtl: null); + OnceAfterReply(node, () => _time.Advance(TimeSpan.FromHours(1))); + + var answer = await ReadAsync(node, read, key); + + answer.Value.Should().Be("P"); + if (read != Read.Get) + { + answer.Expiration.Should().Be(DateTimeOffset.MaxValue); + } + } + + [Theory] + [InlineData(Stored.Plain)] + [InlineData(Stored.FrameWithoutWindow)] + public async Task A_plain_GET_under_a_format_without_a_window_returns_the_value_as_today(Stored stored) + { + var node = await NodeAsync(); + var (key, raw) = await KeyAsync(node); + var inner = node.Codec.Encode("P", null); + await StoreAsync(raw, stored == Stored.Plain ? inner : EntryFrame.Write(inner, DateTimeOffset.MaxValue, TimeSpan.Zero, EntryValidators.From("\"e\"", null)), TimeSpan.FromSeconds(30)); + await node.Cache.GetAsync(key, null, Ct); + node.ClearLog(); + // The reader's clock is past the key's end: a GET holds no TTL to judge by, as on the base build (PV4, the limit). + _time.Advance(TimeSpan.FromHours(1)); + + (await node.Cache.GetAsync(key, null, Ct)).Should().Be("P"); + node.Log().Should().Equal("GET"); + } + + [Theory] + [MemberData(nameof(BothSidesReads))] + public async Task A_value_replaced_on_both_sides_of_its_read_never_gets_another_values_life(Read read, Scripts scripts) + { + var node = await NodeAsync(scripts); + var (key, raw) = await KeyAsync(node); + var ahead = TimeSpan.FromHours(1); + await StoreFrameAsync(node, raw, "A", ahead + TimeSpan.FromSeconds(600), keyTtl: TimeSpan.FromSeconds(660)); + node.Redis.BeforeAnchoredRead = async () => + { + node.Redis.BeforeAnchoredRead = null; + await StoreFrameAsync(node, raw, "B", ahead + TimeSpan.FromSeconds(1), keyTtl: Window + TimeSpan.FromSeconds(1)); + }; + node.Redis.AfterAnchoredRead = async () => + { + node.Redis.AfterAnchoredRead = null; + await StoreFrameAsync(node, raw, "C", ahead + TimeSpan.FromSeconds(600), keyTtl: TimeSpan.FromSeconds(660)); + }; + var before = _time.GetUtcNow(); + + var answer = await ReadAsync(node, read, key); + + if (answer is { Found: true, Value: "B", Expiration: { } bExpiration }) + { + bExpiration.Should().BeOnOrBefore(before + TimeSpan.FromSeconds(1)); + } + + if (answer is { Found: true, Value: "C", Expiration: { } cExpiration }) + { + cExpiration.Should().BeOnOrBefore(before + TimeSpan.FromSeconds(600)); + } + + if (read is Read.Layered or Read.LayeredBatch) + { + _time.Advance(TimeSpan.FromSeconds(2)); + await StorePlainAsync(node, raw, "redis-now", Long); + (await node.Layered.GetAsync(key, null, Ct)).Should().NotBe("B", "no local copy of B outlives its one second"); + } + } + + [Theory] + [InlineData(Read.Get)] + [InlineData(Read.BatchGet)] + [InlineData(Read.Probe)] + public async Task A_value_read_gives_a_value_and_no_deadline(Read read) + { + var node = await NodeAsync(); + var (key, raw) = await KeyAsync(node); + await StoreFrameAsync(node, raw, "A", TimeSpan.FromMinutes(1), keyTtl: TimeSpan.FromHours(1)); + if (read != Read.Probe) + { + (await ReadAsync(node, read, key)).Should().Be(new Answer(true, "A", null, false)); + return; + } + + // A result call joins the probe's run while its judged read is in flight; the run ends with no expiration, and the call reads none. + var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + node.Redis.BeforeAnchoredRead = async () => + { + node.Redis.BeforeAnchoredRead = null; + entered.TrySetResult(); + await release.Task; + }; + var probe = ProbeAsync(node.Cache, key); + await entered.Task.WaitAsync(TimeSpan.FromSeconds(30), Ct); + var joined = node.Cache.GetOrAddResultAsync(key, _ => Task.FromResult("generated"), Long, null, Ct).AsTask(); + node.ClearLog(); + release.SetResult(); + + (await probe).Should().Be(new Answer(true, "A", null, false)); + var result = await joined; + result.Should().Be(new CacheResult("A", null, false)); + node.Log().Should().Equal(["MULTI", "GET", "PTTL", "EXEC"], "the probe's judged read, and nothing from the joined call"); + } + + [Theory] + [InlineData(RedisReadFrom.Master, Scripts.Off)] + [InlineData(RedisReadFrom.Replica, Scripts.Off)] + [InlineData(RedisReadFrom.Master, Scripts.On)] + public async Task A_value_read_of_a_windowed_frame_is_one_transaction_on_the_master(RedisReadFrom readFrom, Scripts scripts) + { + var node = await NodeAsync(scripts, o => o.ReadFrom = readFrom); + var (key, raw) = await KeyAsync(node); + await StoreFrameAsync(node, raw, "A", TimeSpan.FromMinutes(1)); + await node.Cache.GetAsync(key, null, Ct); + node.ClearLog(); + + (await node.Cache.GetAsync(key, null, Ct)).Should().Be("A"); + + var log = node.RawLog(); + log[0].Command.Should().Be("GET"); + var anchored = log.Skip(1).ToList(); + if (scripts == Scripts.On) + { + anchored.Should().ContainSingle().Which.Command.Should().Match(c => IsScript(c)); + return; + } + + anchored.Select(c => c.Command).Should().Equal("MULTI", "GET", "PTTL", "EXEC"); + anchored.Skip(1).Should().OnlyContain(c => (c.Flags & CommandFlags.DemandMaster) == CommandFlags.DemandMaster, "MULTI takes no flags; its commands and EXEC demand the master"); + } + + [Theory] + [InlineData(Read.BatchGet)] + [InlineData(Read.BatchEntry)] + public async Task A_batch_value_read_sends_one_transaction_per_slot_group(Read read) + { + var node = await NodeAsync(); + var tag = Guid.NewGuid().ToString("N"); + var (a, aRaw) = await KeyAsync(node, tag); + var (b, bRaw) = await KeyAsync(node, tag); + var (c, cRaw) = await KeyAsync(node); + foreach (var raw in new[] { aRaw, bRaw, cRaw }) + { + await StoreFrameAsync(node, raw, "A", TimeSpan.FromMinutes(1)); + } + + node.ClearLog(); + var found = read == Read.BatchGet + ? (await node.Cache.GetAsync([a, b, c], null, Ct)).Count(p => p.Value == "A") + : (await node.Cache.GetCacheEntriesAsync([a, b, c], null, Ct)).Count(p => p.Value.Value == "A"); + var log = node.Log(); + + found.Should().Be(3); + var groups = fixture.IsCluster ? 2 : 1; + log.Count(x => x == "MULTI").Should().Be(groups); + log.Count(x => x == "EXEC").Should().Be(groups); + log.Count(x => x == "GET").Should().Be(0, "a group sends one MGET, never a GET per key"); + log.Count(x => x == "PTTL").Should().Be(read == Read.BatchGet ? 3 : 6, "the transactions read one PTTL per key, after the pair of the entry read"); + } + + [Theory] + [InlineData("multi-denied")] + [InlineData("timeout")] + public async Task A_failed_read_transaction_fails_the_value_read_and_sends_no_other_read(string failure) + { + var node = failure == "multi-denied" ? await NodeAsync(user: _ => "-multi") : await NodeAsync(); + var (key, raw) = await KeyAsync(node); + await StoreFrameAsync(node, raw, "A", TimeSpan.FromMinutes(1)); + if (failure == "timeout") + { + node.Redis.AfterAnchoredRead = () => throw new TimeoutException("injected"); + } + + node.ClearLog(); + var value = await node.Cache.GetAsync(key, null, Ct); + var log = node.Log(); + + value.Should().BeNull("a read that fails is a miss"); + log.Count(c => c == "GET").Should().BeLessThanOrEqualTo(2, "the first GET and at most the one inside the transaction"); + log.SkipWhile(c => c != "MULTI").Skip(1).SkipWhile(c => c != "EXEC").Skip(1).Should().BeEmpty("nothing is read after the transaction"); + } + + [Fact] + public async Task A_refused_read_script_falls_back_to_the_transaction() + { + var node = await NodeAsync(Scripts.Refused); + var (key, raw) = await KeyAsync(node); + await StoreFrameAsync(node, raw, "A", TimeSpan.FromMinutes(1), keyTtl: TimeSpan.FromHours(1)); + node.ClearLog(); + + var entry = await node.Cache.GetCacheEntryAsync(key, null, Ct); + await StoreFrameAsync(node, raw, "A", TimeSpan.FromMinutes(-1), keyTtl: Window); + var expired = await node.Cache.GetAsync(key, null, Ct); + + entry.Value.Should().Be("A"); + entry.Expiration.Should().BeCloseTo(_time.GetUtcNow().AddMinutes(1), Slack); + expired.Should().BeNull(); + node.Log().Should().Contain("MULTI"); + } + + [Theory] + [InlineData(Read.Entry)] + [InlineData(Read.BatchEntry)] + public async Task Without_read_scripts_every_deadline_of_a_windowed_frame_comes_from_a_transaction(Read read) + { + var node = await NodeAsync(); + var (key, raw) = await KeyAsync(node); + await StoreFrameAsync(node, raw, "A", TimeSpan.FromMinutes(1), keyTtl: TimeSpan.FromHours(1)); + await ReadAsync(node, read, key); + node.ClearLog(); + + var answer = await ReadAsync(node, read, key); + var log = node.RawLog(); + + answer.Expiration!.Value.Should().BeCloseTo(_time.GetUtcNow().AddMinutes(1), Slack); + var get = read == Read.Entry ? "GET" : "MGET"; + log.Select(c => c.Command).Should().Equal(get, "PTTL", "MULTI", get, "PTTL", "EXEC"); + log.Skip(3).Should().OnlyContain(c => (c.Flags & CommandFlags.DemandMaster) == CommandFlags.DemandMaster, "MULTI takes no flags; its commands and EXEC demand the master"); + } + + [Theory] + [InlineData(Read.Entry)] + [InlineData(Read.BatchEntry)] + public async Task A_fresh_frame_met_by_the_plain_pair_is_read_again_before_it_is_accepted(Read read) + { + var node = await NodeAsync(); + var (key, raw) = await KeyAsync(node); + await StoreFrameAsync(node, raw, "A", TimeSpan.FromMinutes(1)); + await ReadAsync(node, read, key); + node.ClearLog(); + + (await ReadAsync(node, read, key)).Value.Should().Be("A"); + + var get = read == Read.Entry ? "GET" : "MGET"; + node.Log().Should().Equal(get, "PTTL", "MULTI", get, "PTTL", "EXEC"); + } + + // M1: the reply waits 5 seconds. A TTL of 61 seconds leaves 56 at the judgment, inside the window. + [Theory] + [MemberData(nameof(LateReplyReads))] + public async Task A_reply_that_is_processed_late_never_extends_a_windowed_frame(Read read, Scripts scripts) + { + var node = await NodeAsync(scripts); + var (key, raw) = await KeyAsync(node); + + await StoreFrameAsync(node, raw, "A", TimeSpan.FromHours(1), keyTtl: Window + TimeSpan.FromSeconds(1)); + OnceAfterReply(node, () => _time.Advance(Hold)); + var ended = await ReadAsync(node, read, key); + + ended.Found.Should().BeFalse(); + if (read is Read.Layered or Read.LayeredBatch) + { + (await HoldsLocalCopyAsync(node, key, raw)).Should().BeFalse(); + } + + await StoreFrameAsync(node, raw, "A", TimeSpan.FromHours(1), keyTtl: Window + TimeSpan.FromSeconds(10)); + var sent = _time.GetUtcNow(); + OnceAfterReply(node, () => _time.Advance(Hold)); + var alive = await ReadAsync(node, read, key); + + alive.Value.Should().Be("A"); + if (alive.Expiration is { } expiration) + { + expiration.Should().BeCloseTo(sent + TimeSpan.FromSeconds(10), Slack, "it counts from the send, never from the reply"); + } + + if (read is Read.Layered or Read.LayeredBatch) + { + _time.Advance(TimeSpan.FromSeconds(6)); + (await HoldsLocalCopyAsync(node, key, raw)).Should().BeFalse("the local copy ended 10 seconds after the send"); + } + } + + [Theory] + [InlineData("entry-script")] + [InlineData("batch-entry-script")] + [InlineData("snapshot")] + [InlineData("fill-winner")] + [InlineData("fenced-winner")] + [InlineData("fill-script")] + [InlineData("change-snapshot")] + public async Task A_late_read_never_accepts_a_windowed_frame(string path) + { + var scripts = path is "entry-script" or "batch-entry-script" or "fill-script" ? Scripts.On : Scripts.Off; + var node = await NodeAsync(scripts, o => o.RemoveTombstone = path == "fenced-winner" ? TimeSpan.FromSeconds(30) : null); + var read = path switch + { + "entry-script" => Read.Entry, + "batch-entry-script" => Read.BatchEntry, + "snapshot" => Read.Snapshot, + "change-snapshot" => Read.Change, + _ => Read.Fill, + }; + var (key, raw) = await KeyAsync(node); + + await StorePlainAsync(node, raw, "A", TimeSpan.FromHours(1)); + node.ClearLog(); + var plain = await ReadAsync(node, read, key); + var plainLog = node.Log(); + + await StoreFrameAsync(node, raw, "A", TimeSpan.FromMinutes(1), keyTtl: TimeSpan.FromHours(1)); + node.ClearLog(); + var fresh = await ReadAsync(node, read, key); + var freshLog = node.Log(); + + await StoreFrameAsync(node, raw, "A", TimeSpan.FromMinutes(-1), keyTtl: TimeSpan.FromHours(1)); + node.ClearLog(); + var expired = await ReadAsync(node, read, key); + var expiredLog = node.Log(); + + plain.Value.Should().Be("A"); + plain.Expiration!.Value.Should().BeCloseTo(_time.GetUtcNow().AddHours(1), Slack); + fresh.Value.Should().Be("A"); + fresh.Expiration!.Value.Should().BeCloseTo(_time.GetUtcNow().AddMinutes(1), Slack, "the deadline is the anchored read's"); + expired.Found.Should().BeFalse(); + var anchored = scripts == Scripts.On && read != Read.Fill ? (Func)IsScript : c => c == "MULTI"; + freshLog.Count(anchored).Should().Be(plainLog.Count(anchored) + 1, "a fresh frame is read again through the anchored read"); + if (read != Read.Change) + { + expiredLog.Count(anchored).Should().Be(plainLog.Count(anchored), "an expired frame is a miss on the first answer"); + } + } + + [Fact] + public async Task Each_attempt_counts_from_its_own_send() + { + var node = await NodeAsync(services: s => s.AddSingleton(new RetryOnceProvider())); + var (key, raw) = await KeyAsync(node); + await StoreFrameAsync(node, raw, "A", TimeSpan.FromHours(1), keyTtl: Window + TimeSpan.FromSeconds(10)); + FailFirstAttemptAfter(node, TimeSpan.FromSeconds(3)); + + var entry = await node.Cache.GetCacheEntryAsync(key, null, Ct); + + entry.Value.Should().Be("A"); + entry.Expiration.Should().BeCloseTo(_time.GetUtcNow().AddSeconds(10), TimeSpan.FromSeconds(1), "the deadline counts from the second send"); + } + + [Fact] + public async Task A_batch_counts_every_key_from_one_send() + { + var node = await NodeAsync(); + var (first, firstRaw) = await KeyAsync(node); + var (second, secondRaw) = await KeyAsync(node); + await StoreFrameAsync(node, firstRaw, "A", TimeSpan.FromHours(1), keyTtl: Window + TimeSpan.FromSeconds(10)); + await StoreFrameAsync(node, secondRaw, "B", TimeSpan.FromHours(1), keyTtl: Window + TimeSpan.FromSeconds(20)); + var sent = _time.GetUtcNow(); + OnceAfterReply(node, () => _time.Advance(Hold)); + + var entries = await node.Cache.GetCacheEntriesAsync([first, second], null, Ct); + + entries[0].Value.Expiration.Should().BeCloseTo(sent + TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(1)); + entries[1].Value.Expiration.Should().BeCloseTo(sent + TimeSpan.FromSeconds(20), TimeSpan.FromSeconds(1)); + } + + // T1, AnchorMono (AN1, AN2; teeth-anchormono-C9strict_noLim): an anchor on the UTC clock gives back the 10 seconds of the step. + [Theory] + [MemberData(nameof(UtcStepsDuringRead))] + public async Task A_step_of_the_UTC_clock_during_a_read_never_extends_a_windowed_frame(Read read, Scripts scripts, int stepSeconds) + { + var node = await NodeAsync(scripts); + var (key, raw) = await KeyAsync(node); + var step = TimeSpan.FromSeconds(stepSeconds); + + await StoreFrameAsync(node, raw, "A", TimeSpan.FromHours(1), keyTtl: Window + TimeSpan.FromSeconds(1)); + OnceAfterReply(node, () => + { + _time.Advance(Hold); + _time.StepUtc(step); + }); + var ended = await ReadAsync(node, read, key); + + ended.Found.Should().BeFalse(); + ended.Generated.Should().Be(read is Read.Probe or Read.Change); + if (read is Read.Layered or Read.LayeredBatch) + { + (await HoldsLocalCopyAsync(node, key, raw)).Should().BeFalse(); + } + + await StoreFrameAsync(node, raw, "A", TimeSpan.FromHours(1), keyTtl: Window + TimeSpan.FromSeconds(10)); + DateTimeOffset judged = default; + OnceAfterReply(node, () => + { + _time.Advance(Hold); + _time.StepUtc(step); + judged = _time.GetUtcNow(); + }); + var alive = await ReadAsync(node, read, key); + + alive.Value.Should().Be("A"); + if (alive.Expiration is { } expiration) + { + expiration.Should().BeCloseTo(judged + TimeSpan.FromSeconds(5), Slack); + } + } + + [Theory] + [MemberData(nameof(AllAnchoredReads))] + public async Task Time_on_the_monotonic_clock_alone_ends_a_windowed_frame(Read read, Scripts scripts) + { + var node = await NodeAsync(scripts); + var (key, raw) = await KeyAsync(node); + await StoreFrameAsync(node, raw, "A", TimeSpan.FromHours(1), keyTtl: Window + TimeSpan.FromSeconds(1)); + OnceAfterReply(node, () => + { + _time.Advance(Hold); + _time.StepUtc(-Hold); + }); + + (await ReadAsync(node, read, key)).Found.Should().BeFalse(); + } + + [Theory] + [MemberData(nameof(UtcStepsAlone))] + public async Task A_step_of_the_UTC_clock_alone_takes_no_life_off_the_key(Read read, Scripts scripts, int stepSeconds) + { + var node = await NodeAsync(scripts); + var (key, raw) = await KeyAsync(node); + await StoreFrameAsync(node, raw, "A", TimeSpan.FromHours(1), keyTtl: Window + TimeSpan.FromSeconds(1)); + DateTimeOffset judged = default; + OnceAfterReply(node, () => + { + _time.StepUtc(TimeSpan.FromSeconds(stepSeconds)); + judged = _time.GetUtcNow(); + }); + + var answer = await ReadAsync(node, read, key); + + answer.Value.Should().Be("A"); + if (answer.Expiration is { } expiration) + { + expiration.Should().BeCloseTo(judged + TimeSpan.FromSeconds(1), Slack); + } + } + + [Theory] + [MemberData(nameof(PlainOnAnchoredReads))] + public async Task A_plain_value_on_an_anchored_read_ignores_a_step_of_the_UTC_clock(Read read, Scripts scripts, Stored stored) + { + foreach (var step in new[] { TimeSpan.FromSeconds(-10), TimeSpan.FromSeconds(10) }) + { + var node = await NodeAsync(scripts); + var (key, raw) = await KeyAsync(node); + + await ReplaceBeforeAnchoredReadAsync(node, raw, stored, TimeSpan.FromSeconds(4)); + OnceAfterReply(node, () => + { + _time.Advance(Hold); + _time.StepUtc(step); + }); + (await ReadAsync(node, read, key)).Found.Should().BeFalse($"step {step}"); + + await ReplaceBeforeAnchoredReadAsync(node, raw, stored, TimeSpan.FromSeconds(10)); + DateTimeOffset judged = default; + OnceAfterReply(node, () => + { + _time.Advance(Hold); + _time.StepUtc(step); + judged = _time.GetUtcNow(); + }); + var alive = await ReadAsync(node, read, key); + + alive.Value.Should().Be("P", $"step {step}"); + if (alive.Expiration is { } expiration) + { + expiration.Should().BeCloseTo(judged + TimeSpan.FromSeconds(5), Slack); + } + } + } + + [Fact] + public async Task On_a_server_without_PEXPIRETIME_the_transaction_judges_frames() + { + Assert.SkipWhen(fixture.Enabled && fixture.ServerVersion.Major >= 7, "This server has PEXPIRETIME; the Redis 6 entry of the compat matrix runs this test."); + var node = await NodeAsync(Scripts.Off, o => o.ReadScriptsEnabled = true); + var (key, raw) = await KeyAsync(node); + await StoreFrameAsync(node, raw, "A", TimeSpan.FromMinutes(1), keyTtl: TimeSpan.FromHours(1)); + node.ClearLog(); + + var entry = await node.Cache.GetCacheEntryAsync(key, null, Ct); + await StoreFrameAsync(node, raw, "A", TimeSpan.FromHours(1), keyTtl: Window - TimeSpan.FromSeconds(1)); + var ended = await node.Cache.GetAsync(key, null, Ct); + + entry.Expiration.Should().BeCloseTo(_time.GetUtcNow().AddMinutes(1), Slack); + ended.Should().BeNull(); + var log = node.Log(); + log.Should().Contain("MULTI"); + log.Should().NotContain(c => IsScript(c)); + } + + private static TheoryData Cross3(Read[] reads, Scripts[] scripts, T[] values) + { + var data = new TheoryData(); + foreach (var read in reads) + { + foreach (var mode in scripts) + { + foreach (var value in values) + { + data.Add(read, mode, value); + } + } + } + + return data; + } + + /// A frame with a window and one second of logical life, which its frame expiration does not bound. + private async Task StoreOneSecondLeftAsync(Node node, RedisKey raw, string value, Bound bound) + { + var ttl = Window + TimeSpan.FromSeconds(1); + switch (bound) + { + case Bound.WriterTenSecondsAhead: + await StoreFrameAsync(node, raw, value, TimeSpan.FromSeconds(11), keyTtl: ttl); + break; + case Bound.WriterOneHourAhead: + await StoreFrameAsync(node, raw, value, TimeSpan.FromHours(1) + TimeSpan.FromSeconds(1), keyTtl: ttl); + break; + default: + await StoreFrameAsync(node, raw, value, TimeSpan.FromHours(1)); + (await Db.KeyExpireAsync(raw, ttl)).Should().BeTrue(); + break; + } + } + + /// B with one second of life lands before the anchored read; C with 660 seconds lands when its reply is in, after the hold. + private void ReplaceAround(Node node, RedisKey raw, Bound bound, bool hold) + { + node.Redis.BeforeAnchoredRead = async () => + { + node.Redis.BeforeAnchoredRead = null; + switch (bound) + { + case Bound.WriterTenSecondsAhead: + // Equal clocks: B ends by its frame expiration. + await StoreFrameAsync(node, raw, "B", TimeSpan.FromSeconds(1)); + break; + case Bound.WriterOneHourAhead: + await StoreFrameAsync(node, raw, "B", TimeSpan.FromHours(1) + TimeSpan.FromSeconds(1), keyTtl: Window + TimeSpan.FromSeconds(1)); + break; + default: + await StoreFrameAsync(node, raw, "B", TimeSpan.FromHours(1)); + (await Db.KeyExpireAsync(raw, Window + TimeSpan.FromSeconds(1))).Should().BeTrue(); + break; + } + }; + node.Redis.AfterAnchoredRead = async () => + { + node.Redis.AfterAnchoredRead = null; + if (hold) + { + _time.Advance(Hold); + } + + await StoreFrameAsync(node, raw, "C", TimeSpan.FromSeconds(600)); + }; + } + + /// A fresh frame with a window sends the read to the anchored read, and the value it then finds is P: plain, or a frame without a window. + private async Task ReplaceBeforeAnchoredReadAsync(Node node, RedisKey raw, Stored stored, TimeSpan? keyTtl) + { + await StoreFrameAsync(node, raw, "W", TimeSpan.FromHours(1)); + var inner = node.Codec.Encode("P", null); + var bytes = stored == Stored.Plain ? inner : EntryFrame.Write(inner, DateTimeOffset.MaxValue, TimeSpan.Zero, EntryValidators.From("\"e\"", null)); + node.Redis.BeforeAnchoredRead = async () => + { + node.Redis.BeforeAnchoredRead = null; + await StoreAsync(raw, bytes, keyTtl); + }; + } + + private void FailFirstAttemptAfter(Node node, TimeSpan elapsed) + { + node.Redis.AfterAnchoredRead = () => + { + node.Redis.AfterAnchoredRead = null; + _time.Advance(elapsed); + throw new InjectedFault(); + }; + } +} diff --git a/tests/UiPath.Caching.Tests/Redis/EntryFrameReadIntegrationTests.Basics.cs b/tests/UiPath.Caching.Tests/Redis/EntryFrameReadIntegrationTests.Basics.cs new file mode 100644 index 00000000..7342b0b3 --- /dev/null +++ b/tests/UiPath.Caching.Tests/Redis/EntryFrameReadIntegrationTests.Basics.cs @@ -0,0 +1,347 @@ +using StackExchange.Redis; +using UiPath.Caching.Redis; + +namespace UiPath.Caching.Tests.Redis; + +public sealed partial class EntryFrameReadIntegrationTests +{ + public static TheoryData CutTtlReads => Cross([Read.Get, Read.Entry, Read.BatchGet, Read.BatchEntry], [Scripts.Off, Scripts.On, Scripts.Refused]); + + [Theory] + [InlineData(Scripts.Off)] + [InlineData(Scripts.On)] + public async Task GetAsync_returns_the_inner_value_of_a_fresh_frame(Scripts scripts) + { + var node = await NodeAsync(scripts); + var (key, raw) = await KeyAsync(node); + await StoreFrameAsync(node, raw, "A", TimeSpan.FromMinutes(1)); + + (await node.Cache.GetAsync(key, null, Ct)).Should().Be("A"); + } + + [Theory] + [InlineData(Scripts.Off)] + [InlineData(Scripts.On)] + public async Task GetCacheEntryAsync_reports_the_logical_expiration_not_the_key_ttl(Scripts scripts) + { + var node = await NodeAsync(scripts); + var (key, raw) = await KeyAsync(node); + await StoreFrameAsync(node, raw, "A", TimeSpan.FromMinutes(1), window: TimeSpan.FromHours(1)); + + var entry = await node.Cache.GetCacheEntryAsync(key, null, Ct); + + entry.Value.Should().Be("A"); + entry.Expiration.Should().BeCloseTo(_time.GetUtcNow().AddMinutes(1), Slack); + } + + [Theory] + [InlineData(Scripts.Off)] + [InlineData(Scripts.On)] + public async Task GetCacheEntryAsync_shows_the_validators_of_a_frame(Scripts scripts) + { + var node = await NodeAsync(scripts); + var (key, raw) = await KeyAsync(node); + var modified = DateTimeOffset.FromUnixTimeMilliseconds(1_700_000_000_000); + await StoreFrameAsync(node, raw, "A", TimeSpan.FromMinutes(1), validators: EntryValidators.From("\"v1\"", modified)); + + var entry = await node.Cache.GetCacheEntryAsync(key, null, Ct); + + entry.Value.Should().Be("A"); + var validators = EntryValidators.Of(entry.Metadata); + validators!.ETag.Should().Be("\"v1\""); + validators.LastModified.Should().Be(modified); + } + + [Theory] + [InlineData(Scripts.Off)] + [InlineData(Scripts.On)] + public async Task An_expired_frame_is_a_miss_for_GetAsync_for_a_batch_GetAsync_and_for_a_batch_entry_read(Scripts scripts) + { + var node = await NodeAsync(scripts); + var (key, raw) = await KeyAsync(node); + // Ended a minute ago by its frame expiration; its key keeps the window. + await StoreFrameAsync(node, raw, "A", TimeSpan.FromMinutes(-1), keyTtl: Window); + + (await ReadAsync(node, Read.Get, key)).Found.Should().BeFalse(); + (await ReadAsync(node, Read.BatchGet, key)).Found.Should().BeFalse(); + (await ReadAsync(node, Read.BatchEntry, key)).Found.Should().BeFalse(); + (await ReadAsync(node, Read.Entry, key)).Found.Should().BeFalse(); + (await Db.KeyExistsAsync(raw)).Should().BeTrue("an expired frame is no unreadable value"); + } + + // T1, UseKeyDeadline (FR4; teeth-keydeadline-C9strict): judged by its frame expiration alone, the entry would end in an hour. + [Theory] + [InlineData(Scripts.Off)] + [InlineData(Scripts.On)] + public async Task A_frame_on_a_key_whose_ttl_was_cut_expires_with_the_key(Scripts scripts) + { + var node = await NodeAsync(scripts); + var (key, raw) = await KeyAsync(node); + await StoreFrameAsync(node, raw, "A", TimeSpan.FromHours(1)); + (await Db.KeyExpireAsync(raw, Window + TimeSpan.FromSeconds(10))).Should().BeTrue(); + + var entry = await node.Cache.GetCacheEntryAsync(key, null, Ct); + + entry.Value.Should().Be("A"); + entry.Expiration.Should().BeCloseTo(_time.GetUtcNow().AddSeconds(10), Slack); + } + + // Judged by its frame expiration alone, the frame is fresh for ten more minutes. + [Theory] + [InlineData(Scripts.Off)] + [InlineData(Scripts.On)] + public async Task A_reader_whose_clock_is_behind_reads_a_miss_once_the_key_ttl_is_inside_the_window(Scripts scripts) + { + var node = await NodeAsync(scripts); + var (key, raw) = await KeyAsync(node); + await StoreFrameAsync(node, raw, "A", TimeSpan.FromMinutes(10), keyTtl: Window - TimeSpan.FromSeconds(10)); + + foreach (var read in new[] { Read.Get, Read.Entry, Read.BatchGet, Read.BatchEntry, Read.Probe }) + { + (await ReadAsync(node, read, key)).Found.Should().BeFalse($"{read} judges by the key's TTL too"); + await StoreFrameAsync(node, raw, "A", TimeSpan.FromMinutes(10), keyTtl: Window - TimeSpan.FromSeconds(10)); + } + } + + [Theory] + [InlineData(Scripts.Off)] + [InlineData(Scripts.On)] + public async Task A_reader_whose_clock_is_ahead_reads_an_early_miss(Scripts scripts) + { + var node = await NodeAsync(scripts); + var (key, raw) = await KeyAsync(node); + // The writer's clock was a minute behind: the reader sees the frame expiration already behind it, though the key has an hour. + await StoreFrameAsync(node, raw, "A", TimeSpan.FromMinutes(-1), keyTtl: TimeSpan.FromHours(1)); + + (await ReadAsync(node, Read.Get, key)).Found.Should().BeFalse(); + (await ReadAsync(node, Read.Entry, key)).Found.Should().BeFalse(); + } + + [Theory] + [InlineData(Scripts.Off, false)] + [InlineData(Scripts.On, false)] + [InlineData(Scripts.Off, true)] + [InlineData(Scripts.On, true)] + public async Task A_finite_or_never_frame_on_a_persisted_key_is_a_miss(Scripts scripts, bool never) + { + var node = await NodeAsync(scripts); + var (key, raw) = await KeyAsync(node); + var inner = node.Codec.Encode("A", null); + await StoreAsync(raw, EntryFrame.Write(inner, never ? DateTimeOffset.MaxValue : _time.GetUtcNow().AddHours(1), Window, null), keyTtl: null); + + foreach (var read in new[] { Read.Get, Read.Entry, Read.BatchGet, Read.BatchEntry }) + { + (await ReadAsync(node, read, key)).Found.Should().BeFalse($"{read}: a key without an end proves no window"); + } + } + + [Fact] + public async Task With_read_scripts_a_framed_key_is_judged_by_its_remaining_ttl_not_by_the_server_clock() + { + var node = await NodeAsync(Scripts.On); + var (key, raw) = await KeyAsync(node); + // The frame ended by its key 10 minutes ago on the server's clock: the reader is 10 minutes behind the server. + _time.StepUtc(TimeSpan.FromMinutes(-10)); + await StoreFrameAsync(node, raw, "A", TimeSpan.FromHours(1), keyTtl: Window - TimeSpan.FromSeconds(1)); + + (await ReadAsync(node, Read.Entry, key)).Found.Should().BeFalse(); + (await ReadAsync(node, Read.BatchEntry, key)).Found.Should().BeFalse(); + (await ReadAsync(node, Read.Get, key)).Found.Should().BeFalse(); + } + + [Theory] + [InlineData(Scripts.Off)] + [InlineData(Scripts.On)] + public async Task A_value_only_read_of_a_windowed_frame_reads_value_and_ttl_once_more(Scripts scripts) + { + var node = await NodeAsync(scripts); + var (key, raw) = await KeyAsync(node); + await StoreFrameAsync(node, raw, "A", TimeSpan.FromMinutes(1)); + await node.Cache.GetAsync(key, null, Ct); + node.ClearLog(); + + (await node.Cache.GetAsync(key, null, Ct)).Should().Be("A"); + + var log = node.Log(); + log[0].Should().Be("GET"); + if (scripts == Scripts.On) + { + log.Skip(1).Should().ContainSingle().Which.Should().Match(c => IsScript(c)); + } + else + { + log.Skip(1).Should().Equal("MULTI", "GET", "PTTL", "EXEC"); + } + } + + [Theory] + [InlineData(Scripts.Off)] + [InlineData(Scripts.On)] + public async Task A_value_only_read_of_a_plain_value_sends_one_command(Scripts scripts) + { + var node = await NodeAsync(scripts); + var (key, _) = await KeyAsync(node); + await node.Cache.GetAsync(key, null, Ct); + node.ClearLog(); + + (await node.Cache.GetAsync(key, null, Ct)).Should().Be("seed"); + + node.Log().Should().Equal("GET"); + } + + [Theory] + [InlineData(Scripts.Off)] + [InlineData(Scripts.On)] + public async Task A_key_rewritten_between_the_first_read_and_the_second_is_judged_by_the_second(Scripts scripts) + { + var node = await NodeAsync(scripts); + var (key, raw) = await KeyAsync(node); + await StoreFrameAsync(node, raw, "A", TimeSpan.FromMinutes(1)); + node.Redis.BeforeAnchoredRead = async () => + { + node.Redis.BeforeAnchoredRead = null; + await StoreFrameAsync(node, raw, "B", TimeSpan.FromMinutes(-1), keyTtl: Window); + }; + + (await node.Cache.GetAsync(key, null, Ct)).Should().BeNull("the second read found an expired frame"); + await StoreFrameAsync(node, raw, "A", TimeSpan.FromMinutes(1)); + node.Redis.BeforeAnchoredRead = async () => + { + node.Redis.BeforeAnchoredRead = null; + await StoreFrameAsync(node, raw, "B", TimeSpan.FromMinutes(1)); + }; + (await node.Cache.GetAsync(key, null, Ct)).Should().Be("B"); + } + + [Theory] + [MemberData(nameof(CutTtlReads))] + public async Task A_frame_ended_by_a_cut_ttl_is_never_read_as_fresh_when_the_key_is_rewritten_inside_the_read(Read read, Scripts scripts) + { + var node = await NodeAsync(scripts); + var (key, raw) = await KeyAsync(node); + await StoreFrameAsync(node, raw, "old", TimeSpan.FromHours(1), keyTtl: Window - TimeSpan.FromSeconds(5)); + node.Redis.BeforeAnchoredRead = () => StorePlainAsync(node, raw, "new", Long); + node.Redis.AfterAnchoredRead = () => StorePlainAsync(node, raw, "newer", Long); + + var answer = await ReadAsync(node, read, key); + + answer.Value.Should().NotBe("old"); + } + + [Theory] + [InlineData(Scripts.Off)] + [InlineData(Scripts.On)] + public async Task A_snapshot_read_of_an_expired_frame_is_Absent_not_Unreadable(Scripts scripts) + { + var node = await NodeAsync(scripts); + var (key, raw) = await KeyAsync(node); + await StoreFrameAsync(node, raw, "A", TimeSpan.FromMinutes(-1), keyTtl: Window); + + var snapshot = await ((IMigrationCache)node.Redis).ReadSnapshotAsync(key, null, Ct); + + snapshot.Outcome.Should().Be(SnapshotOutcome.Absent); + } + + [Theory] + [InlineData(Scripts.Off)] + [InlineData(Scripts.On)] + public async Task A_layered_cache_keeps_a_fresh_frame_locally_until_its_logical_expiration(Scripts scripts) + { + var node = await NodeAsync(scripts); + var (key, raw) = await KeyAsync(node); + await StoreFrameAsync(node, raw, "A", TimeSpan.FromSeconds(30), keyTtl: TimeSpan.FromHours(1)); + + (await node.Layered.GetAsync(key, null, Ct)).Should().Be("A"); + (await HoldsLocalCopyAsync(node, key, raw)).Should().BeTrue(); + + await StoreFrameAsync(node, raw, "A", TimeSpan.FromSeconds(30), keyTtl: TimeSpan.FromHours(1)); + _time.Advance(TimeSpan.FromSeconds(31)); + (await HoldsLocalCopyAsync(node, key, raw)).Should().BeFalse("the local copy ended at the logical expiration"); + } + + [Theory] + [InlineData(Scripts.Off)] + [InlineData(Scripts.On)] + public async Task GetOrAdd_on_the_Redis_only_provider_returns_the_inner_value_of_a_fresh_frame(Scripts scripts) + { + var node = await NodeAsync(scripts); + var (key, raw) = await KeyAsync(node); + await StoreFrameAsync(node, raw, "A", TimeSpan.FromMinutes(1), keyTtl: TimeSpan.FromHours(1)); + + var probe = await ReadAsync(node, Read.Probe, key); + var result = await ReadAsync(node, Read.Result, key); + + probe.Should().Be(new Answer(true, "A", null, false)); + result.Value.Should().Be("A"); + result.Generated.Should().BeFalse(); + result.Expiration!.Value.Should().BeCloseTo(_time.GetUtcNow().AddMinutes(1), Slack); + } + + [Theory] + [InlineData(Scripts.Off)] + [InlineData(Scripts.On)] + public async Task A_fill_that_meets_a_fresh_frame_reports_its_logical_expiration(Scripts scripts) + { + var node = await NodeAsync(scripts); + var (key, raw) = await KeyAsync(node); + await StoreFrameAsync(node, raw, "A", TimeSpan.FromMinutes(1), keyTtl: TimeSpan.FromHours(1)); + + var fill = await ReadAsync(node, Read.Fill, key); + + fill.Fill.Should().Be(FillOutcome.Existed); + fill.Value.Should().Be("A"); + fill.Expiration!.Value.Should().BeCloseTo(_time.GetUtcNow().AddMinutes(1), Slack); + } + + [Theory] + [InlineData(Scripts.Off)] + [InlineData(Scripts.On)] + public async Task A_batch_fill_that_meets_a_fresh_frame_reports_its_logical_expiration(Scripts scripts) + { + var node = await NodeAsync(scripts); + var (fresh, freshRaw) = await KeyAsync(node); + var (expired, expiredRaw) = await KeyAsync(node); + await StoreFrameAsync(node, freshRaw, "A", TimeSpan.FromMinutes(1), keyTtl: TimeSpan.FromHours(1)); + await StoreFrameAsync(node, expiredRaw, "B", TimeSpan.FromMinutes(-1), keyTtl: TimeSpan.FromHours(1)); + + var results = await node.Redis.TryFillManyAsync([new(fresh, "filler"), new(expired, "filler")], _time.GetUtcNow() + Long, null, Ct); + + results[0].Outcome.Should().Be(FillOutcome.Existed); + results[0].Existing.Should().Be("A"); + results[0].Expiration!.Value.Should().BeCloseTo(_time.GetUtcNow().AddMinutes(1), Slack); + results[1].Outcome.Should().Be(FillOutcome.Failed, "nothing is stored over an expired frame in PR 2"); + TryReadFrame(await Db.StringGetAsync(expiredRaw), out _).Should().BeTrue(); + } + + [Theory] + [InlineData("fresh", Scripts.Off)] + [InlineData("fresh", Scripts.On)] + [InlineData("frame-expired", Scripts.Off)] + [InlineData("frame-expired", Scripts.On)] + [InlineData("key-expired", Scripts.Off)] + [InlineData("key-expired", Scripts.On)] + public async Task RemoveUnreadable_never_deletes_a_windowed_frame(string kind, Scripts scripts) + { + var node = await NodeAsync(scripts); + var (key, raw) = await KeyAsync(node); + foreach (var read in new[] { Read.Get, Read.BatchGet, Read.Probe, Read.Entry, Read.BatchEntry }) + { + var stored = kind switch + { + "fresh" => EntryFrame.Write(node.Codec.Encode("A", null), _time.GetUtcNow().AddMinutes(1), Window, null), + "frame-expired" => EntryFrame.Write(node.Codec.Encode("A", null), _time.GetUtcNow().AddMinutes(-1), Window, null), + _ => EntryFrame.Write(node.Codec.Encode("A", null), _time.GetUtcNow().AddHours(1), Window, null), + }; + await StoreAsync(raw, stored, kind switch { "fresh" => Window * 2, "frame-expired" => Window, _ => Window - TimeSpan.FromSeconds(5) }); + + var answer = await ReadAsync(node, read, key); + + if (!answer.Generated) + { + ((byte[]?)await Db.StringGetAsync(raw)).Should().Equal(stored, $"{read} leaves a {kind} frame in place"); + } + + answer.Found.Should().Be(kind == "fresh", read.ToString()); + } + } +} diff --git a/tests/UiPath.Caching.Tests/Redis/EntryFrameReadIntegrationTests.RefreshEvent.cs b/tests/UiPath.Caching.Tests/Redis/EntryFrameReadIntegrationTests.RefreshEvent.cs new file mode 100644 index 00000000..4fafb7ae --- /dev/null +++ b/tests/UiPath.Caching.Tests/Redis/EntryFrameReadIntegrationTests.RefreshEvent.cs @@ -0,0 +1,39 @@ +using Microsoft.Extensions.Logging.Abstractions; +using NSubstitute; +using UiPath.Caching.Broadcast; +using UiPath.Caching.Config; + +namespace UiPath.Caching.Tests.Redis; + +public sealed partial class EntryFrameReadIntegrationTests +{ + // Task 2.5 drops a copy on a refresh event; a copy adopted from a frame must not come back with a longer life. + [Theory] + [InlineData(Scripts.On)] + [InlineData(Scripts.Off)] + public async Task A_refresh_event_does_not_renew_a_copy_adopted_from_a_frame(Scripts scripts) + { + await using var h = await FrameHarness.StartAsync(fixture, scripts); + var b = h.Build(h.Redis, broadcast: true, name: "b"); + var (key, raw) = await h.KeyAsync(); + await h.StoreFrameAsync(raw, "A", TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(70)); + (await b.Cache.GetAsync(key, null, Ct)).Should().Be("A"); + b.Holds(key).Should().BeTrue(); + + var sent = new List(); + var topic = Substitute.For>(); + topic.PublishAsync(Arg.Do(sent.Add), Arg.Any()).Returns(new ValueTask(true)); + var topics = Substitute.For(); + topics.Create(Arg.Any()).Returns(topic); + var publisher = new CacheEventPublisher(KnownCacheProviderNames.InMemoryRedis, topics, b.PeerEvents, NullLogger.Instance); + await publisher.CacheRefreshedAsync(new CacheEntryOptions { CacheKey = key, CallerKey = key, TopicKey = new TopicKey("topic"), Expiration = h.Time.GetUtcNow().AddHours(1) }); + h.ClearLog(); + b.Deliver(sent.Should().ContainSingle().Subject); + + h.TakeLog().Should().BeEmpty("the event reaches no command"); + h.Time.Advance(TimeSpan.FromSeconds(11)); + (await h.Db.KeyExistsAsync(raw)).Should().BeTrue("the key is still in Redis"); + (await b.Cache.GetAsync(key, null, Ct)).Should().BeNull(); + (await b.Cache.GetCacheEntryAsync(key, null, Ct)).Found.Should().BeFalse(); + } +} diff --git a/tests/UiPath.Caching.Tests/Redis/EntryFrameReadIntegrationTests.Writes.cs b/tests/UiPath.Caching.Tests/Redis/EntryFrameReadIntegrationTests.Writes.cs new file mode 100644 index 00000000..e10ba706 --- /dev/null +++ b/tests/UiPath.Caching.Tests/Redis/EntryFrameReadIntegrationTests.Writes.cs @@ -0,0 +1,287 @@ +using StackExchange.Redis; +using UiPath.Caching.Redis; + +namespace UiPath.Caching.Tests.Redis; + +// The fills, SetIfChangedAsync and the repair of unreadable bytes meet frames through late reads; a fresh frame with a window is read again through the anchored read. +public sealed partial class EntryFrameReadIntegrationTests +{ + public enum Held + { + FreshWindowed, + ExpiredByFrame, + ExpiredByKey, + ValidatorsOnly, + Plain, + PlainNull, + FramedNull, + } + + public enum Generated + { + Single, + Batch, + } + + public static TheoryData ChangeRows + { + get + { + var data = new TheoryData(); + foreach (var held in Enum.GetValues()) + { + foreach (var equal in new[] { true, false }) + { + data.Add(held, equal, Scripts.Off); + data.Add(held, equal, Scripts.On); + } + } + + return data; + } + } + + [Theory] + [MemberData(nameof(ChangeRows))] + public async Task SetIfChangedAsync_judges_a_stored_frame_and_answers_its_logical_expiration(Held held, bool equal, Scripts scripts) + { + var node = await NodeAsync(scripts, o => o.CacheNullValues = true); + var (key, raw) = await KeyAsync(node); + var storedValue = held is Held.PlainNull or Held.FramedNull ? null : "A"; + var inner = storedValue is null ? [] : node.Codec.Encode(storedValue, null); + var keyTtl = TimeSpan.FromMinutes(10); + var stored = held switch + { + Held.FreshWindowed => EntryFrame.Write(inner, _time.GetUtcNow().AddMinutes(1), Window, null), + Held.ExpiredByFrame => EntryFrame.Write(inner, _time.GetUtcNow().AddMinutes(-1), Window, null), + Held.ExpiredByKey => EntryFrame.Write(inner, _time.GetUtcNow().AddHours(1), Window, null), + Held.ValidatorsOnly or Held.FramedNull => EntryFrame.Write(inner, DateTimeOffset.MaxValue, TimeSpan.Zero, EntryValidators.From("\"e\"", null)), + _ => inner, + }; + await StoreAsync(raw, stored, held == Held.ExpiredByKey ? Window - TimeSpan.FromSeconds(5) : keyTtl); + var comparer = new CountingComparer(); + var value = equal ? storedValue : "new"; + + var result = await node.Cache.SetIfChangedAsync(key, value, comparer, Long, null, Ct); + var after = (byte[]?)await Db.StringGetAsync(raw); + + switch (held) + { + case Held.FreshWindowed when equal: + result.Outcome.Should().Be(ChangeOutcome.Unchanged); + result.Expiration!.Value.Should().BeCloseTo(_time.GetUtcNow().AddMinutes(1), Slack, "the logical expiration, never the key's deadline"); + after.Should().Equal(stored); + break; + case Held.ExpiredByFrame or Held.ExpiredByKey: + comparer.Calls.Should().Be(0, "an expired frame counts as absent"); + result.Outcome.Should().Be(ChangeOutcome.Replaced); + after.Should().Equal(node.Codec.Encode(value!, null)); + break; + case not Held.FreshWindowed when equal: + result.Outcome.Should().Be(ChangeOutcome.Unchanged); + result.Expiration!.Value.Should().BeCloseTo(_time.GetUtcNow() + keyTtl, Slack, "the key's deadline, as today"); + after.Should().Equal(stored); + break; + default: + result.Outcome.Should().Be(ChangeOutcome.Replaced); + after.Should().Equal(node.Codec.Encode("new", null)); + break; + } + } + + [Theory] + [InlineData(Scripts.Off)] + [InlineData(Scripts.On)] + public async Task A_layered_SetIfChanged_over_an_unchanged_frame_keeps_the_local_copy_until_the_logical_expiration(Scripts scripts) + { + var node = await NodeAsync(scripts); + var (key, raw) = await KeyAsync(node); + await StoreFrameAsync(node, raw, "A", TimeSpan.FromSeconds(10)); + + var result = await node.Layered.SetIfChangedAsync(key, "A", StringComparer.Ordinal, Long, null, Ct); + _time.Advance(TimeSpan.FromSeconds(11)); + + result.Outcome.Should().Be(ChangeOutcome.Unchanged); + (await HoldsLocalCopyAsync(node, key, raw)).Should().BeFalse("the local copy ended at the logical expiration, ten seconds out"); + } + + [Theory] + [InlineData(Scripts.Off)] + [InlineData(Scripts.On)] + public async Task SetIfChangedAsync_reads_a_fresh_windowed_frame_again_before_the_comparer_runs(Scripts scripts) + { + var node = await NodeAsync(scripts); + var (key, raw) = await KeyAsync(node); + await StoreFrameAsync(node, raw, "A", TimeSpan.FromMinutes(1)); + node.Redis.BeforeAnchoredRead = async () => + { + node.Redis.BeforeAnchoredRead = null; + await StoreFrameAsync(node, raw, "B", TimeSpan.FromMinutes(1)); + }; + var comparer = new CountingComparer(); + node.ClearLog(); + + var result = await node.Cache.SetIfChangedAsync(key, "C", comparer, Long, null, Ct); + + comparer.Seen.Should().Equal(["B"], "the comparer sees the second read alone, and the compare-and-set expects its bytes"); + result.Outcome.Should().Be(ChangeOutcome.Replaced); + ((byte[]?)await Db.StringGetAsync(raw)).Should().Equal(node.Codec.Encode("C", null)); + node.Log().Count(c => c == "MULTI").Should().BeGreaterThanOrEqualTo(2, "the snapshot, then the anchored read"); + } + + [Fact] + public async Task An_unchanged_answer_counts_from_before_the_send() + { + var node = await NodeAsync(); + var (key, raw) = await KeyAsync(node); + + await StoreFrameAsync(node, raw, "A", TimeSpan.FromHours(1), keyTtl: Window + TimeSpan.FromSeconds(10)); + var sent = _time.GetUtcNow(); + OnceAfterReply(node, () => _time.Advance(Hold)); + var unchanged = await node.Cache.SetIfChangedAsync(key, "A", StringComparer.Ordinal, Long, null, Ct); + + await StoreFrameAsync(node, raw, "A", TimeSpan.FromHours(1), keyTtl: Window + TimeSpan.FromSeconds(1)); + OnceAfterReply(node, () => _time.Advance(Hold)); + var expired = await node.Cache.SetIfChangedAsync(key, "A", StringComparer.Ordinal, Long, null, Ct); + + unchanged.Outcome.Should().Be(ChangeOutcome.Unchanged); + unchanged.Expiration!.Value.Should().BeCloseTo(sent + TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(1)); + expired.Outcome.Should().Be(ChangeOutcome.Replaced, "the frame was expired at the judgment, so the new value is stored"); + ((byte[]?)await Db.StringGetAsync(raw)).Should().Equal(node.Codec.Encode("A", null)); + } + + [Fact] + public async Task A_comparer_that_throws_on_a_framed_value_reaches_the_caller() + { + var node = await NodeAsync(); + var (key, raw) = await KeyAsync(node); + await StoreFrameAsync(node, raw, "A", TimeSpan.FromMinutes(1)); + + var act = async () => await node.Cache.SetIfChangedAsync(key, "B", new ThrowingComparer(), Long, null, Ct); + + await act.Should().ThrowAsync().WithMessage("comparer"); + } + + [Fact] + public async Task A_failed_second_read_of_SetIfChangedAsync_is_a_Redis_failure() + { + var node = await NodeAsync(); + var (key, raw) = await KeyAsync(node); + var stored = EntryFrame.Write(node.Codec.Encode("A", null), _time.GetUtcNow().AddMinutes(1), Window, null); + await StoreAsync(raw, stored, Window * 2); + node.Redis.AfterAnchoredRead = () => throw new TimeoutException("injected"); + + var result = await node.Cache.SetIfChangedAsync(key, "B", StringComparer.Ordinal, Long, null, Ct); + + result.Outcome.Should().Be(ChangeOutcome.Failed); + ((byte[]?)await Db.StringGetAsync(raw)).Should().Equal(stored); + } + + [Theory] + [InlineData(Generated.Single)] + [InlineData(Generated.Batch)] + public async Task An_unreadable_fill_loser_that_became_a_fresh_frame_before_the_repair_is_left_alone(Generated shape) + { + var (node, key, raw) = await UnreadableLoserAsync(); + node.Redis.BeforeUnreadableReread = async () => + { + node.Redis.BeforeUnreadableReread = null; + await StoreFrameAsync(node, raw, "F", TimeSpan.FromMinutes(1), keyTtl: TimeSpan.FromHours(1)); + }; + + var answer = await GenerateOverUnreadableAsync(node, key, raw, shape); + + node.Redis.BeforeUnreadableReread.Should().BeNull("the fill read the unreadable bytes and went to repair them"); + TryReadFrame(await Db.StringGetAsync(raw), out var frame).Should().BeTrue("the frame is still there"); + node.Codec.Decode(frame.Inner.ToArray(), null).Value.Should().Be("F"); + if (shape == Generated.Single) + { + answer.Should().Be("F"); + } + } + + [Theory] + [InlineData(Generated.Single)] + [InlineData(Generated.Batch)] + public async Task An_unreadable_fill_loser_that_became_an_expired_frame_is_not_replaced_as_unreadable(Generated shape) + { + var (node, key, raw) = await UnreadableLoserAsync(); + byte[]? expired = null; + node.Redis.BeforeUnreadableReread = async () => + { + node.Redis.BeforeUnreadableReread = null; + expired = EntryFrame.Write(node.Codec.Encode("F", null), _time.GetUtcNow().AddMinutes(-1), Window, null); + await StoreAsync(raw, expired, TimeSpan.FromHours(1)); + }; + + await GenerateOverUnreadableAsync(node, key, raw, shape); + + expired.Should().NotBeNull("the fill read the unreadable bytes and went to repair them"); + ((byte[]?)await Db.StringGetAsync(raw)).Should().Equal(expired); + } + + private static bool TryReadFrame(RedisValue value, out EntryFrame frame) => EntryFrame.TryRead((byte[]?)value ?? [], out frame); + + private async Task<(Node Node, CacheKey Key, RedisKey Raw)> UnreadableLoserAsync() + { + var node = await NodeAsync(configure: o => + { + o.RemoveTombstone = TimeSpan.FromSeconds(30); + o.RemoveUnreadable = false; + }); + var (key, raw) = await KeyAsync(node); + await Db.KeyDeleteAsync(raw); + return (node, key, raw); + } + + /// A GetOrAdd whose probe misses; its generator stores bytes nothing reads, so its fill loses to them. + private async Task GenerateOverUnreadableAsync(Node node, CacheKey key, RedisKey raw, Generated shape) + { + if (shape == Generated.Single) + { + return await node.Cache.GetOrAddAsync( + key, + async _ => + { + await Db.StringSetAsync(raw, "not json{", TimeSpan.FromHours(1)); + return "generated"; + }, + Long, + Ct); + } + + var result = await node.Cache.GetOrAddAsync( + [new(key, 1)], + async (states, _) => + { + await Db.StringSetAsync(raw, "not json{", TimeSpan.FromHours(1)); + return [.. states.Select(s => new KeyValuePair(s, "generated"))]; + }, + Long, + null, + Ct); + return result.Single().Value; + } + + private sealed class CountingComparer : IEqualityComparer + { + public int Calls => Seen.Count; + + public List Seen { get; } = []; + + public bool Equals(string? x, string? y) + { + Seen.Add(x); + return string.Equals(x, y, StringComparison.Ordinal); + } + + public int GetHashCode(string obj) => obj.GetHashCode(StringComparison.Ordinal); + } + + private sealed class ThrowingComparer : IEqualityComparer + { + public bool Equals(string? x, string? y) => throw new InvalidOperationException("comparer"); + + public int GetHashCode(string obj) => 0; + } +} diff --git a/tests/UiPath.Caching.Tests/Redis/EntryFrameReadIntegrationTests.cs b/tests/UiPath.Caching.Tests/Redis/EntryFrameReadIntegrationTests.cs new file mode 100644 index 00000000..a3278f29 --- /dev/null +++ b/tests/UiPath.Caching.Tests/Redis/EntryFrameReadIntegrationTests.cs @@ -0,0 +1,411 @@ +using System.Net; +using System.Reflection; +using System.Runtime.ExceptionServices; +using Microsoft.Extensions.DependencyInjection; +using StackExchange.Redis; +using UiPath.Caching.Config; +using UiPath.Caching.Policies; +using UiPath.Caching.Redis; + +namespace UiPath.Caching.Tests.Redis; + +// Frames are written raw, with StringSet and a TTL. Redis counts a TTL on real time while the reader judges on its +// ManualTimeProvider, so every deadline is compared within Slack, and every hold of a reply is a step of that clock. +[Collection("RedisIntegration")] +[Trait("Category", "Integration")] +public sealed partial class EntryFrameReadIntegrationTests(RedisContainerFixture fixture) : IAsyncDisposable +{ + private static readonly TimeSpan Window = TimeSpan.FromSeconds(60); + private static readonly TimeSpan Long = TimeSpan.FromMinutes(10); + private static readonly TimeSpan Slack = TimeSpan.FromSeconds(2); + private static readonly TimeSpan Hold = TimeSpan.FromSeconds(5); + + private readonly ManualTimeProvider _time = new(fixture.TimeOrigin); + private readonly string _run = Guid.NewGuid().ToString("N")[..10]; + private readonly List _nodes = []; + private ConnectionMultiplexer? _admin; + + public enum Scripts + { + Off, + On, + Refused, + } + + public enum Read + { + Get, + BatchGet, + Probe, + Entry, + BatchEntry, + Snapshot, + Result, + Layered, + LayeredBatch, + Fill, + Change, + } + + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + private IDatabase Db => _admin!.GetDatabase(); + + public async ValueTask DisposeAsync() + { + foreach (var node in _nodes) + { + await node.DisposeAsync(); + } + + if (_admin is not null) + { + await _admin.DisposeAsync(); + } + } + + private static TheoryData Cross(Read[] reads, Scripts[] scripts) + { + var data = new TheoryData(); + foreach (var read in reads) + { + foreach (var mode in scripts) + { + data.Add(read, mode); + } + } + + return data; + } + + private static bool IsScript(string command) => command is "EVAL_RO" or "EVALSHA_RO"; + + private static async Task ProbeAsync(ICache cache, CacheKey key) + { + var ran = false; + var value = await cache.GetOrAddAsync( + key, + _ => + { + ran = true; + return Task.FromResult("generated"); + }, + Long, + Ct); + return new Answer(!ran, ran ? null : value, null, ran); + } + + /// A frame whose frame expiration is from the reader's now, on a key whose TTL is , the life plus the window by default. + private async Task StoreFrameAsync(Node node, RedisKey raw, string? value, TimeSpan life, TimeSpan? keyTtl = null, EntryValidators? validators = null, TimeSpan? window = null) + { + var inner = value is null ? [] : node.Codec.Encode(value, null); + var bytes = EntryFrame.Write(inner, life == TimeSpan.MaxValue ? DateTimeOffset.MaxValue : _time.GetUtcNow() + life, window ?? Window, validators); + await StoreAsync(raw, bytes, keyTtl ?? life + (window ?? Window)); + } + + private async Task StoreAsync(RedisKey raw, byte[] bytes, TimeSpan? keyTtl) + { + (await Db.StringSetAsync(raw, bytes)).Should().BeTrue(); + if (keyTtl is { } ttl) + { + (await Db.KeyExpireAsync(raw, ttl)).Should().BeTrue(); + } + } + + private Task StorePlainAsync(Node node, RedisKey raw, string value, TimeSpan? keyTtl) => StoreAsync(raw, node.Codec.Encode(value, null), keyTtl); + + private async Task<(CacheKey Key, RedisKey Raw)> KeyAsync(Node node, string? tag = null) + { + var id = Guid.NewGuid().ToString("N"); + CacheKey key = $"{{{tag ?? id}}}{id}"; + (await node.Cache.SetAsync(key, "seed", Long, Ct)).Should().BeTrue(); + return (key, RedisTestKeys.Keys(_admin!, $"*{id}").Single()); + } + + private async Task NodeAsync(Scripts scripts = Scripts.Off, Action? configure = null, Action? services = null, Func? user = null) + { + Assert.SkipUnless(fixture.Enabled, "Set RUN_REDIS_INTEGRATION_TESTS=1 (Docker required) to run."); + if (scripts == Scripts.On) + { + Assert.SkipUnless(fixture.SupportsEvalRo && fixture.ServerVersion.Major >= 7, "The read script needs EVAL_RO and PEXPIRETIME."); + } + + _admin ??= await ConnectionMultiplexer.ConnectAsync(fixture.ConnectionString + ",allowAdmin=true"); + var connectionString = fixture.ConnectionString; + string? aclUser = null; + var rules = scripts == Scripts.Refused ? "-@scripting" : null; + if (user is not null || rules is not null) + { + Assert.SkipUnless(fixture.SupportsAcl, "Needs ACL SETUSER, which this server does not allow."); + aclUser = $"it-frame-{Guid.NewGuid():N}"; + var extra = user?.Invoke(aclUser) ?? rules!; + await RedisTestKeys.OnPrimariesAsync(_admin, "ACL", "SETUSER", aclUser, "on", ">pw", "~*", "&*", "+@all", extra); + connectionString += $",user={aclUser},password=pw"; + } + + var mux = await ConnectionMultiplexer.ConnectAsync(connectionString); + var log = new CommandLog(); + var collection = new ServiceCollection().AddSingleton(_time).AddSingleton(new TestConnector(mux, log)); + services?.Invoke(collection); + var provider = collection + .AddCaching( + b => + { + b.AddRedisConnection(o => o.ConnectionString = connectionString); + b.AddRedis(o => + { + o.ReadScriptsEnabled = scripts != Scripts.Off; + configure?.Invoke(o); + }); + b.AddInMemoryRedis(o => o.LocalMaxExpiration = TimeSpan.FromHours(2)); + }, + o => o.AppShortName = "fr" + _run) + .BuildServiceProvider(); + var node = new Node(provider, mux, log, aclUser, _admin); + _nodes.Add(node); + return node; + } + + private async Task ReadAsync(Node node, Read read, CacheKey key, string equalTo = "A") + { + var cache = node.Cache; + switch (read) + { + case Read.Get: + var value = await cache.GetAsync(key, null, Ct); + return new Answer(value is not null, value, null, false); + case Read.BatchGet: + var values = await cache.GetAsync([key], null, Ct); + return new Answer(values[0].Value is not null, values[0].Value, null, false); + case Read.Probe: + return await ProbeAsync(cache, key); + case Read.Entry: + return Answer.Of(await cache.GetCacheEntryAsync(key, null, Ct)); + case Read.BatchEntry: + return Answer.Of((await cache.GetCacheEntriesAsync([key], null, Ct))[0].Value); + case Read.Snapshot: + var snapshot = await ((IMigrationCache)node.Redis).ReadSnapshotAsync(key, null, Ct); + return snapshot.Outcome == SnapshotOutcome.Found ? Answer.Of(snapshot.Entry!) : new Answer(false, null, null, false, snapshot.Outcome); + case Read.Result: + var result = await cache.GetOrAddResultAsync(key, _ => Task.FromResult("generated"), Long, null, Ct); + return new Answer(!result.WasGenerated, result.WasGenerated ? null : result.Value, result.Expiration, result.WasGenerated); + case Read.Layered: + var layered = await node.Layered.GetAsync(key, null, Ct); + return new Answer(layered is not null, layered, null, false); + case Read.LayeredBatch: + var batch = await node.Layered.GetAsync([key], null, Ct); + return new Answer(batch[0].Value is not null, batch[0].Value, null, false); + case Read.Fill: + var fill = await cache.TryFillAsync(key, "filler", Long, null, Ct); + return new Answer(fill.Outcome == FillOutcome.Existed, fill.Existing, fill.Expiration, fill.Outcome == FillOutcome.Added, Fill: fill.Outcome); + default: + var change = await cache.SetIfChangedAsync(key, equalTo, StringComparer.Ordinal, Long, null, Ct); + return new Answer(change.Outcome == ChangeOutcome.Unchanged, change.Current, change.Expiration, change.Outcome != ChangeOutcome.Unchanged, Change: change.Outcome); + } + } + + /// Whether the layered cache answers from a local copy: Redis is rewritten raw, which no local copy hears. + private async Task HoldsLocalCopyAsync(Node node, CacheKey key, RedisKey raw) + { + await StorePlainAsync(node, raw, "redis-now", Long); + var local = await node.Layered.GetAsync(key, null, Ct) != "redis-now"; + // The probe's own value is not left in the local tier. + await node.Layered.RemoveAsync(key, Ct); + return local; + } + + private void OnceAfterReply(Node node, Action act) + { + node.Redis.AfterAnchoredRead = () => + { + node.Redis.AfterAnchoredRead = null; + act(); + return Task.CompletedTask; + }; + } + + private readonly record struct Answer(bool Found, string? Value, DateTimeOffset? Expiration, bool Generated, SnapshotOutcome Snapshot = SnapshotOutcome.Found, FillOutcome Fill = FillOutcome.Failed, ChangeOutcome Change = ChangeOutcome.Failed) + { + public static Answer Of(ICacheEntry entry) => + new(entry.Found, entry.Value, entry.Found ? entry.Expiration : null, false); + } + + /// The commands the cache asked its client for, in the order it asked, with their flags; a transaction is MULTI, its queued commands, then EXEC. + public sealed class CommandLog + { + private readonly List<(string Command, CommandFlags Flags)> _entries = []; + + /// Runs on the calling thread for each command, before it is sent; a test writes the key there. + public Action? OnCommand { get; set; } + + public void Add(string command, CommandFlags flags) + { + lock (_entries) + { + _entries.Add((command, flags)); + } + + OnCommand?.Invoke(command); + } + + public List<(string Command, CommandFlags Flags)> Take() + { + lock (_entries) + { + var taken = _entries.ToList(); + _entries.Clear(); + return taken; + } + } + } + + /// Records each command a database or a transaction is asked for, then forwards it. + public class Recorder : DispatchProxy + { + private object _target = null!; + private CommandLog _log = null!; + + public static T Wrap(T target, CommandLog log) + where T : class + { + var proxy = Create(); + var recorder = (Recorder)(object)proxy; + recorder._target = target; + recorder._log = log; + return proxy; + } + + protected override object? Invoke(MethodInfo? targetMethod, object?[]? args) + { + var method = targetMethod!; + if (Name(method, args) is { } command) + { + _log.Add(command, args?.OfType().LastOrDefault() ?? CommandFlags.None); + } + + object? result; + try + { + result = method.Invoke(_target, args); + } + catch (TargetInvocationException ex) when (ex.InnerException is not null) + { + ExceptionDispatchInfo.Throw(ex.InnerException); + throw; + } + + return result is ITransaction transaction ? Wrap(transaction, _log) : result; + } + + private static string? Name(MethodInfo method, object?[]? args) => + method.Name switch + { + _ when method.IsSpecialName => null, + "StringGetAsync" => args is [RedisKey[], ..] ? "MGET" : "GET", + "KeyTimeToLiveAsync" => "PTTL", + "CreateTransaction" => "MULTI", + "ExecuteAsync" when method.DeclaringType == typeof(ITransaction) => "EXEC", + "ScriptEvaluateReadOnlyAsync" => "EVAL_RO", + "ScriptEvaluateAsync" => "EVAL", + "StringSetAsync" => "SET", + "KeyExistsAsync" => "EXISTS", + _ => method.Name, + }; + } + + /// A connector over the test's own connection, so its commands can be profiled. + internal sealed class TestConnector(IConnectionMultiplexer mux, CommandLog log) : IRedisConnector + { + private readonly IDatabase _database = Recorder.Wrap(mux.GetDatabase(), log); + + public event EventHandler? OnConnectionFailed + { + add { /* Expected: this connector never raises the event. */ } + remove { /* Expected: nothing is attached. */ } + } + + public event EventHandler? OnConnectionRestored + { + add { /* Expected: this connector never raises the event. */ } + remove { /* Expected: nothing is attached. */ } + } + + public event EventHandler? OnReconnected + { + add { /* Expected: this connector never raises the event. */ } + remove { /* Expected: nothing is attached. */ } + } + + public bool IsConnected => mux.IsConnected; + + public Version Version => mux.GetServer(mux.GetEndPoints()[0]).Version; + + public IDatabase Database => _database; + + public ISubscriber Subscriber => mux.GetSubscriber(); + + public void ForceReconnect() + { + } + + public EndPoint[] GetEndPoints(bool configuredOnly = false) => mux.GetEndPoints(configuredOnly); + + public void Dispose() + { + } + } + + private sealed class Node(ServiceProvider provider, ConnectionMultiplexer mux, CommandLog log, string? aclUser, ConnectionMultiplexer admin) : IAsyncDisposable + { + public ICacheFactory Factory => provider.GetRequiredService(); + + public RedisCache Redis => (RedisCache)Factory.CreateCache(KnownCacheProviderNames.Redis); + + public ICache Cache => Redis; + + public IByteCodecCache Codec => Redis; + + public ICache Layered => Factory.CreateCache(KnownCacheProviderNames.InMemoryRedis); + + public void ClearLog() => log.Take(); + + public List Log() => [.. log.Take().Select(c => c.Command)]; + + public List<(string Command, CommandFlags Flags)> RawLog() => log.Take(); + + public async ValueTask DisposeAsync() + { + await provider.DisposeAsync(); + await mux.DisposeAsync(); + if (aclUser is not null) + { + await RedisTestKeys.OnPrimariesAsync(admin, "ACL", "DELUSER", aclUser); + } + } + } + + /// A read pipeline that runs a failed attempt once more, as a retry strategy does. + private sealed class RetryOnceProvider : IResiliencePipelineProvider + { + public IResiliencePipeline Get(string? name) => name == ResiliencePipelineNames.Read ? RetryOnce.Instance : EmptyResiliencePipeline.Instance; + + private sealed class RetryOnce : IResiliencePipeline + { + public static readonly RetryOnce Instance = new(); + + public async ValueTask ExecuteAsync(Func> callback, TResult defaultValue, CancellationToken cancellationToken = default) + { + try + { + return await callback(cancellationToken); + } + catch (InjectedFault) + { + return await callback(cancellationToken); + } + } + } + } + + private sealed class InjectedFault() : Exception("injected"); +} diff --git a/tests/UiPath.Caching.Tests/Redis/EntryFrameTests.cs b/tests/UiPath.Caching.Tests/Redis/EntryFrameTests.cs new file mode 100644 index 00000000..59bc0742 --- /dev/null +++ b/tests/UiPath.Caching.Tests/Redis/EntryFrameTests.cs @@ -0,0 +1,257 @@ +using System.Buffers.Binary; +using System.Text; +using UiPath.Caching.Redis; + +namespace UiPath.Caching.Tests.Redis; + +public class EntryFrameTests +{ + private static readonly DateTimeOffset Expiration = DateTimeOffset.FromUnixTimeMilliseconds(1_725_001_002_003); + private static readonly TimeSpan Window = TimeSpan.FromSeconds(60); + private static ReadOnlySpan Inner => """{"value":123}"""u8; + + [Theory] + [InlineData(1)] + [InlineData(2)] + [InlineData(3)] + [InlineData(4)] + [InlineData(5)] + [InlineData(6)] + [InlineData(7)] + public void Each_flag_combination_round_trips(byte flags) + { + var window = (flags & 1) == 0 ? TimeSpan.Zero : Window; + var lastModified = (flags & 2) == 0 ? (DateTimeOffset?)null : Expiration.AddDays(-1); + var etag = (flags & 4) == 0 ? null : "\"café\""; + var bytes = EntryFrame.Write(Inner, Expiration, window, EntryValidators.From(etag, lastModified)); + + bytes.AsSpan(0, 3).ToArray().Should().Equal(0x0E, 1, flags); + var frame = Read(bytes); + frame.HasWindow.Should().Be(window > TimeSpan.Zero); + frame.Window.Should().Be(window); + if (frame.HasWindow) + { + frame.Expiration.Should().Be(Expiration); + } + + frame.LastModified.Should().Be(lastModified); + frame.ETag.Should().Be(etag); + frame.Inner.ToArray().Should().Equal(Inner.ToArray()); + } + + [Fact] + public void An_empty_inner_value_round_trips() + { + var bytes = EntryFrame.Write( + [], + DateTimeOffset.UnixEpoch, + TimeSpan.FromSeconds(1), + EntryValidators.From("ok", DateTimeOffset.UnixEpoch.AddMilliseconds(1))); + + bytes.Should().Equal(EntryFrameVectors.FullFrame); + Read(bytes).Inner.IsEmpty.Should().BeTrue(); + } + + [Fact] + public void The_frame_expiration_sits_at_offset_3() + { + var bytes = EntryFrame.Write(Inner, Expiration, Window, null); + + EntryFrame.ExpirationOffset.Should().Be(3); + EntryFrame.HeadLength.Should().Be(15); + BinaryPrimitives.ReadInt64LittleEndian(bytes.AsSpan(3, 8)).Should().Be(Expiration.ToUnixTimeMilliseconds()); + BinaryPrimitives.ReadUInt32LittleEndian(bytes.AsSpan(11, 4)).Should().Be(60); + } + + [Fact] + public void Never_is_long_MaxValue() + { + var bytes = EntryFrame.Write(Inner, DateTimeOffset.MaxValue, Window, null); + + BinaryPrimitives.ReadInt64LittleEndian(bytes.AsSpan(3, 8)).Should().Be(long.MaxValue); + Read(bytes).Expiration.Should().Be(DateTimeOffset.MaxValue); + } + + [Theory] + [MemberData(nameof(EntryFrameVectors.GrammarCases), MemberType = typeof(EntryFrameVectors))] + public void The_frame_grammar_matches_the_shared_vectors(string name, byte[] bytes, bool expected) => + EntryFrame.TryRead(bytes, out _).Should().Be(expected, name); + + [Fact] + public void An_unknown_version_is_not_a_frame() => + EntryFrame.TryRead(EntryFrameVectors.WithByte(1, 2), out _).Should().BeFalse(); + + [Fact] + public void A_reserved_flag_bit_is_not_a_frame() => + EntryFrame.TryRead(EntryFrameVectors.WithByte(2, 0x87), out _).Should().BeFalse(); + + [Fact] + public void No_flag_is_not_a_frame() => + EntryFrame.TryRead(EntryFrameVectors.WithByte(2, 0), out _).Should().BeFalse(); + + [Theory] + [MemberData(nameof(EntryFrameVectors.TruncatedLengths), MemberType = typeof(EntryFrameVectors))] + public void A_truncated_frame_is_not_a_frame(int length) => + EntryFrame.TryRead(EntryFrameVectors.FullFrame.AsMemory(0, length), out _).Should().BeFalse(); + + [Fact] + public void A_zero_window_is_not_a_frame() => + EntryFrame.TryRead(EntryFrameVectors.WithByte(11, 0), out _).Should().BeFalse(); + + [Fact] + public void An_ETag_length_past_the_end_is_not_a_frame() => + EntryFrame.TryRead(EntryFrameVectors.WithByte(23, 3), out _).Should().BeFalse(); + + [Fact] + public void A_zero_ETag_length_is_not_a_frame() => + EntryFrame.TryRead(EntryFrameVectors.WithByte(23, 0), out _).Should().BeFalse(); + + [Theory] + [InlineData(0x0E)] + [InlineData(0x0F)] + public void A_nested_frame_or_tombstone_is_not_a_frame(byte header) => + EntryFrame.TryRead(EntryFrameVectors.WithInner(header), out _).Should().BeFalse(); + + [Fact] + public void An_ETag_that_is_not_UTF8_reads_as_null_and_the_frame_still_reads() => + Read(EntryFrameVectors.InvalidUtf8).ETag.Should().BeNull(); + + [Theory] + [MemberData(nameof(EntryFrameVectors.JsonText), MemberType = typeof(EntryFrameVectors))] + public void Json_text_is_never_a_frame(string json) => + EntryFrame.TryRead(Encoding.UTF8.GetBytes(json), out _).Should().BeFalse(); + + [Theory] + [InlineData("0E01", false)] + [InlineData("0E0201", false)] + [InlineData("0F0101", false)] + [InlineData("0E0106", false)] + [InlineData("0E0101", true)] + [InlineData("0E0181", true)] + public void LooksWindowed_checks_only_the_prefix_and_window_bit(string hex, bool expected) + { + var bytes = Convert.FromHexString(hex); + + EntryFrame.LooksWindowed(bytes).Should().Be(expected); + EntryFrame.TryRead(bytes, out _).Should().BeFalse(); + } + + [Theory] + [InlineData(1, 1u)] + [InlineData(19_000_000, 1u)] + [InlineData(long.MaxValue, uint.MaxValue)] + public void The_window_is_stored_as_bounded_whole_seconds(long ticks, uint expectedSeconds) + { + var bytes = EntryFrame.Write(Inner, Expiration, TimeSpan.FromTicks(ticks), null); + + BinaryPrimitives.ReadUInt32LittleEndian(bytes.AsSpan(11, 4)).Should().Be(expectedSeconds); + Read(bytes).Window.Should().Be(TimeSpan.FromSeconds(expectedSeconds)); + } + + [Fact] + public void Needed_is_false_for_a_stored_lifetime_alone() => + EntryFrame.Needed(TimeSpan.Zero, EntryValidators.From(null, null, Window)).Should().BeFalse(); + + [Theory] + [InlineData(0)] + [InlineData(513)] + public void Needed_is_false_when_the_only_validator_is_an_oversized_or_empty_ETag(int length) => + EntryFrame.Needed(TimeSpan.Zero, EntryValidators.From(new string('é', length), null)).Should().BeFalse(); + + [Fact] + public void Needed_is_true_for_a_window_alone() => + EntryFrame.Needed(Window, null).Should().BeTrue(); + + [Fact] + public void An_ETag_at_the_UTF8_byte_limit_round_trips() + { + var etag = new string('é', 512); + var validators = EntryValidators.From(etag, null); + + EntryFrame.Needed(TimeSpan.Zero, validators).Should().BeTrue(); + Read(EntryFrame.Write(Inner, Expiration, TimeSpan.Zero, validators)).ETag.Should().Be(etag); + } + + [Fact] + public void Write_leaves_out_an_oversized_ETag_and_keeps_the_rest() + { + var frame = Read(EntryFrame.Write(Inner, Expiration, Window, EntryValidators.From(new string('é', 513), Expiration))); + + frame.ETag.Should().BeNull(); + frame.LastModified.Should().Be(Expiration); + frame.Window.Should().Be(Window); + frame.Inner.ToArray().Should().Equal(Inner.ToArray()); + } + + [Theory] + [InlineData(0, 65, 5)] + [InlineData(-10, 55, -5)] + [InlineData(10, 65, -5)] + [InlineData(0, 15, -45)] + public void LogicalExpiration_is_the_earlier_of_the_frame_expiration_and_the_key_deadline_less_the_window( + int readerSkewSeconds, int ttlSeconds, int expiresInSeconds) + { + var writerNow = Expiration.AddSeconds(-5); + var reader = new ManualTimeProvider(writerNow.AddSeconds(readerSkewSeconds)); + var frame = Read(EntryFrame.Write(Inner, Expiration, Window, null)); + var now = reader.GetUtcNow(); + + frame.LogicalExpiration(now.AddSeconds(ttlSeconds)).Should().Be(now.AddSeconds(expiresInSeconds)); + } + + [Fact] + public void A_finite_frame_on_a_key_with_no_ttl_is_long_expired() + { + var frame = Read(EntryFrame.Write(Inner, Expiration, Window, null)); + + frame.LogicalExpiration(null).Should().Be(DateTimeOffset.MinValue); + frame.StaleUntil(null).Should().Be(DateTimeOffset.MinValue); + } + + [Fact] + public void A_never_frame_on_a_key_with_no_ttl_is_never_fresh() + { + var clock = new ManualTimeProvider(Expiration); + var frame = Read(EntryFrame.Write(Inner, DateTimeOffset.MaxValue, Window, null)); + frame.LogicalExpiration(clock.GetUtcNow() + Window + Window).Should().BeAfter(clock.GetUtcNow()); + + clock.Advance(TimeSpan.FromSeconds(1)); + + frame.LogicalExpiration(null).Should().Be(DateTimeOffset.MinValue); + frame.StaleUntil(null).Should().Be(DateTimeOffset.MinValue); + } + + [Fact] + public void A_never_frame_on_a_key_with_a_ttl_expires_with_the_key_less_the_window() + { + var frame = Read(EntryFrame.Write(Inner, DateTimeOffset.MaxValue, Window, null)); + + frame.LogicalExpiration(Expiration).Should().Be(Expiration - Window); + } + + [Theory] + [InlineData(30, 30)] + [InlineData(90, 60)] + public void StaleUntil_never_passes_the_key_deadline(int keyLifeSeconds, int staleForSeconds) + { + var frame = Read(EntryFrame.Write(Inner, Expiration, Window, null)); + + frame.StaleUntil(Expiration.AddSeconds(keyLifeSeconds)).Should().Be(Expiration.AddSeconds(staleForSeconds)); + } + + [Fact] + public void StaleUntil_does_not_overflow_for_a_never_frame() + { + var frame = Read(EntryFrame.Write(Inner, DateTimeOffset.MaxValue, Window, null)); + + frame.StaleUntil(DateTimeOffset.MaxValue).Should().Be(DateTimeOffset.MaxValue); + frame.LogicalExpiration(DateTimeOffset.MinValue).Should().Be(DateTimeOffset.MinValue); + frame.StaleUntil(DateTimeOffset.MinValue).Should().Be(DateTimeOffset.MinValue); + } + + private static EntryFrame Read(byte[] bytes) + { + EntryFrame.TryRead(bytes, out var frame).Should().BeTrue(); + return frame; + } +} diff --git a/tests/UiPath.Caching.Tests/Redis/EntryFrameVectors.cs b/tests/UiPath.Caching.Tests/Redis/EntryFrameVectors.cs new file mode 100644 index 00000000..fdee05a8 --- /dev/null +++ b/tests/UiPath.Caching.Tests/Redis/EntryFrameVectors.cs @@ -0,0 +1,68 @@ +using System.Text; + +namespace UiPath.Caching.Tests.Redis; + +internal static class EntryFrameVectors +{ + public static byte[] FullFrame { get; } = + [ + 0x0E, 1, 7, + 0, 0, 0, 0, 0, 0, 0, 0, + 1, 0, 0, 0, + 1, 0, 0, 0, 0, 0, 0, 0, + 2, 0, (byte)'o', (byte)'k', + ]; + + public static byte[] InvalidUtf8 { get; } = [0x0E, 1, 4, 1, 0, 0xFF]; + + public static TheoryData TruncatedLengths => new(Enumerable.Range(0, FullFrame.Length)); + + public static TheoryData JsonText => new(new[] { "{}", "[]", "\"text\"", "123", "true", "null", " \t\r\n{}" }); + + public static TheoryData GrammarCases + { + get + { + var cases = new TheoryData + { + { "all fields with empty inner", FullFrame, true }, + { "invalid UTF-8", InvalidUtf8, true }, + { "expiration before the representable range", [0x0E, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0x80, 1, 0, 0, 0], true }, + { "last modified after the representable range", [0x0E, 1, 2, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F], true }, + { "maximum ETag", ETag(1024), true }, + { "oversized ETag", ETag(1025), false }, + { "unknown version", WithByte(1, 2), false }, + { "reserved flag", WithByte(2, 0x87), false }, + { "no flags", WithByte(2, 0), false }, + { "zero window", WithByte(11, 0), false }, + { "ETag past end", WithByte(23, 3), false }, + { "zero ETag length", WithByte(23, 0), false }, + { "nested frame", WithInner(0x0E), false }, + { "nested tombstone", WithInner(0x0F), false }, + }; + + foreach (var length in Enumerable.Range(0, FullFrame.Length)) + { + cases.Add($"truncated at {length}", FullFrame[..length], false); + } + + foreach (var row in JsonText) + { + cases.Add($"JSON {row.Data}", Encoding.UTF8.GetBytes(row.Data), false); + } + + return cases; + } + } + + public static byte[] WithByte(int index, byte value) + { + var bytes = FullFrame.ToArray(); + bytes[index] = value; + return bytes; + } + + public static byte[] WithInner(byte header) => [.. FullFrame, header]; + + private static byte[] ETag(int length) => [0x0E, 1, 4, (byte)length, (byte)(length >> 8), .. Enumerable.Repeat((byte)'x', length)]; +} diff --git a/tests/UiPath.Caching.Tests/Redis/FormatInventoryIntegrationTests.cs b/tests/UiPath.Caching.Tests/Redis/FormatInventoryIntegrationTests.cs index 29d2587c..ea44e5c3 100644 --- a/tests/UiPath.Caching.Tests/Redis/FormatInventoryIntegrationTests.cs +++ b/tests/UiPath.Caching.Tests/Redis/FormatInventoryIntegrationTests.cs @@ -60,6 +60,45 @@ public async Task A_remove_tombstone_is_counted_under_no_format() counts.Should().BeEquivalentTo(new Dictionary { ["json"] = 2 }, "a tombstone holds no value, so it is neither a format nor an unknown one that would keep a rollout from finishing"); } + [Fact] + public async Task A_frame_is_classified_as_frame() + { + Assert.SkipUnless(fixture.Enabled, "Set RUN_REDIS_INTEGRATION_TESTS=1 (Docker required) to run."); + await using var mux = await ConnectionMultiplexer.ConnectAsync(fixture.ConnectionString); + var db = mux.GetDatabase(); + var run = Run(); + await SetAsync(db, run, "json", 1, Json); + await SetAsync(db, run, "validated", 2, EntryFrame.Write(Fast, DateTimeOffset.MaxValue, TimeSpan.Zero, EntryValidators.From("v1", null))); + await SetAsync(db, run, "null", 1, EntryFrame.Write([], DateTimeOffset.MaxValue, TimeSpan.Zero, EntryValidators.From(null, DateTimeOffset.UnixEpoch))); + using var connector = new Connector(mux); + + var counts = await Provider(connector).CountFormatsAsync($"{run}:*", Ct); + + counts.Should().BeEquivalentTo(new Dictionary { ["json"] = 1, ["frame"] = 3 }, "a frame is counted by its header, not by the format of the value inside"); + } + + [Fact] + public async Task A_frame_with_a_window_is_also_counted_as_frame_windowed() + { + Assert.SkipUnless(fixture.Enabled, "Set RUN_REDIS_INTEGRATION_TESTS=1 (Docker required) to run."); + await using var mux = await ConnectionMultiplexer.ConnectAsync(fixture.ConnectionString); + var db = mux.GetDatabase(); + var run = Run(); + await SetAsync(db, run, "windowed", 2, EntryFrame.Write(Json, new DateTimeOffset(2030, 1, 1, 0, 0, 0, TimeSpan.Zero), TimeSpan.FromHours(1), null)); + await SetAsync(db, run, "validated", 1, EntryFrame.Write(Json, DateTimeOffset.MaxValue, TimeSpan.Zero, EntryValidators.From("v1", null))); + await db.HashSetAsync($"inventory:h:{run}:hash", [new HashEntry("f", EntryFrame.Write(Fast, DateTimeOffset.MaxValue, TimeSpan.FromMinutes(1), null))]); + using var connector = new Connector(mux); + var sut = Provider(connector); + + var counts = await sut.CountFormatsAsync($"{run}:*", Ct); + var report = await sut.CountFormatsByReasonAsync(new CacheKey($"{run}:*"), Ct); + + counts.Should().BeEquivalentTo(new Dictionary { ["frame"] = 4, ["frame_windowed"] = 3 }); + report.ByFormat.Should().BeEquivalentTo(counts); + report.ByReason["format_frame"].Should().Be(3, "the reasons of a string; a hash is sampled"); + report.ByReason["format_frame_windowed"].Should().Be(2); + } + [Fact] public async Task A_verbatim_pattern_counts_mixed_case_and_padded_keys_that_a_normalized_one_cannot() { @@ -550,6 +589,10 @@ public async Task A_null_key_pattern_throws_at_the_call_rather_than_in_the_task( [InlineData(new byte[] { 0x1F }, "unknown")] [InlineData(new byte[] { 0x1F, 0x01 }, "wide")] [InlineData(new byte[] { 0x1F, 0x02 }, "unknown")] + [InlineData(new byte[] { 0x0E, 0x01, 0x01 }, "frame")] + [InlineData(new byte[] { 0x0E, 0x01, 0x06 }, "frame")] + [InlineData(new byte[] { 0x0E, 0x01, 0x00 }, "unknown")] + [InlineData(new byte[] { 0x0E, 0x02, 0x01 }, "unknown")] public void A_value_is_classified_by_its_first_bytes(byte[] head, string? expected) { var registry = new ValueSerializerRegistry([RegistryEntry.Of("fast", new PassthroughValueSerializer(0x10)), RegistryEntry.Of("other", new PassthroughValueSerializer(0x12)), RegistryEntry.Of("wide", new PassthroughValueSerializer(0x101))]); diff --git a/tests/UiPath.Caching.Tests/Redis/FormatSweepIntegrationTests.cs b/tests/UiPath.Caching.Tests/Redis/FormatSweepIntegrationTests.cs index 5d3bfe81..56f54a50 100644 --- a/tests/UiPath.Caching.Tests/Redis/FormatSweepIntegrationTests.cs +++ b/tests/UiPath.Caching.Tests/Redis/FormatSweepIntegrationTests.cs @@ -375,7 +375,7 @@ public async Task An_inventory_publishes_every_known_reason_so_a_count_can_drain second.Single(m => m.Properties!["reason"] == "format_json").Value.Should().Be(0, "nothing is left in json, and the gauge says so"); second.Single(m => m.Properties!["reason"] == "format_fast").Value.Should().Be(2); second.Select(m => m.Properties!["reason"]).Should().BeEquivalentTo( - "empty", "oversize", "no_ttl", "hash_sampled", "format_json", "format_unknown", "format_fast", "format_other"); + "empty", "oversize", "no_ttl", "hash_sampled", "format_json", "format_unknown", "format_frame", "format_frame_windowed", "format_fast", "format_other"); second.Where(m => m.Properties!["reason"] is not "format_fast").Should().OnlyContain(m => m.Value == 0); } diff --git a/tests/UiPath.Caching.Tests/Redis/FormatSweeperTests.cs b/tests/UiPath.Caching.Tests/Redis/FormatSweeperTests.cs index de7ec4ff..dc2d77db 100644 --- a/tests/UiPath.Caching.Tests/Redis/FormatSweeperTests.cs +++ b/tests/UiPath.Caching.Tests/Redis/FormatSweeperTests.cs @@ -78,6 +78,25 @@ public async Task Each_string_is_counted_under_what_became_of_it() Tracked("default_or_empty").Should().Be(2); } + [Fact] + public async Task A_framed_value_is_tallied_as_framed_and_not_rewritten() + { + var keys = new Keyspace(); + keys.Add(0, "windowed", EntryFrame.Write(Json, Start.AddMinutes(1), TimeSpan.FromHours(1), null)); + keys.Add(0, "validated", EntryFrame.Write(Other, DateTimeOffset.MaxValue, TimeSpan.Zero, EntryValidators.From("v1", null))); + keys.Add(0, "unknown-id", Unknown); + keys.Add(0, "json", Json); + + var report = await Sweep(keys, new FormatSweepOptions { RatePerSecond = 1000 }); + + report.Framed.Should().Be(2); + report.Unreadable.Should().Be(1, "a frame is told apart from an id nobody owns"); + report.Converted.Should().Be(1); + report.Scanned.Should().Be(4); + _rewritten.Should().Equal("json"); + Tracked("framed").Should().Be(2); + } + [Fact] public async Task A_key_in_the_target_format_costs_no_more_than_the_two_byte_read() { diff --git a/tests/UiPath.Caching.Tests/Redis/ForwardingTierIntegrationTests.cs b/tests/UiPath.Caching.Tests/Redis/ForwardingTierIntegrationTests.cs new file mode 100644 index 00000000..308efea7 --- /dev/null +++ b/tests/UiPath.Caching.Tests/Redis/ForwardingTierIntegrationTests.cs @@ -0,0 +1,293 @@ +using StackExchange.Redis; +using UiPath.Caching.Config; +using UiPath.Caching.Tests.Fakes; +using static UiPath.Caching.Tests.Redis.AdoptedFrameClockIntegrationTests; +using static UiPath.Caching.Tests.Redis.EntryFrameReadIntegrationTests; +using Forwarder = UiPath.Caching.Tests.Redis.FrameHarness.Forwarder; +using LayeredNode = UiPath.Caching.Tests.Redis.FrameHarness.LayeredNode; + +namespace UiPath.Caching.Tests.Redis; + +// The forwarding tier is an ICache that forwards every call to a RedisCache and implements no interface of the library's +// own, so the library cannot tell what its entries came from. The rebuilding variant copies the value and the expiration +// of each entry into a new entry of CacheEntryFactory. +[Collection("RedisIntegration")] +[Trait("Category", "Integration")] +public sealed class ForwardingTierIntegrationTests(RedisContainerFixture fixture) +{ + private static readonly TimeSpan Passed = TimeSpan.FromSeconds(5); + private static readonly TimeSpan Left = TimeSpan.FromSeconds(56); + + public enum Lost + { + TryFill, + SetIfChanged, + GetOrAddFill, + BatchFill, + SwapForStored, + } + + public enum RebuiltRead + { + Get, + Entry, + BatchGet, + BatchProbe, + PeerSetReread, + RehydrateAdoption, + OuterOverInner, + } + + public static TheoryData AllLost => Cross(Enum.GetValues()); + + public static TheoryData AllRebuilt => Cross(Enum.GetValues()); + + public static TheoryData BothScripts => new() { Scripts.Off, Scripts.On }; + + // MB3, KT4, LS1 to LS4 + [Theory] + [MemberData(nameof(AllLost))] + public async Task A_forwarding_tier_leaves_no_unbounded_copy_of_a_windowed_frame(Lost lost, Scripts scripts) + { + await using var h = await FrameHarness.StartAsync(fixture, scripts); + var node = h.Build(Forwarder.Wrap(h.Redis)); + var (key, raw) = await h.KeyAsync(); + + var caller = await LoseAsync(h, node, lost, key, raw, windowed: true); + + if (lost != Lost.SwapForStored) + { + caller.Should().Be("A"); + } + + node.Holds(key).Should().BeFalse("no copy, and the generated value that was kept ahead of the write is gone"); + h.StepBackThenAdvance(Passed); + await h.LeaveServerAsync(raw, Left); + await ShouldMissAsync(h, node.Cache, Reading.Get, key); + } + + // MB3, OW1 + [Theory] + [MemberData(nameof(BothScripts))] + public async Task A_forwarding_tier_adopts_an_entry_read_with_its_bounds(Scripts scripts) + { + await using var h = await FrameHarness.StartAsync(fixture, scripts); + var node = h.Build(Forwarder.Wrap(h.Redis)); + var (key, raw) = await h.KeyAsync(); + await h.StoreWindowedAsync(raw, "A"); + + (await node.Cache.GetCacheEntryAsync(key, null, Ct)).Value.Should().Be("A"); + + node.Entry(key).Should().BeAssignableTo(); + h.StepBackThenAdvance(Passed); + await h.LeaveServerAsync(raw, Left); + await ShouldMissAsync(h, node.Cache, Reading.Get, key); + } + + // KT4, AD3, OD36, OD38 + [Theory] + [MemberData(nameof(AllLost))] + public async Task A_forwarding_tier_pays_an_inner_read_for_every_read_of_a_plain_value(Lost lost, Scripts scripts) + { + await using var h = await FrameHarness.StartAsync(fixture, scripts); + var node = h.Build(Forwarder.Wrap(h.Redis)); + var own = h.Build(h.Redis); + var (key, raw) = await h.KeyAsync(); + + var caller = await LoseAsync(h, node, lost, key, raw, windowed: false); + + if (lost != Lost.SwapForStored) + { + caller.Should().Be("A"); + } + + node.Holds(key).Should().BeFalse(); + for (var i = 0; i < 3; i++) + { + h.ClearLog(); + (await node.Cache.GetAsync(key, null, Ct)).Should().NotBeNull(); + FrameHarness.ReadSends(h.TakeLog()).Should().Be(1, "each read sends one entry read through the wrapper"); + node.Holds(key).Should().BeFalse(); + } + + // A value this node writes keeps its copy (DA9). + var (written, _) = await h.KeyAsync(); + (await node.Cache.SetAsync(written, "w", FrameHarness.Long, Ct)).Should().BeTrue(); + h.ClearLog(); + (await node.Cache.GetAsync(written, null, Ct)).Should().Be("w"); + h.TakeLog().Should().BeEmpty(); + + // On a RedisCache tier the same call keeps the copy at once (KT1, AD2). + var (ownKey, ownRaw) = await h.KeyAsync(); + await LoseAsync(h, own, lost, ownKey, ownRaw, windowed: false); + own.Holds(ownKey).Should().BeTrue(); + for (var i = 0; i < 3; i++) + { + h.ClearLog(); + await own.Cache.GetAsync(ownKey, null, Ct); + h.TakeLog().Should().BeEmpty(); + } + } + + // KT2, the nested control + [Theory] + [MemberData(nameof(BothScripts))] + public async Task A_nested_layered_cache_answers_for_its_inner_tier(Scripts scripts) + { + await using var h = await FrameHarness.StartAsync(fixture, scripts); + var inner = h.Build(h.Redis); + var outer = h.Build(inner.Cache); + var (plainKey, plainRaw) = await h.KeyAsync(); + var (key, raw) = await h.KeyAsync(); + await h.StorePlainAsync(plainRaw, "P", TimeSpan.FromMinutes(30)); + await h.StoreWindowedAsync(raw, "A"); + + outer.Cache.MetWindowedFrame.Should().BeFalse("no windowed frame has been read"); + (await outer.Cache.TryFillAsync(plainKey, "filler", FrameHarness.Long, null, Ct)).Outcome.Should().Be(FillOutcome.Existed); + (await outer.Cache.SetIfChangedAsync(plainKey, "P", StringComparer.Ordinal, FrameHarness.Long, null, Ct)).Outcome.Should().Be(ChangeOutcome.Unchanged); + outer.Holds(plainKey).Should().BeFalse("the inner cache hands up no expiration"); + + (await inner.Cache.GetAsync(key, null, Ct)).Should().Be("A"); + inner.Cache.MetWindowedFrame.Should().BeTrue(); + outer.Cache.MetWindowedFrame.Should().BeTrue("the outer cache answers for its inner tier"); + (await outer.Cache.TryFillAsync(key, "filler", FrameHarness.Long, null, Ct)).Outcome.Should().Be(FillOutcome.Existed); + (await outer.Cache.SetIfChangedAsync(key, "A", StringComparer.Ordinal, FrameHarness.Long, null, Ct)).Outcome.Should().Be(ChangeOutcome.Unchanged); + outer.Holds(key).Should().BeFalse(); + + await inner.Cache.RemoveAsync(key, Ct); + await outer.Cache.RemoveAsync(key, Ct); + await h.StoreWindowedAsync(raw, "A"); + (await outer.Cache.GetCacheEntryAsync(key, null, Ct)).Value.Should().Be("A"); + inner.Entry(key).Should().BeAssignableTo(); + outer.Entry(key).Should().BeAssignableTo(); + h.StepBackThenAdvance(Passed); + await h.LeaveServerAsync(raw, Left); + await ShouldMissAsync(h, outer.Cache, Reading.Get, key); + + // KeepsBounds follows the chain. + outer.Cache.KeepsBounds.Should().BeTrue(); + (await outer.Cache.GetCacheEntryAsync(plainKey, null, Ct)).Value.Should().Be("P"); + outer.Holds(plainKey).Should().BeTrue("a plain entry is adopted as today"); + var wrapped = h.Build(h.Build(Forwarder.Wrap(h.Redis)).Cache); + wrapped.Cache.KeepsBounds.Should().BeFalse("the wrapper does not keep bounds"); + (await wrapped.Cache.GetCacheEntryAsync(plainKey, null, Ct)).Value.Should().Be("P"); + wrapped.Holds(plainKey).Should().BeFalse(); + } + + // AD3, KT4: the entry rebuilt by the wrapper is not kept. + [Theory] + [MemberData(nameof(AllRebuilt))] + public async Task A_rebuilt_entry_from_an_unknown_tier_is_not_kept(RebuiltRead read, Scripts scripts) + { + await using var h = await FrameHarness.StartAsync(fixture, scripts); + var (key, raw) = await h.KeyAsync(); + await h.StoreWindowedAsync(raw, "A"); + var inner = h.Build(Forwarder.Wrap(h.Redis, rebuild: true), broadcast: read == RebuiltRead.PeerSetReread); + var node = read == RebuiltRead.OuterOverInner ? h.Build(inner.Cache) : inner; + string? value; + switch (read) + { + case RebuiltRead.RehydrateAdoption: + // A rehydrate adopts only through the snapshot read of a tier the library knows, which the wrapper is not: the run generates. + // The generator makes nothing, so the run writes nothing, and the key keeps the frame the copy was due to be replaced by. + await h.Db.KeyDeleteAsync(raw); + var shortLife = RehydratePolicy(TimeSpan.FromSeconds(2), 0.9); + var generated = 0; + Task Nothing(CancellationToken _) + { + Interlocked.Increment(ref generated); + return Task.FromResult(null); + } + + (await node.Cache.GetOrAddAsync(key, (Func>)(_ => Task.FromResult("G")), shortLife, Ct)).Should().Be("G"); + await h.StoreWindowedAsync(raw, "A"); + h.Time.Advance(TimeSpan.FromSeconds(1.9)); + (await node.Cache.GetOrAddAsync(key, (Func>)Nothing, shortLife, Ct)).Should().Be("G", "the local copy answers"); + await EventAsync(node, "cache.rehydrate.succeeded"); + generated.Should().Be(1, "the wrapper offers no adoption read"); + node.Telemetry.Events.Should().NotContain(e => e.Name == "cache.rehydrate.adopted"); + node.Entry(key).Should().NotBeAssignableTo("no entry came from a read of the frame"); + // The copy is gone after its life; the next read of the key goes through the wrapper and keeps nothing. + h.Time.Advance(Passed); + value = await node.Cache.GetAsync(key, null, Ct); + break; + case RebuiltRead.Get: + value = await node.Cache.GetAsync(key, null, Ct); + break; + case RebuiltRead.Entry: + value = (await node.Cache.GetCacheEntryAsync(key, null, Ct)).Value; + break; + case RebuiltRead.BatchGet: + value = (await node.Cache.GetAsync([key], null, Ct))[0].Value; + break; + case RebuiltRead.BatchProbe: + value = (await node.Cache.GetOrAddAsync([new(key, 1)], (states, _) => Task.FromResult(states.Select(s => new KeyValuePair(s, "generated")).ToArray()), FrameHarness.Long, null, Ct))[0].Value; + break; + case RebuiltRead.PeerSetReread: + // The node holds the key because it wrote it; a peer's write makes it read the key again. + await h.Db.KeyDeleteAsync(raw); + (await node.Cache.SetAsync(key, "seed", FrameHarness.Long, Ct)).Should().BeTrue(); + node.Holds(key).Should().BeTrue(); + await h.StoreWindowedAsync(raw, "A"); + node.Deliver(node.PeerEvents.Create(KnownCacheProviderNames.InMemoryRedis, KnownEventTypes.CacheSet, new CacheEventData(key.Name))); + await CachePeers.Reported(node.Cache, node.Telemetry, 1); + node.Telemetry.Metrics.Should().ContainSingle(m => m.Name == "cache.peer_refresh.dropped" && m.Properties!["reason"] == "not_kept"); + value = "A"; + break; + default: + value = await node.Cache.GetAsync(key, null, Ct); + break; + } + + value.Should().Be("A"); + node.Holds(key).Should().BeFalse("no entry that came from the read is kept"); + inner.Holds(key).Should().BeFalse(); + + h.StepBackThenAdvance(Passed); + await h.LeaveServerAsync(raw, Left); + await ShouldMissAsync(h, node.Cache, Reading.Get, key); + } + + /// One call that loses to the stored value; the value the caller got, which is the generated one only where a background write keeps it. + private static async Task LoseAsync(FrameHarness h, LayeredNode node, Lost lost, CacheKey key, RedisKey raw, bool windowed) + { + var cache = node.Cache; + Task StoreAsync() => windowed ? h.StoreWindowedAsync(raw, "A") : h.StorePlainAsync(raw, "A", TimeSpan.FromMinutes(30)); + + if (lost is Lost.TryFill or Lost.SetIfChanged) + { + await StoreAsync(); + } + else + { + await h.Db.KeyDeleteAsync(raw); + } + + async Task Generate(CancellationToken _) + { + await StoreAsync(); + return "generated"; + } + + switch (lost) + { + case Lost.TryFill: + var fill = await cache.TryFillAsync(key, "filler", FrameHarness.Long, null, Ct); + fill.Outcome.Should().Be(FillOutcome.Existed); + return fill.Existing; + case Lost.SetIfChanged: + var change = await cache.SetIfChangedAsync(key, "A", StringComparer.Ordinal, FrameHarness.Long, null, Ct); + change.Outcome.Should().Be(ChangeOutcome.Unchanged); + return change.Current; + case Lost.GetOrAddFill: + return await cache.GetOrAddAsync(key, Generate, FrameHarness.Long, Ct); + case Lost.BatchFill: + var batch = await cache.GetOrAddAsync([new(key, 1)], async (states, _) => [.. states.Select(s => new KeyValuePair(s, Generate(Ct).GetAwaiter().GetResult()))], FrameHarness.Long, null, Ct); + return batch[0].Value; + default: + var kept = await cache.GetOrAddAsync(key, Generate, FrameHarness.Long, new CachePolicy { BackgroundDistributedWrite = true }, Ct); + await CachePeers.BackgroundSettled(cache); + return kept; + } + } +} diff --git a/tests/UiPath.Caching.Tests/Redis/FrameHarness.cs b/tests/UiPath.Caching.Tests/Redis/FrameHarness.cs new file mode 100644 index 00000000..843125ee --- /dev/null +++ b/tests/UiPath.Caching.Tests/Redis/FrameHarness.cs @@ -0,0 +1,344 @@ +using System.Reflection; +using System.Runtime.ExceptionServices; +using Microsoft.Extensions.Caching.Memory; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging.Abstractions; +using Microsoft.Extensions.Options; +using NSubstitute; +using StackExchange.Redis; +using UiPath.Caching.Broadcast; +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.Fakes; +using UiPath.Caching.Tests.Telemetry; +using static UiPath.Caching.Tests.Redis.EntryFrameReadIntegrationTests; + +namespace UiPath.Caching.Tests.Redis; + +/// A node over a real Redis for the tests of monotonic bounds: frames are written raw, the commands are recorded, and layered caches can be built over any . +internal sealed class FrameHarness : IAsyncDisposable +{ + public static readonly TimeSpan Window = TimeSpan.FromSeconds(60); + public static readonly TimeSpan Long = TimeSpan.FromMinutes(10); + public static readonly TimeSpan Slack = TimeSpan.FromSeconds(2); + + private readonly ServiceProvider _provider; + private readonly ConnectionMultiplexer _mux; + private readonly ConnectionMultiplexer _admin; + private readonly List _nodes = []; + + private FrameHarness(ServiceProvider provider, ConnectionMultiplexer mux, ConnectionMultiplexer admin, ManualTimeProvider time, CommandLog log, bool scripts) + { + _provider = provider; + _mux = mux; + _admin = admin; + Time = time; + Log = log; + ScriptsOn = scripts; + } + + public ManualTimeProvider Time { get; } + + public CommandLog Log { get; } + + public bool ScriptsOn { get; } + + public ICacheFactory Factory => _provider.GetRequiredService(); + + public RedisCache Redis => (RedisCache)Factory.CreateCache(KnownCacheProviderNames.Redis); + + /// The layered cache of the provider, with a local maximum of one hour. + public ICache Layered => Factory.CreateCache(KnownCacheProviderNames.InMemoryRedis); + + public IDatabase Db => _admin.GetDatabase(); + + public static async Task StartAsync(RedisContainerFixture fixture, Scripts scripts, Action? redis = null, Action? layered = null) + { + Assert.SkipUnless(fixture.Enabled, "Set RUN_REDIS_INTEGRATION_TESTS=1 (Docker required) to run."); + if (scripts == Scripts.On) + { + Assert.SkipUnless(fixture.SupportsEvalRo && fixture.ServerVersion.Major >= 7, "The read script needs EVAL_RO and PEXPIRETIME."); + } + + var admin = await ConnectionMultiplexer.ConnectAsync(fixture.ConnectionString + ",allowAdmin=true"); + var mux = await ConnectionMultiplexer.ConnectAsync(fixture.ConnectionString); + var time = new ManualTimeProvider(fixture.TimeOrigin); + var log = new CommandLog(); + var collection = new ServiceCollection().AddSingleton(time).AddSingleton(new TestConnector(mux, log)); + var provider = collection + .AddCaching( + b => + { + b.AddRedisConnection(o => o.ConnectionString = fixture.ConnectionString); + b.AddRedis(o => + { + o.ReadScriptsEnabled = scripts == Scripts.On; + redis?.Invoke(o); + }); + b.AddInMemoryRedis(o => + { + o.LocalMaxExpiration = TimeSpan.FromHours(1); + layered?.Invoke(o); + }); + }, + o => o.AppShortName = "fb" + Guid.NewGuid().ToString("N")[..10]) + .BuildServiceProvider(); + return new FrameHarness(provider, mux, admin, time, log, scripts == Scripts.On); + } + + /// The reads sent: a transaction counts once, as does a plain GET or MGET with its PTTL, and a read script. + public static int ReadSends(List commands) + { + var sends = 0; + var inTransaction = false; + foreach (var command in commands) + { + switch (command) + { + case "MULTI": + inTransaction = true; + break; + case "EXEC": + inTransaction = false; + sends++; + break; + case "GET" or "MGET" or "EVAL_RO" or "EVALSHA_RO" when !inTransaction: + sends++; + break; + } + } + + return sends; + } + + /// The commands up to the first write, which a generator's fill sends after the read. + public static List ReadsOf(List commands) => [.. commands.TakeWhile(c => c is not ("SET" or "EVAL" or "EVALSHA" or "DEL" or "UNLINK" or "PUBLISH"))]; + + public async ValueTask DisposeAsync() + { + foreach (var node in _nodes) + { + node.Dispose(); + } + + await _provider.DisposeAsync(); + await _mux.DisposeAsync(); + await _admin.DisposeAsync(); + } + + /// A key whose raw Redis key is known. + public async Task<(CacheKey Key, RedisKey Raw)> KeyAsync() + { + var id = Guid.NewGuid().ToString("N"); + CacheKey key = $"{{{id}}}{id}"; + (await Redis.SetAsync(key, "seed", Long, TestContext.Current.CancellationToken)).Should().BeTrue(); + return (key, RedisTestKeys.Keys(_admin, $"*{id}").Single()); + } + + /// A frame with a TTL of 61 seconds and a window of 60, whose frame expiration is far ahead: one second of logical life. + public Task StoreWindowedAsync(RedisKey raw, string value) => StoreFrameAsync(raw, value, TimeSpan.FromHours(1), TimeSpan.FromSeconds(61)); + + /// As , for a command hook that cannot await. + public void StoreWindowed(RedisKey raw, string value) + { + var bytes = EntryFrame.Write(((IByteCodecCache)Redis).Encode(value, null), Time.GetUtcNow() + TimeSpan.FromHours(1), Window, null); + Db.StringSet(raw, bytes).Should().BeTrue(); + Db.KeyExpire(raw, TimeSpan.FromSeconds(61)).Should().BeTrue(); + } + + public async Task StoreFrameAsync(RedisKey raw, string value, TimeSpan life, TimeSpan keyTtl) + { + var bytes = EntryFrame.Write(((IByteCodecCache)Redis).Encode(value, null), Time.GetUtcNow() + life, Window, null); + (await Db.StringSetAsync(raw, bytes)).Should().BeTrue(); + (await Db.KeyExpireAsync(raw, keyTtl)).Should().BeTrue(); + } + + public async Task StorePlainAsync(RedisKey raw, string value, TimeSpan keyTtl) + { + (await Db.StringSetAsync(raw, ((IByteCodecCache)Redis).Encode(value, null))).Should().BeTrue(); + (await Db.KeyExpireAsync(raw, keyTtl)).Should().BeTrue(); + } + + /// The server counts the TTL on real time: this is the passage of the seconds that only the fake clock saw. + public async Task LeaveServerAsync(RedisKey raw, TimeSpan left) => (await Db.KeyExpireAsync(raw, left)).Should().BeTrue(); + + /// Moves the UTC clock back before any time passes, then lets pass on both clocks. + public void StepBackThenAdvance(TimeSpan passed) + { + Time.StepUtc(-TimeSpan.FromSeconds(10)); + Time.Advance(passed); + } + + /// The reads that were sent; writes and the cache's own streams are left out. With the commands that write a value (a SET or a write script) are in the list too. + public List TakeLog(bool writes = false) => [.. Log.Take().Select(c => c.Command).Where(c => c is "GET" or "MGET" or "PTTL" or "KeyExpireTimeAsync" or "EXISTS" or "MULTI" or "EXEC" or "EVAL_RO" or "EVALSHA_RO" || (writes && c is "SET" or "EVAL" or "EVALSHA"))]; + + public void ClearLog() => Log.Take(); + + public LayeredNode Build(ICache inner, bool broadcast = false, string name = "b", Action? configure = null) + { + var node = new LayeredNode(this, inner, broadcast, name, configure); + _nodes.Add(node); + return node; + } + + /// What a read of returned, and whether it ran its generator. + public readonly record struct Got(bool Found, string? Value, bool Generated, DateTimeOffset? Expiration = null); + + /// A layered cache built over a given inner tier, with its local tier open to the test. + public sealed class LayeredNode : IDisposable + { + private static readonly CacheEventFormatter Formatter = new(); + + private readonly CapturingMemory _memory; + + internal LayeredNode(FrameHarness harness, ICache inner, bool broadcast, string name, Action? configure = null) + { + var options = new InMemoryRedisCacheOptions { LocalMaxExpiration = TimeSpan.FromHours(1) }; + configure?.Invoke(options); + var cacheOptions = new CacheOptions { AppShortName = "test", ConnectionMonitorEnabled = true, SourceUri = new Uri($"urn:node:{name}") }; + _memory = new CapturingMemory(new MemoryCacheFactory(harness.Time, NullLoggerFactory.Instance)); + Telemetry = new RecordingTelemetryProvider(); + Events = new CacheEventFactory(Options.Create(cacheOptions)); + IChangeTokenFactory tokens = NullChangeTokenFactory.Instance; + var topics = NullTopicFactory.Instance as ITopicFactory; + if (broadcast) + { + tokens = new ChangeTokenFactory(Options.Create(cacheOptions), new SystemJsonByteSerializerProxy(), NullLoggerFactory.Instance, Substitute.For()); + var provider = Substitute.For(); + provider.Enabled.Returns(true); + provider.Create(Arg.Any()).Returns(new NodeTopic(Subject)); + var factory = Substitute.For(); + factory.Get(Arg.Any()).Returns(provider); + topics = factory; + } + + Cache = RunTables.Track(new MultilayerCache( + KnownCacheProviderNames.InMemoryRedis, + inner, + _memory, + tokens, + topics, + broadcast ? Events : NullCacheEventFactory.Instance, + Telemetry, + options, + options, + cacheOptions, + NullDistributedLock.Instance, + NullCachePolicyFactory.Instance, + harness.Time, + NullLogger.Instance)); + } + + public MultilayerCache Cache { get; } + + public RecordingTelemetryProvider Telemetry { get; } + + public CacheEventFactory Events { get; } + + /// The factory of another node, whose events this cache hears. + public CacheEventFactory PeerEvents { get; } = new(Options.Create(new CacheOptions { AppShortName = "test", SourceUri = new Uri("urn:node:publisher") })); + + public KeyedSubject Subject { get; } = new(NullLogger.Instance); + + /// Whether the local tier holds an entry for the key. + public bool Holds(CacheKey key) => _memory.Local!.TryGetValue(key.Name, out _); + + /// The local entry of the key, when it holds one. + public object? Entry(CacheKey key) => _memory.Local!.TryGetValue(key.Name, out var entry) ? entry : null; + + /// Hands a peer's event to the cache, as the wire does. + public void Deliver(ICacheEvent @event) => Subject.OnNext(Formatter.Decode(Formatter.Encode(@event))!); + + public void Dispose() => Subject.Dispose(); + } + + /// A cache that forwards every call to a and implements no interface of the library's own. + public class Forwarder : DispatchProxy + { + private static readonly MethodInfo RebuildOne = typeof(Forwarder).GetMethod(nameof(RebuildOneAsync), BindingFlags.Static | BindingFlags.NonPublic)!; + private static readonly MethodInfo RebuildMany = typeof(Forwarder).GetMethod(nameof(RebuildManyAsync), BindingFlags.Static | BindingFlags.NonPublic)!; + + private ICache _target = null!; + private bool _rebuild; + + /// Copies the value and the expiration of each entry it reads into a new entry of . + public static ICache Wrap(ICache target, bool rebuild = false) + { + var proxy = Create(); + var forwarder = (Forwarder)(object)proxy; + forwarder._target = target; + forwarder._rebuild = rebuild; + return proxy; + } + + protected override object? Invoke(MethodInfo? targetMethod, object?[]? args) + { + var method = targetMethod!; + if (method.Name == nameof(IDisposable.Dispose)) + { + return null; + } + + object? result; + try + { + result = method.Invoke(_target, args); + } + catch (TargetInvocationException ex) when (ex.InnerException is not null) + { + ExceptionDispatchInfo.Throw(ex.InnerException); + throw; + } + + if (!_rebuild) + { + return result; + } + + var type = method.GetGenericArguments().FirstOrDefault(); + return method.Name switch + { + nameof(ICache.GetCacheEntryAsync) => RebuildOne.MakeGenericMethod(type!).Invoke(null, [result]), + nameof(ICache.GetCacheEntriesAsync) => RebuildMany.MakeGenericMethod(type!).Invoke(null, [result]), + _ => result, + }; + } + + private static async ValueTask> RebuildOneAsync(ValueTask> read) + { + var entry = await read.ConfigureAwait(false); + return entry.Found ? new CacheEntryFactory().Create(entry.Value, entry.Expiration) : entry; + } + + private static async ValueTask>[]> RebuildManyAsync(ValueTask>[]> read) + { + var entries = await read.ConfigureAwait(false); + return [.. entries.Select(e => e.Value.Found ? new KeyValuePair>(e.Key, new CacheEntryFactory().Create(e.Value.Value, e.Value.Expiration)) : e)]; + } + } + + private sealed class CapturingMemory(IMemoryCacheFactory inner) : IMemoryCacheFactory + { + public IMemoryCache? Local { get; private set; } + + public IMemoryCache Get(IMemoryCacheOptions memoryOptions) => Local = inner.Get(memoryOptions); + } + + private sealed class NodeTopic(KeyedSubject subject) : ITopic + { + public TopicKey TopicKey { get; } = new("topic"); + + public EventHandler? OnDisposed { get; set; } + + public IDisposable Subscribe(IObserver observer) => subject.Subscribe(observer); + + public ValueTask PublishAsync(ICacheEvent @event, CancellationToken token = default) => new(true); + + public void Dispose() + { + } + } +} diff --git a/tests/UiPath.Caching.Tests/Redis/RedisCacheFrameDecodeTests.cs b/tests/UiPath.Caching.Tests/Redis/RedisCacheFrameDecodeTests.cs new file mode 100644 index 00000000..809eeafc --- /dev/null +++ b/tests/UiPath.Caching.Tests/Redis/RedisCacheFrameDecodeTests.cs @@ -0,0 +1,124 @@ +using Microsoft.Extensions.DependencyInjection; +using UiPath.Caching.Config; +using UiPath.Caching.Redis; +using UiPath.Caching.Tests.Fakes; + +namespace UiPath.Caching.Tests.Redis; + +// The byte seam decodes with no knowledge of the key's life, so only a frame without a window gives its value there. +[Collection("RedisIntegration")] +[Trait("Category", "Integration")] +public sealed class RedisCacheFrameDecodeTests(RedisContainerFixture fixture) +{ + private static readonly CachePolicy Registered = new() { Serializer = new SerializerPolicy { Write = "registered" } }; + private static readonly EntryValidators Validators = EntryValidators.From("\"v1\"", null)!; + + public enum Inner + { + Json, + FormatHeader, + CachedNull, + } + + [Theory] + [InlineData(Inner.Json)] + [InlineData(Inner.FormatHeader)] + [InlineData(Inner.CachedNull)] + public void A_frame_without_a_window_decodes_to_its_inner_value(Inner inner) + { + using var provider = Build(); + var codec = Codec(provider); + var policy = inner == Inner.FormatHeader ? Registered : null; + var bytes = inner == Inner.CachedNull ? [] : codec.Encode("value", policy); + var framed = EntryFrame.Write(bytes, DateTimeOffset.MaxValue, TimeSpan.Zero, Validators); + + var (outcome, value) = codec.Decode(framed, policy); + + outcome.Should().Be(SnapshotOutcome.Found); + value.Should().Be(inner == Inner.CachedNull ? null : "value"); + } + + [Fact] + public void A_headerless_value_that_starts_with_0x0E_but_is_no_frame_reaches_the_serializer() + { + var proxy = new RawBytesProxy(); + using var provider = Build(proxy); + byte[] stored = [0x0E, 0x07, 0x01, 0x02]; + + var (outcome, value) = Codec(provider).Decode(stored, null); + + outcome.Should().Be(SnapshotOutcome.Found); + value.Should().Equal(stored); + proxy.Seen.Should().Equal(stored); + } + + [Fact] + public void A_malformed_frame_is_unreadable_on_the_sniff_path() + { + using var provider = Build(); + + // Version 1 and a window flag, cut short before the window: no frame, and no serializer owns 0x0E. + var (outcome, _) = Codec(provider).Decode([0x0E, 0x01, 0x01, 0x00], Registered, quiet: true); + + outcome.Should().Be(SnapshotOutcome.Unreadable); + } + + [Fact] + public void A_frame_with_a_window_is_absent_on_a_decode_that_cannot_judge_it() + { + using var provider = Build(); + var codec = Codec(provider); + var framed = EntryFrame.Write(codec.Encode("value", null), DateTimeOffset.FromUnixTimeSeconds(4_000_000_000), TimeSpan.FromMinutes(1), null); + + codec.Decode(framed, null).Outcome.Should().Be(SnapshotOutcome.Absent); + } + + private static IByteCodecCache Codec(ServiceProvider provider) => + (IByteCodecCache)provider.GetRequiredService().CreateCache(KnownCacheProviderNames.Redis); + + private ServiceProvider Build(ISerializerProxy? proxy = null) + { + Assert.SkipUnless(fixture.Enabled, "Set RUN_REDIS_INTEGRATION_TESTS=1 to run."); + var services = new ServiceCollection(); + if (proxy is not null) + { + services.AddSingleton(proxy); + } + + return services + .AddCaching( + b => + { + b.AddRedisConnection(o => o.ConnectionString = fixture.ConnectionString); + b.AddRedis(o => + { + o.CacheNullValues = true; + o.FormatNegotiation.Mode = FormatNegotiationMode.Force; + }); + if (proxy is null) + { + b.AddValueSerializer("registered", [0x10], _ => new PassthroughValueSerializer(0x10)); + } + }, + o => o.AppShortName = "framedecode") + .BuildServiceProvider(); + } + + /// A custom headerless serializer that hands back the bytes it is given. + private sealed class RawBytesProxy : ISerializerProxy + { + public byte[]? Seen { get; private set; } + + public byte[]? Serialize(object? value) => (byte[]?)value; + + public T? Deserialize(byte[]? value) + { + Seen = value; + return (T?)(object?)value; + } + + public bool TryDeserialize(string? value, out T? result) => throw new NotSupportedException(); + + public bool TryDeserialize(object? value, out T? result) => throw new NotSupportedException(); + } +} diff --git a/tests/UiPath.Caching.Tests/Redis/RedisCacheHoldsTests.cs b/tests/UiPath.Caching.Tests/Redis/RedisCacheHoldsTests.cs index b55bbde9..402524bd 100644 --- a/tests/UiPath.Caching.Tests/Redis/RedisCacheHoldsTests.cs +++ b/tests/UiPath.Caching.Tests/Redis/RedisCacheHoldsTests.cs @@ -1,5 +1,6 @@ using Microsoft.Extensions.DependencyInjection; using UiPath.Caching.Config; +using UiPath.Caching.Redis; using UiPath.Caching.Tests.Fakes; namespace UiPath.Caching.Tests.Redis; @@ -35,6 +36,24 @@ public async Task It_is_false_for_another_value() tier.Holds(stamp, "other", null).Should().BeFalse(); } + [Theory] + [InlineData("value", false)] + [InlineData("value", true)] + [InlineData(null, false)] + public void Holds_compares_the_inner_value_of_a_frame(string? value, bool windowed) + { + using var provider = Build(); + var cache = Cache(provider); + var tier = (IStampedTier)cache; + var inner = value is null ? [] : ((IByteCodecCache)cache).Encode(value, null); + var validators = EntryValidators.From("\"e\"", null); + var framed = EntryFrame.Write(inner, DateTimeOffset.FromUnixTimeSeconds(4_000_000_000), windowed ? TimeSpan.FromMinutes(1) : TimeSpan.Zero, validators); + object stamp = (StackExchange.Redis.RedisValue)framed; + + tier.Holds(stamp, value, null).Should().BeTrue(); + tier.Holds(stamp, "other", null).Should().BeFalse(); + } + [Fact] public void It_is_false_for_a_null_stamp() { diff --git a/tests/UiPath.Caching.Tests/Serialization/ValueMigrationTests.cs b/tests/UiPath.Caching.Tests/Serialization/ValueMigrationTests.cs index 88a6fbf5..346af01b 100644 --- a/tests/UiPath.Caching.Tests/Serialization/ValueMigrationTests.cs +++ b/tests/UiPath.Caching.Tests/Serialization/ValueMigrationTests.cs @@ -1,5 +1,6 @@ using UiPath.Caching.Config; using UiPath.Caching.Negotiation; +using UiPath.Caching.Redis; using UiPath.Caching.Serialization; using UiPath.Caching.Tests.Fakes; using UiPath.Caching.Tests.Telemetry; @@ -149,6 +150,17 @@ public void A_value_already_in_a_format_the_target_owns_is_not_wanted() sut.Wants(_fast, [0x11, (byte)'x']).Should().BeFalse("the target's other id is the same serializer's, which picks it by size"); } + [Fact] + public void A_framed_value_is_never_offered_for_rewrite() + { + var sut = Migration(); + var windowed = EntryFrame.Write(Json, Clock.GetUtcNow().AddMinutes(1), TimeSpan.FromHours(1), null); + var validators = EntryFrame.Write(Other, DateTimeOffset.MaxValue, TimeSpan.Zero, EntryValidators.From("v1", null)); + + sut.Wants(_fast, windowed).Should().BeFalse(); + sut.Wants(_fast, validators).Should().BeFalse(); + } + [Fact] public void Json_a_custom_proxy_wrote_is_not_wanted_since_it_could_only_be_looked_at_and_left() { diff --git a/tests/UiPath.Caching.Tests/Serialization/ValueSerializerRegistryTests.cs b/tests/UiPath.Caching.Tests/Serialization/ValueSerializerRegistryTests.cs index c24697cd..8a3dcb34 100644 --- a/tests/UiPath.Caching.Tests/Serialization/ValueSerializerRegistryTests.cs +++ b/tests/UiPath.Caching.Tests/Serialization/ValueSerializerRegistryTests.cs @@ -84,7 +84,7 @@ public void A_serializer_without_ids_is_rejected() act.Should().Throw().WithMessage("*a*"); } - [Theory, InlineData(0x09), InlineData(0x0A), InlineData(0x0D), InlineData(0x0F), InlineData(0x1F), InlineData(0x00), InlineData(0x20), InlineData(0x200), InlineData(-1)] + [Theory, InlineData(0x09), InlineData(0x0A), InlineData(0x0D), InlineData(0x0E), InlineData(0x0F), InlineData(0x1F), InlineData(0x00), InlineData(0x20), InlineData(0x200), InlineData(-1)] public void Invalid_ids_are_rejected(int id) { var act = () => new ValueSerializerRegistry([RegistryEntry.Of("a", Fake(id))]); @@ -92,7 +92,7 @@ public void Invalid_ids_are_rejected(int id) act.Should().Throw(); } - [Theory, InlineData(0x01), InlineData(0x02), InlineData(0x0E), InlineData(0x10), InlineData(0x1E), InlineData(0x100), InlineData(0x1FF)] + [Theory, InlineData(0x01), InlineData(0x02), InlineData(0x10), InlineData(0x1E), InlineData(0x100), InlineData(0x1FF)] public void Allowed_ids_are_accepted(int id) { var serializer = Fake(id); diff --git a/tests/UiPath.Caching.Tests/TestTimeProviders.cs b/tests/UiPath.Caching.Tests/TestTimeProviders.cs index 0cf4ad76..5e213aca 100644 --- a/tests/UiPath.Caching.Tests/TestTimeProviders.cs +++ b/tests/UiPath.Caching.Tests/TestTimeProviders.cs @@ -113,6 +113,9 @@ public void JumpWall(TimeSpan by) } } + /// Moves the UTC clock alone, forward or back; the timestamp stays and no timer fires. moves both. + public void StepUtc(TimeSpan by) => JumpWall(by); + public override long GetTimestamp() { lock (_gate)