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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions benchmarks/UiPath.Caching.Benchmarks/FakeRedisConnector.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,9 @@ public event EventHandler? OnReconnected
/// <summary>GETs sent so far.</summary>
public long Gets => Volatile.Read(ref _store.GetCount);

/// <summary>The key of the last write, so a benchmark can check that its measured calls sent none.</summary>
public RedisKey? LastSet => _store.LastSet;

/// <summary>Stores a hash for HGETALL to answer.</summary>
public void SeedHash(RedisKey key, HashEntry[] entries) => _store.Hashes[key] = entries;

Expand Down
Original file line number Diff line number Diff line change
@@ -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;

/// <summary>
/// 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.
/// </summary>
[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<string, string?>
{
{ "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<IRedisConnector>(_redis)));
await _host.StartAsync();
_cache = _host.Services.GetRequiredService<ICacheFactory>().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<string?> Hit() => _cache.GetOrAddAsync<string>(Key, static _ => Task.FromResult<string?>("generated"), _expiration, policy: null);

private (long Gets, StackExchange.Redis.RedisKey? LastSet) Commands() => (_redis.Gets, _redis.LastSet);
}
6 changes: 6 additions & 0 deletions src/UiPath.Caching.Abstractions/Config/CachePolicy.cs
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,12 @@ public sealed class CachePolicy
/// <summary>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. <see cref="FactoryTimeout"/> still cancels it. <c>null</c> or zero waits for the generator (default).</summary>
public TimeSpan? FailSafeTimeout { get; init; }

/// <summary>With <see cref="FailSafeEnabled"/>, writes keep an expired copy in Redis for <see cref="FailSafeDistributedMaxStaleAge"/>. Needs <c>RedisCacheOptions.EntryMetadataEnabled</c>. <c>null</c> inherits (default off).</summary>
public bool? FailSafeDistributedEnabled { get; init; }

/// <summary>How long past its logical expiration a value stays in Redis, in whole seconds from 1 second to <see cref="uint.MaxValue"/> seconds. <c>null</c> inherits, then takes <see cref="FailSafeMaxStaleAge"/>, then 1 day.</summary>
public TimeSpan? FailSafeDistributedMaxStaleAge { get; init; }

/// <summary>
/// Lock settings. Merged field-level against the default policy's <see cref="LockProfile"/> —
/// a named policy can override individual fields (e.g. <see cref="LockProfile.LocalSingleFlightEnabled"/>)
Expand Down
4 changes: 4 additions & 0 deletions src/UiPath.Caching.Abstractions/PublicAPI.Unshipped.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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?
Expand Down
5 changes: 5 additions & 0 deletions src/UiPath.Caching.Migration/RegistrationValidator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,11 @@ public static IReadOnlyList<string> 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.");
Expand Down
37 changes: 37 additions & 0 deletions src/UiPath.Caching/AnchoredOptions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
namespace UiPath.Caching;

/// <summary>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 <see cref="CacheEntryOptions"/> does not grow (WA6, C7).</summary>
internal struct AnchoredOptions(CacheEntryOptions options, WriteAnchor anchor) : ILayeredOptions<AnchoredOptions>
{
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<string, string?>? Metadata
{
readonly get => _options.Metadata;
set => _options.Metadata = value;
}

public readonly AnchoredOptions WithToken(CancellationToken token) => new(_options.WithToken(token), anchor);

/// <summary>The same entry under another deadline, with the anchor of that deadline.</summary>
public readonly AnchoredOptions WithExpiration(DateTimeOffset expiration)
{
var changed = _options;
changed.Expiration = expiration;
return new(changed, anchor);
}
}
4 changes: 4 additions & 0 deletions src/UiPath.Caching/CacheEntryBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,4 +41,8 @@ public CacheEntryOptions BuildEntryOptions<T>(CacheKey cacheKey, DateTimeOffset?
Expiration = _clock.ToDateTimeOffset(expiration),
};
}

/// <summary><see cref="BuildEntryOptions{T}(CacheKey, DateTimeOffset?, CancellationToken)"/> for a deadline that already has its anchor: the options and that anchor, unchanged. It takes no anchor and reads no clock (WA4 (b)).</summary>
public (CacheEntryOptions Options, WriteAnchor Anchor) BuildEntryOptions<T>(CacheKey cacheKey, DateTimeOffset expiration, WriteAnchor anchor, CancellationToken token) =>
(BuildEntryOptions<T>(cacheKey, expiration, token), anchor);
}
30 changes: 30 additions & 0 deletions src/UiPath.Caching/Config/CachePolicyFactoryValidator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,28 @@ public static void ValidateAgainstEffectiveDefault(
}
}

/// <summary>Refuses a default or named policy with <see cref="CachePolicy.FailSafeDistributedEnabled"/> on a Redis tier without entry metadata, which cannot write the window.</summary>
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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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.");
}
2 changes: 2 additions & 0 deletions src/UiPath.Caching/Config/CachePolicyMerger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
9 changes: 7 additions & 2 deletions src/UiPath.Caching/Config/CachingBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -58,13 +58,18 @@ internal void Complete()
ServiceDescriptor.Singleton<IValidateOptions<CacheOptions>, CacheKeyCasingSeeder>());
Services.TryAddSingleton<ISerializerProxy<byte[]>>(sp => new SystemJsonByteSerializerProxy(sp.GetService<JsonSerializerOptions>()));
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<IHostedService, FormatNegotiationService>());
}

