diff --git a/benchmarks/UiPath.Caching.Benchmarks/FakeRedisConnector.cs b/benchmarks/UiPath.Caching.Benchmarks/FakeRedisConnector.cs index 0c3f98feb..8da88aec0 100644 --- a/benchmarks/UiPath.Caching.Benchmarks/FakeRedisConnector.cs +++ b/benchmarks/UiPath.Caching.Benchmarks/FakeRedisConnector.cs @@ -46,6 +46,9 @@ public event EventHandler? OnReconnected /// GETs sent so far. public long Gets => Volatile.Read(ref _store.GetCount); + /// The key of the last write, so a benchmark can check that its measured calls sent none. + public RedisKey? LastSet => _store.LastSet; + /// Stores a hash for HGETALL to answer. public void SeedHash(RedisKey key, HashEntry[] entries) => _store.Hashes[key] = entries; diff --git a/benchmarks/UiPath.Caching.Benchmarks/RedisPlainHitGateBenchmark.cs b/benchmarks/UiPath.Caching.Benchmarks/RedisPlainHitGateBenchmark.cs new file mode 100644 index 000000000..7a53734b7 --- /dev/null +++ b/benchmarks/UiPath.Caching.Benchmarks/RedisPlainHitGateBenchmark.cs @@ -0,0 +1,73 @@ +using BenchmarkDotNet.Attributes; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.Hosting; +using UiPath.Caching.Redis; + +namespace UiPath.Caching.Benchmarks; + +/// +/// The local hit of a get-or-add with an explicit expiration on a layered cache over Redis on the fake connector, with entry metadata off (RB1) and on (RB2). +/// Public members only, so the same file runs on a build without the write anchor. Each measured call is a local hit: the fake sees no command. +/// +[MemoryDiagnoser] +public class RedisPlainHitGateBenchmark +{ + private static readonly CacheKey Key = "rb:hit"; + + private readonly FakeRedisConnector _redis = new(); + private IHost _host = default!; + private ICache _cache = default!; + private DateTimeOffset _expiration; + private (long Gets, StackExchange.Redis.RedisKey? LastSet) _commands; + + [Params(false, true)] + public bool EntryMetadataEnabled { get; set; } + + [GlobalSetup] + public async Task Setup() + { + var extra = new Dictionary + { + { "Caching:Connections:Redis:ConnectionString", "fake:6379,abortConnect=false" }, + { "Caching:Redis:EntryMetadataEnabled", EntryMetadataEnabled ? "true" : "false" }, + }; + _host = HostHelper.GetHost(0, cache: KnownCacheProviderNames.InMemoryRedis, extra: extra, configure: b => b.Services.Replace(ServiceDescriptor.Singleton(_redis))); + await _host.StartAsync(); + _cache = _host.Services.GetRequiredService().CreateCache(KnownCacheProviderNames.InMemoryRedis); + _expiration = DateTimeOffset.UtcNow.AddDays(1); + await _cache.SetAsync(Key, "value", _expiration, policy: null); + for (var i = 0; i < 16; i++) + { + if (await Hit() != "value") + { + throw new InvalidOperationException("The warm-up call was not a hit"); + } + } + + _commands = Commands(); + await Hit(); + if (Commands() != _commands) + { + throw new InvalidOperationException("A measured call reached the fake connector, so it is no local hit"); + } + } + + [GlobalCleanup] + public async Task Cleanup() + { + var after = Commands(); + await _host.StopAsync(); + _host.Dispose(); + _redis.Dispose(); + if (after != _commands) + { + throw new InvalidOperationException("A measured call reached the fake connector, so it is no local hit"); + } + } + + [Benchmark] + public ValueTask Hit() => _cache.GetOrAddAsync(Key, static _ => Task.FromResult("generated"), _expiration, policy: null); + + private (long Gets, StackExchange.Redis.RedisKey? LastSet) Commands() => (_redis.Gets, _redis.LastSet); +} diff --git a/samples/UiPath.Caching.Sample/appsettings.all.json b/samples/UiPath.Caching.Sample/appsettings.all.json index 559e01596..672bd63ba 100644 --- a/samples/UiPath.Caching.Sample/appsettings.all.json +++ b/samples/UiPath.Caching.Sample/appsettings.all.json @@ -382,6 +382,8 @@ "RemoveUnreadable": true, // RemoveTombstone: null = off; when set, a remove leaves a tombstone that lives this long, so a fill whose generator started before the remove does not put the value back. Set it to the longest generator time, the same on every node "RemoveTombstone": null, + // EntryMetadataEnabled: write entry frames when format negotiation allows them + "EntryMetadataEnabled": false, // ReadFrom: Master reads from the master, which is faster and never stale after an invalidation; Replica reads from a replica when one exists, except for keys just written or invalidated "ReadFrom": "Master", // MasterReadWindow: with ReadFrom Replica, how long a just-written or invalidated key keeps reading from the master; must exceed the replica lag @@ -542,6 +544,10 @@ "FailSafeCooldown": "0:00:30", // FailSafeTimeout: generator time after which fail-safe returns the last value and lets the generator finish in the background; null = wait (default) "FailSafeTimeout": null, + // FailSafeDistributedEnabled: retain expired values in the shared tier when fail-safe and entry metadata are enabled + "FailSafeDistributedEnabled": false, + // FailSafeDistributedMaxStaleAge: how long the shared tier retains an expired value + "FailSafeDistributedMaxStaleAge": "0:15:00", // Lock: per-cache lock overrides; field-level merged against default policy (UiPath.Caching.LockProfile) "Lock": { // LocalSingleFlightEnabled: null = inherit from provider options or default policy diff --git a/src/UiPath.Caching.Abstractions/Config/CachePolicy.cs b/src/UiPath.Caching.Abstractions/Config/CachePolicy.cs index 27ccac134..c05fe25e0 100644 --- a/src/UiPath.Caching.Abstractions/Config/CachePolicy.cs +++ b/src/UiPath.Caching.Abstractions/Config/CachePolicy.cs @@ -95,6 +95,12 @@ public sealed class CachePolicy /// With fail-safe and a value to fall back to, how long the generator runs before that value is returned; the generator then finishes in the background and its value is stored. still cancels it. null or zero waits for the generator (default). public TimeSpan? FailSafeTimeout { get; init; } + /// With , writes keep an expired copy in Redis for . Needs RedisCacheOptions.EntryMetadataEnabled. null inherits (default off). + public bool? FailSafeDistributedEnabled { get; init; } + + /// How long past its logical expiration a value stays in Redis, in whole seconds from 1 second to seconds. null inherits, then takes , then 1 day. + public TimeSpan? FailSafeDistributedMaxStaleAge { get; init; } + /// /// Lock settings. Merged field-level against the default policy's — /// a named policy can override individual fields (e.g. ) diff --git a/src/UiPath.Caching.Abstractions/PublicAPI.Unshipped.txt b/src/UiPath.Caching.Abstractions/PublicAPI.Unshipped.txt index 1aec25c60..5b8741ea8 100644 --- a/src/UiPath.Caching.Abstractions/PublicAPI.Unshipped.txt +++ b/src/UiPath.Caching.Abstractions/PublicAPI.Unshipped.txt @@ -22,6 +22,10 @@ UiPath.Caching.SerializerPolicy.Write.get -> string? UiPath.Caching.SerializerPolicy.Write.init -> void UiPath.Caching.CachePolicy.FailSafeCooldown.get -> System.TimeSpan? UiPath.Caching.CachePolicy.FailSafeCooldown.init -> void +UiPath.Caching.CachePolicy.FailSafeDistributedEnabled.get -> bool? +UiPath.Caching.CachePolicy.FailSafeDistributedEnabled.init -> void +UiPath.Caching.CachePolicy.FailSafeDistributedMaxStaleAge.get -> System.TimeSpan? +UiPath.Caching.CachePolicy.FailSafeDistributedMaxStaleAge.init -> void UiPath.Caching.CachePolicy.FailSafeEnabled.get -> bool? UiPath.Caching.CachePolicy.FailSafeEnabled.init -> void UiPath.Caching.CachePolicy.FailSafeMaxStaleAge.get -> System.TimeSpan? diff --git a/src/UiPath.Caching.Migration/RegistrationValidator.cs b/src/UiPath.Caching.Migration/RegistrationValidator.cs index 4f28bc68e..6261a356b 100644 --- a/src/UiPath.Caching.Migration/RegistrationValidator.cs +++ b/src/UiPath.Caching.Migration/RegistrationValidator.cs @@ -34,6 +34,11 @@ public static IReadOnlyList Violations(CacheOptions cacheOptions, RedisC violations.Add($"Redis.{nameof(RedisCacheOptions.EntryFactory)} is set: the entry must be the value the source writes."); } + if (redisOptions.EntryMetadataEnabled) + { + violations.Add($"Redis.{nameof(RedisCacheOptions.EntryMetadataEnabled)} is on: the source must receive values in its own format."); + } + if (redisOptions.RemoveUnreadable) { violations.Add($"Redis.{nameof(RedisCacheOptions.RemoveUnreadable)} is on: a value only the source can read would be deleted."); diff --git a/src/UiPath.Caching/AnchoredOptions.cs b/src/UiPath.Caching/AnchoredOptions.cs new file mode 100644 index 000000000..0d78efd61 --- /dev/null +++ b/src/UiPath.Caching/AnchoredOptions.cs @@ -0,0 +1,37 @@ +namespace UiPath.Caching; + +/// The options of a layered entry with the anchor of its deadline beside them, so the layered entry flow of an anchored write carries both and does not grow (WA6, C7). +internal struct AnchoredOptions(CacheEntryOptions options, WriteAnchor anchor) : ILayeredOptions +{ + private CacheEntryOptions _options = options; + + public readonly CacheEntryOptions Options => _options; + + public readonly WriteAnchor Anchor => anchor; + + public readonly CacheKey CacheKey => _options.CacheKey; + + public readonly CacheKey CallerKey => _options.CallerKey; + + public readonly TopicKey TopicKey => _options.TopicKey; + + public readonly CancellationToken Token => _options.Token; + + public readonly DateTimeOffset Expiration => _options.Expiration; + + public IDictionary? Metadata + { + readonly get => _options.Metadata; + set => _options.Metadata = value; + } + + public readonly AnchoredOptions WithToken(CancellationToken token) => new(_options.WithToken(token), anchor); + + /// The same entry under another deadline, with the anchor of that deadline. + public readonly AnchoredOptions WithExpiration(DateTimeOffset expiration) + { + var changed = _options; + changed.Expiration = expiration; + return new(changed, anchor); + } +} diff --git a/src/UiPath.Caching/CacheEntryBuilder.cs b/src/UiPath.Caching/CacheEntryBuilder.cs index b1796f012..061691bfb 100644 --- a/src/UiPath.Caching/CacheEntryBuilder.cs +++ b/src/UiPath.Caching/CacheEntryBuilder.cs @@ -41,4 +41,8 @@ public CacheEntryOptions BuildEntryOptions(CacheKey cacheKey, DateTimeOffset? Expiration = _clock.ToDateTimeOffset(expiration), }; } + + /// for a deadline that already has its anchor: the options and that anchor, unchanged. It takes no anchor and reads no clock (WA4 (b)). + public (CacheEntryOptions Options, WriteAnchor Anchor) BuildEntryOptions(CacheKey cacheKey, DateTimeOffset expiration, WriteAnchor anchor, CancellationToken token) => + (BuildEntryOptions(cacheKey, expiration, token), anchor); } diff --git a/src/UiPath.Caching/Config/CachePolicyFactoryValidator.cs b/src/UiPath.Caching/Config/CachePolicyFactoryValidator.cs index 93f641243..6eda56bc8 100644 --- a/src/UiPath.Caching/Config/CachePolicyFactoryValidator.cs +++ b/src/UiPath.Caching/Config/CachePolicyFactoryValidator.cs @@ -72,6 +72,28 @@ public static void ValidateAgainstEffectiveDefault( } } + /// Refuses a default or named policy with on a Redis tier without entry metadata, which cannot write the window. + internal static void ValidateDistributedFailSafe(ICachePolicyFactory factory, bool entryMetadataEnabled) + { + if (entryMetadataEnabled) + { + return; + } + + if (factory.Default?.FailSafeDistributedEnabled == true) + { + Throw(DistributedNeedsMetadata("DefaultCachePolicy")); + } + + foreach (var name in factory.Keys) + { + if (factory.Resolve(name)?.FailSafeDistributedEnabled == true) + { + Throw(DistributedNeedsMetadata($"Policies['{name}']")); + } + } + } + private static void ValidatePolicy(string scope, CachePolicy policy, TimeSpan pollInterval) { if (policy.LocalExpiration is { } local @@ -101,6 +123,11 @@ private static void ValidatePolicy(string scope, CachePolicy policy, TimeSpan po ValidateNonNegative(scope, nameof(CachePolicy.FailSafeMaxStaleAge), policy.FailSafeMaxStaleAge); ValidateNonNegative(scope, nameof(CachePolicy.FailSafeCooldown), policy.FailSafeCooldown); ValidateNonNegative(scope, nameof(CachePolicy.FailSafeTimeout), policy.FailSafeTimeout); + ValidateNonNegative(scope, nameof(CachePolicy.FailSafeDistributedMaxStaleAge), policy.FailSafeDistributedMaxStaleAge); + if (policy.FailSafeDistributedEnabled == true && policy.FailSafeEnabled != true) + { + Throw(ValidateOptionsResult.Fail($"{scope}.{nameof(CachePolicy.FailSafeDistributedEnabled)} needs {nameof(CachePolicy.FailSafeEnabled)}.")); + } } private static void ValidateNonNegative(string scope, string field, TimeSpan? value) @@ -142,4 +169,7 @@ private static void Throw(ValidateOptionsResult result) throw new OptionsValidationException(nameof(CacheOptions), typeof(CacheOptions), result.Failures); } } + + private static ValidateOptionsResult DistributedNeedsMetadata(string scope) => + ValidateOptionsResult.Fail($"{scope}.{nameof(CachePolicy.FailSafeDistributedEnabled)} needs RedisCacheOptions.EntryMetadataEnabled."); } diff --git a/src/UiPath.Caching/Config/CachePolicyMerger.cs b/src/UiPath.Caching/Config/CachePolicyMerger.cs index 30a4864fa..b41956b8e 100644 --- a/src/UiPath.Caching/Config/CachePolicyMerger.cs +++ b/src/UiPath.Caching/Config/CachePolicyMerger.cs @@ -83,6 +83,8 @@ private static CachePolicy Combine(CachePolicy primary, CachePolicy fallback, IC FailSafeMaxStaleAge = primary.FailSafeMaxStaleAge ?? fallback.FailSafeMaxStaleAge, FailSafeCooldown = primary.FailSafeCooldown ?? fallback.FailSafeCooldown, FailSafeTimeout = primary.FailSafeTimeout ?? fallback.FailSafeTimeout, + FailSafeDistributedEnabled = primary.FailSafeDistributedEnabled ?? fallback.FailSafeDistributedEnabled, + FailSafeDistributedMaxStaleAge = primary.FailSafeDistributedMaxStaleAge ?? fallback.FailSafeDistributedMaxStaleAge, Serializer = MergeSerializer(primary.Serializer, fallback.Serializer), WriteSerializer = writeSerializer ?? (primary.Serializer?.Write is not null diff --git a/src/UiPath.Caching/Config/CachingBuilder.cs b/src/UiPath.Caching/Config/CachingBuilder.cs index bf7d06969..c7ec41ccf 100644 --- a/src/UiPath.Caching/Config/CachingBuilder.cs +++ b/src/UiPath.Caching/Config/CachingBuilder.cs @@ -58,13 +58,18 @@ internal void Complete() ServiceDescriptor.Singleton, CacheKeyCasingSeeder>()); Services.TryAddSingleton>(sp => new SystemJsonByteSerializerProxy(sp.GetService())); Services.TryAddSingleton(ValueSerializerRegistration.BuildRegistry); - if (Services.Any(d => d.ServiceType == typeof(ValueSerializerRegistration) || d.ServiceType == typeof(EventFormatRegistry))) + var hasRegisteredFormats = Services.Any(d => d.ServiceType == typeof(ValueSerializerRegistration) || d.ServiceType == typeof(EventFormatRegistry)); + if (hasRegisteredFormats || Services.Any(d => d.ServiceType == typeof(IEntryFrameWrites))) { Services.TryAddSingleton(FormatNegotiation.Create); - Services.TryAddSingleton(sp => ValueMigration.Create(sp)!); Services.TryAddEnumerable(ServiceDescriptor.Singleton()); } + if (hasRegisteredFormats) + { + Services.TryAddSingleton(sp => ValueMigration.Create(sp)!); + } + Services.TryAddSingleton(EmptyResiliencePipelineProvider.Instance); Services.TryAddSingleton(NullChangeTokenFactory.Instance); Services.TryAddSingleton(NullTopicFactory.Instance); diff --git a/src/UiPath.Caching/Config/RedisCollectionExtensions.cs b/src/UiPath.Caching/Config/RedisCollectionExtensions.cs index 3427bd804..df924db58 100644 --- a/src/UiPath.Caching/Config/RedisCollectionExtensions.cs +++ b/src/UiPath.Caching/Config/RedisCollectionExtensions.cs @@ -1,4 +1,5 @@ using Microsoft.Extensions.Hosting; +using UiPath.Caching.Negotiation; using UiPath.Caching.Telemetry; namespace UiPath.Caching.Config; @@ -22,6 +23,8 @@ public static ICachingBuilder AddRedis(this ICachingBuilder builder, Action(sp => + sp.GetRequiredService().FrameWrites(sp.GetRequiredService>().Value)); builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton(RedisCacheProvider.Create)); return builder; } diff --git a/src/UiPath.Caching/FailSafeLifetimeWarning.cs b/src/UiPath.Caching/FailSafeLifetimeWarning.cs index dde3698bc..ec3b922f6 100644 --- a/src/UiPath.Caching/FailSafeLifetimeWarning.cs +++ b/src/UiPath.Caching/FailSafeLifetimeWarning.cs @@ -2,7 +2,7 @@ namespace UiPath.Caching; -/// Warns once per policy that enables fail-safe on a cache with no size limit, where nothing caps how many values are kept. +/// Warns once per policy that enables fail-safe on a cache with no size limit, where nothing caps how many values are kept, and once per policy that keeps a stale window in Redis. internal static partial class FailSafeLifetimeWarning { internal const string DefaultPolicyName = "(default)"; @@ -23,6 +23,28 @@ public static void Log(ILogger logger, string provider, ICachePolicyFactory poli } } + /// Logs one warning for the default policy and each named policy that keeps a stale window in Redis, naming the window. + public static void LogRedisWindows(ILogger logger, ICachePolicyFactory policies) + { + CheckWindow(logger, DefaultPolicyName, policies.Default); + foreach (var name in policies.Keys) + { + CheckWindow(logger, name, policies.Resolve(name)); + } + } + + /// The stale window a policy keeps in Redis: the distributed age, then the local one, then the default, in whole seconds from 1 to ; zero without both switches. + internal static TimeSpan RedisWindow(CachePolicy policy) + { + if (policy.FailSafeEnabled != true || policy.FailSafeDistributedEnabled != true) + { + return TimeSpan.Zero; + } + + var age = policy.FailSafeDistributedMaxStaleAge ?? policy.FailSafeMaxStaleAge ?? StaleValues.DefaultMaxStaleAge; + return TimeSpan.FromSeconds(Math.Clamp(age.Ticks / TimeSpan.TicksPerSecond, 1L, uint.MaxValue)); + } + private static void Check(ILogger logger, string provider, string name, CachePolicy? policy) { if (policy?.FailSafeEnabled == true) @@ -31,6 +53,17 @@ private static void Check(ILogger logger, string provider, string name, CachePol } } + private static void CheckWindow(ILogger logger, string name, CachePolicy? policy) + { + if (policy is not null && RedisWindow(policy) is { Ticks: > 0 } window) + { + LogRedisWindow(logger, name, window); + } + } + + [LoggerMessage(Level = LogLevel.Warning, Message = "Policy {Policy} keeps every value it writes in Redis for {Window} after its logical expiration, so Redis holds each key for its lifetime plus that window. Set a shorter FailSafeDistributedMaxStaleAge to use less Redis memory.")] + private static partial void LogRedisWindow(ILogger logger, string policy, TimeSpan window); + [LoggerMessage(Level = LogLevel.Warning, Message = "Policy {Policy} enables fail-safe while {Provider} SizeLimit is unset: every key written under it keeps its value in memory until FailSafeMaxStaleAge ({MaxStaleAge}) after its local copy expires, whatever LocalMaxExpiration or LocalExpiration is, and nothing caps how many are kept. Set SizeLimit, which then bounds the local entries and the kept values together, or a shorter FailSafeMaxStaleAge.")] private static partial void LogUnlimited(ILogger logger, string policy, string provider, TimeSpan maxStaleAge); } diff --git a/src/UiPath.Caching/IAnchoredTier.cs b/src/UiPath.Caching/IAnchoredTier.cs new file mode 100644 index 000000000..371346ae4 --- /dev/null +++ b/src/UiPath.Caching/IAnchoredTier.cs @@ -0,0 +1,24 @@ +namespace UiPath.Caching; + +/// A tier that takes the write anchor of a deadline the layered cache made, so the send counts that deadline's life on both clocks and takes no anchor of its own (WA6). +internal interface IAnchoredTier +{ + /// Whether the tier frames its writes and so takes the anchor; asked once per layered call, before the call makes or validates its first deadline. + bool TakesAnchor { get; } + + ValueTask SetAsync(CacheKey cacheKey, T? value, DateTimeOffset expiration, WriteAnchor anchor, CachePolicy? policy, CancellationToken token); + + ValueTask SetAsync(KeyValuePair[] keyValues, DateTimeOffset expiration, WriteAnchor anchor, CachePolicy? policy, CancellationToken token); + + ValueTask TryAddAsync(CacheKey cacheKey, T? value, DateTimeOffset expiration, WriteAnchor anchor, CachePolicy? policy, CancellationToken token); + + ValueTask> TryFillAsync(CacheKey cacheKey, T? value, DateTimeOffset expiration, WriteAnchor anchor, CachePolicy? policy, CancellationToken token); + + ValueTask> TryFillAfterAsync(CacheKey cacheKey, T? value, DateTimeOffset expiration, WriteAnchor anchor, TimeSpan generatorElapsed, CachePolicy? policy, CancellationToken token); + + ValueTask[]> TryFillManyAsync(KeyValuePair[] entries, DateTimeOffset expiration, WriteAnchor anchor, CachePolicy? policy, CancellationToken token, TimeSpan? generatorElapsed); + + ValueTask> SetIfChangedAsync(CacheKey cacheKey, T? value, IEqualityComparer comparer, DateTimeOffset expiration, WriteAnchor anchor, CachePolicy? policy, CancellationToken token); + + ValueTask WriteIfStampAsync(CacheKey cacheKey, T? value, DateTimeOffset expiration, WriteAnchor anchor, CachePolicy? policy, object? stamp, CancellationToken token); +} diff --git a/src/UiPath.Caching/ILayeredShape.cs b/src/UiPath.Caching/ILayeredShape.cs index 45ee4eb55..db4c96931 100644 --- a/src/UiPath.Caching/ILayeredShape.cs +++ b/src/UiPath.Caching/ILayeredShape.cs @@ -30,6 +30,15 @@ internal interface ILayeredShape TOptions BuildOptions(CacheKey cacheKey, DateTimeOffset expiration, CancellationToken token); + /// The options under a deadline made here from and the jitter, as a rehydrate makes its fresh deadline; a shape that anchors its writes takes the anchor there. + TOptions BuildJittered(CacheKey cacheKey, TimeSpan duration, TimeSpan? jitter, CancellationToken token); + + /// The options under an instant the generator named, which the library first validates here; a shape that anchors its writes takes the anchor of that reading. + TOptions BuildOwn(CacheKey cacheKey, DateTimeOffset expiration, CancellationToken token); + + /// The rehydrate run under the shape that takes the anchor of its fresh deadline, when the inner tier takes one; null when this shape's own flow runs it. + ValueTask? RehydrateAnchored(CacheKey originalCacheKey, DateTimeOffset entryExpiration, Func> generator, CachePolicy policy, TimeSpan duration, TimeSpan? jitter, RehydrateRun run, CancellationToken ct, RehydrateOverride? shaped); + ValueTask> ReadInnerAsync(TOptions options, CachePolicy policy); /// The read that decides an adoption: an atomic snapshot of value and lifetime, and a failure thrown rather than answered as a miss; what it saw goes in when the shape can compare against it. diff --git a/src/UiPath.Caching/MultilayerCache.Anchored.cs b/src/UiPath.Caching/MultilayerCache.Anchored.cs new file mode 100644 index 000000000..8bb2e6323 --- /dev/null +++ b/src/UiPath.Caching/MultilayerCache.Anchored.cs @@ -0,0 +1,43 @@ +namespace UiPath.Caching; + +/// A layered cache over a tier that takes the anchor takes the anchor too, and a layered cache above it hands its own on (WA6). +internal sealed partial class MultilayerCache : IAnchoredTier +{ + /// Whether the shared tier takes the anchor of a write; asked once per call, right before the call makes or validates its first deadline. A layered tier answers by asking its own. + public bool TakesAnchor => _anchoredInner?.TakesAnchor == true; + + ValueTask IAnchoredTier.SetAsync(CacheKey cacheKey, T? value, DateTimeOffset expiration, WriteAnchor anchor, CachePolicy? policy, CancellationToken token) + where T : default => + SetCoreAnchoredAsync(cacheKey, value, GetExpirationHanded(expiration), anchor, policy ?? _defaultPolicy, token); + + ValueTask IAnchoredTier.SetAsync(KeyValuePair[] keyValues, DateTimeOffset expiration, WriteAnchor anchor, CachePolicy? policy, CancellationToken token) + where T : default => + SetCoreAnchoredAsync(keyValues, GetExpirationHanded(expiration), anchor, policy ?? _defaultPolicy, token); + + ValueTask IAnchoredTier.TryAddAsync(CacheKey cacheKey, T? value, DateTimeOffset expiration, WriteAnchor anchor, CachePolicy? policy, CancellationToken token) + where T : default => + TryAddCoreAnchoredAsync(cacheKey, value, GetExpirationHanded(expiration), anchor, policy ?? _defaultPolicy, token); + + ValueTask> IAnchoredTier.TryFillAsync(CacheKey cacheKey, T? value, DateTimeOffset expiration, WriteAnchor anchor, CachePolicy? policy, CancellationToken token) + where T : default => + TryFillCoreAnchoredAsync(cacheKey, value, GetExpirationHanded(expiration), anchor, policy ?? _defaultPolicy, token); + + ValueTask> IAnchoredTier.TryFillAfterAsync(CacheKey cacheKey, T? value, DateTimeOffset expiration, WriteAnchor anchor, TimeSpan generatorElapsed, CachePolicy? policy, CancellationToken token) + where T : default => + TryFillCoreAnchoredAsync(cacheKey, value, GetExpirationHanded(expiration), anchor, policy ?? _defaultPolicy, token); + + ValueTask[]> IAnchoredTier.TryFillManyAsync(KeyValuePair[] entries, DateTimeOffset expiration, WriteAnchor anchor, CachePolicy? policy, CancellationToken token, TimeSpan? generatorElapsed) + where T : default => + throw new NotSupportedException("A layered cache fills the keys of a batch itself and does not take a fill of many keys."); + + ValueTask> IAnchoredTier.SetIfChangedAsync(CacheKey cacheKey, T? value, IEqualityComparer comparer, DateTimeOffset expiration, WriteAnchor anchor, CachePolicy? policy, CancellationToken token) + where T : default => + SetIfChangedCoreAnchoredAsync(cacheKey, value, comparer, GetExpirationHanded(expiration), anchor, policy ?? _defaultPolicy, token); + + ValueTask IAnchoredTier.WriteIfStampAsync(CacheKey cacheKey, T? value, DateTimeOffset expiration, WriteAnchor anchor, CachePolicy? policy, object? stamp, CancellationToken token) + where T : default => + throw new NotSupportedException("A layered cache does not compare against a stamp."); + + /// The instant an outer layered cache hands on is validated as the public overload validates it, with no timestamp and no anchor of its own (WA6). + private DateTimeOffset GetExpirationHanded(DateTimeOffset expiration) => GetExpiration(expiration); +} diff --git a/src/UiPath.Caching/MultilayerCache.AnchoredBatch.cs b/src/UiPath.Caching/MultilayerCache.AnchoredBatch.cs new file mode 100644 index 000000000..9a163b591 --- /dev/null +++ b/src/UiPath.Caching/MultilayerCache.AnchoredBatch.cs @@ -0,0 +1,447 @@ +namespace UiPath.Caching; + +/// The batch get-or-add of a layered cache whose shared tier takes the anchor (WA4 (b), WA6): twins of the miss path of the batch that carry the anchor of the batch's one deadline, and hand it to the tier at the fill. The twins are the paths of today with the anchor beside the policy. +internal sealed partial class MultilayerCache +{ + private async ValueTask[]> GetOrAddBatchInternalAnchoredAsync( + KeyValuePair[] entries, + TArg argument, + Func[]>> generator, + DateTimeOffset expiration, + WriteAnchor anchor, + TimeSpan effectiveDuration, + TimeSpan? rehydrateJitter, + CachePolicy policy, + CancellationToken token) + where TState : notnull + { + NotCacheableException.ThrowIfNotCacheable(); + ArgumentNullException.ThrowIfNull(entries); + + if (TryGetAllLocal(entries, policy, token, out var local)) + { + return local; + } + + var (states, keyIndexOfState, callerKeys, options, firstStateOfKey) = DistinctEntries(entries, expiration, token); + if (states.Length == 0) + { + return []; + } + + var seen = _localMemorySetter.Writes; + var probe = await GetCacheEntriesInnerAsync(options, policy, token).ConfigureAwait(false); + + var values = new T?[options.Length]; + var missIndices = new List(); + var hits = new List<(CacheKey CallerKey, TState State, CacheEntryOptions Options, DateTimeOffset Expiration, T? Value)>(); + for (var i = 0; i < probe.Length; i++) + { + var entry = probe[i].Value; + if (entry.Found) + { + values[i] = entry.Value; + hits.Add((callerKeys[i], states[firstStateOfKey[i]], options[i], entry.Expiration, entry.Value)); + continue; + } + missIndices.Add(i); + } + + if (hits.Count > 0 && policy.RehydrateEnabled == true && policy.Rehydrate is not null) + { + TryRehydrateBatch(hits, BindBatch(argument, generator), policy, effectiveDuration, rehydrateJitter); + } + + if (missIndices.Count == 0) + { + return Project(states, keyIndexOfState, values); + } + + var missOptions = new CacheEntryOptions[missIndices.Count]; + var missStates = new TState[missIndices.Count]; + var missProbe = new KeyValuePair>[missIndices.Count]; + for (var i = 0; i < missIndices.Count; i++) + { + var index = missIndices[i]; + missOptions[i] = options[index]; + missStates[i] = states[firstStateOfKey[index]]; + missProbe[i] = probe[index]; + } + + var bound = BindBatch(argument, generator); + var resolved = SharesRuns(policy.Lock) + ? await RunBatchSharedAnchoredAsync(missOptions, missStates, missProbe, bound, anchor, policy, seen, token).ConfigureAwait(false) + : await RunBatchGuardedAnchoredAsync(missOptions, missStates, missProbe, bound, anchor, policy, token).ConfigureAwait(false); + + for (var i = 0; i < missIndices.Count; i++) + { + values[missIndices[i]] = resolved[i].Value.Value; + } + + return Project(states, keyIndexOfState, values); + } + + private async ValueTask>[]> RunBatchGuardedAnchoredAsync( + CacheEntryOptions[] options, + TState[] states, + KeyValuePair>[] probe, + Func[]>> generator, + WriteAnchor anchor, + CachePolicy policy, + CancellationToken token) + where TState : notnull + { + if (!DistributedLockOn(policy.Lock)) + { + return await RunBatchGeneratorAndStoreAnchoredAsync(options, states, probe, generator, anchor, policy, token).ConfigureAwait(false); + } + + await using var lease = await AcquireDistributedLockAsync(CompositeCacheKey.For(Array.ConvertAll(options, o => o.CacheKey)), policy.Lock, token).ConfigureAwait(false); + var latest = await GetCacheEntriesInnerAsync(options, policy, token).ConfigureAwait(false); + return await RunBatchGeneratorAndStoreAnchoredAsync(options, states, latest, generator, anchor, policy, token).ConfigureAwait(false); + } + + private async ValueTask>[]> RunBatchSharedAnchoredAsync( + CacheEntryOptions[] missOptions, + TState[] missStates, + KeyValuePair>[] probe, + Func[]>> generator, + WriteAnchor anchor, + CachePolicy policy, + long seen, + CancellationToken token) + where TState : notnull + { + var result = (KeyValuePair>[])probe.Clone(); + var owned = new List(); + var joined = new List>(); + try + { + ReserveBatchKeys(missOptions, probe, owned, joined, token); + if (owned.Count > 0) + { + await RunOwnedAnchoredAsync(owned, missOptions, missStates, probe, generator, anchor, policy, seen, result, token).ConfigureAwait(false); + } + } + catch (OperationCanceledException) when (token.IsCancellationRequested) + { + EndOwned(owned, new InFlightAbandonedException()); + WithdrawAll(joined); + throw; + } + catch (Exception ex) + { + EndOwned(owned, ex); + WithdrawAll(joined); + throw; + } + + var abandoned = await AwaitJoinedAsync(joined, missOptions, result).ConfigureAwait(false); + if (abandoned.Count > 0) + { + await RetryAbandonedAnchoredAsync(abandoned, missOptions, missStates, generator, anchor, policy, result, token).ConfigureAwait(false); + } + + return result; + } + + private async ValueTask RunOwnedAnchoredAsync( + List owned, + CacheEntryOptions[] missOptions, + TState[] missStates, + KeyValuePair>[] probe, + Func[]>> generator, + WriteAnchor anchor, + CachePolicy policy, + long seen, + KeyValuePair>[] result, + CancellationToken token) + where TState : notnull + { + // A write in this process since the caller probed may have left values in the local tier, which a run writes before it leaves the table. + var rewritten = _localMemorySetter.Writes != seen; + + // Every key is ours, none joined, so the arrays already are the owned set and need no copy. + var all = owned.Count == missOptions.Length; + var ownedOptions = all ? missOptions : owned.Select(o => missOptions[o.Index]).ToArray(); + var ownedStates = all ? missStates : owned.Select(o => missStates[o.Index]).ToArray(); + var current = all && !rewritten + ? probe + : owned.Select(o => rewritten && TryGetLocalEntry(missOptions[o.Index], out var local) ? new KeyValuePair>(missOptions[o.Index].CacheKey, local) : probe[o.Index]).ToArray(); + var produced = await RunBatchGuardedAnchoredAsync(ownedOptions, ownedStates, current, generator, anchor, policy, token).ConfigureAwait(false); + for (var i = 0; i < owned.Count; i++) + { + result[owned[i].Index] = produced[i]; + owned[i].Run.Complete(produced[i].Value); + } + } + + private async ValueTask RetryAbandonedAnchoredAsync( + List abandoned, + CacheEntryOptions[] missOptions, + TState[] missStates, + Func[]>> generator, + WriteAnchor anchor, + CachePolicy policy, + KeyValuePair>[] result, + CancellationToken token) + where TState : notnull + { + var retryOptions = abandoned.Select(i => missOptions[i]).ToArray(); + var freshSeen = _localMemorySetter.Writes; + var fresh = await GetCacheEntriesInnerAsync(retryOptions, policy, token).ConfigureAwait(false); + var again = await RunBatchSharedAnchoredAsync(retryOptions, abandoned.Select(i => missStates[i]).ToArray(), fresh, generator, anchor, policy, freshSeen, token).ConfigureAwait(false); + for (var i = 0; i < abandoned.Count; i++) + { + result[abandoned[i]] = again[i]; + } + } + + private async ValueTask>[]> RunBatchGeneratorAndStoreAnchoredAsync( + CacheEntryOptions[] missOptions, + TState[] missStates, + KeyValuePair>[] probe, + Func[]>> generator, + WriteAnchor anchor, + CachePolicy policy, + CancellationToken token) + where TState : notnull + { + var stillMissing = new List(); + for (var i = 0; i < missOptions.Length; i++) + { + if (!probe[i].Value.Found) + { + stillMissing.Add(i); + } + } + if (stillMissing.Count == 0) + { + return probe; + } + + var requestStates = new TState[stillMissing.Count]; + var mappedKeys = new CacheKey[stillMissing.Count]; + // Log-only, so it is not built for a disabled level. + var missedOptions = _logger.IsEnabled(LogLevel.Debug) ? new CacheEntryOptions[stillMissing.Count] : null; + for (var i = 0; i < stillMissing.Count; i++) + { + requestStates[i] = missStates[stillMissing[i]]; + mappedKeys[i] = missOptions[stillMissing[i]].CacheKey; + if (missedOptions is not null) + { + missedOptions[i] = missOptions[stillMissing[i]]; + } + } + + var telemetryKey = CompositeCacheKey.For(mappedKeys); + if (missedOptions is not null) + { + LogBatchCacheMissed(Logged(missedOptions, typeof(T)), stillMissing.Count); + } + + var watched = BeginBatchFill(missOptions, stillMissing); + try + { + var produced = await InvokeFactoryAsync(telemetryKey, ct => generator(requestStates, ct), policy.FactoryTimeout, token).ConfigureAwait(false); + var producedByState = SelectRequestedProduced(produced, requestStates); + + var toStore = SelectEntriesToStore(missOptions, missStates, stillMissing, producedByState); + Dictionary>? adopted = null; + if (toStore.Count > 0) + { + var innerCacheDisconnected = GetInnerCacheDisconnected(); + if (innerCacheDisconnected) + { + await InternalSetAsync(toStore.ToArray(), innerCacheDisconnected, policy, keepRefused: true, token).ConfigureAwait(false); + } + else + { + adopted = await FillBatchAnchoredAsync(toStore.ToArray(), watched, anchor, policy, token).ConfigureAwait(false); + } + } + + return BuildBatchEntries(missOptions, missStates, probe, producedByState, adopted); + } + finally + { + EndBatchFill(watched); + } + } + + private async ValueTask>?> FillBatchAnchoredAsync(CacheEntryValue[] entries, Dictionary watched, WriteAnchor anchor, CachePolicy policy, CancellationToken token) + { + if (entries.Length == 0) + { + return null; + } + + try + { + return await _background.FillAsync( + entries.Select(static e => e.CacheEntry.CacheKey.Name), + (Cache: this, Entries: entries, Watched: watched, Anchor: anchor, Policy: policy, Token: token), + static (s, _) => s.Cache.TryFillEachAnchoredAsync(s.Entries, s.Watched, s.Anchor, s.Policy, s.Token), + static (s, results, keeper) => s.Cache.KeepFilledBatch(s.Entries, s.Watched, s.Policy, results, keeper), + token).ConfigureAwait(false); + } + catch (OperationCanceledException) when (token.IsCancellationRequested) + { + return null; + } + catch (Exception ex) + { + LogBatchSetError(ex, entries); + return null; + } + } + + private async ValueTask[]> TryFillEachAnchoredAsync(CacheEntryValue[] entries, Dictionary watched, WriteAnchor anchor, CachePolicy policy, CancellationToken token) + { + if (_innerCache is not IFillManyTier || _innerCache is not IAnchoredTier many) + { + var fills = new Task>[entries.Length]; + for (var i = 0; i < entries.Length; i++) + { + fills[i] = TryFillOrReplaceAnchoredAsync(entries[i].CacheEntry, anchor, entries[i].Value, policy, BatchToken(watched, entries[i].CacheEntry.CacheKey.Name)).AsTask(); + } + + return await Task.WhenAll(fills).ConfigureAwait(false); + } + + var results = new FillResult[entries.Length]; + var open = new List(entries.Length); + for (var i = 0; i < entries.Length; i++) + { + var name = entries[i].CacheEntry.CacheKey.Name; + // In the key's turn, just before the command, as for a single fill. + if (LateStillCurrent(entries[i].CacheEntry) && _background.FillIntact(name, BatchToken(watched, name))) + { + open.Add(i); + } + } + + if (open.Count == 0) + { + return results; + } + + try + { + var pairs = open.Select(i => new KeyValuePair(entries[i].CacheEntry.CacheKey, entries[i].Value)).ToArray(); + // One deadline for the batch, as a batch write has: every entry is built from the same resolved expiration. + var filled = await many.TryFillManyAsync(pairs, entries[open[0]].CacheEntry.Expiration, anchor, policy, token, OldestGenerator(entries, watched, open)).ConfigureAwait(false); + for (var k = 0; k < open.Count; k++) + { + var entry = entries[open[k]]; + results[open[k]] = filled[k].Outcome == FillOutcome.Unreadable + ? await HealUnreadableAnchoredAsync(entry.CacheEntry, anchor, entry.Value, policy, BatchToken(watched, entry.CacheEntry.CacheKey.Name)).ConfigureAwait(false) + : filled[k]; + } + } + catch (Exception ex) when (!(ex is OperationCanceledException && token.IsCancellationRequested)) + { + LogBatchSetError(ex, entries); + } + + return results; + } + + /// As , for a tier that takes the anchor: the fresh deadline of the run takes its anchor where it is made, after the generator. + private async ValueTask RehydrateReservedAnchoredAsync( + CacheKey[] reservedKeys, + Dictionary stateByCallerKey, + Dictionary byState, + Func[]>> generator, + CachePolicy policy, + TimeSpan duration, + TimeSpan? rehydrateJitter, + RehydrateRun run, + CancellationToken token) + where TState : notnull + { + var rehydrateStates = MapReservedKeysToStates(reservedKeys, stateByCallerKey); + rehydrateStates = await AdoptFreshInnerAsync(rehydrateStates, byState, policy, duration, run, token).ConfigureAwait(false); + if (rehydrateStates.Length == 0) + { + return; + } + + var produced = await generator(rehydrateStates, token).ConfigureAwait(false); + + var (freshExpiration, anchor) = JitteredAnchored(duration, rehydrateJitter); + var groups = GroupRehydratedAt(produced, rehydrateStates, byState, freshExpiration); + if (groups.Count == 0) + { + return; + } + + await WriteRehydrateGroupsAnchoredAsync(groups, freshExpiration, anchor, policy, token).ConfigureAwait(false); + } + + /// Writes then announces one expiration group at a time, handing the anchor to the group that holds the fresh deadline. + private async ValueTask WriteRehydrateGroupsAnchoredAsync( + Dictionary Entry, CacheKey CallerKey)>> groups, + DateTimeOffset freshExpiration, + WriteAnchor anchor, + CachePolicy policy, + CancellationToken token) + { + var failed = new List(); + var innerCacheDisconnected = GetInnerCacheDisconnected(); + foreach (var (expiration, group) in groups) + { + var entries = group.ConvertAll(e => e.Entry); + var (written, kept) = await SetInnerAnchoredAsync(entries.ToArray(), expiration == freshExpiration ? anchor : default, innerCacheDisconnected, policy, keepRefused: false, token).ConfigureAwait(false); + + // Written before the events, so a node they wake reads the new value; announced even when the write reports + // failure, since across Redis Cluster slots it can have written some keys. + var published = innerCacheDisconnected || await PublishSetsAsync(entries).ConfigureAwait(false); + if (!kept || !published || (!innerCacheDisconnected && !written)) + { + failed.AddRange(group.Select(e => e.CallerKey.Name)); + } + } + + if (failed.Count > 0) + { + // A run timeout that ended the write is the coordinator's to report, not a write failure. + token.ThrowIfCancellationRequested(); + throw new RehydrateWriteFailedException(string.Join(",", failed)); + } + } + + /// Groups the produced pairs by target expiration, the fresh one made by the caller of this method; a null value keeps its original deadline. + private Dictionary Entry, CacheKey CallerKey)>> GroupRehydratedAt( + KeyValuePair[]? produced, + TState[] rehydrateStates, + Dictionary byState, + DateTimeOffset freshExpiration) + where TState : notnull + { + var requested = new HashSet(rehydrateStates); + var seen = new HashSet(rehydrateStates.Length); + var groups = new Dictionary Entry, CacheKey CallerKey)>>(); + foreach (var pair in produced ?? []) + { + if (!requested.Contains(pair.Key) || !seen.Add(pair.Key)) + { + continue; + } + if (pair.Value is null && !_multiLayerCacheOptions.CacheNullValues) + { + continue; + } + var (options, originalExpiration, callerKey) = byState[pair.Key]; + var target = pair.Value is null ? originalExpiration : freshExpiration; + options.Expiration = target; + if (!groups.TryGetValue(target, out var group)) + { + group = []; + groups[target] = group; + } + group.Add((new CacheEntryValue(options, pair.Value), callerKey)); + } + return groups; + } +} diff --git a/src/UiPath.Caching/MultilayerCache.AnchoredFill.cs b/src/UiPath.Caching/MultilayerCache.AnchoredFill.cs new file mode 100644 index 000000000..2e2040c4e --- /dev/null +++ b/src/UiPath.Caching/MultilayerCache.AnchoredFill.cs @@ -0,0 +1,279 @@ +namespace UiPath.Caching; + +/// The fills and the compare-and-set of a layered cache whose shared tier takes the anchor (WA6): twins of TryFillCoreAsync and SetIfChangedCoreAsync that hand the anchor to the tier. +internal sealed partial class MultilayerCache +{ + private async ValueTask> TryFillCoreAnchoredAsync(CacheKey cacheKey, T? value, DateTimeOffset expiration, WriteAnchor handed, CachePolicy policy, CancellationToken token) + { + NotCacheableException.ThrowIfNotCacheable(); + token.ThrowIfCancellationRequested(); + var (options, anchor) = _entryBuilder.BuildEntryOptions(cacheKey, expiration, handed, token); + if (!CanFill(options, value, policy)) + { + return default; + } + + // Counting orders a fill against competing writes, so it is on before the first mark or local commit. + _background.Track(); + if (!_sharedInner) + { + return FillLocally(options, value, policy); + } + + if (GetInnerCacheDisconnected()) + { + KeepUnfilled(options, null, value, policy); + return default; + } + + var name = options.CacheKey.Name; + var mark = MarkInnerRead(name, options.TopicKey); + FillResult filled; + try + { + filled = await ((IAnchoredTier)_innerCache).TryFillAsync(options.CacheKey, value, options.Expiration, anchor, policy, token).ConfigureAwait(false); + } + catch (Exception ex) when (!(ex is OperationCanceledException && token.IsCancellationRequested)) + { + LogInnerCacheFillError(ex, Logged(options, typeof(T))); + filled = default; + } + + return AfterFill(filled, options, mark, value, policy); + } + + private async ValueTask> SetIfChangedCoreAnchoredAsync(CacheKey cacheKey, T? value, IEqualityComparer comparer, DateTimeOffset expiration, WriteAnchor handed, CachePolicy policy, CancellationToken token) + { + NotCacheableException.ThrowIfNotCacheable(); + ArgumentNullException.ThrowIfNull(comparer); + token.ThrowIfCancellationRequested(); + var (options, anchor) = _entryBuilder.BuildEntryOptions(cacheKey, expiration, handed, token); + if (!CanFill(options, value, policy)) + { + return default; + } + + _background.Track(); + _background.NoteChange(options.CacheKey.Name); + if (!_sharedInner) + { + return await ChangeLocallyAsync(options, value, comparer, policy).ConfigureAwait(false); + } + + if (GetInnerCacheDisconnected()) + { + KeepUnfilled(options, null, value, policy); + return default; + } + + var name = options.CacheKey.Name; + var mark = MarkInnerRead(name, options.TopicKey); + ChangeResult changed; + var guarded = new ThrowRecordingComparer(comparer); + try + { + changed = await ((IAnchoredTier)_innerCache).SetIfChangedAsync(options.CacheKey, value, guarded, options.Expiration, anchor, policy, token).ConfigureAwait(false); + } + catch (Exception ex) when (guarded.Thrown is null && !(ex is OperationCanceledException && token.IsCancellationRequested)) + { + LogInnerCacheFillError(ex, Logged(options, typeof(T))); + changed = default; + } + + return await AfterChangeAsync(changed, options, mark, value, policy).ConfigureAwait(false); + } + + /// What the layered cache keeps locally of an inner compare-and-set's answer. + private async ValueTask> AfterChangeAsync(ChangeResult changed, CacheEntryOptions options, long mark, T? value, CachePolicy policy) + { + switch (changed.Outcome) + { + case ChangeOutcome.Filled: + Layered().FillFromInnerRead(options, mark, value, policy); + break; + 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: + await KeepAndAnnounceAsync(options, mark, value, policy).ConfigureAwait(false); + break; + case ChangeOutcome.Unchanged: + break; + default: + if (options.Expiration > _clock.GetUtcNow()) + { + KeepUnfilled(options, mark, value, policy); + } + + break; + } + + return changed with { Expiration = null }; + } + + /// As , with the anchor of the deadline handed to the tier. + private async ValueTask> FillInnerAnchoredAsync(CacheEntryOptions options, WriteAnchor anchor, T? value, CachePolicy policy, ICacheEntry entry, long fill) + { + try + { + return await _background.FillAsync( + options.CacheKey.Name, + (Args: new FillArgs(this, options, value, policy, entry, fill), Anchor: anchor), + static (s, _) => s.Args.Cache.TryFillOrReplaceAnchoredAsync(s.Args.Options, s.Anchor, s.Args.Value, s.Args.Policy, s.Args.Fill), + static (s, filled, keeper) => s.Args.Cache.KeepFilled(s.Args, filled, keeper), + options.Token).ConfigureAwait(false); + } + catch (OperationCanceledException) when (options.Token.IsCancellationRequested) + { + return default; + } + catch (Exception ex) + { + LogInnerCacheSetError(ex, Logged(options, typeof(T))); + return default; + } + } + + [AsyncMethodBuilder(typeof(Pooled<>))] + private async ValueTask> TryFillOrReplaceAnchoredAsync(CacheEntryOptions options, WriteAnchor anchor, T? value, CachePolicy policy, long fill = BackgroundWrites.Untracked) + { + try + { + // A late fail-safe value checks in the key's turn that nothing removed or replaced the key since its generator started. + if (!LateStillCurrent(options)) + { + return default; + } + + // Just before the command: a write or removal since the generator started leaves the key to it, and the keep that follows counts the refusal. + if (!_background.FillIntact(options.CacheKey.Name, fill)) + { + return default; + } + + var filled = await TryInnerFillAnchoredAsync(options, anchor, value, policy, fill).ConfigureAwait(false); + if (filled.Outcome != FillOutcome.Unreadable) + { + return filled; + } + + return await HealUnreadableAnchoredAsync(options, anchor, value, policy, fill).ConfigureAwait(false); + } + catch (Exception ex) when (!(ex is OperationCanceledException && options.Token.IsCancellationRequested)) + { + LogInnerCacheSetError(ex, Logged(options, typeof(T))); + return default; + } + } + + private async ValueTask> HealUnreadableAnchoredAsync(CacheEntryOptions options, WriteAnchor anchor, T? value, CachePolicy policy, long fill) + { + if (_innerCache is not IStampedTier tier) + { + return default; + } + + var (snapshot, stamp) = await tier.ReadStampedAsync(options.CacheKey, policy, options.Token).ConfigureAwait(false); + switch (snapshot.Outcome) + { + case SnapshotOutcome.Found: + return new FillResult(FillOutcome.Existed, snapshot.Entry!.Value, snapshot.Entry.Expiration); + case SnapshotOutcome.Unreadable or SnapshotOutcome.Absent when _background.FillIntact(options.CacheKey.Name, fill): + var written = await ((IAnchoredTier)_innerCache).WriteIfStampAsync(options.CacheKey, value, options.Expiration, anchor, policy, stamp, options.Token).ConfigureAwait(false); + if (written == StampedWrite.Won) + { + return new FillResult(FillOutcome.Added, default); + } + + // Changed again since the read: the key is the winner's, or gone. + return written == StampedWrite.Lost ? await AfterLostHealAnchoredAsync(options, anchor, value, policy, fill).ConfigureAwait(false) : default; + default: + return default; + } + } + + private async ValueTask> AfterLostHealAnchoredAsync(CacheEntryOptions options, WriteAnchor anchor, T? value, CachePolicy policy, long fill) + { + // A removal that arrived while the compare was in flight leaves the key to it. + if (!_background.FillIntact(options.CacheKey.Name, fill)) + { + return default; + } + + var filled = await TryInnerFillAnchoredAsync(options, anchor, value, policy, fill).ConfigureAwait(false); + return filled.Outcome == FillOutcome.Unreadable ? default : filled; + } + + /// The inner fill with the anchor, told how long the key's generator has run when the inner tier leaves tombstones. + private ValueTask> TryInnerFillAnchoredAsync(CacheEntryOptions options, WriteAnchor anchor, T? value, CachePolicy policy, long fill) => + _fencedInner && (_background.FillElapsed(options.CacheKey.Name, fill) ?? LateGeneratorElapsed()) is { } elapsed + ? ((IAnchoredTier)_innerCache).TryFillAfterAsync(options.CacheKey, value, options.Expiration, anchor, elapsed, policy, options.Token) + : ((IAnchoredTier)_innerCache).TryFillAsync(options.CacheKey, value, options.Expiration, anchor, policy, options.Token); + + /// As , with the anchor handed to the tier. + private bool FillInBackgroundAnchored(CacheEntryOptions options, WriteAnchor anchor, T? value, CachePolicy policy, ICacheEntry entry, long fill) + { + var name = options.CacheKey.Name; + var watched = fill != BackgroundWrites.Untracked; + if (watched) + { + _background.RetainFill(name); + } + + var queued = _background.RunWithoutEvent( + name, + (Cache: this, Options: options, Anchor: anchor, Value: value, Policy: policy, Entry: entry, Fill: fill), + static s => s.Cache.MemorySet(s.Options, s.Value, s.Cache.DisconnectedLifetime(s.Policy), s.Entry, s.Policy), + static (s, token) => s.Cache.DetachedWriteAsync(s, static (s, token) => s.Cache.FillDetachedAnchoredAsync(s.Options, s.Anchor, s.Value, s.Policy, s.Entry, s.Fill, token), static s => s.Cache.PromoteDetached(s.Options, s.Value, s.Policy, s.Entry), publish: null, token), + static s => s.Cache.EndFill(s.Options.CacheKey.Name, s.Fill)) is not null; + if (!queued && watched) + { + EndFill(name, fill); + } + + return queued; + } + + private async ValueTask FillDetachedAnchoredAsync(CacheEntryOptions options, WriteAnchor anchor, T? value, CachePolicy policy, ICacheEntry entry, long fill, CancellationToken token) + { + try + { + // The key may have changed while the write waited in the queue. + if (!_background.FillIntact(options.CacheKey.Name, fill)) + { + _background.FillSuperseded(); + return false; + } + + var filled = await TryFillOrReplaceAnchoredAsync(options, anchor, value, policy, fill).ConfigureAwait(false); + switch (filled.Outcome) + { + case FillOutcome.Added: + return true; + case FillOutcome.Existed: + SwapForStored(options, policy, entry, filled); + return true; + case FillOutcome.Removed: + // The generator ran across a removal: the value this node kept ahead of the write goes too. + _background.FillSuperseded(); + ApplyLocal(options.CacheKey.Name, (Cache: this, options.CacheKey.Name, Kept: entry), static s => s.Cache.IsLocalEntry(s.Name, s.Kept) && s.Cache.RemoveHeld(s.Name)); + return false; + default: + return false; + } + } + catch (OperationCanceledException) when (token.IsCancellationRequested) + { + throw; + } + catch (Exception ex) + { + LogInnerCacheSetError(ex, Logged(options, typeof(T))); + return false; + } + finally + { + EndFill(options.CacheKey.Name, fill); + } + } +} diff --git a/src/UiPath.Caching/MultilayerCache.AnchoredGetOrAdd.cs b/src/UiPath.Caching/MultilayerCache.AnchoredGetOrAdd.cs new file mode 100644 index 000000000..666bd567e --- /dev/null +++ b/src/UiPath.Caching/MultilayerCache.AnchoredGetOrAdd.cs @@ -0,0 +1,332 @@ +namespace UiPath.Caching; + +/// +/// The get-or-add and result calls of a layered cache whose shared tier takes the anchor (WA4 (b), WA6): twins of the miss path that carry the anchor of the call's deadline beside its options, in the type of +/// the generator where the run's frames take it, and hand it to the tier at the store. A hit takes the path of today, and a rehydrate takes its own anchor where it makes its fresh deadline. +/// +internal sealed partial class MultilayerCache +{ + private ValueTask GetOrAddInternalAnchoredAsync(CacheKey cacheKey, Func> generator, DateTimeOffset expiration, WriteAnchor anchor, TimeSpan effectiveDuration, CachePolicy policy, long seen, bool localMissed, CancellationToken token) + { + // Not async, as the path of today: the miss path's delegates capture these parameters, and an async method would build that closure on a hit too. + NotCacheableException.ThrowIfNotCacheable(); + if (!localMissed && !token.IsCancellationRequested) + { + var probe = ProbeLocal(cacheKey, token, out var local); + if (probe == LocalProbe.Hit && local!.Found) + { + Layered().TryRehydrate(cacheKey, local.Expiration, local.Value, generator, policy, effectiveDuration, null); + return new ValueTask(local.Value); + } + + localMissed = probe == LocalProbe.Miss; + } + + return GetOrAddCoreAnchoredAsync(cacheKey, generator, expiration, anchor, effectiveDuration, null, policy, seen, localMissed, token); + } + + private ValueTask GetOrAddInternalAnchoredAsync(CacheKey cacheKey, TState state, Func> generator, DateTimeOffset expiration, WriteAnchor anchor, TimeSpan effectiveDuration, CachePolicy policy, long seen, bool localMissed, CancellationToken token) + { + // Binds the state to a delegate only where one is needed, so a hit builds no closure. + NotCacheableException.ThrowIfNotCacheable(); + if (!localMissed && !token.IsCancellationRequested) + { + var probe = ProbeLocal(cacheKey, token, out var local); + if (probe == LocalProbe.Hit && local!.Found) + { + var layered = Layered(); + if (layered.ShouldRehydrate(local.Value, policy, effectiveDuration)) + { + layered.TriggerRehydrate(cacheKey, local.Expiration, Bind(state, generator), policy, effectiveDuration, null); + } + + return new ValueTask(local.Value); + } + + localMissed = probe == LocalProbe.Miss; + } + + return GetOrAddCoreAnchoredAsync(cacheKey, Bind(state, generator), expiration, anchor, effectiveDuration, null, policy, seen, localMissed, token); + } + + /// The miss of a get-or-add whose deadline has an anchor; a miss of a policy call (no ) makes its jittered deadline and its anchor here (WA4 (b)). + private ValueTask GetOrAddCoreAnchoredAsync(CacheKey cacheKey, Func> generator, DateTimeOffset? expiration, WriteAnchor handed, TimeSpan effectiveDuration, TimeSpan? rehydrateJitter, CachePolicy policy, long seen, bool localMissed, CancellationToken token) + { + try + { + var deadline = expiration ?? JitteredFor(effectiveDuration, rehydrateJitter, ref handed); + var (options, anchor) = _entryBuilder.BuildEntryOptions(cacheKey, deadline, handed, token); + if (TryGetCooling(options.CacheKey.Name, policy, out var cooling)) + { + return new ValueTask(cooling.Value); + } + + var fetch = localMissed ? Layered().FetchInnerAsync(options, policy) : GetCacheEntryInnerAsync(options, policy); + var miss = new Miss(cacheKey, options, generator, effectiveDuration, rehydrateJitter, policy, seen, localMissed); + if (fetch.IsCompletedSuccessfully) + { + return GenerateOnMissAnchoredAsync(miss, anchor, fetch.Result, token); + } + + return AwaitFetchAnchoredAsync(miss, anchor, fetch, token); + } + catch (Exception ex) + { + return FailedAsync(ex); + } + } + + private DateTimeOffset JitteredFor(TimeSpan duration, TimeSpan? jitter, ref WriteAnchor anchor) + { + var (deadline, taken) = JitteredAnchored(duration, jitter); + anchor = taken; + return deadline; + } + + private ValueTask GenerateOnMissAnchoredAsync(Miss miss, WriteAnchor anchor, ICacheEntry entry, CancellationToken token) + { + if (entry.Found) + { + Layered().TryRehydrate(miss.Key, entry.Expiration, entry.Value, miss.Generator, miss.Policy, miss.Duration, miss.RehydrateJitter); + return new ValueTask(entry.Value); + } + + var generated = GetOrGenerateEntryAsync> Generator, WriteAnchor Anchor)>(miss.Options, (miss.Generator, anchor), miss.Policy, static (cache, options, g, p, scope) => cache.RunGeneratorAndStoreEntryAnchoredAsync(options, g.Anchor, g.Generator, p, scope), miss.Seen, miss.InnerMissed, token); + if (generated.IsCompletedSuccessfully) + { + return new ValueTask(((ICacheEntry)generated.Result!).Value); + } + + return ValueOfAsync(generated); + } + + private async ValueTask AwaitFetchAnchoredAsync(Miss miss, WriteAnchor anchor, ValueTask> fetch, CancellationToken token) + { + var entry = await fetch.ConfigureAwait(false); + return await GenerateOnMissAnchoredAsync(miss, anchor, entry, token).ConfigureAwait(false); + } + + private ValueTask> GetOrAddResultInternalAnchoredAsync(CacheKey cacheKey, Func> generator, DateTimeOffset expiration, WriteAnchor anchor, TimeSpan effectiveDuration, CachePolicy policy, long seen, bool localMissed, CancellationToken token) + { + NotCacheableException.ThrowIfNotCacheable(); + if (!localMissed && !token.IsCancellationRequested) + { + var probe = ProbeLocal(cacheKey, token, out var local); + if (probe == LocalProbe.Hit && local!.Found) + { + Layered().TryRehydrate(cacheKey, local.Expiration, local.Value, generator, policy, effectiveDuration, null); + return new ValueTask>(ResultOf(local, generated: false)); + } + + localMissed = probe == LocalProbe.Miss; + } + + return GetOrAddResultCoreAnchoredAsync(cacheKey, generator, expiration, anchor, effectiveDuration, null, policy, seen, localMissed, token); + } + + private ValueTask> GetOrAddResultInternalAnchoredAsync(CacheKey cacheKey, TState state, Func> generator, DateTimeOffset expiration, WriteAnchor anchor, TimeSpan effectiveDuration, CachePolicy policy, long seen, bool localMissed, CancellationToken token) + { + NotCacheableException.ThrowIfNotCacheable(); + if (!localMissed && !token.IsCancellationRequested) + { + var probe = ProbeLocal(cacheKey, token, out var local); + if (probe == LocalProbe.Hit && local!.Found) + { + var layered = Layered(); + if (layered.ShouldRehydrate(local.Value, policy, effectiveDuration)) + { + layered.TriggerRehydrate(cacheKey, local.Expiration, Bind(state, generator), policy, effectiveDuration, null); + } + + return new ValueTask>(ResultOf(local, generated: false)); + } + + localMissed = probe == LocalProbe.Miss; + } + + return GetOrAddResultCoreAnchoredAsync(cacheKey, Bind(state, generator), expiration, anchor, effectiveDuration, null, policy, seen, localMissed, token); + } + + /// The miss of a result call whose deadline has an anchor, as for a call that reports what it ran. + private async ValueTask> GetOrAddResultCoreAnchoredAsync(CacheKey cacheKey, Func> generator, DateTimeOffset? expiration, WriteAnchor handed, TimeSpan effectiveDuration, TimeSpan? rehydrateJitter, CachePolicy policy, long seen, bool localMissed, CancellationToken token) + { + var deadline = expiration ?? JitteredFor(effectiveDuration, rehydrateJitter, ref handed); + var (options, anchor) = _entryBuilder.BuildEntryOptions(cacheKey, deadline, handed, token); + if (TryGetCooling(options.CacheKey.Name, policy, out var cooling)) + { + return ResultOf(cooling, generated: false); + } + + var entry = localMissed ? await Layered().FetchInnerAsync(options, policy).ConfigureAwait(false) : await GetCacheEntryInnerAsync(options, policy).ConfigureAwait(false); + if (entry.Found) + { + Layered().TryRehydrate(cacheKey, entry.Expiration, entry.Value, generator, policy, effectiveDuration, rehydrateJitter); + return ResultOf(entry, generated: false); + } + + var recorder = GeneratorRecorder.For(generator); + var generated = (ICacheEntry)(await GetOrGenerateEntryAsync> Generator, WriteAnchor Anchor)>( + options, + (recorder.Generator, anchor), + policy, + static (cache, o, g, p, scope) => cache.RunGeneratorAndStoreEntryAnchoredAsync(o, g.Anchor, g.Generator, p, scope), + seen, + localMissed, + token).ConfigureAwait(false))!; + return ResultOf(generated, recorder.Ran); + } + + private async ValueTask GetOrAddGeneratedAnchoredAsync(CacheKey cacheKey, Func>> generator, CachePolicy policy, long seen, bool localMissed, CancellationToken token) + { + NotCacheableException.ThrowIfNotCacheable(); + var (deadline, anchor) = GetExpirationAnchored(policy); + var (cacheEntryOptions, _) = _entryBuilder.BuildEntryOptions(cacheKey, deadline, anchor, token); + if (TryGetCooling(cacheEntryOptions.CacheKey.Name, policy, out var cooling)) + { + return cooling.Value; + } + + var entry = localMissed + ? await Layered().FetchInnerAsync(cacheEntryOptions, policy).ConfigureAwait(false) + : await GetCacheEntryInnerAsync(cacheEntryOptions, policy).ConfigureAwait(false); + if (entry.Found) + { + return entry.Value; + } + + var result = (ICacheEntry)(await GetOrGenerateEntryAsync>> Generator, WriteAnchor Anchor)>(cacheEntryOptions, (generator, anchor), policy, static (cache, options, g, p, scope) => cache.RunGeneratedAndStoreEntryAnchoredAsync(options, g.Anchor, g.Generator, p, scope), seen, localMissed, token).ConfigureAwait(false))!; + return result.Value; + } + + private async ValueTask GetOrAddGeneratedAnchoredAsync(CacheKey cacheKey, TState state, Func>> generator, CachePolicy policy, long seen, bool localMissed, CancellationToken token) + { + NotCacheableException.ThrowIfNotCacheable(); + var (deadline, anchor) = GetExpirationAnchored(policy); + var (cacheEntryOptions, _) = _entryBuilder.BuildEntryOptions(cacheKey, deadline, anchor, token); + if (TryGetCooling(cacheEntryOptions.CacheKey.Name, policy, out var cooling)) + { + return cooling.Value; + } + + var entry = localMissed + ? await Layered().FetchInnerAsync(cacheEntryOptions, policy).ConfigureAwait(false) + : await GetCacheEntryInnerAsync(cacheEntryOptions, policy).ConfigureAwait(false); + if (entry.Found) + { + return entry.Value; + } + + var result = (ICacheEntry)(await GetOrGenerateEntryAsync>> Generator, WriteAnchor Anchor)>(cacheEntryOptions, (StatefulCacheExtensions.BindGenerated(state, generator), anchor), policy, static (cache, options, g, p, scope) => cache.RunGeneratedAndStoreEntryAnchoredAsync(options, g.Anchor, g.Generator, p, scope), seen, localMissed, token).ConfigureAwait(false))!; + return result.Value; + } + + private ValueTask RunGeneratorAndStoreEntryAnchoredAsync(CacheEntryOptions cacheEntryOptions, WriteAnchor anchor, Func> generator, CachePolicy policy, GenerationScope scope) => + policy.FailSafeEnabled == true + ? RunOrStaleAsync>, T?>(cacheEntryOptions, generator, static (f, ct) => f(ct), policy, scope, localOnly: false, static (c, v, expiration) => c._cacheEntryFactory.Create(v, expiration), (c, o, v, p, s, l) => c.StoreGeneratedEntryAnchoredAsync(o, anchor, v, p, s, l)) + : RunOrdinaryGeneratorAnchoredAsync(cacheEntryOptions, anchor, generator, policy, scope); + + private ValueTask RunGeneratedAndStoreEntryAnchoredAsync(CacheEntryOptions cacheEntryOptions, WriteAnchor anchor, Func>> generator, CachePolicy policy, GenerationScope scope) => + policy.FailSafeEnabled == true + ? RunOrStaleAsync>>, GeneratedValue>(cacheEntryOptions, generator, static (f, ct) => f(ct), policy, scope, localOnly: false, static (c, g, expiration) => c._cacheEntryFactory.Create(g.Value, g.Expiration ?? expiration), (c, o, v, p, s, l) => c.StoreGeneratedValueAnchoredAsync(o, anchor, v, p, s, l)) + : RunOrdinaryGeneratedAnchoredAsync(cacheEntryOptions, anchor, generator, policy, scope); + + private async ValueTask RunOrdinaryGeneratorAnchoredAsync(CacheEntryOptions cacheEntryOptions, WriteAnchor anchor, Func> generator, CachePolicy policy, GenerationScope scope) + { + ICacheEntry entry; + scope = BeginFill(cacheEntryOptions, scope, localOnly: false); + try + { + LogCacheMissed(Logged(cacheEntryOptions, typeof(T))); + var ret = await FactoryTimeout.RunAsync(generator, static (f, ct) => f(ct), policy.FactoryTimeout, cacheEntryOptions.CacheKey, Name, Telemetry, scope.Token, clock: _clock).ConfigureAwait(false); + entry = await StoreGeneratedEntryAnchoredAsync(cacheEntryOptions, anchor, ret, policy, scope).ConfigureAwait(false); + } + catch (Exception ex) + { + scope.Fail(ex); + throw; + } + finally + { + EndFill(cacheEntryOptions.CacheKey.Name, scope); + } + + scope.Complete(entry); + return entry; + } + + private async ValueTask RunOrdinaryGeneratedAnchoredAsync(CacheEntryOptions cacheEntryOptions, WriteAnchor anchor, Func>> generator, CachePolicy policy, GenerationScope scope) + { + ICacheEntry entry; + scope = BeginFill(cacheEntryOptions, scope, localOnly: false); + try + { + LogCacheMissed(Logged(cacheEntryOptions, typeof(T))); + var generated = await FactoryTimeout.RunAsync(generator, static (f, ct) => f(ct), policy.FactoryTimeout, cacheEntryOptions.CacheKey, Name, Telemetry, scope.Token, clock: _clock).ConfigureAwait(false); + entry = await StoreGeneratedValueAnchoredAsync(cacheEntryOptions, anchor, generated, policy, scope, localOnly: false).ConfigureAwait(false); + } + catch (Exception ex) + { + scope.Fail(ex); + throw; + } + finally + { + EndFill(cacheEntryOptions.CacheKey.Name, scope); + } + + scope.Complete(entry); + return entry; + } + + private async ValueTask> StoreGeneratedEntryAnchoredAsync(CacheEntryOptions cacheEntryOptions, WriteAnchor anchor, T? ret, CachePolicy policy, GenerationScope scope, bool localOnly = false) + { + // One entry for the local tier and the caller: both see the same value and deadline. + var entry = _cacheEntryFactory.Create(ret, cacheEntryOptions.Expiration, cacheEntryOptions.Metadata as EntryValidators); + + if (TryPrepareGeneratedStore(cacheEntryOptions, ret, policy, scope, localOnly, entry, out var store, out var innerCacheDisconnected, anchor)) + { + if (innerCacheDisconnected) + { + await StoreGeneratedForegroundAsync(store, ret, true, policy, entry).ConfigureAwait(false); + } + else + { + var (adopted, won) = await FillInnerAnchoredAsync(store, anchor, ret, policy, entry, scope.Fill).ConfigureAwait(false); + if (adopted is not null) + { + entry = adopted; + } + + // Peers in a cooldown serve the value this one replaces, and need the event. + if (won && InLateStore) + { + await Layered().PublishSetAsync(store).ConfigureAwait(false); + } + } + } + + return entry; + } + + /// As : a generator's own instant takes its anchor at its first validation, from the one UTC reading that also says whether it has passed (WA4 (d)). + private ValueTask> StoreGeneratedValueAnchoredAsync(CacheEntryOptions cacheEntryOptions, WriteAnchor anchor, GeneratedValue generated, CachePolicy policy, GenerationScope scope, bool localOnly) + { + if (generated.Expiration is { } expiration) + { + cacheEntryOptions.Expiration = expiration; + if (WriteAnchor.Validate(_clock, expiration, out anchor) is null) + { + // As a value that is stored: a generator every caller left answers for nobody, and a newer run may have kept its own value. + if (!scope.IsAbandoned) + { + DropKeptForUnstored(cacheEntryOptions.CacheKey.Name); + } + + return new(_cacheEntryFactory.Create(generated.Value, expiration)); + } + } + + // Its task as it is: a frame here would cost a state machine whenever the inner write is not complete. + return StoreGeneratedEntryAnchoredAsync(cacheEntryOptions, anchor, generated.Value, generated.SkipFailSafe ? WithoutFailSafe(policy) : policy, scope, localOnly); + } +} diff --git a/src/UiPath.Caching/MultilayerCache.AnchoredLayered.cs b/src/UiPath.Caching/MultilayerCache.AnchoredLayered.cs new file mode 100644 index 000000000..42b9edbf5 --- /dev/null +++ b/src/UiPath.Caching/MultilayerCache.AnchoredLayered.cs @@ -0,0 +1,129 @@ +namespace UiPath.Caching; + +internal sealed partial class MultilayerCache +{ + /// The layered entry flow of a write that carries its anchor beside its options (WA6): the same flow as , over a shape whose inner writes hand the anchor to the tier. + private LayeredEntry, T?, AnchoredOptions, bool> AnchoredLayered() => new(this, new AnchoredShape(this)); + + private readonly struct AnchoredShape(MultilayerCache cache) : ILayeredShape + { + public Type EntryType => typeof(T); + + public string Kind => "cache"; + + public bool InnerIsNull => !cache._sharedInner; + + public bool CanAdopt => Plain.CanAdopt; + + public bool CanStamp => Plain.CanStamp; + + public IStampedTier? StampedTier => Plain.StampedTier; + + /// The shape of the path without an anchor, for what the two share. + public CacheShape Plain => new(cache); + + public bool IsEmpty(T? value) => value is null; + + public T? Present(T? value) => value; + + public AnchoredOptions BuildOptions(CacheKey cacheKey, DateTimeOffset expiration, CancellationToken token) => + new(Plain.BuildOptions(cacheKey, expiration, token), default); + + public AnchoredOptions BuildJittered(CacheKey cacheKey, TimeSpan duration, TimeSpan? jitter, CancellationToken token) + { + var (expiration, anchor) = cache.JitteredAnchored(duration, jitter); + return new(Plain.BuildOptions(cacheKey, expiration, token), anchor); + } + + public AnchoredOptions BuildOwn(CacheKey cacheKey, DateTimeOffset expiration, CancellationToken token) + { + _ = WriteAnchor.Validate(cache._clock, expiration, out var anchor); + return new(Plain.BuildOptions(cacheKey, expiration, token), anchor); + } + + public ValueTask? RehydrateAnchored(CacheKey originalCacheKey, DateTimeOffset entryExpiration, Func> generator, CachePolicy policy, TimeSpan duration, TimeSpan? jitter, RehydrateRun run, CancellationToken ct, RehydrateOverride? shaped) => null; + + public ValueTask> ReadInnerAsync(AnchoredOptions options, CachePolicy policy) => Plain.ReadInnerAsync(options.Options, policy); + + public ValueTask> ReadForAdoptionAsync(AnchoredOptions options, CachePolicy policy, StampBox stamp) => Plain.ReadForAdoptionAsync(options.Options, policy, stamp); + + public async ValueTask StoreStampedAsync(AnchoredOptions options, T? value, CachePolicy policy, StampBox stamp) + { + try + { + stamp.TryGet(out var seen); + return await cache._background.WriteAsync( + options.CacheKey.Name, + (Cache: cache, Shape: Plain, Options: options, Value: value, Policy: policy, Seen: seen), + null, + static (s, _) => ((IAnchoredTier)s.Cache._innerCache).WriteIfStampAsync(s.Options.CacheKey, s.Value, s.Options.Expiration, s.Options.Anchor, s.Policy, s.Seen, s.Options.Token), + static (s, written, keeper) => + { + if (written == StampedWrite.Won) + { + s.Cache.KeepAfterInnerWrite(true, false, s.Policy, (s.Shape, s.Options, s.Value, Keeper: keeper, Policy: s.Policy), static (x, max) => x.Shape.KeepWritten(x.Keeper, x.Options.Options, x.Value, max, null, 0, x.Policy), s.Options.Token); + } + + return written; + }, + options.Token).ConfigureAwait(false); + } + catch (OperationCanceledException) when (options.Token.IsCancellationRequested) + { + return StampedWrite.Failed; + } + catch (Exception ex) + { + cache.LogInnerCacheSetError(ex, cache.Logged(options.Options, typeof(T))); + return StampedWrite.Failed; + } + } + + public void Adopt(ref AnchoredOptions options, ICacheEntry fetched) => options = options.WithExpiration(fetched.Expiration); + + public void LogFoundInner(AnchoredOptions options) => Plain.LogFoundInner(options.Options); + + public bool KeepLocal(AnchoredOptions options, T? value, TimeSpan? maxExpiration, CachePolicy policy) => Plain.KeepLocal(options.Options, value, maxExpiration, policy); + + public bool KeepObserved(AnchoredOptions options, T? value, ObservedLife observed, TimeSpan? maxExpiration, CachePolicy policy) => + Plain.KeepObserved(options.Options, value, observed, maxExpiration, policy); + + public bool KeepWhileDisconnected(AnchoredOptions options, T? value, TimeSpan? maxExpiration, ICacheEntry? entry, CachePolicy policy) => + Plain.KeepWhileDisconnected(options.Options, value, maxExpiration, entry, policy); + + public bool KeepWritten(BackgroundWrites.Keeper keeper, AnchoredOptions options, T? value, TimeSpan? maxExpiration, ICacheEntry? entry, long version, CachePolicy policy) => + Plain.KeepWritten(keeper, options.Options, value, maxExpiration, entry, version, policy); + + public bool Written(bool write) => write; + + public VersionedWrite Counted(bool write) => default; + + public long Version(bool write) => 0; + + [AsyncMethodBuilder(typeof(Pooled<>))] + public async ValueTask WriteInnerAsync(AnchoredOptions options, T? value, CachePolicy policy, bool keepRefused, BackgroundWrites.Keeper keeper) + { + try + { + // A late fail-safe value checks in the key's turn that nothing removed or replaced the key since its generator started. + if (!cache.LateStillCurrent(options.Options)) + { + return false; + } + + return await ((IAnchoredTier)cache._innerCache).SetAsync(options.CacheKey, value, options.Expiration, options.Anchor, policy, options.Token).ConfigureAwait(false); + } + catch (OperationCanceledException) when (!keepRefused && options.Token.IsCancellationRequested) + { + return false; + } + catch (Exception ex) when (keepRefused && !(ex is OperationCanceledException && options.Token.IsCancellationRequested)) + { + cache.LogInnerCacheSetError(ex, cache.Logged(options.Options, typeof(T))); + return false; + } + } + + public ValueTask AnnounceSetAsync(AnchoredOptions options, VersionedWrite counted) => Plain.AnnounceSetAsync(options.Options, counted); + } +} diff --git a/src/UiPath.Caching/MultilayerCache.AnchoredWrite.cs b/src/UiPath.Caching/MultilayerCache.AnchoredWrite.cs new file mode 100644 index 000000000..6c6cf52bc --- /dev/null +++ b/src/UiPath.Caching/MultilayerCache.AnchoredWrite.cs @@ -0,0 +1,437 @@ +namespace UiPath.Caching; + +/// +/// The writes of a layered cache whose shared tier takes the anchor (WA6): each is the twin of the write of the same name, with the anchor beside its options, and hands the instant and the anchor +/// to the tier. The writes of today's path keep their shape and their states (C6). +/// +internal sealed partial class MultilayerCache +{ + private async ValueTask SetCoreAnchoredAsync(CacheKey cacheKey, T? value, DateTimeOffset expiration, WriteAnchor handed, CachePolicy policy, CancellationToken token) + { + NotCacheableException.ThrowIfNotCacheable(); + var (cacheEntryOptions, anchor) = _entryBuilder.BuildEntryOptions(cacheKey, expiration, handed, token); + if (value is null && !_multiLayerCacheOptions.CacheNullValues) + { + return await RemoveAsync(cacheEntryOptions).ConfigureAwait(false); + } + + LogReplacingCachedKey(Logged(cacheEntryOptions, typeof(T))); + var innerCacheDisconnected = GetInnerCacheDisconnected(); + var layered = AnchoredLayered(); + var options = new AnchoredOptions(cacheEntryOptions, anchor); + if (innerCacheDisconnected) + { + return await layered.InternalSetAsync(options, value, innerCacheDisconnected, policy).ConfigureAwait(false); + } + + if (policy.BackgroundDistributedWrite == true && _background.TryReserve(cacheEntryOptions.CacheKey.Name, true) && SetInBackgroundAnchored(cacheEntryOptions, anchor, value, policy) is { } detached) + { + return detached; + } + + // Written before the event, so a node it wakes reads the new value. + var (written, kept, _) = await layered.SetInnerAsync(options, value, innerCacheDisconnected, policy, keepRefused: false).ConfigureAwait(false); + return written && await layered.PublishSetAsync(options).ConfigureAwait(false) && kept; + } + + private async ValueTask SetCoreAnchoredAsync(KeyValuePair[] keyValues, DateTimeOffset expiration, WriteAnchor anchor, CachePolicy policy, CancellationToken token) + { + NotCacheableException.ThrowIfNotCacheable(); + var removeEntries = new List(); + var setEntries = new List>(); + foreach (var keyValue in keyValues) + { + if (keyValue.Value is null && !_multiLayerCacheOptions.CacheNullValues) + { + removeEntries.Add(_entryBuilder.BuildEntryOptions(keyValue.Key, token: token)); + } + else + { + setEntries.Add(new (_entryBuilder.BuildEntryOptions(keyValue.Key, expiration, anchor, token).Options, keyValue.Value)); + } + } + + if (removeEntries.Count > 0) + { + var result = await RemoveAsync(removeEntries.ToArray(), token).ConfigureAwait(false); + if (!result) + { + return false; + } + } + + var innerCacheDisconnected = GetInnerCacheDisconnected(); + var (written, kept) = await SetInnerAnchoredAsync(setEntries.ToArray(), anchor, innerCacheDisconnected, policy, keepRefused: false, token).ConfigureAwait(false); + if (innerCacheDisconnected) + { + if (kept && _logger.IsEnabled(LogLevel.Trace)) + { + LogSettingLocalOnlyForCacheKeys(Logged(setEntries.Select(o => o.CacheEntry).ToArray(), typeof(T))); + } + return kept; + } + + // Announced even when the write reports failure: across Redis Cluster slots it can have written some keys, and a peer + // that drops an unchanged copy only reads it again. + var published = await PublishSetsAsync(setEntries).ConfigureAwait(false); + return written && published && kept; + } + + private async ValueTask<(bool Written, bool Kept)> SetInnerAnchoredAsync(CacheEntryValue[] cacheEntries, WriteAnchor anchor, bool innerCacheDisconnected, CachePolicy policy, bool keepRefused, CancellationToken token) + { + try + { + var cacheKeyValuePairs = cacheEntries.Select(c => new KeyValuePair(c.CacheEntry.CacheKey, c.Value)).ToArray(); + + if (innerCacheDisconnected) + { + if (_logger.IsEnabled(LogLevel.Trace)) + { + LogSettingLocalOnlyForCacheKeys(Logged(cacheEntries.Select(o => o.CacheEntry).ToArray(), typeof(T))); + } + return (false, Array.TrueForAll(cacheEntries, e => ApplyLocal(e.CacheEntry.CacheKey.Name, (Cache: this, Entry: e, Max: policy.LocalExpirationDisconnected ?? _multiLayerCacheOptions.LocalMaxExpirationDisconnected, Policy: policy), static s => s.Cache.MemorySet(s.Entry.CacheEntry, s.Entry.Value, s.Max, failSafe: s.Policy)))); + } + + return await _background.WriteAsync( + cacheEntries.Select(c => c.CacheEntry.CacheKey.Name), + (Cache: this, Entries: cacheEntries, Pairs: cacheKeyValuePairs, Anchor: anchor, Policy: policy, KeepRefused: keepRefused, Token: token), + null, + static (s, _) => s.Cache.SetBatchAnchoredAsync(s.Entries, s.Pairs, s.Anchor, s.Policy, s.KeepRefused, s.Token), + static (s, set, keeper) => + { + // Across Redis Cluster slots a write that reports failure can have written some keys, and this node does not hear + // its own events; dropped inside the turn, so no other write of these keys lands in between. + if (!set && !s.KeepRefused) + { + s.Cache.RemoveLocal(s.Entries); + } + + return (set, s.Cache.KeepAfterInnerWrite(set, s.KeepRefused, s.Policy, (s.Cache, s.Entries, Keeper: keeper, s.Policy), static (x, max) => Array.TrueForAll(x.Entries, e => x.Keeper.Local(e.CacheEntry.CacheKey.Name, (x.Cache, e, max, x.Policy), static y => y.Cache.MemorySet(y.e.CacheEntry, y.e.Value, y.max, null, y.Policy))), s.Token)); + }, + token).ConfigureAwait(false); + } + catch (OperationCanceledException) when (token.IsCancellationRequested) + { + return (false, false); + } + catch (Exception ex) + { + LogBatchSetError(ex, cacheEntries); + return (false, false); + } + } + + private async ValueTask SetBatchAnchoredAsync(CacheEntryValue[] entries, KeyValuePair[] pairs, WriteAnchor anchor, CachePolicy policy, bool keepRefused, CancellationToken token) + { + try + { + // One deadline for the batch, taken from the first entry, and the one anchor of the call. + return await ((IAnchoredTier)_innerCache).SetAsync(pairs, entries[0].CacheEntry.Expiration, anchor, policy, token).ConfigureAwait(false); + } + catch (OperationCanceledException) when (!keepRefused && token.IsCancellationRequested) + { + return false; + } + catch (Exception ex) when (keepRefused && !(ex is OperationCanceledException && token.IsCancellationRequested)) + { + LogBatchSetError(ex, entries); + return false; + } + } + + /// The inner write, the promotion and the event follow detached, as does, with the anchor handed to the tier. + private bool? SetInBackgroundAnchored(CacheEntryOptions options, WriteAnchor anchor, T? value, CachePolicy policy) + { + var entry = NewEntry(options, value); + return _background.Run(options.CacheKey.Name, (Cache: this, Options: options, Anchor: anchor, Value: value, Policy: policy, Entry: entry), static s => s.Cache.MemorySet(s.Options, s.Value, s.Cache.DisconnectedLifetime(s.Policy), s.Entry, s.Policy), static (s, token) => + s.Cache.DetachedWriteAsync(s, static (s, token) => s.Cache.WriteDetachedAnchoredAsync(s.Options, s.Anchor, s.Value, s.Policy, token), static s => s.Cache.PromoteDetached(s.Options, s.Value, s.Policy, s.Entry), static s => s.Cache.Layered().PublishSetAsync(s.Options), token)); + } + + private async ValueTask WriteDetachedAnchoredAsync(CacheEntryOptions options, WriteAnchor anchor, T? value, CachePolicy policy, CancellationToken token) + { + try + { + return await ((IAnchoredTier)_innerCache).SetAsync(options.CacheKey, value, options.Expiration, anchor, policy, token).ConfigureAwait(false); + } + catch (OperationCanceledException) when (token.IsCancellationRequested) + { + throw; + } + catch (Exception ex) + { + LogInnerCacheSetError(ex, Logged(options, typeof(T))); + return false; + } + } + + private async ValueTask TryAddCoreAnchoredAsync(CacheKey cacheKey, T? value, DateTimeOffset expiration, WriteAnchor handed, CachePolicy policy, CancellationToken token) + { + NotCacheableException.ThrowIfNotCacheable(); + var (options, anchor) = _entryBuilder.BuildEntryOptions(cacheKey, expiration, handed, token); + + if (value is null && !_multiLayerCacheOptions.CacheNullValues) + { + LogTryAddSkippedUnrepresentableValue(Logged(options, typeof(T))); + return false; + } + + if (options.Expiration <= _clock.GetUtcNow()) + { + LogTryAddSkippedExpiredEntry(Logged(options, typeof(T)), options.Expiration); + return false; + } + + var localMaxExpiration = policy.LocalExpiration ?? _multiLayerCacheOptions.LocalMaxExpiration; + if (localMaxExpiration is { } max && max <= TimeSpan.Zero) + { + LogTryAddSkippedNonPositiveLocalRetention(Logged(options, typeof(T)), max); + return false; + } + + return await TryAddUnderRunAnchoredAsync(options, anchor, value, policy, localMaxExpiration).ConfigureAwait(false); + } + + private async ValueTask TryAddUnderRunAnchoredAsync(CacheEntryOptions options, WriteAnchor anchor, T? value, CachePolicy policy, TimeSpan? localMaxExpiration) + { + var key = new InFlightKey(options.CacheKey.Name, typeof(T), null, null); + if (!_generations.TryReserve(key, out var reservation) + && (!await WaitForRunAsync(key, ResolveLocalLock(policy.Lock).Timeout, options.Token).ConfigureAwait(false) || !_generations.TryReserve(key, out reservation))) + { + LogTryAddKeyBusy(Logged(options, typeof(T))); + return false; + } + + var added = false; + try + { + added = await TryAddUnderLocalLockAnchoredAsync(options, anchor, value, policy, localMaxExpiration).ConfigureAwait(false); + return added; + } + finally + { + // Callers that joined the add take its value, or take the key over when it lost. + if (added) + { + reservation.Complete(_cacheEntryFactory.Create(value, options.Expiration)); + } + else + { + reservation.Fail(new InFlightAbandonedException()); + } + } + } + + private async ValueTask TryAddUnderLocalLockAnchoredAsync(CacheEntryOptions options, WriteAnchor anchor, T? value, CachePolicy policy, TimeSpan? localMaxExpiration) + { + if (_memoryCache.TryGetValue(options.CacheKey.Name, out var held) && Live(held)) + { + return false; + } + + // Released before the event, so a slow one does not hold the key's background writes. + var added = await _background.WriteAsync( + options.CacheKey.Name, + (Cache: this, Options: options, Anchor: anchor, Value: value, Policy: policy, Max: localMaxExpiration), + null, + [AsyncMethodBuilder(typeof(Pooled<>))] static async ValueTask (s, _) => + { + try + { + return await ((IAnchoredTier)s.Cache._innerCache).TryAddAsync(s.Options.CacheKey, s.Value, s.Options.Expiration, s.Anchor, s.Policy, s.Options.Token).ConfigureAwait(false); + } + catch (Exception ex) when (!(ex is OperationCanceledException && s.Options.Token.IsCancellationRequested)) + { + s.Cache.LogInnerCacheTryAddError(ex, s.Cache.Logged(s.Options, typeof(T))); + return false; + } + }, + static (s, added, keeper) => s.Cache.KeepAdded(s.Options, s.Value, s.Max, s.Policy, added, keeper), + options.Token).ConfigureAwait(false); + if (!added) + { + return false; + } + + // Best-effort after the win: a loss reported here would strand the entry with no owner. + try + { + if (!await _eventPublisher.CacheSetAsync(options, typeof(T)).ConfigureAwait(false)) + { + LogTryAddBroadcastNotPublished(Logged(options, typeof(T))); + } + } + catch (Exception ex) + { + LogTryAddLocalPropagationFailed(ex, Logged(options, typeof(T))); + } + + return true; + } + + /// Keeps the added value locally, inside the key's turn; a failure is logged and the add still stands. + private bool KeepAdded(CacheEntryOptions options, T? value, TimeSpan? max, CachePolicy policy, bool added, BackgroundWrites.Keeper keeper) + { + if (added) + { + try + { + keeper.Local(options.CacheKey.Name, (Cache: this, Options: options, Value: value, Max: max, Policy: policy), static x => x.Cache.MemorySet(x.Options, x.Value, x.Max, null, x.Policy)); + } + catch (Exception ex) + { + LogTryAddLocalPropagationFailed(ex, Logged(options, typeof(T))); + } + } + + return added; + } + + private ValueTask> SetManyCoreAnchoredAsync(IEnumerable> keyValues, DateTimeOffset expiration, WriteAnchor anchor, CachePolicy policy, CancellationToken token) + { + NotCacheableException.ThrowIfNotCacheable(); + return RunBatchAsync( + keyValues, + (Cache: this, Expiration: expiration, Anchor: anchor, Policy: policy, Token: token), + static kv => kv.Key, + static (s, chunk, count, announce) => s.Cache.SetChunkAnchoredAsync(chunk, count, s.Expiration, s.Anchor, s.Policy, announce, s.Token), + static (s, first) => s.Cache._eventPublisher.TopicInvalidatedAsync(s.Cache._entryBuilder.BuildEntryOptions(first, default, CancellationToken.None).TopicKey), + token); + } + + private async ValueTask?> SetChunkAnchoredAsync(KeyValuePair[] chunk, int count, DateTimeOffset expiration, WriteAnchor anchor, CachePolicy policy, bool announce, CancellationToken token) + { + var (keys, entries, entryCount, removals) = Partition(chunk, count, expiration, token); + List? failed = null; + if (removals is not null) + { + AddFailed(ref failed, await RemoveChunkAsync(removals.ToArray(), removals.Count, announce, token).ConfigureAwait(false)); + } + + if (entryCount == 0) + { + return failed; + } + + if (GetInnerCacheDisconnected()) + { + KeepDisconnected(keys, entries, entryCount, policy, ref failed); + return failed; + } + + var (written, kept, toAnnounce, announceIndex, announceCount, cancelled) = await WriteChunkAnchoredAsync(entries, entryCount, expiration, anchor, policy, announce, token).ConfigureAwait(false); + var published = announce && announceCount > 0 + ? await AllAsync(toAnnounce, announceCount, this, static (c, o) => c.Layered().PublishSetAsync(o), static (c, o, ex) => c.LogSetEventError(ex, c.Logged(o, typeof(T)))).ConfigureAwait(false) + : []; + if (cancelled) + { + throw new OperationCanceledException(token); + } + + var announcedOk = new bool[entryCount]; + for (var j = 0; j < published.Length; j++) + { + announcedOk[announceIndex[j]] = published[j]; + } + + for (var i = 0; i < entryCount; i++) + { + if (!written[i] || !kept[i] || (announce && !announcedOk[i])) + { + (failed ??= []).Add(keys[i]); + } + } + + return failed; + } + + /// The turn is released before the events. + private ValueTask<(bool[] Written, bool[] Kept, CacheEntryOptions[] ToAnnounce, int[] AnnounceIndex, int AnnounceCount, bool Cancelled)> WriteChunkAnchoredAsync(CacheEntryValue[] entries, int entryCount, DateTimeOffset expiration, WriteAnchor anchor, CachePolicy policy, bool announce, CancellationToken token) => + _background.WriteAsync( + entries.Take(entryCount).Select(e => e.CacheEntry.CacheKey.Name), + (Cache: this, Entries: entries, Count: entryCount, Expiration: expiration, Anchor: anchor, Policy: policy, Announce: announce, Token: token), + null, + static (s, _) => IssueAsync( + s.Entries, + s.Count, + (s.Cache, s.Expiration, s.Anchor, s.Policy), + static (x, e) => ((IAnchoredTier)x.Cache._innerCache).SetAsync(e.CacheEntry.CacheKey, e.Value, x.Expiration, x.Anchor, x.Policy, e.CacheEntry.Token), + static (x, e, ex) => x.Cache.LogInnerCacheSetError(ex, x.Cache.Logged(e.CacheEntry, typeof(T))), + s.Token), + static (s, issued, keeper) => s.Cache.KeepChunk(s.Entries, s.Count, issued, s.Policy, s.Announce, keeper, s.Token), + token); + + /// The write beside the migration seam: the store write of WriteAsync for an inner tier that has no seam and takes the anchor. + private async ValueTask WriteAnchoredAsync(CacheKey cacheKey, T? value, DateTimeOffset expiration, CachePolicy? policy, CancellationToken token) + { + var sink = new StoreSink(); + try + { + NotCacheableException.ThrowIfNotCacheable(); + var (deadline, anchor) = GetExpirationAnchored(expiration); + var (options, _) = _entryBuilder.BuildEntryOptions(cacheKey, deadline, anchor, token); + if (value is null && !_multiLayerCacheOptions.CacheNullValues) + { + await RemoveRecordedAsync(options, sink).ConfigureAwait(false); + } + else + { + LogReplacingCachedKey(Logged(options, typeof(T))); + var (written, counted) = await SetRecordedAnchoredAsync(options, anchor, value, policy ?? _defaultPolicy, sink).ConfigureAwait(false); + if (written) + { + await Layered().PublishSetAsync(options, counted).ConfigureAwait(false); + } + } + } + catch (Exception ex) when (ex is not OutOfMemoryException) + { + LogInnerCacheSetError(ex, Logged(cacheKey, typeof(T))); + } + + return sink.Outcome ?? StoreOutcome.NotSent; + } + + private async ValueTask<(bool Written, VersionedWrite Counted)> SetRecordedAnchoredAsync(CacheEntryOptions options, WriteAnchor anchor, T? value, CachePolicy policy, StoreSink sink) + { + try + { + var (written, _, counted) = await _background.WriteAsync( + options.CacheKey.Name, + (Cache: this, Shape: new CacheShape(this), Options: options, Anchor: anchor, Value: value, Policy: policy, Sink: sink), + null, + static (s, keeper) => s.Cache.WriteRecordedAnchoredAsync(s.Options, s.Anchor, s.Value, s.Policy, s.Sink), + static (s, written, keeper) => (written, s.Cache.KeepAfterInnerWrite(written, false, s.Policy, (s.Shape, s.Options, s.Value, Keeper: keeper, Written: written, s.Policy), static (x, max) => x.Shape.KeepWritten(x.Keeper, x.Options, x.Value, max, null, x.Shape.Version(x.Written), x.Policy), s.Options.Token), s.Shape.Counted(written)), + options.Token).ConfigureAwait(false); + return (written, counted); + } + catch (OperationCanceledException) when (options.Token.IsCancellationRequested) + { + return (false, default); + } + catch (Exception ex) + { + LogInnerCacheSetError(ex, Logged(options, typeof(T))); + return (false, default); + } + } + + private async ValueTask WriteRecordedAnchoredAsync(CacheEntryOptions options, WriteAnchor anchor, T? value, CachePolicy policy, StoreSink sink) + { + try + { + if (!LateStillCurrent(options)) + { + return false; + } + + var outcome = await ((IAnchoredTier)_innerCache).SetAsync(options.CacheKey, value, options.Expiration, anchor, policy, options.Token).ConfigureAwait(false) ? StoreOutcome.Committed : StoreOutcome.Unknown; + sink.Record(outcome); + return outcome == StoreOutcome.Committed; + } + catch (Exception) + { + sink.Record(StoreOutcome.Unknown); + throw; + } + } +} diff --git a/src/UiPath.Caching/MultilayerCache.Fill.cs b/src/UiPath.Caching/MultilayerCache.Fill.cs index d240fdc05..b2a14b401 100644 --- a/src/UiPath.Caching/MultilayerCache.Fill.cs +++ b/src/UiPath.Caching/MultilayerCache.Fill.cs @@ -12,17 +12,49 @@ private enum LocalChangeState Lapsed, } - public ValueTask> TryFillAsync(CacheKey cacheKey, T? value, TimeSpan expiration, CachePolicy? policy, CancellationToken token = default) => - TryFillCoreAsync(cacheKey, value, GetExpiration(expiration), policy ?? _defaultPolicy, token); + public ValueTask> TryFillAsync(CacheKey cacheKey, T? value, TimeSpan expiration, CachePolicy? policy, CancellationToken token = default) + { + if (TakesAnchor) + { + var (deadline, anchor) = GetExpirationAnchored(expiration); + return TryFillCoreAnchoredAsync(cacheKey, value, deadline, anchor, policy ?? _defaultPolicy, token); + } - public ValueTask> TryFillAsync(CacheKey cacheKey, T? value, DateTimeOffset expiration, CachePolicy? policy, CancellationToken token = default) => - TryFillCoreAsync(cacheKey, value, GetExpiration(expiration), policy ?? _defaultPolicy, token); + return TryFillCoreAsync(cacheKey, value, GetExpiration(expiration), policy ?? _defaultPolicy, token); + } + + public ValueTask> TryFillAsync(CacheKey cacheKey, T? value, DateTimeOffset expiration, CachePolicy? policy, CancellationToken token = default) + { + if (TakesAnchor) + { + var (deadline, anchor) = GetExpirationAnchored(expiration); + return TryFillCoreAnchoredAsync(cacheKey, value, deadline, anchor, policy ?? _defaultPolicy, token); + } - public ValueTask> SetIfChangedAsync(CacheKey cacheKey, T? value, IEqualityComparer comparer, TimeSpan expiration, CachePolicy? policy, CancellationToken token = default) => - SetIfChangedCoreAsync(cacheKey, value, comparer, GetExpiration(expiration), policy ?? _defaultPolicy, token); + return TryFillCoreAsync(cacheKey, value, GetExpiration(expiration), policy ?? _defaultPolicy, token); + } - public ValueTask> SetIfChangedAsync(CacheKey cacheKey, T? value, IEqualityComparer comparer, DateTimeOffset expiration, CachePolicy? policy, CancellationToken token = default) => - SetIfChangedCoreAsync(cacheKey, value, comparer, GetExpiration(expiration), policy ?? _defaultPolicy, token); + public ValueTask> SetIfChangedAsync(CacheKey cacheKey, T? value, IEqualityComparer comparer, TimeSpan expiration, CachePolicy? policy, CancellationToken token = default) + { + if (TakesAnchor) + { + var (deadline, anchor) = GetExpirationAnchored(expiration); + return SetIfChangedCoreAnchoredAsync(cacheKey, value, comparer, deadline, anchor, policy ?? _defaultPolicy, token); + } + + return SetIfChangedCoreAsync(cacheKey, value, comparer, GetExpiration(expiration), policy ?? _defaultPolicy, token); + } + + public ValueTask> SetIfChangedAsync(CacheKey cacheKey, T? value, IEqualityComparer comparer, DateTimeOffset expiration, CachePolicy? policy, CancellationToken token = default) + { + if (TakesAnchor) + { + var (deadline, anchor) = GetExpirationAnchored(expiration); + return SetIfChangedCoreAnchoredAsync(cacheKey, value, comparer, deadline, anchor, policy ?? _defaultPolicy, token); + } + + return SetIfChangedCoreAsync(cacheKey, value, comparer, GetExpiration(expiration), policy ?? _defaultPolicy, token); + } public ValueTask> ReadSnapshotAsync(CacheKey cacheKey, CachePolicy? policy, CancellationToken token = default) { @@ -86,6 +118,12 @@ private async ValueTask> TryFillCoreAsync(CacheKey cacheKey, T? filled = default; } + return AfterFill(filled, options, mark, value, policy); + } + + /// What the layered cache keeps locally of an inner fill's answer. + private FillResult AfterFill(FillResult filled, CacheEntryOptions options, long mark, T? value, CachePolicy policy) + { switch (filled.Outcome) { case FillOutcome.Added: diff --git a/src/UiPath.Caching/MultilayerCache.Generate.cs b/src/UiPath.Caching/MultilayerCache.Generate.cs index 4835ce331..fed5337e9 100644 --- a/src/UiPath.Caching/MultilayerCache.Generate.cs +++ b/src/UiPath.Caching/MultilayerCache.Generate.cs @@ -253,7 +253,8 @@ private bool TryPrepareGeneratedStore( bool localOnly, ICacheEntry entry, out CacheEntryOptions store, - out bool disconnected) + out bool disconnected, + WriteAnchor? anchor = null) { store = default; disconnected = false; @@ -287,7 +288,7 @@ private bool TryPrepareGeneratedStore( } // A peer that takes the distributed lock next must find the value; a late fail-safe value checks in its foreground turn that it is still current. - var detached = !disconnected && policy.BackgroundDistributedWrite == true && !DistributedLockOn(policy.Lock) && !InLateStore && _background.TryReserve(options.CacheKey.Name, false) && FillInBackground(store, value, policy, entry, scope.Fill); + var detached = !disconnected && policy.BackgroundDistributedWrite == true && !DistributedLockOn(policy.Lock) && !InLateStore && _background.TryReserve(options.CacheKey.Name, false) && (anchor is { } held ? FillInBackgroundAnchored(store, held, value, policy, entry, scope.Fill) : FillInBackground(store, value, policy, entry, scope.Fill)); return !detached; } @@ -321,7 +322,18 @@ private bool ProbeMemoryOnly(CacheKey cacheKey, CancellationToken token, out return found; } - private async ValueTask GetOrAddGeneratedAsync(CacheKey cacheKey, Func>> generator, CachePolicy policy, long seen, bool localMissed, CancellationToken token) + // Not async: the cache whose shared tier takes the anchor makes the deadline of the call with its anchor (WA4 (b)); the run of today is untouched. + private ValueTask GetOrAddGeneratedAsync(CacheKey cacheKey, Func>> generator, CachePolicy policy, long seen, bool localMissed, CancellationToken token) => + TakesAnchor + ? GetOrAddGeneratedAnchoredAsync(cacheKey, generator, policy, seen, localMissed, token) + : GetOrAddGeneratedCoreAsync(cacheKey, generator, policy, seen, localMissed, token); + + private ValueTask GetOrAddGeneratedAsync(CacheKey cacheKey, TState state, Func>> generator, CachePolicy policy, long seen, bool localMissed, CancellationToken token) => + TakesAnchor + ? GetOrAddGeneratedAnchoredAsync(cacheKey, state, generator, policy, seen, localMissed, token) + : GetOrAddGeneratedCoreAsync(cacheKey, state, generator, policy, seen, localMissed, token); + + private async ValueTask GetOrAddGeneratedCoreAsync(CacheKey cacheKey, Func>> generator, CachePolicy policy, long seen, bool localMissed, CancellationToken token) { NotCacheableException.ThrowIfNotCacheable(); if (!localMissed && !_sharedInner && !token.IsCancellationRequested && ProbeMemoryOnly(cacheKey, token, out var hit, out localMissed)) @@ -353,7 +365,7 @@ private bool ProbeMemoryOnly(CacheKey cacheKey, CancellationToken token, out return result.Value; } - private async ValueTask GetOrAddGeneratedAsync(CacheKey cacheKey, TState state, Func>> generator, CachePolicy policy, long seen, bool localMissed, CancellationToken token) + private async ValueTask GetOrAddGeneratedCoreAsync(CacheKey cacheKey, TState state, Func>> generator, CachePolicy policy, long seen, bool localMissed, CancellationToken token) { // As the closure form above; the state is bound to a delegate only for the miss, so a hit builds no closure. NotCacheableException.ThrowIfNotCacheable(); diff --git a/src/UiPath.Caching/MultilayerCache.GetOrAdd.cs b/src/UiPath.Caching/MultilayerCache.GetOrAdd.cs index b166b311a..6b9150c0c 100644 --- a/src/UiPath.Caching/MultilayerCache.GetOrAdd.cs +++ b/src/UiPath.Caching/MultilayerCache.GetOrAdd.cs @@ -15,6 +15,12 @@ internal sealed partial class MultilayerCache public ValueTask GetOrAddAsync(CacheKey cacheKey, Func> generator, TimeSpan expiration, CachePolicy? policy, CancellationToken token = default) { ArgumentNullException.ThrowIfNull(generator); + if (TakesAnchor) + { + var (anchoredExpiration, anchoredDuration, anchor) = CallerWriteAnchored(expiration); + return GetOrAddInternalAnchoredAsync(cacheKey, generator, anchoredExpiration, anchor, anchoredDuration, policy ?? _defaultPolicy, _localMemorySetter.Writes, localMissed: false, token); + } + var (writeExpiration, duration) = CallerWrite(expiration); return GetOrAddInternalAsync(cacheKey, generator, writeExpiration, duration, rehydrateJitter: null, policy ?? _defaultPolicy, _localMemorySetter.Writes, localMissed: false, token); } @@ -23,6 +29,12 @@ internal sealed partial class MultilayerCache public ValueTask GetOrAddAsync(CacheKey cacheKey, Func> generator, DateTimeOffset expiration, CachePolicy? policy, CancellationToken token = default) { ArgumentNullException.ThrowIfNull(generator); + if (TakesAnchor) + { + var (anchoredExpiration, anchoredDuration, anchor) = CallerWriteAnchored(expiration); + return GetOrAddInternalAnchoredAsync(cacheKey, generator, anchoredExpiration, anchor, anchoredDuration, policy ?? _defaultPolicy, _localMemorySetter.Writes, localMissed: false, token); + } + var (writeExpiration, duration) = CallerWrite(expiration); return GetOrAddInternalAsync(cacheKey, generator, writeExpiration, duration, rehydrateJitter: null, policy ?? _defaultPolicy, _localMemorySetter.Writes, localMissed: false, token); } @@ -40,6 +52,16 @@ internal sealed partial class MultilayerCache public ValueTask GetOrAddAsync(Span cacheKey, Func> generator, TimeSpan expiration, CachePolicy? policy, CancellationToken token = default) { ArgumentNullException.ThrowIfNull(generator); + if (TakesAnchor) + { + var (anchoredExpiration, anchoredDuration, anchor) = CallerWriteAnchored(expiration); + var anchoredSeen = _localMemorySetter.Writes; + var anchoredProbe = ProbeGetOrAddLocal(cacheKey, policy ?? _defaultPolicy, token, out var anchoredValue); + return anchoredProbe == LocalProbe.Hit + ? new ValueTask(anchoredValue) + : GetOrAddInternalAnchoredAsync(new CacheKey(cacheKey), generator, anchoredExpiration, anchor, anchoredDuration, policy ?? _defaultPolicy, anchoredSeen, anchoredProbe == LocalProbe.Miss, token); + } + var (writeExpiration, duration) = CallerWrite(expiration); var seen = _localMemorySetter.Writes; var probe = ProbeGetOrAddLocal(cacheKey, policy ?? _defaultPolicy, token, out var value); @@ -51,6 +73,16 @@ internal sealed partial class MultilayerCache public ValueTask GetOrAddAsync(Span cacheKey, Func> generator, DateTimeOffset expiration, CachePolicy? policy, CancellationToken token = default) { ArgumentNullException.ThrowIfNull(generator); + if (TakesAnchor) + { + var (anchoredExpiration, anchoredDuration, anchor) = CallerWriteAnchored(expiration); + var anchoredSeen = _localMemorySetter.Writes; + var anchoredProbe = ProbeGetOrAddLocal(cacheKey, policy ?? _defaultPolicy, token, out var anchoredValue); + return anchoredProbe == LocalProbe.Hit + ? new ValueTask(anchoredValue) + : GetOrAddInternalAnchoredAsync(new CacheKey(cacheKey), generator, anchoredExpiration, anchor, anchoredDuration, policy ?? _defaultPolicy, anchoredSeen, anchoredProbe == LocalProbe.Miss, token); + } + var (writeExpiration, duration) = CallerWrite(expiration); var seen = _localMemorySetter.Writes; var probe = ProbeGetOrAddLocal(cacheKey, policy ?? _defaultPolicy, token, out var value); @@ -69,6 +101,12 @@ internal sealed partial class MultilayerCache public ValueTask GetOrAddAsync(CacheKey cacheKey, TState state, Func> generator, TimeSpan expiration, CachePolicy? policy, CancellationToken token = default) { ArgumentNullException.ThrowIfNull(generator); + if (TakesAnchor) + { + var (anchoredExpiration, anchoredDuration, anchor) = CallerWriteAnchored(expiration); + return GetOrAddInternalAnchoredAsync(cacheKey, state, generator, anchoredExpiration, anchor, anchoredDuration, policy ?? _defaultPolicy, _localMemorySetter.Writes, localMissed: false, token); + } + var (writeExpiration, duration) = CallerWrite(expiration); return GetOrAddInternalAsync(cacheKey, state, generator, writeExpiration, duration, rehydrateJitter: null, policy ?? _defaultPolicy, _localMemorySetter.Writes, localMissed: false, token); } @@ -76,6 +114,12 @@ internal sealed partial class MultilayerCache public ValueTask GetOrAddAsync(CacheKey cacheKey, TState state, Func> generator, DateTimeOffset expiration, CachePolicy? policy, CancellationToken token = default) { ArgumentNullException.ThrowIfNull(generator); + if (TakesAnchor) + { + var (anchoredExpiration, anchoredDuration, anchor) = CallerWriteAnchored(expiration); + return GetOrAddInternalAnchoredAsync(cacheKey, state, generator, anchoredExpiration, anchor, anchoredDuration, policy ?? _defaultPolicy, _localMemorySetter.Writes, localMissed: false, token); + } + var (writeExpiration, duration) = CallerWrite(expiration); return GetOrAddInternalAsync(cacheKey, state, generator, writeExpiration, duration, rehydrateJitter: null, policy ?? _defaultPolicy, _localMemorySetter.Writes, localMissed: false, token); } @@ -93,6 +137,16 @@ internal sealed partial class MultilayerCache public ValueTask GetOrAddAsync(Span cacheKey, TState state, Func> generator, TimeSpan expiration, CachePolicy? policy, CancellationToken token = default) { ArgumentNullException.ThrowIfNull(generator); + if (TakesAnchor) + { + var (anchoredExpiration, anchoredDuration, anchor) = CallerWriteAnchored(expiration); + var anchoredSeen = _localMemorySetter.Writes; + var anchoredProbe = ProbeGetOrAddLocal(cacheKey, policy ?? _defaultPolicy, token, out var anchoredValue); + return anchoredProbe == LocalProbe.Hit + ? new ValueTask(anchoredValue) + : GetOrAddInternalAnchoredAsync(new CacheKey(cacheKey), state, generator, anchoredExpiration, anchor, anchoredDuration, policy ?? _defaultPolicy, anchoredSeen, anchoredProbe == LocalProbe.Miss, token); + } + var (writeExpiration, duration) = CallerWrite(expiration); var seen = _localMemorySetter.Writes; var probe = ProbeGetOrAddLocal(cacheKey, policy ?? _defaultPolicy, token, out var value); @@ -104,6 +158,16 @@ internal sealed partial class MultilayerCache public ValueTask GetOrAddAsync(Span cacheKey, TState state, Func> generator, DateTimeOffset expiration, CachePolicy? policy, CancellationToken token = default) { ArgumentNullException.ThrowIfNull(generator); + if (TakesAnchor) + { + var (anchoredExpiration, anchoredDuration, anchor) = CallerWriteAnchored(expiration); + var anchoredSeen = _localMemorySetter.Writes; + var anchoredProbe = ProbeGetOrAddLocal(cacheKey, policy ?? _defaultPolicy, token, out var anchoredValue); + return anchoredProbe == LocalProbe.Hit + ? new ValueTask(anchoredValue) + : GetOrAddInternalAnchoredAsync(new CacheKey(cacheKey), state, generator, anchoredExpiration, anchor, anchoredDuration, policy ?? _defaultPolicy, anchoredSeen, anchoredProbe == LocalProbe.Miss, token); + } + var (writeExpiration, duration) = CallerWrite(expiration); var seen = _localMemorySetter.Writes; var probe = ProbeGetOrAddLocal(cacheKey, policy ?? _defaultPolicy, token, out var value); @@ -120,6 +184,12 @@ internal sealed partial class MultilayerCache policy ??= _defaultPolicy; // One floored resolution for the write and the rehydrate threshold; only the write is jittered. var duration = ResolveDuration(policy); + if (TakesAnchor) + { + var (anchoredExpiration, anchor) = JitteredAnchored(duration, policy.JitterMaxDuration); + return GetOrAddBatchInternalAnchoredAsync[]>>>(entries, generator, DirectBatch.Invoke, anchoredExpiration, anchor, duration, policy.JitterMaxDuration, policy, token); + } + var writeExpiration = _clock.ToDateTimeOffset(ApplyJitter(duration, policy.JitterMaxDuration)); return GetOrAddBatchInternalAsync[]>>>(entries, generator, DirectBatch.Invoke, writeExpiration, duration, policy.JitterMaxDuration, policy, token); } @@ -129,6 +199,12 @@ internal sealed partial class MultilayerCache { ArgumentNullException.ThrowIfNull(entries); ArgumentNullException.ThrowIfNull(generator); + if (TakesAnchor) + { + var (anchoredExpiration, anchoredDuration, anchor) = CallerWriteAnchored(expiration); + return GetOrAddBatchInternalAnchoredAsync[]>>>(entries, generator, DirectBatch.Invoke, anchoredExpiration, anchor, anchoredDuration, rehydrateJitter: null, policy ?? _defaultPolicy, token); + } + var (writeExpiration, duration) = CallerWrite(expiration); return GetOrAddBatchInternalAsync[]>>>(entries, generator, DirectBatch.Invoke, writeExpiration, duration, rehydrateJitter: null, policy ?? _defaultPolicy, token); } @@ -138,6 +214,12 @@ internal sealed partial class MultilayerCache { ArgumentNullException.ThrowIfNull(entries); ArgumentNullException.ThrowIfNull(generator); + if (TakesAnchor) + { + var (anchoredExpiration, anchoredDuration, anchor) = CallerWriteAnchored(expiration); + return GetOrAddBatchInternalAnchoredAsync[]>>>(entries, generator, DirectBatch.Invoke, anchoredExpiration, anchor, anchoredDuration, rehydrateJitter: null, policy ?? _defaultPolicy, token); + } + var (writeExpiration, duration) = CallerWrite(expiration); return GetOrAddBatchInternalAsync[]>>>(entries, generator, DirectBatch.Invoke, writeExpiration, duration, rehydrateJitter: null, policy ?? _defaultPolicy, token); } @@ -150,6 +232,12 @@ internal sealed partial class MultilayerCache policy ??= _defaultPolicy; // One floored resolution for the write and the rehydrate threshold; only the write is jittered. var duration = ResolveDuration(policy); + if (TakesAnchor) + { + var (anchoredExpiration, anchor) = JitteredAnchored(duration, policy.JitterMaxDuration); + return GetOrAddBatchInternalAnchoredAsync(entries, argument, generator, anchoredExpiration, anchor, duration, policy.JitterMaxDuration, policy, token); + } + var writeExpiration = _clock.ToDateTimeOffset(ApplyJitter(duration, policy.JitterMaxDuration)); return GetOrAddBatchInternalAsync(entries, argument, generator, writeExpiration, duration, policy.JitterMaxDuration, policy, token); } @@ -159,6 +247,12 @@ internal sealed partial class MultilayerCache { ArgumentNullException.ThrowIfNull(entries); ArgumentNullException.ThrowIfNull(generator); + if (TakesAnchor) + { + var (anchoredExpiration, anchoredDuration, anchor) = CallerWriteAnchored(expiration); + return GetOrAddBatchInternalAnchoredAsync(entries, argument, generator, anchoredExpiration, anchor, anchoredDuration, rehydrateJitter: null, policy ?? _defaultPolicy, token); + } + var (writeExpiration, duration) = CallerWrite(expiration); return GetOrAddBatchInternalAsync(entries, argument, generator, writeExpiration, duration, rehydrateJitter: null, policy ?? _defaultPolicy, token); } @@ -168,6 +262,12 @@ internal sealed partial class MultilayerCache { ArgumentNullException.ThrowIfNull(entries); ArgumentNullException.ThrowIfNull(generator); + if (TakesAnchor) + { + var (anchoredExpiration, anchoredDuration, anchor) = CallerWriteAnchored(expiration); + return GetOrAddBatchInternalAnchoredAsync(entries, argument, generator, anchoredExpiration, anchor, anchoredDuration, rehydrateJitter: null, policy ?? _defaultPolicy, token); + } + var (writeExpiration, duration) = CallerWrite(expiration); return GetOrAddBatchInternalAsync(entries, argument, generator, writeExpiration, duration, rehydrateJitter: null, policy ?? _defaultPolicy, token); } @@ -279,6 +379,12 @@ internal sealed partial class MultilayerCache private ValueTask GetOrAddCoreAsync(CacheKey cacheKey, Func> generator, DateTimeOffset? expiration, TimeSpan effectiveDuration, TimeSpan? rehydrateJitter, CachePolicy policy, long seen, bool localMissed, CancellationToken token) { // Not async: a miss that never waits builds no state machine, and one that waits builds one, where an async method here would build one for the wait at every step. + // The miss of a policy call makes its deadline here, so it is where the tier is asked whether it takes the anchor (WA6). + if (expiration is null && TakesAnchor) + { + return GetOrAddCoreAnchoredAsync(cacheKey, generator, null, default, effectiveDuration, rehydrateJitter, policy, seen, localMissed, token); + } + try { var options = _entryBuilder.BuildEntryOptions(cacheKey, expiration ?? _clock.ToDateTimeOffset(ApplyJitter(effectiveDuration, rehydrateJitter)), token); diff --git a/src/UiPath.Caching/MultilayerCache.Layered.cs b/src/UiPath.Caching/MultilayerCache.Layered.cs index e687a6934..f5e55800b 100644 --- a/src/UiPath.Caching/MultilayerCache.Layered.cs +++ b/src/UiPath.Caching/MultilayerCache.Layered.cs @@ -25,6 +25,14 @@ private readonly struct CacheShape(MultilayerCache cache) : ILayeredShape cache._entryBuilder.BuildEntryOptions(cacheKey, expiration, token); + public CacheEntryOptions BuildJittered(CacheKey cacheKey, TimeSpan duration, TimeSpan? jitter, CancellationToken token) => + cache._entryBuilder.BuildEntryOptions(cacheKey, cache._clock.ToDateTimeOffset(ApplyJitter(duration, jitter)), token); + + public CacheEntryOptions BuildOwn(CacheKey cacheKey, DateTimeOffset expiration, CancellationToken token) => BuildOptions(cacheKey, expiration, token); + + public ValueTask? RehydrateAnchored(CacheKey originalCacheKey, DateTimeOffset entryExpiration, Func> generator, CachePolicy policy, TimeSpan duration, TimeSpan? jitter, RehydrateRun run, CancellationToken ct, RehydrateOverride? shaped) => + cache.TakesAnchor ? cache.AnchoredLayered().RunRehydrateAsync(originalCacheKey, entryExpiration, generator, policy, duration, jitter, run, ct, shaped) : null; + public ValueTask> ReadInnerAsync(CacheEntryOptions options, CachePolicy policy) => cache._innerCache.GetCacheEntryAsync(options.CacheKey, policy, options.Token); diff --git a/src/UiPath.Caching/MultilayerCache.Many.cs b/src/UiPath.Caching/MultilayerCache.Many.cs index a28305c98..b678d8845 100644 --- a/src/UiPath.Caching/MultilayerCache.Many.cs +++ b/src/UiPath.Caching/MultilayerCache.Many.cs @@ -17,14 +17,36 @@ public ValueTask> RemoveManyAsync(IEnumerable> SetManyAsync(IEnumerable> keyValues, CachePolicy? policy, CancellationToken token = default) { policy ??= _defaultPolicy; + if (TakesAnchor) + { + var (deadline, anchor) = GetExpirationAnchored(policy); + return SetManyCoreAnchoredAsync(keyValues, deadline, anchor, policy, token); + } + return SetManyCoreAsync(keyValues, GetExpiration(policy), policy, token); } - public ValueTask> SetManyAsync(IEnumerable> keyValues, TimeSpan expiration, CachePolicy? policy, CancellationToken token = default) => - SetManyCoreAsync(keyValues, GetExpiration(expiration), policy ?? _defaultPolicy, token); + public ValueTask> SetManyAsync(IEnumerable> keyValues, TimeSpan expiration, CachePolicy? policy, CancellationToken token = default) + { + if (TakesAnchor) + { + var (deadline, anchor) = GetExpirationAnchored(expiration); + return SetManyCoreAnchoredAsync(keyValues, deadline, anchor, policy ?? _defaultPolicy, token); + } - public ValueTask> SetManyAsync(IEnumerable> keyValues, DateTimeOffset expiration, CachePolicy? policy, CancellationToken token = default) => - SetManyCoreAsync(keyValues, GetExpiration(expiration), policy ?? _defaultPolicy, token); + return SetManyCoreAsync(keyValues, GetExpiration(expiration), policy ?? _defaultPolicy, token); + } + + public ValueTask> SetManyAsync(IEnumerable> keyValues, DateTimeOffset expiration, CachePolicy? policy, CancellationToken token = default) + { + if (TakesAnchor) + { + var (deadline, anchor) = GetExpirationAnchored(expiration); + return SetManyCoreAnchoredAsync(keyValues, deadline, anchor, policy ?? _defaultPolicy, token); + } + + return SetManyCoreAsync(keyValues, GetExpiration(expiration), policy ?? _defaultPolicy, token); + } private ValueTask> SetManyCoreAsync(IEnumerable> keyValues, DateTimeOffset expiration, CachePolicy policy, CancellationToken token) { diff --git a/src/UiPath.Caching/MultilayerCache.Migration.cs b/src/UiPath.Caching/MultilayerCache.Migration.cs index 52d5c21b3..df5923a72 100644 --- a/src/UiPath.Caching/MultilayerCache.Migration.cs +++ b/src/UiPath.Caching/MultilayerCache.Migration.cs @@ -15,6 +15,12 @@ public async ValueTask WriteAsync(CacheKey cacheKey, T? value, return await WriteLocallyAsync(cacheKey, value, expiration, policy, token).ConfigureAwait(false); } + // The seam of an inner tier that has one is plain (IC8); the inner set beside it hands its anchor on. + if (_innerCache is not IMigrationCache && TakesAnchor) + { + return await WriteAnchoredAsync(cacheKey, value, expiration, policy, token).ConfigureAwait(false); + } + var sink = new StoreSink(); try { diff --git a/src/UiPath.Caching/MultilayerCache.Rehydrate.cs b/src/UiPath.Caching/MultilayerCache.Rehydrate.cs index 22d2ae0e8..29ee99370 100644 --- a/src/UiPath.Caching/MultilayerCache.Rehydrate.cs +++ b/src/UiPath.Caching/MultilayerCache.Rehydrate.cs @@ -79,7 +79,9 @@ private void TryRehydrateBatch( duration, kind: "cache", rehydrateAsync: (rehydrateKeys, run, ct) => - RehydrateReservedAsync(rehydrateKeys, stateByCallerKey, byState, generator, policy, duration, rehydrateJitter, run, ct), + TakesAnchor + ? RehydrateReservedAnchoredAsync(rehydrateKeys, stateByCallerKey, byState, generator, policy, duration, rehydrateJitter, run, ct) + : RehydrateReservedAsync(rehydrateKeys, stateByCallerKey, byState, generator, policy, duration, rehydrateJitter, run, ct), entryType: typeof(T)); } diff --git a/src/UiPath.Caching/MultilayerCache.Result.cs b/src/UiPath.Caching/MultilayerCache.Result.cs index 45eeb0db8..113fb3208 100644 --- a/src/UiPath.Caching/MultilayerCache.Result.cs +++ b/src/UiPath.Caching/MultilayerCache.Result.cs @@ -12,6 +12,13 @@ public ValueTask> GetOrAddResultAsync(CacheKey cacheKey, Func< public ValueTask> GetOrAddResultAsync(CacheKey cacheKey, Func> generator, TimeSpan expiration, CachePolicy? policy, CancellationToken token = default) { ArgumentNullException.ThrowIfNull(generator); + if (TakesAnchor) + { + var (anchoredExpiration, anchoredDuration, anchor) = CallerWriteAnchored(expiration); + policy ??= _defaultPolicy; + return GetOrAddResultInternalAnchoredAsync(cacheKey, generator, anchoredExpiration, anchor, anchoredDuration, policy, _localMemorySetter.Writes, localMissed: false, token); + } + var (writeExpiration, duration) = CallerWrite(expiration); policy ??= _defaultPolicy; return GetOrAddResultInternalAsync(cacheKey, generator, writeExpiration, duration, rehydrateJitter: null, policy, _localMemorySetter.Writes, localMissed: false, token); @@ -20,6 +27,13 @@ public ValueTask> GetOrAddResultAsync(CacheKey cacheKey, Func< public ValueTask> GetOrAddResultAsync(CacheKey cacheKey, Func> generator, DateTimeOffset expiration, CachePolicy? policy, CancellationToken token = default) { ArgumentNullException.ThrowIfNull(generator); + if (TakesAnchor) + { + var (anchoredExpiration, anchoredDuration, anchor) = CallerWriteAnchored(expiration); + policy ??= _defaultPolicy; + return GetOrAddResultInternalAnchoredAsync(cacheKey, generator, anchoredExpiration, anchor, anchoredDuration, policy, _localMemorySetter.Writes, localMissed: false, token); + } + var (writeExpiration, duration) = CallerWrite(expiration); policy ??= _defaultPolicy; return GetOrAddResultInternalAsync(cacheKey, generator, writeExpiration, duration, rehydrateJitter: null, policy, _localMemorySetter.Writes, localMissed: false, token); @@ -35,6 +49,13 @@ public ValueTask> GetOrAddResultAsync(CacheKey cacheKe public ValueTask> GetOrAddResultAsync(CacheKey cacheKey, TState state, Func> generator, TimeSpan expiration, CachePolicy? policy, CancellationToken token = default) { ArgumentNullException.ThrowIfNull(generator); + if (TakesAnchor) + { + var (anchoredExpiration, anchoredDuration, anchor) = CallerWriteAnchored(expiration); + policy ??= _defaultPolicy; + return GetOrAddResultInternalAnchoredAsync(cacheKey, state, generator, anchoredExpiration, anchor, anchoredDuration, policy, _localMemorySetter.Writes, localMissed: false, token); + } + var (writeExpiration, duration) = CallerWrite(expiration); policy ??= _defaultPolicy; return GetOrAddResultInternalAsync(cacheKey, state, generator, writeExpiration, duration, rehydrateJitter: null, policy, _localMemorySetter.Writes, localMissed: false, token); @@ -43,6 +64,13 @@ public ValueTask> GetOrAddResultAsync(CacheKey cacheKe public ValueTask> GetOrAddResultAsync(CacheKey cacheKey, TState state, Func> generator, DateTimeOffset expiration, CachePolicy? policy, CancellationToken token = default) { ArgumentNullException.ThrowIfNull(generator); + if (TakesAnchor) + { + var (anchoredExpiration, anchoredDuration, anchor) = CallerWriteAnchored(expiration); + policy ??= _defaultPolicy; + return GetOrAddResultInternalAnchoredAsync(cacheKey, state, generator, anchoredExpiration, anchor, anchoredDuration, policy, _localMemorySetter.Writes, localMissed: false, token); + } + var (writeExpiration, duration) = CallerWrite(expiration); policy ??= _defaultPolicy; return GetOrAddResultInternalAsync(cacheKey, state, generator, writeExpiration, duration, rehydrateJitter: null, policy, _localMemorySetter.Writes, localMissed: false, token); @@ -62,6 +90,17 @@ public ValueTask> GetOrAddResultAsync(Span cacheKey, Fun public ValueTask> GetOrAddResultAsync(Span cacheKey, Func> generator, TimeSpan expiration, CachePolicy? policy, CancellationToken token = default) { ArgumentNullException.ThrowIfNull(generator); + if (TakesAnchor) + { + var (anchoredExpiration, anchoredDuration, anchor) = CallerWriteAnchored(expiration); + policy ??= _defaultPolicy; + var anchoredSeen = _localMemorySetter.Writes; + var anchoredProbe = ProbeGetOrAddLocalEntry(cacheKey, policy, token, out var anchoredHit); + return anchoredProbe == LocalProbe.Hit + ? new ValueTask>(ResultOf(anchoredHit!, generated: false)) + : GetOrAddResultInternalAnchoredAsync(new CacheKey(cacheKey), generator, anchoredExpiration, anchor, anchoredDuration, policy, anchoredSeen, anchoredProbe == LocalProbe.Miss, token); + } + var (writeExpiration, duration) = CallerWrite(expiration); policy ??= _defaultPolicy; var seen = _localMemorySetter.Writes; @@ -74,6 +113,17 @@ public ValueTask> GetOrAddResultAsync(Span cacheKey, Fun public ValueTask> GetOrAddResultAsync(Span cacheKey, Func> generator, DateTimeOffset expiration, CachePolicy? policy, CancellationToken token = default) { ArgumentNullException.ThrowIfNull(generator); + if (TakesAnchor) + { + var (anchoredExpiration, anchoredDuration, anchor) = CallerWriteAnchored(expiration); + policy ??= _defaultPolicy; + var anchoredSeen = _localMemorySetter.Writes; + var anchoredProbe = ProbeGetOrAddLocalEntry(cacheKey, policy, token, out var anchoredHit); + return anchoredProbe == LocalProbe.Hit + ? new ValueTask>(ResultOf(anchoredHit!, generated: false)) + : GetOrAddResultInternalAnchoredAsync(new CacheKey(cacheKey), generator, anchoredExpiration, anchor, anchoredDuration, policy, anchoredSeen, anchoredProbe == LocalProbe.Miss, token); + } + var (writeExpiration, duration) = CallerWrite(expiration); policy ??= _defaultPolicy; var seen = _localMemorySetter.Writes; @@ -97,6 +147,17 @@ public ValueTask> GetOrAddResultAsync(Span cache public ValueTask> GetOrAddResultAsync(Span cacheKey, TState state, Func> generator, TimeSpan expiration, CachePolicy? policy, CancellationToken token = default) { ArgumentNullException.ThrowIfNull(generator); + if (TakesAnchor) + { + var (anchoredExpiration, anchoredDuration, anchor) = CallerWriteAnchored(expiration); + policy ??= _defaultPolicy; + var anchoredSeen = _localMemorySetter.Writes; + var anchoredProbe = ProbeGetOrAddLocalEntry(cacheKey, policy, token, out var anchoredHit); + return anchoredProbe == LocalProbe.Hit + ? new ValueTask>(ResultOf(anchoredHit!, generated: false)) + : GetOrAddResultInternalAnchoredAsync(new CacheKey(cacheKey), state, generator, anchoredExpiration, anchor, anchoredDuration, policy, anchoredSeen, anchoredProbe == LocalProbe.Miss, token); + } + var (writeExpiration, duration) = CallerWrite(expiration); policy ??= _defaultPolicy; var seen = _localMemorySetter.Writes; @@ -109,6 +170,17 @@ public ValueTask> GetOrAddResultAsync(Span cache public ValueTask> GetOrAddResultAsync(Span cacheKey, TState state, Func> generator, DateTimeOffset expiration, CachePolicy? policy, CancellationToken token = default) { ArgumentNullException.ThrowIfNull(generator); + if (TakesAnchor) + { + var (anchoredExpiration, anchoredDuration, anchor) = CallerWriteAnchored(expiration); + policy ??= _defaultPolicy; + var anchoredSeen = _localMemorySetter.Writes; + var anchoredProbe = ProbeGetOrAddLocalEntry(cacheKey, policy, token, out var anchoredHit); + return anchoredProbe == LocalProbe.Hit + ? new ValueTask>(ResultOf(anchoredHit!, generated: false)) + : GetOrAddResultInternalAnchoredAsync(new CacheKey(cacheKey), state, generator, anchoredExpiration, anchor, anchoredDuration, policy, anchoredSeen, anchoredProbe == LocalProbe.Miss, token); + } + var (writeExpiration, duration) = CallerWrite(expiration); policy ??= _defaultPolicy; var seen = _localMemorySetter.Writes; @@ -146,7 +218,9 @@ private ValueTask> GetOrAddResultInternalAsync(CacheKey cacheK localMissed = probe == LocalProbe.Miss; } - return GetOrAddResultCoreAsync(cacheKey, generator, expiration, effectiveDuration, rehydrateJitter, policy, seen, localMissed, token); + return expiration is null && TakesAnchor + ? GetOrAddResultCoreAnchoredAsync(cacheKey, generator, null, default, effectiveDuration, rehydrateJitter, policy, seen, localMissed, token) + : GetOrAddResultCoreAsync(cacheKey, generator, expiration, effectiveDuration, rehydrateJitter, policy, seen, localMissed, token); } private ValueTask> GetOrAddResultInternalAsync(CacheKey cacheKey, TState state, Func> generator, DateTimeOffset? expiration, TimeSpan effectiveDuration, TimeSpan? rehydrateJitter, CachePolicy policy, long seen, bool localMissed, CancellationToken token) @@ -169,7 +243,9 @@ private ValueTask> GetOrAddResultInternalAsync(CacheKe localMissed = probe == LocalProbe.Miss; } - return GetOrAddResultCoreAsync(cacheKey, Bind(state, generator), expiration, effectiveDuration, rehydrateJitter, policy, seen, localMissed, token); + return expiration is null && TakesAnchor + ? GetOrAddResultCoreAnchoredAsync(cacheKey, Bind(state, generator), null, default, effectiveDuration, rehydrateJitter, policy, seen, localMissed, token) + : GetOrAddResultCoreAsync(cacheKey, Bind(state, generator), expiration, effectiveDuration, rehydrateJitter, policy, seen, localMissed, token); } /// The miss path: the generator is wrapped to record that this call ran it, so a call that joined another's run, or found a value after the distributed lock, reports false. diff --git a/src/UiPath.Caching/MultilayerCache.Write.cs b/src/UiPath.Caching/MultilayerCache.Write.cs index 6b109e762..4a32a17f6 100644 --- a/src/UiPath.Caching/MultilayerCache.Write.cs +++ b/src/UiPath.Caching/MultilayerCache.Write.cs @@ -5,14 +5,36 @@ internal sealed partial class MultilayerCache public ValueTask SetAsync(CacheKey cacheKey, T? value, CachePolicy? policy, CancellationToken token = default) { policy ??= _defaultPolicy; + if (TakesAnchor) + { + var (deadline, anchor) = GetExpirationAnchored(policy); + return SetCoreAnchoredAsync(cacheKey, value, deadline, anchor, policy, token); + } + return SetCoreAsync(cacheKey, value, GetExpiration(policy), policy, token); } - public ValueTask SetAsync(CacheKey cacheKey, T? value, TimeSpan expiration, CachePolicy? policy, CancellationToken token = default) => - SetCoreAsync(cacheKey, value, GetExpiration(expiration), policy ?? _defaultPolicy, token); + public ValueTask SetAsync(CacheKey cacheKey, T? value, TimeSpan expiration, CachePolicy? policy, CancellationToken token = default) + { + if (TakesAnchor) + { + var (deadline, anchor) = GetExpirationAnchored(expiration); + return SetCoreAnchoredAsync(cacheKey, value, deadline, anchor, policy ?? _defaultPolicy, token); + } + + return SetCoreAsync(cacheKey, value, GetExpiration(expiration), policy ?? _defaultPolicy, token); + } + + public ValueTask SetAsync(CacheKey cacheKey, T? value, DateTimeOffset expiration, CachePolicy? policy, CancellationToken token = default) + { + if (TakesAnchor) + { + var (deadline, anchor) = GetExpirationAnchored(expiration); + return SetCoreAnchoredAsync(cacheKey, value, deadline, anchor, policy ?? _defaultPolicy, token); + } - public ValueTask SetAsync(CacheKey cacheKey, T? value, DateTimeOffset expiration, CachePolicy? policy, CancellationToken token = default) => - SetCoreAsync(cacheKey, value, GetExpiration(expiration), policy ?? _defaultPolicy, token); + return SetCoreAsync(cacheKey, value, GetExpiration(expiration), policy ?? _defaultPolicy, token); + } public ValueTask SetAsync(Span cacheKey, T? value, CachePolicy? policy, CancellationToken token = default) => SetAsync(new CacheKey(cacheKey), value, policy, token); @@ -26,14 +48,36 @@ public ValueTask SetAsync(Span cacheKey, T? value, DateTimeOffset public ValueTask SetAsync(KeyValuePair[] keyValues, CachePolicy? policy, CancellationToken token = default) { policy ??= _defaultPolicy; + if (TakesAnchor) + { + var (deadline, anchor) = GetExpirationAnchored(policy); + return SetCoreAnchoredAsync(keyValues, deadline, anchor, policy, token); + } + return SetCoreAsync(keyValues, GetExpiration(policy), policy, token); } - public ValueTask SetAsync(KeyValuePair[] keyValues, TimeSpan expiration, CachePolicy? policy, CancellationToken token = default) => - SetCoreAsync(keyValues, GetExpiration(expiration), policy ?? _defaultPolicy, token); + public ValueTask SetAsync(KeyValuePair[] keyValues, TimeSpan expiration, CachePolicy? policy, CancellationToken token = default) + { + if (TakesAnchor) + { + var (deadline, anchor) = GetExpirationAnchored(expiration); + return SetCoreAnchoredAsync(keyValues, deadline, anchor, policy ?? _defaultPolicy, token); + } - public ValueTask SetAsync(KeyValuePair[] keyValues, DateTimeOffset expiration, CachePolicy? policy, CancellationToken token = default) => - SetCoreAsync(keyValues, GetExpiration(expiration), policy ?? _defaultPolicy, token); + return SetCoreAsync(keyValues, GetExpiration(expiration), policy ?? _defaultPolicy, token); + } + + public ValueTask SetAsync(KeyValuePair[] keyValues, DateTimeOffset expiration, CachePolicy? policy, CancellationToken token = default) + { + if (TakesAnchor) + { + var (deadline, anchor) = GetExpirationAnchored(expiration); + return SetCoreAnchoredAsync(keyValues, deadline, anchor, policy ?? _defaultPolicy, token); + } + + return SetCoreAsync(keyValues, GetExpiration(expiration), policy ?? _defaultPolicy, token); + } /// /// One path for every provider: take the local lock, probe the local tier, let the L2 decide, @@ -50,16 +94,38 @@ public ValueTask SetAsync(KeyValuePair[] keyValues, DateT public ValueTask TryAddAsync(CacheKey cacheKey, T? value, CachePolicy? policy, CancellationToken token = default) { policy ??= _defaultPolicy; + if (TakesAnchor) + { + var (deadline, anchor) = GetExpirationAnchored(policy); + return TryAddCoreAnchoredAsync(cacheKey, value, deadline, anchor, policy, token); + } + return TryAddCoreAsync(cacheKey, value, GetExpiration(policy), policy, token); } /// - public ValueTask TryAddAsync(CacheKey cacheKey, T? value, TimeSpan expiration, CachePolicy? policy, CancellationToken token = default) => - TryAddCoreAsync(cacheKey, value, GetExpiration(expiration), policy ?? _defaultPolicy, token); + public ValueTask TryAddAsync(CacheKey cacheKey, T? value, TimeSpan expiration, CachePolicy? policy, CancellationToken token = default) + { + if (TakesAnchor) + { + var (deadline, anchor) = GetExpirationAnchored(expiration); + return TryAddCoreAnchoredAsync(cacheKey, value, deadline, anchor, policy ?? _defaultPolicy, token); + } + + return TryAddCoreAsync(cacheKey, value, GetExpiration(expiration), policy ?? _defaultPolicy, token); + } /// - public ValueTask TryAddAsync(CacheKey cacheKey, T? value, DateTimeOffset expiration, CachePolicy? policy, CancellationToken token = default) => - TryAddCoreAsync(cacheKey, value, GetExpiration(expiration), policy ?? _defaultPolicy, token); + public ValueTask TryAddAsync(CacheKey cacheKey, T? value, DateTimeOffset expiration, CachePolicy? policy, CancellationToken token = default) + { + if (TakesAnchor) + { + var (deadline, anchor) = GetExpirationAnchored(expiration); + return TryAddCoreAnchoredAsync(cacheKey, value, deadline, anchor, policy ?? _defaultPolicy, token); + } + + return TryAddCoreAsync(cacheKey, value, GetExpiration(expiration), policy ?? _defaultPolicy, token); + } public ValueTask RemoveAsync(CacheKey cacheKey, CancellationToken token = default) { diff --git a/src/UiPath.Caching/MultilayerCache.cs b/src/UiPath.Caching/MultilayerCache.cs index 22eedb31a..743bbf96e 100644 --- a/src/UiPath.Caching/MultilayerCache.cs +++ b/src/UiPath.Caching/MultilayerCache.cs @@ -9,6 +9,9 @@ internal sealed partial class MultilayerCache : MultilayerCacheBase, ICache, ISp private readonly bool _fencedInner; + /// The shared tier when it takes the anchor of a write (WA6); whether it does is asked per call through . + private readonly IAnchoredTier? _anchoredInner; + private readonly bool _sharedInner; private readonly InFlight _generations = new(); @@ -42,6 +45,7 @@ public MultilayerCache( { _innerCache = innerCache; _fencedInner = innerCache is IFencedFillTier { IsFenced: true }; + _anchoredInner = innerCache as IAnchoredTier; var cacheKeyStrategy = _multiLayerCacheOptions.CacheKeyStrategy ?? new DefaultCacheKeyStrategy(); var topicKeyStrategy = _multiLayerCacheOptions.TopicKeyStrategy ?? new DefaultTopicKeyStrategy(cacheOptions.Separator); _entryBuilder = new CacheEntryBuilder(cacheKeyStrategy, topicKeyStrategy, _clock); diff --git a/src/UiPath.Caching/MultilayerCacheBase.LayeredEntry.cs b/src/UiPath.Caching/MultilayerCacheBase.LayeredEntry.cs index 082603a2a..cf06f1d95 100644 --- a/src/UiPath.Caching/MultilayerCacheBase.LayeredEntry.cs +++ b/src/UiPath.Caching/MultilayerCacheBase.LayeredEntry.cs @@ -41,7 +41,7 @@ public void TriggerRehydrate(CacheKey originalCacheKey, DateTimeOffset entryExpi policy, duration, kind: shape.Kind, - rehydrateAsync: (run, ct) => flow.RehydrateAsync(originalCacheKey, entryExpiration, generator, policy, duration, rehydrateJitter, run, ct), + rehydrateAsync: (run, ct) => flow.RunRehydrateAsync(originalCacheKey, entryExpiration, generator, policy, duration, rehydrateJitter, run, ct, shaped: null), entryType: shape.EntryType); } @@ -55,10 +55,16 @@ public void TriggerRehydrate(CacheKey originalCacheKey, DateTimeOffset entryExpi policy, duration, kind: shape.Kind, - rehydrateAsync: (run, ct) => flow.RehydrateAsync(originalCacheKey, entryExpiration, generator, policy, duration, rehydrateJitter, run, ct, shaped), + rehydrateAsync: (run, ct) => flow.RunRehydrateAsync(originalCacheKey, entryExpiration, generator, policy, duration, rehydrateJitter, run, ct, shaped), entryType: shape.EntryType); } + /// Runs rehydration using the write anchor when the inner tier takes one. + public ValueTask RunRehydrateAsync(CacheKey originalCacheKey, DateTimeOffset entryExpiration, Func> generator, CachePolicy policy, TimeSpan duration, TimeSpan? rehydrateJitter, RehydrateRun run, CancellationToken ct, RehydrateOverride? shaped) => + shape.RehydrateAnchored(originalCacheKey, entryExpiration, generator, policy, duration, rehydrateJitter, run, ct, shaped) is { } anchored + ? anchored + : RehydrateAsync(originalCacheKey, entryExpiration, generator, policy, duration, rehydrateJitter, run, ct, shaped); + /// Reads the inner tier and keeps a hit locally; concurrent reads of one key share one inner read. The null inner tier has nothing to share or keep. public ValueTask> FetchInnerAsync(TOptions options, CachePolicy policy) => shape.InnerIsNull @@ -234,7 +240,7 @@ private bool Keep(TOptions options, CachePolicy policy, ICacheEntry fetc 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) + private async ValueTask RehydrateAsync(CacheKey originalCacheKey, DateTimeOffset entryExpiration, Func> generator, CachePolicy policy, TimeSpan duration, TimeSpan? rehydrateJitter, RehydrateRun run, CancellationToken ct, RehydrateOverride? shaped) { // What the adoption read saw, so the store below can refuse to overwrite a write that landed while the generator ran. var stamp = new StampBox(); @@ -252,8 +258,8 @@ private async ValueTask RehydrateAsync(CacheKey originalCacheKey, DateTimeOffset { return; } - var rehydrateExpiration = RehydrateExpiration(entryExpiration, policy, duration, rehydrateJitter, empty, shaped); - var rehydrateOptions = shape.BuildOptions(originalCacheKey, rehydrateExpiration, ct); + var rehydrateOptions = BuildRehydrateOptions(originalCacheKey, entryExpiration, policy, duration, rehydrateJitter, empty, shaped, ct); + var rehydrateExpiration = rehydrateOptions.Expiration; if (shaped is not null) { var validators = EntryValidators.Of(shaped.Metadata); @@ -275,16 +281,21 @@ private async ValueTask RehydrateAsync(CacheKey originalCacheKey, DateTimeOffset } } - private DateTimeOffset RehydrateExpiration(DateTimeOffset entryExpiration, CachePolicy policy, TimeSpan duration, TimeSpan? jitter, bool empty, RehydrateOverride? shaped) + private TOptions BuildRehydrateOptions(CacheKey originalCacheKey, DateTimeOffset entryExpiration, CachePolicy policy, TimeSpan duration, TimeSpan? jitter, bool empty, RehydrateOverride? shaped, CancellationToken ct) { // A transition to empty preserves the original deadline. A confirmation renews the observed entry. if (empty && shaped?.NotModified != true) { - return entryExpiration; + return shape.BuildOptions(originalCacheKey, entryExpiration, ct); + } + + if (shaped?.Expiration is { } own) + { + return shape.BuildOwn(originalCacheKey, own, ct); } var lifetime = shaped is null ? duration : cache.ResolveDuration(policy); - return shaped?.Expiration ?? cache._clock.ToDateTimeOffset(ApplyJitter(lifetime, jitter)); + return shape.BuildJittered(originalCacheKey, lifetime, jitter, ct); } private ValueTask StoreRehydratedAsync(CacheKey originalCacheKey, DateTimeOffset entryExpiration, TOptions options, TValue value, CachePolicy policy, TimeSpan duration, RehydrateRun run, StampBox stamp, CancellationToken ct) diff --git a/src/UiPath.Caching/MultilayerCacheBase.cs b/src/UiPath.Caching/MultilayerCacheBase.cs index b32bc7a7b..4f6c569de 100644 --- a/src/UiPath.Caching/MultilayerCacheBase.cs +++ b/src/UiPath.Caching/MultilayerCacheBase.cs @@ -644,6 +644,54 @@ private protected DateTimeOffset GetExpiration(TimeSpan expiration, [CallerArgum private protected DateTimeOffset GetExpiration(DateTimeOffset expiration, [CallerArgumentExpression(nameof(expiration))] string? paramName = null) => CacheExpiration.ThrowIfNotFuture(expiration, _clock.GetUtcNow(), paramName); + /// for a tier that takes the anchor: the timestamp, then the one UTC reading that makes the deadline (WA4 (b)). + private protected (DateTimeOffset Expiration, TimeSpan Duration, WriteAnchor Anchor) CallerWriteAnchored(TimeSpan expiration, [CallerArgumentExpression(nameof(expiration))] string? paramName = null) + { + var duration = CacheExpiration.ThrowIfNotPositive(expiration, paramName); + var anchor = WriteAnchor.Capture(_clock, duration, out var deadline); + return (deadline, duration, anchor); + } + + /// for a tier that takes the anchor: the timestamp, then the one UTC reading that validates the instant and gives its life. + private protected (DateTimeOffset Expiration, TimeSpan Duration, WriteAnchor Anchor) CallerWriteAnchored(DateTimeOffset expiration, [CallerArgumentExpression(nameof(expiration))] string? paramName = null) + { + var remaining = WriteAnchor.Validate(_clock, expiration, out var anchor); + var duration = remaining ?? CacheExpiration.ToDuration(expiration, _clock.GetUtcNow(), paramName); + return (expiration, duration, anchor); + } + + /// with its anchor: the jitter is drawn first, then the timestamp and the UTC reading that makes the deadline. + private protected (DateTimeOffset Expiration, WriteAnchor Anchor) GetExpirationAnchored(CachePolicy policy) + { + var anchor = WriteAnchor.Capture(_clock, ResolveWriteDuration(policy), out var deadline); + return (deadline, anchor); + } + + /// with the anchor of . + private protected (DateTimeOffset Expiration, WriteAnchor Anchor) GetExpirationAnchored(TimeSpan expiration, [CallerArgumentExpression(nameof(expiration))] string? paramName = null) + { + var (deadline, _, anchor) = CallerWriteAnchored(expiration, paramName); + return (deadline, anchor); + } + + /// with its anchor: the instant is validated on the one UTC reading that gives its life. + private protected (DateTimeOffset Expiration, WriteAnchor Anchor) GetExpirationAnchored(DateTimeOffset expiration, [CallerArgumentExpression(nameof(expiration))] string? paramName = null) + { + if (WriteAnchor.Validate(_clock, expiration, out var anchor) is null) + { + CacheExpiration.ThrowIfNotFuture(expiration, _clock.GetUtcNow(), paramName); + } + + return (expiration, anchor); + } + + /// A jittered duration made a deadline with its anchor: the jitter, then the timestamp and the UTC reading that makes the deadline. + private protected (DateTimeOffset Expiration, WriteAnchor Anchor) JitteredAnchored(TimeSpan duration, TimeSpan? maxJitter) + { + var anchor = WriteAnchor.Capture(_clock, ApplyJitter(duration, maxJitter), out var deadline); + return (deadline, anchor); + } + /// /// One place for the in-process policy: a per-call wins over the /// options. Enabled turns the shared run per key on; Timeout is how long a diff --git a/src/UiPath.Caching/MultilayerHashCache.Layered.cs b/src/UiPath.Caching/MultilayerHashCache.Layered.cs index 169fc2d84..67df5d88e 100644 --- a/src/UiPath.Caching/MultilayerHashCache.Layered.cs +++ b/src/UiPath.Caching/MultilayerHashCache.Layered.cs @@ -25,6 +25,13 @@ private readonly struct HashShape(MultilayerHashCache cache) : ILayeredShape< public InternalHashCacheEntryOptions BuildOptions(CacheKey cacheKey, DateTimeOffset expiration, CancellationToken token) => cache._entryBuilder.BuildEntryOptions(cacheKey, expiration, HashCacheSetOption.KeyReplace, token); + public InternalHashCacheEntryOptions BuildJittered(CacheKey cacheKey, TimeSpan duration, TimeSpan? jitter, CancellationToken token) => + BuildOptions(cacheKey, cache._clock.ToDateTimeOffset(ApplyJitter(duration, jitter)), token); + + public InternalHashCacheEntryOptions BuildOwn(CacheKey cacheKey, DateTimeOffset expiration, CancellationToken token) => BuildOptions(cacheKey, expiration, token); + + public ValueTask? RehydrateAnchored(CacheKey originalCacheKey, DateTimeOffset entryExpiration, Func>> generator, CachePolicy policy, TimeSpan duration, TimeSpan? jitter, RehydrateRun run, CancellationToken ct, RehydrateOverride? shaped) => null; + public ValueTask>> ReadInnerAsync(InternalHashCacheEntryOptions options, CachePolicy policy) => cache._innerCache.GetCacheEntryAsync(options.CacheKey, policy, options.Token); diff --git a/src/UiPath.Caching/Negotiation/DesiredFrames.cs b/src/UiPath.Caching/Negotiation/DesiredFrames.cs new file mode 100644 index 000000000..c0aedc5f0 --- /dev/null +++ b/src/UiPath.Caching/Negotiation/DesiredFrames.cs @@ -0,0 +1,4 @@ +namespace UiPath.Caching.Negotiation; + +/// The advertised tokens needed to write entry frames. +internal sealed record DesiredFrames(IReadOnlyList Tokens); diff --git a/src/UiPath.Caching/Negotiation/FormatNegotiation.cs b/src/UiPath.Caching/Negotiation/FormatNegotiation.cs index 13cd05698..115c71a03 100644 --- a/src/UiPath.Caching/Negotiation/FormatNegotiation.cs +++ b/src/UiPath.Caching/Negotiation/FormatNegotiation.cs @@ -5,12 +5,12 @@ namespace UiPath.Caching.Negotiation; -/// Everything one stack needs to advertise what it reads and, in , to decide what it writes; for an app with no serializer registered: then nothing is written, read or scheduled. +/// Everything one stack needs to advertise what it reads and, in , to decide what it writes. internal sealed class FormatNegotiation { public static FormatNegotiation Inactive { get; } = new(); - /// Null in : the node advertises, and writes exactly what its policies say. + /// Null in , when the node advertises without consulting the node list. public FormatNegotiator? Negotiator { get; init; } public NodeAdvertisement? Advertisement { get; init; } @@ -40,20 +40,31 @@ internal sealed class FormatNegotiation /// The node reads the node list off a transport it can see; otherwise only the operator's word can switch a format. public bool HasTransport => StreamKeys is not null || PubSub is not null; + private IFormatWriteGate? WriteGate { get; init; } + public static FormatNegotiation Create(IServiceProvider services) { var redisOptions = services.GetRequiredService>().Value; var options = redisOptions.FormatNegotiation; var registry = services.GetRequiredService(); var events = services.GetService(); - if (registry.IsEmpty && events is null) + if (registry.IsEmpty && events is null && !redisOptions.EntryMetadataEnabled) { return Inactive; } + var logger = services.GetRequiredService().CreateLogger(); + if (redisOptions.EntryMetadataEnabled && (options.Mode == FormatNegotiationMode.Force || options.AssumeAllNodesCanRead)) + { + logger.LogWarning( + "EntryMetadataEnabled with Force or AssumeAllNodesCanRead relies on every reader supporting entry frames. A 3.1.x reader on the same key space misses every frame with the default JSON proxy and can return the frame bytes as the value with RawByteSerializerProxy or a custom serializer."); + } + if (services.GetService() is not { } connector) { - return events?.WriteToken is { } token ? WithoutNodeList(services, options, token) : Inactive; + return events?.WriteToken is not null || redisOptions.EntryMetadataEnabled + ? WithoutNodeList(services, redisOptions, events?.WriteToken, logger) + : Inactive; } options.Validate(); @@ -70,27 +81,37 @@ public static FormatNegotiation Create(IServiceProvider services) : null; if (options.Mode == FormatNegotiationMode.Force && NegotiationPlan.ReadingNoJson(policies) is { Count: > 0 } readingNoJson) { - loggers.CreateLogger().LogWarning( + logger.LogWarning( "Serializer.Read of {Policies} leaves out json, and FormatNegotiation.Mode is Force. A node still in Auto writes JSON until every node reads its format, and this node reads those values as misses. Keep every node on the shared keys in Force, or add json to Read.", string.Join(", ", readingNoJson.Select(name => $"'{name}'"))); } DesiredEvents? desiredEvents = events?.WriteToken is { } writeToken ? new DesiredEvents([writeToken]) : null; + DesiredFrames? desiredFrames = redisOptions.EntryMetadataEnabled ? new DesiredFrames([NodeAdvertisement.Frame1]) : null; + var decides = options.Mode != FormatNegotiationMode.Force && + (!registry.IsEmpty || desiredEvents is not null || desiredFrames is not null); + var writeGate = decides || desiredFrames is not null ? services.GetService() : null; var library = typeof(FormatNegotiation).Assembly.GetCustomAttribute()?.InformationalVersion ?? string.Empty; return new() { - // A node with nothing to decide, in Force or with no serializer and no event format to write, only advertises. - Negotiator = options.Mode == FormatNegotiationMode.Force || (registry.IsEmpty && events?.WriteToken is null) - ? null - : new FormatNegotiator( + Negotiator = decides + ? new FormatNegotiator( NegotiationPlan.Desired(registry, policies), options, clock, services.GetRequiredService(), loggers.CreateLogger(), desiredEvents, - services.GetService()), - Advertisement = NegotiationPlan.Advertisement(registry, policies, new ValueReader(services.GetRequiredService>(), registry), library, eventTokens: events?.ReadTokens), + writeGate, + desiredFrames) + : null, + Advertisement = NegotiationPlan.Advertisement( + registry, + policies, + new ValueReader(services.GetRequiredService>(), registry), + library, + eventTokens: events?.ReadTokens, + entryMetadataEnabled: redisOptions.EntryMetadataEnabled), NodeId = (cacheOptions.SourceUri ?? CacheOptions.MachineUri).ToString().ToLowerInvariant(), Store = new NodeListStore(connector, NodeListStore.KeyFor(cacheOptions, redisOptions)), NodeList = new StreamNodeList(new RedisStreamGroupSource(connector), options), @@ -99,7 +120,8 @@ public static FormatNegotiation Create(IServiceProvider services) Subscribers = pubSub is null ? null : new PubSubNodeList(new RedisSubscriberSource(connector, clock, loggers.CreateLogger())), Options = options, Clock = clock, - Logger = loggers.CreateLogger(), + Logger = logger, + WriteGate = writeGate, }; } @@ -122,20 +144,43 @@ public IEventWrites EventWrites(EventFormatRegistry registry) return IsActive || Options.Mode == FormatNegotiationMode.Force ? FixedEventWrites.Always : FixedEventWrites.Never; } - // No Redis connection, so no node list and nothing to advertise to: the node writes JSON events until the operator attests, or forces them. - private static FormatNegotiation WithoutNodeList(IServiceProvider services, FormatNegotiationOptions options, string writeToken) + public IEntryFrameWrites FrameWrites(RedisCacheOptions options) + { + if (!options.EntryMetadataEnabled) + { + return GatedFrameWrites.Never; + } + + if (IsActive && Negotiator is { } negotiator) + { + return negotiator; + } + + var negotiation = options.FormatNegotiation; + var configured = negotiation.Mode == FormatNegotiationMode.Force || negotiation.AssumeAllNodesCanRead; + return new GatedFrameWrites(configured, WriteGate, Logger); + } + + private static FormatNegotiation WithoutNodeList( + IServiceProvider services, + RedisCacheOptions redisOptions, + string? writeToken, + ILogger logger) { + var options = redisOptions.FormatNegotiation; options.Validate(); var clock = services.GetRequiredService(); var loggers = services.GetRequiredService(); + var writeGate = redisOptions.EntryMetadataEnabled ? services.GetService() : null; return new() { - Negotiator = options.Mode == FormatNegotiationMode.Force + Negotiator = options.Mode == FormatNegotiationMode.Force || writeToken is null ? null : new FormatNegotiator([], options, clock, services.GetRequiredService(), loggers.CreateLogger(), new DesiredEvents([writeToken])), Options = options, Clock = clock, - Logger = loggers.CreateLogger(), + Logger = logger, + WriteGate = writeGate, }; } } diff --git a/src/UiPath.Caching/Negotiation/FormatNegotiator.cs b/src/UiPath.Caching/Negotiation/FormatNegotiator.cs index 5ac9e81ad..5e64d13fd 100644 --- a/src/UiPath.Caching/Negotiation/FormatNegotiator.cs +++ b/src/UiPath.Caching/Negotiation/FormatNegotiator.cs @@ -3,12 +3,12 @@ namespace UiPath.Caching.Negotiation; /// -/// Turns what the node list shows into which serializers, and whether the event format, are written now, whatever policy asks for them. A format +/// Turns what the node list shows into which serializers, events and frames are written now, whatever policy asks for them. A format /// is written only while every advertisement lists it and no live node is unaccounted for, and only after that has held for /// since the reading nodes last gained a member. The first node that cannot read it stops the /// writes at once; a node that leaves never does. /// -internal sealed class FormatNegotiator : IEffectiveFormat, IEventWrites +internal sealed class FormatNegotiator : IEffectiveFormat, IEventWrites, IEntryFrameWrites { public const string ReasonUnaccountedGroup = "unaccounted_group"; public const string ReasonMissingFormat = "missing_format"; @@ -24,6 +24,7 @@ internal sealed class FormatNegotiator : IEffectiveFormat, IEventWrites private readonly Slot[] _slots; private readonly int _eventSlot; + private readonly int _frameSlot; private readonly FormatNegotiationOptions _options; private readonly TimeProvider _clock; private readonly ICachingTelemetryProvider _telemetry; @@ -51,12 +52,19 @@ public FormatNegotiator( ICachingTelemetryProvider? telemetry = null, ILogger? logger = null, DesiredEvents? events = null, - IFormatWriteGate? writeGate = null) + IFormatWriteGate? writeGate = null, + DesiredFrames? frames = null) { options.Validate(); _writeGate = writeGate; - _slots = [.. desired.Select(d => new Slot(d.Writer, d.Tokens, d.Policies, d.Others)), .. events is null ? [] : new[] { new Slot(null, events.Tokens, [], []) }]; - _eventSlot = events is null ? -1 : _slots.Length - 1; + _slots = + [ + .. desired.Select(d => new Slot(d.Writer, d.Tokens, d.Policies, d.Others)), + .. events is null ? [] : new[] { new Slot(null, events.Tokens, [], []) }, + .. frames is null ? [] : new[] { new Slot(null, frames.Tokens, [], [], IsFrame: true) }, + ]; + _frameSlot = frames is null ? -1 : _slots.Length - 1; + _eventSlot = events is null ? -1 : _slots.Length - (frames is null ? 1 : 2); _options = options; _clock = clock; _telemetry = telemetry ?? NullTelemetryProvider.Instance; @@ -79,8 +87,20 @@ public bool Writes } } + public bool WritesFrames + { + get + { + var snapshot = _snapshot; + return _frameSlot >= 0 && snapshot.Writers[_frameSlot].Allowed && + _clock.GetElapsedTime(snapshot.Stamp) <= _options.MaxViewAge && GateOpen(_frameSlot, snapshot.Generation); + } + } + public bool Gated => _writeGate is not null; + bool IEntryFrameWrites.Allowed => WritesFrames; + public bool Allows(ICacheValueSerializer writer) { var snapshot = _snapshot; @@ -181,14 +201,14 @@ private static bool Unreadable(Slot want, NodeAdvertisement ad) return true; } - return ad.Strict.Any(entry => entry.Value.Contains(NodeAdvertisement.NoSniff) || (!want.Others.Contains(entry.Key) && !want.Tokens.All(entry.Value.Contains))); + return !want.IsFrame && ad.Strict.Any(entry => entry.Value.Contains(NodeAdvertisement.NoSniff) || (!want.Others.Contains(entry.Key) && !want.Tokens.All(entry.Value.Contains))); } - private static string? SubscriberReason(NodeListView view, bool attested) => - view.Subscribers is { } subscribers && !attested + private static string? SubscriberReason(NodeListView view, bool attested, bool frame) => + view.Subscribers is { } subscribers && (!attested || frame) ? subscribers switch { - { Known: false } => ReasonTransportUnknown, + { Known: false } => attested ? null : ReasonTransportUnknown, { Unaccounted: true } => ReasonUnaccountedSubscriber, { Short: true } => ReasonSubscriberDeficit, { Settled: false } => ReasonSettling, @@ -209,7 +229,7 @@ private bool GateOpen(int slot, long generation) return false; } - if (HoldOf(_writeGate) is null) + if (GatedFrameWrites.HoldOf(_writeGate, _logger) is null) { return true; } @@ -222,20 +242,6 @@ private bool GateOpen(int slot, long generation) return false; } - // A gate that throws is a closed gate. - private string? HoldOf(IFormatWriteGate gate) - { - try - { - return gate.Hold(); - } - catch (Exception ex) when (ex is not OutOfMemoryException) - { - _logger.LogWarning(ex, "The format write gate threw; treated as closed."); - return "gate_error"; - } - } - private string? Block(Slot want, NodeListView view) { // What an advertisement says it cannot read comes first: no grace after an outage and no attestation excuses it. @@ -245,7 +251,7 @@ private bool GateOpen(int slot, long generation) } // An outside condition on the format, asked on every view and again on every write, so a gate that closes stops writes at once and one that opens still waits out the hold. - if (!want.IsEvent && _writeGate is not null && HoldOf(_writeGate) is not null) + if (!want.IsEvent && _writeGate is not null && GatedFrameWrites.HoldOf(_writeGate, _logger) is not null) { return ReasonGated; } @@ -263,13 +269,13 @@ private bool GateOpen(int slot, long generation) return ReasonNoView; } - // The attestation covers nodes that say nothing; a node that advertises without the format is not one of them. - if (view.Blockers.Count > 0 && !attested) + // The attestation covers silent nodes for the serializer and event slots. + if (view.Blockers.Count > 0 && (!attested || want.IsFrame)) { return ReasonUnaccountedGroup; } - return SubscriberReason(view, attested); + return SubscriberReason(view, attested, want.IsFrame); } private bool Decide(int i, bool wasAllowed, bool joined, bool grace, long now) @@ -341,17 +347,24 @@ private void Transition(WriterState[] previous, bool[] allowed) for (var i = 0; i < allowed.Length; i++) { var slot = _slots[i]; - var kind = slot.IsEvent ? "event" : "value"; + var kind = slot.Kind; var format = string.Join('+', slot.Tokens); if (previous[i].Allowed && !allowed[i]) { _telemetry.TrackMetric( Metrics.FormatFallback, 1, - slot.IsEvent + slot.Writer is null ? [new("reason", _reasons[i] ?? ReasonNoView), new("kind", kind)] : [new("reason", _reasons[i] ?? ReasonNoView), new("kind", kind), new("policy", string.Join(',', slot.Policies))]); - _logger.LogWarning("The {Kind} format {Format} falls back to JSON: {Reason}.", kind, format, _reasons[i]); + if (slot.IsFrame) + { + _logger.LogWarning("Entry frame writes stopped: {Reason}.", _reasons[i]); + } + else + { + _logger.LogWarning("The {Kind} format {Format} falls back to JSON: {Reason}.", kind, format, _reasons[i]); + } } else if (!previous[i].Allowed && allowed[i]) { @@ -375,9 +388,9 @@ private void Report(NodeListView view) _telemetry.TrackMetric( Metrics.FormatEffective, current[i].Allowed ? 1 : 0, - slot.IsEvent - ? [new("kind", "event"), format] - : [new("kind", "value"), new("policy", string.Join(',', slot.Policies)), format]); + slot.Writer is null + ? [new("kind", slot.Kind), format] + : [new("kind", slot.Kind), new("policy", string.Join(',', slot.Policies)), format]); } } @@ -447,10 +460,16 @@ private Snapshot Publish(bool[] allowed, long stamp) return new(writers, stamp, ++_generation); } - /// A serializer, or the event format when is , with what a node must read to be sent it. - private sealed record Slot(ICacheValueSerializer? Writer, IReadOnlyList Tokens, IReadOnlyCollection Policies, IReadOnlyCollection Others) + private sealed record Slot( + ICacheValueSerializer? Writer, + IReadOnlyList Tokens, + IReadOnlyCollection Policies, + IReadOnlyCollection Others, + bool IsFrame = false) { - public bool IsEvent => Writer is null; + public bool IsEvent => Writer is null && !IsFrame; + + public string Kind => IsFrame ? "frame" : IsEvent ? "event" : "value"; } private sealed record WriterState(ICacheValueSerializer? Writer, bool Allowed); diff --git a/src/UiPath.Caching/Negotiation/GatedFrameWrites.cs b/src/UiPath.Caching/Negotiation/GatedFrameWrites.cs new file mode 100644 index 000000000..840cf1c91 --- /dev/null +++ b/src/UiPath.Caching/Negotiation/GatedFrameWrites.cs @@ -0,0 +1,21 @@ +namespace UiPath.Caching.Negotiation; + +internal sealed class GatedFrameWrites(bool configured, IFormatWriteGate? gate, ILogger logger) : IEntryFrameWrites +{ + public static GatedFrameWrites Never { get; } = new(false, null, NullLogger.Instance); + + public bool Allowed => configured && (gate is null || HoldOf(gate, logger) is null); + + internal static string? HoldOf(IFormatWriteGate gate, ILogger logger) + { + try + { + return gate.Hold(); + } + catch (Exception ex) when (ex is not OutOfMemoryException) + { + logger.LogWarning(ex, "The format write gate threw; treated as closed."); + return "gate_error"; + } + } +} diff --git a/src/UiPath.Caching/Negotiation/IEntryFrameWrites.cs b/src/UiPath.Caching/Negotiation/IEntryFrameWrites.cs new file mode 100644 index 000000000..c17c0e490 --- /dev/null +++ b/src/UiPath.Caching/Negotiation/IEntryFrameWrites.cs @@ -0,0 +1,7 @@ +namespace UiPath.Caching.Negotiation; + +/// Whether this node can write an entry frame now. +internal interface IEntryFrameWrites +{ + bool Allowed { get; } +} diff --git a/src/UiPath.Caching/Negotiation/NegotiationPlan.cs b/src/UiPath.Caching/Negotiation/NegotiationPlan.cs index 52a2249e3..bc1e9da75 100644 --- a/src/UiPath.Caching/Negotiation/NegotiationPlan.cs +++ b/src/UiPath.Caching/Negotiation/NegotiationPlan.cs @@ -25,7 +25,14 @@ [.. named.Where(p => ReferenceEquals(p.Policy.WriteSerializer, writer)).Select(p } /// The tokens of the registered event formats; a node without any still lists the JSON events it reads. - public static NodeAdvertisement Advertisement(ValueSerializerRegistry registry, ICachePolicyFactory policies, ValueReader reader, string library, IReadOnlyList? eventTokens = null) + /// Whether this node advertises frame support. + public static NodeAdvertisement Advertisement( + ValueSerializerRegistry registry, + ICachePolicyFactory policies, + ValueReader reader, + string library, + IReadOnlyList? eventTokens = null, + bool entryMetadataEnabled = false) { var reads = new List { NodeAdvertisement.Json }; foreach (var (_, serializer, _) in registry.Entries) @@ -33,6 +40,11 @@ public static NodeAdvertisement Advertisement(ValueSerializerRegistry registry, reads.AddRange(registry.FormatIdsOf(serializer).ToArray().Select(NodeAdvertisement.Token)); } + if (entryMetadataEnabled) + { + reads.Add(NodeAdvertisement.Frame1); + } + var strict = new Dictionary>(StringComparer.Ordinal); foreach (var (name, policy) in Policies(policies)) { diff --git a/src/UiPath.Caching/Negotiation/NodeAdvertisement.cs b/src/UiPath.Caching/Negotiation/NodeAdvertisement.cs index 48a4a1bb5..c9ceead39 100644 --- a/src/UiPath.Caching/Negotiation/NodeAdvertisement.cs +++ b/src/UiPath.Caching/Negotiation/NodeAdvertisement.cs @@ -20,6 +20,8 @@ internal sealed record NodeAdvertisement( { public const string Json = "json"; + public const string Frame1 = "frame1"; + /// Marks a read list of a policy whose reads do not look for a header: it reads JSON only, whatever it lists. public const string NoSniff = "nosniff"; diff --git a/src/UiPath.Caching/PublicAPI.Unshipped.txt b/src/UiPath.Caching/PublicAPI.Unshipped.txt index 2df324984..67e58ae01 100644 --- a/src/UiPath.Caching/PublicAPI.Unshipped.txt +++ b/src/UiPath.Caching/PublicAPI.Unshipped.txt @@ -23,6 +23,8 @@ UiPath.Caching.Redis.FormatNegotiationOptions.ViewInterval.get -> System.TimeSpa UiPath.Caching.Redis.FormatNegotiationOptions.ViewInterval.set -> void UiPath.Caching.Redis.IFormatWriteGate UiPath.Caching.Redis.IFormatWriteGate.Hold() -> string? +UiPath.Caching.Redis.RedisCacheOptions.EntryMetadataEnabled.get -> bool +UiPath.Caching.Redis.RedisCacheOptions.EntryMetadataEnabled.set -> void UiPath.Caching.Redis.RedisCacheOptions.FormatNegotiation.get -> UiPath.Caching.Redis.FormatNegotiationOptions! UiPath.Caching.Redis.RedisCacheOptions.FormatNegotiation.set -> void const UiPath.Caching.Metrics.FormatBlockers = "Caching.Stats.FormatBlockers" -> string! diff --git a/src/UiPath.Caching/Redis/FormatRewriteScripts.cs b/src/UiPath.Caching/Redis/FormatRewriteScripts.cs index d446dc367..c748a90ec 100644 --- a/src/UiPath.Caching/Redis/FormatRewriteScripts.cs +++ b/src/UiPath.Caching/Redis/FormatRewriteScripts.cs @@ -53,10 +53,20 @@ public static async Task RewriteStringAsync( } /// Replaces the value only if the key still holds ; null with nothing sent once the lifetime is not positive. - public static async Task ReplaceStringAsync( - IDatabase db, RedisKey key, RedisValue expected, RedisValue value, Func remaining, bool useScripts = true, Action? scriptRefused = null) + public static Task ReplaceStringAsync( + IDatabase db, RedisKey key, RedisValue expected, RedisValue value, Func remaining, bool useScripts = true, Action? scriptRefused = null) => + ReplaceStringAsync(db, key, expected, (Value: value, Remaining: remaining), static s => (s.Value, s.Remaining()), useScripts, scriptRefused); + + /// As the fixed-value overload, with the bytes and the life asked of before the script and again before the transaction. + public static Task ReplaceStringAsync( + IDatabase db, RedisKey key, RedisValue expected, Func<(RedisValue Value, TimeSpan Remaining)> form, bool useScripts = true, Action? scriptRefused = null) => + ReplaceStringAsync(db, key, expected, form, static f => f(), useScripts, scriptRefused); + + /// As the function overload, with the state handed to so a caller needs no closure. + public static async Task ReplaceStringAsync( + IDatabase db, RedisKey key, RedisValue expected, TState state, Func form, bool useScripts = true, Action? scriptRefused = null) { - var expiration = remaining(); + var (value, expiration) = form(state); if (expiration <= TimeSpan.Zero) { return null; @@ -80,8 +90,8 @@ public static async Task RewriteStringAsync( } } - // A refused script cost a round trip, so the lifetime is worked out again. - expiration = remaining(); + // A refused script cost a round trip, so the form and the lifetime are worked out again. + (value, expiration) = form(state); if (expiration <= TimeSpan.Zero) { return null; diff --git a/src/UiPath.Caching/Redis/FrameScripts.Keys.cs b/src/UiPath.Caching/Redis/FrameScripts.Keys.cs new file mode 100644 index 000000000..fd47d5b89 --- /dev/null +++ b/src/UiPath.Caching/Redis/FrameScripts.Keys.cs @@ -0,0 +1,40 @@ +namespace UiPath.Caching.Redis; + +internal static partial class FrameScripts +{ + /// + /// The read of the key commands, in one step and without a write. KEYS[1] is the key. It answers the class of the value + /// (0 no key, 1 any value that is no frame with a window, 2 a frame with a window by the whole grammar, 3 a tombstone), the first 15 bytes of a frame of class 2 + /// (its frame expiration and window) and the PTTL. A key of another type is class 1. + /// + internal const string KeyRead = """ + local t = redis.call('PTTL', KEYS[1]) + if t == -2 then return {0, '', t} end + local ok, h = pcall(redis.call, 'GETRANGE', KEYS[1], 0, 14) + if not ok then return {1, '', t} end + local a, b, f = string.byte(h, 1, 3) + if a == 15 and b and b >= 48 and b <= 57 then return {3, '', t} end + if a ~= 14 or b ~= 1 or not f or f > 7 or bit.band(f, 1) == 0 or #h < 15 then return {1, '', t} end + local w = string.byte(h, 12) + 256 * string.byte(h, 13) + 65536 * string.byte(h, 14) + 16777216 * string.byte(h, 15) + if w == 0 then return {1, '', t} end + local n = redis.call('STRLEN', KEYS[1]) + local o = 15 + if bit.band(f, 2) ~= 0 then + if n - o < 8 then return {1, '', t} end + o = o + 8 + end + if bit.band(f, 4) ~= 0 then + if n - o < 2 then return {1, '', t} end + local l1, l2 = string.byte(redis.call('GETRANGE', KEYS[1], o, o + 1), 1, 2) + local l = l1 + 256 * l2 + o = o + 2 + if l == 0 or l > 1024 or l > n - o then return {1, '', t} end + o = o + l + end + if n > o then + local c = string.byte(redis.call('GETRANGE', KEYS[1], o, o)) + if c == 14 or c == 15 then return {1, '', t} end + end + return {2, h, t} + """; +} diff --git a/src/UiPath.Caching/Redis/FrameScripts.cs b/src/UiPath.Caching/Redis/FrameScripts.cs new file mode 100644 index 000000000..e7fc4fcc5 --- /dev/null +++ b/src/UiPath.Caching/Redis/FrameScripts.cs @@ -0,0 +1,78 @@ +namespace UiPath.Caching.Redis; + +/// The server-side scripts of a node that reads entry frames. The refresh runs for every key such a node refreshes, because only the server knows what the key holds when the command lands. +internal static partial class FrameScripts +{ + /// The SET option that gives the unwrapped value the requested instant; a server before 6.2 does not know it. + internal const string UnwrapOption = "PXAT"; + + /// The mark in ARGV[1] that asks for no expiration. + internal const string Never = "-1"; + + internal const string RefreshTemplate = """ + local at = ARGV[1] + local function today() + if at == '-1' then return redis.call('PERSIST', KEYS[1]) end + return redis.call('PEXPIREAT', KEYS[1], at) + end + local function says(e, word) + if type(e) == 'table' then e = e.err end + return string.find(tostring(e), word, 1, true) ~= nil + end + local ok, h = pcall(redis.call, 'GETRANGE', KEYS[1], 0, 1) + if not ok then + if says(h, 'WRONGTYPE') then return today() end + error(h) + end + local a, b = string.byte(h, 1, 2) + if a == 15 and b and b >= 48 and b <= 57 then return 0 end + if a ~= 14 or b ~= 1 then return today() end + local v = redis.call('GET', KEYS[1]) + local n = #v + if n < 3 then return today() end + local f = string.byte(v, 3) + if f == 0 or f > 7 then return today() end + local windowed = f % 2 == 1 + local o = 4 + if windowed then + if n < 15 then return today() end + if string.byte(v, 12) + string.byte(v, 13) + string.byte(v, 14) + string.byte(v, 15) == 0 then return today() end + o = 16 + end + if f % 4 >= 2 then + if n - o + 1 < 8 then return today() end + o = o + 8 + end + if f >= 4 then + if n - o + 1 < 2 then return today() end + local len = string.byte(v, o) + string.byte(v, o + 1) * 256 + o = o + 2 + if len == 0 or len > 1024 or len > n - o + 1 then return today() end + o = o + len + end + local c = string.byte(v, o) + if c == 14 or c == 15 then return today() end + if windowed then return 0 end + if ARGV[2] == '1' then return today() end + local set + if at == '-1' then + set = { pcall(redis.call, 'SET', KEYS[1], string.sub(v, o)) } + else + set = { pcall(redis.call, 'SET', KEYS[1], string.sub(v, o), '@OPTION@', at) } + end + if set[1] then return 1 end + if says(set[2], 'syntax') then return 0 end + error(set[2]) + """; + + /// The refresh script, for a server that knows . + internal static readonly string Refresh = BuildRefresh(UnwrapOption); + + /// + /// The refresh script with as the SET option of the unwrap, so a test can give it a word that no server knows. + /// ARGV[1] is the requested expiration in Unix milliseconds, or ; ARGV[2] is 1 while the frame gate is open. + /// Every path ends in one command that writes, or in none, and nothing runs after it. + /// + internal static string BuildRefresh(string setOption) => + RefreshTemplate.Replace("@OPTION@", setOption, StringComparison.Ordinal); +} diff --git a/src/UiPath.Caching/Redis/RedisCache.Anchored.cs b/src/UiPath.Caching/Redis/RedisCache.Anchored.cs new file mode 100644 index 000000000..09c6979e4 --- /dev/null +++ b/src/UiPath.Caching/Redis/RedisCache.Anchored.cs @@ -0,0 +1,39 @@ +namespace UiPath.Caching.Redis; + +/// The anchored writes of : a layered cache hands the instant and the anchor it took at its origin, and none of these takes another (WA4, WA6). +internal sealed partial class RedisCache : IAnchoredTier +{ + bool IAnchoredTier.TakesAnchor => EntryMetadataEnabled; + + ValueTask IAnchoredTier.SetAsync(CacheKey cacheKey, T? value, DateTimeOffset expiration, WriteAnchor anchor, CachePolicy? policy, CancellationToken token) + where T : default => + SetCoreAsync(cacheKey, value, CallerDuration(expiration), policy, token, expiration, anchor); + + ValueTask IAnchoredTier.SetAsync(KeyValuePair[] keyValues, DateTimeOffset expiration, WriteAnchor anchor, CachePolicy? policy, CancellationToken token) + where T : default => + SetCoreAsync(keyValues, CallerDuration(expiration), policy, token, expiration, anchor); + + ValueTask IAnchoredTier.TryAddAsync(CacheKey cacheKey, T? value, DateTimeOffset expiration, WriteAnchor anchor, CachePolicy? policy, CancellationToken token) + where T : default => + TryAddCoreAsync(cacheKey, value, CallerDuration(expiration), policy, token, expiration, anchor); + + ValueTask> IAnchoredTier.TryFillAsync(CacheKey cacheKey, T? value, DateTimeOffset expiration, WriteAnchor anchor, CachePolicy? policy, CancellationToken token) + where T : default => + TryFillCoreAsync(cacheKey, value, GetExpiration(expiration), policy, default, token, anchor); + + ValueTask> IAnchoredTier.TryFillAfterAsync(CacheKey cacheKey, T? value, DateTimeOffset expiration, WriteAnchor anchor, TimeSpan generatorElapsed, CachePolicy? policy, CancellationToken token) + where T : default => + TryFillCoreAsync(cacheKey, value, GetExpiration(expiration), policy, NewFence(generatorElapsed), token, anchor); + + ValueTask[]> IAnchoredTier.TryFillManyAsync(KeyValuePair[] entries, DateTimeOffset expiration, WriteAnchor anchor, CachePolicy? policy, CancellationToken token, TimeSpan? generatorElapsed) + where T : default => + TryFillManyCoreAsync(entries, expiration, policy, token, generatorElapsed, anchor); + + ValueTask> IAnchoredTier.SetIfChangedAsync(CacheKey cacheKey, T? value, IEqualityComparer comparer, DateTimeOffset expiration, WriteAnchor anchor, CachePolicy? policy, CancellationToken token) + where T : default => + SetIfChangedCoreAsync(cacheKey, value, comparer, GetExpiration(expiration), policy, token, anchor); + + ValueTask IAnchoredTier.WriteIfStampAsync(CacheKey cacheKey, T? value, DateTimeOffset expiration, WriteAnchor anchor, CachePolicy? policy, object? stamp, CancellationToken token) + where T : default => + WriteIfStampAsync(cacheKey, value, expiration, policy, stamp, token, anchor); +} diff --git a/src/UiPath.Caching/Redis/RedisCache.ByteCodec.cs b/src/UiPath.Caching/Redis/RedisCache.ByteCodec.cs index 91eddacfb..2eccfd20b 100644 --- a/src/UiPath.Caching/Redis/RedisCache.ByteCodec.cs +++ b/src/UiPath.Caching/Redis/RedisCache.ByteCodec.cs @@ -12,7 +12,7 @@ public byte[] Encode(T value, CachePolicy? policy) ArgumentNullException.ThrowIfNull(value); NotCacheableException.ThrowIfNotCacheable(); - // The same format choice as WriteAsync, and the same SerializeValue behind it. + // The same format choice as WriteAsync, and the same SerializeValue behind it. No frame: the seam's bytes are a value, not a stored entry (Task 2.4). var format = FormatFor(policy, forWrite: true); return format.IsDefault ? Stored(value, default(PlainFormat)) : Stored(value, format); } diff --git a/src/UiPath.Caching/Redis/RedisCache.Fill.cs b/src/UiPath.Caching/Redis/RedisCache.Fill.cs index 94536bde5..58ca883d7 100644 --- a/src/UiPath.Caching/Redis/RedisCache.Fill.cs +++ b/src/UiPath.Caching/Redis/RedisCache.Fill.cs @@ -21,22 +21,33 @@ private enum ChangeStep } public ValueTask> TryFillAsync(CacheKey cacheKey, T? value, TimeSpan expiration, CachePolicy? policy, CancellationToken token = default) => - TryFillCoreAsync(cacheKey, value, GetExpiration(expiration), policy, default, token); + EntryMetadataEnabled + ? TryFillCoreAsync(cacheKey, value, ExpirationAnchored(expiration, out var anchor), policy, default, token, anchor) + : TryFillCoreAsync(cacheKey, value, GetExpiration(expiration), policy, default, token); public ValueTask> TryFillAsync(CacheKey cacheKey, T? value, DateTimeOffset expiration, CachePolicy? policy, CancellationToken token = default) => - TryFillCoreAsync(cacheKey, value, GetExpiration(expiration), policy, default, token); + EntryMetadataEnabled + ? TryFillCoreAsync(cacheKey, value, ExpirationAnchored(expiration, out var anchor), policy, default, token, anchor) + : TryFillCoreAsync(cacheKey, value, GetExpiration(expiration), policy, default, token); public ValueTask> TryFillAfterAsync(CacheKey cacheKey, T? value, DateTimeOffset expiration, TimeSpan generatorElapsed, CachePolicy? policy, CancellationToken token) => - TryFillCoreAsync(cacheKey, value, GetExpiration(expiration), policy, NewFence(generatorElapsed), token); + EntryMetadataEnabled + ? TryFillCoreAsync(cacheKey, value, ExpirationAnchored(expiration, out var anchor), policy, NewFence(generatorElapsed), token, anchor) + : TryFillCoreAsync(cacheKey, value, GetExpiration(expiration), policy, NewFence(generatorElapsed), token); public ValueTask> SetIfChangedAsync(CacheKey cacheKey, T? value, IEqualityComparer comparer, TimeSpan expiration, CachePolicy? policy, CancellationToken token = default) => - SetIfChangedCoreAsync(cacheKey, value, comparer, GetExpiration(expiration), policy, token); + EntryMetadataEnabled + ? SetIfChangedCoreAsync(cacheKey, value, comparer, ExpirationAnchored(expiration, out var anchor), policy, token, anchor) + : SetIfChangedCoreAsync(cacheKey, value, comparer, GetExpiration(expiration), policy, token); public ValueTask> SetIfChangedAsync(CacheKey cacheKey, T? value, IEqualityComparer comparer, DateTimeOffset expiration, CachePolicy? policy, CancellationToken token = default) => - SetIfChangedCoreAsync(cacheKey, value, comparer, GetExpiration(expiration), policy, token); + EntryMetadataEnabled + ? SetIfChangedCoreAsync(cacheKey, value, comparer, ExpirationAnchored(expiration, out var anchor), policy, token, anchor) + : SetIfChangedCoreAsync(cacheKey, value, comparer, GetExpiration(expiration), policy, token); /// The attempts after a plain NX lost: one read of the winner, then whole attempts if it was gone again. - private static async ValueTask FillAfterAsync(RedisCache self, RedisKey key, RedisValue serialized, DateTimeOffset until, bool lost, FillFence fence, CancellationToken token) + private static async ValueTask FillAfterAsync(RedisCache self, RedisKey key, RedisValue serialized, TDeadline until, bool lost, FillFence fence, CancellationToken token) + where TDeadline : struct, IFillDeadline { var read = lost; for (var attempt = 0; attempt < FillAttempts; attempt++) @@ -45,7 +56,7 @@ public ValueTask> SetIfChangedAsync(CacheKey cacheKey, T? val FillRaw? filled; if (read) { - filled = self.RemainingOrZero(until) <= TimeSpan.Zero ? FillRaw.Lapsed : await ReadWinnerAsync(self, key, fence).ConfigureAwait(false); + filled = until.Left(self) <= TimeSpan.Zero ? FillRaw.Lapsed : await ReadWinnerAsync(self, key, fence).ConfigureAwait(false); } else { @@ -53,9 +64,9 @@ public ValueTask> SetIfChangedAsync(CacheKey cacheKey, T? val } read = false; - if (filled is { IsTombstone: true } held) + if (filled is { } held && (held.IsTombstone || held.IsExpiredFrame)) { - filled = await SettleTombstoneAsync(self, key, held, serialized, until).ConfigureAwait(false); + filled = await (held.IsTombstone ? SettleTombstoneAsync(self, key, held, serialized, until) : SettleExpiredFrameAsync(self, key, held, serialized, until)).ConfigureAwait(false); } if (filled is { } done) @@ -81,7 +92,7 @@ public ValueTask> SetIfChangedAsync(CacheKey cacheKey, T? val return null; } - return new FillRaw(false, value, self.Clock.ToDateTimeOffset(deadline)); + return Winner(self, value, self.Clock.ToDateTimeOffset(deadline)); } private static async ValueTask ReadFencedWinnerAsync(RedisCache self, RedisKey key, FillFence fence) @@ -92,7 +103,7 @@ public ValueTask> SetIfChangedAsync(CacheKey cacheKey, T? val return null; } - return TombstoneValue.TryRead(value, out var grace) ? JudgeTombstone(self, value, grace, left, fence) : new FillRaw(false, value, self.Clock.ToDateTimeOffset(left)); + return TombstoneValue.TryRead(value, out var grace) ? JudgeTombstone(self, value, grace, left, fence) : Winner(self, value, self.Clock.ToDateTimeOffset(left)); } /// The fill's verdict on the tombstone it met, as a marker for . @@ -108,7 +119,8 @@ private static FillRaw JudgeTombstone(RedisCache self, RedisValue tombstone, lon } /// Null when the tombstone changed since it was read, for another attempt. - private static async ValueTask SettleTombstoneAsync(RedisCache self, RedisKey key, FillRaw held, RedisValue serialized, DateTimeOffset until) + private static async ValueTask SettleTombstoneAsync(RedisCache self, RedisKey key, FillRaw held, RedisValue serialized, TDeadline until) + where TDeadline : struct, IFillDeadline { if (held.IsRemoved) { @@ -121,12 +133,23 @@ private static FillRaw JudgeTombstone(RedisCache self, RedisValue tombstone, lon return FillRaw.Removed; } + return await ReplaceHeldAsync(self, key, held, serialized, until).ConfigureAwait(false); + } + + /// The expired frame a winner read found is absent: the fill replaces exactly its bytes by compare-and-set, on the deadline and the anchor of the fill (K5, WA3, WS4). Null when the key changed since it was read, for another attempt. + private static ValueTask SettleExpiredFrameAsync(RedisCache self, RedisKey key, FillRaw held, RedisValue serialized, TDeadline until) + where TDeadline : struct, IFillDeadline => + ReplaceHeldAsync(self, key, held, serialized, until); + + private static async ValueTask ReplaceHeldAsync(RedisCache self, RedisKey key, FillRaw held, RedisValue serialized, TDeadline until) + where TDeadline : struct, IFillDeadline + { if (self.BeforeTombstoneSwap is { } hook) { await hook().ConfigureAwait(false); } - var replaced = await FormatRewriteScripts.ReplaceStringAsync(self.Database, key, held.Value, serialized, () => self.RemainingOrZero(until), self.RewriteScriptsOn, self._rewriteScriptRefused).ConfigureAwait(false); + var replaced = await self.ReplaceUntilAsync(key, held.Value, serialized, until).ConfigureAwait(false); return replaced switch { true => new FillRaw(true, RedisValue.Null, DateTimeOffset.MaxValue), @@ -135,10 +158,18 @@ private static FillRaw JudgeTombstone(RedisCache self, RedisValue tombstone, lon }; } - private static async ValueTask FillOnceAsync(RedisCache self, RedisKey key, RedisValue serialized, DateTimeOffset until, FillFence fence) + /// A winner a late read found, judged after a tombstone: an expired frame is marked for , on every node whatever EntryMetadataEnabled says (K5). + private static FillRaw Winner(RedisCache self, RedisValue stored, DateTimeOffset expiration) => + new(false, stored, expiration, IsExpiredFrame: IsExpiredFrame(self, stored, expiration)); + + /// Whether a late read saw an expired frame: a late deadline is never too early, so it may end a frame and never keeps one. + private static bool IsExpiredFrame(RedisCache self, in RedisValue stored, DateTimeOffset expiration) => + TryReadFrame(stored, out var entry) && !self.JudgeFrame(entry, KeyLife.Late(expiration), out var frame) && frame.Expired; + + private static async ValueTask FillOnceAsync(RedisCache self, RedisKey key, RedisValue serialized, TDeadline until, FillFence fence) + where TDeadline : struct, IFillDeadline { - var expiration = self.RemainingOrZero(until); - if (expiration <= TimeSpan.Zero) + if (until.Send(self, serialized) is not { } send) { return FillRaw.Lapsed; } @@ -147,8 +178,8 @@ private static FillRaw JudgeTombstone(RedisCache self, RedisValue tombstone, lon { try { - var milliseconds = expiration == TimeSpan.MaxValue ? 0 : Math.Max(1, (long)Math.Ceiling(expiration.TotalMilliseconds)); - var reply = await self.Database.ScriptEvaluateAsync(FillScript, [key], [serialized, milliseconds], CommandFlags.DemandMaster).ConfigureAwait(false); + var milliseconds = send.Ttl == TimeSpan.MaxValue ? 0 : Math.Max(1, (long)Math.Ceiling(send.Ttl.TotalMilliseconds)); + var reply = await self.Database.ScriptEvaluateAsync(FillScript, [key], [send.Bytes, milliseconds], CommandFlags.DemandMaster).ConfigureAwait(false); if (reply.IsNull) { return new FillRaw(true, RedisValue.Null, DateTimeOffset.MaxValue); @@ -160,7 +191,7 @@ private static FillRaw JudgeTombstone(RedisCache self, RedisValue tombstone, lon TimeSpan? left = ttl < 0 ? null : TimeSpan.FromMilliseconds(ttl); return self._tombstoneGrace is not null && TombstoneValue.TryRead(stored, out var grace) ? JudgeTombstone(self, stored, grace, left, fence) - : new FillRaw(false, stored, self.Clock.ToDateTimeOffset(left)); + : Winner(self, stored, self.Clock.ToDateTimeOffset(left)); } catch (Exception ex) when (RedisUtils.RefusesScript(ex)) { @@ -169,14 +200,13 @@ private static FillRaw JudgeTombstone(RedisCache self, RedisValue tombstone, lon } // A refused script cost a round trip, so the lifetime is worked out again. - expiration = self.RemainingOrZero(until); - if (expiration <= TimeSpan.Zero) + if (until.Send(self, serialized) is not { } again) { return FillRaw.Lapsed; } // SET NX is atomic by itself; the read after a lost NX is a snapshot. - if (await self.Database.StringSetAsync(key, serialized, expiration, When.NotExists, CommandFlags.DemandMaster).ConfigureAwait(false)) + if (await self.Database.StringSetAsync(key, again.Bytes, again.Ttl, When.NotExists, CommandFlags.DemandMaster).ConfigureAwait(false)) { return new FillRaw(true, RedisValue.Null, DateTimeOffset.MaxValue); } @@ -186,30 +216,56 @@ private static FillRaw JudgeTombstone(RedisCache self, RedisValue tombstone, lon private FillFence NewFence(TimeSpan generatorElapsed) => _tombstoneGrace is null ? default : new FillFence(generatorElapsed, Clock.GetTimestamp(), true); - private ValueTask> TryFillCoreAsync(CacheKey cacheKey, T? value, DateTimeOffset deadline, CachePolicy? policy, FillFence fence, CancellationToken token) + private ValueTask> TryFillCoreAsync(CacheKey cacheKey, T? value, DateTimeOffset deadline, CachePolicy? policy, FillFence fence, CancellationToken token, WriteAnchor anchor = default) { NotCacheableException.ThrowIfNotCacheable(); var redisKey = ToRedisKey(cacheKey, token); var format = FormatFor(policy, forWrite: true, alsoReads: true); + var frame = FrameFor(policy); + if (!frame.IsNone) + { + frame = frame with { Anchor = anchor }; + return format.IsDefault + ? TryFillInternalAsync(cacheKey, redisKey, value, deadline, new FramedFormat(default, frame), fence, token) + : TryFillInternalAsync(cacheKey, redisKey, value, deadline, new FramedFormat(format, frame), fence, token); + } + return format.IsDefault ? TryFillInternalAsync(cacheKey, redisKey, value, deadline, default(PlainFormat), fence, token) : TryFillInternalAsync(cacheKey, redisKey, value, deadline, format, fence, token); } - private ValueTask> SetIfChangedCoreAsync(CacheKey cacheKey, T? value, IEqualityComparer comparer, DateTimeOffset deadline, CachePolicy? policy, CancellationToken token) + private ValueTask> SetIfChangedCoreAsync(CacheKey cacheKey, T? value, IEqualityComparer comparer, DateTimeOffset deadline, CachePolicy? policy, CancellationToken token, WriteAnchor anchor = default) { NotCacheableException.ThrowIfNotCacheable(); ArgumentNullException.ThrowIfNull(comparer); var redisKey = ToRedisKey(cacheKey, token); var format = FormatFor(policy, forWrite: true, alsoReads: true); + var frame = FrameFor(policy); + if (!frame.IsNone) + { + frame = frame with { Anchor = anchor }; + return format.IsDefault + ? SetIfChangedInternalAsync(cacheKey, redisKey, value, comparer, deadline, new FramedFormat(default, frame), token) + : SetIfChangedInternalAsync(cacheKey, redisKey, value, comparer, deadline, new FramedFormat(format, frame), token); + } + return format.IsDefault ? SetIfChangedInternalAsync(cacheKey, redisKey, value, comparer, deadline, default(PlainFormat), token) : SetIfChangedInternalAsync(cacheKey, redisKey, value, comparer, deadline, format, token); } + /// The fill of one key; the framed branch carries the anchor of its format with the deadline. + private ValueTask> TryFillInternalAsync(CacheKey cacheKey, RedisKey redisKey, T? value, DateTimeOffset deadline, TFormat format, FillFence fence, CancellationToken token) + where TFormat : struct, IValueFormat => + NeverFramed() + ? FillInternalAsync(cacheKey, redisKey, value, new PlainSend(deadline), format, fence, token) + : FillInternalAsync(cacheKey, redisKey, value, new AnchoredSend(deadline, format.Frame.Anchor), format, fence, token); + [AsyncMethodBuilder(typeof(Pooled<>))] - private async ValueTask> TryFillInternalAsync(CacheKey cacheKey, RedisKey redisKey, T? value, DateTimeOffset deadline, TFormat format, FillFence fence, CancellationToken token) + private async ValueTask> FillInternalAsync(CacheKey cacheKey, RedisKey redisKey, T? value, TDeadline deadline, TFormat format, FillFence fence, CancellationToken token) where TFormat : struct, IValueFormat + where TDeadline : struct, IFillDeadline { token.ThrowIfCancellationRequested(); @@ -232,6 +288,11 @@ private async ValueTask> TryFillInternalAsync(CacheKey NoteWritten(redisKey); var (serialized, payload) = isNull ? (RedisValue.EmptyString, default(SerializedPayload)) : SerializeValue(value, format); _auditKeySize?.Invoke(Logged(cacheKey, redisKey, typeof(T)), serialized); + if (!NeverFramed()) + { + serialized = FramedUntil(serialized, deadline.At, format.Frame).Stored; + } + using (payload) { // Scripts off: one plain NX, which a win answers as a write does. Null is a command the pipeline gave up on, which is not a loss. @@ -241,8 +302,7 @@ private async ValueTask> TryFillInternalAsync(CacheKey [AsyncMethodBuilder(typeof(Pooled<>))] static async ValueTask (s, token) => { token.ThrowIfCancellationRequested(); - var remaining = s.Self.RemainingOrZero(s.Deadline); - return remaining > TimeSpan.Zero && await s.Self.Database.StringSetAsync(s.Key, s.Serialized, remaining, When.NotExists, CommandFlags.DemandMaster).ConfigureAwait(false); + return s.Deadline.Send(s.Self, s.Serialized) is { } send && await s.Self.Database.StringSetAsync(s.Key, send.Bytes, send.Ttl, When.NotExists, CommandFlags.DemandMaster).ConfigureAwait(false); }, (Self: this, Key: redisKey, Serialized: serialized, Deadline: deadline), null, @@ -251,11 +311,11 @@ private async ValueTask> TryFillInternalAsync(CacheKey if (won == true) { - result = new(FillOutcome.Added, default, deadline); + result = new(FillOutcome.Added, default, deadline.At); } else if (won is not null) { - result = await FillAfterNxAsync(cacheKey, redisKey, serialized, deadline, plain, format, fence, token).ConfigureAwait(false); + result = await FillAfterNxAsync(cacheKey, redisKey, serialized, deadline, plain, format, fence, token).ConfigureAwait(false); } } @@ -283,8 +343,9 @@ 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. /// 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) + private async ValueTask> FillAfterNxAsync(CacheKey cacheKey, RedisKey redisKey, RedisValue serialized, TDeadline deadline, bool lost, TFormat format, FillFence fence, CancellationToken token, bool reread = true) where TFormat : struct, IValueFormat + where TDeadline : struct, IFillDeadline { var raw = await _write.ExecuteAsync(static (s, token) => FillAfterAsync(s.Self, s.Key, s.Serialized, s.Deadline, s.Lost, s.Fence, token), (Self: this, Key: redisKey, Serialized: serialized, Deadline: deadline, Lost: lost, Fence: fence), @@ -310,7 +371,7 @@ private async ValueTask> FillAfterNxAsync(CacheKey cac if (stored.Added) { - return new(FillOutcome.Added, default, deadline); + return new(FillOutcome.Added, default, deadline.At); } var existing = ExistingEntry(redisKey, stored, format, out var frame); @@ -319,12 +380,13 @@ private async ValueTask> FillAfterNxAsync(CacheKey cac return existing; } - return reread ? await ExistingAgainAsync(cacheKey, redisKey, serialized, deadline, format, fence, token).ConfigureAwait(false) : default; + return reread ? await ExistingAgainAsync(cacheKey, redisKey, serialized, deadline, format, fence, token).ConfigureAwait(false) : default; } /// 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) + private async ValueTask> ExistingAgainAsync(CacheKey cacheKey, RedisKey redisKey, RedisValue serialized, TDeadline deadline, TFormat format, FillFence fence, CancellationToken token) where TFormat : struct, IValueFormat + where TDeadline : struct, IFillDeadline { var (value, life) = await ReadAtomicAsync(redisKey, token, onMaster: true).ConfigureAwait(false); if (!life.IsAnchored) @@ -340,8 +402,7 @@ private async ValueTask> ExistingAgainAsync(CacheKey c if (frame.Expired) { - // Nothing is stored and nothing is repaired over an expired frame. - return default; + return await ReplaceExpiredAgainAsync(cacheKey, redisKey, value, serialized, deadline, format, fence, token).ConfigureAwait(false); } if (IsAlive(value, life) && !TombstoneValue.Is(value)) @@ -349,7 +410,32 @@ private async ValueTask> ExistingAgainAsync(CacheKey c return new(FillOutcome.Unreadable, default); } - return await FillAfterNxAsync(cacheKey, redisKey, serialized, deadline, lost: false, format, fence, token, reread: false).ConfigureAwait(false); + return await FillAfterNxAsync(cacheKey, redisKey, serialized, deadline, lost: false, format, fence, token, reread: false).ConfigureAwait(false); + } + + /// The expired frame that the anchored read found: replaced by compare-and-set on its bytes. A key that changed since is a lost race, and the fill tries once more. + private async ValueTask> ReplaceExpiredAgainAsync(CacheKey cacheKey, RedisKey redisKey, RedisValue expired, RedisValue serialized, TDeadline deadline, TFormat format, FillFence fence, CancellationToken token) + where TFormat : struct, IValueFormat + where TDeadline : struct, IFillDeadline + { + var settled = await _write.ExecuteAsync(static (s, token) => + { + token.ThrowIfCancellationRequested(); + return SettleExpiredFrameAsync(s.Self, s.Key, new FillRaw(false, s.Expired, DateTimeOffset.MinValue, IsExpiredFrame: true), s.Serialized, s.Deadline); + }, + (Self: this, Key: redisKey, Expired: expired, Serialized: serialized, Deadline: deadline), + null, + token).ConfigureAwait(false); + + if (settled is { IsLapsed: true }) + { + LogFillSkipped(Logged(cacheKey, redisKey, typeof(T)), ExpirationPassed); + return default; + } + + return settled is { Added: true } + ? new(FillOutcome.Added, default, deadline.At) + : await FillAfterNxAsync(cacheKey, redisKey, serialized, deadline, lost: true, 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. @@ -382,8 +468,15 @@ private FillResult ExistingEntry(RedisKey redisKey, FillRaw store 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) + private ValueTask> SetIfChangedInternalAsync(CacheKey cacheKey, RedisKey redisKey, T? value, IEqualityComparer comparer, DateTimeOffset deadline, TFormat format, CancellationToken token) + where TFormat : struct, IValueFormat => + NeverFramed() + ? ChangeInternalAsync(cacheKey, redisKey, value, comparer, new PlainSend(deadline), format, token) + : ChangeInternalAsync(cacheKey, redisKey, value, comparer, new AnchoredSend(deadline, format.Frame.Anchor), format, token); + + private async ValueTask> ChangeInternalAsync(CacheKey cacheKey, RedisKey redisKey, T? value, IEqualityComparer comparer, TDeadline deadline, TFormat format, CancellationToken token) where TFormat : struct, IValueFormat + where TDeadline : struct, IFillDeadline { token.ThrowIfCancellationRequested(); @@ -407,6 +500,11 @@ private async ValueTask> SetIfChangedInternalAsync(C NoteWritten(redisKey); var (serialized, payload) = isNull ? (RedisValue.EmptyString, default(SerializedPayload)) : SerializeValue(value, format); _auditKeySize?.Invoke(Logged(cacheKey, redisKey, typeof(T)), serialized); + if (!NeverFramed()) + { + serialized = FramedUntil(serialized, deadline.At, format.Frame).Stored; + } + using (payload) { result = await ChangeWithRetriesAsync(cacheKey, redisKey, value, comparer, deadline, format, serialized, run, token).ConfigureAwait(false); @@ -434,8 +532,9 @@ private async ValueTask> SetIfChangedInternalAsync(C return result; } - private async ValueTask> ChangeWithRetriesAsync(CacheKey cacheKey, RedisKey redisKey, T? value, IEqualityComparer comparer, DateTimeOffset deadline, TFormat format, RedisValue serialized, ChangeRun run, CancellationToken token) + private async ValueTask> ChangeWithRetriesAsync(CacheKey cacheKey, RedisKey redisKey, T? value, IEqualityComparer comparer, TDeadline deadline, TFormat format, RedisValue serialized, ChangeRun run, CancellationToken token) where TFormat : struct, IValueFormat + where TDeadline : struct, IFillDeadline { ChangeResult result = default; var losses = 0; @@ -471,27 +570,50 @@ private async ValueTask> ChangeWithRetriesAsync(Cach return result; } - private async ValueTask<(ChangeStep Step, ChangeResult Result)> ChangeAttemptAsync(RedisKey redisKey, T? value, IEqualityComparer comparer, DateTimeOffset deadline, TFormat format, RedisValue serialized, ChangeRun run, CancellationToken token) + private async ValueTask<(ChangeStep Step, ChangeResult Result)> ChangeAttemptAsync(RedisKey redisKey, T? value, IEqualityComparer comparer, TDeadline deadline, TFormat format, RedisValue serialized, ChangeRun run, CancellationToken token) where TFormat : struct, IValueFormat + where TDeadline : struct, IFillDeadline { - var read = await ReadSnapshotRawAsync(redisKey, token).ConfigureAwait(false); - if (read is not { } snapshot) + (RedisValue Value, DateTimeOffset Expiration) snapshot; + ChangeResult? unchanged; + bool expired; + if (format.Frame.Window > TimeSpan.Zero) { - return (ChangeStep.Stopped, default); - } + // Under a format with a window the attempt starts with the anchored read, so it reads once: its value, its bytes and its deadline (CS2). + var (held, life) = await ReadAtomicAsync(redisKey, token, onMaster: true).ConfigureAwait(false); + if (!life.IsAnchored) + { + return (ChangeStep.Stopped, default); + } - var unchanged = UnchangedAgainst(redisKey, snapshot, KeyLife.Late(snapshot.Expiration), value, comparer, format, run, out var frame); - if (frame.ReadAgain) + snapshot = (held, DateTimeOffset.MaxValue); + unchanged = UnchangedAgainst(redisKey, snapshot, life, value, comparer, format, run, out var judged); + expired = judged.Expired; + } + else { - // 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) + var read = await ReadSnapshotRawAsync(redisKey, token).ConfigureAwait(false); + if (read is not { } late) { return (ChangeStep.Stopped, default); } - snapshot = (again, DateTimeOffset.MaxValue); - unchanged = UnchangedAgainst(redisKey, snapshot, life, value, comparer, format, run, out _); + snapshot = late; + unchanged = UnchangedAgainst(redisKey, snapshot, KeyLife.Late(snapshot.Expiration), value, comparer, format, run, out var frame); + expired = frame.Expired; + 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 var second); + expired = second.Expired; + } } if (unchanged is { } same) @@ -503,15 +625,14 @@ private async ValueTask> ChangeWithRetriesAsync(Cach var written = await _write.ExecuteAsync(static async (s, token) => { token.ThrowIfCancellationRequested(); - var remaining = s.Self.RemainingOrZero(s.Deadline); - if (remaining <= TimeSpan.Zero) + if (s.Deadline.Send(s.Self, s.Serialized) is not { } send) { s.Run.Lapsed = true; return null; } return s.Absent - ? await s.Self.StoreIfAbsentAsync(s.Key, s.Serialized, remaining).ConfigureAwait(false) + ? await s.Self.StoreIfAbsentAsync(s.Key, send.Bytes, send.Ttl).ConfigureAwait(false) : await s.Self.ReplaceIfUnchangedAsync(s.Key, s.Expected, s.Serialized, s.Deadline, s.Run).ConfigureAwait(false); }, (Self: this, Key: redisKey, Serialized: serialized, Deadline: deadline, Absent: snapshot.Value.IsNull, Expected: snapshot.Value, Run: run), @@ -527,7 +648,7 @@ private async ValueTask> ChangeWithRetriesAsync(Cach return (ChangeStep.Lost, default); } - return (ChangeStep.Settled, new ChangeResult(snapshot.Value.IsNull || (_tombstoneGrace is not null && TombstoneValue.Is(snapshot.Value)) ? ChangeOutcome.Filled : ChangeOutcome.Replaced, value, deadline)); + return (ChangeStep.Settled, new ChangeResult(snapshot.Value.IsNull || expired || (_tombstoneGrace is not null && TombstoneValue.Is(snapshot.Value)) ? ChangeOutcome.Filled : ChangeOutcome.Replaced, value, deadline.At)); } /// 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 (). @@ -555,31 +676,32 @@ private async ValueTask> ChangeWithRetriesAsync(Cach private async ValueTask StoreIfAbsentAsync(RedisKey key, RedisValue serialized, TimeSpan remaining) => await Database.StringSetAsync(key, serialized, remaining, When.NotExists, CommandFlags.DemandMaster).ConfigureAwait(false); - private async ValueTask ReplaceIfUnchangedAsync(RedisKey key, RedisValue expected, RedisValue serialized, DateTimeOffset deadline, ChangeRun run) + private async ValueTask ReplaceIfUnchangedAsync(RedisKey key, RedisValue expected, RedisValue serialized, TDeadline deadline, ChangeRun run) + where TDeadline : struct, IFillDeadline { - var done = await FormatRewriteScripts.ReplaceStringAsync(Database, key, expected, serialized, () => RemainingOrZero(deadline), RewriteScriptsOn, _rewriteScriptRefused).ConfigureAwait(false); + var done = await ReplaceUntilAsync(key, expected, serialized, deadline).ConfigureAwait(false); run.Lapsed |= done is null; return done; } - private async ValueTask> OverwriteAfterLossesAsync(RedisKey redisKey, T? value, DateTimeOffset deadline, RedisValue serialized, ChangeRun run, CancellationToken token) + private async ValueTask> OverwriteAfterLossesAsync(RedisKey redisKey, T? value, TDeadline deadline, RedisValue serialized, ChangeRun run, CancellationToken token) + where TDeadline : struct, IFillDeadline { var overwritten = await _write.ExecuteAsync(static async (s, token) => { token.ThrowIfCancellationRequested(); - var remaining = s.Self.RemainingOrZero(s.Deadline); - if (remaining <= TimeSpan.Zero) + if (s.Deadline.Send(s.Self, s.Serialized) is not { } send) { s.Run.Lapsed = true; return null; } - return (bool?)await s.Self.Database.StringSetAsync(s.Key, s.Serialized, remaining, When.Always, CommandFlags.DemandMaster).ConfigureAwait(false); + return (bool?)await s.Self.Database.StringSetAsync(s.Key, send.Bytes, send.Ttl, When.Always, CommandFlags.DemandMaster).ConfigureAwait(false); }, (Self: this, Key: redisKey, Serialized: serialized, Deadline: deadline, Run: run), null, token).ConfigureAwait(false); - return overwritten == true ? new ChangeResult(ChangeOutcome.Replaced, value, deadline) : default; + return overwritten == true ? new ChangeResult(ChangeOutcome.Replaced, value, deadline.At) : default; } private async ValueTask<(RedisValue Value, DateTimeOffset Expiration)?> ReadSnapshotRawAsync(RedisKey redisKey, CancellationToken token) @@ -604,6 +726,18 @@ private async ValueTask> OverwriteAfterLossesAsync(RedisKey r return (value, Clock.ToDateTimeOffset(expiration)); } + /// A compare-and-set of over , whose form and life are asked again before the transaction after a refused script (WS4). + private Task ReplaceUntilAsync(RedisKey key, RedisValue expected, RedisValue serialized, TDeadline deadline) + where TDeadline : struct, IFillDeadline => + FormatRewriteScripts.ReplaceStringAsync( + Database, + key, + expected, + (Self: this, Stored: serialized, Deadline: deadline), + static s => s.Deadline.Send(s.Self, s.Stored) ?? (RedisValue.Null, TimeSpan.Zero), + RewriteScriptsOn, + _rewriteScriptRefused); + /// for no deadline. private TimeSpan RemainingOrZero(DateTimeOffset deadline) => Remaining(deadline) ?? TimeSpan.Zero; @@ -621,7 +755,7 @@ private bool CanStore(CacheKey cacheKey, RedisKey redisKey, bool isNull, Type va [LoggerMessage(Level = LogLevel.Debug, Message = "TryFill or SetIfChanged skipped for {RedisKey}: {Reason}.")] private partial void LogFillSkipped(LoggedKey redisKey, string reason); - private readonly record struct FillRaw(bool Added, RedisValue Value, DateTimeOffset Expiration, bool IsLapsed = false, bool IsRemoved = false, bool IsTombstone = false) + private readonly record struct FillRaw(bool Added, RedisValue Value, DateTimeOffset Expiration, bool IsLapsed = false, bool IsRemoved = false, bool IsTombstone = false, bool IsExpiredFrame = false) { public static FillRaw Lapsed { get; } = new(false, RedisValue.Null, DateTimeOffset.MinValue, true); diff --git a/src/UiPath.Caching/Redis/RedisCache.FillDeadline.cs b/src/UiPath.Caching/Redis/RedisCache.FillDeadline.cs new file mode 100644 index 000000000..ff2e7e09b --- /dev/null +++ b/src/UiPath.Caching/Redis/RedisCache.FillDeadline.cs @@ -0,0 +1,48 @@ +namespace UiPath.Caching.Redis; + +/// +/// The deadline a fill, a compare-and-swap or a stamped write carries down to its sends. The plain one is today's: the bytes as given and the +/// UTC remainder. The anchored one is the framed branch's: the send form of the bytes and the remainder on both clocks (W2, W8, WA2). The two +/// differ only in type, so the plain instantiation keeps the shape of today's states and the anchored one adds its 16-byte anchor (C6). +/// +internal sealed partial class RedisCache +{ + private interface IFillDeadline + { + /// The logical deadline, which a fill reports. + DateTimeOffset At { get; } + + /// The logical life left, from one clock pair. + TimeSpan Left(RedisCache self); + + /// The bytes and TTL of one send; null once the life left is not positive. + (RedisValue Bytes, TimeSpan Ttl)? Send(RedisCache self, RedisValue stored); + + /// The bytes and TTL of one key of a batch whose remainder and gate answer were read once for the attempt. + (RedisValue Bytes, TimeSpan Ttl) Form(RedisValue stored, TimeSpan left, bool open); + } + + /// Whether is today's deadline, which never reads the gate; the JIT folds it. + private static bool NeverFramedDeadline() + where TDeadline : struct, IFillDeadline => + typeof(TDeadline) == typeof(PlainSend); + + private readonly record struct PlainSend(DateTimeOffset At) : IFillDeadline + { + public TimeSpan Left(RedisCache self) => self.RemainingOrZero(At); + + public (RedisValue Bytes, TimeSpan Ttl)? Send(RedisCache self, RedisValue stored) => + self.RemainingOrZero(At) is var left && left > TimeSpan.Zero ? (stored, left) : null; + + public (RedisValue Bytes, TimeSpan Ttl) Form(RedisValue stored, TimeSpan left, bool open) => (stored, left); + } + + private readonly record struct AnchoredSend(DateTimeOffset At, WriteAnchor Anchor) : IFillDeadline + { + public TimeSpan Left(RedisCache self) => Anchor.Left(self.Clock, At); + + public (RedisValue Bytes, TimeSpan Ttl)? Send(RedisCache self, RedisValue stored) => self.SendFormLeft(stored, At, Anchor); + + public (RedisValue Bytes, TimeSpan Ttl) Form(RedisValue stored, TimeSpan left, bool open) => SendFormFor(stored, left, open); + } +} diff --git a/src/UiPath.Caching/Redis/RedisCache.FillGenerated.cs b/src/UiPath.Caching/Redis/RedisCache.FillGenerated.cs index a9a9a854e..367d84e6f 100644 --- a/src/UiPath.Caching/Redis/RedisCache.FillGenerated.cs +++ b/src/UiPath.Caching/Redis/RedisCache.FillGenerated.cs @@ -14,7 +14,14 @@ private static void SetGeneratedFillExpiration(IInFlightEnd run, DateTime { var started = Clock.GetTimestamp(); var value = await RunGeneratorAsync(cacheKey, state, generator, factoryTimeout, run.Token).ConfigureAwait(false); - return !IsDefault(value) || _cacheNullValues ? await FillGeneratedAsync(cacheKey, redisKey, value, lifetime, started, format, run).ConfigureAwait(false) : value; + if (IsDefault(value) && !_cacheNullValues) + { + return value; + } + + // After the generator: today's reading on the unframed branch; a caller's instant first on the framed one, and a duration made an instant only when none was given (GI2). + var (deadline, anchor) = NeverFramed() ? (Clock.ToDateTimeOffset(lifetime), default(WriteAnchor)) : FramedDeadline(lifetime, format); + return await FillGeneratedAsync(cacheKey, redisKey, value, deadline, anchor, started, format, run).ConfigureAwait(false); } private async Task> GenerateAndFillExpiringAsync(CacheKey cacheKey, RedisKey redisKey, TState state, Func>> generator, CachePolicy? policy, TFormat format, IInFlightEnd run) @@ -22,23 +29,58 @@ private async Task> GenerateAndFillExpiringAsync()) + { + // A value that skips fail-safe keeps no window where it is first stored (W7). + return await (generated.SkipFailSafe + ? FillExpiringFramedAsync(cacheKey, redisKey, generated, policy, new WithoutWindow(format), started, run) + : FillExpiringFramedAsync(cacheKey, redisKey, generated, policy, format, started, run)).ConfigureAwait(false); + } + var duration = generated.Expiration is { } expiration ? Remaining(expiration) : PolicyDuration(policy); if (duration is not { } lifetime || (IsDefault(generated.Value) && !_cacheNullValues)) { return generated; } - return generated with { Value = await FillGeneratedAsync(cacheKey, redisKey, generated.Value, lifetime, started, format, run).ConfigureAwait(false) }; + return generated with { Value = await FillGeneratedAsync(cacheKey, redisKey, generated.Value, Clock.ToDateTimeOffset(lifetime), default, started, format, run).ConfigureAwait(false) }; + } + + /// The framed fenced fill of a generator that names its expiration: its instant validated with its anchor in place of , or the policy duration made an instant once (GI1, GI2). + private async Task> FillExpiringFramedAsync(CacheKey cacheKey, RedisKey redisKey, GeneratedValue generated, CachePolicy? policy, TFormat format, long started, IInFlightEnd run) + where TFormat : struct, IValueFormat + { + if (!GeneratedUntil(generated, policy, out var until, out var anchor) || (IsDefault(generated.Value) && !_cacheNullValues)) + { + return generated; + } + + return generated with { Value = await FillGeneratedAsync(cacheKey, redisKey, generated.Value, until, anchor, started, format, run).ConfigureAwait(false) }; + } + + /// The instant of a framed store and its anchor: the caller's, which rides in the format, or a capture of . + private (DateTimeOffset Until, WriteAnchor Anchor) FramedDeadline(TimeSpan lifetime, TFormat format) + where TFormat : struct, IValueFormat + { + if (format.Frame.Until is { } until) + { + return (until, format.Frame.Anchor); + } + + var anchor = WriteAnchor.Capture(Clock, lifetime, out var deadline); + return (deadline, anchor); } - /// The value to answer: the key's own when one was stored meanwhile, the generator's otherwise. - private async Task FillGeneratedAsync(CacheKey cacheKey, RedisKey redisKey, T? value, TimeSpan lifetime, long startedAt, TFormat format, IInFlightEnd run) + /// The value to answer: the key's own when one was stored meanwhile, the generator's otherwise. is the fill's, the repair's, every send's and the reported one; on the framed branch every attempt evaluates . + private async Task FillGeneratedAsync(CacheKey cacheKey, RedisKey redisKey, T? value, DateTimeOffset deadline, WriteAnchor anchor, long startedAt, TFormat format, IInFlightEnd run) where TFormat : struct, IValueFormat { - var deadline = Clock.ToDateTimeOffset(lifetime); for (var attempt = 0; attempt < FillAttempts; attempt++) { - var filled = await TryFillInternalAsync(cacheKey, redisKey, value, deadline, format, NewFence(Clock.GetElapsedTime(startedAt)), run.Token).ConfigureAwait(false); + var fence = NewFence(Clock.GetElapsedTime(startedAt)); + var filled = await (NeverFramed() + ? FillInternalAsync(cacheKey, redisKey, value, new PlainSend(deadline), format, fence, run.Token) + : FillInternalAsync(cacheKey, redisKey, value, new AnchoredSend(deadline, anchor), format, fence, run.Token)).ConfigureAwait(false); switch (filled.Outcome) { case FillOutcome.Added: @@ -49,7 +91,10 @@ private async Task> GenerateAndFillExpiringAsync() + ? ReplaceUnreadableAsync(cacheKey, redisKey, value, new PlainSend(deadline), format, run.Token) + : ReplaceUnreadableAsync(cacheKey, redisKey, value, new AnchoredSend(deadline, anchor), format, run.Token)).ConfigureAwait(false); + switch (replaced) { case UnreadableReplace.Stored: SetGeneratedFillExpiration(run, deadline); @@ -94,8 +139,19 @@ private async Task> GenerateAndFillExpiringAsync FillGeneratedBatchAsync(KeyValuePair[] pairs, StoreLifetime lifetime, CachePolicy? policy, long startedAt, CancellationToken token) { - var deadline = Clock.ToDateTimeOffset(lifetime.Resolve(this, policy)); var format = FormatFor(policy, forWrite: true, alsoReads: true); + var frame = FrameFor(policy); + if (!frame.IsNone) + { + // The instant of an At is the caller's own, with the anchor taken where the lifetime was built; a duration is captured here (IC5, WA5). + var (until, anchor) = lifetime.Until(this, policy); + frame = frame with { Anchor = anchor }; + return format.IsDefault + ? FillGeneratedBatchAsync(pairs, until, startedAt, new FramedFormat(default, frame), token) + : FillGeneratedBatchAsync(pairs, until, startedAt, new FramedFormat(format, frame), token); + } + + var deadline = Clock.ToDateTimeOffset(lifetime.Resolve(this, policy)); return format.IsDefault ? FillGeneratedBatchAsync(pairs, deadline, startedAt, default(PlainFormat), token) : FillGeneratedBatchAsync(pairs, deadline, startedAt, format, token); @@ -141,7 +197,7 @@ private async ValueTask FillGeneratedBatchAsync(KeyValuePairHow long a batch's values live: the policy's, a duration or a deadline. + /// How long a batch's values live: the policy's, a duration or a deadline; with the option on, a deadline carries the anchor taken where it was built. private readonly record struct StoreLifetime(TimeSpan? Span, DateTimeOffset? At) { public StoreLifetime(TimeSpan span) @@ -154,6 +210,28 @@ public StoreLifetime(DateTimeOffset at) { } + public WriteAnchor Anchor { get; private init; } + + /// A deadline whose anchor is taken now, beside the validation of . + public static StoreLifetime AnchoredAt(RedisCache cache, DateTimeOffset at) + { + cache.CallerDurationAnchored(at, out var anchor); + return new StoreLifetime(at) { Anchor = anchor }; + } + + /// The instant of the framed branch and its anchor: an At validated as does and answered itself, a duration captured now. + public (DateTimeOffset Until, WriteAnchor Anchor) Until(RedisCache cache, CachePolicy? policy) + { + if (At is { } at) + { + cache.CallerDuration(at); + return (at, Anchor); + } + + var anchor = WriteAnchor.Capture(cache.Clock, Resolve(cache, policy), out var until); + return (until, anchor); + } + public TimeSpan Resolve(RedisCache cache, CachePolicy? policy) => this switch { diff --git a/src/UiPath.Caching/Redis/RedisCache.FillMany.cs b/src/UiPath.Caching/Redis/RedisCache.FillMany.cs index 2ce0877b7..c466e7768 100644 --- a/src/UiPath.Caching/Redis/RedisCache.FillMany.cs +++ b/src/UiPath.Caching/Redis/RedisCache.FillMany.cs @@ -5,16 +5,8 @@ namespace UiPath.Caching.Redis; internal sealed partial class RedisCache : IFillManyTier { - public ValueTask[]> TryFillManyAsync(KeyValuePair[] entries, DateTimeOffset expiration, CachePolicy? policy, CancellationToken token, TimeSpan? generatorElapsed = null) - { - NotCacheableException.ThrowIfNotCacheable(); - var format = FormatFor(policy, forWrite: true, alsoReads: true); - var deadline = GetExpiration(expiration); - var fence = generatorElapsed is { } elapsed ? NewFence(elapsed) : default; - return format.IsDefault - ? TryFillManyInternalAsync(entries, deadline, default(PlainFormat), fence, token) - : TryFillManyInternalAsync(entries, deadline, format, fence, token); - } + public ValueTask[]> TryFillManyAsync(KeyValuePair[] entries, DateTimeOffset expiration, CachePolicy? policy, CancellationToken token, TimeSpan? generatorElapsed = null) => + TryFillManyCoreAsync(entries, expiration, policy, token, generatorElapsed, default); private static List StorableSlotPositions(bool[] storable, int[] group) { @@ -30,7 +22,8 @@ private static List StorableSlotPositions(bool[] storable, int[] group) return open; } - private static async ValueTask FillSlotOnceAsync(RedisCache self, RedisKey[] keys, RedisValue[] serialized, bool[] storable, int[] group, DateTimeOffset deadline, FillFence fence, CancellationToken token) + private static async ValueTask FillSlotOnceAsync(RedisCache self, RedisKey[] keys, RedisValue[] serialized, bool[] storable, int[] group, TDeadline deadline, FillFence fence, CancellationToken token) + where TDeadline : struct, IFillDeadline { token.ThrowIfCancellationRequested(); var raws = new FillRaw?[group.Length]; @@ -47,7 +40,8 @@ private static List StorableSlotPositions(bool[] storable, int[] group) return raws; } - var remaining = self.RemainingOrZero(deadline); + // One remainder and one gate answer for every key of the slot attempt (WS2, WA3). + var remaining = deadline.Left(self); if (remaining <= TimeSpan.Zero) { foreach (var j in open) @@ -59,12 +53,14 @@ private static List StorableSlotPositions(bool[] storable, int[] group) } // One flush for the slot: every key is sent before any reply is awaited. + var gate = !NeverFramedDeadline() && self.FrameWrites.Allowed; var batch = self.Database.CreateBatch(); var sets = new Task[open.Count]; for (var k = 0; k < open.Count; k++) { var i = group[open[k]]; - sets[k] = batch.StringSetAsync(keys[i], serialized[i], remaining, When.NotExists, CommandFlags.DemandMaster); + var (bytes, ttl) = deadline.Form(serialized[i], remaining, gate); + sets[k] = batch.StringSetAsync(keys[i], bytes, ttl, When.NotExists, CommandFlags.DemandMaster); } batch.Execute(); @@ -96,6 +92,27 @@ private static List StorableSlotPositions(bool[] storable, int[] group) return raws; } + private ValueTask[]> TryFillManyCoreAsync(KeyValuePair[] entries, DateTimeOffset expiration, CachePolicy? policy, CancellationToken token, TimeSpan? generatorElapsed, WriteAnchor anchor) + { + NotCacheableException.ThrowIfNotCacheable(); + var format = FormatFor(policy, forWrite: true, alsoReads: true); + var frame = FrameFor(policy); + // A caller of the Redis tier itself takes the anchor of its instant here; a layered caller hands its own. + var deadline = !frame.IsNone && !anchor.IsSet ? ExpirationAnchored(expiration, out anchor) : GetExpiration(expiration); + var fence = generatorElapsed is { } elapsed ? NewFence(elapsed) : default; + if (!frame.IsNone) + { + frame = frame with { Anchor = anchor }; + return format.IsDefault + ? TryFillManyInternalAsync(entries, deadline, new FramedFormat(default, frame), fence, token) + : TryFillManyInternalAsync(entries, deadline, new FramedFormat(format, frame), fence, token); + } + + return format.IsDefault + ? TryFillManyInternalAsync(entries, deadline, default(PlainFormat), fence, token) + : TryFillManyInternalAsync(entries, deadline, format, fence, token); + } + /// The command's answer, or none when it failed; a cancellation is not a failure of the key. private async ValueTask<(bool Answered, TResult? Value)> SettleAsync(Task command) { @@ -110,8 +127,15 @@ private static List StorableSlotPositions(bool[] storable, int[] group) } } - private async ValueTask[]> TryFillManyInternalAsync(KeyValuePair[] entries, DateTimeOffset deadline, TFormat format, FillFence fence, CancellationToken token) + private ValueTask[]> TryFillManyInternalAsync(KeyValuePair[] entries, DateTimeOffset deadline, TFormat format, FillFence fence, CancellationToken token) + where TFormat : struct, IValueFormat => + NeverFramed() + ? FillManyInternalAsync(entries, new PlainSend(deadline), format, fence, token) + : FillManyInternalAsync(entries, new AnchoredSend(deadline, format.Frame.Anchor), format, fence, token); + + private async ValueTask[]> FillManyInternalAsync(KeyValuePair[] entries, TDeadline deadline, TFormat format, FillFence fence, CancellationToken token) where TFormat : struct, IValueFormat + where TDeadline : struct, IFillDeadline { token.ThrowIfCancellationRequested(); var results = new FillResult[entries.Length]; @@ -140,6 +164,10 @@ private async ValueTask[]> TryFillManyInternalAsync(Ke storable[i] = true; (serialized[i], payloads[i]) = isNull ? (RedisValue.EmptyString, default(SerializedPayload)) : SerializeValue(entries[i].Value, format); _auditKeySize?.Invoke(Logged(entries[i].Key, redisKeys[i], typeof(T)), serialized[i]); + if (!NeverFramed()) + { + serialized[i] = FramedUntil(serialized[i], deadline.At, format.Frame).Stored; + } } await EnsureConnectedAsync(_write, token).ConfigureAwait(false); @@ -155,10 +183,10 @@ private async ValueTask[]> TryFillManyInternalAsync(Ke null, LogRedisCacheException).ConfigureAwait(false); - var again = ReadFillSlotResults(entries, redisKeys, storable, groups, slots, deadline, format, results, ref ok); + var again = ReadFillSlotResults(entries, redisKeys, storable, groups, slots, deadline.At, format, results, ref ok); if (again is not null) { - ok &= await ExistingManyAgainAsync(redisKeys, again, format, results, token).ConfigureAwait(false); + ok &= await ExistingManyAgainAsync(entries, redisKeys, serialized, again, deadline, format, fence, results, token).ConfigureAwait(false); } operation.Stop(); @@ -189,9 +217,10 @@ private async ValueTask[]> TryFillManyInternalAsync(Ke return results; } - /// 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) + /// The winners a late read found as fresh frames with a window, read again through the anchored read, whose answers alone are the fills'. A frame that is expired by then is replaced like any expired frame (K5); a key gone by then fails its fill. + private async ValueTask ExistingManyAgainAsync(KeyValuePair[] entries, RedisKey[] redisKeys, RedisValue[] serialized, List again, TDeadline deadline, TFormat format, FillFence fence, FillResult[] results, CancellationToken token) where TFormat : struct, IValueFormat + where TDeadline : struct, IFillDeadline { var positions = again.ToArray(); var (values, lives) = await ReadManyAtomicAsync(Pick(redisKeys, positions), token).ConfigureAwait(false); @@ -201,7 +230,13 @@ private async ValueTask ExistingManyAgainAsync(RedisKey[] redi 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; + if (frame.Expired) + { + var i = positions[k]; + results[i] = await ReplaceExpiredAgainAsync(entries[i].Key, redisKeys[i], values[k], serialized[i], deadline, format, fence, token).ConfigureAwait(false); + } + + ok &= results[positions[k]].Outcome is not (FillOutcome.Failed or FillOutcome.Unreadable); } return ok; diff --git a/src/UiPath.Caching/Redis/RedisCache.FrameWrite.cs b/src/UiPath.Caching/Redis/RedisCache.FrameWrite.cs new file mode 100644 index 000000000..cdf9b0951 --- /dev/null +++ b/src/UiPath.Caching/Redis/RedisCache.FrameWrite.cs @@ -0,0 +1,137 @@ +using UiPath.Caching.Serialization; + +namespace UiPath.Caching.Redis; + +/// The write side of the entry frame: which spec a call frames with, the frame built at the storage boundary, and the form each send takes. +internal sealed partial class RedisCache +{ + private int _reservedValueWarned; + private int _windowedFrameWarned; + + /// Whether this cache may write entry frames at all; a layered cache hands its write anchors on only then. + internal bool EntryMetadataEnabled { get; private init; } + + /// Whether is the plain or the format branch, which never frames; the JIT folds it. + internal static bool NeverFramed() + where TFormat : struct, IValueFormat => + typeof(TFormat) == typeof(PlainFormat) || typeof(TFormat) == typeof(ValueFormat); + + /// The bytes and TTL of one key of a send whose remainder and gate answer were read once for the attempt. + internal static (RedisValue Bytes, TimeSpan Ttl) SendFormFor(RedisValue stored, TimeSpan left, bool open) + { + if (!TryReadFrame(stored, out var frame)) + { + return (stored, left); + } + + if (!open) + { + return (frame.Inner, left); + } + + return (stored, frame.HasWindow ? Plus(left, frame.Window) : left); + } + + /// As , with the gate answer read once for the attempt. + internal static (RedisValue Bytes, TimeSpan Life) SendForm(RedisValue stored, TimeSpan life, bool open) + { + if (open || !TryReadFrame(stored, out var frame)) + { + return (stored, life); + } + + return (frame.Inner, frame.HasWindow && life != TimeSpan.MaxValue ? life - frame.Window : life); + } + + /// The frame a write under takes: none when the option is off, the gate is closed or nothing is left to say. + internal FrameSpec FrameFor(CachePolicy? policy, EntryValidators? validators = null) + { + if (!EntryMetadataEnabled || !FrameWrites.Allowed) + { + return default; + } + + var window = FailSafeLifetimeWarning.RedisWindow(policy ?? DefaultPolicy); + return EntryFrame.Needed(window, validators) ? new FrameSpec(window, validators) : default; + } + + /// The stored bytes and the physical life of a relative lifetime: a frame whose expiration is now plus the lifetime, with the window added to the TTL. The given pair for no spec, a closed gate, a reserved first byte or no expiry. + internal (RedisValue Stored, TimeSpan Lifetime) Framed(RedisValue serialized, TimeSpan lifetime, in FrameSpec spec) + { + if (!Frames(serialized, lifetime == TimeSpan.MaxValue, spec, out var window)) + { + return (serialized, lifetime); + } + + var expiration = Clock.ToDateTimeOffset(lifetime); + return (Frame(serialized, expiration, window, spec.Validators), Plus(lifetime, window)); + } + + /// As , for a deadline: the frame expiration is , and the physical deadline adds the window. + internal (RedisValue Stored, DateTimeOffset Deadline) FramedUntil(RedisValue serialized, DateTimeOffset deadline, in FrameSpec spec) + { + if (!Frames(serialized, deadline == DateTimeOffset.MaxValue, spec, out var window)) + { + return (serialized, deadline); + } + + var physical = deadline.UtcTicks > DateTimeOffset.MaxValue.UtcTicks - window.Ticks ? DateTimeOffset.MaxValue : deadline + window; + return (Frame(serialized, deadline, window, spec.Validators), physical); + } + + /// The bytes a send takes and their life: as given while the gate is open or for bytes that are no frame; with it closed, the inner bytes and the life less the window. + internal (RedisValue Bytes, TimeSpan Life) SendForm(RedisValue stored, TimeSpan life) => SendForm(stored, life, FrameWrites.Allowed); + + /// As , for a physical deadline. + internal (RedisValue Bytes, DateTimeOffset Deadline) SendFormUntil(RedisValue stored, DateTimeOffset deadline) + { + if (FrameWrites.Allowed || !TryReadFrame(stored, out var frame)) + { + return (stored, deadline); + } + + return (frame.Inner, frame.HasWindow && deadline != DateTimeOffset.MaxValue ? deadline - frame.Window : deadline); + } + + /// The send of a deadline site from one clock pair: the bytes of and the remainder of on both clocks, plus the window of a frame that keeps one. Null when the remainder is not positive. + internal (RedisValue Bytes, TimeSpan Ttl)? SendFormLeft(RedisValue stored, DateTimeOffset until, in WriteAnchor anchor) + { + var left = anchor.Left(Clock, until); + return left > TimeSpan.Zero ? SendFormFor(stored, left, FrameWrites.Allowed) : null; + } + + private static TimeSpan Plus(TimeSpan life, TimeSpan window) => + life == TimeSpan.MaxValue || life.Ticks > TimeSpan.MaxValue.Ticks - window.Ticks ? TimeSpan.MaxValue : life + window; + + private static RedisValue Frame(RedisValue serialized, DateTimeOffset expiration, TimeSpan window, EntryValidators? validators) + { + ReadOnlyMemory inner = serialized; + return EntryFrame.Write(inner.Span, expiration, window, validators); + } + + /// Whether to build a frame, asking the gate again; drops the window, and bytes a reader would refuse inside a frame stay plain. + private bool Frames(RedisValue serialized, bool never, in FrameSpec spec, out TimeSpan window) + { + window = never ? TimeSpan.Zero : spec.Window; + if (spec.IsNone || !EntryFrame.Needed(window, spec.Validators) || !FrameWrites.Allowed) + { + return false; + } + + ReadOnlyMemory bytes = serialized; + if (!bytes.IsEmpty && bytes.Span[0] is EntryFrame.Header or FormatIdRules.TombstoneId) + { + if (Interlocked.Exchange(ref _reservedValueWarned, 1) == 0) + { + LogReservedValueStoredPlain(bytes.Span[0]); + } + + return false; + } + + return true; + } + + [LoggerMessage(Level = LogLevel.Warning, Message = "A serialized value starts with the reserved byte 0x{FirstByte:X2}, so it is stored without an entry frame: it keeps no stale window in Redis. A custom serializer whose output starts with 0x0E or 0x0F should write a format header.")] + private partial void LogReservedValueStoredPlain(byte firstByte); +} diff --git a/src/UiPath.Caching/Redis/RedisCache.FramedStore.cs b/src/UiPath.Caching/Redis/RedisCache.FramedStore.cs new file mode 100644 index 000000000..747b70e77 --- /dev/null +++ b/src/UiPath.Caching/Redis/RedisCache.FramedStore.cs @@ -0,0 +1,208 @@ +using System.Runtime.CompilerServices; +using UiPath.Caching.Serialization; + +namespace UiPath.Caching.Redis; + +/// The stores of the framed branch that hold an instant: one helper for a caller's instant and for a generated value, and the add that evaluates its anchor at every attempt. +internal sealed partial class RedisCache +{ + /// A caller's instant validated as today, with its anchor: the timestamp first, then the UTC reading of . "Never" takes none. + private TimeSpan CallerDurationAnchored(DateTimeOffset expiration, out WriteAnchor anchor, [CallerArgumentExpression(nameof(expiration))] string? paramName = null) + { + anchor = default; + if (expiration == DateTimeOffset.MaxValue) + { + return CallerDuration(expiration, paramName); + } + + var stamp = Clock.GetTimestamp(); + var duration = CallerDuration(expiration, paramName); + anchor = new WriteAnchor(stamp, duration); + return duration; + } + + /// A caller's duration made a deadline with its anchor: the timestamp, then the one UTC reading that makes the deadline (WA1). + private DateTimeOffset ExpirationAnchored(TimeSpan expiration, out WriteAnchor anchor, [CallerArgumentExpression(nameof(expiration))] string? paramName = null) + { + var duration = CallerDuration(expiration, paramName); + anchor = WriteAnchor.Capture(Clock, duration, out var deadline); + return deadline; + } + + /// A caller's instant validated with its anchor: the timestamp, then the one UTC reading that validates it and gives its life (WA1). + private DateTimeOffset ExpirationAnchored(DateTimeOffset expiration, out WriteAnchor anchor, [CallerArgumentExpression(nameof(expiration))] string? paramName = null) + { + anchor = default; + if (expiration == DateTimeOffset.MaxValue) + { + return expiration; + } + + var stamp = Clock.GetTimestamp(); + var now = Clock.GetUtcNow(); + CacheExpiration.ThrowIfNotFuture(expiration, now, paramName); + anchor = new WriteAnchor(stamp, expiration - now); + return expiration; + } + + /// The framed single-key set: a caller's instant is a store with an instant, a duration is counted from the store (W1, IC5). + private ValueTask SetFramedAsync(CacheKey cacheKey, RedisKey redisKey, T? value, TimeSpan duration, TFormat format, CancellationToken token) + where TFormat : struct, IValueFormat => + format.Frame.Until is { } until + ? StoreGeneratedUntilAsync(cacheKey, redisKey, value, until, format.Frame.Anchor, format, null, token) + : SetInternalAsync(cacheKey, redisKey, value, duration, format, token); + + /// The generated store of a run on the framed branch (W9): one clock reading before the value is serialized is the frame expiration and the run's, unless the caller's instant rides in the format. + private ValueTask StoreGeneratedAsync(CacheKey cacheKey, RedisKey redisKey, T? value, TimeSpan lifetime, TFormat format, IInFlightEnd run, CancellationToken token) + where TFormat : struct, IValueFormat + { + DateTimeOffset until; + WriteAnchor anchor; + if (format.Frame.Until is { } at) + { + until = at; + anchor = format.Frame.Anchor; + } + else + { + anchor = WriteAnchor.Capture(Clock, lifetime, out until); + } + + return StoreGeneratedUntilAsync(cacheKey, redisKey, value, until, anchor, format, run, token); + } + + /// + /// A store that holds an instant (GS2 to GS5, IC4, IC6): is the frame expiration, the bound of every send and the run's expiration. + /// Each send takes the remainder of on both clocks plus the window of its form, and sends nothing once that remainder is not positive. + /// + private async ValueTask StoreGeneratedUntilAsync(CacheKey cacheKey, RedisKey redisKey, T? value, DateTimeOffset until, WriteAnchor anchor, TFormat format, IInFlightEnd? run, CancellationToken token) + where TFormat : struct, IValueFormat + { + bool ret = default; + token.ThrowIfCancellationRequested(); + + if (!IsConnected) + { + return false; + } + + NoteWritten(redisKey); + var operation = StartOperation(nameof(SetAsync)); + try + { + if (IsDefault(value) && !_cacheNullValues) + { + await RemoveAsync(redisKey, token).ConfigureAwait(false); + ret = true; + } + else + { + var (serialized, payload) = IsDefault(value) ? (RedisValue.EmptyString, default(SerializedPayload)) : SerializeValue(value, format); + _auditKeySize?.Invoke(Logged(cacheKey, redisKey, typeof(T)), serialized); + var stored = FramedUntil(serialized, until, format.Frame).Stored; + using (payload) + { + ret = await _write.ExecuteAsync(static (s, token) => + { + token.ThrowIfCancellationRequested(); + return s.Self.SendFormLeft(s.Stored, s.Until, s.Anchor) is { } send + ? s.Self.Database.StringSetAsync(s.Key, send.Bytes, send.Ttl, When.Always, CommandFlags.DemandMaster).AsValueTask() + : new ValueTask(false); + }, + (Self: this, Key: redisKey, Stored: stored, Until: until, Anchor: anchor), + default, + token).ConfigureAwait(false); + } + + if (ret && run is not null) + { + run.Expiration = until == DateTimeOffset.MaxValue ? null : until; + } + } + + operation.Stop(); + } + catch (OperationCanceledException) when (token.IsCancellationRequested) + { + operation.Cancel(); + throw; + } + catch (Exception ex) + { + operation.Stop(); + LogRedisCacheException(ex); + } + finally + { + NoteWritten(redisKey); + operation.Track(ret); + } + + return ret; + } + + /// The framed add of a caller's instant: each attempt evaluates the anchor in its callback (IC5, WA3). + private ValueTask TryAddUntilAsync(RedisKey redisKey, RedisValue stored, FrameSpec spec, CancellationToken token) => + _write.ExecuteAsync(static (s, token) => + { + token.ThrowIfCancellationRequested(); + return s.Self._tombstoneGrace is null + ? s.Self.AddFramedAsync(s.Key, s.Stored, default, s.Until, s.Anchor) + : s.Self.AddOverTombstoneFramedAsync(s.Key, s.Stored, default, s.Until, s.Anchor); + }, + (Self: this, Key: redisKey, Stored: stored, spec.Until, spec.Anchor), + default, + token); + + /// The send form of a relative life, or of an instant through its anchor; null once the instant's remainder is not positive. + private (RedisValue Bytes, TimeSpan Ttl)? SendFormOf(RedisValue stored, TimeSpan life, DateTimeOffset? until, in WriteAnchor anchor) => + until is { } at ? SendFormLeft(stored, at, anchor) : SendForm(stored, life); + + private ValueTask AddFramedAsync(RedisKey key, RedisValue stored, TimeSpan life, DateTimeOffset? until, WriteAnchor anchor) => + SendFormOf(stored, life, until, anchor) is { } send + ? Database.StringSetAsync(key, send.Bytes, send.Ttl, When.NotExists, CommandFlags.DemandMaster).AsValueTask() + : new ValueTask(false); + + /// The framed twin of : each attempt and the transaction after a refused script take the send form again. + private async ValueTask AddOverTombstoneFramedAsync(RedisKey key, RedisValue stored, TimeSpan life, DateTimeOffset? until, WriteAnchor anchor) + { + for (var attempt = 0; attempt < FillAttempts; attempt++) + { + if (SendFormOf(stored, life, until, anchor) is not { } send) + { + return false; + } + + if (await Database.StringSetAsync(key, send.Bytes, send.Ttl, When.NotExists, CommandFlags.DemandMaster).ConfigureAwait(false)) + { + return true; + } + + var held = await ReadTombstoneAsync(key).ConfigureAwait(false); + if (held.IsNull) + { + if (await Database.KeyExistsAsync(key, CommandFlags.DemandMaster).ConfigureAwait(false)) + { + return false; + } + + continue; + } + + var replaced = await FormatRewriteScripts.ReplaceStringAsync( + Database, + key, + held, + (Self: this, Stored: stored, Life: life, Until: until, Anchor: anchor), + static s => s.Self.SendFormOf(s.Stored, s.Life, s.Until, s.Anchor) ?? (RedisValue.Null, TimeSpan.Zero), + RewriteScriptsOn, + _rewriteScriptRefused).ConfigureAwait(false); + if (replaced == true) + { + return true; + } + } + + return false; + } +} diff --git a/src/UiPath.Caching/Redis/RedisCache.GetOrAdd.cs b/src/UiPath.Caching/Redis/RedisCache.GetOrAdd.cs index 7be108e01..36b5b8663 100644 --- a/src/UiPath.Caching/Redis/RedisCache.GetOrAdd.cs +++ b/src/UiPath.Caching/Redis/RedisCache.GetOrAdd.cs @@ -13,7 +13,9 @@ internal sealed partial class RedisCache public ValueTask GetOrAddAsync(CacheKey cacheKey, Func> generator, DateTimeOffset expiration, CachePolicy? policy, CancellationToken token = default) { ArgumentNullException.ThrowIfNull(generator); - return GetOrAddCoreAsync>>(cacheKey, generator, static (g, ct) => g(ct), CallerDuration(expiration), policy, token); + return EntryMetadataEnabled + ? GetOrAddCoreAsync>>(cacheKey, generator, static (g, ct) => g(ct), CallerDurationAnchored(expiration, out var anchor), policy, token, expiration, anchor) + : GetOrAddCoreAsync>>(cacheKey, generator, static (g, ct) => g(ct), CallerDuration(expiration), policy, token); } public ValueTask GetOrAddAsync(CacheKey cacheKey, Func> generator, TimeSpan expiration, CachePolicy? policy, CancellationToken token = default) @@ -29,7 +31,9 @@ internal sealed partial class RedisCache GetOrAddCoreAsync(cacheKey, state, generator, CallerDuration(expiration), policy, token); public ValueTask GetOrAddAsync(CacheKey cacheKey, TState state, Func> generator, DateTimeOffset expiration, CachePolicy? policy, CancellationToken token = default) => - GetOrAddCoreAsync(cacheKey, state, generator, CallerDuration(expiration), policy, token); + EntryMetadataEnabled + ? GetOrAddCoreAsync(cacheKey, state, generator, CallerDurationAnchored(expiration, out var anchor), policy, token, expiration, anchor) + : GetOrAddCoreAsync(cacheKey, state, generator, CallerDuration(expiration), policy, token); /// public ValueTask[]> GetOrAddAsync(KeyValuePair[] entries, Func[]>> generator, CachePolicy? policy, CancellationToken token = default) @@ -44,7 +48,9 @@ internal sealed partial class RedisCache /// public ValueTask[]> GetOrAddAsync(KeyValuePair[] entries, Func[]>> generator, DateTimeOffset expiration, CachePolicy? policy, CancellationToken token = default) where TState : notnull => - GetOrAddBatchAsync(entries, generator, (pairs, t) => SetAsync(pairs, expiration, policy, t), new StoreLifetime(expiration), policy, token); + EntryMetadataEnabled + ? GetOrAddBatchAnchored(entries, generator, expiration, policy, token) + : GetOrAddBatchAsync(entries, generator, (pairs, t) => SetAsync(pairs, expiration, policy, t), new StoreLifetime(expiration), policy, token); public ValueTask[]> GetOrAddAsync(KeyValuePair[] entries, TArg argument, Func[]>> generator, CachePolicy? policy, CancellationToken token = default) where TState : notnull => @@ -56,13 +62,23 @@ internal sealed partial class RedisCache public ValueTask[]> GetOrAddAsync(KeyValuePair[] entries, TArg argument, Func[]>> generator, DateTimeOffset expiration, CachePolicy? policy, CancellationToken token = default) where TState : notnull => - GetOrAddBatchAsync(entries, argument, generator, (pairs, t) => SetAsync(pairs, expiration, policy, t), new StoreLifetime(expiration), policy, token); + EntryMetadataEnabled + ? GetOrAddBatchAnchored(entries, argument, generator, expiration, policy, token) + : GetOrAddBatchAsync(entries, argument, generator, (pairs, t) => SetAsync(pairs, expiration, policy, t), new StoreLifetime(expiration), policy, token); public ValueTask GetOrAddWithExpirationAsync(CacheKey cacheKey, Func>> generator, CachePolicy? policy, CancellationToken token = default) { NotCacheableException.ThrowIfNotCacheable(); ArgumentNullException.ThrowIfNull(generator); var format = FormatFor(policy, forWrite: true, alsoReads: true); + var frame = FrameFor(policy); + if (!frame.IsNone) + { + return format.IsDefault + ? GetOrAddGeneratedAsync(cacheKey, ToRedisKey(cacheKey, token), generator, static (g, ct) => g(ct), policy, new FramedFormat(default, frame), token) + : GetOrAddGeneratedAsync(cacheKey, ToRedisKey(cacheKey, token), generator, static (g, ct) => g(ct), policy, new FramedFormat(format, frame), token); + } + return format.IsDefault ? GetOrAddGeneratedAsync(cacheKey, ToRedisKey(cacheKey, token), generator, static (g, ct) => g(ct), policy, default(PlainFormat), token) : GetOrAddGeneratedAsync(cacheKey, ToRedisKey(cacheKey, token), generator, static (g, ct) => g(ct), policy, format, token); @@ -73,11 +89,34 @@ internal sealed partial class RedisCache NotCacheableException.ThrowIfNotCacheable(); ArgumentNullException.ThrowIfNull(generator); var format = FormatFor(policy, forWrite: true, alsoReads: true); + var frame = FrameFor(policy); + if (!frame.IsNone) + { + return format.IsDefault + ? GetOrAddGeneratedAsync(cacheKey, ToRedisKey(cacheKey, token), state, generator, policy, new FramedFormat(default, frame), token) + : GetOrAddGeneratedAsync(cacheKey, ToRedisKey(cacheKey, token), state, generator, policy, new FramedFormat(format, frame), token); + } + return format.IsDefault ? GetOrAddGeneratedAsync(cacheKey, ToRedisKey(cacheKey, token), state, generator, policy, default(PlainFormat), token) : GetOrAddGeneratedAsync(cacheKey, ToRedisKey(cacheKey, token), state, generator, policy, format, token); } + /// The batch get-or-add of an instant with the option on: the anchor is taken where the store lifetime is built, and the store hands it on (IC5, WA4). A twin closure, so today's keeps its size. + private ValueTask[]> GetOrAddBatchAnchored(KeyValuePair[] entries, Func[]>> generator, DateTimeOffset expiration, CachePolicy? policy, CancellationToken token) + where TState : notnull + { + var lifetime = StoreLifetime.AnchoredAt(this, expiration); + return GetOrAddBatchAsync(entries, generator, (pairs, t) => SetCoreAsync(pairs, CallerDuration(expiration), policy, t, expiration, lifetime.Anchor), lifetime, policy, token); + } + + private ValueTask[]> GetOrAddBatchAnchored(KeyValuePair[] entries, TArg argument, Func[]>> generator, DateTimeOffset expiration, CachePolicy? policy, CancellationToken token) + where TState : notnull + { + var lifetime = StoreLifetime.AnchoredAt(this, expiration); + return GetOrAddBatchAsync(entries, argument, generator, (pairs, t) => SetCoreAsync(pairs, CallerDuration(expiration), policy, t, expiration, lifetime.Anchor), lifetime, policy, token); + } + private ValueTask[]> GetOrAddBatchAsync( KeyValuePair[] entries, Func[]>> generator, @@ -128,12 +167,21 @@ internal sealed partial class RedisCache clock: Clock); } - private ValueTask GetOrAddCoreAsync(CacheKey cacheKey, TState state, Func> generator, TimeSpan duration, CachePolicy? policy, CancellationToken token) + private ValueTask GetOrAddCoreAsync(CacheKey cacheKey, TState state, Func> generator, TimeSpan duration, CachePolicy? policy, CancellationToken token, DateTimeOffset? until = null, WriteAnchor anchor = default) { NotCacheableException.ThrowIfNotCacheable(); ArgumentNullException.ThrowIfNull(generator); var redisKey = ToRedisKey(cacheKey, token); var format = FormatFor(policy, forWrite: true, alsoReads: true); + var frame = FrameFor(policy); + if (!frame.IsNone) + { + frame = frame with { Until = until, Anchor = anchor }; + return format.IsDefault + ? GetOrAddInternalAsync(cacheKey, redisKey, state, generator, (policy ?? DefaultPolicy)?.FactoryTimeout, duration, new FramedFormat(default, frame), token) + : GetOrAddInternalAsync(cacheKey, redisKey, state, generator, (policy ?? DefaultPolicy)?.FactoryTimeout, duration, new FramedFormat(format, frame), token); + } + return format.IsDefault ? GetOrAddInternalAsync(cacheKey, redisKey, state, generator, (policy ?? DefaultPolicy)?.FactoryTimeout, duration, default(PlainFormat), token) : GetOrAddInternalAsync(cacheKey, redisKey, state, generator, (policy ?? DefaultPolicy)?.FactoryTimeout, duration, format, token); @@ -168,8 +216,9 @@ internal sealed partial class RedisCache var operation = StartOperation(nameof(GetOrAddAsync)); try { - var value = await ReadStringAsync(redisKey, token).ConfigureAwait(false); - (found, cached, var unreadable) = InterpretReadResult(redisKey, value, KeyLife.Unknown, format, out _, out var frame); + // Under a format with a window the first read is the anchored one, so a hit costs one round trip (FR7). + var value = await (format.Frame.Window > TimeSpan.Zero ? ReadJudgedAsync(redisKey, token) : ReadStringAsync(redisKey, token)).ConfigureAwait(false); + (found, cached, var unreadable) = InterpretReadResult(redisKey, value, format.Frame.Window > TimeSpan.Zero ? KeyLife.Judged : KeyLife.Unknown, format, out _, out var frame); if (frame.ReadAgain) { value = await ReadJudgedAsync(redisKey, token).ConfigureAwait(false); @@ -214,7 +263,10 @@ internal sealed partial class RedisCache ? RunGeneratorAsync(cacheKey, state, generator, factoryTimeout, token) : GenerateAndFillAsync(cacheKey, redisKey, state, generator, factoryTimeout, expiration, format, run)).ConfigureAwait(false); - if (ShouldStoreGenerated(ret) && await SetInternalAsync(cacheKey, redisKey, ret, expiration, format, token).ConfigureAwait(false)) + // The framed branch reports the instant of its frame, set by the store itself (W9, GS1 to GS3). + if (ShouldStoreGenerated(ret) + && await (NeverFramed() ? SetInternalAsync(cacheKey, redisKey, ret, expiration, format, token) : StoreGeneratedAsync(cacheKey, redisKey, ret, expiration, format, run, token)).ConfigureAwait(false) + && NeverFramed()) { run.Expiration = StoredDeadline(expiration); } @@ -274,7 +326,14 @@ internal sealed partial class RedisCache ? RunGeneratorAsync(cacheKey, state, generator, (policy ?? DefaultPolicy)?.FactoryTimeout, token) : GenerateAndFillExpiringAsync(cacheKey, redisKey, state, generator, policy, format, run)).ConfigureAwait(false); - if (_tombstoneGrace is null) + if (_tombstoneGrace is null && !NeverFramed()) + { + // The generator's instant is carried, never rebuilt, and a value that skips fail-safe keeps no window (GI1, W7). + await (generated.SkipFailSafe + ? StoreExpiringAsync(cacheKey, redisKey, generated, policy, new WithoutWindow(format), run, token) + : StoreExpiringAsync(cacheKey, redisKey, generated, policy, format, run, token)).ConfigureAwait(false); + } + else if (_tombstoneGrace is null) { var duration = generated.Expiration is { } expiration ? Remaining(expiration) : PolicyDuration(policy); if (duration is { } lifetime && (!IsDefault(generated.Value) || _cacheNullValues) @@ -297,6 +356,31 @@ internal sealed partial class RedisCache return ret; } + /// The framed store of a generator that names its expiration (GI1): its instant validated from one UTC reading with its anchor, or the policy duration made an instant once; nothing for an instant that passed. + private ValueTask StoreExpiringAsync(CacheKey cacheKey, RedisKey redisKey, GeneratedValue generated, CachePolicy? policy, TFormat format, IInFlightEnd run, CancellationToken token) + where TFormat : struct, IValueFormat + { + if (!GeneratedUntil(generated, policy, out var until, out var anchor) || (IsDefault(generated.Value) && !_cacheNullValues)) + { + return new ValueTask(false); + } + + return StoreGeneratedUntilAsync(cacheKey, redisKey, generated.Value, until, anchor, format, run, token); + } + + /// The instant of a generated value and its anchor: in place of , or a capture of the policy duration. False for an instant that passed. + private bool GeneratedUntil(GeneratedValue generated, CachePolicy? policy, out DateTimeOffset until, out WriteAnchor anchor) + { + if (generated.Expiration is { } at) + { + until = at; + return WriteAnchor.Validate(Clock, at, out anchor) is not null; + } + + anchor = WriteAnchor.Capture(Clock, PolicyDuration(policy), out until); + return true; + } + private TimeSpan? Remaining(DateTimeOffset expiration) { if (expiration == DateTimeOffset.MaxValue) diff --git a/src/UiPath.Caching/Redis/RedisCache.KeyFrame.cs b/src/UiPath.Caching/Redis/RedisCache.KeyFrame.cs new file mode 100644 index 000000000..fdfc3a113 --- /dev/null +++ b/src/UiPath.Caching/Redis/RedisCache.KeyFrame.cs @@ -0,0 +1,309 @@ +using UiPath.Caching.Serialization; + +namespace UiPath.Caching.Redis; + +/// The key commands on a node that reads entry frames: a frame with a window is judged by its logical expiration, never by its key's TTL alone (K1, K2, K4, JR1 to JR5). +internal sealed partial class RedisCache +{ + private enum KeyKind + { + Missing, + Plain, + Tombstone, + Windowed, + } + + private static bool IsWrongType(RedisServerException ex) => ex.Message.StartsWith("WRONGTYPE", StringComparison.OrdinalIgnoreCase); + + private static KeyRead ReadOfKeyReply(RedisResult reply, long sentAt, bool fenced) + { + var parts = ((RedisResult[]?)reply)!; + var timeToLive = (long)parts[2]; + var life = KeyLife.Of(timeToLive < 0 ? null : TimeSpan.FromMilliseconds(timeToLive), sentAt); + switch ((long)parts[0]) + { + case 0: + return new KeyRead(KeyKind.Missing, default, life); + case 3 when fenced: + return new KeyRead(KeyKind.Tombstone, default, life); + case 2: + // The head holds the flags that follow the window; the frame of its first 15 bytes alone has the window. + var head = ((byte[]?)parts[1])!; + head[2] = 1; + return EntryFrame.TryRead(head, out var frame) ? new KeyRead(KeyKind.Windowed, frame, life) : new KeyRead(KeyKind.Plain, default, life); + default: + return new KeyRead(KeyKind.Plain, default, life); + } + } + + /// The read script of the key commands; null when scripts are not available, so the caller reads with commands. + private async ValueTask TryReadKeyByScriptAsync(RedisKey key) + { + if (!IsReadScriptAvailable()) + { + return null; + } + + if (BeforeAnchoredRead is { } before) + { + await before().ConfigureAwait(false); + } + + var sentAt = Clock.GetTimestamp(); + if (await TryReadScriptAsync(FrameScripts.KeyRead, [key], _logReadScriptUnavailable).ConfigureAwait(false) is not { } reply) + { + return null; + } + + if (AfterAnchoredRead is { } after) + { + await after().ConfigureAwait(false); + } + + return ReadOfKeyReply(reply, sentAt, _tombstoneGrace is not null); + } + + /// + /// The first step of K2: one transaction on the master with the first three bytes and the PTTL, taking the timestamp right before it is sent. + /// A value that may be a frame with a window is read again by the anchored read, which judges it with the full grammar. + /// + private async ValueTask ReadKeyByTransactionAsync(RedisKey key, CancellationToken token) + { + token.ThrowIfCancellationRequested(); + if (BeforeAnchoredRead is { } before) + { + await before().ConfigureAwait(false); + } + + var sentAt = Clock.GetTimestamp(); + var transaction = Database.CreateTransaction(); + var head = transaction.StringGetRangeAsync(key, 0, 2, CommandFlags.DemandMaster); + var ttl = transaction.KeyTimeToLiveAsync(key, CommandFlags.DemandMaster); + RedisValue first; + TimeSpan? timeToLive; + try + { + if (!await transaction.ExecuteAsync(CommandFlags.DemandMaster).ConfigureAwait(false)) + { + throw new InvalidOperationException("The read transaction was not committed"); + } + + timeToLive = await ttl.ConfigureAwait(false); + try + { + first = await head.ConfigureAwait(false); + } + catch (RedisServerException ex) when (IsWrongType(ex)) + { + return new KeyRead(KeyKind.Plain, default, KeyLife.Of(timeToLive, sentAt)); + } + } + catch + { + head.Observe(); + ttl.Observe(); + throw; + } + + var firstBytes = ((ReadOnlyMemory)first).Span; + if (_tombstoneGrace is not null && TombstoneValue.IsHead(firstBytes)) + { + return new KeyRead(KeyKind.Tombstone, default, KeyLife.Of(timeToLive, sentAt)); + } + + if (!EntryFrame.LooksWindowed(firstBytes)) + { + return new KeyRead(KeyKind.Plain, default, KeyLife.Of(timeToLive, sentAt)); + } + + var (value, life) = await ReadAtomicAsync(key, token).ConfigureAwait(false); + if (value.IsNull) + { + return new KeyRead(KeyKind.Missing, default, life); + } + + return TryReadFrame(value, out var frame) && frame.HasWindow ? new KeyRead(KeyKind.Windowed, frame, life) : new KeyRead(KeyKind.Plain, default, life); + } + + private async ValueTask ReadKeyAsync(RedisKey key, CancellationToken token) => + await TryReadKeyByScriptAsync(key).ConfigureAwait(false) ?? await ReadKeyByTransactionAsync(key, token).ConfigureAwait(false); + + /// The key's life at the judgment: the logical expiration of a frame with a window, else the deadline of the key; null when the key has ended or has none. + private (TimeSpan Left, DateTimeOffset Deadline)? LogicalLife(in KeyRead read) + { + if (read.Kind is KeyKind.Missing or KeyKind.Tombstone || !read.Life.IsAnchored) + { + return null; + } + + var deadline = AnchoredDeadline(read.Life, out var now); + DateTimeOffset end; + if (read.Kind == KeyKind.Windowed) + { + end = read.Frame.LogicalExpiration(deadline); + } + else if (deadline is { } bound) + { + end = bound; + } + else + { + return null; + } + + return end > now ? (end - now, end) : null; + } + + /// K1: whether the key holds a value that is alive. A frame with a window ends at its logical expiration; a tombstone is no value when the grace is set. + private async Task ExistsUnlessExpiredAsync(RedisKey key) + { + if (await TryReadKeyByScriptAsync(key).ConfigureAwait(false) is { } read) + { + return read.Kind switch + { + KeyKind.Missing or KeyKind.Tombstone => false, + KeyKind.Windowed => LogicalLife(read) is not null, + _ => true, + }; + } + + var flags = ReadFlagsFor(key); + var batch = Database.CreateBatch(); + var exists = batch.KeyExistsAsync(key, flags); + var head = batch.StringGetRangeAsync(key, 0, 2, flags); + batch.Execute(); + RedisValue first; + try + { + var present = await exists.ConfigureAwait(false); + try + { + first = await head.ConfigureAwait(false); + } + catch (RedisServerException ex) when (IsWrongType(ex)) + { + return present; + } + + if (!present) + { + return false; + } + } + catch + { + head.Observe(); + throw; + } + + var firstBytes = ((ReadOnlyMemory)first).Span; + if (_tombstoneGrace is not null && TombstoneValue.IsHead(firstBytes)) + { + return false; + } + + return !EntryFrame.LooksWindowed(firstBytes) || !(await ReadJudgedAsync(key, default).ConfigureAwait(false)).IsNull; + } + + /// K2: the logical life of the key, from one read taken at the send. + private async Task TimeToLiveByFrameAsync(RedisKey key) + { + var read = await ReadKeyAsync(key, default).ConfigureAwait(false); + if (read.Kind == KeyKind.Tombstone) + { + await RepairTombstoneAsync(key).ConfigureAwait(false); + return null; + } + + return LogicalLife(read) is { } life ? life.Left : null; + } + + /// K2: the logical expiration of the key, from one read taken at the send. + private async Task ExpireTimeByFrameAsync(RedisKey key) + { + var read = await ReadKeyAsync(key, default).ConfigureAwait(false); + if (read.Kind == KeyKind.Tombstone) + { + await RepairTombstoneAsync(key).ConfigureAwait(false); + return null; + } + + return LogicalLife(read) is { } life ? life.Deadline.UtcDateTime : null; + } + + /// + /// The deadline a result call reports for a value its run read without one (JR1 to JR5). A frame with a window has none to report, so a value that was + /// rewritten into one since is not paired with a deadline of its own; any other value gets the deadline of this read. + /// + private async ValueTask ReadDeadlineByFrameAsync(CacheKey cacheKey, CancellationToken token) => + await RunAsync( + _read, + StartOperation(nameof(GetOrAddResultAsync)), + static async (s, token) => + { + var read = await s.Self.ReadKeyAsync(s.Self.ToRedisKey(s.Key, token), token).ConfigureAwait(false); + return read.Kind == KeyKind.Windowed || s.Self.LogicalLife(read) is not { } life ? (DateTimeOffset?)null : life.Deadline; + }, + (Self: this, Key: cacheKey), + (DateTimeOffset?)null, + static deadline => deadline is not null, + _logFailure, + token).ConfigureAwait(false); + + /// K4: the add that lost its NX to an expired frame, or to a tombstone when the grace is set, replaces it; any other value, or a frame that is not expired, refuses it. + private async ValueTask AddOverExpiredFrameAsync(RedisKey key, RedisValue serialized, TimeSpan lifetime, TFormat format, CancellationToken token) + where TFormat : struct, IValueFormat + { + var (until, anchor) = NeverFramed() ? (default(DateTimeOffset?), default(WriteAnchor)) : (format.Frame.Until, format.Frame.Anchor); + for (var attempt = 0; attempt < FillAttempts; attempt++) + { + if (SendFormOf(serialized, lifetime, until, anchor) is not { } send) + { + return false; + } + + if (await Database.StringSetAsync(key, send.Bytes, send.Ttl, When.NotExists, CommandFlags.DemandMaster).ConfigureAwait(false)) + { + return true; + } + + var (held, life) = await ReadAtomicOnceAsync(this, key, true, token).ConfigureAwait(false); + if (held.IsNull) + { + continue; + } + + var replaceable = _tombstoneGrace is not null && TombstoneValue.Is(held) + || TryReadFrame(held, out var frame) && frame.HasWindow && !IsAlive(held, life); + if (!replaceable) + { + return false; + } + + var replaced = await FormatRewriteScripts.ReplaceStringAsync( + Database, + key, + held, + (Self: this, Stored: serialized, Life: lifetime, Until: until, Anchor: anchor), + static s => s.Self.SendFormOf(s.Stored, s.Life, s.Until, s.Anchor) ?? (RedisValue.Null, TimeSpan.Zero), + RewriteScriptsOn, + _rewriteScriptRefused).ConfigureAwait(false); + if (replaced is { } done) + { + if (done) + { + return true; + } + } + else + { + return false; + } + } + + return false; + } + + /// What one read of a key learned: its class, the frame when it holds one with a window, and the life of the key from that read. + private readonly record struct KeyRead(KeyKind Kind, EntryFrame Frame, KeyLife Life); +} diff --git a/src/UiPath.Caching/Redis/RedisCache.Migration.cs b/src/UiPath.Caching/Redis/RedisCache.Migration.cs index fc1fe7b12..f42578f31 100644 --- a/src/UiPath.Caching/Redis/RedisCache.Migration.cs +++ b/src/UiPath.Caching/Redis/RedisCache.Migration.cs @@ -18,6 +18,7 @@ public async ValueTask WriteAsync(CacheKey cacheKey, T? value, return StoreOutcome.NotSent; } + // The migration seam writes plain values, so it asks for no frame and keeps today's conversion of the instant (Task 2.4, IC8). format = FormatFor(policy, forWrite: true); duration = CallerDuration(expiration); } diff --git a/src/UiPath.Caching/Redis/RedisCache.Read.cs b/src/UiPath.Caching/Redis/RedisCache.Read.cs index 29b29079d..56e549ac2 100644 --- a/src/UiPath.Caching/Redis/RedisCache.Read.cs +++ b/src/UiPath.Caching/Redis/RedisCache.Read.cs @@ -10,6 +10,11 @@ internal sealed partial class RedisCache NotCacheableException.ThrowIfNotCacheable(); var format = FormatFor(policy, forWrite: false); var redisKey = ToRedisKey(cacheKey, token); + if (FrameFor(policy) is { Window.Ticks: > 0 } frame) + { + return format.Sniff ? GetAsync>(redisKey, new(format, frame), token) : GetAsync>(redisKey, new(default, frame), token); + } + return format.Sniff ? GetAsync(redisKey, format, token) : GetAsync(redisKey, default, token); } @@ -17,6 +22,11 @@ internal sealed partial class RedisCache { NotCacheableException.ThrowIfNotCacheable(); var format = FormatFor(policy, forWrite: false); + if (FrameFor(policy) is { Window.Ticks: > 0 } frame) + { + return format.Sniff ? GetAsyncInternal>(cacheKeys, new(format, frame), token) : GetAsyncInternal>(cacheKeys, new(default, frame), token); + } + return format.Sniff ? GetAsyncInternal(cacheKeys, format, token) : GetAsyncInternal(cacheKeys, default, token); } @@ -24,6 +34,11 @@ internal sealed partial class RedisCache { NotCacheableException.ThrowIfNotCacheable(); var format = FormatFor(policy, forWrite: false); + if (FrameFor(policy) is { Window.Ticks: > 0 } frame) + { + return format.Sniff ? GetCacheEntryInternalAsync>(cacheKey, new(format, frame), token) : GetCacheEntryInternalAsync>(cacheKey, new(default, frame), token); + } + return format.Sniff ? GetCacheEntryInternalAsync(cacheKey, format, token) : GetCacheEntryInternalAsync(cacheKey, default, token); } @@ -31,6 +46,13 @@ public ValueTask> ReadSnapshotAsync(CacheKey cacheKey, CacheP { NotCacheableException.ThrowIfNotCacheable(); var format = FormatFor(policy, forWrite: false); + if (FrameFor(policy) is { Window.Ticks: > 0 } frame) + { + return format.Sniff + ? ReadSnapshotInternalAsync>(cacheKey, new(format, frame), token) + : ReadSnapshotInternalAsync>(cacheKey, new(default, frame), token); + } + return format.Sniff ? ReadSnapshotInternalAsync(cacheKey, format, token) : ReadSnapshotInternalAsync(cacheKey, default, token); @@ -40,6 +62,11 @@ public ValueTask> ReadSnapshotAsync(CacheKey cacheKey, CacheP { NotCacheableException.ThrowIfNotCacheable(); var format = FormatFor(policy, forWrite: false); + if (FrameFor(policy) is { Window.Ticks: > 0 } frame) + { + return format.Sniff ? GetCacheEntriesInternalAsync>(cacheKeys, new(format, frame), token) : GetCacheEntriesInternalAsync>(cacheKeys, new(default, frame), token); + } + return format.Sniff ? GetCacheEntriesInternalAsync(cacheKeys, format, token) : GetCacheEntriesInternalAsync(cacheKeys, default, token); } @@ -231,6 +258,11 @@ private static async ValueTask ReadManyAsync((RedisCache Self, RedisKey[] if (TryReadFrame(value, out var entry)) { + if (entry.HasWindow && !EntryMetadataEnabled) + { + WarnWindowedFrameWithOptionOff(); + } + // 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) @@ -245,6 +277,17 @@ private static async ValueTask ReadManyAsync((RedisCache Self, RedisKey[] return DecodeStored(key, value, format, out undecoded, offerRewrite, quiet); } + private void WarnWindowedFrameWithOptionOff() + { + if (Interlocked.Exchange(ref _windowedFrameWarned, 1) == 0) + { + LogWindowedFrameWithOptionOff(Name); + } + } + + [LoggerMessage(Level = LogLevel.Warning, Message = "The {CacheName} cache has EntryMetadataEnabled off and read a windowed frame: step 2 of the config rollback, which drains windowed frames before the option goes off, was skipped. Its reads and fills judge the frame, but ContainsAsync, the TTL commands and RefreshAsync answer from the key and can over-report or end a value early.")] + private partial void LogWindowedFrameWithOptionOff(string cacheName); + /// 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 @@ -381,8 +424,9 @@ private ValueTask ReadStringAsync(RedisKey redisKey, CancellationTok var windowed = false; try { - var value = await ReadStringAsync(redisKey, token).ConfigureAwait(false); - (found, deserialized, var unreadable) = InterpretReadResult(redisKey, value, KeyLife.Unknown, format, out _, out var frame); + // Under a format with a window the first read is the judged one, so a hit costs one round trip (FR7). + var value = await (format.Frame.Window > TimeSpan.Zero ? ReadJudgedAsync(redisKey, token) : ReadStringAsync(redisKey, token)).ConfigureAwait(false); + (found, deserialized, var unreadable) = InterpretReadResult(redisKey, value, format.Frame.Window > TimeSpan.Zero ? KeyLife.Judged : KeyLife.Unknown, format, out _, out var frame); if (frame.ReadAgain) { value = await ReadJudgedAsync(redisKey, token).ConfigureAwait(false); @@ -431,8 +475,9 @@ private ValueTask ReadStringAsync(RedisKey redisKey, CancellationTok try { - var value = await ReadStringAsync(redisKey, token).ConfigureAwait(false); - (found, ret, var unreadable) = InterpretReadResult(redisKey, value, KeyLife.Unknown, format, out _, out var frame); + // Under a format with a window the first read is the judged one, so a hit costs one round trip (FR7). + var value = await (format.Frame.Window > TimeSpan.Zero ? ReadJudgedAsync(redisKey, token) : ReadStringAsync(redisKey, token)).ConfigureAwait(false); + (found, ret, var unreadable) = InterpretReadResult(redisKey, value, format.Frame.Window > TimeSpan.Zero ? KeyLife.Judged : KeyLife.Unknown, format, out _, out var frame); if (frame.ReadAgain) { value = await ReadJudgedAsync(redisKey, token).ConfigureAwait(false); @@ -485,8 +530,9 @@ private ValueTask ReadStringAsync(RedisKey redisKey, CancellationTok { await EnsureConnectedAsync(_read, token).ConfigureAwait(false); var groups = SlotGroups(redisKeys, _logger); + // Under a format with a window no MGET is sent: every key goes to the judged read (FR7). var groupValues = await PerSlotAsync( - groups, + format.Frame.Window > TimeSpan.Zero ? [] : groups, (Self: this, Keys: redisKeys, Token: token), static (s, group) => s.Self._read.ExecuteAsync(static (r, token) => { @@ -499,8 +545,8 @@ private ValueTask ReadStringAsync(RedisKey redisKey, CancellationTok [], LogRedisCacheException).ConfigureAwait(false); retValues = GetDefaultValues(keys); - List? again = null; - for (var g = 0; g < groups.Length; g++) + List? again = format.Frame.Window > TimeSpan.Zero ? [.. Enumerable.Range(0, keys.Length)] : null; + for (var g = 0; g < groupValues.Length; g++) { var (group, values) = (groups[g], groupValues[g]); // A slot whose read answered nothing reads as misses; the others keep their values. @@ -563,7 +609,11 @@ private ValueTask ReadStringAsync(RedisKey redisKey, CancellationTok return retValues; } - private async ValueTask> GetCacheEntryInternalAsync(CacheKey cacheKey, TFormat format, CancellationToken token, string methodName = nameof(GetCacheEntryInternalAsync)) + private ValueTask> GetCacheEntryInternalAsync(CacheKey cacheKey, TFormat format, CancellationToken token, string methodName = nameof(GetCacheEntryInternalAsync)) + where TFormat : struct, IValueFormat => + format.Frame.Window > TimeSpan.Zero ? GetCacheEntryAnchoredAsync(cacheKey, format, token, methodName) : GetCacheEntryReadAsync(cacheKey, format, token, methodName); + + private async ValueTask> GetCacheEntryReadAsync(CacheKey cacheKey, TFormat format, CancellationToken token, string methodName) where TFormat : struct, IValueFormat { token.ThrowIfCancellationRequested(); @@ -635,7 +685,13 @@ private ValueTask ReadStringAsync(RedisKey redisKey, CancellationTok return ret; } - private async ValueTask> ReadSnapshotInternalAsync(CacheKey cacheKey, TFormat format, CancellationToken token, StrongBox? raw = null) + private ValueTask> ReadSnapshotInternalAsync(CacheKey cacheKey, TFormat format, CancellationToken token, StrongBox? raw = null) + where TFormat : struct, IValueFormat => + format.Frame.Window > TimeSpan.Zero + ? ReadSnapshotAnchoredAsync(cacheKey, format, token, raw) + : ReadSnapshotPlainAsync(cacheKey, format, token, raw); + + private async ValueTask> ReadSnapshotPlainAsync(CacheKey cacheKey, TFormat format, CancellationToken token, StrongBox? raw) where TFormat : struct, IValueFormat { token.ThrowIfCancellationRequested(); @@ -784,9 +840,10 @@ private SnapshotRead InterpretSnapshot(RedisKey key, RedisValue v { await EnsureConnectedAsync(_read, token).ConfigureAwait(false); var groups = SlotGroups(redisKeys, _logger); - List? again = null; + List? again = format.Frame.Window > TimeSpan.Zero ? [.. Enumerable.Range(0, keys.Length)] : null; + // Under a format with a window no pair is sent: every key goes to the anchored read (FR7). var groupReads = await PerSlotAsync( - groups, + format.Frame.Window > TimeSpan.Zero ? [] : groups, (Self: this, Keys: redisKeys, Token: token), static async (s, group) => { @@ -801,7 +858,7 @@ static async (s, group) => null, LogRedisCacheException).ConfigureAwait(false); - for (var g = 0; g < groups.Length; g++) + for (var g = 0; g < groupReads.Length; g++) { // A slot whose read did not commit reads as misses; the others keep their entries. if (groupReads[g] is not { } result) diff --git a/src/UiPath.Caching/Redis/RedisCache.ReadWindowed.cs b/src/UiPath.Caching/Redis/RedisCache.ReadWindowed.cs new file mode 100644 index 000000000..133c2be4c --- /dev/null +++ b/src/UiPath.Caching/Redis/RedisCache.ReadWindowed.cs @@ -0,0 +1,118 @@ +using UiPath.Caching.Serialization; + +namespace UiPath.Caching.Redis; + +/// The entry read under a format with a window: the anchored read first, since only it can say "fresh" and publish a deadline (FR7, G4). +internal sealed partial class RedisCache +{ + private async ValueTask> GetCacheEntryAnchoredAsync(CacheKey cacheKey, TFormat format, CancellationToken token, string methodName) + where TFormat : struct, IValueFormat + { + token.ThrowIfCancellationRequested(); + var redisKey = ToRedisKey(cacheKey, token); + if (!IsConnected) + { + return DefaultEntry(); + } + + var operation = StartOperation(methodName); + ICacheEntry ret = DefaultEntry(); + try + { + var (value, life) = await ReadAtomicAsync(redisKey, token).ConfigureAwait(false); + if (!life.IsAnchored) + { + operation.Stop(); + return ret; + } + + var (found, deserialized, unreadable) = InterpretReadResult(redisKey, value, life, format, out _, out var frame); + if (found) + { + ret = EntryOf(deserialized, frame.LogicalExpiration ?? DateTimeOffset.MaxValue, frame); + } + + if (unreadable != 0) + { + await RemoveUnreadableAsync(redisKey, value, unreadable, token).ConfigureAwait(false); + } + + operation.Stop(); + } + catch (OperationCanceledException) when (token.IsCancellationRequested) + { + operation.Cancel(); + throw; + } + catch (Exception ex) when (format.Handles(ex)) + { + operation.Stop(); + LogRedisCacheException(ex); + } + finally + { + TrackRead(operation, ret.Found, redisKey); + } + + return ret; + } + + /// The snapshot read under a format with a window: one anchored read on the master, no plain pair first (FR7, AN3, AN4). + private async ValueTask> ReadSnapshotAnchoredAsync(CacheKey cacheKey, TFormat format, CancellationToken token, StrongBox? raw) + where TFormat : struct, IValueFormat + { + token.ThrowIfCancellationRequested(); + if (!IsConnected) + { + return default; + } + + RedisKey redisKey; + try + { + redisKey = ToRedisKey(cacheKey, token); + } + catch (Exception ex) when (ex is not OutOfMemoryException && !(ex is OperationCanceledException && token.IsCancellationRequested)) + { + LogRedisCacheException(ex); + return default; + } + + var operation = StartOperation(nameof(ReadSnapshotAsync)); + var found = false; + try + { + var (value, life) = await ReadAtomicAsync(redisKey, token, onMaster: true).ConfigureAwait(false); + if (!life.IsAnchored) + { + operation.Stop(); + return default; + } + + var snapshot = InterpretSnapshot(redisKey, value, life, DateTimeOffset.MaxValue, format, out _); + if (raw is not null) + { + raw.Value = value; + } + + found = snapshot.Outcome == SnapshotOutcome.Found; + operation.Stop(); + return snapshot; + } + catch (OperationCanceledException) when (token.IsCancellationRequested) + { + operation.Cancel(); + throw; + } + catch (Exception ex) when (ex is not OutOfMemoryException) + { + operation.Stop(); + LogRedisCacheException(ex); + return default; + } + finally + { + TrackRead(operation, found, redisKey); + } + } +} diff --git a/src/UiPath.Caching/Redis/RedisCache.Result.cs b/src/UiPath.Caching/Redis/RedisCache.Result.cs index 584051043..0e4be55db 100644 --- a/src/UiPath.Caching/Redis/RedisCache.Result.cs +++ b/src/UiPath.Caching/Redis/RedisCache.Result.cs @@ -11,7 +11,9 @@ public ValueTask> GetOrAddResultAsync(CacheKey cacheKey, Func< => GetOrAddResultCoreAsync(cacheKey, GeneratorRecorder.For(generator), CallerDuration(expiration), policy, token); public ValueTask> GetOrAddResultAsync(CacheKey cacheKey, Func> generator, DateTimeOffset expiration, CachePolicy? policy, CancellationToken token = default) - => GetOrAddResultCoreAsync(cacheKey, GeneratorRecorder.For(generator), CallerDuration(expiration), policy, token); + => EntryMetadataEnabled + ? GetOrAddResultCoreAsync(cacheKey, GeneratorRecorder.For(generator), CallerDurationAnchored(expiration, out var anchor), policy, token, expiration, anchor) + : GetOrAddResultCoreAsync(cacheKey, GeneratorRecorder.For(generator), CallerDuration(expiration), policy, token); public ValueTask> GetOrAddResultAsync(CacheKey cacheKey, TState state, Func> generator, CachePolicy? policy, CancellationToken token = default) => GetOrAddResultCoreAsync(cacheKey, GeneratorRecorder.For(state, generator), PolicyDuration(policy), policy, token); @@ -20,7 +22,9 @@ public ValueTask> GetOrAddResultAsync(CacheKey cacheKe => GetOrAddResultCoreAsync(cacheKey, GeneratorRecorder.For(state, generator), CallerDuration(expiration), policy, token); public ValueTask> GetOrAddResultAsync(CacheKey cacheKey, TState state, Func> generator, DateTimeOffset expiration, CachePolicy? policy, CancellationToken token = default) - => GetOrAddResultCoreAsync(cacheKey, GeneratorRecorder.For(state, generator), CallerDuration(expiration), policy, token); + => EntryMetadataEnabled + ? GetOrAddResultCoreAsync(cacheKey, GeneratorRecorder.For(state, generator), CallerDurationAnchored(expiration, out var anchor), policy, token, expiration, anchor) + : GetOrAddResultCoreAsync(cacheKey, GeneratorRecorder.For(state, generator), CallerDuration(expiration), policy, token); ValueTask> IResultCache.GetOrAddResultAsync(Span cacheKey, Func> generator, CachePolicy? policy, CancellationToken token) where T : default @@ -32,7 +36,9 @@ ValueTask> IResultCache.GetOrAddResultAsync(Span cacheKe ValueTask> IResultCache.GetOrAddResultAsync(Span cacheKey, Func> generator, DateTimeOffset expiration, CachePolicy? policy, CancellationToken token) where T : default - => GetOrAddResultCoreAsync(new CacheKey(cacheKey), GeneratorRecorder.For(generator), CallerDuration(expiration), policy, token); + => EntryMetadataEnabled + ? GetOrAddResultCoreAsync(new CacheKey(cacheKey), GeneratorRecorder.For(generator), CallerDurationAnchored(expiration, out var anchor), policy, token, expiration, anchor) + : GetOrAddResultCoreAsync(new CacheKey(cacheKey), GeneratorRecorder.For(generator), CallerDuration(expiration), policy, token); ValueTask> IResultCache.GetOrAddResultAsync(Span cacheKey, TState state, Func> generator, CachePolicy? policy, CancellationToken token) where T : default @@ -44,7 +50,9 @@ ValueTask> IResultCache.GetOrAddResultAsync(Span ValueTask> IResultCache.GetOrAddResultAsync(Span cacheKey, TState state, Func> generator, DateTimeOffset expiration, CachePolicy? policy, CancellationToken token) where T : default - => GetOrAddResultCoreAsync(new CacheKey(cacheKey), GeneratorRecorder.For(state, generator), CallerDuration(expiration), policy, token); + => EntryMetadataEnabled + ? GetOrAddResultCoreAsync(new CacheKey(cacheKey), GeneratorRecorder.For(state, generator), CallerDurationAnchored(expiration, out var anchor), policy, token, expiration, anchor) + : GetOrAddResultCoreAsync(new CacheKey(cacheKey), GeneratorRecorder.For(state, generator), CallerDuration(expiration), policy, token); private async ValueTask> AttributeAsync(ValueTask shared, IInFlightRun run, GeneratorRecorder recorder, CacheKey cacheKey, CancellationToken token) { @@ -53,6 +61,15 @@ private async ValueTask> AttributeAsync(ValueTask shared, return new CacheResult(value, expiration, recorder.Ran); } + /// As , on a node that reads entry frames: the deadline is read by , and never belongs to another value than the joined one (JR1 to JR5). + private async ValueTask> AttributeByFrameAsync(ValueTask shared, IInFlightRun run, GeneratorRecorder recorder, CacheKey cacheKey, TFormat format, CancellationToken token) + where TFormat : struct, IValueFormat + { + var value = await shared.ConfigureAwait(false); + var expiration = run.ExpirationUnread ? await ReadDeadlineByFrameAsync(cacheKey, token).ConfigureAwait(false) : run.Expiration; + return new CacheResult(value, expiration, recorder.Ran); + } + /// The deadline of a hit that a plain call's read found without its TTL: one PTTL, only for a result call that joined that read. A separate command after the shared GET: if the key is rewritten in between, the deadline is the new value's; if it is deleted, null. private async ValueTask ReadDeadlineAsync(CacheKey cacheKey, CancellationToken token) { @@ -60,10 +77,19 @@ private async ValueTask> AttributeAsync(ValueTask shared, return left is { } lifetime ? StoredDeadline(lifetime) : null; } - private ValueTask> GetOrAddResultCoreAsync(CacheKey cacheKey, GeneratorRecorder recorder, TimeSpan duration, CachePolicy? policy, CancellationToken token) + private ValueTask> GetOrAddResultCoreAsync(CacheKey cacheKey, GeneratorRecorder recorder, TimeSpan duration, CachePolicy? policy, CancellationToken token, DateTimeOffset? until = null, WriteAnchor anchor = default) { NotCacheableException.ThrowIfNotCacheable(); var format = FormatFor(policy, forWrite: true, alsoReads: true); + var frame = FrameFor(policy); + if (!frame.IsNone) + { + frame = frame with { Until = until, Anchor = anchor }; + return format.IsDefault + ? GetOrAddResultCoreAsync(cacheKey, recorder, duration, policy, new FramedFormat(default, frame), token) + : GetOrAddResultCoreAsync(cacheKey, recorder, duration, policy, new FramedFormat(format, frame), token); + } + return format.IsDefault ? GetOrAddResultCoreAsync(cacheKey, recorder, duration, policy, default(PlainFormat), token) : GetOrAddResultCoreAsync(cacheKey, recorder, duration, policy, format, token); @@ -79,7 +105,7 @@ private ValueTask> GetOrAddResultCoreAsync(CacheKey c static (args, run) => args.Cache.ReadOrGenerateResultAsync(args.Key, args.RedisKey, args.Recorder, args.FactoryTimeout, args.Duration, args.Format, run), token, out var flight); - return AttributeAsync(shared, flight, recorder, cacheKey, token); + return EntryMetadataEnabled ? AttributeByFrameAsync(shared, flight, recorder, cacheKey, format, token) : AttributeAsync(shared, flight, recorder, cacheKey, token); } /// The lifetime a write kept, as the deadline to report; none for an entry without expiry. @@ -112,7 +138,9 @@ private ValueTask> GetOrAddResultCoreAsync(CacheKey c ? RunGeneratorAsync(cacheKey, recorder.Generator, static (g, ct) => g(ct), factoryTimeout, token) : GenerateAndFillAsync(cacheKey, redisKey, recorder.Generator, static (g, ct) => g(ct), factoryTimeout, duration, format, run)).ConfigureAwait(false); // Only a value that was written has an expiration to report. - if (_tombstoneGrace is null && (!IsDefault(ret) || _cacheNullValues) && await SetInternalAsync(cacheKey, redisKey, ret, duration, format, token).ConfigureAwait(false)) + if (_tombstoneGrace is null && (!IsDefault(ret) || _cacheNullValues) + && await (NeverFramed() ? SetInternalAsync(cacheKey, redisKey, ret, duration, format, token) : StoreGeneratedAsync(cacheKey, redisKey, ret, duration, format, run, token)).ConfigureAwait(false) + && NeverFramed()) { run.Expiration = StoredDeadline(duration); } diff --git a/src/UiPath.Caching/Redis/RedisCache.Stamped.cs b/src/UiPath.Caching/Redis/RedisCache.Stamped.cs index 8d28b2b0b..c31a5d264 100644 --- a/src/UiPath.Caching/Redis/RedisCache.Stamped.cs +++ b/src/UiPath.Caching/Redis/RedisCache.Stamped.cs @@ -9,21 +9,20 @@ internal sealed partial class RedisCache : IStampedTier { NotCacheableException.ThrowIfNotCacheable(); var format = FormatFor(policy, forWrite: false); + if (FrameFor(policy) is { Window.Ticks: > 0 } frame) + { + return format.Sniff + ? ReadStampedCoreAsync>(cacheKey, new(format, frame), token) + : ReadStampedCoreAsync>(cacheKey, new(default, frame), token); + } + return format.Sniff ? ReadStampedCoreAsync(cacheKey, format, token) : ReadStampedCoreAsync(cacheKey, default, token); } - public ValueTask WriteIfStampAsync(CacheKey cacheKey, T? value, DateTimeOffset expiration, CachePolicy? policy, object? stamp, CancellationToken token) - { - NotCacheableException.ThrowIfNotCacheable(); - var redisKey = ToRedisKey(cacheKey, token); - var format = FormatFor(policy, forWrite: true, alsoReads: true); - var expected = stamp is RedisValue seen ? seen : RedisValue.Null; - return format.IsDefault - ? WriteIfStampCoreAsync(cacheKey, redisKey, value, expiration, expected, default(PlainFormat), token) - : WriteIfStampCoreAsync(cacheKey, redisKey, value, expiration, expected, format, token); - } + public ValueTask WriteIfStampAsync(CacheKey cacheKey, T? value, DateTimeOffset expiration, CachePolicy? policy, object? stamp, CancellationToken token) => + WriteIfStampAsync(cacheKey, value, expiration, policy, stamp, token, default); public bool Holds(object? stamp, T? value, CachePolicy? policy) { @@ -57,16 +56,45 @@ public bool Holds(object? stamp, T? value, CachePolicy? policy) } } + /// The stamped write with the anchor of its deadline; a caller without one has its instant anchored here when a frame is written. + internal ValueTask WriteIfStampAsync(CacheKey cacheKey, T? value, DateTimeOffset expiration, CachePolicy? policy, object? stamp, CancellationToken token, WriteAnchor anchor) + { + NotCacheableException.ThrowIfNotCacheable(); + var redisKey = ToRedisKey(cacheKey, token); + var format = FormatFor(policy, forWrite: true, alsoReads: true); + var expected = stamp is RedisValue seen ? seen : RedisValue.Null; + var frame = FrameFor(policy); + if (!frame.IsNone) + { + // Both branches of the stamped write take the one anchor of the deadline (O3a, O3b); a step back that already happened is the boundary (WL2). + if (!anchor.IsSet && expiration != DateTimeOffset.MaxValue && WriteAnchor.Validate(Clock, expiration, out anchor) is null) + { + return new ValueTask(StampedWrite.Failed); + } + + var anchored = new AnchoredSend(expiration, anchor); + return format.IsDefault + ? WriteIfStampCoreAsync(cacheKey, redisKey, value, anchored, expected, new FramedFormat(default, frame), token) + : WriteIfStampCoreAsync(cacheKey, redisKey, value, anchored, expected, new FramedFormat(format, frame), token); + } + + return format.IsDefault + ? WriteIfStampCoreAsync(cacheKey, redisKey, value, new PlainSend(expiration), expected, default(PlainFormat), token) + : WriteIfStampCoreAsync(cacheKey, redisKey, value, new PlainSend(expiration), expected, format, token); + } + private async ValueTask<(SnapshotRead Snapshot, object? Stamp)> ReadStampedCoreAsync(CacheKey cacheKey, TFormat format, CancellationToken token) where TFormat : struct, IValueFormat { var raw = new StrongBox(); var snapshot = await ReadSnapshotInternalAsync(cacheKey, format, token, raw).ConfigureAwait(false); - return (snapshot, snapshot.Outcome is SnapshotOutcome.Found or SnapshotOutcome.Unreadable ? (object)raw.Value : null); + // An expired frame is absent, and its bytes are the stamp, so the write replaces exactly them (K7). + return (snapshot, snapshot.Outcome is SnapshotOutcome.Found or SnapshotOutcome.Unreadable || (snapshot.Outcome == SnapshotOutcome.Absent && TryReadFrame(raw.Value, out _)) ? (object)raw.Value : null); } - private async ValueTask WriteIfStampCoreAsync(CacheKey cacheKey, RedisKey redisKey, T? value, DateTimeOffset deadline, RedisValue expected, TFormat format, CancellationToken token) + private async ValueTask WriteIfStampCoreAsync(CacheKey cacheKey, RedisKey redisKey, T? value, TDeadline deadline, RedisValue expected, TFormat format, CancellationToken token) where TFormat : struct, IValueFormat + where TDeadline : struct, IFillDeadline { token.ThrowIfCancellationRequested(); if (!IsConnected) @@ -88,19 +116,23 @@ private async ValueTask WriteIfStampCoreAsync(CacheKey NoteWritten(redisKey); var (serialized, payload) = isNull ? (RedisValue.EmptyString, default(SerializedPayload)) : SerializeValue(value, format); _auditKeySize?.Invoke(Logged(cacheKey, redisKey, typeof(T)), serialized); + if (!NeverFramed()) + { + serialized = FramedUntil(serialized, deadline.At, format.Frame).Stored; + } + using (payload) { var written = await _write.ExecuteAsync(static async (s, token) => { token.ThrowIfCancellationRequested(); - var remaining = s.Self.RemainingOrZero(s.Deadline); - if (remaining <= TimeSpan.Zero) + if (s.Deadline.Send(s.Self, s.Serialized) is not { } send) { return null; } return s.Expected.IsNull - ? await s.Self.StoreIfAbsentAsync(s.Key, s.Serialized, remaining).ConfigureAwait(false) + ? await s.Self.StoreIfAbsentAsync(s.Key, send.Bytes, send.Ttl).ConfigureAwait(false) : await s.Self.ReplaceIfUnchangedAsync(s.Key, s.Expected, s.Serialized, s.Deadline, new ChangeRun()).ConfigureAwait(false); }, (Self: this, Key: redisKey, Serialized: serialized, Deadline: deadline, Expected: expected), diff --git a/src/UiPath.Caching/Redis/RedisCache.Tombstone.cs b/src/UiPath.Caching/Redis/RedisCache.Tombstone.cs index f83218173..6a75a810a 100644 --- a/src/UiPath.Caching/Redis/RedisCache.Tombstone.cs +++ b/src/UiPath.Caching/Redis/RedisCache.Tombstone.cs @@ -10,6 +10,13 @@ internal sealed partial class RedisCache : IFencedFillTier /// Sets the key's deadline (ARGV[1], Unix milliseconds) unless it holds a tombstone, in one step. private const string ExpireUnlessTombstoneScript = "local ok, h = pcall(redis.call, 'GETRANGE', KEYS[1], 0, 1) if ok then local a, b = string.byte(h, 1, 2) if a == 15 and b and b >= 48 and b <= 57 then return 0 end end return redis.call('PEXPIREAT', KEYS[1], ARGV[1])"; + /// How long a frame-aware node sends no refresh after the server refused its script. + private static readonly TimeSpan RefreshScriptRetryAfter = TimeSpan.FromMinutes(5); + + private int _refreshScriptAnswered; + private int _refreshScriptRefused; + private long _refreshScriptRefusedAt; + private enum UnreadableReplace { Stored, @@ -19,12 +26,18 @@ private enum UnreadableReplace public bool IsFenced => _tombstoneGrace is not null; - /// Runs after a fill has judged a tombstone replaceable and before it swaps it; tests land a removal there. + /// Runs after a fill has judged a tombstone replaceable, or found an expired frame, and before it swaps it; tests land a write or a removal there. internal Func? BeforeTombstoneSwap { get; set; } /// Runs after a refresh without scripts has inspected the key and before it changes it; tests land a removal there. internal Func? BeforeRefreshChange { get; set; } + /// Runs after a frame-aware refresh has built its arguments and before it sends the script; tests change the key or move a clock there. + internal Func? BeforeRefreshSend { get; set; } + + /// The refresh script a frame-aware node sends; a test gives it another option word for the unwrap. + internal string RefreshScript { get; set; } = FrameScripts.Refresh; + /// Runs after a fill has read a value it cannot read and before it replaces those bytes; tests land a removal there. internal Func? BeforeUnreadableReplace { get; set; } @@ -32,10 +45,10 @@ private enum UnreadableReplace internal Action? AfterFillRead { get; set; } private protected override Task TimeToLiveOfAsync(RedisKey key) => - _tombstoneGrace is null ? base.TimeToLiveOfAsync(key) : TimeToLiveUnlessTombstoneAsync(key); + EntryMetadataEnabled ? TimeToLiveByFrameAsync(key) : _tombstoneGrace is null ? base.TimeToLiveOfAsync(key) : TimeToLiveUnlessTombstoneAsync(key); private protected override Task ExpireTimeOfAsync(RedisKey key) => - _tombstoneGrace is null ? base.ExpireTimeOfAsync(key) : ExpireTimeUnlessTombstoneAsync(key); + EntryMetadataEnabled ? ExpireTimeByFrameAsync(key) : _tombstoneGrace is null ? base.ExpireTimeOfAsync(key) : ExpireTimeUnlessTombstoneAsync(key); /// A refresh that is not awaited answers nothing. private static bool IsOne(RedisResult? reply) => reply is { IsNull: false } && (long)reply == 1; @@ -127,7 +140,7 @@ private async Task TombstoneKeysAsync(RedisKey[] keys) } private Task ExistsAsync(RedisKey key) => - _tombstoneGrace is null ? Database.KeyExistsAsync(key, ReadFlagsFor(key)) : ExistsUnlessTombstoneAsync(key); + EntryMetadataEnabled ? ExistsUnlessExpiredAsync(key) : _tombstoneGrace is null ? Database.KeyExistsAsync(key, ReadFlagsFor(key)) : ExistsUnlessTombstoneAsync(key); private async Task ExistsUnlessTombstoneAsync(RedisKey key) { @@ -212,6 +225,54 @@ private async ValueTask RefreshUnlessTombstoneAsync(RedisKey key, DateTime return await transaction.ExecuteAsync(RefreshFlags).ConfigureAwait(false); } + + /// + /// The refresh of a frame-aware node: the refresh script and no other command, whatever ReadScriptsEnabled says. It never changes a frame with a window; every other value + /// gets the command of today, in one step on the server. The gate is asked here, at the send, and the arguments are built again for each attempt of the write pipeline. + /// + private async ValueTask ExpireFrameAwareAsync(RedisKey key, DateTime? expiration) + { + if (Volatile.Read(ref _refreshScriptRefused) != 0 && Clock.GetElapsedTime(Volatile.Read(ref _refreshScriptRefusedAt)) < RefreshScriptRetryAfter) + { + return false; + } + + RedisValue[] arguments = + [ + expiration is { } at ? Math.Max(1, new DateTimeOffset(at.ToUniversalTime()).ToUnixTimeMilliseconds()) : FrameScripts.Never, + FrameWrites.Allowed ? 1 : 0, + ]; + if (BeforeRefreshSend is { } hook) + { + await hook().ConfigureAwait(false); + } + + // Until a refresh script has answered, and for the first call after a pause, the caller awaits it: a refusal is not seen on a fire-and-forget send. + var primed = Volatile.Read(ref _refreshScriptAnswered) != 0; + try + { + var reply = await Database.ScriptEvaluateAsync(RefreshScript, [key], arguments, primed ? RefreshFlags : CommandFlags.DemandMaster).ConfigureAwait(false); + if (primed) + { + return IsOne(reply); + } + + Volatile.Write(ref _refreshScriptAnswered, 1); + return (RefreshFlags & CommandFlags.FireAndForget) == 0 && IsOne(reply); + } + catch (Exception ex) when (RedisUtils.RefusesScript(ex)) + { + Volatile.Write(ref _refreshScriptAnswered, 0); + Volatile.Write(ref _refreshScriptRefusedAt, Clock.GetTimestamp()); + Volatile.Write(ref _refreshScriptRefused, 1); + LogRefreshScriptRefused(ex, Name); + return false; + } + } + + [LoggerMessage(Level = LogLevel.Warning, Message = "The server refused the refresh script of the {CacheName} cache. With EntryMetadataEnabled the refresh runs only as a script, so its user needs EVAL, and RefreshAsync changes nothing until the server accepts it; the script is sent again in five minutes.")] + private partial void LogRefreshScriptRefused(Exception ex, string cacheName); + private async ValueTask HoldsTombstoneAsync(RedisKey key) => IsTombstoneHead(await Database.StringGetRangeAsync(key, 0, 1, CommandFlags.DemandMaster).ConfigureAwait(false)); @@ -294,8 +355,16 @@ private async ValueTask AddOverTombstoneAsync(RedisKey key, RedisValue ser } /// Replaces the unreadable bytes the key holds, and only those: a removal or write that landed since has changed the key, which is for the fill to decide again. - private async ValueTask ReplaceUnreadableAsync(CacheKey cacheKey, RedisKey redisKey, T? value, DateTimeOffset deadline, TFormat format, CancellationToken token) + private ValueTask ReplaceUnreadableAsync(CacheKey cacheKey, RedisKey redisKey, T? value, DateTimeOffset deadline, TFormat format, CancellationToken token) + where TFormat : struct, IValueFormat => + NeverFramed() + ? ReplaceUnreadableAsync(cacheKey, redisKey, value, new PlainSend(deadline), format, token) + : ReplaceUnreadableAsync(cacheKey, redisKey, value, new AnchoredSend(deadline, format.Frame.Anchor), format, token); + + /// As the overload above, with the deadline whose anchor its replace evaluates after the read (WS4). + private async ValueTask ReplaceUnreadableAsync(CacheKey cacheKey, RedisKey redisKey, T? value, TDeadline deadline, TFormat format, CancellationToken token) where TFormat : struct, IValueFormat + where TDeadline : struct, IFillDeadline { token.ThrowIfCancellationRequested(); NoteWritten(redisKey); @@ -329,9 +398,14 @@ private async ValueTask ReplaceUnreadableAsync(Ca var isNull = IsDefault(value); var (serialized, payload) = isNull ? (RedisValue.EmptyString, default(SerializedPayload)) : SerializeValue(value, format); _auditKeySize?.Invoke(Logged(cacheKey, redisKey, typeof(T)), serialized); + if (!NeverFramed()) + { + serialized = FramedUntil(serialized, deadline.At, format.Frame).Stored; + } + using (payload) { - return await FormatRewriteScripts.ReplaceStringAsync(Database, redisKey, held, serialized, () => RemainingOrZero(deadline), RewriteScriptsOn, _rewriteScriptRefused).ConfigureAwait(false) switch + return await ReplaceUntilAsync(redisKey, held, serialized, deadline).ConfigureAwait(false) switch { true => UnreadableReplace.Stored, false => UnreadableReplace.Changed, diff --git a/src/UiPath.Caching/Redis/RedisCache.Write.cs b/src/UiPath.Caching/Redis/RedisCache.Write.cs index 25dc961ac..8c32a76fa 100644 --- a/src/UiPath.Caching/Redis/RedisCache.Write.cs +++ b/src/UiPath.Caching/Redis/RedisCache.Write.cs @@ -31,7 +31,9 @@ public ValueTask SetAsync(CacheKey cacheKey, T? value, TimeSpan expirat SetCoreAsync(cacheKey, value, CallerDuration(expiration), policy, token); public ValueTask SetAsync(CacheKey cacheKey, T? value, DateTimeOffset expiration, CachePolicy? policy, CancellationToken token = default) => - SetCoreAsync(cacheKey, value, CallerDuration(expiration), policy, token); + EntryMetadataEnabled + ? SetCoreAsync(cacheKey, value, CallerDurationAnchored(expiration, out var anchor), policy, token, expiration, anchor) + : SetCoreAsync(cacheKey, value, CallerDuration(expiration), policy, token); public ValueTask SetAsync(KeyValuePair[] keyValues, CachePolicy? policy, CancellationToken token = default) => SetCoreAsync(keyValues, PolicyDuration(policy), policy, token); @@ -40,7 +42,9 @@ public ValueTask SetAsync(KeyValuePair[] keyValues, TimeS SetCoreAsync(keyValues, CallerDuration(expiration), policy, token); public ValueTask SetAsync(KeyValuePair[] keyValues, DateTimeOffset expiration, CachePolicy? policy, CancellationToken token = default) => - SetCoreAsync(keyValues, CallerDuration(expiration), policy, token); + EntryMetadataEnabled + ? SetCoreAsync(keyValues, CallerDurationAnchored(expiration, out var anchor), policy, token, expiration, anchor) + : SetCoreAsync(keyValues, CallerDuration(expiration), policy, token); public ValueTask TryAddAsync(CacheKey cacheKey, T? value, CachePolicy? policy, CancellationToken token = default) => TryAddCoreAsync(cacheKey, value, PolicyDuration(policy), policy, token); @@ -49,7 +53,9 @@ public ValueTask TryAddAsync(CacheKey cacheKey, T? value, TimeSpan expi TryAddCoreAsync(cacheKey, value, CallerDuration(expiration), policy, token); public ValueTask TryAddAsync(CacheKey cacheKey, T? value, DateTimeOffset expiration, CachePolicy? policy, CancellationToken token = default) => - TryAddCoreAsync(cacheKey, value, CallerDuration(expiration), policy, token); + EntryMetadataEnabled + ? TryAddCoreAsync(cacheKey, value, CallerDurationAnchored(expiration, out var anchor), policy, token, expiration, anchor) + : TryAddCoreAsync(cacheKey, value, CallerDuration(expiration), policy, token); private async ValueTask RefreshCoreAsync(CacheKey cacheKey, DateTimeOffset expiration, CancellationToken token) { @@ -62,7 +68,18 @@ private async ValueTask RefreshCoreAsync(CacheKey cacheKey, DateTimeOff var operation = StartOperation(); try { - if (expiration == DateTimeOffset.MaxValue) + if (EntryMetadataEnabled) + { + ret = await _write.ExecuteAsync(static (s, token) => + { + token.ThrowIfCancellationRequested(); + return s.Self.ExpireFrameAwareAsync(s.Key, s.Expiration == DateTimeOffset.MaxValue ? null : s.Expiration.UtcDateTime); + }, + (Self: this, Key: redisKey, Expiration: expiration), + default, + token).ConfigureAwait(false); + } + else if (expiration == DateTimeOffset.MaxValue) { ret = await _write.ExecuteAsync(static (s, token) => { @@ -105,30 +122,58 @@ private async ValueTask RefreshCoreAsync(CacheKey cacheKey, DateTimeOff return ret; } - private ValueTask SetCoreAsync(CacheKey cacheKey, T? value, TimeSpan duration, CachePolicy? policy, CancellationToken token) + private ValueTask SetCoreAsync(CacheKey cacheKey, T? value, TimeSpan duration, CachePolicy? policy, CancellationToken token, DateTimeOffset? until = null, WriteAnchor anchor = default) { NotCacheableException.ThrowIfNotCacheable(); var redisKey = ToRedisKey(cacheKey, token); var format = FormatFor(policy, forWrite: true); + var frame = FrameFor(policy); + if (!frame.IsNone) + { + frame = frame with { Until = until, Anchor = anchor }; + return format.IsDefault + ? SetFramedAsync(cacheKey, redisKey, value, duration, new FramedFormat(default, frame), token) + : SetFramedAsync(cacheKey, redisKey, value, duration, new FramedFormat(format, frame), token); + } + return format.IsDefault ? SetInternalAsync(cacheKey, redisKey, value, duration, default(PlainFormat), token) : SetInternalAsync(cacheKey, redisKey, value, duration, format, token); } - private ValueTask SetCoreAsync(KeyValuePair[] keyValues, TimeSpan duration, CachePolicy? policy, CancellationToken token) + private ValueTask SetCoreAsync(KeyValuePair[] keyValues, TimeSpan duration, CachePolicy? policy, CancellationToken token, DateTimeOffset? until = null, WriteAnchor anchor = default) { NotCacheableException.ThrowIfNotCacheable(); var format = FormatFor(policy, forWrite: true); + var frame = FrameFor(policy); + if (!frame.IsNone) + { + // A many-key write asks the gate once for the batch (W4). + frame = frame with { Until = until, Anchor = anchor }; + return format.IsDefault + ? SetInternalAsync(keyValues, duration, new FramedFormat(default, frame), token) + : SetInternalAsync(keyValues, duration, new FramedFormat(format, frame), token); + } + return format.IsDefault ? SetInternalAsync(keyValues, duration, default(PlainFormat), token) : SetInternalAsync(keyValues, duration, format, token); } - private ValueTask TryAddCoreAsync(CacheKey cacheKey, T? value, TimeSpan duration, CachePolicy? policy, CancellationToken token) + private ValueTask TryAddCoreAsync(CacheKey cacheKey, T? value, TimeSpan duration, CachePolicy? policy, CancellationToken token, DateTimeOffset? until = null, WriteAnchor anchor = default) { NotCacheableException.ThrowIfNotCacheable(); var redisKey = ToRedisKey(cacheKey, token); var format = FormatFor(policy, forWrite: true); + var frame = FrameFor(policy); + if (!frame.IsNone) + { + frame = frame with { Until = until, Anchor = anchor }; + return format.IsDefault + ? TryAddInternalAsync(cacheKey, redisKey, value, duration, new FramedFormat(default, frame), token) + : TryAddInternalAsync(cacheKey, redisKey, value, duration, new FramedFormat(format, frame), token); + } + return format.IsDefault ? TryAddInternalAsync(cacheKey, redisKey, value, duration, default(PlainFormat), token) : TryAddInternalAsync(cacheKey, redisKey, value, duration, format, token); @@ -173,7 +218,8 @@ private async ValueTask SetInternalAsync(CacheKey cacheKey, Re var operation = StartOperation(nameof(SetAsync)); try { - if (IsDefault(value)) + // The framed branch frames a cached null with an empty inner value, so it goes the way of a value. + if (IsDefault(value) && (NeverFramed() || !_cacheNullValues || expiration <= TimeSpan.Zero)) { if (_cacheNullValues && expiration > TimeSpan.Zero) { @@ -194,14 +240,20 @@ private async ValueTask SetInternalAsync(CacheKey cacheKey, Re } else { - var (serialized, payload) = SerializeValue(value, format); + var (serialized, payload) = IsDefault(value) ? (RedisValue.EmptyString, default(SerializedPayload)) : SerializeValue(value, format); _auditKeySize?.Invoke(Logged(cacheKey, redisKey, typeof(T)), serialized); + if (!NeverFramed()) + { + (serialized, expiration) = Framed(serialized, expiration, format.Frame); + } + using (payload) { ret = await _write.ExecuteAsync(static (s, token) => { token.ThrowIfCancellationRequested(); - return s.Self.Database.StringSetAsync(s.Key, s.Serialized, s.Expiration, When.Always, CommandFlags.DemandMaster).AsValueTask(); + var (bytes, life) = NeverFramed() ? (s.Serialized, s.Expiration) : s.Self.SendForm(s.Serialized, s.Expiration); + return s.Self.Database.StringSetAsync(s.Key, bytes, life, When.Always, CommandFlags.DemandMaster).AsValueTask(); }, (Self: this, Key: redisKey, Serialized: serialized, Expiration: expiration), default, @@ -283,6 +335,11 @@ private async ValueTask SetInternalAsync(KeyValuePair SetSlotAsync(KeyValuePair[] keyValues, RedisKey[] redisKeys, SerializedPayload[] payloads, int[] group, TimeSpan expiration, TFormat format, CancellationToken token) where TFormat : struct, IValueFormat { + if (!NeverFramed()) + { + return SetSlotFramedAsync(keyValues, redisKeys, payloads, group, expiration, format, token); + } + var transaction = Database.CreateTransaction(asyncState: null); foreach (var i in group) { @@ -317,6 +374,70 @@ private ValueTask SetSlotAsync(KeyValuePair[] ke token); } + /// The framed slot: the bytes are built once, and each attempt builds its transaction inside the callback from them, with one gate answer and, for an instant, one remainder (WS3). + private ValueTask SetSlotFramedAsync(KeyValuePair[] keyValues, RedisKey[] redisKeys, SerializedPayload[] payloads, int[] group, TimeSpan expiration, TFormat format, CancellationToken token) + where TFormat : struct, IValueFormat + { + var spec = format.Frame; + var keys = new RedisKey[group.Length]; + var stored = new RedisValue[group.Length]; + var lives = new TimeSpan[group.Length]; + for (var j = 0; j < group.Length; j++) + { + var i = group[j]; + keys[j] = redisKeys[i]; + var value = keyValues[i].Value; + RedisValue serialized; + if (IsDefault(value)) + { + if (!_cacheNullValues || expiration <= TimeSpan.Zero) + { + // Null bytes mark a key the transaction removes. + stored[j] = RedisValue.Null; + continue; + } + + serialized = RedisValue.EmptyString; + } + else + { + (serialized, payloads[i]) = SerializeValue(value, format); + _auditKeySize?.Invoke(Logged(keyValues[i].Key, redisKeys[i], typeof(T)), serialized); + } + + (stored[j], lives[j]) = spec.Until is { } until ? (FramedUntil(serialized, until, spec).Stored, default) : Framed(serialized, expiration, spec); + } + + return _write.ExecuteAsync(static (s, token) => + { + token.ThrowIfCancellationRequested(); + var left = s.Until is { } until ? s.Anchor.Left(s.Self.Clock, until) : TimeSpan.MaxValue; + if (left <= TimeSpan.Zero) + { + return new ValueTask(false); + } + + var open = s.Self.FrameWrites.Allowed; + var transaction = s.Self.Database.CreateTransaction(asyncState: null); + for (var j = 0; j < s.Keys.Length; j++) + { + if (s.Stored[j].IsNull) + { + s.Self.QueueRemove(transaction, s.Keys[j]); + continue; + } + + var (bytes, life) = s.Until is null ? SendForm(s.Stored[j], s.Lives[j], open) : SendFormFor(s.Stored[j], left, open); + transaction.StringSetAsync(s.Keys[j], bytes, life, When.Always, CommandFlags.DemandMaster).Forget(); + } + + return transaction.ExecuteAsync(CommandFlags.DemandMaster).AsValueTask(); + }, + (Self: this, Keys: keys, Stored: stored, Lives: lives, spec.Until, spec.Anchor), + default, + token); + } + /// /// SET key value EX … NX in one round-trip: Redis decides, so no probe precedes the write. /// Safe to retry — an attempt whose reply was lost is refused by the key it just wrote, and @@ -350,18 +471,34 @@ private async ValueTask TryAddInternalAsync(CacheKey cacheKey, NoteWritten(redisKey); var (serialized, payload) = isNull ? (RedisValue.EmptyString, default(SerializedPayload)) : SerializeValue(value, format); _auditKeySize?.Invoke(Logged(cacheKey, redisKey, typeof(T)), serialized); + if (!NeverFramed()) + { + (serialized, expiration) = format.Frame.Until is { } until ? (FramedUntil(serialized, until, format.Frame).Stored, expiration) : Framed(serialized, expiration, format.Frame); + } + using (payload) { - ret = await _write.ExecuteAsync(static (s, token) => - { - token.ThrowIfCancellationRequested(); - return s.Self._tombstoneGrace is null - ? s.Self.Database.StringSetAsync(s.Key, s.Serialized, s.Expiration, When.NotExists, CommandFlags.DemandMaster).AsValueTask() - : s.Self.AddOverTombstoneAsync(s.Key, s.Serialized, s.Expiration); - }, - (Self: this, Key: redisKey, Serialized: serialized, Expiration: expiration), - default, - token).ConfigureAwait(false); + ret = await (EntryMetadataEnabled + ? _write.ExecuteAsync(static (s, token) => s.Self.AddOverExpiredFrameAsync(s.Key, s.Serialized, s.Expiration, s.Format, token), (Self: this, Key: redisKey, Serialized: serialized, Expiration: expiration, Format: format), default, token) + : NeverFramed() || format.Frame.Until is null + ? _write.ExecuteAsync(static (s, token) => + { + token.ThrowIfCancellationRequested(); + if (!NeverFramed()) + { + return s.Self._tombstoneGrace is null + ? s.Self.AddFramedAsync(s.Key, s.Serialized, s.Expiration, null, default) + : s.Self.AddOverTombstoneFramedAsync(s.Key, s.Serialized, s.Expiration, null, default); + } + + return s.Self._tombstoneGrace is null + ? s.Self.Database.StringSetAsync(s.Key, s.Serialized, s.Expiration, When.NotExists, CommandFlags.DemandMaster).AsValueTask() + : s.Self.AddOverTombstoneAsync(s.Key, s.Serialized, s.Expiration); + }, + (Self: this, Key: redisKey, Serialized: serialized, Expiration: expiration), + default, + token) + : TryAddUntilAsync(redisKey, serialized, format.Frame, token)).ConfigureAwait(false); } } operation.Stop(); diff --git a/src/UiPath.Caching/Redis/RedisCache.cs b/src/UiPath.Caching/Redis/RedisCache.cs index 854d47145..b9b10e971 100644 --- a/src/UiPath.Caching/Redis/RedisCache.cs +++ b/src/UiPath.Caching/Redis/RedisCache.cs @@ -91,6 +91,7 @@ public RedisCache( _redisKeyStrategy = RedisKeyStrategies.Resolve(redisCacheOptions, cacheOptions, GetType()); _cacheEntryFactory = redisCacheOptions.EntryFactory ?? new CacheEntryFactory(); _cacheNullValues = redisCacheOptions.CacheNullValues; + EntryMetadataEnabled = redisCacheOptions.EntryMetadataEnabled; if (cacheOptions.AuditEnabled && _largeValueThreshold > 0) { @@ -100,6 +101,8 @@ public RedisCache( public string Name => KnownCacheProviderNames.Redis; + internal IEntryFrameWrites FrameWrites { get; init; } = GatedFrameWrites.Never; + internal ValueSerializerRegistry ValueSerializers { get => _valueSerializers; diff --git a/src/UiPath.Caching/Redis/RedisCacheOptions.cs b/src/UiPath.Caching/Redis/RedisCacheOptions.cs index 5d2d2228f..0ff40fd87 100644 --- a/src/UiPath.Caching/Redis/RedisCacheOptions.cs +++ b/src/UiPath.Caching/Redis/RedisCacheOptions.cs @@ -76,6 +76,9 @@ public class RedisCacheOptions : ICacheOptions /// public TimeSpan? RemoveTombstone { get; set; } + /// Enables entry frame writes when format negotiation allows them. Off by default. + public bool EntryMetadataEnabled { get; set; } + public FormatNegotiationOptions FormatNegotiation { get; set; } = new(); /// The format of the node list and the stream maintainer's keys while a format move runs; null follows . diff --git a/src/UiPath.Caching/Redis/RedisCacheProvider.cs b/src/UiPath.Caching/Redis/RedisCacheProvider.cs index b7547b625..3f807c253 100644 --- a/src/UiPath.Caching/Redis/RedisCacheProvider.cs +++ b/src/UiPath.Caching/Redis/RedisCacheProvider.cs @@ -1,3 +1,4 @@ +using UiPath.Caching.Config; using UiPath.Caching.Negotiation; using UiPath.Caching.Policies; using UiPath.Caching.Serialization; @@ -22,6 +23,7 @@ public sealed class RedisCacheProvider : ICacheProvider private readonly ValueSerializerRegistry _valueSerializers; private readonly IEffectiveFormat? _effectiveFormat; private readonly ValueMigration? _migration; + private readonly IEntryFrameWrites _frameWrites; private readonly Lazy _cache; private readonly Lazy _hashCache; @@ -64,11 +66,13 @@ internal RedisCacheProvider( IKeyMaskingPolicy? keyMaskingPolicy, ValueSerializerRegistry valueSerializers, IEffectiveFormat? effectiveFormat = null, - ValueMigration? migration = null) + ValueMigration? migration = null, + IEntryFrameWrites? frameWrites = null) { _valueSerializers = valueSerializers; _effectiveFormat = effectiveFormat; _migration = migration; + _frameWrites = frameWrites ?? GatedFrameWrites.Never; _keyMaskingPolicy = keyMaskingPolicy; _clock = clock; _redisCacheOptions = redisCacheOptions.Value; @@ -206,7 +210,8 @@ internal static RedisCacheProvider Create(IServiceProvider services) => services.GetService(), services.GetRequiredService(), services.GetService()?.Negotiator, - services.GetService()); + services.GetService(), + services.GetService()); private FormatInventory NewInventory() { @@ -222,6 +227,8 @@ private FormatInventory NewInventory() private RedisCache BuildCache() { _valueSerializers.ValidateWriteNames(_policyFactory); + CachePolicyFactoryValidator.ValidateDistributedFailSafe(_policyFactory, _redisCacheOptions.EntryMetadataEnabled); + FailSafeLifetimeWarning.LogRedisWindows(_loggerFactory.CreateLogger(Name), _policyFactory); return new( _redis, _serializerProxy, @@ -237,6 +244,7 @@ private RedisCache BuildCache() ValueSerializers = _valueSerializers, EffectiveFormat = _effectiveFormat, Migration = _migration, + FrameWrites = _frameWrites, }; } diff --git a/src/UiPath.Caching/Serialization/FrameSpec.cs b/src/UiPath.Caching/Serialization/FrameSpec.cs new file mode 100644 index 000000000..ca16bb3af --- /dev/null +++ b/src/UiPath.Caching/Serialization/FrameSpec.cs @@ -0,0 +1,10 @@ +namespace UiPath.Caching.Serialization; + +/// What a write puts in an entry frame: the stale window and the validators, and on a caller's instant that instant and its anchor. +/// The instant a caller passed on a overload; null for a duration. Only the framed branch of a dispatcher sets it. +/// The anchor its overload took for at entry; default when is null. +internal readonly record struct FrameSpec(TimeSpan Window, EntryValidators? Validators, DateTimeOffset? Until = null, WriteAnchor Anchor = default) +{ + /// Whether no frame is needed; the instant and the anchor do not count. + public bool IsNone => Window <= TimeSpan.Zero && Validators is null; +} diff --git a/src/UiPath.Caching/Serialization/FramedFormat.cs b/src/UiPath.Caching/Serialization/FramedFormat.cs new file mode 100644 index 000000000..cab74ade6 --- /dev/null +++ b/src/UiPath.Caching/Serialization/FramedFormat.cs @@ -0,0 +1,16 @@ +namespace UiPath.Caching.Serialization; + +/// A format that also writes an entry frame; every other member is the inner format's. +internal readonly struct FramedFormat(TInner inner, FrameSpec frame) : IValueFormat + where TInner : struct, IValueFormat +{ + public ICacheValueSerializer? Writer => inner.Writer; + + public bool Sniff => inner.Sniff; + + public ReadableFormats? Readable => inner.Readable; + + public FrameSpec Frame => frame; + + public bool Handles(Exception exception) => inner.Handles(exception); +} diff --git a/src/UiPath.Caching/Serialization/IValueFormat.cs b/src/UiPath.Caching/Serialization/IValueFormat.cs index f0002660b..88c85537d 100644 --- a/src/UiPath.Caching/Serialization/IValueFormat.cs +++ b/src/UiPath.Caching/Serialization/IValueFormat.cs @@ -10,6 +10,9 @@ internal interface IValueFormat /// The formats a read accepts; null when it looks for no header. ReadableFormats? Readable { get; } + /// What a write frames the value with; none for the plain and the format branch. + FrameSpec Frame { get; } + /// Whether a read that failed with logs it and reads as a miss. bool Handles(Exception exception); } diff --git a/src/UiPath.Caching/Serialization/PlainFormat.cs b/src/UiPath.Caching/Serialization/PlainFormat.cs index 9f9c829e6..b4d973f46 100644 --- a/src/UiPath.Caching/Serialization/PlainFormat.cs +++ b/src/UiPath.Caching/Serialization/PlainFormat.cs @@ -9,5 +9,7 @@ namespace UiPath.Caching.Serialization; public ReadableFormats? Readable => null; + public FrameSpec Frame => default; + public bool Handles(Exception exception) => true; } diff --git a/src/UiPath.Caching/Serialization/ValueFormat.cs b/src/UiPath.Caching/Serialization/ValueFormat.cs index 8779c0f12..5c9af134e 100644 --- a/src/UiPath.Caching/Serialization/ValueFormat.cs +++ b/src/UiPath.Caching/Serialization/ValueFormat.cs @@ -7,5 +7,7 @@ internal readonly record struct ValueFormat(ICacheValueSerializer? Writer, Reada public bool IsDefault => Writer is null && Readable is null; + public FrameSpec Frame => default; + public bool Handles(Exception exception) => exception is not OutOfMemoryException; } diff --git a/src/UiPath.Caching/Serialization/WithoutWindow.cs b/src/UiPath.Caching/Serialization/WithoutWindow.cs new file mode 100644 index 000000000..5532e9f66 --- /dev/null +++ b/src/UiPath.Caching/Serialization/WithoutWindow.cs @@ -0,0 +1,16 @@ +namespace UiPath.Caching.Serialization; + +/// A format whose frame keeps no stale window, for a value that skips fail-safe; the instant and its anchor stay. +internal readonly struct WithoutWindow(TInner inner) : IValueFormat + where TInner : struct, IValueFormat +{ + public ICacheValueSerializer? Writer => inner.Writer; + + public bool Sniff => inner.Sniff; + + public ReadableFormats? Readable => inner.Readable; + + public FrameSpec Frame => inner.Frame with { Window = TimeSpan.Zero }; + + public bool Handles(Exception exception) => inner.Handles(exception); +} diff --git a/src/UiPath.Caching/WriteAnchor.cs b/src/UiPath.Caching/WriteAnchor.cs new file mode 100644 index 000000000..a261870ae --- /dev/null +++ b/src/UiPath.Caching/WriteAnchor.cs @@ -0,0 +1,63 @@ +namespace UiPath.Caching; + +/// +/// The monotonic anchor of a deadline that a framed write holds: a reading taken before the UTC reading +/// that made or validated the deadline, and the life the deadline had at that UTC reading. A send counts the life left on both clocks, so a UTC +/// clock set back after the capture adds nothing. Default is no anchor. +/// +internal readonly record struct WriteAnchor(long Stamp, TimeSpan Life) +{ + public bool IsSet => Life > TimeSpan.Zero; + + /// Validates an instant from one UTC reading, taken after the timestamp: the remainder and its anchor. and no anchor for , which reads no clock; null and no anchor for a remainder that is not positive. + public static TimeSpan? Validate(TimeProvider clock, DateTimeOffset deadline, out WriteAnchor anchor) + { + anchor = default; + if (deadline == DateTimeOffset.MaxValue) + { + return TimeSpan.MaxValue; + } + + var stamp = clock.GetTimestamp(); + var remaining = deadline - clock.GetUtcNow(); + if (remaining <= TimeSpan.Zero) + { + return null; + } + + anchor = new WriteAnchor(stamp, remaining); + return remaining; + } + + /// Makes the deadline of a duration: the timestamp, then the one UTC reading that makes it. "Never" takes no anchor and reads no clock. + public static WriteAnchor Capture(TimeProvider clock, TimeSpan lifetime, out DateTimeOffset deadline) + { + if (lifetime == TimeSpan.MaxValue) + { + deadline = DateTimeOffset.MaxValue; + return default; + } + + var stamp = clock.GetTimestamp(); + deadline = clock.ToDateTimeOffset(lifetime); + return deadline == DateTimeOffset.MaxValue || lifetime <= TimeSpan.Zero ? default : new WriteAnchor(stamp, lifetime); + } + + /// The logical life left of , from one timestamp and one UTC reading: the smaller of the UTC remainder and the anchored life less the monotonic time since. Without an anchor, the UTC remainder alone. + public TimeSpan Left(TimeProvider clock, DateTimeOffset deadline) + { + if (deadline == DateTimeOffset.MaxValue) + { + return TimeSpan.MaxValue; + } + + if (!IsSet) + { + return deadline - clock.GetUtcNow(); + } + + var anchored = Life - clock.GetElapsedTime(Stamp); + var byUtc = deadline - clock.GetUtcNow(); + return byUtc < anchored ? byUtc : anchored; + } +} diff --git a/tests/UiPath.Caching.Migration.Tests/RegistrationTests.cs b/tests/UiPath.Caching.Migration.Tests/RegistrationTests.cs index f62cd2b01..946acda74 100644 --- a/tests/UiPath.Caching.Migration.Tests/RegistrationTests.cs +++ b/tests/UiPath.Caching.Migration.Tests/RegistrationTests.cs @@ -16,7 +16,7 @@ public sealed class RegistrationTests private static readonly string[] Defaults = [ "Redis.AwaitRefresh=false", "Redis.CacheKeyStrategy=none", "Redis.CacheNullValues=false", "Redis.ConnectionMonitorEnabled=none", - "Redis.DefaultExpiration=01:00:00", "Redis.Enabled=true", "Redis.EntryFactory=none", "Redis.FormatNegotiation=FormatNegotiationOptions", + "Redis.DefaultExpiration=01:00:00", "Redis.Enabled=true", "Redis.EntryFactory=none", "Redis.EntryMetadataEnabled=false", "Redis.FormatNegotiation=FormatNegotiationOptions", "Redis.HashFieldBatchSize=1000", "Redis.KeyFormat=none", "Redis.KeyPrefix=", "Redis.KeyReadTelemetryEnabled=false", "Redis.MasterReadWindow=00:00:01", "Redis.ReadFrom=Master", "Redis.ReadScriptsEnabled=false", "Redis.RedisKeyStrategyFactory=none", "Redis.RemoveTombstone=none", "Redis.RemoveUnreadable=true", "Redis.Timeout=00:00:01", "Redis.FormatNegotiation.AdvertiseInterval=00:00:15", "Redis.FormatNegotiation.AssumeAllNodesCanRead=false", "Redis.FormatNegotiation.LivenessWindow=00:02:00", @@ -27,7 +27,7 @@ public sealed class RegistrationTests "Caching.DistributedLockMaxPollInterval=00:00:00.5000000", "Caching.DistributedLockPollInterval=00:00:00.0500000", "Caching.Enabled=true", "Caching.KeyCasing=Insensitive", "Caching.LargeValueThreshold=20000", "Caching.Policies=0 entries", "Caching.Separator=:", "Caching.ShardKeyEnabled=false", "Caching.TelemetryEnabled=true", - "Policy.BackgroundDistributedWrite=none", "Policy.DistributedExpiration=none", "Policy.FactoryTimeout=none", "Policy.FailSafeCooldown=none", + "Policy.BackgroundDistributedWrite=none", "Policy.DistributedExpiration=none", "Policy.FactoryTimeout=none", "Policy.FailSafeCooldown=none", "Policy.FailSafeDistributedEnabled=none", "Policy.FailSafeDistributedMaxStaleAge=none", "Policy.FailSafeEnabled=none", "Policy.FailSafeMaxStaleAge=none", "Policy.FailSafeTimeout=none", "Policy.JitterMaxDuration=none", "Policy.LocalExpiration=none", "Policy.LocalExpirationDisconnected=none", "Policy.Lock=none", "Policy.RefreshLocalOnPeerWrite=none", "Policy.RefreshLocalRetryWindow=none", "Policy.Rehydrate=none", "Policy.RehydrateEnabled=none", "Policy.Serializer=none", @@ -54,6 +54,18 @@ public void The_router_stack_as_built_breaks_no_rule() RegistrationValidator.Violations(new CacheOptions(), stack).Should().BeEmpty("a library default that breaks a rule would show here"); } + [Fact] + public void EntryMetadataEnabled_is_refused_on_the_router_stack() + { + var stack = new RedisCacheOptions(); + RouterServiceCollectionExtensions.ConfigureStackRedis(stack); + stack.EntryMetadataEnabled = true; + + var act = () => RegistrationValidator.ThrowIfInvalid(new CacheOptions(), stack); + + act.Should().Throw().WithMessage("*Redis.EntryMetadataEnabled*"); + } + [Fact] public void Each_setting_that_changes_what_the_source_sees_is_named() { diff --git a/tests/UiPath.Caching.Migration.Tests/RouterOptionOffFrameTests.cs b/tests/UiPath.Caching.Migration.Tests/RouterOptionOffFrameTests.cs new file mode 100644 index 000000000..7068f01c8 --- /dev/null +++ b/tests/UiPath.Caching.Migration.Tests/RouterOptionOffFrameTests.cs @@ -0,0 +1,118 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using StackExchange.Redis; +using UiPath.Caching.Config; +using UiPath.Caching.Migration.Tests.Support; + +namespace UiPath.Caching.Migration.Tests; + +// I-KM8, FS13: the router's stack refuses EntryMetadataEnabled, so on the library path with no move on it is the node with the option off. +// A windowed frame set raw stands for one that a group left behind. The test pins the documented limit of the four commands. +[Collection("RedisIntegration")] +[Trait("Category", "Integration")] +public sealed class RouterOptionOffFrameTests(RedisFixture fixture) : IAsyncLifetime +{ + private const string Skip = "Set RUN_REDIS_INTEGRATION_TESTS=1 (Redis at 127.0.0.1:6379) to run."; + private static readonly TimeSpan Window = TimeSpan.FromSeconds(60); + + private readonly string _cacheName = $"Of{Guid.NewGuid():N}"[..12]; + private ConnectionMultiplexer? _redis; + private ManualTimeProvider _clock = new(DateTimeOffset.UnixEpoch); + + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + public async ValueTask InitializeAsync() + { + if (fixture.Enabled) + { + _redis = await ConnectionMultiplexer.ConnectAsync(fixture.ConnectionString); + _clock = new ManualTimeProvider(await _redis.GetServer(_redis.GetEndPoints()[0]).TimeAsync()); + } + } + + public async ValueTask DisposeAsync() + { + if (_redis is not null) + { + await _redis.DisposeAsync(); + } + } + + [Fact] + public async Task Through_the_router_the_four_commands_answer_as_on_a_node_with_the_option_off() + { + Assert.SkipUnless(fixture.Enabled, Skip); + await using var provider = Provider(); + var router = provider.GetRequiredService(); + await RouterTestBase.WaitForLibraryAsync(router, Ct); + router.Mode.Should().Be(RouterMode.Library); + var cache = router.Get>(_cacheName); + var db = _redis!.GetDatabase(); + var key = (RedisKey)$"n:{_cacheName},c:framed"; + var frame = Redis.EntryFrame.Write(InPlaceEnvelope.Write(new List { 1, 2 }), _clock.GetUtcNow() - TimeSpan.FromSeconds(5), Window, null); + await db.StringSetAsync(key, frame, Window); + try + { + (await cache.ContainsAsync("framed", Ct)).Should().BeTrue("the command answers from the key, which still has life"); + (await cache.TimeToLiveAsync("framed", Ct)).Should().BeGreaterThan(TimeSpan.FromSeconds(30), "the key's life, not the frame's"); + (await cache.ExpireTimeAsync("framed", Ct)).Should().BeAfter(_clock.GetUtcNow().AddSeconds(30)); + + (await cache.GetAsync("framed", Ct)).Should().BeNull("a value read judges the frame, which has expired"); + (await cache.TryAddAsync("framed", [9], TimeSpan.FromMinutes(10), Ct)).Should().BeFalse("an add loses to an expired frame until the key leaves"); + await SettleAsync(cache); + + // The refresh is fire and forget on this stack, so its answer says nothing; the next command on the same connection sees its effect. + await cache.RefreshAsync("framed", TimeSpan.FromMinutes(10), Ct); + await SettleAsync(cache); + (await cache.TimeToLiveAsync("framed", Ct)).Should().BeGreaterThan(TimeSpan.FromMinutes(9), "the refresh set the TTL of the key and read nothing"); + ((byte[]?)await db.StringGetAsync(key)).Should().Equal(frame, "the frame is as it was"); + + var filled = await cache.TryFillAsync("framed", [7], TimeSpan.FromMinutes(10), Ct); + + filled.Outcome.Should().Be(FillOutcome.Added, "a fill replaces an expired frame"); + (await cache.GetAsync("framed", Ct)).Should().Equal([7]); + ((byte[]?)await db.StringGetAsync(key)).Should().Equal(InPlaceEnvelope.Write(new List { 7 })); + } + finally + { + await SettleAsync(cache); + await db.KeyDeleteAsync(key); + } + } + + /// A routed write is pending until its deadline passes on the router's clock. + private async Task SettleAsync(ICache> cache) + { + var routed = (IRouterParticipant)cache; + var pending = routed.PendingKeys(); + if (pending.Count > 0) + { + _clock.Advance(pending.Max(item => item.Until) - _clock.GetUtcNow()); + await routed.WhenPendingSettledAsync().WaitAsync(Ct); + } + } + + private ServiceProvider Provider() + { + var configuration = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary + { + ["Caching:AppShortName"] = "oftest", + ["Caching:DefaultCache"] = KnownCacheProviderNames.Redis, + ["Caching:Connections:Redis:ConnectionString"] = fixture.ConnectionString, + ["Caching:Connections:Redis:WarmUpOnStart"] = "false", + ["Caching:Connections:Redis:PlannedMaintenanceEnabled"] = "false", + }).Build(); + var source = new InPlaceSource(_redis!, _cacheName); + var services = new ServiceCollection().AddLogging().AddSingleton(_clock); + services.AddCaching(configuration, builder => builder.AddRedisConnection()); + services.AddCachingRouter(configuration, router => + { + router.UseLibraryWhen(_ => true); + router.UseEnvelope(new InPlaceEnvelopeProxy()); + router.Add(new RouterCacheRegistration> { Name = _cacheName, Group = "ofg", Source = source, RedisKey = source.RedisKey }); + }); + var provider = services.BuildServiceProvider(); + _ = provider.GetRequiredService(); + return provider; + } +} diff --git a/tests/UiPath.Caching.Tests/CachePolicyMergerTests.cs b/tests/UiPath.Caching.Tests/CachePolicyMergerTests.cs index 40af6e304..bf556cfc9 100644 --- a/tests/UiPath.Caching.Tests/CachePolicyMergerTests.cs +++ b/tests/UiPath.Caching.Tests/CachePolicyMergerTests.cs @@ -262,4 +262,18 @@ public void Slot_comes_from_the_side_that_supplies_the_write_name() // Names json: the default's slot must not leak back in. CachePolicyMerger.WriteSerializerOf(CachePolicyMerger.Merge(new CachePolicy { Serializer = new SerializerPolicy { Write = "json" } }, resolvedDefault)!).Should().BeNull(); } + + [Fact] + public void FailSafeDistributed_options_merge_like_the_other_fail_safe_options() + { + var defaults = new CachePolicy { FailSafeDistributedEnabled = true, FailSafeDistributedMaxStaleAge = TimeSpan.FromHours(1) }; + + var named = CachePolicyMerger.Merge(new CachePolicy { FailSafeDistributedEnabled = false, FailSafeDistributedMaxStaleAge = TimeSpan.FromMinutes(5) }, defaults)!; + var inherited = CachePolicyMerger.Merge(new CachePolicy(), defaults)!; + + named.FailSafeDistributedEnabled.Should().BeFalse(); + named.FailSafeDistributedMaxStaleAge.Should().Be(TimeSpan.FromMinutes(5)); + inherited.FailSafeDistributedEnabled.Should().BeTrue(); + inherited.FailSafeDistributedMaxStaleAge.Should().Be(TimeSpan.FromHours(1)); + } } diff --git a/tests/UiPath.Caching.Tests/FailSafeLifetimeWarningTests.cs b/tests/UiPath.Caching.Tests/FailSafeLifetimeWarningTests.cs index 207ad9bf4..f4ed2c70d 100644 --- a/tests/UiPath.Caching.Tests/FailSafeLifetimeWarningTests.cs +++ b/tests/UiPath.Caching.Tests/FailSafeLifetimeWarningTests.cs @@ -68,6 +68,30 @@ public void A_policy_without_fail_safe_logs_nothing() _logger.Warnings.Should().BeEmpty(); } + [Fact] + public void A_policy_with_a_Redis_stale_window_logs_its_window_once() + { + var windowed = new CachePolicy { FailSafeEnabled = true, FailSafeDistributedEnabled = true, FailSafeDistributedMaxStaleAge = TimeSpan.FromMinutes(10) }; + var factory = Factory(null, ("routes", windowed), ("plain", FailSafe), ("off", new CachePolicy { FailSafeDistributedEnabled = true })); + + FailSafeLifetimeWarning.LogRedisWindows(_logger, factory); + + _logger.Warnings.Should().ContainSingle("only a policy with fail-safe and the distributed switch writes a window").Which.Should().Contain("routes").And.Contain("00:10:00"); + } + + private static ICachePolicyFactory Factory(CachePolicy? defaultPolicy, params (string Name, CachePolicy Policy)[] named) + { + var factory = Substitute.For(); + factory.Default.Returns(defaultPolicy); + factory.Keys.Returns(named.Select(p => p.Name).ToArray()); + foreach (var (name, policy) in named) + { + factory.Resolve(name).Returns(policy); + } + + return factory; + } + private void Log(long? sizeLimit, CachePolicy? defaultPolicy, params (string Name, CachePolicy Policy)[] named) { var factory = Substitute.For(); diff --git a/tests/UiPath.Caching.Tests/FailSafePolicyTests.cs b/tests/UiPath.Caching.Tests/FailSafePolicyTests.cs index a4f3dad9f..34a4f1a55 100644 --- a/tests/UiPath.Caching.Tests/FailSafePolicyTests.cs +++ b/tests/UiPath.Caching.Tests/FailSafePolicyTests.cs @@ -47,6 +47,7 @@ public void The_merger_carries_every_policy_field() FactoryTimeout = TimeSpan.FromSeconds(1), BackgroundDistributedWrite = true, RefreshLocalOnPeerWrite = true, RefreshLocalRetryWindow = TimeSpan.FromSeconds(1), JitterMaxDuration = TimeSpan.FromSeconds(1), RehydrateEnabled = true, Rehydrate = new RehydrateOptions(), Lock = new LockProfile(), FailSafeEnabled = true, FailSafeMaxStaleAge = TimeSpan.FromSeconds(1), FailSafeCooldown = TimeSpan.FromSeconds(1), FailSafeTimeout = TimeSpan.FromSeconds(1), + FailSafeDistributedEnabled = true, FailSafeDistributedMaxStaleAge = TimeSpan.FromSeconds(1), Serializer = new SerializerPolicy(), }); @@ -76,6 +77,35 @@ public void A_negative_fail_safe_duration_is_refused(string field) act.Should().Throw().WithMessage($"*Policies['p'].{field}*"); } + [Fact] + public void FailSafeDistributedEnabled_needs_FailSafeEnabled() + { + var act = () => new DefaultCachePolicyFactory(new Dictionary { ["p"] = new() { FailSafeDistributedEnabled = true } }, null); + + act.Should().Throw().WithMessage("*Policies['p'].FailSafeDistributedEnabled*FailSafeEnabled*"); + } + + [Fact] + public void FailSafeDistributedEnabled_needs_EntryMetadataEnabled() + { + var policy = new CachePolicy { FailSafeEnabled = true, FailSafeDistributedEnabled = true }; + var factory = new DefaultCachePolicyFactory(new Dictionary { ["p"] = policy }, null); + + var refused = () => CachePolicyFactoryValidator.ValidateDistributedFailSafe(factory, entryMetadataEnabled: false); + var accepted = () => CachePolicyFactoryValidator.ValidateDistributedFailSafe(factory, entryMetadataEnabled: true); + + refused.Should().Throw().WithMessage("*Policies['p'].FailSafeDistributedEnabled*EntryMetadataEnabled*"); + accepted.Should().NotThrow(); + } + + [Fact] + public void A_negative_FailSafeDistributedMaxStaleAge_is_refused() + { + var act = () => new DefaultCachePolicyFactory(new Dictionary { ["p"] = new() { FailSafeDistributedMaxStaleAge = TimeSpan.FromSeconds(-1) } }, null); + + act.Should().Throw().WithMessage("*Policies['p'].FailSafeDistributedMaxStaleAge*"); + } + [Fact] public void Fail_safe_binds_from_the_policies_section() { diff --git a/tests/UiPath.Caching.Tests/LegacyReaderTests.cs b/tests/UiPath.Caching.Tests/LegacyReaderTests.cs new file mode 100644 index 000000000..480512f8e --- /dev/null +++ b/tests/UiPath.Caching.Tests/LegacyReaderTests.cs @@ -0,0 +1,116 @@ +using System.Text.Json; +using StackExchange.Redis; +using UiPath.Caching.Redis; +using UiPath.Caching.Tests.Redis; + +namespace UiPath.Caching.Tests; + +public class LegacyReaderTests +{ + public static TheoryData Frames + { + get + { + var frames = new TheoryData(); + foreach (var row in EntryFrameVectors.GrammarCases) + { + var (name, bytes, valid) = row.Data; + if (valid) + { + frames.Add(name, bytes); + } + } + + frames.Add("window with JSON inner", EntryFrame.Write("\"value\""u8, DateTimeOffset.UnixEpoch, TimeSpan.FromSeconds(1), null)); + return frames; + } + } + + [Theory] + [MemberData(nameof(Frames))] + public void A_3_1_reader_with_the_default_proxy_fails_on_every_frame(string vector, byte[] frame) + { + var proxy = new SystemJsonByteSerializerProxy(); + + AssertJsonFailure(proxy, frame, vector); + AssertJsonFailure(proxy, frame, vector); + AssertJsonFailure(proxy, frame, vector); + AssertJsonFailure(proxy, frame, vector); + } + + [Theory] + [MemberData(nameof(Frames))] + public void A_3_1_reader_with_the_raw_proxy_returns_the_frame_as_the_value(string vector, byte[] frame) + { + var proxy = new RawByteSerializerProxy(); + + var (found, bytes) = LegacyRead(frame, proxy); + found.Should().BeTrue(vector); + bytes.Should().Equal(frame, vector); + LegacyRead>(frame, proxy).Value.ToArray().Should().Equal(frame, vector); + LegacyRead>(frame, proxy).Value.ToArray().Should().Equal(frame, vector); + } + + [Theory] + [MemberData(nameof(Frames))] + public void A_3_1_raw_reader_falls_to_json_for_any_other_type(string vector, byte[] frame) + { + var proxy = new RawByteSerializerProxy(); + + AssertJsonFailure(proxy, frame, vector); + AssertJsonFailure(proxy, frame, vector); + AssertJsonFailure(proxy, frame, vector); + } + + [Theory] + [MemberData(nameof(Frames))] + public void A_3_1_reader_with_a_custom_proxy_is_handed_the_whole_frame(string vector, byte[] frame) + { + var strict = Substitute.For>(); + strict.Deserialize(Arg.Any()).Returns(_ => throw new FormatException("Unexpected bytes")); + var permissive = Substitute.For>(); + permissive.Deserialize(Arg.Any()).Returns("wrong value"); + + var logged = new List(); + LegacyReadOrMiss(frame, strict, logged.Add).Should().Be((false, null), vector); + logged.Should().ContainSingle().Which.Should().BeOfType(); + LegacyReadOrMiss(frame, permissive, logged.Add).Should().Be((true, "wrong value"), vector); + logged.Should().ContainSingle(); + + strict.Received(1).Deserialize(Arg.Is(bytes => bytes.SequenceEqual(frame))); + permissive.Received(1).Deserialize(Arg.Is(bytes => bytes.SequenceEqual(frame))); + } + + private static void AssertJsonFailure(ISerializerProxy proxy, byte[] frame, string vector) + { + var read = () => LegacyRead(frame, proxy); + read.Should().Throw(vector); + } + + // The 3.1.2 read pipeline logs a command failure and returns its fallback. + private static (bool Found, T? Value) LegacyReadOrMiss(RedisValue value, ISerializerProxy serializer, Action logFailure) + { + try + { + return LegacyRead(value, serializer); + } + catch (Exception ex) + { + logFailure(ex); + return (false, default); + } + } + + private static (bool Found, T? Value) LegacyRead(RedisValue value, ISerializerProxy serializer) + { + if (value.IsNull) + { + return (false, default); + } + + var deserialized = value.Length() == 0 ? default : serializer.Deserialize(value); + return CacheValueHelpers.IsDefault(deserialized) ? (false, default) : (true, deserialized); + } + + private sealed record Sample(string Value); +} diff --git a/tests/UiPath.Caching.Tests/Negotiation/EntryFrameGateTests.cs b/tests/UiPath.Caching.Tests/Negotiation/EntryFrameGateTests.cs new file mode 100644 index 000000000..56ce9eaa4 --- /dev/null +++ b/tests/UiPath.Caching.Tests/Negotiation/EntryFrameGateTests.cs @@ -0,0 +1,150 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using UiPath.Caching.Config; +using UiPath.Caching.Negotiation; +using UiPath.Caching.Redis; +using UiPath.Caching.Tests.Fakes; + +namespace UiPath.Caching.Tests.Negotiation; + +public class EntryFrameGateTests +{ + [Fact] + public void With_the_option_off_no_node_advertises_frame1_and_frames_are_never_allowed() + { + using var node = Build(enabled: false, mode: FormatNegotiationMode.Force, registerSerializer: true); + + node.GetRequiredService().Advertisement!.ValueReads.Should().NotContain(NodeAdvertisement.Frame1); + node.GetRequiredService().Allowed.Should().BeFalse(); + } + + [Fact] + public void With_the_option_on_and_no_serializer_the_negotiation_is_active() + { + using var node = Build(); + + var negotiation = node.GetRequiredService(); + negotiation.IsActive.Should().BeTrue(); + negotiation.Advertisement!.ValueReads.Should().Equal("json", NodeAdvertisement.Frame1); + negotiation.Negotiator.Should().NotBeNull(); + } + + [Theory] + [InlineData(FormatNegotiationMode.Force, false, true, 1)] + [InlineData(FormatNegotiationMode.Auto, true, true, 1)] + [InlineData(FormatNegotiationMode.Auto, false, true, 0)] + [InlineData(FormatNegotiationMode.Force, true, false, 0)] + public void Writing_frames_on_the_operators_word_logs_the_3_1_warning_once( + FormatNegotiationMode mode, bool attested, bool enabled, int count) + { + var logger = new RecordedLogger(); + using var node = Build(enabled, mode, attested, logger: logger, registerSerializer: !enabled); + + _ = node.GetRequiredService(); + _ = node.GetRequiredService().Allowed; + _ = node.GetRequiredService().Allowed; + + var warnings = logger.Records.Where(r => r.Level == LogLevel.Warning && r.Message.Contains("3.1.x", StringComparison.Ordinal)).ToArray(); + warnings.Should().HaveCount(count); + foreach (var warning in warnings) + { + warning.Message.Should().Contain("miss").And.Contain("JSON").And.Contain("RawByteSerializerProxy").And.Contain("custom").And.Contain("frame bytes"); + } + } + + [Fact] + public void Force_writes_frames_at_once() + { + using var node = Build(mode: FormatNegotiationMode.Force); + + node.GetRequiredService().Allowed.Should().BeTrue(); + node.GetRequiredService().Negotiator.Should().BeNull(); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void With_no_node_list_the_operator_must_attest(bool attested) + { + using var node = Build(attested: attested, connector: false); + + node.GetRequiredService().Allowed.Should().Be(attested); + } + + [Fact] + public void Force_with_a_held_write_gate_allows_no_frame() => + HeldGate(FormatNegotiationMode.Force, connector: true); + + [Fact] + public void An_attested_node_without_a_node_list_and_a_held_write_gate_allows_no_frame() => + HeldGate(FormatNegotiationMode.Auto, connector: false); + + [Fact] + public void A_write_gate_that_throws_allows_no_frame() + { + var gate = Substitute.For(); + gate.Hold().Returns(_ => throw new InvalidOperationException("gate failed"), _ => null); + using var node = Build(mode: FormatNegotiationMode.Force, gate: gate); + var writes = node.GetRequiredService(); + + writes.Allowed.Should().BeFalse(); + writes.Allowed.Should().BeTrue(); + } + + private static void HeldGate(FormatNegotiationMode mode, bool connector) + { + var gate = Substitute.For(); + gate.Hold().Returns("key move"); + using var node = Build(mode: mode, attested: true, connector: connector, gate: gate); + var writes = node.GetRequiredService(); + + writes.Allowed.Should().BeFalse(); + gate.Hold().Returns((string?)null); + writes.Allowed.Should().BeTrue(); + } + + private static ServiceProvider Build( + bool enabled = true, + FormatNegotiationMode mode = FormatNegotiationMode.Auto, + bool attested = false, + bool connector = true, + IFormatWriteGate? gate = null, + RecordedLogger? logger = null, + bool registerSerializer = false) + { + var services = new ServiceCollection(); + if (gate is not null) + { + services.AddSingleton(gate); + } + if (logger is not null) + { + var factory = Substitute.For(); + factory.CreateLogger(Arg.Any()).Returns(logger); + services.AddSingleton(factory); + } + + return services + .AddSingleton(new ManualTimeProvider(DateTimeOffset.UnixEpoch)) + .AddCaching( + b => + { + if (connector) + { + b.AddRedisConnection(o => o.ConnectionString = "127.0.0.1:1"); + } + b.AddRedis(o => + { + o.EntryMetadataEnabled = enabled; + o.FormatNegotiation.Mode = mode; + o.FormatNegotiation.AssumeAllNodesCanRead = attested; + }); + if (registerSerializer) + { + b.AddValueSerializer("fast", [0x10], _ => new PassthroughValueSerializer(0x10)); + } + }, + o => o.AppShortName = "framegate") + .BuildServiceProvider(); + } +} diff --git a/tests/UiPath.Caching.Tests/Negotiation/FormatNegotiationIntegrationTests.cs b/tests/UiPath.Caching.Tests/Negotiation/FormatNegotiationIntegrationTests.cs index 02101a515..e1fa9ebb8 100644 --- a/tests/UiPath.Caching.Tests/Negotiation/FormatNegotiationIntegrationTests.cs +++ b/tests/UiPath.Caching.Tests/Negotiation/FormatNegotiationIntegrationTests.cs @@ -13,6 +13,7 @@ using UiPath.Caching.Tests.Broadcast; using UiPath.Caching.Tests.Fakes; using UiPath.Caching.Tests.Redis; +using UiPath.Caching.Tests.Telemetry; namespace UiPath.Caching.Tests.Negotiation; @@ -220,6 +221,51 @@ public async Task An_old_node_keeps_the_writer_on_json_until_it_goes_idle_and_a_ } } + [Fact] + public async Task With_a_3_1_node_on_the_stream_no_frame_is_written_even_when_attested() + { + Assert.SkipUnless(fixture.Enabled, "Set RUN_REDIS_INTEGRATION_TESTS=1 (Docker required) to run."); + Assert.SkipUnless(fixture.StreamsUsable, RedisContainerFixture.StreamsSkipReason); + var app = $"fn{Guid.NewGuid():N}"[..12]; + var topic = new TopicKey($"orders-{Guid.NewGuid():N}"); + await using var raw = await ConnectionMultiplexer.ConnectAsync(fixture.ConnectionString); + var db = raw.GetDatabase(); + _now = DateTimeOffset.FromUnixTimeMilliseconds(ServerMs(await db.ExecuteAsync("TIME"))); + var telemetry = new RecordingTelemetryProvider(); + using var node = Node(app, "node-a", registerSerializer: false, entryMetadata: true, telemetry: telemetry); + var service = node.GetServices().OfType().Single(); + var writes = node.GetRequiredService(); + var cache = (RedisCache)node.GetRequiredService().CreateCache(KnownCacheProviderNames.Redis); + cache.FrameWrites.Should().BeSameAs(writes); + var streamKey = new PrefixStrategy(RedisKeyspaces.Streams, new CacheOptions { AppShortName = app }).GetRedisKey(topic); + var nodeListKey = NodeListStore.KeyFor(new CacheOptions { AppShortName = app }, new RedisCacheOptions()); + + try + { + var subscribed = node.GetRequiredService().Get(KnownTopicNames.RedisStreams).Create(topic); + await BroadcastNodeSignals.ReadyAsync(subscribed, Clock(node)); + await service.TickAsync(Ct); + Clock(node).Advance(TimeSpan.FromSeconds(2)); + await service.TickAsync(Ct); + writes.Allowed.Should().BeTrue(); + + await db.StreamAddAsync(streamKey, "f", "v"); + await db.StreamCreateConsumerGroupAsync(streamKey, "urn:node-old", "0-0"); + await db.StreamReadGroupAsync(streamKey, "urn:node-old", "urn:node-old", ">", 1); + await service.TickAsync(Ct); + + writes.Allowed.Should().BeFalse(); + telemetry.Metrics.Should().ContainSingle(m => m.Name == Metrics.FormatFallback && + m.Properties!["kind"] == "frame" && m.Properties["reason"] == FormatNegotiator.ReasonUnaccountedGroup); + } + finally + { + await service.StopAsync(CancellationToken.None); + await db.KeyDeleteAsync(streamKey); + await db.KeyDeleteAsync(nodeListKey); + } + } + [Fact] public async Task A_node_that_stops_gracefully_never_makes_the_rest_fall_back() { @@ -285,9 +331,15 @@ private static RedisKey HashKey(ConnectionMultiplexer raw, string app, string ke private static ManualTimeProvider Clock(ServiceProvider node) => (ManualTimeProvider)node.GetRequiredService(); - private ServiceProvider Node(string app, string source, bool registerSerializer = true) => + private ServiceProvider Node( + string app, + string source, + bool registerSerializer = true, + bool entryMetadata = false, + ICachingTelemetryProvider? telemetry = null) => new ServiceCollection() .AddLogging() + .AddSingleton(telemetry ?? NullTelemetryProvider.Instance) .AddSingleton(new ManualTimeProvider(_now)) .AddCaching( b => @@ -295,6 +347,8 @@ private ServiceProvider Node(string app, string source, bool registerSerializer b.AddRedisConnection(o => o.ConnectionString = fixture.ConnectionString); b.AddRedis(o => { + o.EntryMetadataEnabled = entryMetadata; + o.FormatNegotiation.AssumeAllNodesCanRead = entryMetadata; o.FormatNegotiation.AdvertiseInterval = TimeSpan.FromSeconds(1); o.FormatNegotiation.ViewInterval = TimeSpan.FromSeconds(1); o.FormatNegotiation.LivenessWindow = TimeSpan.FromSeconds(3); diff --git a/tests/UiPath.Caching.Tests/Negotiation/FormatNegotiatorTests.cs b/tests/UiPath.Caching.Tests/Negotiation/FormatNegotiatorTests.cs index 96c9edaa1..72cac23c1 100644 --- a/tests/UiPath.Caching.Tests/Negotiation/FormatNegotiatorTests.cs +++ b/tests/UiPath.Caching.Tests/Negotiation/FormatNegotiatorTests.cs @@ -537,6 +537,128 @@ public void A_decision_behind_an_open_gate_is_read_without_allocating() best.Should().Be(0); } + [Fact] + public void The_slot_opens_when_every_node_advertises_frame1_and_the_hold_has_passed() + { + var sut = FrameNegotiator(); + var view = View(FrameNode("a"), FrameNode("b")); + + sut.Observe(view); + sut.WritesFrames.Should().BeFalse(); + _clock.Advance(_options.UpgradeHold); + sut.Observe(view); + sut.WritesFrames.Should().BeTrue(); + } + + [Fact] + public void A_node_that_advertises_without_frame1_blocks_the_slot_even_when_attested() + { + _options.AssumeAllNodesCanRead = true; + var sut = FrameNegotiator(); + + Settle(sut, View(FrameNode("a"), Node("older", Binary))); + + sut.WritesFrames.Should().BeFalse(); + sut.Allows(_writer).Should().BeTrue(); + } + + [Fact] + public void An_older_node_that_advertises_0E_for_its_own_serializer_does_not_open_the_slot() + { + var sut = FrameNegotiator(); + + Settle(sut, View(FrameNode("a"), Node("older", ["0E"]))); + + sut.WritesFrames.Should().BeFalse(); + } + + [Theory] + [InlineData(false, FormatNegotiator.ReasonUnaccountedGroup)] + [InlineData(true, FormatNegotiator.ReasonUnaccountedSubscriber)] + public void A_node_the_transport_shows_that_advertises_nothing_blocks_the_frame_slot_even_when_attested( + bool pubSub, string reason) + { + _options.AssumeAllNodesCanRead = true; + var sut = FrameNegotiator(); + var view = View(FrameNode("a")); + Settle(sut, view); + sut.WritesFrames.Should().BeTrue(); + + sut.Observe(pubSub + ? view with { Subscribers = new(true, true, false, 1, ["channel"]) } + : view with { Blockers = ["older"] }); + + sut.WritesFrames.Should().BeFalse(); + sut.Allows(_writer).Should().BeTrue(); + _telemetry.Metrics.Should().Contain(m => m.Name == Metrics.FormatFallback && + m.Properties!["kind"] == "frame" && m.Properties["reason"] == reason); + } + + [Theory] + [InlineData("no transport")] + [InlineData("incomplete view")] + [InlineData("uncountable subscribers")] + public void The_attestation_opens_the_frame_slot_only_where_the_transport_shows_no_node(string scenario) + { + var view = scenario switch + { + "no transport" => new NodeListView([], [], false), + "incomplete view" => View([FrameNode("a")], [], complete: false), + _ => View(FrameNode("a")) with { Subscribers = SubscriberReading.Unknown }, + }; + var sut = FrameNegotiator(); + Settle(sut, view); + sut.WritesFrames.Should().BeFalse(); + + _options.AssumeAllNodesCanRead = true; + Settle(sut, view); + sut.WritesFrames.Should().BeTrue(); + } + + [Fact] + public void A_node_that_joins_without_frame1_closes_the_slot_again() + { + var sut = FrameNegotiator(); + Settle(sut, View(FrameNode("a"))); + sut.WritesFrames.Should().BeTrue(); + + sut.Observe(View(FrameNode("a"), Node("joined", []))); + + sut.WritesFrames.Should().BeFalse(); + } + + [Fact] + public void A_key_move_hold_closes_the_frame_slot() + { + var gate = new FakeGate(null); + var sut = FrameNegotiator(gate); + var view = View(FrameNode("a")); + Settle(sut, view); + sut.WritesFrames.Should().BeTrue(); + + gate.Reason = "key move"; + sut.WritesFrames.Should().BeFalse(); + gate.Reason = null; + sut.WritesFrames.Should().BeFalse(); + Settle(sut, view); + sut.WritesFrames.Should().BeTrue(); + } + + [Fact] + public void The_fallback_metric_names_the_frame_slot() + { + var sut = FrameNegotiator(); + Settle(sut, View(FrameNode("a"))); + + sut.Observe(View(FrameNode("a"), Node("joined", Binary))); + + _telemetry.Metrics.Should().ContainSingle(m => m.Name == Metrics.FormatFallback && + m.Properties!["kind"] == "frame" && m.Properties["reason"] == FormatNegotiator.ReasonMissingFormat); + } + + private static (string Id, NodeAdvertisement Ad) FrameNode(string id) => + Node(id, ["10", NodeAdvertisement.Frame1], new Dictionary> { ["plain"] = ["json", "10"] }); + private static (string Id, NodeAdvertisement Ad) Node(string id, string[] formats, IReadOnlyDictionary>? strict = null, string? instance = null) => (id, new("3.2.0", instance ?? id, ["json", .. formats], strict ?? new Dictionary>())); @@ -545,6 +667,15 @@ private static (string Id, NodeAdvertisement Ad) Node(string id, string[] format private static NodeListView View((string Id, NodeAdvertisement Ad)[] nodes, string[] blockers, bool complete = true) => new([.. nodes.Select(n => new StoredAdvertisement(n.Id, n.Ad, TimeSpan.Zero))], blockers, complete); + private FormatNegotiator FrameNegotiator(IFormatWriteGate? gate = null) => + new( + [new DesiredWrite(_writer, Binary, ["default"], [])], + _options, + _clock, + _telemetry, + writeGate: gate, + frames: new DesiredFrames([NodeAdvertisement.Frame1])); + private FormatNegotiator Negotiator(string[]? policies = null, string[]? others = null) => new([new DesiredWrite(_writer, Binary, policies ?? ["default"], others ?? [])], _options, _clock, _telemetry); diff --git a/tests/UiPath.Caching.Tests/Negotiation/NodeAdvertisementTests.cs b/tests/UiPath.Caching.Tests/Negotiation/NodeAdvertisementTests.cs index 90b807c1a..e60011a77 100644 --- a/tests/UiPath.Caching.Tests/Negotiation/NodeAdvertisementTests.cs +++ b/tests/UiPath.Caching.Tests/Negotiation/NodeAdvertisementTests.cs @@ -12,6 +12,22 @@ public class NodeAdvertisementTests private static CancellationToken Ct => TestContext.Current.CancellationToken; + [Fact] + public void An_advertisement_with_frame1_parses_on_a_node_that_does_not_know_it() + { + var ad = new NodeAdvertisement( + "3.2.0", + "node", + ["json", NodeAdvertisement.Frame1, "10"], + new Dictionary>()); + + var encoded = ad.Encode(); + + encoded.Should().Contain(";vr=json,frame1,10"); + NodeAdvertisement.TryParse(encoded, out var parsed).Should().BeTrue(); + parsed!.ValueReads.Should().Equal("json", "frame1", "10"); + } + [Fact] public void Ad_round_trips_formats_version_and_strict_lists() { diff --git a/tests/UiPath.Caching.Tests/Redis/AdoptedFrameClockIntegrationTests.cs b/tests/UiPath.Caching.Tests/Redis/AdoptedFrameClockIntegrationTests.cs index 68bb5739a..8cf676f70 100644 --- a/tests/UiPath.Caching.Tests/Redis/AdoptedFrameClockIntegrationTests.cs +++ b/tests/UiPath.Caching.Tests/Redis/AdoptedFrameClockIntegrationTests.cs @@ -490,7 +490,7 @@ internal static async Task ShouldMissAsync(FrameHarness h, ICache cache, Reading 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)); + FrameHarness.ReadSends(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); diff --git a/tests/UiPath.Caching.Tests/Redis/EntryFrameFillIntegrationTests.cs b/tests/UiPath.Caching.Tests/Redis/EntryFrameFillIntegrationTests.cs new file mode 100644 index 000000000..f6ec57542 --- /dev/null +++ b/tests/UiPath.Caching.Tests/Redis/EntryFrameFillIntegrationTests.cs @@ -0,0 +1,613 @@ +using Microsoft.Extensions.Logging; +using StackExchange.Redis; +using UiPath.Caching.Redis; + +namespace UiPath.Caching.Tests.Redis; + +// Fills over an expired frame (K5 to K8). Frames are written raw, with StringSet and a TTL. Redis counts a TTL on real time while the node +// judges on its ManualTimeProvider, so every TTL is compared within Slack. +[Collection("RedisIntegration")] +[Trait("Category", "Integration")] +public sealed class EntryFrameFillIntegrationTests(RedisContainerFixture fixture) : IAsyncDisposable +{ + private static readonly TimeSpan Window = FrameWriteRig.Window; + private static readonly TimeSpan Life = TimeSpan.FromSeconds(10); + private static readonly TimeSpan Long = TimeSpan.FromMinutes(10); + private static readonly TimeSpan Slack = TimeSpan.FromSeconds(2); + private static readonly CachePolicy Windowed = FrameWriteRig.Windowed(distributed: Life); + + private readonly FrameWriteRig _rig = new(fixture); + + public enum Expired + { + ByFrame, + ByTtl, + } + + public enum Call + { + TryFill, + ManyFill, + FencedFill, + SetIfChanged, + Stamped, + } + + public enum Replace + { + Script, + RefusedScript, + } + + public enum Verdict + { + Filled, + Replaced, + Unchanged, + } + + public static TheoryData AnchorRows + { + get + { + var data = new TheoryData(); + foreach (var call in Enum.GetValues()) + { + data.Add(call, Replace.Script); + data.Add(call, Replace.RefusedScript); + } + + return data; + } + } + + public static TheoryData ExpiredWrites + { + get + { + var data = new TheoryData(); + foreach (var how in Enum.GetValues()) + { + data.Add(how, false); + data.Add(how, true); + } + + return data; + } + } + + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + private IDatabase Db => _rig.Db; + + private DateTimeOffset Now => _rig.Manual.GetUtcNow(); + + public ValueTask DisposeAsync() => _rig.DisposeAsync(); + + // T1 (round 12, OT1; K5, K6, WA3, WA5; teeth-expiredframe-anchor): a replace that took its own instant, or one UTC reading, would send 10 seconds plus the window after the step back. + [Theory] + [MemberData(nameof(AnchorRows))] + public async Task A_replace_over_an_expired_frame_keeps_the_anchor_of_its_deadline(Call call, Replace replace) + { + var refused = replace == Replace.RefusedScript; + var node = await _rig.NodeAsync( + o => + { + o.ReadScriptsEnabled = true; + o.RemoveTombstone = call == Call.FencedFill ? TimeSpan.FromSeconds(1) : null; + }, + user: refused ? static _ => "-@scripting" : null); + var (id, key) = NewKey(); + await StoreExpiredAsync(node, id, key, "old", Expired.ByFrame); + var instant = Now + Life; + _rig.Pipelines.BeforeWrite = () => + { + _rig.Manual.Advance(TimeSpan.FromSeconds(1)); + _rig.Manual.StepUtc(TimeSpan.FromSeconds(-10)); + return Task.CompletedTask; + }; + if (refused) + { + // The refused script costs a second more, which the transaction after it must not count as life. + _rig.OnCommand = command => + { + if (command == "EVAL") + { + _rig.OnCommand = null; + _rig.Manual.Advance(TimeSpan.FromSeconds(1)); + } + }; + } + + _rig.Log.Take(); + var reported = await CallAsync(node, call, key, instant); + + var (bytes, ttl) = await _rig.ReadRawAsync(id); + var frame = Frame(bytes); + Ms(frame.Expiration).Should().Be(Ms(instant), "the frame expiration is the caller's instant to the tick"); + frame.Inner.ToArray().Should().Equal(Encode(node, "v")); + Within(ttl, (refused ? TimeSpan.FromSeconds(8) : TimeSpan.FromSeconds(9)) + Window); + if (reported is { } expiration) + { + expiration.Should().Be(instant); + } + + var commands = _rig.Log.Take().Select(c => c.Command).ToArray(); + commands.Should().Contain("EVAL"); + if (refused) + { + commands.Should().Contain("EXEC", "the replace is a transaction after the refused script"); + } + } + + [Theory] + [InlineData(Expired.ByFrame)] + [InlineData(Expired.ByTtl)] + public async Task A_fill_replaces_an_expired_frame(Expired how) + { + var node = await _rig.NodeAsync(); + var (id, key) = NewKey(); + await StoreExpiredAsync(node, id, key, "old", how); + var deadline = Now + Life; + + var filled = await node.Cache.TryFillAsync(key, "new", deadline, Windowed, Ct); + + filled.Outcome.Should().Be(FillOutcome.Added); + filled.Expiration.Should().Be(deadline); + (await node.Cache.GetAsync(key, Windowed, Ct)).Should().Be("new"); + var (bytes, ttl) = await _rig.ReadRawAsync(id); + Frame(bytes).Inner.ToArray().Should().Equal(Encode(node, "new")); + Within(ttl, Life + Window); + } + + // T1 (K5; teeth-fillfresh): a fill that replaced every frame would overwrite a live value. + [Fact] + public async Task A_fill_leaves_a_fresh_frame_and_reports_its_logical_expiration() + { + var node = await _rig.NodeAsync(); + var (id, key) = NewKey(); + var at = Now; + var seeded = await StoreFreshAsync(node, id, key, "old"); + + var filled = await node.Cache.TryFillAsync(key, "new", Life, Windowed, Ct); + + filled.Outcome.Should().Be(FillOutcome.Existed); + filled.Existing.Should().Be("old"); + filled.Expiration.Should().BeOnOrBefore(at + Life).And.BeAfter(at + Life - Slack, "the logical expiration of the frame, which FR4 gives"); + (await _rig.ReadRawAsync(id)).Bytes.Should().Equal(seeded); + } + + [Fact] + public async Task A_generated_store_replaces_an_expired_frame() + { + var node = await _rig.NodeAsync(); + var (id, key) = NewKey(); + await StoreExpiredAsync(node, id, key, "old", Expired.ByFrame); + var runs = 0; + + var value = await node.Layered.GetOrAddAsync(key, _ => Task.FromResult($"generated{++runs}"), Life, Windowed, Ct); + + value.Should().Be("generated1"); + runs.Should().Be(1); + Frame((await _rig.ReadRawAsync(id)).Bytes).Inner.ToArray().Should().Equal(Encode(node, "generated1")); + (await node.Cache.GetAsync(key, Windowed, Ct)).Should().Be("generated1"); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task A_batch_fill_replaces_expired_frames_and_leaves_fresh_values(bool scripts) + { + var node = await _rig.NodeAsync(o => o.ReadScriptsEnabled = true, user: scripts ? null : static _ => "-@scripting"); + var (idA, keyA) = NewKey(); + var (idB, keyB) = NewKey(); + await StoreExpiredAsync(node, idA, keyA, "old", Expired.ByFrame); + var fresh = await StoreFreshAsync(node, idB, keyB, "kept"); + var filled = await ((IFillManyTier)node.Redis).TryFillManyAsync([new(keyA, "new"), new KeyValuePair(keyB, "new")], Now + Life, Windowed, Ct); + + filled[0].Outcome.Should().Be(FillOutcome.Added); + filled[1].Outcome.Should().Be(FillOutcome.Existed); + filled[1].Existing.Should().Be("kept"); + Frame((await _rig.ReadRawAsync(idA)).Bytes).Inner.ToArray().Should().Equal(Encode(node, "new")); + (await _rig.ReadRawAsync(idB)).Bytes.Should().Equal(fresh); + } + + // T1 (K5, F11; teeth-fill-cas): a plain overwrite of the expired frame would lose the value that landed since. + [Fact] + public async Task A_value_written_between_the_read_and_the_replace_wins() + { + var node = await _rig.NodeAsync(); + var (id, key) = NewKey(); + var raw = await StoreExpiredAsync(node, id, key, "old", Expired.ByFrame); + node.Redis.BeforeTombstoneSwap = async () => + { + node.Redis.BeforeTombstoneSwap = null; + await Db.StringSetAsync(raw, Encode(node, "other"), Long); + }; + + var filled = await node.Cache.TryFillAsync(key, "new", Life, Windowed, Ct); + + filled.Outcome.Should().Be(FillOutcome.Existed); + filled.Existing.Should().Be("other"); + (await _rig.ReadRawAsync(id)).Bytes.Should().Equal(Encode(node, "other")); + } + + [Fact] + public async Task A_tombstone_written_between_the_read_and_the_replace_fences_the_fill() + { + var node = await _rig.NodeAsync(o => o.RemoveTombstone = TimeSpan.FromSeconds(1)); + var (id, key) = NewKey(); + await StoreExpiredAsync(node, id, key, "old", Expired.ByFrame); + node.Redis.BeforeTombstoneSwap = async () => + { + node.Redis.BeforeTombstoneSwap = null; + await node.Cache.RemoveAsync(key, Ct); + }; + + var filled = await node.Redis.TryFillAfterAsync(key, "new", Now + Life, TimeSpan.FromSeconds(10), Windowed, Ct); + + filled.Outcome.Should().Be(FillOutcome.Removed); + (await _rig.ReadRawAsync(id)).Bytes![0].Should().Be(0x0F, "the tombstone stands"); + } + + // T1 (K6, CS3, CS4; teeth-change-expired): a comparer that ran over the expired frame would answer Unchanged for the equal value. + [Theory] + [MemberData(nameof(ExpiredWrites))] + public async Task SetIfChangedAsync_writes_over_an_expired_frame(Expired how, bool equal) + { + var node = await _rig.NodeAsync(); + var (id, key) = NewKey(); + await StoreExpiredAsync(node, id, key, "old", how); + var comparer = new CountingComparer(); + var deadline = Now + Life; + + var result = await node.Cache.SetIfChangedAsync(key, equal ? "old" : "new", comparer, deadline, Windowed, Ct); + + result.Outcome.Should().Be(ChangeOutcome.Filled); + result.Expiration.Should().Be(deadline); + comparer.Calls.Should().BeEmpty("an expired frame counts as absent"); + var frame = Frame((await _rig.ReadRawAsync(id)).Bytes); + Ms(frame.Expiration).Should().Be(Ms(deadline)); + frame.Inner.ToArray().Should().Equal(Encode(node, equal ? "old" : "new")); + } + + [Fact] + public async Task SetIfChangedAsync_over_an_expired_frame_loses_to_a_value_written_after_the_read_and_judges_it_next() + { + var node = await _rig.NodeAsync(); + var (id, key) = NewKey(); + var raw = await StoreExpiredAsync(node, id, key, "old", Expired.ByFrame); + var comparer = new CountingComparer(); + _rig.Pipelines.BeforeWrite = async () => await Db.StringSetAsync(raw, Encode(node, "other"), Long); + + var result = await node.Cache.SetIfChangedAsync(key, "new", comparer, Life, Windowed, Ct); + + result.Outcome.Should().Be(ChangeOutcome.Replaced); + comparer.Calls.Should().Equal([("other", "new")], "the next attempt judged the value that won"); + Frame((await _rig.ReadRawAsync(id)).Bytes).Inner.ToArray().Should().Equal(Encode(node, "new")); + } + + // T1 (K6, CS2, CS5; teeth-change-once): a late read before the anchored one sends a second transaction. + [Theory] + [InlineData(Verdict.Filled)] + [InlineData(Verdict.Replaced)] + [InlineData(Verdict.Unchanged)] + public async Task SetIfChangedAsync_under_a_windowed_policy_reads_once_and_answers_the_frame_expiration(Verdict verdict) + { + var node = await _rig.NodeAsync(o => o.ReadScriptsEnabled = true); + var (id, key) = NewKey(); + byte[]? seeded = null; + if (verdict == Verdict.Filled) + { + await StoreExpiredAsync(node, id, key, "old", Expired.ByFrame); + } + else + { + seeded = await StoreFreshAsync(node, id, key, "old"); + } + + var frameExpiration = seeded is null ? (DateTimeOffset?)null : Frame(seeded).Expiration; + var deadline = Now + Life; + _rig.Log.Take(); + + var result = await node.Cache.SetIfChangedAsync(key, verdict == Verdict.Replaced ? "new" : verdict == Verdict.Filled ? "v" : "old", StringComparer.Ordinal, deadline, Windowed, Ct); + + result.Outcome.Should().Be(Enum.Parse(verdict.ToString())); + var commands = _rig.Log.Take().Select(c => c.Command).ToArray(); + commands.Should().Equal(verdict == Verdict.Unchanged ? ["MULTI", "GET", "PTTL", "EXEC"] : ["MULTI", "GET", "PTTL", "EXEC", "EVAL"], "one anchored transaction reads, and a write sends once"); + if (verdict == Verdict.Unchanged) + { + result.Expiration.Should().BeOnOrBefore(frameExpiration!.Value).And.BeAfter(frameExpiration.Value - Slack, "the logical expiration holds the window"); + (await _rig.ReadRawAsync(id)).Bytes.Should().Equal(seeded); + } + else + { + result.Expiration.Should().Be(deadline); + Ms(Frame((await _rig.ReadRawAsync(id)).Bytes).Expiration).Should().Be(Ms(deadline), "the stored frame holds the same instant"); + } + } + + // T1 (CS5; teeth-layered-change): a copy kept to the caller's deadline on Unchanged would outlive the frame. + [Theory] + [InlineData(Verdict.Filled)] + [InlineData(Verdict.Replaced)] + [InlineData(Verdict.Unchanged)] + public async Task A_layered_SetIfChanged_never_keeps_a_copy_past_the_frame_expiration(Verdict verdict) + { + var node = await _rig.NodeAsync(); + var (id, key) = NewKey(); + if (verdict == Verdict.Filled) + { + await StoreExpiredAsync(node, id, key, "old", Expired.ByFrame); + } + else + { + await StoreFreshAsync(node, id, key, "old"); + } + + var value = verdict == Verdict.Replaced ? "new" : verdict == Verdict.Filled ? "v" : "old"; + var result = await node.Layered.SetIfChangedAsync(key, value, StringComparer.Ordinal, verdict == Verdict.Unchanged ? Long : Life, Windowed, Ct); + + result.Outcome.Should().Be(Enum.Parse(verdict.ToString())); + (await node.Layered.GetAsync(key, Windowed, Ct)).Should().Be(value, "the copy is served while the frame is fresh"); + _rig.Manual.Advance(Life + TimeSpan.FromSeconds(5)); + (await node.Layered.GetAsync(key, Windowed, Ct)).Should().BeNull("the frame expired, and the copy ended with it"); + } + + // T1 (K7; teeth-stamp-expired): an expired frame with no stamp would make the write an NX that loses to it. + [Fact] + public async Task A_stamped_write_replaces_exactly_the_expired_frame_it_read() + { + var node = await _rig.NodeAsync(); + var (id, key) = NewKey(); + var raw = await StoreExpiredAsync(node, id, key, "old", Expired.ByFrame); + var expired = (byte[]?)await Db.StringGetAsync(raw); + + var (snapshot, stamp) = await node.Redis.ReadStampedAsync(key, Windowed, Ct); + + snapshot.Outcome.Should().Be(SnapshotOutcome.Absent); + stamp.Should().BeOfType(); + ((byte[]?)(RedisValue)stamp!).Should().Equal(expired, "the stamp is the bytes it read"); + (await node.Redis.WriteIfStampAsync(key, "new", Now + Life, Windowed, stamp, Ct)).Should().Be(StampedWrite.Won); + Frame((await _rig.ReadRawAsync(id)).Bytes).Inner.ToArray().Should().Equal(Encode(node, "new")); + + var (otherId, other) = NewKey(); + var otherRaw = await StoreExpiredAsync(node, otherId, other, "old", Expired.ByFrame); + var (_, otherStamp) = await node.Redis.ReadStampedAsync(other, Windowed, Ct); + await Db.StringSetAsync(otherRaw, Encode(node, "landed"), Long); + + (await node.Redis.WriteIfStampAsync(other, "new", Now + Life, Windowed, otherStamp, Ct)).Should().Be(StampedWrite.Lost); + (await _rig.ReadRawAsync(otherId)).Bytes.Should().Equal(Encode(node, "landed"), "the value that landed since stands"); + } + + [Theory] + [InlineData(Expired.ByFrame, true)] + [InlineData(Expired.ByFrame, false)] + [InlineData(Expired.ByTtl, true)] + [InlineData(Expired.ByTtl, false)] + public async Task ReadSnapshotAsync_is_Absent_for_an_expired_frame(Expired how, bool windowed) + { + var node = await _rig.NodeAsync(); + var (id, key) = NewKey(); + await StoreExpiredAsync(node, id, key, "old", how); + + var snapshot = await node.Redis.ReadSnapshotAsync(key, windowed ? Windowed : null, Ct); + + snapshot.Outcome.Should().Be(SnapshotOutcome.Absent); + } + + // T1 (K5, MV5; teeth-emoff-fill): the replace that is judged by the option would leave a node with it off failing every fill. + [Theory] + [InlineData(Expired.ByFrame)] + [InlineData(Expired.ByTtl)] + public async Task A_fill_replaces_an_expired_frame_on_a_node_with_the_option_off(Expired how) + { + var node = await _rig.NodeAsync(metadata: false); + var (id, key) = NewKey(); + await StoreExpiredAsync(node, id, key, "old", how); + + var filled = await node.Cache.TryFillAsync(key, "new", Life, null, Ct); + + filled.Outcome.Should().Be(FillOutcome.Added); + var (bytes, ttl) = await _rig.ReadRawAsync(id); + bytes.Should().Equal(Encode(node, "new"), "a node with the option off writes no frame"); + Within(ttl, Life); + } + + [Fact] + public async Task With_the_option_off_Contains_and_TimeToLive_answer_from_the_key_and_a_refresh_ends_a_fresh_frame_early() + { + var writer = await _rig.NodeAsync(); + var off = await _rig.NodeAsync(o => o.AwaitRefresh = true, metadata: false); + var (_, expired) = NewKey(); + (await writer.Cache.SetAsync(expired, "v", Life, Windowed, Ct)).Should().BeTrue(); + _rig.Manual.Advance(Life + TimeSpan.FromSeconds(1)); + + (await writer.Cache.ContainsAsync(expired, Ct)).Should().BeFalse("a node with the option judges the frame"); + (await off.Cache.ContainsAsync(expired, Ct)).Should().BeTrue("a node with it off answers from the key"); + (await off.Cache.TimeToLiveAsync(expired, Ct)).Should().BeGreaterThan(TimeSpan.FromSeconds(30), "the life the key has, not the frame's"); + + var (_, fresh) = NewKey(); + (await writer.Cache.SetAsync(fresh, "v", Life, Windowed, Ct)).Should().BeTrue(); + (await writer.Cache.GetAsync(fresh, Windowed, Ct)).Should().Be("v"); + _rig.Log.Take(); + + (await off.Cache.RefreshAsync(fresh, Now + Life, null, Ct)).Should().BeTrue(); + + _rig.Log.Take().Select(c => c.Command).Should().ContainSingle(c => c.Contains("EXPIRE", StringComparison.OrdinalIgnoreCase), "the refresh sends one command and reads nothing"); + (await writer.Cache.GetAsync(fresh, Windowed, Ct)).Should().BeNull("the new TTL holds no window, so the fresh frame ended early"); + } + + // The documented limit of FS13: this pins it, so a change to it is seen. + [Fact] + public async Task With_the_option_off_a_refresh_brings_back_an_expired_frame_that_never_expires() + { + var writer = await _rig.NodeAsync(); + var off = await _rig.NodeAsync(o => o.AwaitRefresh = true, metadata: false); + var (id, key) = NewKey(); + (await writer.Cache.SetAsync(key, "seed", Long, null, Ct)).Should().BeTrue(); + var raw = _rig.Raw(id); + await Db.StringSetAsync(raw, EntryFrame.Write(Encode(writer, "old"), DateTimeOffset.MaxValue, Window, null), Window - TimeSpan.FromSeconds(30)); + (await writer.Cache.GetAsync(key, Windowed, Ct)).Should().BeNull("the key's end is inside the window"); + + (await off.Cache.RefreshAsync(key, Now + Long, null, Ct)).Should().BeTrue(); + + (await writer.Cache.GetAsync(key, Windowed, Ct)).Should().Be("old", "no frame-aware node writes a frame that never expires, and the raised TTL brings it back"); + } + + [Fact] + public async Task A_node_with_the_option_off_that_reads_a_windowed_frame_warns_once() + { + var logs = new WarningLogs(); + var writer = await _rig.NodeAsync(); + var off = await _rig.NodeAsync(metadata: false, logs: logs); + var (_, first) = NewKey(); + var (_, second) = NewKey(); + var (_, plain) = NewKey(); + (await writer.Cache.SetAsync(first, "v", Life, Windowed, Ct)).Should().BeTrue(); + (await writer.Cache.SetAsync(second, "v", Life, Windowed, Ct)).Should().BeTrue(); + (await writer.Cache.SetAsync(plain, "v", Life, null, Ct)).Should().BeTrue(); + + (await off.Cache.GetAsync(plain, Ct)).Should().Be("v"); + logs.Messages.Should().NotContain(m => m.Contains("windowed frame", StringComparison.Ordinal), "a plain value is not a windowed frame"); + (await off.Cache.GetAsync(first, Ct)).Should().Be("v"); + (await off.Cache.GetAsync(second, Ct)).Should().Be("v"); + + logs.Messages.Should().ContainSingle(m => m.Contains("windowed frame", StringComparison.Ordinal) && m.Contains("EntryMetadataEnabled", StringComparison.Ordinal)); + } + + private static (string Id, CacheKey Key) NewKey() + { + var id = Guid.NewGuid().ToString("N"); + return (id, $"{{f}}x:{id}"); + } + + private static long Ms(DateTimeOffset at) => at.ToUnixTimeMilliseconds(); + + private static byte[] Encode(FrameWriteRig.Node node, string value) => ((IByteCodecCache)node.Redis).Encode(value, null); + + private static EntryFrame Frame(byte[]? bytes) + { + bytes.Should().NotBeNull(); + EntryFrame.TryRead(bytes, out var frame).Should().BeTrue("the stored value is a frame"); + return frame; + } + + private static void Within(TimeSpan? ttl, TimeSpan expected) + { + ttl.Should().NotBeNull(); + ttl!.Value.Should().BeLessThanOrEqualTo(expected).And.BeGreaterThan(expected - Slack); + } + + private async Task SeedAsync(FrameWriteRig.Node node, string id, CacheKey key) + { + (await node.Cache.SetAsync(key, "seed", Long, null, Ct)).Should().BeTrue(); + return _rig.Raw(id); + } + + /// An expired frame: its frame expiration has passed, or its key's TTL is inside the window. + private async Task StoreExpiredAsync(FrameWriteRig.Node node, string id, CacheKey key, string value, Expired how) + { + var raw = await SeedAsync(node, id, key); + var inner = Encode(node, value); + if (how == Expired.ByFrame) + { + await Db.StringSetAsync(raw, EntryFrame.Write(inner, Now - TimeSpan.FromSeconds(5), Window, null), Window); + } + else + { + await Db.StringSetAsync(raw, EntryFrame.Write(inner, Now + Long, Window, null), Window - TimeSpan.FromSeconds(30)); + } + + return raw; + } + + /// A fresh frame, whose bytes are returned. + private async Task StoreFreshAsync(FrameWriteRig.Node node, string id, CacheKey key, string value) + { + var raw = await SeedAsync(node, id, key); + var bytes = EntryFrame.Write(Encode(node, value), Now + Life, Window, null); + await Db.StringSetAsync(raw, bytes, Life + Window); + return bytes; + } + + private async Task CallAsync(FrameWriteRig.Node node, Call call, CacheKey key, DateTimeOffset instant) + { + switch (call) + { + case Call.TryFill: + var fill = await node.Cache.TryFillAsync(key, "v", instant, Windowed, Ct); + fill.Outcome.Should().Be(FillOutcome.Added); + return fill.Expiration; + case Call.ManyFill: + var many = await ((IFillManyTier)node.Redis).TryFillManyAsync([new KeyValuePair(key, "v")], instant, Windowed, Ct); + many[0].Outcome.Should().Be(FillOutcome.Added); + return many[0].Expiration; + case Call.FencedFill: + (await node.Cache.GetOrAddAsync(key, _ => Task.FromResult("v"), instant, Windowed, Ct)).Should().Be("v"); + return null; + case Call.SetIfChanged: + var change = await node.Cache.SetIfChangedAsync(key, "v", StringComparer.Ordinal, instant, Windowed, Ct); + change.Outcome.Should().Be(ChangeOutcome.Filled); + return change.Expiration; + default: + var (_, stamp) = await node.Redis.ReadStampedAsync(key, Windowed, Ct); + (await node.Redis.WriteIfStampAsync(key, "v", instant, Windowed, stamp, Ct)).Should().Be(StampedWrite.Won); + return null; + } + } + + private sealed class CountingComparer : IEqualityComparer + { + public List<(string? X, string? Y)> Calls { get; } = []; + + public bool Equals(string? x, string? y) + { + Calls.Add((x, y)); + return string.Equals(x, y, StringComparison.Ordinal); + } + + public int GetHashCode(string obj) => obj.GetHashCode(StringComparison.Ordinal); + } + + private sealed class WarningLogs : ILoggerProvider + { + private readonly List _messages = []; + + public string[] Messages + { + get + { + lock (_messages) + { + return [.. _messages]; + } + } + } + + public ILogger CreateLogger(string categoryName) => new Sink(this); + + public void Dispose() + { + } + + private sealed class Sink(WarningLogs owner) : ILogger + { + public IDisposable? BeginScope(TState state) + where TState : notnull => null; + + public bool IsEnabled(LogLevel logLevel) => logLevel >= LogLevel.Warning; + + public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) + { + if (logLevel >= LogLevel.Warning) + { + lock (owner._messages) + { + owner._messages.Add(formatter(state, exception)); + } + } + } + } + } +} diff --git a/tests/UiPath.Caching.Tests/Redis/EntryFrameKeyCommandIntegrationTests.Helpers.cs b/tests/UiPath.Caching.Tests/Redis/EntryFrameKeyCommandIntegrationTests.Helpers.cs new file mode 100644 index 000000000..45a66cea6 --- /dev/null +++ b/tests/UiPath.Caching.Tests/Redis/EntryFrameKeyCommandIntegrationTests.Helpers.cs @@ -0,0 +1,143 @@ +using System.Text; +using StackExchange.Redis; +using UiPath.Caching.Policies; +using UiPath.Caching.Redis; + +namespace UiPath.Caching.Tests.Redis; + +public sealed partial class EntryFrameKeyCommandIntegrationTests +{ + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + private IDatabase Db => _rig.Db; + + private DateTimeOffset Now => _rig.Manual.GetUtcNow(); + + private static TheoryData Cross(T[] values) + { + var data = new TheoryData(); + foreach (var value in values) + { + data.Add(value, false); + data.Add(value, true); + } + + return data; + } + + private static void OnceAfterReply(FrameWriteRig.Node node, Action act) => + node.Redis.AfterAnchoredRead = () => + { + node.Redis.AfterAnchoredRead = null; + act(); + return Task.CompletedTask; + }; + + private static DateTimeOffset Millisecond(DateTimeOffset at) => DateTimeOffset.FromUnixTimeMilliseconds(at.ToUnixTimeMilliseconds()); + + private async Task NodeAsync(bool scripts = false, bool metadata = true, Action? configure = null, ISerializerProxy? serializer = null) + { + if (scripts) + { + Assert.SkipUnless(fixture.SupportsEvalRo && fixture.ServerVersion.Major >= 7, "The read script needs EVAL_RO and PEXPIRETIME."); + } + + return await _rig.NodeAsync( + o => + { + o.ReadScriptsEnabled = scripts; + configure?.Invoke(o); + }, + serializer, + metadata); + } + + private async Task<(CacheKey Key, string Id, RedisKey Raw)> SeedAsync(FrameWriteRig.Node node) + { + var id = Guid.NewGuid().ToString("N"); + CacheKey key = $"k{id}"; + (await node.Cache.SetAsync(key, "seed", Long, Ct)).Should().BeTrue(); + return (key, id, _rig.Raw(id)); + } + + /// A frame whose frame expiration is from the node's now, on a key whose TTL is , the life plus the window by default. + private async Task StoreFrameAsync(FrameWriteRig.Node node, RedisKey raw, string value, TimeSpan life, TimeSpan? keyTtl = null) + { + var inner = ((IByteCodecCache)node.Redis).Encode(value, null); + var bytes = EntryFrame.Write(inner, Now + life, Window, null); + await StoreAsync(raw, bytes, keyTtl ?? life + 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(FrameWriteRig.Node node, RedisKey raw, string value, TimeSpan? keyTtl) => + StoreAsync(raw, ((IByteCodecCache)node.Redis).Encode(value, null), keyTtl); + + /// An expired frame: its frame expiration has passed, or its key's TTL is inside the window. + private Task StoreExpiredAsync(FrameWriteRig.Node node, RedisKey raw, Expired how) => + how == Expired.ByFrame + ? StoreFrameAsync(node, raw, "old", TimeSpan.FromSeconds(-5), Window) + : StoreFrameAsync(node, raw, "old", Long, Window - TimeSpan.FromSeconds(30)); + + private async Task<(bool? Contains, TimeSpan? Left, DateTimeOffset? Expiration)> AskAsync(FrameWriteRig.Node node, CacheKey key, Command command) + { + switch (command) + { + case Command.Contains: + return (await node.Cache.ContainsAsync(key, Ct), null, null); + case Command.TimeToLive: + return (null, await node.Cache.TimeToLiveAsync(key, Ct), null); + default: + return (null, null, await node.Cache.ExpireTimeAsync(key, Ct)); + } + } + + private async Task<(bool Contains, TimeSpan? Left, DateTimeOffset? Expiration)> Ask3Async(FrameWriteRig.Node node, CacheKey key) => + (await node.Cache.ContainsAsync(key, Ct), await node.Cache.TimeToLiveAsync(key, Ct), await node.Cache.ExpireTimeAsync(key, Ct)); + + /// The first call runs the probe of the key and is held at its first command until the result call has started and joined it. + private async Task> JoinedAsync(FrameWriteRig.Node node, CacheKey key, CachePolicy? policy) + { + using var atProbe = new ManualResetEventSlim(); + using var release = new ManualResetEventSlim(); + _rig.OnCommand = _ => + { + _rig.OnCommand = null; + atProbe.Set(); + release.Wait(); + }; + var first = Task.Run(() => node.Cache.GetOrAddAsync(key, _ => Task.FromResult("generated"), Long, policy, Ct).AsTask(), Ct); + atProbe.Wait(Ct); + var joined = node.Cache.GetOrAddResultAsync(key, _ => Task.FromResult("generated"), Long, policy, Ct).AsTask(); + release.Set(); + await first; + return await joined; + } + + /// A header-free serializer that reads any bytes as one string, so a value that only starts like a frame is still a readable value. + private sealed class RawStringSerializer : ISerializerProxy, IHeaderFreeSerializerProxy + { + public byte[]? Serialize(object? value) => value is string text ? Encoding.UTF8.GetBytes(text) : null; + + public T? Deserialize(byte[]? value) => value is null ? default : (T?)(object)"raw"; + + public bool TryDeserialize(string? value, out T? result) + { + result = (T?)(object?)value; + return true; + } + + public bool TryDeserialize(object? value, out T? result) + { + result = (T?)value; + return true; + } + } +} diff --git a/tests/UiPath.Caching.Tests/Redis/EntryFrameKeyCommandIntegrationTests.Refresh.cs b/tests/UiPath.Caching.Tests/Redis/EntryFrameKeyCommandIntegrationTests.Refresh.cs new file mode 100644 index 000000000..fd87a3d13 --- /dev/null +++ b/tests/UiPath.Caching.Tests/Redis/EntryFrameKeyCommandIntegrationTests.Refresh.cs @@ -0,0 +1,1156 @@ +using System.Net; +using System.Net.Sockets; +using StackExchange.Redis; +using UiPath.Caching.Redis; + +namespace UiPath.Caching.Tests.Redis; + +// The refresh of a frame-aware node (K3, RW1 to RW7, RC1 to RC8). Frames are written raw. Redis counts a TTL on real time while the node judges +// on its ManualTimeProvider, so a TTL is compared within RefreshSlack, and time passes by moving the clock and cutting the key's TTL. +public sealed partial class EntryFrameKeyCommandIntegrationTests +{ + private static readonly TimeSpan RefreshLife = TimeSpan.FromSeconds(10); + private static readonly TimeSpan RefreshWindow = FrameWriteRig.Window; + private static readonly TimeSpan RefreshSlack = TimeSpan.FromSeconds(2); + private static readonly byte[] RefreshJson = "\"v\""u8.ToArray(); + private static readonly DateTimeOffset RefreshStamp = DateTimeOffset.UnixEpoch.AddDays(1000); + + public enum RefreshValue + { + Plain, + LooksLikeAFrame, + ValidatorsOnly, + Fresh, + ExpiredByFrame, + ExpiredByTtl, + Bit0WithLastModified, + Bit0WithETag, + Bit0WithBoth, + Tombstone, + Missing, + OtherType, + } + + public enum RefreshTo + { + Later, + Earlier, + Never, + } + + public enum RefreshGate + { + Open, + ClosedAtTheCall, + ClosedBetweenAttempts, + } + + public enum RefreshChange + { + HoldPastTheFrameEnd, + CutTheTtlIntoTheWindow, + WriteTheSameBytesInTheWindow, + } + + public enum RefreshBound + { + TheFrameExpiration, + TheTtl, + } + + public enum RefreshCall + { + Keep, + Drop, + Unwrap, + Never, + } + + public enum RefreshDeny + { + PExpireAt, + Persist, + Set, + } + + public enum RefreshRefusal + { + NoEval, + NoWrite, + } + + public enum RefreshReplacement + { + Plain, + ValidatorsOnly, + Fresh, + ExpiredByFrame, + Removed, + Tombstone, + } + + public static TheoryData RefreshWindowedRows + { + get + { + var data = new TheoryData(); + RefreshValue[] frames = [RefreshValue.Fresh, RefreshValue.ExpiredByFrame, RefreshValue.ExpiredByTtl, RefreshValue.Bit0WithLastModified, RefreshValue.Bit0WithETag, RefreshValue.Bit0WithBoth]; + foreach (var frame in frames) + { + foreach (var to in Enum.GetValues()) + { + foreach (var option in new[] { true, false }) + { + foreach (var closed in new[] { false, true }) + { + foreach (var scripts in new[] { false, true }) + { + foreach (var awaited in new[] { true, false }) + { + data.Add(frame, to, option, closed, scripts, awaited); + } + } + } + } + } + } + + return data; + } + } + + public static TheoryData RefreshUnwrapRows + { + get + { + var data = new TheoryData(); + foreach (var validators in new[] { 1, 2, 3 }) + { + foreach (var windowed in new[] { false, true }) + { + foreach (var gate in new[] { RefreshGate.ClosedAtTheCall, RefreshGate.ClosedBetweenAttempts }) + { + foreach (var to in new[] { RefreshTo.Later, RefreshTo.Never }) + { + foreach (var scripts in new[] { false, true }) + { + data.Add(validators, windowed, gate, to, scripts); + } + } + } + } + } + + return data; + } + } + + public static TheoryData RefreshOneWriteRows + { + get + { + var data = new TheoryData(); + RefreshValue[] values = [RefreshValue.Plain, RefreshValue.LooksLikeAFrame, RefreshValue.ValidatorsOnly, RefreshValue.Fresh, RefreshValue.ExpiredByFrame, RefreshValue.Tombstone, RefreshValue.Missing, RefreshValue.OtherType]; + foreach (var value in values) + { + foreach (var gate in new[] { RefreshGate.Open, RefreshGate.ClosedAtTheCall }) + { + foreach (var to in new[] { RefreshTo.Later, RefreshTo.Never }) + { + data.Add(value, gate, to); + } + } + } + + return data; + } + } + + public static TheoryData RefreshFailedWriteRows + { + get + { + var data = new TheoryData(); + foreach (var deny in Enum.GetValues()) + { + foreach (var (value, gate) in new[] { (RefreshValue.Plain, RefreshGate.Open), (RefreshValue.ValidatorsOnly, RefreshGate.Open), (RefreshValue.ValidatorsOnly, RefreshGate.ClosedAtTheCall), (RefreshValue.ExpiredByFrame, RefreshGate.Open) }) + { + foreach (var to in new[] { RefreshTo.Later, RefreshTo.Never }) + { + foreach (var awaited in new[] { true, false }) + { + if (RefreshDenied(deny, value, gate, to) || value == RefreshValue.ExpiredByFrame) + { + data.Add(deny, value, gate, to, awaited); + } + } + } + } + } + + return data; + } + } + + public static TheoryData RefreshRaceRows + { + get + { + var data = new TheoryData(); + foreach (var caller in new[] { RefreshValue.Plain, RefreshValue.ValidatorsOnly, RefreshValue.Fresh }) + { + foreach (var replacement in Enum.GetValues()) + { + foreach (var closed in new[] { false, true }) + { + foreach (var mode in new[] { false, true }) + { + data.Add(caller, replacement, closed, mode); + } + } + } + } + + return data; + } + } + + public static TheoryData RefreshRefusedRows + { + get + { + var data = new TheoryData(); + var variant = 0; + foreach (var refusal in Enum.GetValues()) + { + RefreshValue[] values = refusal == RefreshRefusal.NoEval + ? [RefreshValue.Plain, RefreshValue.ValidatorsOnly, RefreshValue.Fresh, RefreshValue.ExpiredByFrame, RefreshValue.Tombstone] + : [RefreshValue.Plain, RefreshValue.ValidatorsOnly]; + foreach (var value in values) + { + foreach (var scripts in new[] { false, true }) + { + foreach (var awaited in new[] { true, false }) + { + data.Add(refusal, value, scripts, awaited, variant++ % 8); + } + } + } + } + + return data; + } + } + + public static TheoryData RefreshEndedRows + { + get + { + var data = new TheoryData(); + foreach (var change in Enum.GetValues()) + { + foreach (var bound in Enum.GetValues()) + { + foreach (var call in Enum.GetValues()) + { + foreach (var scripts in new[] { false, true }) + { + foreach (var awaited in new[] { true, false }) + { + data.Add(change, bound, call, scripts, awaited); + } + } + } + } + } + + return data; + } + } + + public static TheoryData RefreshVectors + { + get + { + var data = new TheoryData(); + foreach (var row in EntryFrameVectors.GrammarCases) + { + var (name, bytes, _) = row.Data; + data.Add(name, bytes); + if (bytes.Length >= EntryFrame.HeadLength && bytes[0] == EntryFrame.Header && bytes[1] == EntryFrame.Version && bytes[2] != 0 && (bytes[2] & 1) != 0) + { + // The same bytes with bit 0 cleared and the expiration and window cut out: a frame without a window where the grammar still holds. + data.Add(name + ", no window", [.. bytes[..2], (byte)(bytes[2] & ~1), .. bytes[EntryFrame.HeadLength..]]); + } + } + + return data; + } + } + + private static CancellationToken RefreshCt => TestContext.Current.CancellationToken; + + [Theory] + [MemberData(nameof(RefreshWindowedRows))] + public async Task RefreshAsync_never_changes_a_windowed_frame(RefreshValue frame, RefreshTo to, bool withOption, bool gateClosed, bool scripts, bool awaited) + { + await using var c = await RefreshBeginAsync(scripts, awaited); + await RefreshStoreAsync(c, frame); + if (gateClosed) + { + c.Rig.WriteGate.Close(); + } + + var before = await RefreshRawAsync(c); + + var refreshed = await RefreshCallAsync(c, to, withOption ? FrameWriteRig.Windowed() : new CachePolicy()); + await RefreshSettleAsync(c); + + refreshed.Should().BeFalse(); + RefreshUnchanged(before, await RefreshRawAsync(c)); + var fresh = frame is RefreshValue.Fresh or RefreshValue.Bit0WithLastModified or RefreshValue.Bit0WithETag or RefreshValue.Bit0WithBoth; + (await c.Node.Cache.GetAsync(c.Key, null, RefreshCt)).Should().Be(fresh ? "v" : null); + c.Rig.Manual.Advance(RefreshLife + TimeSpan.FromSeconds(1)); + (await c.Node.Cache.GetAsync(c.Key, null, RefreshCt)).Should().BeNull("a fresh frame ends at its old logical expiration"); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task RefreshAsync_with_read_scripts_off_sends_the_same_script(bool scripts) + { + await using var c = await RefreshBeginAsync(scripts); + (await RefreshCallAsync(c, RefreshTo.Later)).Should().BeTrue("the first refresh loads the script"); + + var (refreshed, server, client) = await RefreshObservedAsync(c, async () => await RefreshCallAsync(c, RefreshTo.Earlier)); + + refreshed.Should().BeTrue(); + client.Select(static call => call.Command).Should().Equal("EVAL"); + server.Select(static call => call.Command).Should().ContainSingle(static command => command.StartsWith("eval", StringComparison.Ordinal)); + RefreshWrites(server).Should().Equal("pexpireat"); + RefreshNear((await RefreshRawAsync(c)).Ttl, TimeSpan.FromSeconds(5)); + } + + [Theory] + [MemberData(nameof(RefreshUnwrapRows))] + public async Task A_refresh_behind_a_closed_gate_unwraps_a_frame_without_a_window(int validators, bool windowed, RefreshGate gate, RefreshTo to, bool scripts) + { + await using var c = await RefreshBeginAsync(scripts); + var now = c.Rig.Manual.GetUtcNow(); + var bytes = windowed ? RefreshFrame(now + TimeSpan.FromHours(1), RefreshWindow, validators) : RefreshFrame(DateTimeOffset.MaxValue, TimeSpan.Zero, validators); + (await c.Rig.Db.StringSetAsync(c.Raw, bytes, windowed ? RefreshWindow + RefreshLife : TimeSpan.FromMinutes(5))).Should().BeTrue(); + var before = await RefreshRawAsync(c); + RefreshGateFor(c, gate); + + var refreshed = await RefreshCallAsync(c, to); + await RefreshSettleAsync(c); + + var after = await RefreshRawAsync(c); + if (windowed) + { + refreshed.Should().BeFalse("a frame with bit 0 is never changed"); + RefreshUnchanged(before, after); + return; + } + + refreshed.Should().BeTrue(); + after.Bytes.Should().Equal(RefreshJson, "the inner value alone, with no 0E 01 head"); + if (to == RefreshTo.Never) + { + after.Ttl.Should().BeNull(); + } + else + { + RefreshNear(after.Ttl, TimeSpan.FromHours(1)); + } + } + + [Theory] + [MemberData(nameof(RefreshOneWriteRows))] + public async Task The_refresh_ends_in_one_write_or_none(RefreshValue value, RefreshGate gate, RefreshTo to) + { + await using var c = await RefreshBeginAsync(); + await RefreshStoreAsync(c, value); + RefreshGateFor(c, gate); + + var (_, server, client) = await RefreshObservedAsync(c, async () => await RefreshCallAsync(c, to)); + + var writes = RefreshWrites(server); + writes.Length.Should().BeLessThanOrEqualTo(1); + writes.Should().NotContain(["setrange", "pexpire", "del", "unlink"]); + if (writes.Length == 1) + { + server.Where(static call => call.Source == "lua").Select(static call => call.Command).Last().Should().Be(writes[0], "nothing runs after the write"); + } + + client.Select(static call => call.Command).Should().Equal("EVAL"); + } + + [Theory] + [MemberData(nameof(RefreshFailedWriteRows))] + public async Task A_refresh_script_that_fails_on_its_write_has_changed_nothing(RefreshDeny deny, RefreshValue value, RefreshGate gate, RefreshTo to, bool awaited) + { + string? name = null; + await using var c = await RefreshBeginAsync(awaited: awaited, user: n => + { + name = n; + return "-" + deny.ToString().ToLowerInvariant(); + }); + await RefreshStoreAsync(c, value); + RefreshGateFor(c, gate); + var before = await RefreshRawAsync(c); + var denied = RefreshDenied(deny, value, gate, to); + + var refreshed = await RefreshCallAsync(c, to); + await RefreshSettleAsync(c); + + refreshed.Should().BeFalse(); + RefreshUnchanged(before, await RefreshRawAsync(c)); + c.Rig.Log.Take(); + (await RefreshCallAsync(c, to)).Should().BeFalse(); + var second = c.Rig.Log.Take().Select(static call => call.Command); + if (denied) + { + second.Should().NotContain("EVAL", "the pause of RC3 started"); + } + else + { + second.Should().Contain("EVAL"); + } + + name.Should().NotBeNull(); + (await c.Node.Cache.GetAsync(c.Key, null, RefreshCt)).Should().Be(value == RefreshValue.ExpiredByFrame ? null : "v", "the old life stands, and the frame that ended at second 1 is a miss"); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task A_refresh_of_a_frame_without_a_window_keeps_its_bytes_while_the_gate_is_open(bool scripts) + { + await using var c = await RefreshBeginAsync(scripts); + await RefreshStoreAsync(c, RefreshValue.ValidatorsOnly); + var before = await RefreshRawAsync(c); + + var (refreshed, server, client) = await RefreshObservedAsync(c, async () => await RefreshCallAsync(c, RefreshTo.Later)); + + refreshed.Should().BeTrue(); + client.Select(static call => call.Command).Should().Equal("EVAL"); + RefreshWrites(server).Should().Equal("pexpireat"); + var after = await RefreshRawAsync(c); + after.Bytes.Should().Equal(before.Bytes); + RefreshNear(after.Ttl, TimeSpan.FromHours(1)); + } + + [Theory] + [MemberData(nameof(RefreshRaceRows))] + public async Task A_refresh_meets_the_value_that_is_there_when_the_script_runs(RefreshValue caller, RefreshReplacement replacement, bool closed, bool mode) + { + // mode: scripts on, no await, a tombstone grace; or scripts off, awaited, none. + await using var c = await RefreshBeginAsync(scripts: mode, awaited: !mode, tombstone: mode); + await RefreshStoreAsync(c, caller); + if (closed) + { + c.Rig.WriteGate.Close(); + } + + (byte[]? Bytes, TimeSpan? Ttl) stored = default; + c.Redis.BeforeRefreshSend = async () => + { + c.Redis.BeforeRefreshSend = null; + await RefreshStoreAsync(c, replacement switch + { + RefreshReplacement.Plain => RefreshValue.Plain, + RefreshReplacement.ValidatorsOnly => RefreshValue.ValidatorsOnly, + RefreshReplacement.Fresh => RefreshValue.Fresh, + RefreshReplacement.ExpiredByFrame => RefreshValue.ExpiredByFrame, + RefreshReplacement.Tombstone => RefreshValue.Tombstone, + _ => RefreshValue.Missing, + }); + stored = await RefreshRawAsync(c); + }; + + var (refreshed, server, client) = await RefreshObservedAsync(c, async () => await RefreshCallAsync(c, RefreshTo.Later)); + await RefreshSettleAsync(c); + + client.Select(static call => call.Command).Should().Equal("EVAL"); + RefreshWrites(server).Length.Should().BeLessThanOrEqualTo(1); + var after = await RefreshRawAsync(c); + switch (replacement) + { + case RefreshReplacement.Plain: + after.Bytes.Should().Equal(stored.Bytes); + RefreshNear(after.Ttl, TimeSpan.FromHours(1)); + refreshed.Should().Be(!mode); + break; + case RefreshReplacement.ValidatorsOnly: + after.Bytes.Should().Equal(closed ? RefreshJson : stored.Bytes); + RefreshNear(after.Ttl, TimeSpan.FromHours(1)); + refreshed.Should().Be(!mode); + break; + default: + RefreshUnchanged(stored, after); + refreshed.Should().BeFalse(); + break; + } + } + + [Theory] + [InlineData(false, false)] + [InlineData(false, true)] + [InlineData(true, false)] + [InlineData(true, true)] + public async Task A_refresh_that_lost_the_race_to_a_windowed_frame_does_not_revive_it(bool awaited, bool scripts) + { + await using var c = await RefreshBeginAsync(scripts, awaited); + await RefreshStoreAsync(c, RefreshValue.Plain); + (byte[]? Bytes, TimeSpan? Ttl) stored = default; + c.Redis.BeforeRefreshSend = async () => + { + c.Redis.BeforeRefreshSend = null; + // A node whose clock is one hour ahead wrote it: the frame expiration is far ahead and the key's TTL is inside the window. + var bytes = RefreshFrame(c.Rig.Manual.GetUtcNow() + TimeSpan.FromHours(1) + RefreshLife, RefreshWindow, 0); + (await c.Rig.Db.StringSetAsync(c.Raw, bytes, TimeSpan.FromSeconds(30))).Should().BeTrue(); + stored = await RefreshRawAsync(c); + }; + + var refreshed = await RefreshCallAsync(c, RefreshTo.Later); + await RefreshSettleAsync(c); + + refreshed.Should().BeFalse(); + RefreshUnchanged(stored, await RefreshRawAsync(c)); + (await c.Node.Cache.GetAsync(c.Key, null, RefreshCt)).Should().BeNull(); + } + + [Fact] + public async Task With_AwaitRefresh_off_a_node_awaits_its_refresh_script_until_one_has_answered() + { + await using var c = await RefreshBeginAsync(awaited: false); + await RefreshStoreAsync(c, RefreshValue.Plain); + + c.Rig.Log.Take(); + (await RefreshCallAsync(c, RefreshTo.Later)).Should().BeFalse("the call that primes the script masks its Boolean reply"); + var first = c.Rig.Log.Take(); + (await RefreshCallAsync(c, RefreshTo.Earlier)).Should().BeFalse(); + var second = c.Rig.Log.Take(); + (await RefreshCallAsync(c, RefreshTo.Later)).Should().BeFalse(); + var third = c.Rig.Log.Take(); + await RefreshSettleAsync(c); + + first.Should().ContainSingle().Which.Should().Match<(string Command, CommandFlags Flags)>(static call => call.Command == "EVAL" && (call.Flags & CommandFlags.FireAndForget) == 0); + second.Should().ContainSingle().Which.Should().Match<(string Command, CommandFlags Flags)>(static call => call.Command == "EVAL" && (call.Flags & CommandFlags.FireAndForget) != 0); + third.Should().ContainSingle().Which.Should().Match<(string Command, CommandFlags Flags)>(static call => call.Command == "EVAL" && (call.Flags & CommandFlags.FireAndForget) != 0); + RefreshNear((await RefreshRawAsync(c)).Ttl, TimeSpan.FromHours(1)); + } + + [Theory] + [InlineData(true, false, false, 16)] + [InlineData(true, true, true, 16)] + [InlineData(true, false, true, 1_048_576)] + [InlineData(true, true, false, 1_048_576)] + [InlineData(false, false, false, 16)] + [InlineData(false, true, true, 16)] + [InlineData(false, false, true, 1_048_576)] + [InlineData(false, true, false, 1_048_576)] + public async Task A_refresh_of_a_plain_value_costs_one_script_and_reads_two_bytes(bool metadata, bool tombstone, bool awaited, int size) + { + await using var c = await RefreshBeginAsync(awaited: awaited, tombstone: tombstone, metadata: metadata); + var value = new byte[size]; + Array.Fill(value, (byte)'x'); + value[0] = (byte)'"'; + value[^1] = (byte)'"'; + (await c.Rig.Db.StringSetAsync(c.Raw, value, TimeSpan.FromMinutes(5))).Should().BeTrue(); + (await RefreshCallAsync(c, RefreshTo.Later)).Should().Be(awaited, "this refresh loads the script"); + + var (_, server, client) = await RefreshObservedAsync(c, async () => + { + var refreshed = await RefreshCallAsync(c, RefreshTo.Earlier); + await RefreshSettleAsync(c); + return refreshed; + }); + + var commands = client.Select(static call => call.Command).Where(static command => command != "PingAsync").ToArray(); + if (metadata) + { + commands.Should().Equal("EVAL"); + var names = server.Select(static call => call.Command).ToArray(); + names.Count(static name => name == "getrange").Should().Be(1); + names.Count(static name => name == "pexpireat").Should().Be(1); + names.Should().NotContain("get"); + } + else if (tombstone) + { + commands.Should().Contain("StringGetRangeAsync").And.NotContain("EVAL"); + } + else + { + commands.Should().Equal("KeyExpireAsync"); + } + } + + [Theory] + [MemberData(nameof(RefreshRefusedRows))] + public async Task A_server_that_refuses_the_refresh_script_gets_no_other_refresh_command(RefreshRefusal refusal, RefreshValue value, bool scripts, bool awaited, int variant) + { + var closed = (variant & 1) != 0; + var to = (variant & 2) != 0 ? RefreshTo.Never : RefreshTo.Later; + var tombstone = (variant & 4) != 0; + string? name = null; + await using var c = await RefreshBeginAsync(scripts, awaited, tombstone, n => + { + name = n; + return refusal == RefreshRefusal.NoEval ? "-@scripting" : "-@write"; + }); + await RefreshStoreAsync(c, value); + if (closed) + { + c.Rig.WriteGate.Close(); + } + + var before = await RefreshRawAsync(c); + c.Rig.Log.Take(); + + (await RefreshCallAsync(c, to)).Should().BeFalse(); + var first = c.Rig.Log.Take().Select(static call => call.Command).ToArray(); + RefreshUnchanged(before, await RefreshRawAsync(c)); + first.Should().Equal("EVAL"); + + // A write that the user may not make still raises inside the script, which is a refusal too. + (await RefreshCallAsync(c, to)).Should().BeFalse(); + c.Rig.Log.Take().Should().BeEmpty("the pause sends nothing"); + c.Rig.Manual.Advance(TimeSpan.FromMinutes(4)); + (await RefreshCallAsync(c, to)).Should().BeFalse(); + c.Rig.Log.Take().Should().BeEmpty("the pause lasts five minutes"); + c.Rig.Manual.Advance(TimeSpan.FromMinutes(1) + TimeSpan.FromSeconds(1)); + (await RefreshCallAsync(c, to)).Should().BeFalse(); + c.Rig.Log.Take().Select(static call => call.Command).Should().Equal("EVAL"); + + await RedisTestKeys.OnPrimariesAsync(c.Rig.Db.Multiplexer, "ACL", "SETUSER", name!, "+@all"); + c.Rig.Manual.Advance(TimeSpan.FromMinutes(5) + TimeSpan.FromSeconds(1)); + var landed = await RefreshCallAsync(c, to); + landed.Should().Be(awaited && value is RefreshValue.Plain or RefreshValue.ValidatorsOnly, "the script lands once the user may run it"); + c.Rig.Log.Take(); + (await RefreshCallAsync(c, RefreshTo.Later)).Should().Be(landed, "the refresh after the first answer is fire-and-forget, or awaited and true for a value that takes it"); + var flags = c.Rig.Log.Take().Single().Flags; + (flags & CommandFlags.FireAndForget).Should().Be(awaited ? CommandFlags.None : CommandFlags.FireAndForget); + } + + [Theory] + [MemberData(nameof(RefreshEndedRows))] + public async Task A_refresh_never_revives_a_frame_that_ended_before_the_command(RefreshChange change, RefreshBound bound, RefreshCall call, bool scripts, bool awaited) + { + await using var c = await RefreshBeginAsync(scripts, awaited); + var now = c.Rig.Manual.GetUtcNow(); + var (expiration, ttl) = bound == RefreshBound.TheFrameExpiration ? (now + RefreshLife, TimeSpan.FromSeconds(120)) : (now + TimeSpan.FromHours(1), RefreshLife + RefreshWindow); + var original = RefreshFrame(expiration, RefreshWindow, 0); + (await c.Rig.Db.StringSetAsync(c.Raw, original, ttl)).Should().BeTrue(); + if (call == RefreshCall.Unwrap) + { + c.Rig.WriteGate.Close(); + } + + (byte[]? Bytes, TimeSpan? Ttl) stored = default; + c.Redis.BeforeRefreshSend = async () => + { + c.Redis.BeforeRefreshSend = null; + switch (change) + { + case RefreshChange.HoldPastTheFrameEnd: + c.Rig.Manual.Advance(RefreshLife + TimeSpan.FromSeconds(1)); + break; + case RefreshChange.CutTheTtlIntoTheWindow: + (await c.Rig.Db.KeyExpireAsync(c.Raw, TimeSpan.FromSeconds(30))).Should().BeTrue(); + break; + default: + (await c.Rig.Db.StringSetAsync(c.Raw, original, TimeSpan.FromSeconds(30))).Should().BeTrue(); + break; + } + + stored = await RefreshRawAsync(c); + }; + + var refreshed = await (call switch + { + RefreshCall.Keep => RefreshCallAsync(c, RefreshTo.Later, FrameWriteRig.Windowed()), + RefreshCall.Drop => RefreshCallAsync(c, RefreshTo.Later, new CachePolicy()), + RefreshCall.Unwrap => RefreshCallAsync(c, RefreshTo.Later), + _ => RefreshCallAsync(c, RefreshTo.Never), + }); + await RefreshSettleAsync(c); + + refreshed.Should().BeFalse(); + RefreshUnchanged(stored, await RefreshRawAsync(c)); + var ended = !(change == RefreshChange.HoldPastTheFrameEnd && bound == RefreshBound.TheTtl); + if (ended) + { + (await c.Node.Cache.GetAsync(c.Key, null, RefreshCt)).Should().BeNull(); + c.Rig.Manual.Advance(TimeSpan.FromHours(2)); + (await c.Node.Cache.GetAsync(c.Key, null, RefreshCt)).Should().BeNull(); + } + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task A_refresh_of_a_key_of_another_type(bool scripts) + { + await using var c = await RefreshBeginAsync(scripts); + await RefreshStoreAsync(c, RefreshValue.OtherType); + + (await RefreshCallAsync(c, RefreshTo.Later)).Should().BeTrue(); + + RefreshNear(await c.Rig.Db.KeyTimeToLiveAsync(c.Raw), TimeSpan.FromHours(1)); + (await c.Rig.Db.KeyTypeAsync(c.Raw)).Should().Be(RedisType.Hash); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task A_script_flush_costs_at_most_one_refresh(bool awaited) + { + await using var c = await RefreshBeginAsync(awaited: awaited); + await RefreshStoreAsync(c, RefreshValue.Plain); + await RefreshCallAsync(c, RefreshTo.Later); + c.Rig.Log.Take(); + foreach (var server in RedisTestKeys.Primaries(c.Rig.Db.Multiplexer)) + { + await server.ScriptFlushAsync(); + } + + var now = c.Rig.Manual.GetUtcNow(); + (await c.Node.Cache.RefreshAsync(c.Key, now + TimeSpan.FromHours(2), null, RefreshCt)).Should().Be(awaited); + await RefreshSettleAsync(c); + if (awaited) + { + RefreshNear((await RefreshRawAsync(c)).Ttl, TimeSpan.FromHours(2)); + } + + await c.Node.Cache.RefreshAsync(c.Key, now + TimeSpan.FromHours(3), null, RefreshCt); + await RefreshSettleAsync(c); + + RefreshNear((await RefreshRawAsync(c)).Ttl, TimeSpan.FromHours(3)); + c.Rig.Log.Take().Select(static call => call.Command).Where(static command => command != "PingAsync").Should().OnlyContain(static command => command == "EVAL"); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task An_unwrap_sets_the_instant_that_todays_refresh_sets(bool scripts) + { + await using var c = await RefreshBeginAsync(scripts); + await c.Rig.Db.StringSetAsync(c.Raw, RefreshFrame(DateTimeOffset.MaxValue, TimeSpan.Zero, 3), TimeSpan.FromMinutes(5)); + c.Rig.WriteGate.Close(); + c.Rig.Manual.Advance(TimeSpan.FromSeconds(10)); + var instant = c.Rig.Manual.GetUtcNow() + TimeSpan.FromSeconds(5); + + (await c.Node.Cache.RefreshAsync(c.Key, instant, null, RefreshCt)).Should().BeTrue(); + + var unwrapped = await RefreshRawAsync(c); + unwrapped.Bytes.Should().Equal(RefreshJson); + RefreshNear(unwrapped.Ttl, TimeSpan.FromSeconds(15)); + // The plain value that the same call refreshes gets the same instant from PEXPIREAT. + await c.Rig.Db.StringSetAsync(c.Raw, RefreshJson, TimeSpan.FromMinutes(5)); + (await c.Node.Cache.RefreshAsync(c.Key, instant, null, RefreshCt)).Should().BeTrue(); + RefreshNear((await RefreshRawAsync(c)).Ttl, TimeSpan.FromSeconds(15)); + } + + [Theory] + [InlineData(RefreshCall.Keep, false)] + [InlineData(RefreshCall.Keep, true)] + [InlineData(RefreshCall.Drop, false)] + [InlineData(RefreshCall.Drop, true)] + [InlineData(RefreshCall.Never, false)] + [InlineData(RefreshCall.Never, true)] + public async Task A_delayed_unwrap_never_passes_the_requested_instant(RefreshCall row, bool scripts) + { + // Keep: 10 seconds ahead. Drop: 1 second ahead, so the instant has passed when the script runs. Never: no TTL. + await using var c = await RefreshBeginAsync(scripts); + await c.Rig.Db.StringSetAsync(c.Raw, RefreshFrame(DateTimeOffset.MaxValue, TimeSpan.Zero, 3), TimeSpan.FromSeconds(60)); + c.Rig.WriteGate.Close(); + var now = c.Rig.Manual.GetUtcNow(); + var admin = c.Rig.Db.Multiplexer; + (await RedisTestKeys.OnPrimariesAsync(admin, "CLIENT", "PAUSE", 2000, "ALL")).Should().NotBeEmpty(); + + var refreshed = row switch + { + RefreshCall.Keep => await c.Node.Cache.RefreshAsync(c.Key, now + TimeSpan.FromSeconds(10), null, RefreshCt), + RefreshCall.Drop => await c.Node.Cache.RefreshAsync(c.Key, now + TimeSpan.FromSeconds(1), null, RefreshCt), + _ => await c.Node.Cache.RefreshAsync(c.Key, DateTimeOffset.MaxValue, null, RefreshCt), + }; + + var after = await RefreshRawAsync(c); + refreshed.Should().BeTrue(); + switch (row) + { + case RefreshCall.Keep: + after.Bytes.Should().Equal(RefreshJson); + after.Ttl.Should().NotBeNull(); + after.Ttl!.Value.Should().BeLessThanOrEqualTo(TimeSpan.FromSeconds(8)).And.BeGreaterThan(TimeSpan.Zero); + break; + case RefreshCall.Drop: + after.Bytes.Should().BeNull("the instant had passed when the script ran, as with PEXPIREAT"); + break; + default: + after.Bytes.Should().Equal(RefreshJson); + after.Ttl.Should().BeNull(); + break; + } + } + + [Theory] + [InlineData(false, true)] + [InlineData(true, true)] + [InlineData(false, false)] + [InlineData(true, false)] + public async Task A_server_without_PXAT_refuses_the_unwrap(bool scripts, bool awaited) + { + await using var c = await RefreshBeginAsync(scripts, awaited); + await c.Rig.Db.StringSetAsync(c.Raw, RefreshFrame(DateTimeOffset.MaxValue, TimeSpan.Zero, 3), TimeSpan.FromMinutes(5)); + c.Rig.WriteGate.Close(); + c.Redis.RefreshScript = FrameScripts.BuildRefresh("PXATX"); + var before = await RefreshRawAsync(c); + + var (refreshed, server, client) = await RefreshObservedAsync(c, async () => await RefreshCallAsync(c, RefreshTo.Later)); + + refreshed.Should().BeFalse(); + RefreshUnchanged(before, await RefreshRawAsync(c)); + client.Select(static call => call.Command).Should().Equal("EVAL"); + RefreshWrites(server).Should().BeEquivalentTo(["set"], "the SET that the server rejected for its option wrote nothing"); + c.Rig.Log.Take(); + (await RefreshCallAsync(c, RefreshTo.Later)).Should().BeFalse(); + var second = c.Rig.Log.Take(); + second.Select(static call => call.Command).Should().Equal(["EVAL"], "the refusal of the option does not start the pause of RC3"); + (second[0].Flags & CommandFlags.FireAndForget).Should().Be(awaited ? CommandFlags.None : CommandFlags.FireAndForget, "the script answered 0, so it is primed and no error was raised"); + + (await RefreshCallAsync(c, RefreshTo.Never)).Should().Be(awaited, "a SET with no option is known to every server"); + await RefreshSettleAsync(c); + var unwrapped = await RefreshRawAsync(c); + unwrapped.Bytes.Should().Equal(RefreshJson); + unwrapped.Ttl.Should().BeNull(); + } + + [Fact] + public async Task RefreshAsync_never_changes_a_tombstone() + { + await using var c = await RefreshBeginAsync(tombstone: true); + await RefreshStoreAsync(c, RefreshValue.Tombstone); + var before = await RefreshRawAsync(c); + + foreach (var to in Enum.GetValues()) + { + (await RefreshCallAsync(c, to)).Should().BeFalse(); + RefreshUnchanged(before, await RefreshRawAsync(c)); + } + } + + [Theory] + [InlineData(23, 3)] + [InlineData(23, 0)] + [InlineData(-1, 0x0F)] + public async Task RefreshAsync_leaves_a_value_that_only_starts_like_a_frame_byte_for_byte(int index, byte value) + { + await using var c = await RefreshBeginAsync(); + var bytes = index < 0 ? EntryFrameVectors.WithInner(value) : EntryFrameVectors.WithByte(index, value); + await c.Rig.Db.StringSetAsync(c.Raw, bytes, TimeSpan.FromMinutes(5)); + + (await RefreshCallAsync(c, RefreshTo.Later)).Should().BeTrue(); + + var after = await RefreshRawAsync(c); + after.Bytes.Should().Equal(bytes); + RefreshNear(after.Ttl, TimeSpan.FromHours(1)); + } + + [Theory] + [MemberData(nameof(RefreshVectors))] + public async Task The_script_and_the_codec_agree_on_every_vector(string name, byte[] bytes) + { + await using var c = await RefreshBeginAsync(); + await c.Rig.Db.StringSetAsync(c.Raw, bytes, TimeSpan.FromMinutes(5)); + c.Rig.WriteGate.Close(); + var isFrame = EntryFrame.TryRead(bytes, out var frame); + + var refreshed = await RefreshCallAsync(c, RefreshTo.Later); + + var after = await RefreshRawAsync(c); + if (isFrame && frame.HasWindow) + { + refreshed.Should().BeFalse(name); + after.Bytes.Should().Equal(bytes); + RefreshNear(after.Ttl, TimeSpan.FromMinutes(5)); + } + else if (isFrame) + { + refreshed.Should().BeTrue(name); + after.Bytes.Should().Equal(frame.Inner.ToArray(), name); + RefreshNear(after.Ttl, TimeSpan.FromHours(1)); + } + else + { + refreshed.Should().BeTrue(name); + after.Bytes.Should().Equal(bytes); + RefreshNear(after.Ttl, TimeSpan.FromHours(1)); + } + } + + private static byte[] RefreshFrame(DateTimeOffset expiration, TimeSpan window, int validators) => + EntryFrame.Write(RefreshJson, expiration, window, EntryValidators.From((validators & 2) != 0 ? "tag" : null, (validators & 1) != 0 ? RefreshStamp : null)); + + private static void RefreshNear(TimeSpan? ttl, TimeSpan expected) + { + ttl.Should().NotBeNull(); + ttl!.Value.Should().BeLessThanOrEqualTo(expected + TimeSpan.FromSeconds(1)).And.BeGreaterThan(expected - RefreshSlack); + } + + private static void RefreshUnchanged((byte[]? Bytes, TimeSpan? Ttl) before, (byte[]? Bytes, TimeSpan? Ttl) after) + { + after.Bytes.Should().Equal(before.Bytes); + if (before.Ttl is null) + { + after.Ttl.Should().BeNull(); + return; + } + + after.Ttl.Should().NotBeNull(); + after.Ttl!.Value.Should().BeLessThanOrEqualTo(before.Ttl.Value + TimeSpan.FromMilliseconds(50)).And.BeGreaterThan(before.Ttl.Value - RefreshSlack); + } + + /// Whether the write that the script ends in is the one command that the user may not run. + private static bool RefreshDenied(RefreshDeny deny, RefreshValue value, RefreshGate gate, RefreshTo to) => + value switch + { + RefreshValue.ExpiredByFrame => false, + _ when gate == RefreshGate.Open || value == RefreshValue.Plain => deny == (to == RefreshTo.Never ? RefreshDeny.Persist : RefreshDeny.PExpireAt), + _ => deny == RefreshDeny.Set, + }; + + private static string[] RefreshWrites(IEnumerable<(string Source, string Command)> server) => + [.. server.Where(static call => call.Source == "lua").Select(static call => call.Command).Where(static command => command is "pexpireat" or "persist" or "set" or "setrange" or "pexpire" or "del" or "unlink" or "expire" or "expireat")]; + + /// A command on the connection of the node comes after a fire-and-forget refresh of it, so its reply says that the refresh has run. + private static Task RefreshSettleAsync(RefreshCase c) => c.Node.Connector.Database.PingAsync(CommandFlags.DemandMaster); + + private static void RefreshGateFor(RefreshCase c, RefreshGate gate) + { + switch (gate) + { + case RefreshGate.ClosedAtTheCall: + c.Rig.WriteGate.Close(); + break; + case RefreshGate.ClosedBetweenAttempts: + c.Rig.Pipelines.FailFirst = () => + { + c.Rig.WriteGate.Close(); + return Task.CompletedTask; + }; + break; + } + } + + private static async Task<(byte[]? Bytes, TimeSpan? Ttl)> RefreshRawAsync(RefreshCase c) => await c.Rig.ReadRawAsync(c.Id); + + private async Task RefreshBeginAsync(bool scripts = false, bool awaited = true, bool tombstone = false, Func? user = null, bool metadata = true) + { + var rig = new FrameWriteRig(fixture); + try + { + void Configure(RedisCacheOptions o) + { + o.ReadScriptsEnabled = scripts; + o.AwaitRefresh = awaited; + o.RemoveTombstone = tombstone ? TimeSpan.FromMinutes(1) : null; + } + + // A user that may not write cannot seed the key, so a node of the default user does. + var seeder = user is null ? null : await rig.NodeAsync(Configure, metadata: metadata); + var node = await rig.NodeAsync(Configure, metadata: metadata, user: user); + var id = Guid.NewGuid().ToString("N"); + CacheKey key = $"r:{id}"; + (await (seeder ?? node).Cache.SetAsync(key, "seed", TimeSpan.FromMinutes(5), RefreshCt)).Should().BeTrue(); + return new RefreshCase(rig, node, id, key, rig.Raw(id)); + } + catch + { + await rig.DisposeAsync(); + throw; + } + } + + private async Task RefreshStoreAsync(RefreshCase c, RefreshValue kind) + { + var now = c.Rig.Manual.GetUtcNow(); + var db = c.Rig.Db; + switch (kind) + { + case RefreshValue.Missing: + await db.KeyDeleteAsync(c.Raw); + return; + case RefreshValue.OtherType: + await db.KeyDeleteAsync(c.Raw); + await db.HashSetAsync(c.Raw, "f", "v"); + await db.KeyExpireAsync(c.Raw, TimeSpan.FromMinutes(5)); + return; + } + + var (bytes, ttl) = kind switch + { + RefreshValue.Plain => (RefreshJson, TimeSpan.FromMinutes(5)), + RefreshValue.LooksLikeAFrame => (EntryFrameVectors.WithByte(23, 3), TimeSpan.FromMinutes(5)), + RefreshValue.ValidatorsOnly => (RefreshFrame(DateTimeOffset.MaxValue, TimeSpan.Zero, 3), TimeSpan.FromMinutes(5)), + RefreshValue.Fresh => (RefreshFrame(now + RefreshLife, RefreshWindow, 0), RefreshLife + RefreshWindow), + RefreshValue.ExpiredByFrame => (RefreshFrame(now - TimeSpan.FromSeconds(5), RefreshWindow, 0), TimeSpan.FromSeconds(120)), + RefreshValue.ExpiredByTtl => (RefreshFrame(now + TimeSpan.FromHours(1), RefreshWindow, 0), TimeSpan.FromSeconds(30)), + RefreshValue.Bit0WithLastModified => (RefreshFrame(now + RefreshLife, RefreshWindow, 1), RefreshLife + RefreshWindow), + RefreshValue.Bit0WithETag => (RefreshFrame(now + RefreshLife, RefreshWindow, 2), RefreshLife + RefreshWindow), + RefreshValue.Bit0WithBoth => (RefreshFrame(now + RefreshLife, RefreshWindow, 3), RefreshLife + RefreshWindow), + RefreshValue.Tombstone => (TombstoneValue.Create(60_000), TimeSpan.FromSeconds(60)), + _ => throw new ArgumentOutOfRangeException(nameof(kind)), + }; + (await db.StringSetAsync(c.Raw, bytes, ttl)).Should().BeTrue(); + } + + private ValueTask RefreshCallAsync(RefreshCase c, RefreshTo to, CachePolicy? policy = null) + { + var now = c.Rig.Manual.GetUtcNow(); + return to switch + { + RefreshTo.Later => c.Node.Cache.RefreshAsync(c.Key, now + TimeSpan.FromHours(1), policy, RefreshCt), + RefreshTo.Earlier => c.Node.Cache.RefreshAsync(c.Key, now + TimeSpan.FromSeconds(5), policy, RefreshCt), + _ => c.Node.Cache.RefreshAsync(c.Key, DateTimeOffset.MaxValue, policy, RefreshCt), + }; + } + + /// Runs with the server's MONITOR open and answers the commands the server ran on the key, the ones inside a script included. + private async Task<(T Result, List<(string Source, string Command)> Server, List<(string Command, CommandFlags Flags)> Client)> RefreshObservedAsync(RefreshCase c, Func> act) + { + Assert.SkipWhen(fixture.IsCluster, "MONITOR sees one node."); + await using var monitor = await RefreshMonitor.StartAsync(fixture.ConnectionString); + c.Rig.Log.Take(); + var result = await act(); + var client = c.Rig.Log.Take(); + var server = await monitor.SettleAsync(c.Node.Connector.Database, c.Id); + return (result, server, client); + } + + private sealed class RefreshCase(FrameWriteRig rig, FrameWriteRig.Node node, string id, CacheKey key, RedisKey raw) : IAsyncDisposable + { + public FrameWriteRig Rig => rig; + + public FrameWriteRig.Node Node => node; + + public string Id => id; + + public CacheKey Key => key; + + public RedisKey Raw => raw; + + public RedisCache Redis => node.Redis; + + public ValueTask DisposeAsync() => rig.DisposeAsync(); + } + + /// A MONITOR connection of its own: the server shows each command with the name of its client, which is lua for the ones a script runs. + private sealed class RefreshMonitor : IAsyncDisposable + { + private readonly TcpClient _tcp = new(); + private readonly List _lines = []; + private readonly TaskCompletionSource _ready = new(TaskCreationOptions.RunContinuationsAsynchronously); + private readonly TaskCompletionSource _seen = new(TaskCreationOptions.RunContinuationsAsynchronously); + private Task _reading = Task.CompletedTask; + private volatile string? _marker; + + public static async Task StartAsync(string connectionString) + { + var options = ConfigurationOptions.Parse(connectionString); + var (host, port) = options.EndPoints[0] switch + { + DnsEndPoint dns => (dns.Host, dns.Port), + IPEndPoint ip => (ip.Address.ToString(), ip.Port), + var other => throw new NotSupportedException(other.ToString()), + }; + var monitor = new RefreshMonitor(); + await monitor._tcp.ConnectAsync(host, port, RefreshCt); + var stream = monitor._tcp.GetStream(); + var expected = 1; + var greeting = string.Empty; + if (!string.IsNullOrEmpty(options.Password)) + { + greeting = options.User is { Length: > 0 } user ? $"AUTH {user} {options.Password}\r\n" : $"AUTH {options.Password}\r\n"; + expected++; + } + + await stream.WriteAsync(System.Text.Encoding.ASCII.GetBytes(greeting + "MONITOR\r\n"), RefreshCt); + monitor._reading = Task.Run(() => monitor.ReadAsync(new StreamReader(stream), expected)); + await monitor._ready.Task.WaitAsync(TimeSpan.FromSeconds(30), RefreshCt); + return monitor; + } + + /// Sends a command of that names nothing of the key and waits until the server shows it, then answers what it showed for . + public async Task> SettleAsync(IDatabase db, string key) + { + var marker = "settled-" + Guid.NewGuid().ToString("N"); + _marker = marker; + await db.StringSetAsync(marker, "1", TimeSpan.FromSeconds(30), flags: CommandFlags.DemandMaster); + await _seen.Task.WaitAsync(TimeSpan.FromSeconds(30), RefreshCt); + lock (_lines) + { + return [.. _lines.Where(line => line.Contains(key, StringComparison.Ordinal) && !line.Contains(marker, StringComparison.Ordinal)).Select(Parse)]; + } + } + + public async ValueTask DisposeAsync() + { + _tcp.Dispose(); + try + { + await _reading; + } + catch (Exception ex) when (ex is IOException or ObjectDisposedException or SocketException) + { + // Expected: the connection is closed under the reader. + } + } + + private static (string Source, string Command) Parse(string line) + { + var open = line.IndexOf('[', StringComparison.Ordinal); + var close = line.IndexOf(']', StringComparison.Ordinal); + var source = line[(open + 1)..close].Contains("lua", StringComparison.Ordinal) ? "lua" : "client"; + var first = line.IndexOf('"', close); + var end = line.IndexOf('"', first + 1); + return (source, line[(first + 1)..end].ToLowerInvariant()); + } + + private async Task ReadAsync(StreamReader reader, int expected) + { + try + { + while (await reader.ReadLineAsync() is { } line) + { + if (expected > 0) + { + if (--expected == 0) + { + _ready.TrySetResult(); + } + + continue; + } + + lock (_lines) + { + _lines.Add(line); + } + + if (_marker is { } marker && line.Contains(marker, StringComparison.Ordinal)) + { + _seen.TrySetResult(); + } + } + } + catch (Exception ex) when (ex is IOException or ObjectDisposedException or SocketException) + { + _ready.TrySetException(ex); + _seen.TrySetException(ex); + } + } + } +} diff --git a/tests/UiPath.Caching.Tests/Redis/EntryFrameKeyCommandIntegrationTests.Result.cs b/tests/UiPath.Caching.Tests/Redis/EntryFrameKeyCommandIntegrationTests.Result.cs new file mode 100644 index 000000000..27d3aa27b --- /dev/null +++ b/tests/UiPath.Caching.Tests/Redis/EntryFrameKeyCommandIntegrationTests.Result.cs @@ -0,0 +1,165 @@ +using System.Text; +using StackExchange.Redis; +using UiPath.Caching.Redis; + +namespace UiPath.Caching.Tests.Redis; + +public sealed partial class EntryFrameKeyCommandIntegrationTests +{ + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task A_result_call_that_joined_a_probe_hit_on_a_windowed_frame_reports_no_expiration(bool metadata) + { + var node = await NodeAsync(metadata: metadata); + var (key, _, raw) = await SeedAsync(node); + await StoreFrameAsync(node, raw, "stored", TimeSpan.FromSeconds(30)); + _rig.Log.Take(); + + var result = await JoinedAsync(node, key, Windowed); + + result.Value.Should().Be("stored"); + result.WasGenerated.Should().BeFalse(); + result.Expiration.Should().BeNull(); + // The shared read alone: one anchored read of the master, nothing after it. + _rig.Log.Take().Select(c => c.Command).Should().Equal(metadata ? ["MULTI", "GET", "PTTL", "EXEC"] : ["GET", "MULTI", "GET", "PTTL", "EXEC"]); + } + + [Theory] + [MemberData(nameof(Races))] + public async Task A_joined_result_call_never_pairs_its_value_with_another_values_deadline(Race race, bool scripts) + { + var node = await NodeAsync(scripts); + var (key, _, raw) = await SeedAsync(node); + var ten = Long * 10; + var firstWindowed = race is Race.WindowedToPlain or Race.WindowedToWindowed; + if (firstWindowed) + { + await StoreFrameAsync(node, raw, "first", TimeSpan.FromSeconds(30)); + } + else + { + await StorePlainAsync(node, raw, "first", Long); + } + + async Task Replace() + { + switch (race) + { + case Race.WindowedToPlain or Race.PlainToPlain: + await StorePlainAsync(node, raw, "second", ten); + break; + case Race.PlainToWindowed or Race.WindowedToWindowed: + await StoreFrameAsync(node, raw, "second", ten); + break; + default: + await Db.KeyDeleteAsync(raw); + break; + } + } + + var done = false; + if (firstWindowed) + { + // The windowed probe is the anchored read: rewrite the key when its reply has arrived. + node.Redis.AfterAnchoredRead = () => + { + node.Redis.AfterAnchoredRead = null; + done = true; + return Replace(); + }; + } + else + { + // The plain probe is no anchored read: rewrite the key when the attribution's read is about to be sent. + node.Redis.BeforeAnchoredRead = () => + { + node.Redis.BeforeAnchoredRead = null; + done = true; + return Replace(); + }; + } + + var result = await JoinedAsync(node, key, firstWindowed ? Windowed : null); + + done.Should().BeTrue(); + result.Value.Should().Be("first"); + if (race == Race.PlainToPlain) + { + result.Expiration.Should().BeCloseTo(Now + ten, Slack); + } + else + { + result.Expiration.Should().BeNull(); + } + } + + [Fact] + public async Task A_result_call_that_joined_a_probe_hit_on_a_plain_value_reads_three_bytes_and_the_ttl_in_one_transaction() + { + var node = await NodeAsync(); + var (key, _, _) = await SeedAsync(node); + _rig.Log.Take(); + + var result = await JoinedAsync(node, key, null); + + result.Value.Should().Be("seed"); + result.Expiration.Should().BeCloseTo(Now + Long, Slack); + var log = _rig.Log.Take(); + log.Select(c => c.Command).Should().Equal("GET", "MULTI", "StringGetRangeAsync", "PTTL", "EXEC"); + log.Single(c => c.Command == "EXEC").Flags.Should().HaveFlag(CommandFlags.DemandMaster); + } + + [Theory] + [MemberData(nameof(LookAlikes))] + public async Task A_result_call_that_joined_a_plain_value_that_only_starts_like_a_frame_reports_its_ttl(string name, byte[] bytes) + { + name.Should().NotBeNull(); + foreach (var scripts in new[] { false, true }) + { + var node = await NodeAsync(scripts, serializer: new RawStringSerializer()); + var (key, _, raw) = await SeedAsync(node); + await StoreAsync(raw, bytes, Long); + + var result = await JoinedAsync(node, key, null); + + result.WasGenerated.Should().BeFalse(); + result.Expiration.Should().BeCloseTo(Now + Long, Slack); + } + } + + [Fact] + public async Task A_result_call_that_joined_a_fill_that_met_a_fresh_frame_reports_the_logical_expiration_of_that_read() + { + var node = await NodeAsync(configure: o => o.RemoveTombstone = TimeSpan.FromSeconds(30)); + var id = Guid.NewGuid().ToString("N"); + CacheKey key = $"k{id}"; + (await node.Cache.SetAsync(key, "seed", Long, Ct)).Should().BeTrue(); + var raw = _rig.Raw(id); + (await node.Cache.RemoveAsync(key, Ct)).Should().BeTrue(); + var started = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var first = node.Cache.GetOrAddAsync( + key, + async _ => + { + started.SetResult(); + await release.Task; + return "generated"; + }, + Long, + Windowed, + Ct).AsTask(); + await started.Task; + var joined = node.Cache.GetOrAddResultAsync(key, _ => Task.FromResult("generated"), Long, Windowed, Ct).AsTask(); + await Db.KeyDeleteAsync(raw); + await StoreFrameAsync(node, raw, "winner", TimeSpan.FromSeconds(30)); + release.SetResult(); + await first; + + var result = await joined; + + result.Value.Should().Be("winner"); + result.Expiration.Should().BeCloseTo(Now + TimeSpan.FromSeconds(30), Slack); + } +} diff --git a/tests/UiPath.Caching.Tests/Redis/EntryFrameKeyCommandIntegrationTests.cs b/tests/UiPath.Caching.Tests/Redis/EntryFrameKeyCommandIntegrationTests.cs new file mode 100644 index 000000000..b66768240 --- /dev/null +++ b/tests/UiPath.Caching.Tests/Redis/EntryFrameKeyCommandIntegrationTests.cs @@ -0,0 +1,415 @@ +using StackExchange.Redis; +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 node 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 EntryFrameKeyCommandIntegrationTests(RedisContainerFixture fixture) : IAsyncDisposable +{ + private static readonly TimeSpan Window = FrameWriteRig.Window; + 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 static readonly CachePolicy Windowed = FrameWriteRig.Windowed(); + + private readonly FrameWriteRig _rig = new(fixture); + + public enum Expired + { + ByFrame, + ByTtl, + } + + public enum Command + { + Contains, + TimeToLive, + ExpireTime, + } + + public enum Race + { + WindowedToPlain, + PlainToWindowed, + WindowedToWindowed, + Removed, + PlainToPlain, + } + + public static TheoryData ExpiredByScripts => Cross([Expired.ByFrame, Expired.ByTtl]); + + public static TheoryData UtcSteps + { + get + { + var data = new TheoryData(); + foreach (var command in Enum.GetValues()) + { + foreach (var scripts in new[] { false, true }) + { + foreach (var step in new[] { -10, 10, 0 }) + { + data.Add(command, scripts, step); + } + } + } + + return data; + } + } + + public static TheoryData Races + { + get + { + var data = new TheoryData(); + foreach (var race in Enum.GetValues()) + { + data.Add(race, false); + data.Add(race, true); + } + + return data; + } + } + + /// The entries of the vectors that are no frame but pass the three-byte test for a window. + public static TheoryData LookAlikes + { + get + { + var data = new TheoryData(); + foreach (var row in EntryFrameVectors.GrammarCases) + { + var (name, bytes, valid) = (row.Data.Item1, row.Data.Item2, row.Data.Item3); + if (!valid && bytes.Length >= 3 && EntryFrame.LooksWindowed(bytes.AsSpan(0, 3))) + { + data.Add(name, bytes); + } + } + + return data; + } + } + + public ValueTask DisposeAsync() => _rig.DisposeAsync(); + + [Fact] + public async Task TryAddAsync_over_an_expired_frame_keeps_the_anchor_of_its_instant() + { + var node = await NodeAsync(); + var (key, id, raw) = await SeedAsync(node); + await StoreExpiredAsync(node, raw, Expired.ByTtl); + var instant = Millisecond(Now + TimeSpan.FromSeconds(10)); + var lost = false; + var stepped = false; + _rig.OnCommand = command => + { + if (stepped) + { + return; + } + + if (!lost) + { + lost = command == "SET"; + return; + } + + stepped = true; + _rig.Manual.Advance(TimeSpan.FromSeconds(1)); + _rig.Manual.StepUtc(TimeSpan.FromSeconds(-10)); + }; + + (await node.Cache.TryAddAsync(key, "v", instant, Windowed, Ct)).Should().BeTrue(); + + stepped.Should().BeTrue(); + var (bytes, ttl) = await _rig.ReadRawAsync(id); + EntryFrame.TryRead(bytes!, out var frame).Should().BeTrue(); + frame.Expiration.ToUnixTimeMilliseconds().Should().Be(instant.ToUnixTimeMilliseconds()); + ttl.Should().BeLessThanOrEqualTo(TimeSpan.FromSeconds(9) + Window + TimeSpan.FromMilliseconds(100)); + ttl.Should().BeGreaterThan(Window); + } + + [Theory] + [MemberData(nameof(ExpiredByScripts))] + public async Task TryAddAsync_adds_over_an_expired_frame(Expired how, bool scripts) + { + var node = await NodeAsync(scripts); + var (key, id, raw) = await SeedAsync(node); + await StoreExpiredAsync(node, raw, how); + + (await node.Cache.TryAddAsync(key, "v", Long, Windowed, Ct)).Should().BeTrue(); + + var (bytes, ttl) = await _rig.ReadRawAsync(id); + EntryFrame.TryRead(bytes!, out var frame).Should().BeTrue(); + frame.Inner.ToArray().Should().Equal(((IByteCodecCache)node.Redis).Encode("v", null)); + ttl.Should().BeGreaterThan(Long); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task TryAddAsync_loses_to_a_fresh_frame(bool scripts) + { + var node = await NodeAsync(scripts); + var (key, id, raw) = await SeedAsync(node); + await StoreFrameAsync(node, raw, "old", TimeSpan.FromSeconds(30)); + var before = await _rig.ReadRawAsync(id); + + (await node.Cache.TryAddAsync(key, "v", Long, Windowed, Ct)).Should().BeFalse(); + (await node.Cache.TryAddAsync(key, "v", Now + Long, Windowed, Ct)).Should().BeFalse(); + + (await _rig.ReadRawAsync(id)).Bytes.Should().Equal(before.Bytes); + } + + [Theory] + [MemberData(nameof(LookAlikes))] + public async Task TryAddAsync_loses_to_a_value_that_only_starts_like_a_frame(string name, byte[] bytes) + { + name.Should().NotBeNull(); + var node = await NodeAsync(); + var (key, id, raw) = await SeedAsync(node); + await StoreAsync(raw, bytes, Long); + + (await node.Cache.TryAddAsync(key, "v", Long, Windowed, Ct)).Should().BeFalse(); + + (await _rig.ReadRawAsync(id)).Bytes.Should().Equal(bytes); + } + + [Theory] + [MemberData(nameof(ExpiredByScripts))] + public async Task ContainsAsync_is_false_for_an_expired_frame_and_true_for_a_fresh_one(Expired how, bool scripts) + { + var node = await NodeAsync(scripts); + var (key, _, raw) = await SeedAsync(node); + + await StoreFrameAsync(node, raw, "v", TimeSpan.FromSeconds(30)); + (await node.Cache.ContainsAsync(key, Ct)).Should().BeTrue(); + + await StoreExpiredAsync(node, raw, how); + (await node.Cache.ContainsAsync(key, Ct)).Should().BeFalse(); + } + + [Theory] + [InlineData(false, true)] + [InlineData(false, false)] + [InlineData(true, true)] + [InlineData(true, false)] + public async Task ContainsAsync_whose_reply_waits_past_the_logical_end_is_false(bool scripts, bool held) + { + var node = await NodeAsync(scripts); + var (key, _, raw) = await SeedAsync(node); + await StoreFrameAsync(node, raw, "v", TimeSpan.FromSeconds(1)); + if (held) + { + OnceAfterReply(node, () => _rig.Manual.Advance(Hold)); + } + + (await node.Cache.ContainsAsync(key, Ct)).Should().Be(!held); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task TimeToLiveAsync_and_ExpireTimeAsync_answer_the_logical_expiration(bool scripts) + { + var node = await NodeAsync(scripts); + var (key, _, raw) = await SeedAsync(node); + await StoreFrameAsync(node, raw, "v", TimeSpan.FromSeconds(30)); + + (await node.Cache.TimeToLiveAsync(key, Ct)).Should().BeCloseTo(TimeSpan.FromSeconds(30), Slack); + (await node.Cache.ExpireTimeAsync(key, Ct)).Should().BeCloseTo(Now + TimeSpan.FromSeconds(30), Slack); + } + + [Theory] + [MemberData(nameof(ExpiredByScripts))] + public async Task TimeToLiveAsync_is_null_for_an_expired_frame(Expired how, bool scripts) + { + var node = await NodeAsync(scripts); + var (key, _, raw) = await SeedAsync(node); + await StoreExpiredAsync(node, raw, how); + + (await node.Cache.TimeToLiveAsync(key, Ct)).Should().BeNull(); + (await node.Cache.ExpireTimeAsync(key, Ct)).Should().BeNull(); + } + + [Theory] + [MemberData(nameof(UtcSteps))] + public async Task The_key_commands_ignore_a_step_of_the_UTC_clock_during_their_read(Command command, bool scripts, int step) + { + var node = await NodeAsync(scripts); + var (key, _, raw) = await SeedAsync(node); + + await StoreFrameAsync(node, raw, "v", TimeSpan.FromHours(1), Window + TimeSpan.FromSeconds(1)); + OnceAfterReply(node, () => + { + _rig.Manual.Advance(Hold); + _rig.Manual.StepUtc(TimeSpan.FromSeconds(step)); + }); + var expired = await AskAsync(node, key, command); + expired.Contains.Should().NotBe(true); + expired.Left.Should().BeNull(); + expired.Expiration.Should().BeNull(); + + await StoreFrameAsync(node, raw, "v", TimeSpan.FromHours(1), Window + TimeSpan.FromSeconds(10)); + OnceAfterReply(node, () => + { + _rig.Manual.Advance(Hold); + _rig.Manual.StepUtc(TimeSpan.FromSeconds(step)); + }); + var alive = await AskAsync(node, key, command); + switch (command) + { + case Command.Contains: + alive.Contains.Should().BeTrue(); + break; + case Command.TimeToLive: + alive.Left.Should().BeCloseTo(Hold, TimeSpan.FromSeconds(1)); + break; + default: + alive.Expiration.Should().BeCloseTo(Now + Hold, TimeSpan.FromSeconds(1)); + break; + } + } + + [Theory] + [InlineData(Command.TimeToLive, false)] + [InlineData(Command.TimeToLive, true)] + [InlineData(Command.ExpireTime, false)] + [InlineData(Command.ExpireTime, true)] + public async Task TimeToLiveAsync_of_a_windowed_frame_counts_from_before_the_send(Command command, bool scripts) + { + var node = await NodeAsync(scripts); + var (key, _, raw) = await SeedAsync(node); + await StoreFrameAsync(node, raw, "v", TimeSpan.FromHours(1), Window + TimeSpan.FromSeconds(10)); + OnceAfterReply(node, () => _rig.Manual.Advance(Hold)); + var answer = await AskAsync(node, key, command); + if (command == Command.TimeToLive) + { + answer.Left.Should().BeCloseTo(Hold, TimeSpan.FromSeconds(1)); + } + else + { + answer.Expiration.Should().BeCloseTo(Now + Hold, TimeSpan.FromSeconds(1)); + } + + await StoreFrameAsync(node, raw, "v", TimeSpan.FromHours(1), Window + TimeSpan.FromSeconds(1)); + OnceAfterReply(node, () => _rig.Manual.Advance(Hold)); + var gone = await AskAsync(node, key, command); + gone.Left.Should().BeNull(); + gone.Expiration.Should().BeNull(); + } + + [Fact] + public async Task TimeToLiveAsync_of_a_plain_value_reads_its_three_bytes_and_its_ttl_in_one_transaction() + { + var node = await NodeAsync(); + var (key, _, _) = await SeedAsync(node); + _rig.Log.Take(); + + (await node.Cache.TimeToLiveAsync(key, Ct)).Should().BeCloseTo(Long, Slack); + + _rig.Log.Take().Select(c => c.Command).Should().Equal("MULTI", "StringGetRangeAsync", "PTTL", "EXEC"); + } + + [Fact] + public async Task TimeToLiveAsync_of_a_windowed_frame_reads_value_and_ttl_in_one_transaction() + { + var node = await NodeAsync(); + var (key, _, raw) = await SeedAsync(node); + await StoreFrameAsync(node, raw, "v", TimeSpan.FromSeconds(30)); + _rig.Log.Take(); + + (await node.Cache.TimeToLiveAsync(key, Ct)).Should().BeCloseTo(TimeSpan.FromSeconds(30), Slack); + + var log = _rig.Log.Take(); + log.Select(c => c.Command).Should().Equal("MULTI", "StringGetRangeAsync", "PTTL", "EXEC", "MULTI", "GET", "PTTL", "EXEC"); + log.Where(c => c.Command is "EXEC").Should().OnlyContain(c => c.Flags.HasFlag(CommandFlags.DemandMaster)); + } + + [Fact] + public async Task ContainsAsync_of_a_plain_value_takes_one_round_trip_and_reads_three_bytes() + { + var node = await NodeAsync(); + var (key, _, _) = await SeedAsync(node); + _rig.Log.Take(); + + (await node.Cache.ContainsAsync(key, Ct)).Should().BeTrue(); + + _rig.Log.Take().Select(c => c.Command).Should().Equal("BATCH", "EXISTS", "StringGetRangeAsync", "Execute"); + } + + [Theory] + [MemberData(nameof(LookAlikes))] + public async Task ContainsAsync_and_TimeToLiveAsync_judge_a_value_that_only_starts_like_a_frame_as_a_plain_value(string name, byte[] bytes) + { + name.Should().NotBeNull(); + foreach (var scripts in new[] { false, true }) + { + var node = await NodeAsync(scripts); + var (key, _, raw) = await SeedAsync(node); + await StoreAsync(raw, bytes, Long); + + (await node.Cache.ContainsAsync(key, Ct)).Should().BeTrue(); + (await node.Cache.TimeToLiveAsync(key, Ct)).Should().BeCloseTo(Long, Slack); + } + } + + [Fact] + public async Task With_read_scripts_on_the_three_commands_answer_the_same() + { + var off = await NodeAsync(); + var on = await NodeAsync(scripts: true); + var states = new Func[] + { + raw => StorePlainAsync(off, raw, "p", Long), + raw => StoreFrameAsync(off, raw, "f", TimeSpan.FromSeconds(30)), + raw => StoreExpiredAsync(off, raw, Expired.ByFrame), + raw => StoreExpiredAsync(off, raw, Expired.ByTtl), + raw => Db.KeyDeleteAsync(raw), + }; + var (key, _, raw) = await SeedAsync(off); + foreach (var state in states) + { + await state(raw); + var a = await Ask3Async(off, key); + var b = await Ask3Async(on, key); + b.Contains.Should().Be(a.Contains); + if (a.Left is { } left) + { + b.Left.Should().BeCloseTo(left, Slack); + b.Expiration.Should().BeCloseTo(a.Expiration!.Value, Slack); + } + else + { + b.Left.Should().BeNull(); + b.Expiration.Should().BeNull(); + } + } + } + + [Fact] + public async Task With_the_option_off_the_commands_send_what_they_sent_before() + { + var node = await NodeAsync(metadata: false, configure: o => o.AwaitRefresh = true); + var (key, _, _) = await SeedAsync(node); + _rig.Log.Take(); + + (await node.Cache.ContainsAsync(key, Ct)).Should().BeTrue(); + _rig.Log.Take().Select(c => c.Command).Should().Equal("EXISTS"); + + (await node.Cache.TimeToLiveAsync(key, Ct)).Should().BeCloseTo(Long, Slack); + _rig.Log.Take().Select(c => c.Command).Should().Equal("PTTL"); + + (await node.Cache.TryAddAsync(key, "v", Long, null, Ct)).Should().BeFalse(); + _rig.Log.Take().Select(c => c.Command).Should().Equal("SET"); + + (await node.Cache.RefreshAsync(key, Long, null, Ct)).Should().BeTrue(); + _rig.Log.Take().Select(c => c.Command).Should().Equal("KeyExpireAsync"); + } +} diff --git a/tests/UiPath.Caching.Tests/Redis/EntryFrameReadAllocationTests.cs b/tests/UiPath.Caching.Tests/Redis/EntryFrameReadAllocationTests.cs new file mode 100644 index 000000000..81a9973b8 --- /dev/null +++ b/tests/UiPath.Caching.Tests/Redis/EntryFrameReadAllocationTests.cs @@ -0,0 +1,116 @@ +using Microsoft.Extensions.DependencyInjection; +using StackExchange.Redis; +using UiPath.Caching.Config; +using UiPath.Caching.Redis; + +namespace UiPath.Caching.Tests.Redis; + +/// A value-only hit under a format with a window is one transaction of four commands where a plain hit is one GET (AV6); the two costs are pinned side by side. +[Collection(RedisAllocationCollection.Name)] +[Trait("Category", "Integration")] +public sealed class EntryFrameReadAllocationTests(RedisContainerFixture fixture, ITestOutputHelper output) : IDisposable +{ + private const int Rounds = 7; + private const int PerRound = 200; + + // Measured by this test in Release against Redis 7.4, scripts off: the fewest over 7 rounds of 200 hits after one warm-up round, the bytes allocated + // on the calling thread before the first await of the hit completes, whole bytes per call. + // net8.0: plain GET hit 480 B, windowed hit 3968 B. net10.0: plain GET hit 480 B, windowed hit 3968 B. + private const long PlainHitBytes = 480; + private const long WindowedHitBytes = 3968; + private static readonly TimeSpan Ttl = TimeSpan.FromMinutes(2); + private static readonly CachePolicy Windowed = new() + { + FailSafeEnabled = true, + FailSafeDistributedEnabled = true, + FailSafeDistributedMaxStaleAge = TimeSpan.FromMinutes(1), + DistributedExpiration = Ttl, + }; + + private readonly string _app = $"ra{Guid.NewGuid():N}"[..10]; + private readonly List _nodes = []; + + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + [Fact] + public async Task A_windowed_hit_allocates_its_pinned_bytes_and_a_plain_hit_its_own() + { + Assert.SkipUnless(fixture.Enabled, "Set RUN_REDIS_INTEGRATION_TESTS=1 (Docker required) to run."); +#if DEBUG + Assert.Skip("Allocation pins are measured in Release."); +#endif + Assert.SkipWhen(Environment.GetEnvironmentVariable("CORECLR_ENABLE_PROFILING") == "1", "A profiler is attached, so the allocation count is not the library's alone."); + var cache = Node(); + var plain = await PerHitAsync(cache, null); + var windowed = await PerHitAsync(cache, Windowed); + + output.WriteLine($"{RuntimeTfm()}: plain GET hit {plain} B, windowed hit {windowed} B"); + plain.Should().BeLessThanOrEqualTo(PlainHitBytes, $"a plain hit allocated {plain} B"); + windowed.Should().BeLessThanOrEqualTo(WindowedHitBytes, $"a windowed hit allocated {windowed} B"); + } + + public void Dispose() + { + foreach (var node in _nodes) + { + node.Dispose(); + } + + GC.SuppressFinalize(this); + } + + private static string RuntimeTfm() => Environment.Version.Major.ToString(System.Globalization.CultureInfo.InvariantCulture); + + private static async Task PerHitAsync(ICache cache, CachePolicy? policy) + { + var keys = Enumerable.Range(0, (Rounds + 1) * PerRound).Select(i => (CacheKey)$"alloc:{Guid.NewGuid():N}:{i}").ToArray(); + foreach (var key in keys) + { + (await cache.SetAsync(key, "v", Ttl, policy, Ct)).Should().BeTrue(); + } + + for (var i = 0; i < PerRound; i++) + { + (await cache.GetAsync(keys[i], policy, Ct)).Should().Be("v"); + } + + var fewest = long.MaxValue; + for (var round = 1; round <= Rounds; round++) + { + var allocated = 0L; + for (var i = 0; i < PerRound; i++) + { + var before = GC.GetAllocatedBytesForCurrentThread(); + var pending = cache.GetAsync(keys[(round * PerRound) + i], policy, Ct); + allocated += GC.GetAllocatedBytesForCurrentThread() - before; + (await pending).Should().Be("v"); + } + + fewest = Math.Min(fewest, allocated / PerRound); + } + + return fewest; + } + + private ICache Node() + { + var node = new ServiceCollection() + .AddSingleton(new ManualTimeProvider(DateTimeOffset.UnixEpoch)) + .AddLogging() + .AddCaching( + b => + { + b.AddRedisConnection(o => o.ConnectionString = fixture.ConnectionString); + b.AddRedis(o => + { + o.ReadScriptsEnabled = false; + o.EntryMetadataEnabled = true; + o.FormatNegotiation.Mode = FormatNegotiationMode.Force; + }); + }, + o => o.AppShortName = _app) + .BuildServiceProvider(); + _nodes.Add(node); + return node.GetRequiredService().CreateCache(KnownCacheProviderNames.Redis); + } +} diff --git a/tests/UiPath.Caching.Tests/Redis/EntryFrameReadIntegrationTests.Anchor.cs b/tests/UiPath.Caching.Tests/Redis/EntryFrameReadIntegrationTests.Anchor.cs index 67c298618..de094a96e 100644 --- a/tests/UiPath.Caching.Tests/Redis/EntryFrameReadIntegrationTests.Anchor.cs +++ b/tests/UiPath.Caching.Tests/Redis/EntryFrameReadIntegrationTests.Anchor.cs @@ -473,7 +473,9 @@ public async Task A_late_read_never_accepts_a_windowed_frame(string path) 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"); + // A fill over an expired frame replaces it by compare-and-set, which is one more transaction where scripts are off (K5). + var replaced = read == Read.Fill && scripts == Scripts.Off ? 1 : 0; + expiredLog.Count(anchored).Should().Be(plainLog.Count(anchored) + replaced, "an expired frame is a miss on the first answer"); } } @@ -526,7 +528,7 @@ public async Task A_step_of_the_UTC_clock_during_a_read_never_extends_a_windowed var ended = await ReadAsync(node, read, key); ended.Found.Should().BeFalse(); - ended.Generated.Should().Be(read is Read.Probe or Read.Change); + ended.Generated.Should().Be(read is Read.Probe or Read.Change or Read.Fill, "the generator, the change and the fill each store over the frame that ended"); if (read is Read.Layered or Read.LayeredBatch) { (await HoldsLocalCopyAsync(node, key, raw)).Should().BeFalse(); diff --git a/tests/UiPath.Caching.Tests/Redis/EntryFrameReadIntegrationTests.Basics.cs b/tests/UiPath.Caching.Tests/Redis/EntryFrameReadIntegrationTests.Basics.cs index 7342b0b33..e640ac03c 100644 --- a/tests/UiPath.Caching.Tests/Redis/EntryFrameReadIntegrationTests.Basics.cs +++ b/tests/UiPath.Caching.Tests/Redis/EntryFrameReadIntegrationTests.Basics.cs @@ -309,8 +309,8 @@ public async Task A_batch_fill_that_meets_a_fresh_frame_reports_its_logical_expi 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(); + results[1].Outcome.Should().Be(FillOutcome.Added, "an expired frame is absent, so the fill replaces it (K5)"); + TryReadFrame(await Db.StringGetAsync(expiredRaw), out _).Should().BeFalse(); } [Theory] diff --git a/tests/UiPath.Caching.Tests/Redis/EntryFrameReadIntegrationTests.Windowed.cs b/tests/UiPath.Caching.Tests/Redis/EntryFrameReadIntegrationTests.Windowed.cs new file mode 100644 index 000000000..85a50d01f --- /dev/null +++ b/tests/UiPath.Caching.Tests/Redis/EntryFrameReadIntegrationTests.Windowed.cs @@ -0,0 +1,109 @@ +using StackExchange.Redis; +using UiPath.Caching.Redis; + +namespace UiPath.Caching.Tests.Redis; + +// Carried from Task 2.3: under a format with a window (Task 3.2) a value read sends no GET first, so a hit costs one round trip (FR7, AV1, AV6). +public sealed partial class EntryFrameReadIntegrationTests +{ + private static readonly CachePolicy WindowedPolicy = new() { FailSafeEnabled = true, FailSafeDistributedEnabled = true, FailSafeDistributedMaxStaleAge = Window }; + + public static TheoryData WindowedValueReads => Cross([Read.Get, Read.BatchGet, Read.Probe], [Scripts.Off, Scripts.On]); + + [Theory] + [MemberData(nameof(WindowedValueReads))] + public async Task A_value_read_under_a_format_with_a_window_sends_the_anchored_read_alone(Read read, Scripts scripts) + { + var node = await NodeAsync(scripts, WithFrames); + var (key, raw) = await KeyAsync(node); + await StoreFrameAsync(node, raw, "A", TimeSpan.FromMinutes(1)); + node.ClearLog(); + + var value = await WindowedValueReadAsync(node, read, key); + + value.Should().Be("A"); + var log = node.Log(); + if (scripts == Scripts.On) + { + log.Should().ContainSingle().Which.Should().Match(c => IsScript(c)); + return; + } + + log.Should().Equal("MULTI", read == Read.BatchGet ? "MGET" : "GET", "PTTL", "EXEC"); + } + + [Theory] + [MemberData(nameof(WindowedValueReads))] + public async Task Under_a_format_with_a_window_a_value_read_whose_reply_waits_past_the_logical_end_is_a_miss(Read read, Scripts scripts) + { + var node = await NodeAsync(scripts, WithFrames); + var (key, raw) = await KeyAsync(node); + await StoreOneSecondLeftAsync(node, raw, "A", Bound.CutTtl); + node.ClearLog(); + OnceAfterReply(node, () => _time.Advance(Hold)); + + var value = await WindowedValueReadAsync(node, read, key); + + value.Should().Be(read == Read.Probe ? "generated" : null); + node.Log()[0].Should().Match(c => c == "MULTI" || IsScript(c), "no plain read precedes the anchored one"); + } + + [Theory] + [InlineData(Read.Get)] + [InlineData(Read.Entry)] + public async Task A_read_under_a_windowed_format_goes_to_the_master_when_reads_prefer_replicas(Read read) + { + var node = await NodeAsync(Scripts.Off, o => + { + WithFrames(o); + o.ReadFrom = RedisReadFrom.Replica; + }); + var (key, raw) = await KeyAsync(node); + await StoreFrameAsync(node, raw, "A", TimeSpan.FromMinutes(1)); + node.ClearLog(); + + var value = read == Read.Get + ? await node.Cache.GetAsync(key, WindowedPolicy, Ct) + : (await node.Cache.GetCacheEntryAsync(key, WindowedPolicy, Ct)).Value; + + value.Should().Be("A"); + var log = node.RawLog(); + log.Select(c => c.Command).Should().Equal("MULTI", "GET", "PTTL", "EXEC"); + log.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.Snapshot)] + [InlineData(Read.Result)] + public async Task A_snapshot_or_stamped_read_under_a_windowed_format_sends_the_anchored_read_alone_to_the_master(Read read) + { + var node = await NodeAsync(Scripts.Off, WithFrames); + var (key, raw) = await KeyAsync(node); + await StoreFrameAsync(node, raw, "A", TimeSpan.FromMinutes(1)); + node.ClearLog(); + + var snapshot = read == Read.Snapshot + ? await ((IMigrationCache)node.Redis).ReadSnapshotAsync(key, WindowedPolicy, Ct) + : (await ((IStampedTier)node.Redis).ReadStampedAsync(key, WindowedPolicy, Ct)).Snapshot; + + snapshot.Outcome.Should().Be(SnapshotOutcome.Found); + snapshot.Entry!.Value.Should().Be("A"); + var log = node.RawLog(); + log.Select(c => c.Command).Should().Equal("MULTI", "GET", "PTTL", "EXEC"); + log.Skip(1).Should().OnlyContain(c => (c.Flags & CommandFlags.DemandMaster) == CommandFlags.DemandMaster); + } + + private static void WithFrames(RedisCacheOptions options) + { + options.EntryMetadataEnabled = true; + options.FormatNegotiation.Mode = FormatNegotiationMode.Force; + } + + private static async Task WindowedValueReadAsync(Node node, Read read, CacheKey key) => + read switch + { + Read.Get => await node.Cache.GetAsync(key, WindowedPolicy, Ct), + Read.BatchGet => (await node.Cache.GetAsync([key], WindowedPolicy, Ct))[0].Value, + _ => await node.Cache.GetOrAddAsync(key, _ => Task.FromResult("generated"), WindowedPolicy, Ct), + }; +} diff --git a/tests/UiPath.Caching.Tests/Redis/EntryFrameReadIntegrationTests.Writes.cs b/tests/UiPath.Caching.Tests/Redis/EntryFrameReadIntegrationTests.Writes.cs index e10ba706c..fc3a799b7 100644 --- a/tests/UiPath.Caching.Tests/Redis/EntryFrameReadIntegrationTests.Writes.cs +++ b/tests/UiPath.Caching.Tests/Redis/EntryFrameReadIntegrationTests.Writes.cs @@ -74,7 +74,7 @@ public async Task SetIfChangedAsync_judges_a_stored_frame_and_answers_its_logica break; case Held.ExpiredByFrame or Held.ExpiredByKey: comparer.Calls.Should().Be(0, "an expired frame counts as absent"); - result.Outcome.Should().Be(ChangeOutcome.Replaced); + result.Outcome.Should().Be(ChangeOutcome.Filled, "an expired frame counts as absent (CS3)"); after.Should().Equal(node.Codec.Encode(value!, null)); break; case not Held.FreshWindowed when equal: @@ -146,7 +146,7 @@ public async Task An_unchanged_answer_counts_from_before_the_send() 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"); + expired.Outcome.Should().Be(ChangeOutcome.Filled, "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)); } @@ -203,7 +203,7 @@ public async Task An_unreadable_fill_loser_that_became_a_fresh_frame_before_the_ [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) + public async Task An_unreadable_fill_loser_that_became_an_expired_frame_is_replaced_as_an_expired_frame(Generated shape) { var (node, key, raw) = await UnreadableLoserAsync(); byte[]? expired = null; @@ -217,7 +217,7 @@ public async Task An_unreadable_fill_loser_that_became_an_expired_frame_is_not_r 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); + ((byte[]?)await Db.StringGetAsync(raw)).Should().Equal(node.Codec.Encode("generated", null), "an expired frame is absent, so the fill replaced exactly the frame it read (K5)"); } private static bool TryReadFrame(RedisValue value, out EntryFrame frame) => EntryFrame.TryRead((byte[]?)value ?? [], out frame); diff --git a/tests/UiPath.Caching.Tests/Redis/EntryFrameRefreshEventIntegrationTests.cs b/tests/UiPath.Caching.Tests/Redis/EntryFrameRefreshEventIntegrationTests.cs new file mode 100644 index 000000000..57156f284 --- /dev/null +++ b/tests/UiPath.Caching.Tests/Redis/EntryFrameRefreshEventIntegrationTests.cs @@ -0,0 +1,334 @@ +using Microsoft.Extensions.Caching.Memory; +using Microsoft.Extensions.Logging.Abstractions; +using StackExchange.Redis; +using UiPath.Caching.Config; +using UiPath.Caching.Locking; +using UiPath.Caching.Policies; +using UiPath.Caching.Telemetry; +using UiPath.Caching.Tests.Fakes; + +namespace UiPath.Caching.Tests.Redis; + +// I-B6, RC4: two layered nodes on one Redis and one bus. A refresh event drops a peer's copy, and the peer reads Redis again, so what Redis refused +// is never held past the key's own end. Redis counts a TTL on real time while the nodes count on manual clocks, so time passes by moving the +// clocks and cutting the key's TTL by the same amount. Node a's layer runs 2 seconds ahead of the rest. +[Collection("RedisIntegration")] +[Trait("Category", "Integration")] +public sealed class EntryFrameRefreshEventIntegrationTests(RedisContainerFixture fixture) : IAsyncDisposable +{ + private static readonly TimeSpan Life = TimeSpan.FromSeconds(10); + private static readonly TimeSpan Window = FrameWriteRig.Window; + private static readonly TimeSpan Ahead = TimeSpan.FromSeconds(2); + private static readonly byte[] Json = "\"v\""u8.ToArray(); + + private readonly FrameWriteRig _rig = new(fixture); + private readonly Bus _bus = new(); + private readonly List _peers = []; + + public enum Failure + { + ServerRefusesTheScript, + InsideThePause, + TimeoutWhoseScriptDidNotRun, + NoscriptOnAFireAndForgetSend, + TimeoutWhoseScriptRan, + } + + public static TheoryData Modes + { + get + { + var data = new TheoryData(); + foreach (var scripts in new[] { false, true }) + { + foreach (var awaited in new[] { true, false }) + { + foreach (var metadata in new[] { true, false }) + { + data.Add(scripts, awaited, metadata); + } + } + } + + return data; + } + } + + public static TheoryData StoredModes + { + get + { + var data = new TheoryData(); + foreach (var validators in new[] { false, true }) + { + foreach (var scripts in new[] { false, true }) + { + foreach (var awaited in new[] { true, false }) + { + foreach (var metadata in new[] { true, false }) + { + data.Add(validators, scripts, awaited, metadata); + } + } + } + } + + return data; + } + } + + public static TheoryData Failures => new(Enum.GetValues()); + + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + public async ValueTask DisposeAsync() + { + foreach (var peer in _peers) + { + peer.Dispose(); + } + + await _rig.DisposeAsync(); + } + + [Theory] + [MemberData(nameof(Modes))] + public async Task A_peer_holds_no_renewed_copy_of_a_frame_that_Redis_refused_to_refresh(bool scripts, bool awaited, bool metadata) + { + var (a, b, key, raw) = await SetUpAsync(scripts, awaited, metadata); + await StoreAsync(raw, Frame(_rig.Manual.GetUtcNow() + Life), Life + Window); + (await b.Cache.GetAsync(key, null, Ct)).Should().Be("v"); + b.Holds(key).Should().BeTrue("b adopted the frame"); + await PassAsync(raw, TimeSpan.FromSeconds(9)); + a.Redis.Redis.BeforeRefreshSend = async () => + { + a.Redis.Redis.BeforeRefreshSend = null; + b.Holds(key).Should().BeFalse("the event reached b at second 9, before the script was sent"); + await PassAsync(raw, TimeSpan.FromSeconds(2)); + }; + + var refreshed = await a.Cache.RefreshAsync(key, TimeSpan.FromHours(1), null, Ct); + await a.Redis.Settle(); + + refreshed.Should().BeFalse(); + b.Holds(key).Should().BeFalse("nothing renewed the copy"); + (await b.Cache.GetAsync(key, null, Ct)).Should().BeNull("the frame ended at second 10"); + (await b.Cache.GetCacheEntryAsync(key, null, Ct)).Found.Should().BeFalse(); + } + + [Theory] + [MemberData(nameof(StoredModes))] + public async Task After_a_refresh_that_landed_a_peer_reads_the_new_expiration_from_Redis(bool validators, bool scripts, bool awaited, bool metadata) + { + var (a, b, key, raw) = await SetUpAsync(scripts, awaited, metadata); + var stored = validators ? EntryFrame.Write(Json, DateTimeOffset.MaxValue, TimeSpan.Zero, EntryValidators.From("tag", null)) : Json; + await StoreAsync(raw, stored, TimeSpan.FromSeconds(70)); + (await b.Cache.GetAsync(key, null, Ct)).Should().Be("v"); + await PassAsync(raw, TimeSpan.FromSeconds(9)); + + var refreshed = await a.Cache.RefreshAsync(key, TimeSpan.FromHours(1), null, Ct); + await a.Redis.Settle(); + + refreshed.Should().Be(awaited, "the script landed"); + b.Holds(key).Should().BeFalse("the event drops the copy and renews nothing"); + _rig.Log.Take(); + (await b.Cache.GetAsync(key, null, Ct)).Should().Be("v"); + _rig.Log.Take().Should().NotBeEmpty("b read Redis for the new expiration"); + b.Holds(key).Should().BeTrue(); + var ttl = (await _rig.Db.KeyTimeToLiveAsync(raw))!.Value; + ttl.Should().BeGreaterThan(TimeSpan.FromMinutes(59), "the new TTL is the hour of the refresh, counted from Redis"); + } + + [Theory] + [MemberData(nameof(Failures))] + public async Task After_a_refresh_that_failed_no_node_holds_the_value_past_its_stored_deadline(Failure failure) + { + var awaited = failure != Failure.NoscriptOnAFireAndForgetSend; + var (a, b, key, raw) = await SetUpAsync(false, awaited, true, failure == Failure.ServerRefusesTheScript || failure == Failure.InsideThePause ? "-@scripting" : null); + var ran = failure == Failure.TimeoutWhoseScriptRan; + await StoreAsync(raw, ran ? Json : Frame(_rig.Manual.GetUtcNow() + Life), ran ? Life : Life + Window); + (await b.Cache.GetAsync(key, null, Ct)).Should().Be("v"); + (await a.Cache.GetAsync(key, null, Ct)).Should().Be("v"); + await PassAsync(raw, TimeSpan.FromSeconds(9)); + switch (failure) + { + case Failure.InsideThePause: + (await a.Cache.RefreshAsync(key, TimeSpan.FromHours(1), null, Ct)).Should().BeFalse(); + break; + case Failure.TimeoutWhoseScriptDidNotRun: + a.Redis.Redis.BeforeRefreshSend = () => throw new TimeoutException("injected"); + break; + case Failure.NoscriptOnAFireAndForgetSend: + (await a.Cache.RefreshAsync(key, TimeSpan.FromSeconds(30), null, Ct)).Should().BeFalse("this refresh primes the script"); + foreach (var server in RedisTestKeys.Primaries(_rig.Db.Multiplexer)) + { + await server.ScriptFlushAsync(); + } + + break; + case Failure.TimeoutWhoseScriptRan: + _rig.Pipelines.AfterWrite = () => throw new TimeoutException("injected"); + break; + } + + (await a.Cache.RefreshAsync(key, TimeSpan.FromHours(1), null, Ct)).Should().BeFalse(); + await a.Redis.Settle(); + + a.Holds(key).Should().BeFalse("no node keeps a copy under the requested expiration"); + b.Holds(key).Should().BeFalse(); + if (ran) + { + // The unknown outcome: the script may have run, so the next read takes what Redis holds. + (await b.Cache.GetAsync(key, null, Ct)).Should().Be("v"); + b.Holds(key).Should().BeTrue(); + return; + } + + await PassAsync(raw, TimeSpan.FromSeconds(2)); + (await b.Cache.GetAsync(key, null, Ct)).Should().BeNull("every read after second 10 is a miss"); + (await a.Cache.GetAsync(key, null, Ct)).Should().BeNull(); + } + + private static byte[] Frame(DateTimeOffset expiration) => EntryFrame.Write(Json, expiration, Window, null); + + /// Moves every clock by and cuts the key's TTL by as much. + private async Task PassAsync(RedisKey raw, TimeSpan by) + { + var left = await _rig.Db.KeyTimeToLiveAsync(raw); + _rig.Manual.Advance(by); + _bus.Skewed.Advance(by); + await _rig.Db.KeyExpireAsync(raw, left!.Value - by); + } + + private Task StoreAsync(RedisKey raw, byte[] bytes, TimeSpan ttl) => _rig.Db.StringSetAsync(raw, bytes, ttl); + + private async Task<(Peer A, Peer B, CacheKey Key, RedisKey Raw)> SetUpAsync(bool scripts, bool awaited, bool metadataOfB, string? userRules = null) + { + var seeder = await _rig.NodeAsync(o => o.ReadScriptsEnabled = scripts); + void ConfigureA(RedisCacheOptions o) + { + o.ReadScriptsEnabled = scripts; + o.AwaitRefresh = awaited; + } + + var nodeA = await _rig.NodeAsync(ConfigureA, user: userRules is null ? null : _ => userRules); + var nodeB = await _rig.NodeAsync(o => o.ReadScriptsEnabled = scripts, metadata: metadataOfB); + var id = Guid.NewGuid().ToString("N"); + CacheKey key = $"e:{id}"; + (await seeder.Cache.SetAsync(key, "seed", TimeSpan.FromMinutes(5), Ct)).Should().BeTrue(); + var raw = _rig.Raw(id); + var a = _bus.Add("a", nodeA, _rig); + var b = _bus.Add("b", nodeB, _rig); + _peers.Add(a); + _peers.Add(b); + return (a, b, key, raw); + } + + private sealed class Peer : IDisposable + { + public Peer(string name, FrameWriteRig.Node redis, TimeProvider clock, Bus bus) + { + Redis = new PeerRedis(redis); + var options = new InMemoryRedisCacheOptions { LocalMaxExpiration = TimeSpan.FromHours(1), CacheNullValues = true }; + var cacheOptions = new CacheOptions { AppShortName = "test", ConnectionMonitorEnabled = true, SourceUri = new Uri($"urn:node:{name}") }; + var events = new CacheEventFactory(Options.Create(cacheOptions)); + var tokens = new ChangeTokenFactory(Options.Create(cacheOptions), new SystemJsonByteSerializerProxy(), NullLoggerFactory.Instance, Substitute.For()); + Topic = new PeerTopic(this, bus); + var provider = Substitute.For(); + provider.Enabled.Returns(true); + provider.Create(Arg.Any()).Returns(Topic); + var topics = Substitute.For(); + topics.Get(Arg.Any()).Returns(provider); + Cache = new MultilayerCache( + KnownCacheProviderNames.InMemoryRedis, + redis.Redis, + new Memory(this, clock), + tokens, + topics, + events, + NullTelemetryProvider.Instance, + options, + options, + cacheOptions, + NullDistributedLock.Instance, + ((CacheFactory)redis.Factory).PolicyFactory!, + clock, + NullLogger.Instance); + } + + public PeerRedis Redis { get; } + + public MultilayerCache Cache { get; } + + public KeyedSubject Subject { get; } = new(NullLogger.Instance); + + public IMemoryCache? Local { get; set; } + + private PeerTopic Topic { get; } + + public bool Holds(CacheKey key) => Local is { } local && local.TryGetValue(key.ToString(), out _); + + public void Dispose() + { + Cache.Dispose(); + Subject.Dispose(); + } + + private sealed class Memory(Peer peer, TimeProvider clock) : IMemoryCacheFactory + { + private readonly MemoryCacheFactory _inner = new(clock, NullLoggerFactory.Instance); + + public IMemoryCache Get(IMemoryCacheOptions memoryOptions) => peer.Local = _inner.Get(memoryOptions); + } + } + + private sealed class PeerRedis(FrameWriteRig.Node node) + { + public RedisCache Redis => node.Redis; + + /// A command on the node's connection comes after a fire-and-forget refresh of it, so its reply says that the refresh has run. + public Task Settle() => node.Connector.Database.PingAsync(CommandFlags.DemandMaster); + } + + private sealed class PeerTopic(Peer peer, Bus bus) : ITopic + { + public TopicKey TopicKey { get; } = new("topic"); + + public EventHandler? OnDisposed { get; set; } + + public IDisposable Subscribe(IObserver observer) => peer.Subject.Subscribe(observer); + + public ValueTask PublishAsync(ICacheEvent @event, CancellationToken token = default) => bus.PublishAsync(@event); + + public void Dispose() + { + } + } + + private sealed class Bus + { + private readonly List _peers = []; + private readonly CacheEventFormatter _formatter = new(); + + /// The clock of the layer of node a: 2 seconds ahead of the others. + public ManualTimeProvider Skewed { get; private set; } = null!; + + public Peer Add(string name, FrameWriteRig.Node redis, FrameWriteRig rig) + { + Skewed ??= new ManualTimeProvider(rig.Manual.GetUtcNow() + Ahead); + var peer = new Peer(name, redis, name == "a" ? Skewed : rig.Manual, this); + _peers.Add(peer); + return peer; + } + + public ValueTask PublishAsync(ICacheEvent @event) + { + foreach (var peer in _peers.ToArray()) + { + peer.Subject.OnNext(_formatter.Decode(_formatter.Encode(@event))!); + } + + return new ValueTask(true); + } + } +} diff --git a/tests/UiPath.Caching.Tests/Redis/EntryFrameRollbackIntegrationTests.cs b/tests/UiPath.Caching.Tests/Redis/EntryFrameRollbackIntegrationTests.cs new file mode 100644 index 000000000..89b3b1f1f --- /dev/null +++ b/tests/UiPath.Caching.Tests/Redis/EntryFrameRollbackIntegrationTests.cs @@ -0,0 +1,214 @@ +using System.Reflection; +using StackExchange.Redis; +using UiPath.Caching.Redis; + +namespace UiPath.Caching.Tests.Redis; + +// MV5: after step 1 no policy has the option, and a windowed frame only drains. Redis counts a TTL on real time while the nodes count on one +// ManualTimeProvider, so time passes by moving that clock and cutting the key's TTL by the same amount. +[Collection("RedisIntegration")] +[Trait("Category", "Integration")] +public sealed class EntryFrameRollbackIntegrationTests(RedisContainerFixture fixture) : IAsyncDisposable +{ + private static readonly TimeSpan Life = TimeSpan.FromMinutes(5); + private static readonly TimeSpan Window = FrameWriteRig.Window; + private static readonly TimeSpan Step = TimeSpan.FromMinutes(2); + private static readonly CachePolicy WithOption = FrameWriteRig.Windowed(Window, Life); + private static readonly CachePolicy WithoutOption = new() { DistributedExpiration = Life }; + private static readonly FieldInfo Providers = typeof(CacheFactory).GetField("_providers", BindingFlags.Instance | BindingFlags.NonPublic)!; + + private readonly FrameWriteRig _rig = new(fixture); + private readonly string _run = "rb" + Guid.NewGuid().ToString("N")[..10]; + + public enum Command + { + Set, + TryAdd, + Fill, + StampedWrite, + RefreshToATime, + RefreshToNever, + Read, + } + + public static TheoryData Commands => new(Enum.GetValues()); + + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + public ValueTask DisposeAsync() => _rig.DisposeAsync(); + + [Fact] + public async Task Periodic_refreshes_after_step_1_do_not_keep_a_windowed_frame() + { + var (a, b, key, id) = await TwoNodesAsync(); + TimeSpan? life = await WriteAsync(a, key, WithOption); + var provider = ProviderOf(a); + + for (var minutes = 2; minutes <= 20; minutes += 2) + { + life = await PassAsync(id, life, Step); + var before = await _rig.ReadRawAsync(id); + (await b.Cache.RefreshAsync(key, _rig.Manual.GetUtcNow() + TimeSpan.FromMinutes(30), WithoutOption, Ct)).Should().BeFalse($"at {minutes} minutes"); + var after = await _rig.ReadRawAsync(id); + after.Bytes.Should().Equal(before.Bytes, $"a refresh at {minutes} minutes changes nothing"); + if (minutes < 5) + { + (await b.Cache.GetAsync(key, WithoutOption, Ct)).Should().Be("v", $"the frame is fresh at {minutes} minutes"); + } + } + + (await WindowedCountAsync(provider)).Should().Be(0); + } + + [Fact] + public async Task Writes_from_a_node_that_kept_the_option_hold_a_windowed_frame_past_the_timed_wait() + { + var (a, b, key, id) = await TwoNodesAsync(); + TimeSpan? life = await WriteAsync(a, key, WithOption); + var provider = ProviderOf(a); + + for (var minutes = 2; minutes <= 20; minutes += 2) + { + life = await PassAsync(id, life, Step); + life = await WriteAsync(b, key, WithOption); + (await b.Cache.RefreshAsync(key, _rig.Manual.GetUtcNow() + TimeSpan.FromHours(1), WithOption, Ct)).Should().BeFalse(); + if (minutes is 6 or 20) + { + (await WindowedCountAsync(provider)).Should().Be(1, $"at {minutes} minutes"); + } + } + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task A_refresh_to_never_during_the_wait_does_not_persist_a_windowed_frame(bool optionNode) + { + var (a, b, key, id) = await TwoNodesAsync(); + TimeSpan? life = await WriteAsync(a, key, WithOption); + life = await PassAsync(id, life, Step); + var before = await _rig.ReadRawAsync(id); + + var refreshed = await b.Cache.RefreshAsync(key, DateTimeOffset.MaxValue, optionNode ? WithOption : WithoutOption, Ct); + + refreshed.Should().BeFalse(); + var after = await _rig.ReadRawAsync(id); + after.Bytes.Should().Equal(before.Bytes); + after.Ttl.Should().NotBeNull("the key keeps its TTL"); + life = await PassAsync(id, life, TimeSpan.FromMinutes(4) + TimeSpan.FromSeconds(1)); + life.Should().BeLessThanOrEqualTo(TimeSpan.Zero); + (await WindowedCountAsync(ProviderOf(a))).Should().Be(0); + } + + [Theory] + [MemberData(nameof(Commands))] + public async Task After_step_1_the_windowed_count_only_falls(Command command) + { + var (a, b, key, id) = await TwoNodesAsync(); + var life = await WriteAsync(a, key, WithOption); + var provider = ProviderOf(a); + var before = await WindowedCountAsync(provider); + var now = _rig.Manual.GetUtcNow(); + + switch (command) + { + case Command.Set: + await b.Cache.SetAsync(key, "w", Life, WithoutOption, Ct); + break; + case Command.TryAdd: + await b.Cache.TryAddAsync(key, "w", Life, WithoutOption, Ct); + break; + case Command.Fill: + await b.Cache.GetOrAddAsync(key, _ => Task.FromResult("w"), Life, WithoutOption, Ct); + break; + case Command.StampedWrite: + await b.Cache.SetIfChangedAsync(key, "w", StringComparer.Ordinal, Life, WithoutOption, Ct); + break; + case Command.RefreshToATime: + await b.Cache.RefreshAsync(key, now + TimeSpan.FromHours(1), WithoutOption, Ct); + break; + case Command.RefreshToNever: + await b.Cache.RefreshAsync(key, DateTimeOffset.MaxValue, WithoutOption, Ct); + break; + default: + await b.Cache.GetAsync(key, WithoutOption, Ct); + break; + } + + (await WindowedCountAsync(provider)).Should().BeLessThanOrEqualTo(before, "no command raises the count"); + if (command is Command.RefreshToATime or Command.RefreshToNever or Command.Read or Command.TryAdd or Command.Fill) + { + (await WindowedCountAsync(provider)).Should().Be(1, "a command that leaves the frame alone leaves it as it was"); + await PassAsync(id, life, TimeSpan.FromMinutes(6)); + (await WindowedCountAsync(provider)).Should().Be(0, "no command touched the key, so it is zero after 6 minutes"); + } + else + { + (await WindowedCountAsync(provider)).Should().Be(0, "a write under a policy without the option replaces the frame"); + } + } + + [Fact] + public async Task A_frame_persisted_from_outside_stays_in_the_count() + { + var (a, _, key, id) = await TwoNodesAsync(); + await WriteAsync(a, key, WithOption); + + (await _rig.Db.KeyPersistAsync(_rig.Raw(id))).Should().BeTrue(); + (await PassAsync(id, null, TimeSpan.FromMinutes(20))).Should().BeNull(); + (await WindowedCountAsync(ProviderOf(a))).Should().Be(1, "a frame with no TTL is out of reach: the documented limit"); + } + + private static RedisCacheProvider ProviderOf(FrameWriteRig.Node node) => + ((Dictionary)Providers.GetValue(node.Factory)!).Values.OfType().Single(); + + private async Task<(FrameWriteRig.Node A, FrameWriteRig.Node B, CacheKey Key, string Id)> TwoNodesAsync() + { + var a = await _rig.NodeAsync(static o => o.AwaitRefresh = true); + var b = await _rig.NodeAsync(static o => o.AwaitRefresh = true); + var id = $"{_run}:{Guid.NewGuid():N}"; + return (a, b, id, id); + } + + private async Task WriteAsync(FrameWriteRig.Node node, CacheKey key, CachePolicy policy) + { + (await node.Cache.SetAsync(key, "v", Life, policy, Ct)).Should().BeTrue(); + return policy.FailSafeDistributedEnabled == true ? Life + Window : Life; + } + + /// Moves the clock of every node by and cuts the key's TTL by as much; a key whose life ran out is gone. Answers the life left, or null for a key with none. + private async Task PassAsync(string id, TimeSpan? life, TimeSpan by) + { + _rig.Manual.Advance(by); + if (life is not { } left) + { + return null; + } + + if (left <= TimeSpan.Zero) + { + return left; + } + + left -= by; + var raw = _rig.Raw(id); + if (left <= TimeSpan.Zero) + { + await _rig.Db.KeyDeleteAsync(raw); + } + else + { + await _rig.Db.KeyExpireAsync(raw, left); + } + + return left; + } + + private async Task WindowedCountAsync(RedisCacheProvider provider) + { + var report = await provider.CountFormatsByReasonAsync(new CacheKey($"{_run}:*"), Ct); + return report.ByReason.GetValueOrDefault(FormatInventory.FormatReason(FormatInventory.FrameWindowedName)); + } + + +} diff --git a/tests/UiPath.Caching.Tests/Redis/EntryFrameSendTests.cs b/tests/UiPath.Caching.Tests/Redis/EntryFrameSendTests.cs new file mode 100644 index 000000000..2991001f0 --- /dev/null +++ b/tests/UiPath.Caching.Tests/Redis/EntryFrameSendTests.cs @@ -0,0 +1,190 @@ +using System.Text; +using Microsoft.Extensions.Logging.Abstractions; +using StackExchange.Redis; +using UiPath.Caching.Config; +using UiPath.Caching.Negotiation; +using UiPath.Caching.Policies; +using UiPath.Caching.Redis; +using UiPath.Caching.Serialization; +using UiPath.Caching.Telemetry; + +namespace UiPath.Caching.Tests.Redis; + +/// The form of each send (W8): with the gate closed a frame goes out as its inner bytes and its logical life, and nothing else changes. +public class EntryFrameSendTests +{ + private static readonly TimeSpan Window = TimeSpan.FromSeconds(60); + private static readonly TimeSpan Life = TimeSpan.FromSeconds(70); + private static readonly DateTimeOffset Start = new(2026, 11, 29, 10, 0, 0, TimeSpan.Zero); + + private readonly ManualTimeProvider _clock = new(Start); + private readonly Gate _gate = new(); + + public static TheoryData Frames => new() + { + { "all fields", EntryFrameVectors.FullFrame }, + { "invalid UTF-8", EntryFrameVectors.InvalidUtf8 }, + { "window and JSON", EntryFrame.Write("\"v\""u8, Start.AddSeconds(10), Window, null) }, + { "window and empty inner", EntryFrame.Write([], Start.AddSeconds(10), Window, null) }, + }; + + public static TheoryData NoFrames + { + get + { + var data = new TheoryData { { "JSON", "{\"a\":1}"u8.ToArray() }, { "format header", [0x10, 1, 2, 3] }, { "empty", [] } }; + foreach (var row in EntryFrameVectors.GrammarCases) + { + if (!row.Data.Item3) + { + data.Add(row.Data.Item1, row.Data.Item2); + } + } + + return data; + } + } + + [Theory] + [MemberData(nameof(Frames))] + public void The_send_form_of_a_frame_is_its_inner_bytes_and_its_life_less_the_window(string name, byte[] stored) + { + _ = name; + var cache = Cache(); + EntryFrame.TryRead(stored, out var frame).Should().BeTrue(); + _gate.Open = false; + var deadline = Start.AddSeconds(70); + + var (bytes, life) = cache.SendForm(stored, Life); + var (untilBytes, until) = cache.SendFormUntil(stored, deadline); + + ((byte[])bytes!).Should().Equal(frame.Inner.ToArray()); + ((byte[])untilBytes!).Should().Equal(frame.Inner.ToArray()); + life.Should().Be(Life - frame.Window); + until.Should().Be(deadline - frame.Window); + } + + [Fact] + public void A_frame_without_a_window_keeps_its_life() + { + var cache = Cache(); + var stored = EntryFrame.Write("\"v\""u8, DateTimeOffset.MaxValue, TimeSpan.Zero, EntryValidators.From("\"e\"", null)); + _gate.Open = false; + + var (bytes, life) = cache.SendForm(stored, Life); + + ((byte[])bytes!).Should().Equal("\"v\""u8.ToArray()); + life.Should().Be(Life); + } + + [Theory] + [MemberData(nameof(NoFrames))] + public void Bytes_that_are_no_frame_pass_through(string name, byte[] stored) + { + _ = name; + var cache = Cache(); + _gate.Open = false; + + var (bytes, life) = cache.SendForm(stored, Life); + var left = cache.SendFormLeft(stored, Start.AddSeconds(10), default); + + ((byte[])bytes!).Should().Equal(stored); + life.Should().Be(Life); + left.Should().NotBeNull(); + ((byte[])left!.Value.Bytes!).Should().Equal(stored); + left.Value.Ttl.Should().Be(TimeSpan.FromSeconds(10)); + } + + [Fact] + public void With_the_gate_open_the_pair_passes_through_and_nothing_is_allocated() + { + var cache = Cache(); + RedisValue stored = EntryFrame.Write("\"v\""u8, Start.AddSeconds(10), Window, null); + _ = cache.SendForm(stored, Life); + + var before = GC.GetAllocatedBytesForCurrentThread(); + var (bytes, life) = cache.SendForm(stored, Life); + var allocated = GC.GetAllocatedBytesForCurrentThread() - before; + + bytes.Should().Be(stored); + life.Should().Be(Life); + allocated.Should().Be(0); + } + + [Fact] + public void Plain_bytes_that_pass_the_whole_grammar_are_stripped_as_a_reader_reads_them() + { + // The documented limit (WS5): a headerless value that passes the frame grammar is read as a frame by every node of this build, so the strip sends what they read. + var cache = Cache(); + var plain = EntryFrameVectors.WithInner((byte)'x'); + EntryFrame.TryRead(plain, out var asRead).Should().BeTrue(); + _gate.Open = false; + + var (bytes, _) = cache.SendForm(plain, Life); + + ((byte[])bytes!).Should().Equal(asRead.Inner.ToArray()); + } + + [Fact] + public void The_anchored_send_adds_the_window_only_to_a_positive_remainder() + { + var cache = Cache(); + var until = Start.AddSeconds(10); + var anchor = WriteAnchor.Capture(_clock, TimeSpan.FromSeconds(10), out _); + RedisValue stored = EntryFrame.Write("\"v\""u8, until, Window, null); + + _clock.Advance(TimeSpan.FromSeconds(1)); + _clock.StepUtc(TimeSpan.FromSeconds(-10)); + var stepped = cache.SendFormLeft(stored, until, anchor); + _clock.Advance(TimeSpan.FromSeconds(9)); + var ended = cache.SendFormLeft(stored, until, anchor); + + stepped!.Value.Ttl.Should().Be(TimeSpan.FromSeconds(9) + Window, "a step back after the capture adds nothing"); + ended.Should().BeNull("the anchored life ended, whatever the UTC clock says"); + } + + [Fact] + public void A_value_that_starts_with_a_reserved_byte_is_framed_never() + { + var cache = Cache(); + var spec = new FrameSpec(Window, null); + RedisValue reserved = new byte[] { 0x0E, 7, 1 }; + + var (stored, lifetime) = cache.Framed(reserved, Life, spec); + var (forever, never) = cache.Framed(Encoding.UTF8.GetBytes("\"v\""), TimeSpan.MaxValue, spec); + + stored.Should().Be(reserved); + lifetime.Should().Be(Life); + ((byte[])forever!).Should().Equal(Encoding.UTF8.GetBytes("\"v\"")); + never.Should().Be(TimeSpan.MaxValue); + } + + private RedisCache Cache() + { + var connector = Substitute.For(); + connector.IsConnected.Returns(true); + connector.Version.Returns(new Version(7, 4)); + var pipelines = Substitute.For(); + pipelines.Get(Arg.Any()).Returns(EmptyResiliencePipeline.Instance); + return new RedisCache( + connector, + new SystemJsonByteSerializerProxy(), + pipelines, + NullTelemetryProvider.Instance, + new RedisCacheOptions { EntryMetadataEnabled = true }, + new CacheOptions { AppShortName = "test" }, + new DefaultCachePolicyFactory(null, null), + _clock, + NullLogger.Instance) + { + FrameWrites = _gate, + }; + } + + private sealed class Gate : IEntryFrameWrites + { + public bool Open { get; set; } = true; + + public bool Allowed => Open; + } +} diff --git a/tests/UiPath.Caching.Tests/Redis/EntryFrameWriteAnchorTests.Layered.cs b/tests/UiPath.Caching.Tests/Redis/EntryFrameWriteAnchorTests.Layered.cs new file mode 100644 index 000000000..2f33e8d35 --- /dev/null +++ b/tests/UiPath.Caching.Tests/Redis/EntryFrameWriteAnchorTests.Layered.cs @@ -0,0 +1,474 @@ +using UiPath.Caching.Policies; +using UiPath.Caching.Redis; + +namespace UiPath.Caching.Tests.Redis; + +// The layered cache hands its write anchor to the Redis tier (WA4 (b), WA6, WA8 (c), WA9 (a) and (d)): the UTC clock is set back after the layered origin made its deadline. +public sealed partial class EntryFrameWriteAnchorTests +{ + private static readonly TimeSpan StepBack = TimeSpan.FromSeconds(-10); + + public enum Handoff + { + Foreground, + Background, + Batch, + ManySet, + TryAdd, + GeneratedStore, + TryFill, + FencedFill, + SetIfChangedAbsent, + SetIfChangedHeld, + Migration, + Stamped, + } + + public enum Deadline + { + Instant, + Duration, + Policy, + } + + public enum Origin + { + Set, + ManySet, + BatchGetOrAdd, + TryFill, + SetIfChanged, + PolicyMiss, + ResultMiss, + GeneratedStore, + } + + public enum Step + { + AfterUtc, + InKeyStrategy, + } + + public static CachePolicy RehydratingPolicy { get; } = new() + { + FailSafeEnabled = true, + FailSafeDistributedEnabled = true, + FailSafeDistributedMaxStaleAge = Window, + DistributedExpiration = TimeSpan.FromSeconds(30), + RehydrateEnabled = true, + Rehydrate = new RehydrateOptions { Threshold = 0.1, BaseCooldown = TimeSpan.FromSeconds(1), MaxCooldown = TimeSpan.FromMinutes(1), TimeoutFraction = 0.5, Name = "anchor" }, + }; + + public static TheoryData Handoffs + { + get + { + var data = new TheoryData(); + foreach (var handoff in Enum.GetValues()) + { + foreach (var deadline in Enum.GetValues()) + { + foreach (var shape in Enum.GetValues()) + { + var seam = handoff is Handoff.Migration; + var stamped = handoff is Handoff.Stamped; + if ((seam && (deadline != Deadline.Instant || shape != TierShape.Layered)) + || (stamped && (deadline != Deadline.Policy || shape != TierShape.Layered))) + { + continue; + } + + data.Add(handoff, deadline, shape); + } + } + } + + return data; + } + } + + public static TheoryData Origins + { + get + { + var data = new TheoryData(); + foreach (var origin in Enum.GetValues()) + { + foreach (var deadline in Enum.GetValues()) + { + if (origin is Origin.PolicyMiss or Origin.ResultMiss or Origin.GeneratedStore && deadline != Deadline.Policy) + { + continue; + } + + foreach (var step in Enum.GetValues()) + { + data.Add(origin, deadline, step); + } + } + } + + return data; + } + } + + public static TheoryData Ordinary => + new() + { + { null, false, "off", 0, 0, 0 }, + { null, true, "unframed", 0, 0, 1 }, + { null, true, "framed", 0, 0, 2 }, + { null, true, "relative", 0, 0, 0 }, + { null, true, "never", 0, 0, 0 }, + { null, true, "batch", 0, 0, 2 }, + { TierShape.Layered, false, "set", 0, 1, 0 }, + { TierShape.Layered, true, "set", 0, 1, 2 }, + { TierShape.Layered, true, "set-unframed", 0, 1, 1 }, + { TierShape.Layered, true, "never", 0, 1, 0 }, + { TierShape.Layered, true, "relative", 0, 1, 2 }, + { TierShape.Layered, false, "hit-explicit", 0, 1, 0 }, + { TierShape.Layered, true, "hit-explicit", 0, 1, 1 }, + { TierShape.Layered, false, "hit-policy", 0, 0, 0 }, + { TierShape.Layered, true, "hit-policy", 0, 0, 0 }, + { TierShape.Layered, false, "miss-policy", 0, 1, 0 }, + { TierShape.Layered, true, "miss-policy", 0, 1, 4 }, + { TierShape.Layered, false, "miss-explicit", 0, 1, 0 }, + { TierShape.Layered, true, "miss-explicit", 0, 1, 4 }, + { TierShape.TwoLevels, false, "set", 1, 2, 0 }, + { TierShape.TwoLevels, true, "set", 1, 1, 2 }, + { TierShape.TwoLevels, true, "never", 1, 1, 0 }, + { TierShape.TwoLevels, false, "hit-explicit", 1, 1, 0 }, + { TierShape.TwoLevels, true, "hit-explicit", 1, 1, 1 }, + { TierShape.TwoLevels, true, "hit-policy", 0, 0, 0 }, + }; + + // T1, WA6 (the handoff of every inner write) and WA4 (b): without it the Redis tier takes a new anchor at its entry, after the step, and sends 19 seconds plus the window. + [Theory] + [MemberData(nameof(Handoffs))] + public async Task A_layered_write_hands_its_anchor_to_the_Redis_tier(Handoff handoff, Deadline deadline, TierShape shape) + { + var node = await _rig.NodeAsync(o => o.RemoveTombstone = handoff == Handoff.FencedFill ? TimeSpan.FromSeconds(1) : null); + var (id, key) = NewKey(); + var stack = node.StackOf(shape, seam: handoff != Handoff.Migration); + var policy = handoff switch + { + Handoff.Background => new CachePolicy { FailSafeEnabled = true, FailSafeDistributedEnabled = true, FailSafeDistributedMaxStaleAge = Window, DistributedExpiration = Life, BackgroundDistributedWrite = true }, + Handoff.Stamped => RehydratingPolicy, + _ => Windowed, + }; + var landed = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + await PrepareLayeredAsync(stack.Top, handoff, key, policy); + var start = Now; + _rig.Pipelines.AfterWrite = () => + { + landed.TrySetResult(); + return Task.CompletedTask; + }; + stack.Bottom.OnWrite = () => + { + _rig.Manual.Advance(TimeSpan.FromSeconds(1)); + _rig.Manual.StepUtc(StepBack); + }; + + await LayeredCallAsync(stack.Top, handoff, deadline, key, policy, start + Life); + await landed.Task.WaitAsync(Ct); + + var (bytes, ttl) = await _rig.ReadRawAsync(id); + EntryFrame.TryRead(bytes, out var frame).Should().BeTrue(); + if (handoff == Handoff.Stamped) + { + frame.Expiration.Should().BeAfter(start, "the rehydrate wrote its fresh value"); + } + else + { + frame.Expiration.ToUnixTimeMilliseconds().Should().Be((start + Life).ToUnixTimeMilliseconds(), "the frame expiration is the layered origin's instant"); + } + + if (shape == TierShape.AppCache) + { + ttl!.Value.Should().BeGreaterThan(TimeSpan.FromSeconds(15) + Window, "an application's own cache takes the public instant, so the Redis tier takes a new anchor at its entry (WL2)"); + return; + } + + var left = (handoff == Handoff.Stamped ? RehydratingPolicy.DistributedExpiration!.Value : Life) - TimeSpan.FromSeconds(1); + ttl!.Value.Should().BeLessThanOrEqualTo(left + Window).And.BeGreaterThan(Window, "the window is there; the time between the SET and the PTTL read is real time, so no lower bound counts it"); + if (handoff != Handoff.Stamped && handoff != Handoff.Migration) + { + var local = await stack.Top.GetCacheEntryAsync(key, Windowed, Ct); + if (local.Found) + { + local.Expiration.ToUnixTimeMilliseconds().Should().Be(frame.Expiration.ToUnixTimeMilliseconds(), "the local copy ends where the frame does"); + } + } + } + + // T1, WA4 (b): the timestamp is read before the UTC reading that makes or validates the deadline, and the step that falls right after that reading is in the anchored life. + [Theory] + [MemberData(nameof(Origins))] + public async Task A_layered_origin_that_steps_the_clock_back_keeps_its_own_life(Origin origin, Deadline deadline, Step step) + { + var node = await _rig.NodeAsync(); + var (id, key) = NewKey(); + var stepper = new SteppingStrategy(_rig); + var stack = node.StackOf(TierShape.Layered, stepper); + var start = Now; + _rig.Clock.Reset(); + if (step == Step.AfterUtc) + { + _rig.Clock.AfterTimestamp = () => _rig.Clock.AfterUtc = _ => _rig.Manual.StepUtc(StepBack); + } + else + { + stepper.Armed = true; + } + + await OriginCallAsync(stack.Top, origin, deadline, key, start + Life); + + var (bytes, ttl) = await _rig.ReadRawAsync(id); + EntryFrame.TryRead(bytes, out var frame).Should().BeTrue(); + frame.Expiration.ToUnixTimeMilliseconds().Should().Be((start + Life).ToUnixTimeMilliseconds()); + ttl!.Value.Should().BeLessThanOrEqualTo(Life + Window, "the life is the deadline's at its origin, and never that life plus the 10 seconds of the step").And.BeGreaterThan(Window, "the window is there; the time between the SET and the PTTL read is real time, so no lower bound counts it"); + var readings = string.Concat(_rig.Clock.Readings); + var first = readings.IndexOf('T', StringComparison.Ordinal); + first.Should().BeGreaterThanOrEqualTo(0); + readings[first + 1].Should().Be('U', "the timestamp comes right before the UTC reading that makes the deadline, with no capture between"); + } + + // T1, WriteAnchor (WA1) and WA4 (b): a capture that read UTC before the timestamp would give the anchor the 5 seconds of the gap. + [Theory] + [InlineData(null)] + [InlineData(TierShape.Layered)] + [InlineData(TierShape.TwoLevels)] + public async Task The_anchor_is_taken_before_the_UTC_reading(TierShape? shape) + { + var node = await _rig.NodeAsync(); + var (id, key) = NewKey(); + var top = shape is { } tiers ? node.StackOf(tiers).Top : node.Cache; + var instant = Now + TimeSpan.FromSeconds(20); + _rig.Clock.AfterTimestamp = () => _rig.Manual.Advance(TimeSpan.FromSeconds(5)); + + (await top.SetAsync(key, "v", instant, Windowed, Ct)).Should().BeTrue(); + + // The anchored life is the instant less the later UTC reading, 15 seconds, and the send comes 5 monotonic seconds after the timestamp. + var (_, ttl) = await _rig.ReadRawAsync(id); + ttl!.Value.Should().BeLessThanOrEqualTo(TimeSpan.FromSeconds(10) + Window).And.BeGreaterThan(Window, "the window is there; the time between the SET and the PTTL read is real time, so no lower bound counts it"); + } + + // T1, WA8 (c) and WA9 (a): the query runs on both answers, no timestamp is read with the option off, and one capture with it on. + [Theory] + [MemberData(nameof(Ordinary))] + public async Task The_write_anchor_leaves_the_ordinary_paths_as_they_were(TierShape? shape, bool metadata, string path, int middleQueries, int bottomQueries, int timestamps) + { + var node = await _rig.NodeAsync(metadata: metadata); + var (_, key) = NewKey(); + if (shape is not { } tiers) + { + await DirectOrdinaryAsync(node, path, key, timestamps); + return; + } + + var stack = node.StackOf(tiers); + var policy = metadata && path != "set-unframed" ? Windowed : new CachePolicy { DistributedExpiration = Life }; + if (path.StartsWith("hit", StringComparison.Ordinal)) + { + (await stack.Top.SetAsync(key, "v", TimeSpan.FromMinutes(5), policy, Ct)).Should().BeTrue(); + } + + _rig.Clock.Reset(); + stack.Bottom.Reset(); + stack.Middle.Reset(); + + switch (path) + { + case "never": + (await stack.Top.SetAsync(key, "v", DateTimeOffset.MaxValue, policy, Ct)).Should().BeTrue(); + break; + case "relative": + (await stack.Top.SetAsync(key, "v", Life, policy, Ct)).Should().BeTrue(); + break; + case "hit-explicit" or "miss-explicit": + (await stack.Top.GetOrAddAsync(key, static _ => Task.FromResult("v"), Now + Life, policy, Ct)).Should().Be("v"); + break; + case "hit-policy" or "miss-policy": + (await stack.Top.GetOrAddAsync(key, static _ => Task.FromResult("v"), policy, Ct)).Should().Be("v"); + break; + default: + (await stack.Top.SetAsync(key, "v", Now + Life, policy, Ct)).Should().BeTrue(); + break; + } + + _rig.Clock.Timestamps.Should().Be(timestamps, "one capture at the origin, and one timestamp per evaluation of a framed send ({0})", string.Concat(_rig.Clock.Readings)); + stack.Bottom.Queries.Should().Be(bottomQueries, "the query of the tier the layered cache asks, once per call and level"); + stack.Middle.Queries.Should().Be(middleQueries); + } + + private async Task DirectOrdinaryAsync(FrameWriteRig.Node node, string path, CacheKey key, int timestamps) + { + var policy = path is "unframed" or "off" ? new CachePolicy() : Windowed; + _rig.Clock.Reset(); + + _ = path switch + { + "relative" => await node.Cache.SetAsync(key, "v", Life, policy, Ct), + "never" => await node.Cache.SetAsync(key, "v", DateTimeOffset.MaxValue, policy, Ct), + "batch" => await node.Cache.SetAsync([new KeyValuePair(key, "v")], Now + Life, policy, Ct), + _ => await node.Cache.SetAsync(key, "v", Now + Life, policy, Ct), + }; + + _rig.Clock.Timestamps.Should().Be(timestamps, "one capture at the entry of an enabled instant, and one per evaluation of a framed send"); + } + + private async Task PrepareLayeredAsync(ICache cache, Handoff handoff, CacheKey key, CachePolicy policy) + { + switch (handoff) + { + case Handoff.SetIfChangedHeld: + (await cache.SetAsync(key, "old", TimeSpan.FromMinutes(5), null, Ct)).Should().BeTrue(); + break; + case Handoff.Stamped: + (await cache.SetAsync(key, "old", TimeSpan.FromSeconds(30), policy, Ct)).Should().BeTrue(); + _rig.Manual.Advance(TimeSpan.FromSeconds(3.5)); + break; + } + } + + private async Task LayeredCallAsync(ICache cache, Handoff handoff, Deadline deadline, CacheKey key, CachePolicy policy, DateTimeOffset instant) + { + KeyValuePair[] pair = [new(key, "v")]; + switch (handoff) + { + case Handoff.Foreground or Handoff.Background: + (await (deadline switch + { + Deadline.Instant => cache.SetAsync(key, "v", instant, policy, Ct), + Deadline.Duration => cache.SetAsync(key, "v", Life, policy, Ct), + _ => cache.SetAsync(key, "v", policy, Ct), + })).Should().BeTrue(); + break; + case Handoff.Batch: + (await (deadline switch + { + Deadline.Instant => cache.SetAsync(pair, instant, policy, Ct), + Deadline.Duration => cache.SetAsync(pair, Life, policy, Ct), + _ => cache.SetAsync(pair, policy, Ct), + })).Should().BeTrue(); + break; + case Handoff.ManySet: + _ = await (deadline switch + { + Deadline.Instant => cache.SetManyAsync(pair, instant, policy, Ct), + Deadline.Duration => cache.SetManyAsync(pair, Life, policy, Ct), + _ => cache.SetManyAsync(pair, policy, Ct), + }); + break; + case Handoff.TryAdd: + (await (deadline switch + { + Deadline.Instant => cache.TryAddAsync(key, "v", instant, policy, Ct), + Deadline.Duration => cache.TryAddAsync(key, "v", Life, policy, Ct), + _ => cache.TryAddAsync(key, "v", policy, Ct), + })).Should().BeTrue(); + break; + case Handoff.GeneratedStore or Handoff.FencedFill or Handoff.Stamped: + (await (deadline switch + { + Deadline.Instant => cache.GetOrAddAsync(key, static _ => Task.FromResult("v"), instant, policy, Ct), + Deadline.Duration => cache.GetOrAddAsync(key, static _ => Task.FromResult("v"), Life, policy, Ct), + _ => cache.GetOrAddAsync(key, static _ => Task.FromResult("v"), policy, Ct), + })).Should().Be(handoff == Handoff.Stamped ? "old" : "v"); + break; + case Handoff.TryFill: + (await (deadline switch + { + Deadline.Instant => cache.TryFillAsync(key, "v", instant, policy, Ct), + Deadline.Duration => cache.TryFillAsync(key, "v", Life, policy, Ct), + _ => cache.TryFillAsync(key, "v", Life, policy, Ct), + })).Outcome.Should().Be(FillOutcome.Added); + break; + case Handoff.SetIfChangedAbsent or Handoff.SetIfChangedHeld: + var change = await (deadline == Deadline.Instant + ? cache.SetIfChangedAsync(key, "v", StringComparer.Ordinal, instant, policy, Ct) + : cache.SetIfChangedAsync(key, "v", StringComparer.Ordinal, Life, policy, Ct)); + change.Outcome.Should().Be(handoff == Handoff.SetIfChangedAbsent ? ChangeOutcome.Filled : ChangeOutcome.Replaced); + break; + default: + (await ((IMigrationCache)cache).WriteAsync(key, "v", instant, policy, Ct)).Should().Be(StoreOutcome.Committed); + break; + } + } + + private async Task OriginCallAsync(ICache cache, Origin origin, Deadline deadline, CacheKey key, DateTimeOffset instant) + { + KeyValuePair[] pair = [new(key, "v")]; + KeyValuePair[] asked = [new(key, "s")]; + static Task[]> Batch(string[] states, CancellationToken ct) => + Task.FromResult(states.Select(static s => new KeyValuePair(s, "v")).ToArray()); + switch (origin) + { + case Origin.Set: + (await (deadline switch + { + Deadline.Instant => cache.SetAsync(key, "v", instant, Windowed, Ct), + Deadline.Duration => cache.SetAsync(key, "v", Life, Windowed, Ct), + _ => cache.SetAsync(key, "v", Windowed, Ct), + })).Should().BeTrue(); + break; + case Origin.ManySet: + (await (deadline switch + { + Deadline.Instant => cache.SetAsync(pair, instant, Windowed, Ct), + Deadline.Duration => cache.SetAsync(pair, Life, Windowed, Ct), + _ => cache.SetAsync(pair, Windowed, Ct), + })).Should().BeTrue(); + break; + case Origin.BatchGetOrAdd: + _ = await (deadline switch + { + Deadline.Instant => cache.GetOrAddAsync(asked, Batch, instant, Windowed, Ct), + Deadline.Duration => cache.GetOrAddAsync(asked, Batch, Life, Windowed, Ct), + _ => cache.GetOrAddAsync(asked, Batch, Windowed, Ct), + }); + break; + case Origin.TryFill: + (await (deadline switch + { + Deadline.Instant => cache.TryFillAsync(key, "v", instant, Windowed, Ct), + _ => cache.TryFillAsync(key, "v", Life, Windowed, Ct), + })).Outcome.Should().Be(FillOutcome.Added); + break; + case Origin.SetIfChanged: + (await (deadline == Deadline.Instant + ? cache.SetIfChangedAsync(key, "v", StringComparer.Ordinal, instant, Windowed, Ct) + : cache.SetIfChangedAsync(key, "v", StringComparer.Ordinal, Life, Windowed, Ct))).Outcome.Should().Be(ChangeOutcome.Filled); + break; + case Origin.PolicyMiss: + (await cache.GetOrAddAsync(key, static _ => Task.FromResult("v"), Windowed, Ct)).Should().Be("v"); + break; + case Origin.ResultMiss: + (await cache.GetOrAddResultAsync(key, static _ => Task.FromResult("v"), Windowed, Ct)).Value.Should().Be("v"); + break; + default: + (await cache.GetOrAddWithExpirationAsync(key, static _ => Task.FromResult(new GeneratedValue("v")), Windowed, Ct)).Should().Be("v"); + break; + } + } + + /// A key strategy that sets the UTC clock back when armed, which the entry builder runs after the layered origin took its deadline. + private sealed class SteppingStrategy(FrameWriteRig rig) : ICacheKeyStrategy + { + private readonly DefaultCacheKeyStrategy _inner = new(); + + public bool Armed { get; set; } + + public CacheKey GetCacheKey(CacheKey key) + { + if (Armed) + { + Armed = false; + rig.Manual.StepUtc(StepBack); + } + + return _inner.GetCacheKey(key); + } + } +} diff --git a/tests/UiPath.Caching.Tests/Redis/EntryFrameWriteAnchorTests.cs b/tests/UiPath.Caching.Tests/Redis/EntryFrameWriteAnchorTests.cs new file mode 100644 index 000000000..60f5d0b63 --- /dev/null +++ b/tests/UiPath.Caching.Tests/Redis/EntryFrameWriteAnchorTests.cs @@ -0,0 +1,416 @@ +using UiPath.Caching.Redis; + +namespace UiPath.Caching.Tests.Redis; + +// The write anchor (WA1 to WA5, OD40): the UTC clock and the timestamp move apart on the ManualTimeProvider, so a test sets UTC back or forward while monotonic time runs on. +[Collection("RedisIntegration")] +[Trait("Category", "Integration")] +public sealed partial class EntryFrameWriteAnchorTests(RedisContainerFixture fixture) : IAsyncDisposable +{ + private static readonly TimeSpan Window = FrameWriteRig.Window; + private static readonly TimeSpan Life = TimeSpan.FromSeconds(10); + private static readonly CachePolicy Windowed = FrameWriteRig.Windowed(distributed: Life); + + private readonly FrameWriteRig _rig = new(fixture); + + public enum Call + { + Set, + CachedNull, + ManySet, + TryAdd, + TryAddOverTombstone, + GeneratedStore, + Result, + TryFill, + ManyFill, + FencedFill, + SetIfChangedAbsent, + SetIfChangedHeld, + StampedAbsent, + StampedOverStamp, + } + + public enum Form + { + GateClosedAfterDispatch, + GateClosedBetweenAttempts, + SkipFailSafe, + ReservedByte, + } + + public enum Ended + { + UtcPastTheInstant, + MonotonicLifeEnded, + } + + public enum Own + { + Positive, + Zero, + Negative, + None, + Never, + } + + public static TheoryData StepBackCalls + { + get + { + var data = new TheoryData(); + foreach (var call in Enum.GetValues()) + { + data.Add(call, 1); + } + + data.Add(Call.Set, 2); + data.Add(Call.FencedFill, 2); + return data; + } + } + + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + private DateTimeOffset Now => _rig.Manual.GetUtcNow(); + + public ValueTask DisposeAsync() => _rig.DisposeAsync(); + + // T1, WriteAnchor (WA2 to WA5; teeth-wanchor-C9strict_noLim): a send that counted the UTC clock alone would send 19 seconds plus the window. + [Theory] + [MemberData(nameof(StepBackCalls))] + public async Task A_UTC_step_back_before_the_send_adds_no_life_to_the_TTL(Call call, int steps) + { + var node = await _rig.NodeAsync(o => o.RemoveTombstone = call is Call.FencedFill or Call.TryAddOverTombstone ? TimeSpan.FromSeconds(1) : null); + var (id, key) = NewKey(); + await PrepareAsync(node, call, key); + var instant = Now + Life; + _rig.Pipelines.BeforeWrite = () => + { + _rig.Manual.Advance(TimeSpan.FromSeconds(1)); + for (var i = 0; i < steps; i++) + { + _rig.Manual.StepUtc(TimeSpan.FromSeconds(-10)); + } + + return Task.CompletedTask; + }; + + var reported = await CallAsync(node, call, key, instant); + + var (bytes, ttl) = await _rig.ReadRawAsync(id); + EntryFrame.TryRead(bytes, out var frame).Should().BeTrue(); + frame.Expiration.ToUnixTimeMilliseconds().Should().Be(instant.ToUnixTimeMilliseconds(), "the frame expiration is the caller's instant to the tick"); + ttl!.Value.Should().BeLessThanOrEqualTo(TimeSpan.FromSeconds(9) + Window).And.BeGreaterThan(Window, "the window is there; the time between the SET and the PTTL read is real time, so no lower bound counts it"); + if (reported is { } expiration) + { + expiration.Should().Be(instant); + } + } + + [Theory] + [InlineData(Form.GateClosedAfterDispatch, "set")] + [InlineData(Form.GateClosedBetweenAttempts, "set")] + [InlineData(Form.GateClosedAfterDispatch, "generated")] + [InlineData(Form.SkipFailSafe, "generated")] + [InlineData(Form.SkipFailSafe, "fenced")] + [InlineData(Form.GateClosedAfterDispatch, "fenced")] + [InlineData(Form.ReservedByte, "set")] + public async Task A_UTC_step_forward_before_the_send_ends_the_plain_forms_at_the_UTC_deadline(Form form, string call) + { + var node = await _rig.NodeAsync(o => o.RemoveTombstone = call == "fenced" ? TimeSpan.FromSeconds(1) : null, serializer: form == Form.ReservedByte ? new RawByteSerializerProxy() : null); + var (id, key) = NewKey(); + var instant = Now + Life; + Func stepForward = () => + { + _rig.Manual.Advance(TimeSpan.FromSeconds(1)); + _rig.Manual.StepUtc(TimeSpan.FromSeconds(4)); + return Task.CompletedTask; + }; + if (form == Form.GateClosedBetweenAttempts) + { + _rig.Pipelines.FailFirst = () => + { + _rig.WriteGate.Close(); + return stepForward(); + }; + } + else + { + _rig.Pipelines.BeforeWrite = stepForward; + } + + if (form == Form.GateClosedAfterDispatch) + { + _rig.OnSerialize = () => _rig.WriteGate.Close(); + } + + switch (call) + { + case "set" when form == Form.ReservedByte: + (await node.Cache.SetAsync(key, [0x0E, 7, 1], instant, Windowed, Ct)).Should().BeTrue(); + break; + case "set": + (await node.Cache.SetAsync(key, "v", instant, Windowed, Ct)).Should().BeTrue(); + break; + default: + await node.Cache.GetOrAddWithExpirationAsync(key, _ => Task.FromResult(new GeneratedValue("v") { Expiration = instant, SkipFailSafe = form == Form.SkipFailSafe }), Windowed, Ct); + break; + } + + var (bytes, ttl) = await _rig.ReadRawAsync(id); + EntryFrame.TryRead(bytes, out _).Should().BeFalse("the stored bytes are plain"); + ttl!.Value.Should().BeLessThanOrEqualTo(TimeSpan.FromSeconds(5), "the plain forms end at the instant on the UTC clock that was set forward"); + } + + // T1, WriteAnchor (WA2, GI5): a guard on one clock alone lets one of the two cases through. + [Theory] + [InlineData(Ended.UtcPastTheInstant, true, "set")] + [InlineData(Ended.MonotonicLifeEnded, true, "set")] + [InlineData(Ended.UtcPastTheInstant, false, "set")] + [InlineData(Ended.MonotonicLifeEnded, false, "set")] + [InlineData(Ended.MonotonicLifeEnded, true, "tryadd")] + [InlineData(Ended.MonotonicLifeEnded, true, "generated")] + [InlineData(Ended.UtcPastTheInstant, true, "generated")] + [InlineData(Ended.MonotonicLifeEnded, true, "fill")] + public async Task A_deadline_that_either_clock_ended_stores_nothing(Ended ended, bool windowed, string call) + { + var node = await _rig.NodeAsync(); + var (id, key) = NewKey(); + if (call is "set") + { + (await node.Cache.SetAsync(key, "old", TimeSpan.FromMinutes(5), null, Ct)).Should().BeTrue(); + } + + var instant = Now + Life; + if (!windowed) + { + _rig.OnSerialize = () => _rig.WriteGate.Close(); + } + + _rig.Pipelines.BeforeWrite = () => + { + if (ended == Ended.UtcPastTheInstant) + { + _rig.Manual.Advance(TimeSpan.FromSeconds(1)); + _rig.Manual.StepUtc(TimeSpan.FromSeconds(20)); + } + else + { + _rig.Manual.Advance(TimeSpan.FromSeconds(11)); + _rig.Manual.StepUtc(TimeSpan.FromSeconds(-11)); + } + + _rig.Log.Take(); + return Task.CompletedTask; + }; + + object answer = call switch + { + "set" => await node.Cache.SetAsync(key, "v", instant, Windowed, Ct), + "tryadd" => await node.Cache.TryAddAsync(key, "v", instant, Windowed, Ct), + "generated" => await node.Cache.GetOrAddResultAsync(key, _ => Task.FromResult("v"), instant, Windowed, Ct), + _ => (await node.Cache.TryFillAsync(key, "v", instant, Windowed, Ct)).Outcome, + }; + + _rig.Log.Take().Select(c => c.Command).Should().NotContain("SET"); + switch (answer) + { + case bool stored: + stored.Should().BeFalse(); + break; + case CacheResult result: + result.Value.Should().Be("v"); + result.Expiration.Should().BeNull(); + break; + default: + answer.Should().Be(FillOutcome.Failed); + break; + } + + if (call is "set") + { + (await _rig.ReadRawAsync(id)).Bytes.Should().Equal("\"old\""u8.ToArray()); + } + } + + // T1, WriteAnchor and CarryInstant (WA4 (c), GI1, GI2): a deadline from a duration and a caller's instant keep the anchor of their origin. + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task Each_deadline_origin_keeps_its_own_anchor(bool tombstone) + { + var node = await _rig.NodeAsync(o => o.RemoveTombstone = tombstone ? TimeSpan.FromSeconds(1) : null); + var (callerId, callerKey) = NewKey(); + var (policyId, policyKey) = NewKey(); + var (neverId, neverKey) = NewKey(); + var instant = Now + TimeSpan.FromSeconds(30); + + // A caller's instant: the anchor taken at entry, a generator that runs 20 seconds and a step back of 10 seconds during it. + await node.Cache.GetOrAddAsync(callerKey, _ => Advance(20, -10), instant, Windowed, Ct); + + // A policy duration: the anchor taken where it becomes an instant after the generator, so the step during the generator is not counted. + await node.Cache.GetOrAddAsync(policyKey, _ => Advance(20, -10), Windowed, Ct); + + // "Never": no anchor, plain bytes and no TTL. + var never = await node.Cache.GetOrAddResultAsync(neverKey, _ => Task.FromResult("v"), DateTimeOffset.MaxValue, Windowed, Ct); + + var (_, callerTtl) = await _rig.ReadRawAsync(callerId); + callerTtl!.Value.Should().BeLessThanOrEqualTo(TimeSpan.FromSeconds(10) + Window).And.BeGreaterThan(Window, "the window is there; the time between the SET and the PTTL read is real time, so no lower bound counts it"); + var (_, policyTtl) = await _rig.ReadRawAsync(policyId); + policyTtl!.Value.Should().BeLessThanOrEqualTo(Life + Window).And.BeGreaterThan(Window, "the window is there; the time between the SET and the PTTL read is real time, so no lower bound counts it"); + var (neverBytes, neverTtl) = await _rig.ReadRawAsync(neverId); + neverBytes.Should().Equal("\"v\""u8.ToArray()); + neverTtl.Should().BeNull(); + never.Expiration.Should().BeNull(); + } + + // T1, CarryInstant (WA1, WA4 (d), GI1, GI2; teeth-instantfill-C9strict): a second UTC reading after the validation would give the anchor 10 seconds more. + [Theory] + [InlineData(false, Own.Positive)] + [InlineData(false, Own.Zero)] + [InlineData(false, Own.Negative)] + [InlineData(false, Own.None)] + [InlineData(false, Own.Never)] + [InlineData(true, Own.Positive)] + [InlineData(true, Own.Zero)] + [InlineData(true, Own.Negative)] + [InlineData(true, Own.None)] + [InlineData(true, Own.Never)] + public async Task A_generators_instant_is_validated_and_anchored_from_one_UTC_reading(bool tombstone, Own own) + { + var node = await _rig.NodeAsync(o => o.RemoveTombstone = tombstone ? TimeSpan.FromSeconds(1) : null); + var (id, key) = NewKey(); + List? atSend = null; + _rig.OnCommand = command => + { + if (command == "SET" && atSend is null) + { + lock (_rig.Clock.Readings) + { + atSend = [.. _rig.Clock.Readings]; + } + } + }; + + var value = await node.Cache.GetOrAddWithExpirationAsync( + key, + _ => + { + var now = Now; + DateTimeOffset? instant = own switch + { + Own.Positive => now + Life, + Own.Zero => now, + Own.Negative => now - TimeSpan.FromSeconds(1), + Own.Never => DateTimeOffset.MaxValue, + _ => null, + }; + _rig.Clock.Reset(); + _rig.Clock.AfterUtc = _ => _rig.Manual.StepUtc(TimeSpan.FromSeconds(-10)); + return Task.FromResult(new GeneratedValue("v") { Expiration = instant }); + }, + Windowed, + Ct); + + value.Should().Be("v"); + var (bytes, ttl) = await _rig.ReadRawAsync(id); + switch (own) + { + case Own.Positive or Own.None: + ttl!.Value.Should().BeLessThanOrEqualTo(Life + Window, "not 20 seconds plus the window"); + atSend.Should().NotBeNull(); + atSend!.Take(2).Should().Equal('T', 'U'); + atSend.Count(r => r == 'U').Should().Be(2, "the one reading that validates or makes the instant, then the send's own"); + break; + case Own.Never: + bytes.Should().Equal("\"v\""u8.ToArray()); + ttl.Should().BeNull(); + break; + default: + bytes.Should().BeNull("a zero or negative remainder stores nothing"); + break; + } + } + + [Fact] + public async Task A_refresh_takes_no_anchor() + { + var node = await _rig.NodeAsync(); + var (_, key) = NewKey(); + (await node.Cache.SetAsync(key, "v", Life, null, Ct)).Should().BeTrue(); + _rig.Clock.Reset(); + + await node.Cache.RefreshAsync(key, Now + TimeSpan.FromMinutes(1), null, Ct); + + _rig.Clock.Timestamps.Should().Be(0, "a refresh carries its instant on the server's clock"); + } + + private static (string Id, CacheKey Key) NewKey() + { + var id = Guid.NewGuid().ToString("N"); + return (id, $"{{a}}w:{id}"); + } + + private Task Advance(int seconds, int utcStep) + { + _rig.Manual.Advance(TimeSpan.FromSeconds(seconds)); + _rig.Manual.StepUtc(TimeSpan.FromSeconds(utcStep)); + return Task.FromResult("v"); + } + + private async Task PrepareAsync(FrameWriteRig.Node node, Call call, CacheKey key) + { + switch (call) + { + case Call.TryAddOverTombstone: + (await node.Cache.SetAsync(key, "old", Life, null, Ct)).Should().BeTrue(); + (await node.Cache.RemoveAsync(key, Ct)).Should().BeTrue(); + break; + case Call.SetIfChangedHeld or Call.StampedOverStamp: + (await node.Cache.SetAsync(key, "old", TimeSpan.FromMinutes(5), null, Ct)).Should().BeTrue(); + break; + } + } + + private async Task CallAsync(FrameWriteRig.Node node, Call call, CacheKey key, DateTimeOffset instant) + { + var results = node.Cache; + switch (call) + { + case Call.Set: + (await node.Cache.SetAsync(key, "v", instant, Windowed, Ct)).Should().BeTrue(); + return null; + case Call.CachedNull: + (await node.Cache.SetAsync(key, null, instant, Windowed, Ct)).Should().BeTrue(); + return null; + case Call.ManySet: + (await node.Cache.SetAsync([new KeyValuePair(key, "v")], instant, Windowed, Ct)).Should().BeTrue(); + return null; + case Call.TryAdd or Call.TryAddOverTombstone: + (await node.Cache.TryAddAsync(key, "v", instant, Windowed, Ct)).Should().BeTrue(); + return null; + case Call.GeneratedStore or Call.FencedFill: + (await node.Cache.GetOrAddAsync(key, _ => Task.FromResult("v"), instant, Windowed, Ct)).Should().Be("v"); + return null; + case Call.Result: + return (await results.GetOrAddResultAsync(key, _ => Task.FromResult("v"), instant, Windowed, Ct)).Expiration; + case Call.TryFill: + var fill = await node.Cache.TryFillAsync(key, "v", instant, Windowed, Ct); + fill.Outcome.Should().Be(FillOutcome.Added); + return fill.Expiration; + case Call.ManyFill: + var many = await ((IFillManyTier)node.Redis).TryFillManyAsync([new KeyValuePair(key, "v")], instant, Windowed, Ct); + many[0].Outcome.Should().Be(FillOutcome.Added); + return many[0].Expiration; + case Call.SetIfChangedAbsent or Call.SetIfChangedHeld: + var change = await node.Cache.SetIfChangedAsync(key, "v", StringComparer.Ordinal, instant, Windowed, Ct); + change.Outcome.Should().Be(call == Call.SetIfChangedAbsent ? ChangeOutcome.Filled : ChangeOutcome.Replaced); + return change.Expiration; + default: + var (_, stamp) = await node.Redis.ReadStampedAsync(key, Windowed, Ct); + (await node.Redis.WriteIfStampAsync(key, "v", instant, Windowed, stamp, Ct)).Should().Be(StampedWrite.Won); + return null; + } + } +} diff --git a/tests/UiPath.Caching.Tests/Redis/EntryFrameWriteIntegrationTests.cs b/tests/UiPath.Caching.Tests/Redis/EntryFrameWriteIntegrationTests.cs new file mode 100644 index 000000000..f1fb9eebd --- /dev/null +++ b/tests/UiPath.Caching.Tests/Redis/EntryFrameWriteIntegrationTests.cs @@ -0,0 +1,1427 @@ +using StackExchange.Redis; +using UiPath.Caching.Redis; + +namespace UiPath.Caching.Tests.Redis; + +// Redis counts a TTL on real time while the writer counts on its ManualTimeProvider, so every TTL is compared within Slack. +[Collection("RedisIntegration")] +[Trait("Category", "Integration")] +public sealed class EntryFrameWriteIntegrationTests(RedisContainerFixture fixture) : IAsyncDisposable +{ + private static readonly TimeSpan Window = FrameWriteRig.Window; + private static readonly TimeSpan Life = TimeSpan.FromSeconds(10); + private static readonly TimeSpan Slack = TimeSpan.FromSeconds(1); + private static readonly CachePolicy Windowed = FrameWriteRig.Windowed(distributed: Life); + private static readonly byte[] JsonV = "\"v\""u8.ToArray(); + private static readonly byte[] Reserved = [0x0E, 0x07, 1, 2]; + + private readonly FrameWriteRig _rig = new(fixture); + + public enum Call + { + Set, + TryAdd, + TryFill, + SetIfChanged, + ManySet, + } + + public enum Generated + { + GetOrAdd, + WithExpiration, + Result, + } + + public enum InstantCall + { + Set, + ManySet, + TryAdd, + TryAddOverTombstone, + GetOrAdd, + GetOrAddFenced, + Result, + ResultFenced, + BatchGetOrAdd, + BatchGetOrAddFenced, + } + + public enum Own + { + Ahead, + Passed, + None, + Never, + } + + public enum Closing + { + Set, + CachedNull, + TryAdd, + GeneratedStore, + Fill, + StampedAbsent, + } + + public enum Between + { + Set, + ManySet, + Fill, + ManyFill, + } + + public enum Refused + { + StampedOverStamp, + SetIfChanged, + TryAddOverTombstone, + } + + public enum Fill + { + GetOrAdd, + Result, + Joined, + } + + public enum Fenced7 + { + Future, + ExpiryDuringGeneration, + ExpiryDuringSerialization, + Retry, + Repair, + GateFallback, + Never, + } + + public enum Plain + { + SkipFailSafe, + GateInGenerator, + GateBetweenAttempts, + ReservedByte, + } + + public static TheoryData FencedFills + { + get + { + var data = new TheoryData(); + foreach (var fill in Enum.GetValues()) + { + foreach (var case7 in Enum.GetValues()) + { + data.Add(fill, case7); + } + } + + return data; + } + } + + public static TheoryData PlainForms + { + get + { + var data = new TheoryData(); + foreach (var form in Enum.GetValues()) + { + data.Add(form, false); + data.Add(form, true); + } + + return data; + } + } + + public static TheoryData InstantCalls => new(Enum.GetValues()); + + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + private DateTimeOffset Now => _rig.Manual.GetUtcNow(); + + public ValueTask DisposeAsync() => _rig.DisposeAsync(); + + [Fact] + public async Task A_write_under_the_policy_stores_a_frame_with_ttl_of_lifetime_plus_window() + { + var node = await _rig.NodeAsync(); + var (id, key) = NewKey(); + var at = Now; + + (await node.Cache.SetAsync(key, "v", Life, Windowed, Ct)).Should().BeTrue(); + + var (bytes, ttl) = await _rig.ReadRawAsync(id); + bytes![..2].Should().Equal(0x0E, 0x01); + var frame = Frame(bytes); + frame.Window.Should().Be(Window); + Ms(frame.Expiration).Should().Be(Ms(at + Life)); + frame.Inner.ToArray().Should().Equal(JsonV); + Within(ttl, Life + Window); + } + + [Theory] + [InlineData(Call.Set)] + [InlineData(Call.TryAdd)] + [InlineData(Call.TryFill)] + [InlineData(Call.SetIfChanged)] + [InlineData(Call.ManySet)] + public async Task SetAsync_TryAddAsync_TryFillAsync_SetIfChangedAsync_and_a_many_key_set_all_frame(Call call) + { + var node = await _rig.NodeAsync(); + var (id, key) = NewKey(); + var at = Now; + + var stored = call switch + { + Call.Set => await node.Cache.SetAsync(key, "v", Life, Windowed, Ct), + Call.TryAdd => await node.Cache.TryAddAsync(key, "v", Life, Windowed, Ct), + Call.TryFill => (await node.Cache.TryFillAsync(key, "v", Life, Windowed, Ct)).Outcome == FillOutcome.Added, + Call.SetIfChanged => (await node.Cache.SetIfChangedAsync(key, "v", StringComparer.Ordinal, Life, Windowed, Ct)).Outcome == ChangeOutcome.Filled, + _ => await node.Cache.SetAsync([new KeyValuePair(key, "v")], Life, Windowed, Ct), + }; + + stored.Should().BeTrue(); + var (bytes, ttl) = await _rig.ReadRawAsync(id); + var frame = Frame(bytes); + Ms(frame.Expiration).Should().Be(Ms(at + Life)); + frame.Inner.ToArray().Should().Equal(JsonV); + Within(ttl, Life + Window); + } + + [Fact] + public async Task An_anchored_entry_read_carries_the_observed_bounds() + { + var node = await _rig.NodeAsync(); + var (_, key) = NewKey(); + (await node.Cache.SetAsync(key, "v", TimeSpan.FromMinutes(1), Windowed, Ct)).Should().BeTrue(); + + var entry = await node.Cache.GetCacheEntryAsync(key, Windowed, Ct); + + entry.Value.Should().Be("v"); + entry.Should().BeAssignableTo(); + } + + [Fact] + public async Task An_anchored_unchanged_answer_does_not_keep_a_copy_of_a_windowed_frame() + { + var node = await _rig.NodeAsync(); + var layered = node.LayeredOver(node.Cache, "layered"); + var (_, key) = NewKey(); + var lifetime = TimeSpan.FromMinutes(1); + (await node.Cache.SetAsync(key, "v1", lifetime, Windowed, Ct)).Should().BeTrue(); + + var unchanged = await layered.SetIfChangedAsync(key, "v1", StringComparer.Ordinal, lifetime, Windowed, Ct); + unchanged.Outcome.Should().Be(ChangeOutcome.Unchanged); + + (await node.Cache.SetAsync(key, "v2", lifetime, Windowed, Ct)).Should().BeTrue(); + (await layered.GetAsync(key, Windowed, Ct)).Should().Be("v2"); + } + + [Fact] + public async Task A_batch_fill_frames_each_value() + { + var node = await _rig.NodeAsync(); + var (a, keyA) = NewKey("t"); + var (b, keyB) = NewKey("t"); + var deadline = Now + Life; + + var filled = await ((IFillManyTier)node.Redis).TryFillManyAsync([new(keyA, "v"), new KeyValuePair(keyB, "v")], deadline, Windowed, Ct); + + filled.Should().OnlyContain(f => f.Outcome == FillOutcome.Added); + foreach (var id in new[] { a, b }) + { + var (bytes, ttl) = await _rig.ReadRawAsync(id); + Ms(Frame(bytes).Expiration).Should().Be(Ms(deadline)); + Within(ttl, Life + Window); + } + } + + [Fact] + public async Task A_generated_store_on_the_layered_cache_frames_the_value() + { + var node = await _rig.NodeAsync(); + var (id, key) = NewKey(); + + (await node.Layered.GetOrAddAsync(key, _ => Task.FromResult("v"), Life, Windowed, Ct)).Should().Be("v"); + + var (bytes, ttl) = await _rig.ReadRawAsync(id); + Frame(bytes).Inner.ToArray().Should().Equal(JsonV); + Within(ttl, Life + Window); + } + + [Theory] + [InlineData(Generated.GetOrAdd)] + [InlineData(Generated.WithExpiration)] + [InlineData(Generated.Result)] + public async Task A_generated_store_on_the_Redis_only_provider_frames_the_value(Generated call) + { + var node = await _rig.NodeAsync(); + var (id, key) = NewKey(); + var at = Now; + + await GenerateAsync(node, call, key); + + var (bytes, ttl) = await _rig.ReadRawAsync(id); + Ms(Frame(bytes).Expiration).Should().Be(Ms(at + Life)); + Within(ttl, Life + Window); + } + + [Theory] + [InlineData(Generated.GetOrAdd)] + [InlineData(Generated.WithExpiration)] + [InlineData(Generated.Result)] + public async Task A_fenced_generated_fill_frames_the_value(Generated call) + { + var node = await _rig.NodeAsync(o => o.RemoveTombstone = TimeSpan.FromSeconds(1)); + var (id, key) = NewKey(); + var at = Now; + + await GenerateAsync(node, call, key); + + var (bytes, ttl) = await _rig.ReadRawAsync(id); + Ms(Frame(bytes).Expiration).Should().Be(Ms(at + Life)); + Within(ttl, Life + Window); + } + + // T1, WriteAnchor and CarryInstant (W9, GS2, GS3): a run that worked out its deadline after the reply would report one 5 seconds later than its frame. + [Theory] + [InlineData(Generated.Result)] + [InlineData(Generated.GetOrAdd)] + [InlineData(Generated.WithExpiration)] + public async Task A_generated_store_reports_the_frame_expiration_however_late_the_write_reply_is(Generated joined) + { + var node = await _rig.NodeAsync(); + var (id, key) = NewKey(); + var at = Now; + _rig.Pipelines.AfterWrite = () => + { + _rig.Manual.Advance(TimeSpan.FromSeconds(5)); + return Task.CompletedTask; + }; + + var result = await JoinedResultAsync(node, joined, key); + + result.Expiration.Should().Be(at + Life, "the store took its instant before the send"); + var (bytes, _) = await _rig.ReadRawAsync(id); + Ms(Frame(bytes).Expiration).Should().Be(Ms(result.Expiration!.Value)); + var entry = await node.Cache.GetCacheEntryAsync(key, Windowed, Ct); + Ms(entry.Expiration).Should().Be(Ms(result.Expiration.Value)); + } + + [Theory] + [InlineData(false, Generated.Result)] + [InlineData(false, Generated.GetOrAdd)] + [InlineData(true, Generated.Result)] + public async Task A_generated_store_without_a_frame_reports_what_it_reports_today(bool metadata, Generated joined) + { + var node = await _rig.NodeAsync(metadata: metadata); + var (id, key) = NewKey(); + var policy = metadata ? new CachePolicy { DistributedExpiration = Life } : Windowed; + _rig.Pipelines.AfterWrite = () => + { + _rig.Manual.Advance(TimeSpan.FromSeconds(5)); + return Task.CompletedTask; + }; + + var result = await JoinedResultAsync(node, joined, key, policy); + + result.Expiration.Should().Be(Now + Life, "today's run counts the lifetime from after the reply"); + var (bytes, ttl) = await _rig.ReadRawAsync(id); + bytes.Should().Equal(JsonV); + Within(ttl, Life); + } + + // T1, CarryInstant (GS5, GI1 to GI5; teeth-instant-C9strict): an instant rebuilt from a duration after the gap would end 20 seconds late. + [Theory] + [InlineData(false, Own.Ahead)] + [InlineData(false, Own.Passed)] + [InlineData(false, Own.None)] + [InlineData(false, Own.Never)] + [InlineData(true, Own.Ahead)] + [InlineData(true, Own.Passed)] + [InlineData(true, Own.None)] + [InlineData(true, Own.Never)] + public async Task A_generators_own_expiration_is_the_frame_expiration_and_the_reported_one(bool tombstone, Own own) + { + var node = await _rig.NodeAsync(o => o.RemoveTombstone = tombstone ? TimeSpan.FromSeconds(1) : null); + var (id, key) = NewKey(); + var instant = own switch + { + Own.Ahead => Now + TimeSpan.FromSeconds(30), + Own.Passed => Now - TimeSpan.FromSeconds(1), + Own.Never => DateTimeOffset.MaxValue, + _ => (DateTimeOffset?)null, + }; + if (own == Own.Ahead) + { + _rig.Pipelines.BeforeWrite = () => + { + _rig.Manual.Advance(TimeSpan.FromSeconds(20)); + return Task.CompletedTask; + }; + } + + var captured = Now; + _rig.Log.Take(); + + var result = await JoinedResultAsync(node, Generated.WithExpiration, key, Windowed, instant); + + var (bytes, ttl) = await _rig.ReadRawAsync(id); + switch (own) + { + case Own.Ahead: + Ms(Frame(bytes).Expiration).Should().Be(Ms(instant!.Value)); + result.Expiration.Should().Be(instant); + ttl.Should().BeLessThanOrEqualTo(TimeSpan.FromSeconds(10) + Window + Slack); + break; + case Own.Passed: + _rig.Log.Take().Select(c => c.Command).Should().NotContain("SET").And.NotContain("EVAL"); + result.Value.Should().Be("v"); + result.Expiration.Should().BeNull(); + break; + case Own.None: + Ms(Frame(bytes).Expiration).Should().Be(Ms(captured + Life)); + result.Expiration.Should().Be(captured + Life); + break; + default: + bytes.Should().Equal(JsonV); + ttl.Should().BeNull(); + result.Expiration.Should().BeNull(); + break; + } + } + + // T1, CarryInstant (IC1 to IC5; teeth-instant-C9strict): a duration taken at entry and counted again at the send gives a frame that ends 3 seconds late. + [Theory] + [MemberData(nameof(InstantCalls))] + public async Task A_callers_instant_is_the_frame_expiration(InstantCall call) + { + var node = await _rig.NodeAsync(o => o.RemoveTombstone = Fenced(call) ? TimeSpan.FromSeconds(1) : null); + var (id, key) = NewKey(); + var instant = Now + Life; + + var (stored, reported) = await WithInstantAsync(node, call, key, id, instant, seed: false, () => _rig.Pipelines.BeforeWrite = () => + { + _rig.Manual.Advance(TimeSpan.FromSeconds(3)); + return Task.CompletedTask; + }); + + stored.Should().BeTrue(); + var (bytes, ttl) = await _rig.ReadRawAsync(id); + Ms(Frame(bytes).Expiration).Should().Be(Ms(instant)); + Within(ttl, TimeSpan.FromSeconds(7) + Window); + if (reported is { } expiration) + { + expiration.Should().Be(instant); + } + } + + // T1, WriteAnchor (IC4, GI5): a window that kept a write alive would send once the instant has passed. + [Theory] + [MemberData(nameof(InstantCalls))] + public async Task A_store_whose_instant_passed_before_the_send_stores_nothing(InstantCall call) + { + var node = await _rig.NodeAsync(o => o.RemoveTombstone = Fenced(call) ? TimeSpan.FromSeconds(1) : null); + var (id, key) = NewKey(); + var instant = Now + Life; + + var (stored, reported) = await WithInstantAsync(node, call, key, id, instant, seed: true, () => _rig.Pipelines.BeforeWrite = () => + { + _rig.Manual.Advance(TimeSpan.FromSeconds(20)); + _rig.Log.Take(); + return Task.CompletedTask; + }); + + _rig.Log.Take().Select(c => c.Command).Should().NotContain("SET").And.NotContain("EVAL"); + stored.Should().BeFalse(); + reported.Should().BeNull(); + var (bytes, _) = await _rig.ReadRawAsync(id); + if (call is InstantCall.Set or InstantCall.ManySet) + { + bytes.Should().Equal("\"old\""u8.ToArray(), "the value that was in the key stays"); + } + } + + [Fact] + public async Task A_callers_instant_of_MaxValue_stores_plain_bytes_without_a_TTL() + { + var node = await _rig.NodeAsync(); + var (id, key) = NewKey(); + + (await node.Cache.SetAsync(key, "v", DateTimeOffset.MaxValue, Windowed, Ct)).Should().BeTrue(); + + var (bytes, ttl) = await _rig.ReadRawAsync(id); + bytes.Should().Equal(JsonV); + ttl.Should().BeNull(); + } + + [Fact] + public async Task A_duration_still_counts_from_the_store() + { + var node = await _rig.NodeAsync(); + var (id, key) = NewKey(); + var at = Now; + _rig.Pipelines.BeforeWrite = () => + { + _rig.Manual.Advance(TimeSpan.FromSeconds(3)); + return Task.CompletedTask; + }; + + (await node.Cache.SetAsync(key, "v", Life, Windowed, Ct)).Should().BeTrue(); + + var (bytes, ttl) = await _rig.ReadRawAsync(id); + Ms(Frame(bytes).Expiration).Should().Be(Ms(at + Life)); + Within(ttl, Life + Window); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task Without_the_option_or_with_the_gate_closed_a_callers_instant_is_a_duration_as_today(bool gateClosed) + { + var node = await _rig.NodeAsync(metadata: gateClosed); + if (gateClosed) + { + _rig.WriteGate.Close(); + } + + var (id, key) = NewKey(); + _rig.Pipelines.BeforeWrite = () => + { + _rig.Manual.Advance(TimeSpan.FromSeconds(3)); + return Task.CompletedTask; + }; + + (await node.Cache.SetAsync(key, "v", Now + Life, Windowed, Ct)).Should().BeTrue(); + + var (bytes, ttl) = await _rig.ReadRawAsync(id); + bytes.Should().Equal(JsonV); + Within(ttl, Life, "the entry turned the instant into a duration, which the SET counts from its send"); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task The_default_policy_and_a_call_site_policy_both_frame(bool callSite) + { + var node = await _rig.NodeAsync(defaultPolicy: callSite ? null : Windowed); + var (id, key) = NewKey(); + + (await node.Cache.SetAsync(key, "v", Life, callSite ? Windowed : null, Ct)).Should().BeTrue(); + + var (bytes, ttl) = await _rig.ReadRawAsync(id); + Frame(bytes).Window.Should().Be(Window); + Within(ttl, Life + Window); + } + + [Fact] + public async Task A_cached_null_is_framed_with_an_empty_inner_value() + { + var node = await _rig.NodeAsync(); + var (id, key) = NewKey(); + + (await node.Cache.SetAsync(key, null, Life, Windowed, Ct)).Should().BeTrue(); + + var (bytes, ttl) = await _rig.ReadRawAsync(id); + Frame(bytes).Inner.IsEmpty.Should().BeTrue(); + Within(ttl, Life + Window); + } + + [Fact] + public async Task A_write_without_the_policy_option_stores_the_plain_value() + { + var node = await _rig.NodeAsync(); + var (id, key) = NewKey(); + + (await node.Cache.SetAsync(key, "v", Life, new CachePolicy { FailSafeEnabled = true }, Ct)).Should().BeTrue(); + + var (bytes, ttl) = await _rig.ReadRawAsync(id); + bytes.Should().Equal(JsonV); + Within(ttl, Life); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task A_SkipFailSafe_value_stores_no_window(bool tombstone) + { + var node = await _rig.NodeAsync(o => o.RemoveTombstone = tombstone ? TimeSpan.FromSeconds(1) : null); + var (id, key) = NewKey(); + + await node.Cache.GetOrAddWithExpirationAsync(key, _ => Task.FromResult(new GeneratedValue("v") { SkipFailSafe = true }), Windowed, Ct); + + var (bytes, ttl) = await _rig.ReadRawAsync(id); + bytes.Should().Equal(JsonV); + Within(ttl, Life); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task A_stamped_write_frames_the_value(bool overStamp) + { + var node = await _rig.NodeAsync(); + var (id, key) = NewKey(); + if (overStamp) + { + (await node.Cache.SetAsync(key, "old", Life, Windowed, Ct)).Should().BeTrue(); + } + + var (_, stamp) = await node.Redis.ReadStampedAsync(key, Windowed, Ct); + var deadline = Now + Life; + + (await node.Redis.WriteIfStampAsync(key, "v", deadline, Windowed, stamp, Ct)).Should().Be(StampedWrite.Won); + + var (bytes, ttl) = await _rig.ReadRawAsync(id); + Ms(Frame(bytes).Expiration).Should().Be(Ms(deadline)); + Within(ttl, Life + Window); + } + + [Fact] + public async Task A_stamped_write_whose_logical_deadline_has_passed_stores_nothing() + { + var node = await _rig.NodeAsync(); + var (id, key) = NewKey(); + var deadline = Now + Life; + _rig.Pipelines.BeforeWrite = () => + { + _rig.Manual.Advance(TimeSpan.FromSeconds(11)); + return Task.CompletedTask; + }; + + (await node.Redis.WriteIfStampAsync(key, "v", deadline, Windowed, null, Ct)).Should().Be(StampedWrite.Failed); + + (await _rig.ReadRawAsync(id)).Bytes.Should().BeNull("the window does not keep it alive"); + } + + // T1, RecheckGate (W4, FR9; teeth-gate-NoFrameAfterGateClosed): a gate asked only at dispatch would store a frame after it closed. + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task A_gate_that_closes_while_the_generator_runs_stores_the_plain_value(bool tombstone) + { + var node = await _rig.NodeAsync(o => o.RemoveTombstone = tombstone ? TimeSpan.FromSeconds(1) : null); + var (id, key) = NewKey(); + + await node.Cache.GetOrAddAsync( + key, + _ => + { + _rig.WriteGate.Close(); + return Task.FromResult("v"); + }, + Windowed, + Ct); + + var (bytes, ttl) = await _rig.ReadRawAsync(id); + bytes.Should().Equal(JsonV); + Within(ttl, Life); + } + + [Theory] + [InlineData(new byte[] { 0x0E, 0x07, 1, 2 })] + [InlineData(new byte[] { 0x0F, 1, 2 })] + public async Task A_value_whose_bytes_start_with_a_reserved_byte_is_stored_plain_and_reads_back(byte[] value) + { + var a = await _rig.NodeAsync(serializer: new RawByteSerializerProxy()); + var b = await _rig.NodeAsync(serializer: new RawByteSerializerProxy()); + var (id, key) = NewKey(); + + (await a.Cache.SetAsync(key, value, Life, Windowed, Ct)).Should().BeTrue(); + + var (bytes, ttl) = await _rig.ReadRawAsync(id); + bytes.Should().Equal(value); + Within(ttl, Life); + if (value[0] == 0x0E) + { + (await a.Cache.GetAsync(key, Windowed, Ct)).Should().Equal(value); + (await b.Cache.GetAsync(key, null, Ct)).Should().Equal(value); + } + } + + [Fact] + public async Task A_write_with_no_expiry_under_the_policy_stores_the_plain_value_without_a_ttl() + { + var node = await _rig.NodeAsync(); + var (id, key) = NewKey(); + + (await node.Cache.SetAsync(key, "v", TimeSpan.MaxValue, Windowed, Ct)).Should().BeTrue(); + + var (bytes, ttl) = await _rig.ReadRawAsync(id); + bytes.Should().Equal(JsonV); + ttl.Should().BeNull(); + } + + [Fact] + public async Task With_the_gate_closed_the_plain_value_is_stored() + { + var node = await _rig.NodeAsync(); + _rig.WriteGate.Close(); + var (id, key) = NewKey(); + + (await node.Cache.SetAsync(key, "v", Life, Windowed, Ct)).Should().BeTrue(); + + var (bytes, ttl) = await _rig.ReadRawAsync(id); + bytes.Should().Equal(JsonV); + Within(ttl, Life); + } + + // T1, RecheckGate (W8; teeth-gate-NoFrameAfterGateClosed): bytes built before a connect wait must not land as a frame once the gate closed. + [Theory] + [InlineData(Closing.Set)] + [InlineData(Closing.CachedNull)] + [InlineData(Closing.TryAdd)] + [InlineData(Closing.GeneratedStore)] + [InlineData(Closing.Fill)] + [InlineData(Closing.StampedAbsent)] + public async Task A_gate_that_closes_before_a_delayed_send_stores_the_plain_value(Closing call) + { + var node = await _rig.NodeAsync(); + var (id, key) = NewKey(); + var connect = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + if (call != Closing.GeneratedStore) + { + node.Connector.PendingConnect = connect; + } + + Task PendAndGenerate(CancellationToken token) + { + node.Connector.PendingConnect = connect; + return Task.FromResult("v"); + } + + var pending = call switch + { + Closing.Set => (Task)node.Cache.SetAsync(key, "v", Life, Windowed, Ct).AsTask(), + Closing.CachedNull => node.Cache.SetAsync(key, null, Life, Windowed, Ct).AsTask(), + Closing.TryAdd => node.Cache.TryAddAsync(key, "v", Life, Windowed, Ct).AsTask(), + Closing.GeneratedStore => node.Cache.GetOrAddAsync(key, PendAndGenerate, Windowed, Ct).AsTask(), + Closing.Fill => node.Cache.TryFillAsync(key, "v", Life, Windowed, Ct).AsTask(), + _ => node.Redis.WriteIfStampAsync(key, "v", Now + Life, Windowed, null, Ct).AsTask(), + }; + await WaitUntilAsync(() => node.Connector.PendingConnect is null); + _rig.WriteGate.Close(); + connect.SetResult(); + await pending; + + var (bytes, ttl) = await _rig.ReadRawAsync(id); + bytes.Should().Equal(call == Closing.CachedNull ? [] : JsonV); + Within(ttl, Life); + } + + [Theory] + [InlineData(Between.Set)] + [InlineData(Between.ManySet)] + [InlineData(Between.Fill)] + [InlineData(Between.ManyFill)] + public async Task A_gate_that_closes_between_two_attempts_stores_the_plain_value(Between call) + { + var node = await _rig.NodeAsync(); + var (id, key) = NewKey(); + _rig.Pipelines.FailFirst = () => + { + _rig.WriteGate.Close(); + return Task.CompletedTask; + }; + + _ = call switch + { + Between.Set => await node.Cache.SetAsync(key, "v", Life, Windowed, Ct), + Between.ManySet => await node.Cache.SetAsync([new KeyValuePair(key, "v")], Life, Windowed, Ct), + Between.Fill => (await node.Cache.TryFillAsync(key, "v", Life, Windowed, Ct)).Outcome == FillOutcome.Added, + _ => (await ((IFillManyTier)node.Redis).TryFillManyAsync([new KeyValuePair(key, "v")], Now + Life, Windowed, Ct))[0].Outcome == FillOutcome.Added, + }; + + var (bytes, ttl) = await _rig.ReadRawAsync(id); + bytes.Should().Equal(JsonV); + Within(ttl, Life); + } + + // T1, RecheckGate (WS4): the transaction after a refused script sends what the gate allows then, not what it allowed before the script. + [Theory] + [InlineData(Refused.StampedOverStamp)] + [InlineData(Refused.SetIfChanged)] + [InlineData(Refused.TryAddOverTombstone)] + public async Task A_gate_that_closes_after_a_refused_script_stores_the_plain_value_in_the_transaction(Refused call) + { + var node = await _rig.NodeAsync( + o => + { + o.ReadScriptsEnabled = true; + o.RemoveTombstone = call == Refused.TryAddOverTombstone ? TimeSpan.FromSeconds(1) : null; + }, + user: _ => "-@scripting"); + var (id, key) = NewKey(); + (await node.Cache.SetAsync(key, "old", Life, Windowed, Ct)).Should().BeTrue(); + object? stamp = null; + if (call == Refused.StampedOverStamp) + { + (_, stamp) = await node.Redis.ReadStampedAsync(key, Windowed, Ct); + } + else if (call == Refused.TryAddOverTombstone) + { + (await node.Cache.RemoveAsync(key, Ct)).Should().BeTrue(); + } + + var refused = false; + _rig.OnCommand = command => refused |= command == "EVAL"; + _rig.WriteGate.Holding = () => refused ? "closed after the script" : null; + + _ = call switch + { + Refused.StampedOverStamp => await node.Redis.WriteIfStampAsync(key, "v", Now + Life, Windowed, stamp, Ct) == StampedWrite.Won, + Refused.SetIfChanged => (await node.Cache.SetIfChangedAsync(key, "v", StringComparer.Ordinal, Life, Windowed, Ct)).Outcome == ChangeOutcome.Replaced, + _ => await node.Cache.TryAddAsync(key, "v", Life, Windowed, Ct), + }; + + refused.Should().BeTrue(); + var (bytes, ttl) = await _rig.ReadRawAsync(id); + bytes.Should().Equal(JsonV); + Within(ttl, Life); + } + + [Fact] + public async Task A_gate_that_opens_after_the_bytes_were_built_still_stores_the_plain_value() + { + var node = await _rig.NodeAsync(); + var (id, key) = NewKey(); + _rig.OnSerialize = () => + { + _rig.OnSerialize = null; + _rig.WriteGate.Close(); + }; + _rig.Pipelines.BeforeWrite = () => + { + _rig.WriteGate.Open(); + return Task.CompletedTask; + }; + + (await node.Cache.SetAsync(key, "v", Life, Windowed, Ct)).Should().BeTrue(); + + var (bytes, ttl) = await _rig.ReadRawAsync(id); + bytes.Should().Equal(JsonV); + Within(ttl, Life); + } + + [Fact] + public async Task A_plain_policy_never_asks_for_the_send_form() + { + var node = await _rig.NodeAsync(serializer: new RawByteSerializerProxy()); + _rig.WriteGate.Close(); + var (id, key) = NewKey(); + var looksFramed = EntryFrameVectors.WithInner((byte)'x'); + + (await node.Cache.SetAsync(key, looksFramed, Life, null, Ct)).Should().BeTrue(); + + (await _rig.ReadRawAsync(id)).Bytes.Should().Equal(looksFramed, "the plain branch stores its bytes as given, with the gate closed"); + } + + [Fact] + public async Task The_other_node_reads_the_value_and_expires_it_locally_at_the_logical_expiration() + { + var a = await _rig.NodeAsync(); + var b = await _rig.NodeAsync(); + var (_, key) = NewKey(); + var at = Now; + + (await a.Cache.SetAsync(key, "v", Life, Windowed, Ct)).Should().BeTrue(); + + var entry = await b.Layered.GetCacheEntryAsync(key, Windowed, Ct); + entry.Value.Should().Be("v"); + entry.Expiration.Should().BeOnOrBefore(at + Life, "the logical expiration is the earlier of the frame's and the key's end less the window").And.BeAfter(at + Life - Slack); + _rig.Manual.Advance(Life + TimeSpan.FromSeconds(1)); + (await b.Layered.GetAsync(key, Windowed, Ct)).Should().BeNull("the logical expiration passed on both tiers"); + } + + // T1, ReadsUnwrapOnEmOff (FR3, FS13; teeth-emoff-C9strict): a node whose option is off that answered the inner value of a windowed frame past its logical expiration would serve a copy that ended. + [Fact] + public async Task A_node_with_entry_metadata_off_unwraps_a_windowed_frame_and_ends_it_at_its_logical_expiration() + { + var writer = await _rig.NodeAsync(); + var reader = await _rig.NodeAsync(metadata: false); + var (id, key) = NewKey(); + var at = Now; + (await writer.Cache.SetAsync(key, "v", Life, Windowed, Ct)).Should().BeTrue(); + Frame((await _rig.ReadRawAsync(id)).Bytes); + + (await reader.Cache.GetAsync(key, Windowed, Ct)).Should().Be("v", "the value read unwraps the frame"); + var entry = await reader.Cache.GetCacheEntryAsync(key, Windowed, Ct); + entry.Value.Should().Be("v", "the entry read unwraps it too"); + entry.Expiration.Should().BeOnOrBefore(at + Life).And.BeAfter(at + Life - Slack); + + _rig.Manual.Advance(Life + TimeSpan.FromSeconds(1)); + + (await reader.Cache.GetAsync(key, Windowed, Ct)).Should().BeNull("the logical expiration passed while the window keeps the key"); + (await reader.Cache.GetCacheEntryAsync(key, Windowed, Ct)).Found.Should().BeFalse(); + (await _rig.ReadRawAsync(id)).Bytes.Should().NotBeNull("the window still holds the copy"); + } + + [Theory] + [InlineData("get")] + [InlineData("probe")] + [InlineData("batch")] + public async Task A_value_only_read_under_a_windowed_policy_takes_one_round_trip(string read) + { + var node = await _rig.NodeAsync(); + var (_, key) = NewKey(); + (await node.Cache.SetAsync(key, "v", Life, Windowed, Ct)).Should().BeTrue(); + _rig.Log.Take(); + + var value = read switch + { + "get" => await node.Cache.GetAsync(key, Windowed, Ct), + "probe" => await node.Cache.GetOrAddAsync(key, _ => Task.FromResult("generated"), Windowed, Ct), + _ => (await node.Cache.GetAsync([key], Windowed, Ct))[0].Value, + }; + + value.Should().Be("v"); + _rig.Log.Take().Select(c => c.Command).Should().Equal("MULTI", read == "batch" ? "MGET" : "GET", "PTTL", "EXEC"); + } + + [Theory] + [InlineData("entry")] + [InlineData("batch")] + [InlineData("layered")] + public async Task An_entry_read_under_a_windowed_policy_takes_one_transaction_and_no_other_read(string read) + { + var node = await _rig.NodeAsync(); + var (_, key) = NewKey(); + (await node.Cache.SetAsync(key, "v", Life, Windowed, Ct)).Should().BeTrue(); + _rig.Log.Take(); + + var entry = read switch + { + "entry" => await node.Cache.GetCacheEntryAsync(key, Windowed, Ct), + "batch" => (await node.Cache.GetCacheEntriesAsync([key], Windowed, Ct))[0].Value, + _ => await node.Layered.GetCacheEntryAsync(key, Windowed, Ct), + }; + + entry.Value.Should().Be("v"); + string[] readCommands = ["MULTI", "GET", "MGET", "PTTL", "EXEC", "EVAL_RO"]; + var reads = _rig.Log.Take().Select(c => c.Command).Where(readCommands.Contains); + reads.Should().Equal(["MULTI", read == "batch" ? "MGET" : "GET", "PTTL", "EXEC"], "the layered cache's event stream sends commands of its own, which are no reads"); + } + + [Fact] + public async Task A_replaced_unreadable_value_is_framed() + { + var node = await _rig.NodeAsync(o => o.RemoveTombstone = TimeSpan.FromSeconds(1)); + var (id, key) = NewKey(); + (await node.Cache.SetAsync(key, "seed", Life, null, Ct)).Should().BeTrue(); + var raw = _rig.Raw(id); + await _rig.Db.KeyDeleteAsync(raw); + var at = Now; + + var value = await node.Cache.GetOrAddAsync( + key, + _ => + { + _rig.Db.StringSet(raw, "not json{", TimeSpan.FromHours(1)); + return Task.FromResult("v"); + }, + Windowed, + Ct); + + value.Should().Be("v"); + var (bytes, ttl) = await _rig.ReadRawAsync(id); + Ms(Frame(bytes).Expiration).Should().Be(Ms(at + Life)); + Within(ttl, Life + Window); + } + + // T1, WriteAnchor (GI2, IC5; teeth-instant-C9strict): a fill that counted the instant again after the generator would store a frame that ends late. + [Theory] + [MemberData(nameof(FencedFills))] + public async Task A_callers_instant_bounds_the_fenced_single_key_fill(Fill fill, Fenced7 row) + { + var node = await _rig.NodeAsync(o => o.RemoveTombstone = TimeSpan.FromSeconds(1)); + var (id, key) = NewKey(); + var at = Now; + var instant = row switch + { + Fenced7.Never => DateTimeOffset.MaxValue, + Fenced7.ExpiryDuringGeneration or Fenced7.ExpiryDuringSerialization => at + Life, + _ => at + TimeSpan.FromSeconds(30), + }; + var advance20 = () => _rig.Manual.Advance(TimeSpan.FromSeconds(20)); + Action? during = row switch + { + Fenced7.Future or Fenced7.ExpiryDuringGeneration => advance20, + Fenced7.GateFallback => () => + { + advance20(); + _rig.WriteGate.Close(); + }, + _ => null, + }; + if (row == Fenced7.Repair) + { + (await node.Cache.SetAsync(key, "seed", Life, null, Ct)).Should().BeTrue(); + var raw = _rig.Raw(id); + await _rig.Db.KeyDeleteAsync(raw); + during = () => _rig.Db.StringSet(raw, "not json{", TimeSpan.FromHours(1)); + } + + if (row == Fenced7.ExpiryDuringSerialization) + { + _rig.OnSerialize = () => + { + _rig.OnSerialize = null; + advance20(); + }; + } + + if (row == Fenced7.Retry) + { + _rig.Pipelines.FailFirst = () => + { + _rig.Manual.Advance(TimeSpan.FromSeconds(4)); + return Task.CompletedTask; + }; + } + + _rig.Log.Take(); + + var (value, reported) = await FillAsync(node, fill, key, instant, during); + + value.Should().Be("v"); + var (bytes, ttl) = await _rig.ReadRawAsync(id); + switch (row) + { + case Fenced7.Future or Fenced7.Repair: + Ms(Frame(bytes).Expiration).Should().Be(Ms(instant)); + Within(ttl, (row == Fenced7.Future ? TimeSpan.FromSeconds(10) : TimeSpan.FromSeconds(30)) + Window); + break; + case Fenced7.Retry: + Ms(Frame(bytes).Expiration).Should().Be(Ms(instant)); + Within(ttl, TimeSpan.FromSeconds(26) + Window); + break; + case Fenced7.ExpiryDuringGeneration or Fenced7.ExpiryDuringSerialization: + _rig.Log.Take().Select(c => c.Command).Should().NotContain("SET").And.NotContain("EVAL"); + bytes.Should().BeNull(); + reported.Should().BeNull(); + return; + case Fenced7.GateFallback: + bytes.Should().Equal(JsonV); + ttl.Should().BeLessThanOrEqualTo(Life).And.BeGreaterThan(Life - Slack); + break; + default: + bytes.Should().Equal(JsonV); + ttl.Should().BeNull(); + reported.Should().BeNull(); + return; + } + + if (fill != Fill.GetOrAdd) + { + reported.Should().Be(instant); + } + } + + [Theory] + [MemberData(nameof(PlainForms))] + public async Task A_generators_own_expiration_bounds_the_plain_forms_too(Plain form, bool tombstone) + { + var node = await _rig.NodeAsync(o => o.RemoveTombstone = tombstone ? TimeSpan.FromSeconds(1) : null, serializer: form == Plain.ReservedByte ? new RawByteSerializerProxy() : null); + var (id, key) = NewKey(); + var instant = Now + TimeSpan.FromSeconds(30); + _rig.Pipelines.BeforeWrite = () => + { + _rig.Manual.Advance(TimeSpan.FromSeconds(20)); + return Task.CompletedTask; + }; + + var expiration = await PlainFormAsync(node, form, key, instant); + + var (bytes, ttl) = await _rig.ReadRawAsync(id); + bytes.Should().Equal(form == Plain.ReservedByte ? Reserved : JsonV); + ttl.Should().BeLessThanOrEqualTo(TimeSpan.FromSeconds(10)).And.BeGreaterThan(TimeSpan.FromSeconds(10) - Slack); + expiration.Should().Be(instant); + } + + [Theory] + [InlineData(true, Generated.Result, false)] + [InlineData(true, Generated.GetOrAdd, false)] + [InlineData(true, Generated.WithExpiration, false)] + [InlineData(false, Generated.Result, false)] + [InlineData(false, Generated.GetOrAdd, false)] + [InlineData(false, Generated.WithExpiration, false)] + [InlineData(true, Generated.WithExpiration, true)] + [InlineData(false, Generated.WithExpiration, true)] + public async Task A_generated_store_that_never_expires_reports_no_expiration(bool option, Generated joined, bool generatorSaysNever) + { + var node = await _rig.NodeAsync(metadata: option); + var (id, key) = NewKey(); + var distributed = generatorSaysNever ? Life : TimeSpan.MaxValue; + var policy = option ? FrameWriteRig.Windowed(distributed: distributed) : new CachePolicy { DistributedExpiration = distributed }; + + var result = await JoinedResultAsync(node, joined, key, policy, generatorSaysNever ? DateTimeOffset.MaxValue : null); + + result.Expiration.Should().BeNull(); + var (bytes, ttl) = await _rig.ReadRawAsync(id); + bytes.Should().Equal(JsonV); + ttl.Should().BeNull(); + } + + [Theory] + [InlineData(Plain.SkipFailSafe)] + [InlineData(Plain.GateInGenerator)] + [InlineData(Plain.GateBetweenAttempts)] + [InlineData(Plain.ReservedByte)] + public async Task A_generated_store_that_falls_back_to_plain_bytes_reports_their_end(Plain form) + { + var node = await _rig.NodeAsync(serializer: form == Plain.ReservedByte ? new RawByteSerializerProxy() : null); + var (id, key) = NewKey(); + var until = Now + Life; + _rig.Pipelines.BeforeWrite = () => + { + _rig.Manual.Advance(TimeSpan.FromSeconds(5)); + return Task.CompletedTask; + }; + + var expiration = await PlainFormAsync(node, form, key, null); + + var (bytes, ttl) = await _rig.ReadRawAsync(id); + bytes.Should().Equal(form == Plain.ReservedByte ? Reserved : JsonV); + Within(ttl, Life - TimeSpan.FromSeconds(5)); + expiration.Should().Be(until); + } + + // T1, GI6: the unframed branch is the base build's store, whatever the generator and the reply do. + [Theory] + [InlineData(Generated.GetOrAdd, false)] + [InlineData(Generated.WithExpiration, false)] + [InlineData(Generated.Result, false)] + [InlineData(Generated.GetOrAdd, true)] + [InlineData(Generated.WithExpiration, true)] + [InlineData(Generated.Result, true)] + public async Task With_the_gate_closed_before_the_call_a_generated_store_is_todays_store(Generated joined, bool tombstone) + { + var node = await _rig.NodeAsync(o => o.RemoveTombstone = tombstone ? TimeSpan.FromSeconds(1) : null); + _rig.WriteGate.Close(); + var (id, key) = NewKey(); + var at = Now; + _rig.Pipelines.AfterWrite = () => + { + _rig.Manual.Advance(TimeSpan.FromSeconds(5)); + return Task.CompletedTask; + }; + + var result = await JoinedResultAsync(node, joined, key); + + var (bytes, ttl) = await _rig.ReadRawAsync(id); + bytes.Should().Equal(JsonV); + Within(ttl, Life); + result.Expiration.Should().Be(tombstone ? at + Life : at + TimeSpan.FromSeconds(5) + Life, tombstone ? "the fenced fill reports the deadline fixed before the fill" : "the ordinary store counts the lifetime from after the reply"); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task Each_attempt_of_a_store_with_an_instant_counts_from_its_own_send(bool many) + { + var node = await _rig.NodeAsync(); + var instant = Now + Life; + + async Task> StoreAsync(CacheKey key) => many + ? node.Cache.SetAsync([new KeyValuePair(key, "v")], instant, Windowed, Ct) + : node.Cache.SetAsync(key, "v", instant, Windowed, Ct); + + var (firstId, first) = NewKey(); + (await await StoreAsync(first)).Should().BeTrue(); + var (id, key) = NewKey(); + _rig.Pipelines.FailFirst = () => + { + _rig.Manual.Advance(TimeSpan.FromSeconds(4)); + return Task.CompletedTask; + }; + + (await await StoreAsync(key)).Should().BeTrue(); + + var (firstBytes, firstTtl) = await _rig.ReadRawAsync(firstId); + var (bytes, ttl) = await _rig.ReadRawAsync(id); + bytes.Should().Equal(firstBytes); + Within(firstTtl, Life + Window); + Within(ttl, Life - TimeSpan.FromSeconds(4) + Window); + } + + [Theory] + [InlineData(InstantCall.Set)] + [InlineData(InstantCall.ManySet)] + [InlineData(InstantCall.TryAdd)] + public async Task A_gate_that_closes_after_dispatch_stores_the_plain_value_until_the_callers_instant(InstantCall call) + { + var node = await _rig.NodeAsync(); + var (id, key) = NewKey(); + + var (stored, _) = await WithInstantAsync(node, call, key, id, Now + Life, seed: false, () => + { + _rig.Pipelines.FailFirst = () => + { + _rig.WriteGate.Close(); + return Task.CompletedTask; + }; + _rig.Pipelines.BeforeWrite = () => + { + _rig.Manual.Advance(TimeSpan.FromSeconds(3)); + return Task.CompletedTask; + }; + }); + + stored.Should().BeTrue(); + var (bytes, ttl) = await _rig.ReadRawAsync(id); + bytes.Should().Equal(JsonV); + Within(ttl, Life - TimeSpan.FromSeconds(3)); + } + + [Theory] + [InlineData(Generated.GetOrAdd)] + [InlineData(Generated.WithExpiration)] + [InlineData(Generated.Result)] + public async Task A_generated_store_whose_deadline_passed_before_the_send_stores_nothing(Generated joined) + { + var node = await _rig.NodeAsync(); + var (id, key) = NewKey(); + _rig.Pipelines.BeforeWrite = () => + { + _rig.Manual.Advance(TimeSpan.FromSeconds(20)); + _rig.Log.Take(); + return Task.CompletedTask; + }; + + var result = await JoinedResultAsync(node, joined, key); + + _rig.Log.Take().Select(c => c.Command).Should().NotContain("SET").And.NotContain("EVAL"); + result.Value.Should().Be("v"); + result.Expiration.Should().BeNull(); + (await _rig.ReadRawAsync(id)).Bytes.Should().BeNull(); + } + + // T1, WriteAnchor (W2, GI2): the fenced fill fixes its deadline before the fill, and a late reply moves neither the frame nor the report. + [Theory] + [InlineData(Generated.GetOrAdd, false)] + [InlineData(Generated.WithExpiration, false)] + [InlineData(Generated.Result, false)] + [InlineData(Generated.GetOrAdd, true)] + [InlineData(Generated.Result, true)] + public async Task A_fenced_generated_fill_reports_the_frame_expiration_however_late_the_reply_is(Generated joined, bool callersInstant) + { + var node = await _rig.NodeAsync(o => o.RemoveTombstone = TimeSpan.FromSeconds(1)); + var (id, key) = NewKey(); + var at = Now; + DateTimeOffset? instant = callersInstant ? at + Life : null; + _rig.Pipelines.AfterWrite = () => + { + _rig.Manual.Advance(TimeSpan.FromSeconds(5)); + return Task.CompletedTask; + }; + + var result = await JoinedResultAsync(node, joined, key, instant: instant); + + result.Expiration.Should().Be(at + Life); + var (bytes, _) = await _rig.ReadRawAsync(id); + Ms(Frame(bytes).Expiration).Should().Be(Ms(result.Expiration!.Value)); + } + + private static bool Fenced(InstantCall call) => call is InstantCall.GetOrAddFenced or InstantCall.ResultFenced or InstantCall.BatchGetOrAddFenced or InstantCall.TryAddOverTombstone; + + private static (string Id, CacheKey Key) NewKey(string? tag = null) + { + var id = Guid.NewGuid().ToString("N"); + return (id, tag is null ? $"w:{id}" : $"{{{tag}}}w:{id}"); + } + + private static EntryFrame Frame(byte[]? bytes) + { + bytes.Should().NotBeNull(); + EntryFrame.TryRead(bytes, out var frame).Should().BeTrue("the stored value is a frame"); + return frame; + } + + private static long Ms(DateTimeOffset at) => at.ToUnixTimeMilliseconds(); + + private static void Within(TimeSpan? ttl, TimeSpan expected, string because = "") + { + ttl.Should().NotBeNull(); + ttl!.Value.Should().BeLessThanOrEqualTo(expected, because).And.BeGreaterThan(expected - Slack, because); + } + + private static async Task WaitUntilAsync(Func condition) + { + using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(10)); + while (!condition()) + { + await Task.Yield(); + timeout.Token.ThrowIfCancellationRequested(); + } + } + + private async Task GenerateAsync(FrameWriteRig.Node node, Generated call, CacheKey key) + { + switch (call) + { + case Generated.GetOrAdd: + (await node.Cache.GetOrAddAsync(key, _ => Task.FromResult("v"), Windowed, Ct)).Should().Be("v"); + break; + case Generated.WithExpiration: + (await node.Cache.GetOrAddWithExpirationAsync(key, _ => Task.FromResult(new GeneratedValue("v")), Windowed, Ct)).Should().Be("v"); + break; + default: + (await node.Cache.GetOrAddResultAsync(key, _ => Task.FromResult("v"), Windowed, Ct)).Value.Should().Be("v"); + break; + } + } + + /// A result call alone, or one that joined the run of while its generator waited. + private async Task> JoinedResultAsync(FrameWriteRig.Node node, Generated joined, CacheKey key, CachePolicy? policy = null, DateTimeOffset? own = null, DateTimeOffset? instant = null, Action? during = null) + { + policy ??= Windowed; + var results = node.Cache; + if (joined == Generated.Result) + { + Task Generate(CancellationToken token) + { + during?.Invoke(); + return Task.FromResult("v"); + } + + return instant is { } callersInstant + ? await results.GetOrAddResultAsync(key, Generate, callersInstant, policy, Ct) + : await results.GetOrAddResultAsync(key, Generate, policy, Ct); + } + + var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var started = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + async Task PlainGenerator(CancellationToken token) + { + started.SetResult(); + await release.Task; + during?.Invoke(); + return "v"; + } + + async Task> Expiring(CancellationToken token) + { + started.SetResult(); + await release.Task; + during?.Invoke(); + return new GeneratedValue("v") { Expiration = own }; + } + + var run = joined == Generated.GetOrAdd + ? (instant is { } at + ? node.Cache.GetOrAddAsync(key, PlainGenerator, at, policy, Ct).AsTask() + : node.Cache.GetOrAddAsync(key, PlainGenerator, policy, Ct).AsTask()) + : node.Cache.GetOrAddWithExpirationAsync(key, Expiring, policy, Ct).AsTask(); + await started.Task; + var result = (instant is { } joinedAt + ? results.GetOrAddResultAsync(key, _ => Task.FromResult("unused"), joinedAt, policy, Ct) + : results.GetOrAddResultAsync(key, _ => Task.FromResult("unused"), policy, Ct)).AsTask(); + release.SetResult(); + await run; + return await result; + } + + /// The call with ; runs after the key is prepared, so the hooks it sets are the call's own. + private async Task<(bool Stored, DateTimeOffset? Reported)> WithInstantAsync(FrameWriteRig.Node node, InstantCall call, CacheKey key, string id, DateTimeOffset instant, bool seed, Action arm) + { + if (seed && call is InstantCall.Set or InstantCall.ManySet) + { + (await node.Cache.SetAsync(key, "old", TimeSpan.FromMinutes(5), null, Ct)).Should().BeTrue(); + } + + if (call == InstantCall.TryAddOverTombstone) + { + (await node.Cache.SetAsync(key, "old", TimeSpan.FromMinutes(5), null, Ct)).Should().BeTrue(); + (await node.Cache.RemoveAsync(key, Ct)).Should().BeTrue(); + } + + arm(); + var results = node.Cache; + switch (call) + { + case InstantCall.Set: + return (await node.Cache.SetAsync(key, "v", instant, Windowed, Ct), null); + case InstantCall.ManySet: + return (await node.Cache.SetAsync([new KeyValuePair(key, "v")], instant, Windowed, Ct), null); + case InstantCall.TryAdd or InstantCall.TryAddOverTombstone: + return (await node.Cache.TryAddAsync(key, "v", instant, Windowed, Ct), null); + case InstantCall.GetOrAdd or InstantCall.GetOrAddFenced: + (await node.Cache.GetOrAddAsync(key, _ => Task.FromResult("v"), instant, Windowed, Ct)).Should().Be("v"); + return (await HoldsFrameAsync(id), null); + case InstantCall.Result or InstantCall.ResultFenced: + var result = await results.GetOrAddResultAsync(key, _ => Task.FromResult("v"), instant, Windowed, Ct); + result.Value.Should().Be("v"); + return (result.Expiration is not null, result.Expiration); + default: + var batch = await node.Cache.GetOrAddAsync([new(key, "s")], (states, _) => Task.FromResult(states.Select(s => new KeyValuePair(s, "v")).ToArray()), instant, Windowed, Ct); + batch[0].Value.Should().Be("v"); + return (await HoldsFrameAsync(id), null); + } + } + + private async Task<(string? Value, DateTimeOffset? Reported)> FillAsync(FrameWriteRig.Node node, Fill fill, CacheKey key, DateTimeOffset instant, Action? during) + { + if (fill == Fill.GetOrAdd) + { + var value = await node.Cache.GetOrAddAsync( + key, + _ => + { + during?.Invoke(); + return Task.FromResult("v"); + }, + instant, + Windowed, + Ct); + return (value, null); + } + + var result = await JoinedResultAsync(node, fill == Fill.Result ? Generated.Result : Generated.GetOrAdd, key, instant: instant, during: during); + return (result.Value, result.Expiration); + } + + /// The expiration a result call reports after it joined a run of the generator's own expiration, which falls back to one of the plain forms. + private async Task PlainFormAsync(FrameWriteRig.Node node, Plain form, CacheKey key, DateTimeOffset? own) + { + Action? during = form == Plain.GateInGenerator ? _rig.WriteGate.Close : null; + if (form == Plain.GateBetweenAttempts) + { + _rig.Pipelines.FailFirst = () => + { + _rig.WriteGate.Close(); + return Task.CompletedTask; + }; + } + + return form == Plain.ReservedByte + ? await JoinedExpiringAsync(node, key, new GeneratedValue(Reserved) { Expiration = own }, during) + : await JoinedExpiringAsync(node, key, new GeneratedValue("v") { Expiration = own, SkipFailSafe = form == Plain.SkipFailSafe }, during); + } + + private async Task JoinedExpiringAsync(FrameWriteRig.Node node, CacheKey key, GeneratedValue generated, Action? during) + { + var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var started = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + async Task> Generate(CancellationToken token) + { + started.SetResult(); + await release.Task; + during?.Invoke(); + return generated; + } + + var run = node.Cache.GetOrAddWithExpirationAsync(key, Generate, Windowed, Ct).AsTask(); + await started.Task; + var result = node.Cache.GetOrAddResultAsync(key, _ => Task.FromResult(default), Windowed, Ct).AsTask(); + release.SetResult(); + await run; + return (await result).Expiration; + } + + private async Task HoldsFrameAsync(string id) => (await _rig.ReadRawAsync(id)).Bytes is { } bytes && EntryFrame.TryRead(bytes, out _); +} diff --git a/tests/UiPath.Caching.Tests/Redis/FormatRewriteTransactionTests.cs b/tests/UiPath.Caching.Tests/Redis/FormatRewriteTransactionTests.cs index 8f1d2e50b..cc4170916 100644 --- a/tests/UiPath.Caching.Tests/Redis/FormatRewriteTransactionTests.cs +++ b/tests/UiPath.Caching.Tests/Redis/FormatRewriteTransactionTests.cs @@ -68,4 +68,30 @@ public void The_condition_names_the_key_and_the_field_so_the_comparison_above_ca Condition.HashEqual("k", "a", Old).ToString().Should().NotBe(Condition.HashEqual("k", "b", Old).ToString()); Condition.HashEqual("k", "a", Old).ToString().Should().NotBe(Condition.HashExists("k", "a").ToString()); } + + [Fact] + public async Task The_form_is_asked_again_before_the_transaction() + { + byte[] frame = [0x0E, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 60, 0, 0, 0, (byte)'v']; + byte[] plain = [(byte)'v']; + var forms = new Queue<(RedisValue, TimeSpan)>([(frame, TimeSpan.FromSeconds(70)), (plain, TimeSpan.FromSeconds(9))]); + _db.ScriptEvaluateAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_ => throw new RedisServerException(RedisErrorKind.None, CommandFlags.None, "NOPERM this user has no permissions to run the 'eval' command")); + + var replaced = await FormatRewriteScripts.ReplaceStringAsync(_db, "k", Old, () => forms.Dequeue(), useScripts: true); + + replaced.Should().BeTrue(); + forms.Should().BeEmpty(); + _ = _transaction.Received(1).StringSetAsync("k", Arg.Is(v => ((byte[]?)v)!.SequenceEqual(plain)), TimeSpan.FromSeconds(9), When.Always, CommandFlags.DemandMaster); + } + + [Fact] + public async Task The_fixed_value_overload_sends_what_it_sent_before() + { + var replaced = await FormatRewriteScripts.ReplaceStringAsync(_db, "k", Old, Rewritten, () => TimeSpan.FromSeconds(5), useScripts: false); + + replaced.Should().BeTrue(); + _transaction.Received(1).AddCondition(Arg.Is(c => c.ToString() == Condition.StringEqual("k", Old).ToString())); + _ = _transaction.Received(1).StringSetAsync("k", Arg.Is(v => ((byte[]?)v)!.SequenceEqual(Rewritten)), TimeSpan.FromSeconds(5), When.Always, CommandFlags.DemandMaster); + } } diff --git a/tests/UiPath.Caching.Tests/Redis/FrameHarness.cs b/tests/UiPath.Caching.Tests/Redis/FrameHarness.cs index 843125ee1..eae75616f 100644 --- a/tests/UiPath.Caching.Tests/Redis/FrameHarness.cs +++ b/tests/UiPath.Caching.Tests/Redis/FrameHarness.cs @@ -89,23 +89,32 @@ public static async Task StartAsync(RedisContainerFixture fixture, 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. + /// Counts each read transaction once, along with each standalone value read and read script. public static int ReadSends(List commands) { var sends = 0; var inTransaction = false; + var transactionRead = false; foreach (var command in commands) { switch (command) { case "MULTI": inTransaction = true; + transactionRead = false; break; - case "EXEC": + case "EXEC" when inTransaction: + if (transactionRead) + { + sends++; + } + inTransaction = false; - sends++; break; - case "GET" or "MGET" or "EVAL_RO" or "EVALSHA_RO" when !inTransaction: + case "GET" or "MGET" or "EVAL_RO" or "EVALSHA_RO" when inTransaction: + transactionRead = true; + break; + case "GET" or "MGET" or "EVAL_RO" or "EVALSHA_RO": sends++; break; } @@ -114,9 +123,6 @@ public static int ReadSends(List commands) 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) diff --git a/tests/UiPath.Caching.Tests/Redis/FrameWriteRig.cs b/tests/UiPath.Caching.Tests/Redis/FrameWriteRig.cs new file mode 100644 index 000000000..2971d9a40 --- /dev/null +++ b/tests/UiPath.Caching.Tests/Redis/FrameWriteRig.cs @@ -0,0 +1,487 @@ +using System.Net; +using System.Reflection; +using System.Runtime.ExceptionServices; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging.Abstractions; +using StackExchange.Redis; +using UiPath.Caching.Config; +using UiPath.Caching.Locking; +using UiPath.Caching.Policies; +using UiPath.Caching.Redis; +using UiPath.Caching.Telemetry; +using UiPath.Caching.Tests.Fakes; + +namespace UiPath.Caching.Tests.Redis; + +/// +/// Nodes over a real Redis for the write side of the entry frame: a write gate a test closes, a write pipeline whose attempts a test can hold or +/// repeat, a serializer hook, a counting clock whose UTC reading and timestamp move apart, and the command log of the read tests. +/// +internal sealed class FrameWriteRig : IAsyncDisposable +{ + public static readonly TimeSpan Window = TimeSpan.FromSeconds(60); + + private readonly RedisContainerFixture _fixture; + private readonly string _run = Guid.NewGuid().ToString("N")[..10]; + private readonly List<(ServiceProvider Provider, ConnectionMultiplexer Mux)> _nodes = []; + private readonly List _layers = []; + private ConnectionMultiplexer? _admin; + + public FrameWriteRig(RedisContainerFixture fixture) + { + _fixture = fixture; + Manual = new ManualTimeProvider(fixture.TimeOrigin); + Clock = new CountingClock(Manual); + } + + public ManualTimeProvider Manual { get; } + + public CountingClock Clock { get; } + + public Gate WriteGate { get; } = new(); + + public HookedPipelines Pipelines { get; } = new(); + + public EntryFrameReadIntegrationTests.CommandLog Log { get; } = new(); + + /// Runs as each command is asked of the client, before it is sent, with the name the command log gives it. + public Action? OnCommand { get; set; } + + /// Runs inside the serializer, after the write took its deadline and before its send. + public Action? OnSerialize { get; set; } + + public IDatabase Db => _admin!.GetDatabase(); + + public static CachePolicy Windowed(TimeSpan? window = null, TimeSpan? distributed = null) => + new() { FailSafeEnabled = true, FailSafeDistributedEnabled = true, FailSafeDistributedMaxStaleAge = window ?? Window, DistributedExpiration = distributed }; + + public async Task NodeAsync(Action? configure = null, ISerializerProxy? serializer = null, bool metadata = true, Func? user = null, CachePolicy? defaultPolicy = null, Microsoft.Extensions.Logging.ILoggerProvider? logs = null) + { + Assert.SkipUnless(_fixture.Enabled, "Set RUN_REDIS_INTEGRATION_TESTS=1 (Docker required) to run."); + _admin ??= await ConnectionMultiplexer.ConnectAsync(_fixture.ConnectionString + ",allowAdmin=true"); + var connectionString = _fixture.ConnectionString; + if (user is not null) + { + Assert.SkipUnless(_fixture.SupportsAcl, "Needs ACL SETUSER, which this server does not allow."); + var name = $"it-fw-{Guid.NewGuid():N}"; + await RedisTestKeys.OnPrimariesAsync(_admin, "ACL", "SETUSER", name, "on", ">pw", "~*", "&*", "+@all", user(name)); + connectionString += $",user={name},password=pw"; + } + + var mux = await ConnectionMultiplexer.ConnectAsync(connectionString); + var connector = new Connector(mux, Log, this); + var services = new ServiceCollection() + .AddSingleton(Clock) + .AddSingleton(connector) + .AddSingleton(WriteGate) + .AddSingleton(Pipelines) + .AddSingleton>(serializer is null ? new HookedJsonSerializer(this) : new HookedSerializer(serializer, this)); + if (logs is not null) + { + services.AddLogging().AddSingleton(logs); + } + + var provider = services + .AddCaching( + b => + { + b.AddRedisConnection(o => o.ConnectionString = connectionString); + b.AddRedis(o => + { + o.ReadScriptsEnabled = false; + o.EntryMetadataEnabled = metadata; + o.FormatNegotiation.Mode = FormatNegotiationMode.Force; + o.CacheNullValues = true; + configure?.Invoke(o); + }); + b.AddInMemoryRedis(o => o.LocalMaxExpiration = TimeSpan.FromHours(2)); + }, + o => + { + o.AppShortName = "fw" + _run; + o.DefaultCachePolicy = defaultPolicy; + }) + .BuildServiceProvider(); + _nodes.Add((provider, mux)); + return new Node(provider, connector, this); + } + + /// The raw key a cache key landed on. + public RedisKey Raw(string id) => RedisTestKeys.Keys(_admin!, $"*{id}").Single(); + + public async Task<(byte[]? Bytes, TimeSpan? Ttl)> ReadRawAsync(string id) + { + var keys = RedisTestKeys.Keys(_admin!, $"*{id}").ToArray(); + if (keys.Length == 0) + { + return (null, null); + } + + return ((byte[]?)await Db.StringGetAsync(keys[0]), await Db.KeyTimeToLiveAsync(keys[0])); + } + + public async ValueTask DisposeAsync() + { + foreach (var layer in _layers) + { + layer.Dispose(); + } + + foreach (var (provider, mux) in _nodes) + { + await provider.DisposeAsync(); + await mux.DisposeAsync(); + } + + if (_admin is not null) + { + await _admin.DisposeAsync(); + } + } + + public sealed class Node(ServiceProvider provider, Connector connector, FrameWriteRig rig) + { + public ICacheFactory Factory => provider.GetRequiredService(); + + public RedisCache Redis => (RedisCache)Factory.CreateCache(KnownCacheProviderNames.Redis); + + public ICache Cache => Redis; + + public ICache Layered => Factory.CreateCache(KnownCacheProviderNames.InMemoryRedis); + + public Connector Connector => connector; + + public FrameWriteRig Rig => rig; + + /// A layered cache over on the rig's clock, with no broadcast. + public MultilayerCache LayeredOver(ICache inner, string name, ICacheKeyStrategy? keyStrategy = null) + { + var options = new InMemoryRedisCacheOptions { LocalMaxExpiration = TimeSpan.FromHours(2), CacheNullValues = true, CacheKeyStrategy = keyStrategy }; + var cache = new MultilayerCache( + name + rig._run, + inner, + provider.GetRequiredService(), + NullChangeTokenFactory.Instance, + NullTopicFactory.Instance, + NullCacheEventFactory.Instance, + NullTelemetryProvider.Instance, + options, + options, + provider.GetRequiredService>().Value, + NullDistributedLock.Instance, + provider.GetRequiredService(), + provider.GetRequiredService(), + NullLogger.Instance); + rig._layers.Add(cache); + return cache; + } + + /// The layered cache a test calls, over the shape of tiers it names, and the probes that count what reaches each tier below it. + public Stack StackOf(TierShape shape, ICacheKeyStrategy? keyStrategy = null, bool seam = true) + { + var bottom = new Probe(); + var middle = new Probe(); + switch (shape) + { + case TierShape.AppCache: + var app = Proxy(Redis, bottom); + return new Stack(LayeredOver(app, "app", keyStrategy), bottom, middle); + case TierShape.TwoLevels: + var inner = LayeredOver(Proxy(Redis, bottom), "inner"); + return new Stack(LayeredOver(Proxy(inner, middle), "outer", keyStrategy), bottom, middle); + default: + return seam + ? new Stack(LayeredOver(Proxy(Redis, bottom), "one", keyStrategy), bottom, middle) + : new Stack(LayeredOver(Proxy(Redis, bottom), "one", keyStrategy), bottom, middle); + } + } + + /// A proxy of over a target that offers every member of it through the interfaces it implements itself. + private static T Proxy(object target, Probe probe) + where T : class => + Forwarding.Wrap(System.Runtime.CompilerServices.Unsafe.As(target), probe.Before); + } + + public sealed class Gate : IFormatWriteGate + { + public Func? Holding { get; set; } + + public string? Hold() => Holding?.Invoke(); + + public void Close() => Holding = static () => "test"; + + public void Open() => Holding = null; + } + + /// A clock over the manual one that counts its readings and can run a hook after a UTC reading or between a timestamp and the next UTC reading. + public sealed class CountingClock(ManualTimeProvider inner) : TimeProvider + { + private int _timestamps; + private int _utcReadings; + + public int Timestamps => Volatile.Read(ref _timestamps); + + public int UtcReadings => Volatile.Read(ref _utcReadings); + + /// Runs once after the next UTC reading, which it is handed. + public Action? AfterUtc { get; set; } + + /// Runs once between the next timestamp and the UTC reading after it. + public Action? AfterTimestamp { get; set; } + + public List Readings { get; } = []; + + public override long TimestampFrequency => inner.TimestampFrequency; + + public override DateTimeOffset GetUtcNow() + { + var now = inner.GetUtcNow(); + Interlocked.Increment(ref _utcReadings); + lock (Readings) + { + Readings.Add('U'); + } + + if (AfterUtc is { } hook) + { + AfterUtc = null; + hook(now); + } + + return now; + } + + public override long GetTimestamp() + { + var stamp = inner.GetTimestamp(); + Interlocked.Increment(ref _timestamps); + lock (Readings) + { + Readings.Add('T'); + } + + if (AfterTimestamp is { } hook) + { + AfterTimestamp = null; + hook(); + } + + return stamp; + } + + public override ITimer CreateTimer(TimerCallback callback, object? state, TimeSpan dueTime, TimeSpan period) => inner.CreateTimer(callback, state, dueTime, period); + + public void Reset() + { + Volatile.Write(ref _timestamps, 0); + Volatile.Write(ref _utcReadings, 0); + lock (Readings) + { + Readings.Clear(); + } + } + } + + /// The write pipeline: a hook before each attempt, an optional first attempt that fails before its command, and a hook after the reply. + public sealed class HookedPipelines : IResiliencePipelineProvider + { + private int _attempts; + + /// Runs once before the next write attempt. + public Func? BeforeWrite { get; set; } + + /// Runs once instead of the next write attempt, which then fails before its command, and the pipeline tries again. + public Func? FailFirst { get; set; } + + /// Runs once after the next write reply, before the caller sees it. + public Func? AfterWrite { get; set; } + + public int Attempts => Volatile.Read(ref _attempts); + + public IResiliencePipeline Get(string? name) => name == ResiliencePipelineNames.Write ? new Write(this) : EmptyResiliencePipeline.Instance; + + private sealed class Write(HookedPipelines owner) : IResiliencePipeline + { + public ValueTask ExecuteAsync(Func> callback, TResult defaultValue, CancellationToken cancellationToken = default) => + ExecuteAsync(static (c, t) => c(t), callback, defaultValue, cancellationToken); + + public async ValueTask ExecuteAsync(Func> callback, TState state, TResult defaultValue, CancellationToken cancellationToken = default) + { + if (owner.FailFirst is { } fail) + { + owner.FailFirst = null; + Interlocked.Increment(ref owner._attempts); + await fail(); + } + + if (owner.BeforeWrite is { } before) + { + owner.BeforeWrite = null; + await before(); + } + + Interlocked.Increment(ref owner._attempts); + var result = await callback(state, cancellationToken); + if (owner.AfterWrite is { } after) + { + owner.AfterWrite = null; + await after(); + } + + return result; + } + } + } + + /// A connector over the test's connection that records commands and can keep its connect pending. + public sealed class Connector(IConnectionMultiplexer mux, EntryFrameReadIntegrationTests.CommandLog log, FrameWriteRig rig) : IRedisConnector + { + private readonly IDatabase _database = HookedRecorder.Wrap(mux.GetDatabase(), log, rig); + + 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. */ } + } + + /// Set to keep the next connect pending until it completes. + public TaskCompletionSource? PendingConnect { get; set; } + + public bool IsConnected => mux.IsConnected; + + public Version Version => mux.GetServer(mux.GetEndPoints()[0]).Version; + + public IDatabase Database => _database; + + public ISubscriber Subscriber => mux.GetSubscriber(); + + public ValueTask ConnectAsync(CancellationToken cancellationToken = default) + { + if (PendingConnect is { } pending) + { + PendingConnect = null; + return new ValueTask(pending.Task); + } + + return ValueTask.CompletedTask; + } + + public void ForceReconnect() + { + } + + public EndPoint[] GetEndPoints(bool configuredOnly = false) => mux.GetEndPoints(configuredOnly); + + public void Dispose() + { + } + } + + /// The command log of the read tests, with the rig's hook before each command. + public class HookedRecorder : DispatchProxy + { + private object _target = null!; + private EntryFrameReadIntegrationTests.CommandLog _log = null!; + private FrameWriteRig _rig = null!; + + public static T Wrap(T target, EntryFrameReadIntegrationTests.CommandLog log, FrameWriteRig rig) + where T : class + { + var proxy = Create(); + var recorder = (HookedRecorder)(object)proxy; + recorder._target = target; + recorder._log = log; + recorder._rig = rig; + 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); + _rig.OnCommand?.Invoke(command); + } + + object? result; + try + { + result = method.Invoke(_target, args); + } + catch (TargetInvocationException ex) when (ex.InnerException is not null) + { + ExceptionDispatchInfo.Throw(ex.InnerException); + throw; + } + + return result switch + { + ITransaction transaction => Wrap(transaction, _log, _rig), + IBatch batch => Wrap(batch, _log, _rig), + _ => 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", + "CreateBatch" => "BATCH", + "ExecuteAsync" when method.DeclaringType == typeof(ITransaction) => "EXEC", + "ScriptEvaluateReadOnlyAsync" => "EVAL_RO", + "ScriptEvaluateAsync" => "EVAL", + "StringSetAsync" => "SET", + "KeyExistsAsync" => "EXISTS", + _ => method.Name, + }; + } + + private sealed class HookedSerializer(ISerializerProxy inner, FrameWriteRig rig) : ISerializerProxy + { + public byte[]? Serialize(object? value) + { + rig.OnSerialize?.Invoke(); + return inner.Serialize(value); + } + + public T? Deserialize(byte[]? value) => inner.Deserialize(value); + + public bool TryDeserialize(string? value, out T? result) => inner.TryDeserialize(value, out result); + + public bool TryDeserialize(object? value, out T? result) => inner.TryDeserialize(value, out result); + } + + /// The hook over the default JSON proxy, marked header-free as the default is, so reads classify bytes as they do without the hook. + private sealed class HookedJsonSerializer(FrameWriteRig rig) : ISerializerProxy, IHeaderFreeSerializerProxy + { + private readonly SystemJsonByteSerializerProxy _inner = new(); + + public byte[]? Serialize(object? value) + { + rig.OnSerialize?.Invoke(); + return _inner.Serialize(value); + } + + public T? Deserialize(byte[]? value) => _inner.Deserialize(value); + + public bool TryDeserialize(string? value, out T? result) => _inner.TryDeserialize(value, out result); + + public bool TryDeserialize(object? value, out T? result) => _inner.TryDeserialize(value, out result); + } +} diff --git a/tests/UiPath.Caching.Tests/Redis/FrameWriteTiers.cs b/tests/UiPath.Caching.Tests/Redis/FrameWriteTiers.cs new file mode 100644 index 000000000..d340d7413 --- /dev/null +++ b/tests/UiPath.Caching.Tests/Redis/FrameWriteTiers.cs @@ -0,0 +1,66 @@ +using UiPath.Caching; + +namespace UiPath.Caching.Tests.Redis; + +/// The tiers a layered cache of a test sits over: Redis, a layered cache over Redis, or an application's own cache over Redis. +public enum TierShape +{ + Layered, + TwoLevels, + AppCache, +} + + +/// What a Redis tier offers a layered cache, behind a proxy that counts. +internal interface IWriteTier : ICache, IAnchoredTier, IStampedTier, IFencedFillTier, IFillManyTier, IMigrationCache +{ +} + +/// A tier that takes the anchor and has no migration seam of its own. +internal interface IBareTier : ICache, IAnchoredTier +{ +} + +/// A layered cache that a layered cache sits over. +internal interface ILayeredTier : ICache, IAnchoredTier +{ +} + +internal sealed record Stack(ICache Top, Probe Bottom, Probe Middle); + +/// Counts the TakesAnchor queries that reach a tier and runs a hook once, just before the first write reaches it. +internal sealed class Probe +{ + private static readonly HashSet Writes = ["SetAsync", "TryAddAsync", "TryFillAsync", "TryFillAfterAsync", "TryFillManyAsync", "SetIfChangedAsync", "WriteIfStampAsync", "WriteAsync"]; + + private Action? _onWrite; + private int _queries; + private int _writes; + + public int Queries => Volatile.Read(ref _queries); + + public int WritesSeen => Volatile.Read(ref _writes); + + /// Runs once, before the next write reaches the tier. + public Action? OnWrite + { + set => Volatile.Write(ref _onWrite, value); + } + + public (bool Handled, object? Result) Before(System.Reflection.MethodInfo method, object?[] args) + { + if (method.Name == "get_TakesAnchor") + { + Interlocked.Increment(ref _queries); + } + else if (Writes.Contains(method.Name)) + { + Interlocked.Increment(ref _writes); + Interlocked.Exchange(ref _onWrite, null)?.Invoke(); + } + + return (false, null); + } + + public void Reset() => Volatile.Write(ref _queries, 0); +}