Skip to content
Merged
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
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/)
- **Router registrations are checked, can be excluded, and come with a conformance check.** Building the router fails when its library stack would change what the application's own client sees: the stack's Redis options are set by the router alone, so their checks (key strategy factory, `CacheKeyStrategy`, `EntryFactory`, `RemoveUnreadable`, `ReadFrom`) catch a library default that changes, and the `CacheOptions` it inherits from the router's section must not set a `DefaultCachePolicy` serializer policy. The startup log lists the value of every library option of the stack. `RouterBuilder.Exclude(cacheName, reason)` lists a cache that stays on the application's client (a lock, or a map cache the library cannot match): the startup log names it, and `IRouter.Get` for it fails with the reason. `RouterConformance.CheckAsync(services, cacheName, samples)` is the parity check for an application's CI, against a test Redis: what the source writes the library reads and the reverse, both clients write the same bytes and the same deadline, and the report names samples by position only. See [Router](docs/how-to/router.md).
- **Router conditional create, version-named caches and cached nulls.** `IRouter.Get<T>` returns `ICache<T>`. On the library path, `TryAddAsync` returns true only when the create is confirmed. An unknown create keeps the key pending. The router exposes cache-wide clears through `IRouter.ClearAsync`. `ISourceCache` gains `TryAddAsync` (returning `AddResult`), and `IMigrationCache` gains `TryCreateAsync` (`SET NX` with the deadline on Redis). `RouterCacheRegistration.Version` names a cache whose older client puts a type version in its keys: its events and topic use `{name}@{version}`, so peers on another version do not hear them. `RouterCacheRegistration.CacheNulls` reads a null the source stores as a hit on both paths and in the local tier; a null from a factory is still not stored. See [Router](docs/how-to/router.md).
- **The router hosts a bridge to the older client's invalidation channel.** `RouterBuilder.UseChannelBridge(IChannelBridge)` takes the application's adapter. Every key write, delete and create the router commits, and every clear, is published on it as a `BridgeMessage` (`Key`, `Clear`) carrying the router's identity, on either path and in `BypassLibrary`, since the bridge needs no started library. A received `Key` message evicts that key's local copy, a `Clear` drops the cache's local copies and a `Tag` drops every cache's, since the router keeps no tags; a message carrying the router's own identity is ignored, and nothing received is published again, so no echo can start. A publish runs off the caller's thread and is cancelled at the source timeout, at most 16 run at once by default (more are dropped; `PublishAsync` must not block), a throwing `Subscribe` is retried in the background, and every failure is counted (`bridge`), never thrown; the local cap bounds how long a peer serves its copy. The adapter for a real older client is the application's. See [Router](docs/how-to/router.md).
- **A router group can be pinned to the library path, and a switch is durable.** `RouterBuilder.UsePinWhen` pins groups (polled about once a second): a pinned group ignores bypass and the group predicate and never falls to the source, answering unavailable instead. A node advertises `pin=<group>` only after calls that started on the old path have ended, with an `ap` token naming its application so applications sharing one node hash do not count each other. The switch state of a group is a durable Redis key, `{prefix}mg:{app:group}:sw`, recorded by a script when a format write needs it and only while every live node's acknowledgement record is unchanged, and a withdrawal is recorded in the same step as the read that confirms it (the pin needs scripts); a switched group stays on the library or unavailable through a restart, a failed library start, a throwing predicate and bypass, which changes the router's rule that a throwing predicate means the source. State is read before the first call and refreshed; an unknown state fails a group that is not pinned closed. `IFormatWriteGate` is a new seam: a registered gate holds non-JSON value writes while it returns a reason, as part of the existing hold, including on a custom serializer proxy, and a gate that closes, even briefly, restarts the hold. The router's gate opens only when every group is pinned. Counter path reasons `pin` and `pin_state_unknown`. See [Router](docs/how-to/router.md).
- **A router group can be pinned to the library path, and a switch is durable.** `RouterBuilder.UsePinWhen` pins groups (polled about once a second): a pinned group ignores bypass and the group predicate and never falls to the source, answering unavailable instead. A node advertises `pin=<group>` only after calls that started on the old path have ended, with an `ap` token naming its application so applications sharing one node hash do not count each other. The switch state of a group is a durable Redis key, `{prefix}mg:{app:group}:sw`, recorded by a script when a format write needs it and only while every live node's acknowledgement record is unchanged, and a withdrawal is recorded in the same step as the read that confirms it (the pin needs scripts); a switched group stays on the library or unavailable through a restart, a failed library start, a throwing predicate and bypass, which changes the router's rule that a throwing predicate means the source. State is read before the first call and refreshed; an unknown state fails a group that is not pinned closed. Non-JSON value writes stay held, as part of the existing format hold and on a custom serializer proxy too, until every router group is pinned; a gate that closes, even briefly, restarts the hold. Counter path reasons `pin` and `pin_state_unknown`. See [Router](docs/how-to/router.md).
- **The stream maintainer removes the consumer groups of departed nodes.** A group is named for its node, so the maintainer checks the node list once per pass (only when a stream has a group with consumers) and quarantines, then deletes, a group whose node left (`left=1`), whose entry is older than the gone window, or, on Redis 7.2 and later in a fleet that advertises, whose entry was pruned and whose consumers have all been idle past the gone window and the quarantine. Everything else is kept, as is every group while the node list cannot be read. Metric `Caching.Stats.DepartedGroupDeleted` by reason. Before this, groups of crashed nodes stayed on quiet streams for good. See [Broadcast](docs/how-to/broadcast.md).
- **An inventory by reason and a bounded sweep of stored values.** `RedisCacheProvider.CountFormatsByReasonAsync(keyPattern, token)` (or `(keyPattern, group, token)`, which sets the `group` tag) returns a `FormatInventoryReport` (`ByFormat`, `ByReason`, `Scanned`) whose reasons are `format_json`, `format_<name>`, `format_unknown`, `format_frame`, `format_frame_windowed`, `empty`, `oversize`, `no_ttl` and `hash_sampled`; each string costs a `PTTL` and a headerless one a `STRLEN`, so it is for an operator and not for a request. `SweepFormatsAsync<T>(keyPattern, options, token)` rewrites strings stored in another format into the default policy's write format in place, with the conversion of `MigrateOnRead`: lossless check, compare-and-set that keeps the exact TTL, transaction when scripts are refused, no origin call and no event, so a writer or a delete that comes meanwhile wins and no key is created. It takes its own `FormatSweepOptions.RatePerSecond`, shares the one-minute claim window and byte budget of `MigrateOnRead`, asks the node list again for each key (the first refusal ends the pass), and a `Budget` and a `Cursor` make it resumable (`FormatSweepReport.NextCursor`, `Completed`). It leaves the empty, `default(T)`, oversize and lossy values and reports each under its reason; hashes are never swept (only the inventory reports them, as `hash_sampled`). Metrics `cache.format.sweep{outcome,group}` and `cache.format.inventory{reason,group}`. Every inventory, `CountFormatsAsync` and `CountFormatsByKeyAsync` included, now counts an entry frame as `frame`, and one with a stale window as `frame_windowed` too, so `frame_windowed` overlaps `frame` and the counts can add up to more than the keys; a frame is never `oversize`; the sweep leaves frames as they are and counts them in `FormatSweepReport.Framed`. See [concepts](docs/concepts.md#counting-by-reason-and-sweeping-what-reads-do-not-reach).
- **`IHeaderFreeSerializerProxy`** marks a custom byte serializer proxy whose values never start with a format header byte. Such a proxy is treated as the default JSON proxy is: reads tell its values from a registered format by the first byte under every policy, the node advertises the formats it reads instead of `nosniff`, a write the format negotiation holds back falls back to the proxy's bytes, and `MigrateOnRead` converts its values when the proxy writes the value back byte for byte. The router marks its envelope this way, and an envelope write whose first byte would read as a header fails with `InvalidOperationException`.
Expand Down
2 changes: 1 addition & 1 deletion docs/how-to/router.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ A call is decided by the first of these that applies, and the router logs this o
- **Switch state.** Once something asks for a format write that needs it (the format negotiation asks the router's gate) and every group of the router is pinned and every live node of the application has the pin, the router records the group as switched in Redis, `{prefix}mg:{app:group}:sw` (no expiry; the prefix is `RedisCacheOptions.KeyPrefix` when `UseSourceConnection` is used, and otherwise the library connection adds it), and only then opens the gate. A switched group is pinned whatever the setting says, so a restart, a library that fails to start, a throwing predicate or `BypassLibrary` leave it on the library or unavailable. A pin alone records nothing, and a recorded switch is not undone.
- **State read.** The state is read before the first call is admitted (at most the start bound) and then every `AdvertiseInterval`, and again after every mode change. A group that is not pinned may take the source only while a read succeeded within three intervals; otherwise, and when the value is not one this version knows, the group is answered unavailable. A call that has fallen from the library asks again before it takes the source, and so does a write that waited on a factory or a lock before it goes to the source, so a state that went stale, a pin that applied or a switch that was recorded meanwhile stops it: the write goes to the library or is not sent.
- **Lost key.** A node that saw the switch writes the key again. A node that restarts with the key missing treats the group as switched when a live router entry of its application reports `sw=<group>`; with no node left that remembers it, a missing key reads as not switched, so keep the pin setting on for a switched group.
- **Format gate.** MessagePack writes stay held, through the format negotiation's own hold, until every group that asks for MessagePack is pinned (with `UseWriteFormatWhen`; without it, every group of the router), every live router entry of the application has `pin=<group>`, every library advertisement has a router entry, this node's own entry is in the list and the switch is recorded against their acknowledgement records. A node without the pin that joins, an incomplete node list, a failed state write or a node list that cannot be read closes it, and a gate that closes even briefly restarts the hold; an unreadable node list keeps the last decision for `FormatNegotiation.MaxViewAge`. The gate applies to the router's envelope too: while it is closed the envelope writes the old format. `IFormatWriteGate` is the seam the library exposes for this.
- **Format gate.** MessagePack writes stay held, through the format negotiation's own hold, until every group that asks for MessagePack is pinned (with `UseWriteFormatWhen`; without it, every group of the router), every live router entry of the application has `pin=<group>`, every library advertisement has a router entry, this node's own entry is in the list and the switch is recorded against their acknowledgement records. A node without the pin that joins, an incomplete node list, a failed state write or a node list that cannot be read closes it, and a gate that closes even briefly restarts the hold; an unreadable node list keeps the last decision for `FormatNegotiation.MaxViewAge`. The gate applies to the router's envelope too: while it is closed the envelope writes the old format.
- **Applications on one hash.** The router stack's node list key has no application part, so applications on one Redis share `caching:nodes`. Entries are told apart by the `ap` token of the router entry (a library advertisement by the router entry of its node), and the state key and gate count only the application's own. An entry that names no application (an older build, or a router with no `AppShortName`) cannot be attributed: it holds the gate and never approves it; two applications with the same `AppShortName` on one Redis are not told apart.
- Group names of a router with a pin setting hold none of `+ @ = { }`. `Clear` still clears through the source client, so a switched group's `Clear` still needs a working source client.

Expand Down
11 changes: 5 additions & 6 deletions src/UiPath.Caching.Migration/AimdMoveRate.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ namespace UiPath.Caching.Migration;
internal sealed class AimdMoveRate : IMoveRate
{
private readonly IKeyMoveHealthSource _health;
private readonly IMoverMemory? _memory;
private readonly LastGoodOptions _options;
private readonly TimeProvider _time;
private readonly long _origin;
Expand All @@ -25,10 +24,10 @@ internal sealed class AimdMoveRate : IMoveRate
private TimeSpan _globalNext;
private string? _lastPause;

public AimdMoveRate(IKeyMoveHealthSource health, IMoverMemory? memory, IOptionsMonitor<KeyMoveMoverOptions> options, TimeProvider time, MoverLatency? latency = null)
public AimdMoveRate(IKeyMoveHealthSource health, IOptionsMonitor<KeyMoveMoverOptions> options, TimeProvider time, MoverLatency? latency = null)
{
_health = health ?? throw new ArgumentNullException(nameof(health));
(_memory, _options, _time, _latency) = (memory, LastGoodOptions.Over(options), time ?? throw new ArgumentNullException(nameof(time)), latency);
(_options, _time, _latency) = (LastGoodOptions.Over(options), time ?? throw new ArgumentNullException(nameof(time)), latency);
_origin = _time.GetTimestamp();
}

Expand Down Expand Up @@ -189,7 +188,7 @@ internal static AimdMoveRate Compose(Func<CancellationToken, Task<IReadOnlyList<
var shared = LastGoodOptions.Over(options);
var watch = new RedisInfoWatch(read, shared, time);
var latency = new MoverLatency(time);
return new AimdMoveRate(new RedisInfoHealthSource(watch, latency, shared), watch, shared, time, latency);
return new AimdMoveRate(new RedisInfoHealthSource(watch, latency, shared), shared, time, latency);
}

private static Call<T> Start<T>(Func<CancellationToken, ValueTask<T>> work, CancellationToken cancellationToken)
Expand Down Expand Up @@ -284,11 +283,11 @@ private async ValueTask RefreshAsync(KeyMoveMoverOptions o, CancellationToken ca
string? memory = null;

// A failed health read is red already; a second read that would wait for the same outage adds nothing.
if (_memory is not null && !failed)
if (!failed)
{
try
{
memory = await BoundedAsync(_memoryFlight, _memory.PauseReasonAsync, o.HealthTimeout, cancellationToken).ConfigureAwait(false);
memory = await BoundedAsync(_memoryFlight, _health.PauseReasonAsync, o.HealthTimeout, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (!cancellationToken.IsCancellationRequested && ex is not OutOfMemoryException)
{
Expand Down
7 changes: 0 additions & 7 deletions src/UiPath.Caching.Migration/IMoverMemory.cs

This file was deleted.

7 changes: 0 additions & 7 deletions src/UiPath.Caching.Migration/IRouterClear.cs

This file was deleted.

2 changes: 2 additions & 0 deletions src/UiPath.Caching.Migration/IRouterParticipant.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ internal interface IAttachment : IDisposable
/// <summary>Clears this node's copies of the cache and announces a cache-level invalidation, for what a bounded stop could not settle.</summary>
Task InvalidateAsync();

ValueTask ClearAsync(CancellationToken cancellationToken = default);

/// <summary>Takes the library parts without using them yet.</summary>
IAttachment Prepare(LibraryParts library);
}
3 changes: 3 additions & 0 deletions src/UiPath.Caching.Migration/RedisInfoHealthSource.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ internal sealed class RedisInfoHealthSource(RedisInfoWatch watch, MoverLatency l
{
private readonly LastGoodOptions _options = LastGoodOptions.Over(monitor);

public async ValueTask<string?> PauseReasonAsync(CancellationToken cancellationToken) =>
(await watch.ReadAsync(cancellationToken).ConfigureAwait(false)).MemoryPause;

public async ValueTask<KeyMoveHealth> GetHealthAsync(CancellationToken cancellationToken)
{
var o = _options.CurrentValue;
Expand Down
4 changes: 1 addition & 3 deletions src/UiPath.Caching.Migration/RedisInfoWatch.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
namespace UiPath.Caching.Migration;

/// <summary>Reads <c>INFO</c> of every primary and replica, turns it into CPU and lag, and runs the memory rules, once per interval.</summary>
internal sealed class RedisInfoWatch : IMoverMemory
internal sealed class RedisInfoWatch
{
// The most INFO calls one reading has in flight.
private const int MaxConcurrentReads = 4;
Expand Down Expand Up @@ -84,8 +84,6 @@ public async ValueTask<InfoReading> ReadAsync(CancellationToken cancellationToke
}
}

public async ValueTask<string?> PauseReasonAsync(CancellationToken cancellationToken) =>
(await ReadAsync(cancellationToken).ConfigureAwait(false)).MemoryPause;

private static async Task<IReadOnlyList<NodeInfo>> ReadUnitsAsync(IScanUnits units, CancellationToken cancellationToken)
{
Expand Down
2 changes: 1 addition & 1 deletion src/UiPath.Caching.Migration/RoutedCacheOfT.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

namespace UiPath.Caching.Migration;

internal sealed partial class RoutedCache<T> : IRouterParticipant, IRouterClear, ICache<T>, IDisposable
internal sealed partial class RoutedCache<T> : IRouterParticipant, ICache<T>, IDisposable
where T : class
{
/// <summary>A command that changed nothing (a create that found the key held): neither retried on the other client nor settled.</summary>
Expand Down
2 changes: 1 addition & 1 deletion src/UiPath.Caching.Migration/RoutedHashCacheOfT.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

namespace UiPath.Caching.Migration;

internal sealed partial class RoutedHashCache<T> : IRouterParticipant, IRouterClear, IHashCache<T>, ISpanKeyHashCache<T>, IDisposable
internal sealed partial class RoutedHashCache<T> : IRouterParticipant, IHashCache<T>, ISpanKeyHashCache<T>, IDisposable
where T : class
{
private static readonly CacheEntryFactory Entries = new();
Expand Down
2 changes: 1 addition & 1 deletion src/UiPath.Caching.Migration/Router.cs
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ public async Task ClearAsync(string cacheName, CancellationToken cancellationTok
throw new KeyNotFoundException($"No cache named '{cacheName}' is registered with the router.");
}

await ((IRouterClear)entry.Cache).ClearAsync(cancellationToken).ConfigureAwait(false);
await ((IRouterParticipant)entry.Cache).ClearAsync(cancellationToken).ConfigureAwait(false);
}

public Task EnterBypassAsync(CancellationToken cancellationToken = default)
Expand Down
Loading