if (hasRegisteredFormats)
{
Services.TryAddSingleton(sp => ValueMigration.Create(sp)!);
}

Services.TryAddSingleton<IResiliencePipelineProvider>(EmptyResiliencePipelineProvider.Instance);
Services.TryAddSingleton<IChangeTokenFactory>(NullChangeTokenFactory.Instance);
Services.TryAddSingleton<ITopicFactory>(NullTopicFactory.Instance);
Expand Down
3 changes: 3 additions & 0 deletions src/UiPath.Caching/Config/RedisCollectionExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Microsoft.Extensions.Hosting;
using UiPath.Caching.Negotiation;
using UiPath.Caching.Telemetry;

namespace UiPath.Caching.Config;
Expand All @@ -22,6 +23,8 @@ public static ICachingBuilder AddRedis(this ICachingBuilder builder, Action<Red
{
return builder;
}
builder.Services.TryAddSingleton<IEntryFrameWrites>(sp =>
sp.GetRequiredService<FormatNegotiation>().FrameWrites(sp.GetRequiredService<IOptions<RedisCacheOptions>>().Value));
builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton<ICacheProvider, RedisCacheProvider>(RedisCacheProvider.Create));
return builder;
}
Expand Down
35 changes: 34 additions & 1 deletion src/UiPath.Caching/FailSafeLifetimeWarning.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

namespace UiPath.Caching;

/// <summary>Warns once per policy that enables fail-safe on a cache with no size limit, where nothing caps how many values are kept.</summary>
/// <summary>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.</summary>
internal static partial class FailSafeLifetimeWarning
{
internal const string DefaultPolicyName = "(default)";
Expand All @@ -23,6 +23,28 @@ public static void Log(ILogger logger, string provider, ICachePolicyFactory poli
}
}

/// <summary>Logs one warning for the default policy and each named policy that keeps a stale window in Redis, naming the window.</summary>
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));
}
}

/// <summary>The stale window a policy keeps in Redis: the distributed age, then the local one, then the default, in whole seconds from 1 to <see cref="uint.MaxValue"/>; zero without both switches.</summary>
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)
Expand All @@ -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);
}
24 changes: 24 additions & 0 deletions src/UiPath.Caching/IAnchoredTier.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
namespace UiPath.Caching;

/// <summary>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).</summary>
internal interface IAnchoredTier
{
/// <summary>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.</summary>
bool TakesAnchor { get; }

ValueTask<bool> SetAsync<T>(CacheKey cacheKey, T? value, DateTimeOffset expiration, WriteAnchor anchor, CachePolicy? policy, CancellationToken token);

ValueTask<bool> SetAsync<T>(KeyValuePair<CacheKey, T?>[] keyValues, DateTimeOffset expiration, WriteAnchor anchor, CachePolicy? policy, CancellationToken token);

ValueTask<bool> TryAddAsync<T>(CacheKey cacheKey, T? value, DateTimeOffset expiration, WriteAnchor anchor, CachePolicy? policy, CancellationToken token);

ValueTask<FillResult<T>> TryFillAsync<T>(CacheKey cacheKey, T? value, DateTimeOffset expiration, WriteAnchor anchor, CachePolicy? policy, CancellationToken token);

ValueTask<FillResult<T>> TryFillAfterAsync<T>(CacheKey cacheKey, T? value, DateTimeOffset expiration, WriteAnchor anchor, TimeSpan generatorElapsed, CachePolicy? policy, CancellationToken token);

ValueTask<FillResult<T>[]> TryFillManyAsync<T>(KeyValuePair<CacheKey, T?>[] entries, DateTimeOffset expiration, WriteAnchor anchor, CachePolicy? policy, CancellationToken token, TimeSpan? generatorElapsed);

ValueTask<ChangeResult<T>> SetIfChangedAsync<T>(CacheKey cacheKey, T? value, IEqualityComparer<T> comparer, DateTimeOffset expiration, WriteAnchor anchor, CachePolicy? policy, CancellationToken token);

ValueTask<StampedWrite> WriteIfStampAsync<T>(CacheKey cacheKey, T? value, DateTimeOffset expiration, WriteAnchor anchor, CachePolicy? policy, object? stamp, CancellationToken token);
}
9 changes: 9 additions & 0 deletions src/UiPath.Caching/ILayeredShape.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,15 @@ internal interface ILayeredShape<TValue, TOptions, TWrite>

TOptions BuildOptions(CacheKey cacheKey, DateTimeOffset expiration, CancellationToken token);

/// <summary>The options under a deadline made here from <paramref name="duration"/> and the jitter, as a rehydrate makes its fresh deadline; a shape that anchors its writes takes the anchor there.</summary>
TOptions BuildJittered(CacheKey cacheKey, TimeSpan duration, TimeSpan? jitter, CancellationToken token);

/// <summary>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.</summary>
TOptions BuildOwn(CacheKey cacheKey, DateTimeOffset expiration, CancellationToken token);

/// <summary>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.</summary>
ValueTask? RehydrateAnchored(CacheKey originalCacheKey, DateTimeOffset entryExpiration, Func<CancellationToken, Task<TValue>> generator, CachePolicy policy, TimeSpan duration, TimeSpan? jitter, RehydrateRun run, CancellationToken ct, RehydrateOverride? shaped);

ValueTask<ICacheEntry<TValue>> ReadInnerAsync(TOptions options, CachePolicy policy);

/// <summary>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 <paramref name="stamp"/> when the shape can compare against it.</summary>
Expand Down
Loading
Loading