diff --git a/docs/Execute.md b/docs/Execute.md
index b20fd28146..37adfb174b 100644
--- a/docs/Execute.md
+++ b/docs/Execute.md
@@ -93,7 +93,7 @@ using RespResult result = db.ExecuteResp("GET", new RedisKeyOrValue[] { (RedisKe
// ...
```
-Keys passed this way participate in cluster slot routing and `KeyPrefixed` key-prefixing, just like a key argument to any built-in command. `ExecuteResp` recognizes known command names (applying the same command-map renaming/disabling rules as everything else) and falls back to treating the command as opaque only if it isn't recognized.
+Keys passed this way participate in cluster slot routing and `WithKeyPrefix` key-prefixing, just like a key argument to any built-in command. `ExecuteResp` recognizes known command names (applying the same command-map renaming/disabling rules as everything else) and falls back to treating the command as opaque only if it isn't recognized.
The `new RedisKeyOrValue[]` above is fine for occasional use, but allocates on every call - see [Leasing the argument buffer](#leasing-the-argument-buffer) below for the low-allocation form once you're on a hot path.
diff --git a/docs/rules/SER352.md b/docs/rules/SER352.md
deleted file mode 100644
index b4c0dd7be0..0000000000
--- a/docs/rules/SER352.md
+++ /dev/null
@@ -1,35 +0,0 @@
-# SER352: generated database members are not implemented
-
-A type marked `[AutoDatabase(WarnIfIncomplete = true)]` still has members that the generator supplied, and
-those members throw rather than doing anything. The count is how many.
-
-This is a **transition tripwire**, not a code-quality rule. `[AutoDatabase]` fills in every member of
-`IDatabase`/`IDatabaseAsync` that the type does not implement itself, funnelling them through the type's own
-`Execute`/`ExecuteAsync`. For most users of the attribute those generated members genuinely work - they
-forward to an inner database - and this rule is off for them. It is opt-in precisely because "generated" and
-"unimplemented" are only the same thing for a type whose funnel throws, which is the shape of a type being
-migrated to a new implementation one command at a time.
-
-## Fixing it
-
-Implement the member on the type. That is the whole fix, and it is self-maintaining: the generator skips
-whatever the class declares itself, so the member stops being generated and the count goes down. When the
-count reaches zero the warning disappears on its own.
-
-There is nothing to add to a list, and no list to forget to update - which is the reason the generated half
-exists at all.
-
-## Why Release only
-
-The inner development loop is exactly when the type is *expected* to be incomplete, and a warning that fires
-on every build during the work it is describing is a warning people learn to skip past. It is reported when
-the `DEBUG` preprocessor symbol is absent, which is how the SDK's own `Release` configuration is defined.
-
-## Suppressing
-
-Do not suppress it to make it quiet - it is counting something real, and something that will throw in front
-of a user.
-
-Do consider `SER352 ` while the migration is in progress: in a
-build with `TreatWarningsAsErrors` this rule is otherwise fatal, which blocks the very work it is tracking.
-Removing that line once the migration is close is what makes shipping an incomplete type impossible.
diff --git a/docs/rules/index.md b/docs/rules/index.md
index 1bb6322ee5..bb44ab6072 100644
--- a/docs/rules/index.md
+++ b/docs/rules/index.md
@@ -51,7 +51,6 @@ Unlike everything under [Usage](#usage), these describe code that does not do wh
- [SER350](SER350) - language version too low for generated code
- [SER351](SER351) - a `[Resp]` declaration the fragment generator cannot implement
-- [SER352](SER352) - generated database members that are not implemented and will throw
## When these rules stay quiet
diff --git a/eng/StackExchange.Redis.Build/AnalyzerReleases.Unshipped.md b/eng/StackExchange.Redis.Build/AnalyzerReleases.Unshipped.md
index e0733f289d..1e5213fe00 100644
--- a/eng/StackExchange.Redis.Build/AnalyzerReleases.Unshipped.md
+++ b/eng/StackExchange.Redis.Build/AnalyzerReleases.Unshipped.md
@@ -18,4 +18,3 @@ SER308 | Usage | Warning | QueuedResultAnalyzer: calling the library's own
SER309 | Usage | Warning | RespInterpolationAnalyzer: literal text in a RESP interpolated command is parsed and encoded on every call, where a fragment or resolved command is prepared once
SER310 | Usage | Info | CancellationAnalyzer: a redis call that cannot honour the CancellationToken parameter its enclosing method accepts
SER351 | Build | Warning | RespFragmentGenerator: a [Resp] declaration that cannot be implemented, which would otherwise be skipped silently
-SER352 | Build | Warning | AutoDatabaseGenerator: an [AutoDatabase(WarnIfIncomplete = true)] type still has generated members that only throw; Release builds only
diff --git a/eng/StackExchange.Redis.Build/AutoDatabaseGenerator.cs b/eng/StackExchange.Redis.Build/AutoDatabaseGenerator.cs
deleted file mode 100644
index 1f3913e2a6..0000000000
--- a/eng/StackExchange.Redis.Build/AutoDatabaseGenerator.cs
+++ /dev/null
@@ -1,722 +0,0 @@
-using System;
-using System.Collections.Immutable;
-using System.Reflection.Metadata.Ecma335;
-using System.Text;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-
-// readable names for the info we gather; kept as tuples (+ BasicArray) so they have
-// value equality and play nicely with incremental generator caching.
-using ParamInfo = (string Name, string Type, Microsoft.CodeAnalysis.RefKind RefKind, bool IsParams, bool IsOptional, bool HasDefault, string? Default);
-using MethodInfo = (string Name, string ReturnType, StackExchange.Redis.Build.BasicArray<(string Name, string Type, Microsoft.CodeAnalysis.RefKind RefKind, bool IsParams, bool IsOptional, bool HasDefault, string? Default)> Parameters, StackExchange.Redis.Build.BasicArray TypeArgs);
-using InterfaceInfo = (string Name, string Namespace, StackExchange.Redis.Build.AutoDatabaseGenerator.KnownInterfaces KnownType, StackExchange.Redis.Build.BasicArray<(string Name, string ReturnType, StackExchange.Redis.Build.BasicArray<(string Name, string Type, Microsoft.CodeAnalysis.RefKind RefKind, bool IsParams, bool IsOptional, bool HasDefault, string? Default)> Parameters, StackExchange.Redis.Build.BasicArray TypeArgs)> Methods);
-using ClassInfo = (string Name, string Namespace, StackExchange.Redis.Build.AutoDatabaseGenerator.KnownInterfaces Interfaces, bool IsMutator, bool Replays, StackExchange.Redis.Build.BasicArray Declared, bool WarnIfIncomplete);
-
-namespace StackExchange.Redis.Build;
-
-[Generator(LanguageNames.CSharp)]
-public class AutoDatabaseGenerator : IIncrementalGenerator
-{
- public void Initialize(IncrementalGeneratorInitializationContext ctx)
- {
- var interfaces = ctx.SyntaxProvider
- .CreateSyntaxProvider(
- static (node, _) => node is InterfaceDeclarationSyntax decl && FastIndexFilter(decl), ExtractInterfaceMethods)
- .Where(pair => pair.Name is { Length: > 0 })
- .Collect();
-
- var classes = ctx.SyntaxProvider
- .CreateSyntaxProvider(
- static (node, _) => node is ClassDeclarationSyntax decl && FastClassFilter(decl), ExtractClasses)
- .Where(pair => pair.Name is { Length: > 0 })
- .Collect();
-
- // Release is "no DEBUG symbol", which is what the SDK's own configuration does; a generator has no
- // other reliable view of $(Configuration) without the project opting the property in.
- var isRelease = ctx.ParseOptionsProvider.Select(
- static (options, _) => !options.PreprocessorSymbolNames.Contains("DEBUG"));
-
- ctx.RegisterSourceOutput(
- interfaces.Combine(classes).Combine(isRelease),
- static (ctx, content) => Generate(ctx, content.Left.Left, content.Left.Right, content.Right));
- }
-
- ///
- /// The only assembly this generator has anything to say about.
- ///
- ///
- /// This is repo-internal machinery, but it now ships as an analyzer inside the StackExchange.Redis package
- /// (for AsciiHashGenerator 's benefit), so it is loaded by every consumer. It can never generate
- /// anything useful for them - the semantic checks below reject anything that isn't our own
- /// StackExchange.Redis declaration - so short-circuit on the assembly name first, and skip even the
- /// semantic-model query for the consumers who happen to declare a type called IDatabase .
- ///
- private const string OwningAssembly = "StackExchange.Redis";
-
- static KnownInterfaces Identify(string type) => type switch
- {
- "IDatabase" => KnownInterfaces.IDatabase,
- "IDatabaseAsync" => KnownInterfaces.IDatabaseAsync,
- "IRedis" => KnownInterfaces.IRedis,
- "IRedisAsync" => KnownInterfaces.IRedisAsync,
- _ => KnownInterfaces.None,
- };
-
- private static bool FastIndexFilter(InterfaceDeclarationSyntax decl) // limit to IDatabase, IDatabaseAsync
- => Identify(decl.Identifier.ValueText) is not 0;
-
- private static bool FastClassFilter(ClassDeclarationSyntax decl) // limit to IDatabase, IDatabaseAsync
- => decl.AttributeLists.Any(x => x.Attributes.Any(x => x.Name.ToString() is "AutoDatabase" or "AutoDatabaseAttribute"));
-
- // does this auto-database rewrite keys/channels? if not, the captured-args structs need no mapping members
- private static bool IsMutatorInterface(INamedTypeSymbol symbol) =>
- symbol is
- {
- TypeKind: TypeKind.Interface,
- Name: "IRedisArgsMutator",
- ContainingType: null,
- ContainingNamespace:
- {
- Name: "Redis",
- ContainingNamespace:
- {
- Name: "StackExchange",
- ContainingNamespace.IsGlobalNamespace: true
- }
- }
- };
-
- private static bool IsOurInterface(INamedTypeSymbol symbol) =>
- symbol is
- {
- TypeKind: TypeKind.Interface,
- Name: "IDatabase" or "IDatabaseAsync" or "IRedis" or "IRedisAsync",
- ContainingType: null,
- ContainingNamespace:
- {
- Name: "Redis",
- ContainingNamespace:
- {
- Name: "StackExchange",
- ContainingNamespace.IsGlobalNamespace: true
- }
- }
- };
-
- private static InterfaceInfo ExtractInterfaceMethods(GeneratorSyntaxContext context, CancellationToken cancel)
- {
- if (context.SemanticModel.Compilation.AssemblyName is not OwningAssembly) return default;
-
- // note: we deliberately do NOT interpret anything here - just capture the raw shape of every
- // method (name, return type, and per-parameter name/type/modifiers/optionality/default) so that
- // later passes have everything they might need.
- if (context.SemanticModel.GetDeclaredSymbol(context.Node, cancel) is not INamedTypeSymbol iface
- || !IsOurInterface(iface))
- {
- return default;
- }
-
- var knownType = Identify(iface.Name);
- if (knownType is KnownInterfaces.None) return default;
-
- var methods = new List();
- foreach (var member in iface.GetMembers())
- {
- cancel.ThrowIfCancellationRequested();
- if (member is not IMethodSymbol { MethodKind: MethodKind.Ordinary } method) continue;
-
- var parameters = BasicArray.From(method.Parameters, static p => (
- Name: p.Name,
- Type: p.Type.ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageFormat),
- RefKind: p.RefKind,
- IsParams: p.IsParams,
- IsOptional: p.IsOptional,
- HasDefault: p.HasExplicitDefaultValue,
- Default: p.HasExplicitDefaultValue ? FormatDefault(p.ExplicitDefaultValue) : null));
-
- BasicArray typeArgs = default;
- if (method.IsGenericMethod)
- {
- typeArgs = BasicArray.From(method.TypeParameters, p => p.Name);
- }
- methods.Add((
- Name: method.Name,
- ReturnType: method.ReturnType.ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageFormat),
- Parameters: parameters,
- TypeArgs: typeArgs));
- }
-
- var ns = iface.ContainingNamespace.ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageFormat);
- return (iface.Name, ns, knownType, BasicArray.From(methods));
- }
-
- private ClassInfo ExtractClasses(GeneratorSyntaxContext context, CancellationToken cancel)
- {
- if (context.SemanticModel.Compilation.AssemblyName is not OwningAssembly) return default;
-
- // note: we deliberately do NOT interpret anything here - just capture the raw shape of every
- // method (name, return type, and per-parameter name/type/modifiers/optionality/default) so that
- // later passes have everything they might need.
- if (context.SemanticModel.GetDeclaredSymbol(context.Node, cancel) is not INamedTypeSymbol cls
- || !HasAutoDatabaseAttrib(cls))
- {
- return default;
- }
-
- static bool HasAutoDatabaseAttrib(INamedTypeSymbol symbol)
- {
- var attribs = symbol.GetAttributes();
- foreach (var attrib in attribs)
- {
- if (attrib.AttributeClass is
- {
- Name: "AutoDatabaseAttribute",
- ContainingType: null,
- ContainingNamespace:
- {
- Name: "Redis",
- ContainingNamespace:
- {
- Name: "StackExchange",
- ContainingNamespace.IsGlobalNamespace: true
- }
- }
- })
- {
- return true;
- }
- }
-
- return false;
- }
-
- // AllInterfaces, not Interfaces: IBatch and ITransaction ARE IDatabaseAsync (IBatch : IDatabaseAsync,
- // ITransaction : IBatch), so a class declaring one of those implements every async command member
- // and wants exactly the same generated set. Matching only the directly-declared name generated
- // nothing for them, silently - the class compiled, and the members it had not written were simply
- // absent rather than throwing. The union below is idempotent, so a class that declares IDatabase
- // directly is unaffected by also seeing it here transitively.
- KnownInterfaces known = 0;
- foreach (var iFace in cls.AllInterfaces)
- {
- if (IsOurInterface(iFace))
- {
- switch (iFace.Name)
- {
- case "IDatabase":
- known |= KnownInterfaces.IDatabase | KnownInterfaces.IDatabaseAsync |
- KnownInterfaces.IRedis | KnownInterfaces.IRedisAsync;
- break;
- case "IDatabaseAsync":
- known |= KnownInterfaces.IDatabaseAsync | KnownInterfaces.IRedisAsync;
- break;
- case "IRedis":
- known |= KnownInterfaces.IRedis | KnownInterfaces.IRedisAsync;
- break;
- case "IRedisAsync":
- known |= KnownInterfaces.IRedisAsync;
- break;
- }
- }
- }
-
- if (known is KnownInterfaces.None) return default; // nothing to do!
-
- // AllInterfaces (not Interfaces) so an inherited/explicit implementation still counts
- bool isMutator = false;
- foreach (var iFace in cls.AllInterfaces)
- {
- if (IsMutatorInterface(iFace))
- {
- isMutator = true;
- break;
- }
- }
-
- // [AutoDatabase(Replays = true)] - the owning database can invoke a captured operation more than
- // once, so captured Memory arguments have to be copies rather than the caller's own buffer
- bool replays = false, warnIfIncomplete = false;
- foreach (var attrib in cls.GetAttributes())
- {
- if (attrib.AttributeClass?.Name is not ("AutoDatabaseAttribute" or "AutoDatabase")) continue;
- foreach (var named in attrib.NamedArguments)
- {
- if (named.Key == "Replays" && named.Value.Value is bool b) replays = b;
- if (named.Key == "WarnIfIncomplete" && named.Value.Value is bool w) warnIfIncomplete = w;
- }
- }
-
- // What the class already implements by hand, so generation can stand back. The generator emits
- // EXPLICIT interface implementations, which means a hand-written member does NOT collide - both
- // compile, and interface dispatch silently prefers the generated one. So this is a correctness
- // check, not a convenience: without it, a partial that implements StringGet for real would still
- // see IDatabase.StringGet route to the funnel.
- //
- // Other partials are ordinary source and therefore visible here; this generator's own output is
- // not part of the compilation it sees, so there is nothing to exclude.
- var declared = new List();
- foreach (var member in cls.GetMembers())
- {
- cancel.ThrowIfCancellationRequested();
- if (member is not IMethodSymbol { MethodKind: MethodKind.Ordinary or MethodKind.ExplicitInterfaceImplementation } method) continue;
- declared.Add(SignatureKey(method));
- }
-
- var ns = cls.ContainingNamespace.ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageFormat);
- return (cls.Name, ns, known, isMutator, replays, BasicArray.From(declared), warnIfIncomplete);
- }
-
- ///
- /// Name plus parameter types, formatted exactly as the interface side formats them so the two can be
- /// compared as strings.
- ///
- ///
- /// An explicit implementation's Name is the fully-qualified Namespace.IFace.Member , so
- /// the implemented member's own name is used instead - a hand-written explicit implementation and a
- /// hand-written public one mean the same thing here: "do not generate this".
- ///
- private static string SignatureKey(IMethodSymbol method)
- {
- var name = method.ExplicitInterfaceImplementations.Length > 0
- ? method.ExplicitInterfaceImplementations[0].Name
- : method.Name;
-
- var sb = new StringBuilder(name).Append('(');
- bool first = true;
- foreach (var p in method.Parameters)
- {
- if (!first) sb.Append(',');
- first = false;
- sb.Append(p.Type.ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageFormat));
- }
-
- return sb.Append(')').ToString();
- }
-
- /// The same key, from the interface-side shape.
- private static string SignatureKey(MethodInfo method)
- {
- var sb = new StringBuilder(method.Name).Append('(');
- bool first = true;
- foreach (var p in method.Parameters.Span)
- {
- if (!first) sb.Append(',');
- first = false;
- sb.Append(p.Type);
- }
-
- return sb.Append(')').ToString();
- }
-
- [Flags]
- internal enum KnownInterfaces
- {
- None = 0,
- IDatabase = 1,
- IDatabaseAsync = 2,
- IRedis = 4,
- IRedisAsync = 8,
- }
-
- // methods that don't fit the capture-and-replay shape are left for the caller to implement manually:
- // - generic methods (open type args can't be captured into a concrete state struct)
- // - the Wait family (synchronization over caller-supplied Tasks, not server calls)
- // - IsConnected: a synchronous status probe that IDatabaseAsync carries; it would route through the
- // sync Execute funnel, which an async-only database (e.g. RetryDatabase) doesn't provide - and a
- // connection check shouldn't be retried in any case
- // - IdentifyEndpoint / IdentifyEndpointAsync: a routing lookup ("which endpoint serves this key"),
- // not a replayable server command; wrappers want their own behaviour here (e.g. a connection-group
- // resolving against the currently-active member and returning null when there is none)
- // - streaming returns (IEnumerable / IAsyncEnumerable) whose execution is deferred
- // Memory/ReadOnlyMemory arguments still belong to the caller once the call returns; a database
- // that replays has to capture a copy. Matched on the open generic prefix so a nullable or an array *of*
- // them - neither of which is the caller's own buffer in the same way - does not match.
- private static bool IsMemoryArg(string type)
- => type.StartsWith("System.ReadOnlyMemory<", StringComparison.Ordinal)
- || type.StartsWith("System.Memory<", StringComparison.Ordinal);
-
- // the element type, for the ArrayPool we rent the copy from
- private static string MemoryElement(string type)
- => type.Substring(type.IndexOf('<') + 1, type.Length - type.IndexOf('<') - 2);
-
- private static bool SkipMethod(MethodInfo method)
- => !method.TypeArgs.IsEmpty
- || method.Name.Contains("Wait")
- || method.Name == "IsConnected"
- || method.Name.Contains("IdentifyEndpoint")
- // transaction/batch factories are not server round-trips and cannot be captured-and-replayed;
- // the (few) databases that offer them implement them by hand
- || method.Name == "CreateTransaction"
- || method.Name == "CreateBatch"
- || method.ReturnType.StartsWith("System.Collections.Generic.IEnumerable<", StringComparison.Ordinal)
- || method.ReturnType.StartsWith("System.Collections.Generic.IAsyncEnumerable<", StringComparison.Ordinal);
-
- private const string TaskType = "System.Threading.Tasks.Task";
-
- // Task / Task returns route through ExecuteAsync (its own retry policy); everything else
- // uses Execute.
- private static bool IsAsync(string returnType)
- => returnType.StartsWith(TaskType, StringComparison.Ordinal);
-
- // the retry machinery unwraps the Task and only ever sees the inner result, so key/channel
- // (un)mapping must be decided on T, not Task; this strips the Task<...> wrapper from an async
- // return type. A bare (non-generic) Task has no result and is returned unchanged (as is any
- // non-async return type), which is harmless since neither matches NeedsMap.
- private static string StripTask(string returnType)
- => IsAsync(returnType) && returnType.StartsWith(TaskType + "<", StringComparison.Ordinal)
- ? returnType.Substring(TaskType.Length + 1, returnType.Length - TaskType.Length - 2)
- : returnType;
-
- private static string FormatDefault(object? value) => value switch
- {
- null => "null",
- string s => $"\"{s}\"",
- bool b => b ? "true" : "false",
- _ => value.ToString() ?? "null",
- };
-
- private static void Generate(SourceProductionContext ctx, ImmutableArray interfaces, ImmutableArray classes, bool isRelease)
- {
- if (interfaces.IsDefaultOrEmpty | classes.IsDefaultOrEmpty) return; // nothing to do
-
- // each interface is declared across several partial files, so we get one (identical) entry per
- // partial declaration; structural equality lets us collapse those down to one per interface.
- var iKeyed = new Dictionary();
- foreach (var t in interfaces)
- {
- if (t.KnownType is KnownInterfaces.None) continue;
- if (!iKeyed.ContainsKey(t.KnownType)) iKeyed.Add(t.KnownType, t);
- }
-
- var sb = new StringBuilder();
- var writer = new CodeWriter(sb);
- writer.NewLine().Append("// ");
- writer.NewLine().Append("// AutoDatabaseGenerator - explicit interface implementations that funnel every");
- writer.NewLine().Append("// call through Execute(state, projection), capturing the arguments in a generated");
- writer.NewLine().Append("// state struct (one per unique parameter-type signature) to avoid per-call closures.");
- writer.NewLine().Append("#nullable enable"); // this needs to be explicit for code-gen
- writer.NewLine();
- foreach (var cls in classes.Distinct())
- {
- if (!string.IsNullOrWhiteSpace(cls.Namespace))
- {
- writer.NewLine().Append("namespace ").Append(cls.Namespace).NewLine().Append("{").Indent();
- }
-
- // what this class implements by hand, and therefore must NOT have generated for it
- var declared = new HashSet(StringComparer.Ordinal);
- foreach (var signature in cls.Declared) declared.Add(signature);
-
- // how many members this class did NOT implement, for the SER352 tripwire below
- int generated = 0;
-
- // unique parameter-type signatures encountered while emitting this class's methods;
- // keyed on the '|'-joined parameter types so distinct methods with the same shape share
- // one state struct. tupleDefs[i] holds a representative parameter list for _tuple{i}.
- var tupleIndex = new Dictionary();
- var tupleDefs = new List>();
-
- // every unique key/channel-bearing result type across all shapes; a single shared
- // singleton (emitted after the tuples) implements IRedisArgsResult for each, so
- // tuples expose unmap dispatch via UnMapper without ever being cast to an interface
- var allReturns = new HashSet();
-
- bool isFirst = true;
- writer.NewLine().Append("partial class ").Append(cls.Name);
- AppendInterfaceDeclaration(KnownInterfaces.IDatabase);
- AppendInterfaceDeclaration(KnownInterfaces.IDatabaseAsync);
- AppendInterfaceDeclaration(KnownInterfaces.IRedis);
- AppendInterfaceDeclaration(KnownInterfaces.IRedisAsync);
- writer.NewLine().Append("{").Indent();
- AppendInterfaceMethods(KnownInterfaces.IDatabase);
- AppendInterfaceMethods(KnownInterfaces.IDatabaseAsync);
- AppendInterfaceMethods(KnownInterfaces.IRedis);
- AppendInterfaceMethods(KnownInterfaces.IRedisAsync);
- AppendTupleTypes();
-
- // The tripwire: a type opted into WarnIfIncomplete is mid-transition, and every member still
- // generated for it is one the class has not taken over. Release only, so the inner loop is
- // quiet and the noise arrives exactly when someone is preparing something that ships.
- if (isRelease && cls.WarnIfIncomplete && generated > 0)
- {
- var fqn = string.IsNullOrWhiteSpace(cls.Namespace) ? cls.Name : cls.Namespace + "." + cls.Name;
- ctx.ReportDiagnostic(Diagnostic.Create(Diagnostics.AutoDatabaseIncomplete, Location.None, generated, fqn));
- }
-
- writer.Outdent().NewLine().Append("}");
-
- if (!string.IsNullOrWhiteSpace(cls.Namespace))
- {
- writer.Outdent().NewLine().Append("}");
- }
- writer.NewLine();
-
-
- void AppendInterfaceDeclaration(KnownInterfaces knownType)
- {
- if ((cls.Interfaces & knownType) is 0 | !iKeyed.TryGetValue(knownType, out var iType)) return;
- writer.Append(isFirst ? " : " : ", ").Append("global::")
- .Append(iType.Namespace).Append('.') .Append(iType.Name);
- isFirst = false;
- }
-
- void AppendInterfaceMethods(KnownInterfaces knownType)
- {
- if ((cls.Interfaces & knownType) is 0 | !iKeyed.TryGetValue(knownType, out var iType)) return;
- foreach (var method in iType.Methods)
- {
- if (SkipMethod(method)) continue; // wonky by nature - left for the caller to implement manually
- if (declared.Contains(SignatureKey(method))) continue; // the class implements this itself
- generated++;
-
- writer.NewLine().Append(method.ReturnType).Append(" global::")
- .Append(iType.Namespace).Append('.').Append(iType.Name).Append('.').Append(method.Name).Append("(");
- bool firstParam = true;
- foreach (var p in method.Parameters.Span)
- {
- if (firstParam) firstParam = false;
- else writer.Append(", ");
- writer.Append(p.Type).Append(" ").Append(p.Name);
- }
- writer.Append(')').Indent().NewLine();
-
- // async methods route to ExecuteAsync (its own retry policy); everything else uses
- // Execute. The state struct is shared regardless of return type - keyed on parameter
- // types only - so e.g. ArraySet and ArraySetAsync land on the same _tupleN. The return
- // type is Task-stripped so unmapping is keyed on the inner result the retry machinery
- // actually sees, not the Task wrapper.
- bool isAsync = IsAsync(method.ReturnType);
- var simpleResult = StripTask(method.ReturnType);
- bool needsMap = NeedsMap(simpleResult);
- if (needsMap) allReturns.Add(simpleResult);
- int tuple = GetTupleIndex(method.Parameters, needsMap);
- writer.Append(isAsync ? "=> ExecuteAsync(new _tuple" : "=> Execute(new _tuple").Append(tuple).Append("(");
- firstParam = true;
- foreach (var p in method.Parameters.Span)
- {
- if (firstParam) firstParam = false;
- else writer.Append(", ");
- writer.Append(p.Name);
- }
- // the funnels take the state by readonly-ref (see AutoDatabase{Sync|Async}Operation) to avoid
- // copying the larger state structs; a lambda only binds to an `in` parameter if it says so,
- // hence the explicit modifier (C# 14 allows it without also naming the type)
- writer.Append("), static (in state, inner) => inner.").Append(method.Name).Append("(");
- for (int i = 0; i < method.Parameters.Length; i++)
- {
- if (i != 0) writer.Append(", ");
- writer.Append("state.Arg").Append(i);
- }
- writer.Append("));").Outdent().NewLine();
- }
- }
-
- static string GetTupleKey(BasicArray parameters)
- {
- var keyBuilder = new StringBuilder();
- foreach (var p in parameters.Span)
- {
- keyBuilder.Append(p.Type).Append('|'); // types-only key; no ref/out on this surface, so type is sufficient
- }
-
- return keyBuilder.ToString();
- }
-
- bool TupleNeedsMap(BasicArray parameters) =>
- tupleIndex.TryGetValue(GetTupleKey(parameters), out var found) && found.NeedsMap;
-
- int GetTupleIndex(BasicArray parameters, bool needsMap)
- {
- var key = GetTupleKey(parameters);
- int index;
- if (tupleIndex.TryGetValue(key, out var found))
- {
- index = found.Index;
- if (needsMap && !found.NeedsMap)
- {
- found.NeedsMap = true;
- tupleIndex[key] = found;
- }
- }
- else
- {
- index = tupleDefs.Count;
- tupleIndex.Add(key, (index, needsMap));
- tupleDefs.Add(parameters);
- }
-
- return index;
- }
-
- const string CommandFlagsType = "StackExchange.Redis.CommandFlags";
- const string RedisKeyType = "StackExchange.Redis.RedisKey";
- const string RedisChannelType = "StackExchange.Redis.RedisChannel";
- // types that carry key(s) internally without "RedisKey" in their name, so the
- // substring check below won't catch them; they rely on a Map extension method
- const string StreamPositionType = "StackExchange.Redis.StreamPosition";
- // the Execute/ExecuteAsync escape hatch boxes keys/channels inside a loosely-typed
- // arg list; these route through a Map extension that unboxes and rewrites matches
- const string ScriptArgArrayType = "object[]";
- const string ScriptArgCollectionType = "System.Collections.Generic.ICollection";
-
- static bool NeedsMap(string name) =>
- name.IndexOf(RedisKeyType, StringComparison.Ordinal) >= 0
- || name.IndexOf(RedisChannelType, StringComparison.Ordinal) >= 0
- || name.IndexOf(StreamPositionType, StringComparison.Ordinal) >= 0
- || name == ScriptArgArrayType
- || name == ScriptArgCollectionType
- || name.IndexOf("ListPopResult", StringComparison.Ordinal) >= 0
- || name.IndexOf("SortedSetPopResult", StringComparison.Ordinal) >= 0
- || name == ScriptArgCollectionType + "?";
-
- void AppendTupleTypes()
- {
- for (int i = 0; i < tupleDefs.Count; i++)
- {
- var raw = tupleDefs[i];
- bool needsMap = TupleNeedsMap(raw);
- var parameters = raw.Span;
-
- // key/channel-bearing fields are mutable only when something can rewrite them (i.e. the
- // owning database is an IRedisArgsMutator); otherwise every field is readonly
- // a non-mutator's captured args never change after capture, so the struct itself can be
- // readonly - which also guarantees no defensive copies when read through an `in` ref
- writer.NewLine().NewLine().Append(cls.IsMutator ? "private struct _tuple" : "private readonly struct _tuple").Append(i).Append("(");
- for (int p = 0; p < parameters.Length; p++)
- {
- if (p != 0) writer.Append(", ");
- writer.Append(parameters[p].Type).Append(" arg").Append(p);
- }
-
- // captured args are a plain struct unless the owning database rewrites keys, in which
- // case the mapping members - and the interface that carries them - are emitted below.
- // A captured CommandFlags is surfaced through IFlaggedRedisArgs regardless, so that a
- // funnel holding an opaque TState can still see fire-and-forget; the two compose.
- writer.Append(")");
- int flagsArg = -1;
- for (int p = 0; p < parameters.Length; p++)
- {
- // suffix rather than substring: this must not match a nullable, an array, or a
- // container *of* flags, none of which the funnel could read as a plain value
- if (parameters[p].Type.EndsWith(CommandFlagsType, StringComparison.Ordinal))
- {
- flagsArg = p;
- break;
- }
- }
-
- bool firstBase = true;
- if (cls.IsMutator)
- {
- writer.Append(" : global::StackExchange.Redis.IMappableRedisArgs");
- firstBase = false;
- }
-
- if (flagsArg >= 0)
- {
- writer.Append(firstBase ? " : " : ", ").Append("global::StackExchange.Redis.IFlaggedRedisArgs");
- firstBase = false;
- }
-
- // a replaying funnel constrains its TState to IDisposable so it can give cloned
- // arguments back; every one of its captures implements it, most as a no-op
- if (cls.Replays)
- {
- writer.Append(firstBase ? " : " : ", ").Append("global::System.IDisposable");
- }
- writer.NewLine().Append("{").Indent();
- for (int p = 0; p < parameters.Length; p++)
- {
- var clone = cls.Replays && IsMemoryArg(parameters[p].Type);
- writer.NewLine().Append("public ").Append(cls.IsMutator && NeedsMap(parameters[p].Type) ? "" : "readonly ").Append(parameters[p].Type)
- .Append(" Arg").Append(p).Append(" = ")
- .Append(clone ? "global::StackExchange.Redis.CapturedArgs.Clone(arg" : "arg").Append(p).Append(clone ? ");" : ";");
- }
-
- if (flagsArg >= 0)
- {
- // explicit implementation, so it cannot collide with a captured argument's own name;
- // readonly only on a mutator's struct, since a readonly struct's members already are
- writer.NewLine().Append(cls.IsMutator ? "readonly " : "")
- .Append("global::StackExchange.Redis.CommandFlags global::StackExchange.Redis.IFlaggedRedisArgs.Flags => Arg")
- .Append(flagsArg).Append(";");
- }
-
- if (cls.Replays)
- {
- // emitted even when there is nothing to give back: the funnel's TState constraint
- // needs every capture to satisfy it, and an empty one inlines away
- writer.NewLine().Append(cls.IsMutator ? "readonly " : "").Append("public void Dispose()").NewLine().Append("{").Indent();
- for (int p = 0; p < parameters.Length; p++)
- {
- if (!IsMemoryArg(parameters[p].Type)) continue;
- writer.NewLine().Append("global::StackExchange.Redis.CapturedArgs.Release(in Arg").Append(p).Append(");");
- }
- writer.Outdent().NewLine().Append("}");
- }
-
- if (!cls.IsMutator)
- {
- // nothing rewrites keys here, so there is no Map/UnMapper to emit at all
- writer.Outdent().NewLine().Append("}");
- continue;
- }
-
- // Map rewrites each scalar key/channel field directly, and defers container or
- // loosely-typed fields to a matching Map extension method
- writer.NewLine().Append("public void Map(global::StackExchange.Redis.IRedisArgsMutator mutator)")
- .NewLine().Append("{").Indent();
- for (int p = 0; p < parameters.Length; p++)
- {
- if (NeedsMap(parameters[p].Type))
- {
- // key/channel-bearing container (or the loosely-typed script arg list); it
- // is the library's job to ensure a suitable Map extension method exists
- writer.NewLine().Append("Arg").Append(p).Append(" = mutator.Map(Arg").Append(p).Append(");");
- }
- }
- writer.Outdent().NewLine().Append("}");
-
- // tuples with key/channel-bearing results point UnMapper at the shared singleton
- // (which knows how to unmap every such result type); the rest return null so the
- // Execute helper skips unmapping entirely - and neither path boxes the struct
- writer.NewLine().Append("public readonly object? UnMapper => ")
- .Append(needsMap ? "_UnMapper.Instance;" : "null;");
-
- writer.Outdent().NewLine().Append("}");
- }
-
- if (cls.IsMutator && allReturns.Count is not 0)
- {
- // sorted for deterministic (cache-stable) output
- var ordered = new List(allReturns);
- ordered.Sort(StringComparer.Ordinal);
-
- writer.NewLine().NewLine().Append("private sealed class _UnMapper").Indent();
- bool firstIface = true;
- foreach (var retType in ordered)
- {
- writer.NewLine().Append(firstIface ? ": " : ", ")
- .Append("global::StackExchange.Redis.IRedisArgsResult<").Append(retType).Append(">");
- firstIface = false;
- }
- writer.Outdent().NewLine().Append("{").Indent();
- writer.NewLine().Append("public static readonly _UnMapper Instance = new();");
- foreach (var retType in ordered)
- {
- writer.NewLine().NewLine().Append(retType).Append(' ')
- .Append("global::StackExchange.Redis.IRedisArgsResult<")
- .Append(retType)
- .Append(">.UnMap(global::StackExchange.Redis.IRedisArgsMutator mutator, ")
- .Append(retType).Append(" value)")
- .Indent().NewLine().Append("=> mutator.UnMap(value);").Outdent();
- }
- writer.Outdent().NewLine().Append("}");
- }
- }
- }
- writer.NewLine();
-
- ctx.AddSource("AutoDatabase.generated.cs", sb.ToString());
- }
-}
diff --git a/eng/StackExchange.Redis.Build/Diagnostics.cs b/eng/StackExchange.Redis.Build/Diagnostics.cs
index 949388f43c..06a0828a76 100644
--- a/eng/StackExchange.Redis.Build/Diagnostics.cs
+++ b/eng/StackExchange.Redis.Build/Diagnostics.cs
@@ -383,32 +383,5 @@ internal static class Diagnostics
description: "The RespFragment generator implements [Resp] partial properties of type RespFragment or RespCommand; a declaration it cannot match is skipped, which would otherwise appear only as a missing implementation part.",
helpLinkUri: HelpLink("SER351"));
- ///
- /// An [AutoDatabase(WarnIfIncomplete = true)] type still has members that only throw.
- ///
- ///
- ///
- /// A transition tripwire, not a code-quality rule. A type being migrated to a new implementation one
- /// command at a time has the rest generated as throwing stubs; that is fine while the work is in
- /// progress and not fine in something that ships, and the difference is invisible at a glance
- /// because the whole point of the generated half is that nobody writes or reads it.
- ///
- ///
- /// Reported only for Release builds (detected by the absence of the DEBUG preprocessor
- /// symbol) so the inner development loop stays quiet, and only where the attribute opts in - the other
- /// [AutoDatabase] users generate members that genuinely work by forwarding, and counting those
- /// as "not implemented" would be both wrong and deafening.
- ///
- ///
- public static readonly DiagnosticDescriptor AutoDatabaseIncomplete = new(
- id: "SER352",
- title: "Generated database members are not implemented",
- messageFormat: "{0} member(s) of '{1}' are not implemented and will throw at run time",
- category: BuildCategory,
- defaultSeverity: DiagnosticSeverity.Warning,
- isEnabledByDefault: true,
- description: "A type generated by [AutoDatabase(WarnIfIncomplete = true)] still has members that only throw; it is mid-transition and should not ship in that state.",
- helpLinkUri: HelpLink("SER352"));
-
private static string HelpLink(string id) => string.Format(HelpLinkFormat, id);
}
diff --git a/src/StackExchange.Redis/AutoDatabase.cs b/src/StackExchange.Redis/AutoDatabase.cs
deleted file mode 100644
index c4ccd6b3c1..0000000000
--- a/src/StackExchange.Redis/AutoDatabase.cs
+++ /dev/null
@@ -1,293 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.Diagnostics.CodeAnalysis;
-using System.Runtime.CompilerServices;
-using System.Threading.Tasks;
-
-namespace StackExchange.Redis;
-
-[Conditional("DEBUG")]
-[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false)]
-internal sealed class AutoDatabaseAttribute : Attribute
-{
- ///
- /// Warn (SER352) on Release builds while any member of the decorated type is still generated
- /// rather than implemented by the type itself.
- ///
- ///
- /// For a type that is mid-transition, where the generated members throw rather than forward. Off by
- /// default, because the other users of this attribute generate members that genuinely work - counting
- /// those as unimplemented would be both wrong and deafening.
- ///
- public bool WarnIfIncomplete { get; set; }
-
- ///
- /// Whether the owning database can invoke a captured operation more than once, i.e. it replays.
- ///
- ///
- /// A replaying database outlives the call it captured: it re-invokes with the same captured arguments
- /// after the caller has long since regained control. Arguments passed as Memory /ReadOnlyMemory
- /// still belong to the caller, who is entitled to reuse that buffer once the call returns - so a replay
- /// would read whatever is in it by then. When this is set, the generated capture takes a pooled shallow
- /// copy of those arguments and the funnel disposes it; when it is not, the arguments are captured as-is,
- /// because a single forward cannot outlive the call.
- ///
- public bool Replays { get; set; }
-}
-
-// Implemented by a generated captured-arguments struct only when the owning auto-database implements
-// IRedisArgsMutator - i.e. only when something actually rewrites keys/channels. Everything else captures its
-// arguments into a plain readonly struct with no interface at all; a funnel that wants to map opts in by
-// constraining its TState to this (which is how KeyPrefixedDatabase will work once it moves onto
-// [AutoDatabase]).
-//
-// Map mutates the struct in place, so a funnel that maps MUST take its state BY VALUE - never by `in`, because
-// calling a non-readonly member through an `in` reference silently takes a defensive copy, mutates that, and
-// throws it away. Invoke it via RedisArgsMutatorExtensions.MapInPlace, which makes that mistake a compile
-// error (CS8329) instead of a silent loss of prefixing. (`ref` on the funnel is not an alternative: the
-// generated call site passes a constructed temporary, which `ref` rejects with CS1510, and async funnels
-// cannot have by-ref parameters at all.) The by-value copy is not waste here - a mapping funnel needs its own
-// mutable copy by definition. Only non-mapping funnels take `in`, and their structs are readonly, so for them
-// no defensive copy is even possible.
-internal interface IMappableRedisArgs
-{
- [Obsolete("Use MapInPlace instead; calling Map directly does nothing when the state is held by `in`.")]
- void Map(IRedisArgsMutator mutator);
-
- object? UnMapper { get; }
-}
-
-// Implemented by a generated captured-arguments struct whenever the captured call has a CommandFlags
-// parameter - which is very nearly all of them - so that a funnel holding an opaque TState can still ask the
-// one question that changes what it must hand back: was this fire-and-forget?
-//
-// It exists for RetryTransaction. That funnel records each call and returns a durable proxy task completed
-// later from the attempt, which is wrong for fire-and-forget: a plain RedisTransaction hands back an
-// *already-completed* task there (the caller has explicitly declined the reply), so without this the same
-// source awaiting the same result returns instantly on one and hangs on the other. The flags are captured
-// inside TState and are otherwise invisible to a funnel, which is the whole reason this interface is needed
-// rather than the funnel simply reading a parameter.
-internal interface IFlaggedRedisArgs
-{
- CommandFlags Flags { get; }
-}
-
-// The projections used by the auto-database funnels. There are exactly four real shapes, so each is named
-// rather than being expressed generically over the target/return type: that lets the type system encode the
-// invariants (sync goes to IDatabase, async goes to IDatabaseAsync and returns a Task) instead of leaving
-// nonsense combinations like "sync database, Task result" expressible.
-//
-// They exist at all (rather than Func<,,>/Action<,>) purely to pass the captured state by readonly-reference:
-// some of the generated state structs are chunky (a dozen-plus arguments), and by-value would copy the whole
-// thing on every call. Note that a lambda only binds to an `in` parameter if it says so - the generator emits
-// `static (in state, inner) => ...` accordingly.
-//
-// TState is necessarily invariant: it is passed by readonly-ref, and variant type parameters cannot carry
-// the struct constraint. TResult is covariant on the sync projection (it is the direct return); it cannot be
-// on the async one, because there it appears inside the invariant Task.
-internal delegate void AutoDatabaseSyncOperation(in TState state, IDatabase database)
- where TState : struct;
-
-internal delegate TResult AutoDatabaseSyncOperation(in TState state, IDatabase database)
- where TState : struct;
-
-internal delegate Task AutoDatabaseAsyncOperation(in TState state, IDatabaseAsync database)
- where TState : struct;
-
-internal delegate Task AutoDatabaseAsyncOperation(in TState state, IDatabaseAsync database)
- where TState : struct;
-
-internal interface IRedisArgsMutator
-{
- RedisKey Map(RedisKey key);
- RedisChannel Map(RedisChannel channel);
-
- RedisKey UnMap(RedisKey key);
- RedisChannel UnMap(RedisChannel channel);
-}
-
-internal interface IRedisArgsResult
-{
- T UnMap(IRedisArgsMutator mutator, T value);
-}
-
-internal static class RedisArgsMutatorExtensions
-{
- // these are used by the generated tuple-types via auto-database: each maps the key-bearing parts
- // of an argument through the supplied mutator. They hang off IRedisArgsMutator (rather than the
- // argument) so a call site reads consistently with the interface's own MapKey/MapChannel.
- public static KeyValuePair Map(
- this IRedisArgsMutator mutator,
- KeyValuePair value) =>
- new(mutator.Map(value.Key), value.Value);
-
- // Funnels should map via this rather than calling state.Map(mutator) directly. Mapping mutates the struct
- // in place, so it is only correct on a writable variable; the `ref this` here means that applying it to an
- // `in` parameter fails to compile (CS8329) instead of silently taking a defensive copy, mutating that, and
- // discarding it - which would leave keys unprefixed, i.e. a wrong-keyspace bug rather than a perf nit.
- // (Deliberately not named Map: an extension cannot shadow the instance member, so the guard would be lost.)
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- public static void MapInPlace(this ref TState state, IRedisArgsMutator mutator)
- where TState : struct, IMappableRedisArgs
-#pragma warning disable CS0618 // the one sanctioned call site: `state` is a genuine `ref`, so this mutates in place
- => state.Map(mutator);
-#pragma warning restore CS0618
-
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- public static TResult UnMap(this IRedisArgsMutator mutator, in TState state, TResult result)
- where TState : struct, IMappableRedisArgs
- {
- // note JIT will elide these tests using per-TResult value-type rules
- if (typeof(TResult) == typeof(RedisKey))
- {
- var tmp = mutator.UnMap(Unsafe.As(ref result));
- return Unsafe.As(ref tmp);
- }
-
- if (typeof(TResult) == typeof(RedisChannel))
- {
- var tmp = mutator.UnMap(Unsafe.As(ref result));
- return Unsafe.As(ref tmp);
- }
-
- if (typeof(TResult) == typeof(RedisValue))
- {
- return result; // never mapped
- }
-
- return state.UnMapper is IRedisArgsResult unmap ? unmap.UnMap(mutator, result) : result;
- }
-
- [return: NotNullIfNotNull("keys")]
- public static RedisKey[]? Map(this IRedisArgsMutator mutator, RedisKey[]? keys)
- {
- if (keys is null || keys.Length is 0) return keys;
- var arr = new RedisKey[keys.Length];
- for (int i = 0; i < arr.Length; i++)
- {
- arr[i] = mutator.Map(keys[i]);
- }
- return arr;
- }
-
- // ScriptEvaluateResp's keys parameter - every element is a key (unlike RedisKeyOrValue below),
- // mirroring the RedisKey[]? overload above but for the ReadOnlyMemory shape.
- public static ReadOnlyMemory Map(this IRedisArgsMutator mutator, ReadOnlyMemory keys)
- {
- if (keys.Length is 0) return keys;
- var arr = new RedisKey[keys.Length];
- var span = keys.Span;
- for (int i = 0; i < arr.Length; i++)
- {
- arr[i] = mutator.Map(span[i]);
- }
- return arr;
- }
-
- // the ExecuteResp escape hatch mixes keys and values in one collection (mirroring KeyPrefixed.ToInner);
- // rewrite only the key-shaped entries, copying only when there is something to rewrite so the common
- // all-values call allocates nothing.
- public static ReadOnlyMemory Map(this IRedisArgsMutator mutator, ReadOnlyMemory args)
- {
- if (args.Length is 0) return args;
- var span = args.Span;
- RedisKeyOrValue[]? copy = null;
- for (int i = 0; i < span.Length; i++)
- {
- if (span[i].IsKey)
- {
- (copy ??= span.ToArray())[i] = RedisKeyOrValue.FromKey(mutator.Map(span[i].Key));
- }
- }
- return copy ?? args;
- }
-
- [return: NotNullIfNotNull("pairs")]
- public static KeyValuePair[]? Map(
- this IRedisArgsMutator mutator,
- KeyValuePair[]? pairs)
- {
- if (pairs is null || pairs.Length is 0) return pairs;
- var arr = new KeyValuePair[pairs.Length];
- for (int i = 0; i < arr.Length; i++)
- {
- ref readonly KeyValuePair pair = ref pairs[i];
- arr[i] = new(mutator.Map(pair.Key), pair.Value);
- }
- return arr;
- }
-
- public static StreamPosition Map(this IRedisArgsMutator mutator, StreamPosition value) =>
- new(mutator.Map(value.Key), value.Position);
-
- [return: NotNullIfNotNull("positions")]
- public static StreamPosition[]? Map(this IRedisArgsMutator mutator, StreamPosition[]? positions)
- {
- if (positions is null || positions.Length is 0) return positions;
- var arr = new StreamPosition[positions.Length];
- for (int i = 0; i < arr.Length; i++)
- {
- ref readonly StreamPosition position = ref positions[i];
- arr[i] = new(mutator.Map(position.Key), position.Position);
- }
- return arr;
- }
-
- // the Execute/ExecuteAsync escape hatch takes a loosely-typed arg list in which any element may
- // be a boxed RedisKey or RedisChannel; these rewrite just those entries (mirroring
- // KeyPrefixed.ToInner), copying only when there is something to rewrite so the common call allocates nothing.
- [return: NotNullIfNotNull("args")]
- public static object[]? Map(this IRedisArgsMutator mutator, object[]? args)
- {
- if (args is null || args.Length is 0) return args;
- object[]? copy = null;
- for (int i = 0; i < args.Length; i++)
- {
- if (args[i] is RedisKey key)
- {
- (copy ??= (object[])args.Clone())[i] = mutator.Map(key);
- }
- else if (args[i] is RedisChannel channel)
- {
- (copy ??= (object[])args.Clone())[i] = mutator.Map(channel);
- }
- }
- return copy ?? args;
- }
-
- [return: NotNullIfNotNull("args")]
- public static ICollection? Map(this IRedisArgsMutator mutator, ICollection? args)
- {
- if (args is null || args.Count is 0) return args;
- bool any = false;
- foreach (var arg in args)
- {
- if (arg is RedisKey or RedisChannel)
- {
- any = true;
- break;
- }
- }
- if (!any) return args;
-
- var copy = new object[args.Count];
- int i = 0;
- foreach (var arg in args)
- {
- copy[i++] = arg switch
- {
- RedisKey key => mutator.Map(key),
- RedisChannel channel => mutator.Map(channel),
- _ => arg,
- };
- }
- return copy;
- }
-
- public static SortedSetPopResult UnMap(this IRedisArgsMutator mutator, SortedSetPopResult value) =>
- value.IsNull ? SortedSetPopResult.Null : new(mutator.Map(value.Key), value.Entries);
-
- public static ListPopResult UnMap(this IRedisArgsMutator mutator, ListPopResult value) =>
- value.IsNull ? ListPopResult.Null : new(mutator.Map(value.Key), value.Values);
-}
diff --git a/src/StackExchange.Redis/Availability/CircuitBreaker.cs b/src/StackExchange.Redis/Availability/CircuitBreaker.cs
index e04c6a9468..a66622640b 100644
--- a/src/StackExchange.Redis/Availability/CircuitBreaker.cs
+++ b/src/StackExchange.Redis/Availability/CircuitBreaker.cs
@@ -187,7 +187,7 @@ public override void ObserveResult(in FaultContext fault) { }
public override void Reset() { }
}
- // note we leave IsConnectionFault alone - that would impact RetryDatabase, where this is the key
+ // note we leave IsConnectionFault alone - that would impact RespRetryExecutor, where this is the key
}
private sealed class DefaultCircuitBreaker : CircuitBreaker
{
diff --git a/src/StackExchange.Redis/Availability/DatabaseExtensions.cs b/src/StackExchange.Redis/Availability/DatabaseExtensions.cs
index 13c1926046..ce02d487f0 100644
--- a/src/StackExchange.Redis/Availability/DatabaseExtensions.cs
+++ b/src/StackExchange.Redis/Availability/DatabaseExtensions.cs
@@ -1,5 +1,6 @@
using System.Diagnostics.CodeAnalysis;
using RESPite;
+using StackExchange.Redis.Interfaces;
namespace StackExchange.Redis.Availability;
@@ -18,8 +19,8 @@ public static class DatabaseExtensions
/// SE.Redis concepts, so can respond to server failover events, apply circuit-breaker rules, and
/// respect command effect categorization.
///
- /// The database to wrap; this must not be a batch, a transaction, an
- /// already-retrying database, or a database carrying an asyncState (see remarks).
+ /// The database to make retrying; this must not be a batch, a transaction, or
+ /// an already-retrying database.
///
/// The policy to apply; when (the default), the policy configured for the
/// underlying connection is used - for a connection group,
@@ -27,18 +28,40 @@ public static class DatabaseExtensions
/// .
///
///
- /// asyncState is not supported. A database's asyncState is stamped onto the task
- /// produced by a single dispatch, but a retrying database hands back its own task spanning however
- /// many attempts the operation takes; the same is true of the per-operation tasks handed out by
- /// on such a database. Rather than dropping
- /// the state silently, both refuse it: wrapping a database obtained via
- /// GetDatabase(db, asyncState) throws, as does supplying an asyncState when creating a
- /// transaction from a retrying database.
+ ///
+ /// Retry is a link in the dispatch chain, not a wrapper on the database. This re-dispatches
+ /// through the same executor decorator as :
+ /// what is replayed is the rendered command, so everything the database carries - the key prefix, the
+ /// database index, an asyncState , the multi-group failover source - travels unchanged. It used
+ /// to build a capture-and-replay wrapper, which replayed method calls and therefore had to
+ /// refuse an asyncState it could not stamp; the re-dispatched form has no such limit.
+ ///
+ ///
+ /// A database this cannot see inside is handed back unchanged. An external
+ /// implementation exposes no executor to decorate, and there is nothing
+ /// to capture any more - so rather than failing, such a database is returned as it came, without
+ /// retry.
+ ///
///
/// If is a batch, a
- /// transaction, already retrying, or carries an asyncState .
+ /// transaction, or already retrying.
public static IDatabaseAsync WithRetry(this IDatabaseAsync database, RetryPolicy? retryPolicy = null)
- => new RetryDatabase(database, retryPolicy ?? ResolveRetryPolicy(database.Multiplexer));
+ {
+ if (database is null) throw new System.ArgumentNullException(nameof(database));
+
+ if (database.Context is not { Raw: { Executor: not null } raw })
+ {
+ // nothing to decorate: an external implementation, or a context with no executor; see remarks
+ return database;
+ }
+
+ // a batch or a transaction queues rather than dispatches, so there is nothing to retry yet; the
+ // context overload below refuses nesting, which is the third historical rejection
+ database.RejectFlags(DatabaseFeatureFlags.Batch | DatabaseFeatureFlags.Transaction);
+
+ var context = new RespDatabaseContext(raw).WithRetry(retryPolicy);
+ return new RedisDatabase(context, database.Multiplexer, database.GetAsyncState());
+ }
///
/// A context whose commands are retried when a transient fault says they can be.
@@ -75,18 +98,16 @@ public static RespDatabaseContext WithRetry(this RespDatabaseContext context, Re
var inner = raw.Executor ?? throw new System.InvalidOperationException(
"This context has no executor, so there is nothing to retry through.");
- // cannot nest retry, as RetryDatabase.Validate refuses to wrap a retrying database: two loops
- // would multiply the attempt counts rather than sharing them
+ // cannot nest retry: two loops would multiply the attempt counts rather than sharing them
if (inner is RespRetryExecutor)
{
throw new System.InvalidOperationException(
"This context is already retrying; a second policy would multiply the attempts rather than replace them.");
}
- // the failover source comes from the executor chain rather than from an IDatabaseAsync, which is
- // what lets a retrying CONTEXT track failover at all: RetryDatabase could always hand its own
- // GetNextFailover down, but a context built with WithRetry had nowhere to get one and so silently
- // ran with the failover rungs unreachable. Fetched per use, never captured - see GetFailoverSource.
+ // the failover source comes from the executor chain rather than from an IDatabaseAsync: a
+ // multi-group chain offers one through GetFailoverSource, and anything else honestly has none.
+ // Fetched per use, never captured - see GetFailoverSource.
return new RespDatabaseContext(
raw.WithExecutor(new RespRetryExecutor(inner, retryPolicy ?? ResolveRetryPolicy(raw.Multiplexer), inner.GetFailoverSource())));
}
diff --git a/src/StackExchange.Redis/Availability/MultiGroupDatabase.Scans.cs b/src/StackExchange.Redis/Availability/MultiGroupDatabase.Scans.cs
index e9fbe96df5..b3a2b8cb32 100644
--- a/src/StackExchange.Redis/Availability/MultiGroupDatabase.Scans.cs
+++ b/src/StackExchange.Redis/Availability/MultiGroupDatabase.Scans.cs
@@ -1,47 +1,50 @@
-using System.Collections.Generic;
+using System.Collections.Generic;
namespace StackExchange.Redis.Availability;
-// Streaming cursor scans (IEnumerable / IAsyncEnumerable) are deferred-execution and don't fit the
-// capture-and-replay shape, so [AutoDatabase] skips them; they forward straight to the active member.
+// The cursor scans PIN to the member that is active when the scan starts, by forwarding to its own
+// database: a cursor is only meaningful to the server that issued it, so letting the base implementation
+// page through the group executor would hand member A's cursor to member B after a failover - a silently
+// wrong enumeration rather than a failed one. Pinned, a failover mid-scan faults the scan, which is the
+// honest outcome.
internal sealed partial class MultiGroupDatabase
{
- public IEnumerable HashScan(RedisKey key, RedisValue pattern, int pageSize, CommandFlags flags)
+ public override IEnumerable HashScan(RedisKey key, RedisValue pattern, int pageSize, CommandFlags flags)
=> GetActiveDatabase().HashScan(key, pattern, pageSize, flags);
- public IEnumerable HashScan(RedisKey key, RedisValue pattern = default, int pageSize = RedisBase.CursorUtils.DefaultLibraryPageSize, long cursor = RedisBase.CursorUtils.Origin, int pageOffset = 0, CommandFlags flags = CommandFlags.None)
+ public override IEnumerable HashScan(RedisKey key, RedisValue pattern = default, int pageSize = RedisBase.CursorUtils.DefaultLibraryPageSize, long cursor = RedisBase.CursorUtils.Origin, int pageOffset = 0, CommandFlags flags = CommandFlags.None)
=> GetActiveDatabase().HashScan(key, pattern, pageSize, cursor, pageOffset, flags);
- public IEnumerable HashScanNoValues(RedisKey key, RedisValue pattern = default, int pageSize = RedisBase.CursorUtils.DefaultLibraryPageSize, long cursor = RedisBase.CursorUtils.Origin, int pageOffset = 0, CommandFlags flags = CommandFlags.None)
+ public override IEnumerable HashScanNoValues(RedisKey key, RedisValue pattern = default, int pageSize = RedisBase.CursorUtils.DefaultLibraryPageSize, long cursor = RedisBase.CursorUtils.Origin, int pageOffset = 0, CommandFlags flags = CommandFlags.None)
=> GetActiveDatabase().HashScanNoValues(key, pattern, pageSize, cursor, pageOffset, flags);
- public IEnumerable SetScan(RedisKey key, RedisValue pattern, int pageSize, CommandFlags flags)
+ public override IEnumerable SetScan(RedisKey key, RedisValue pattern, int pageSize, CommandFlags flags)
=> GetActiveDatabase().SetScan(key, pattern, pageSize, flags);
- public IEnumerable SetScan(RedisKey key, RedisValue pattern = default, int pageSize = RedisBase.CursorUtils.DefaultLibraryPageSize, long cursor = RedisBase.CursorUtils.Origin, int pageOffset = 0, CommandFlags flags = CommandFlags.None)
+ public override IEnumerable SetScan(RedisKey key, RedisValue pattern = default, int pageSize = RedisBase.CursorUtils.DefaultLibraryPageSize, long cursor = RedisBase.CursorUtils.Origin, int pageOffset = 0, CommandFlags flags = CommandFlags.None)
=> GetActiveDatabase().SetScan(key, pattern, pageSize, cursor, pageOffset, flags);
- public IEnumerable SortedSetScan(RedisKey key, RedisValue pattern, int pageSize, CommandFlags flags)
+ public override IEnumerable SortedSetScan(RedisKey key, RedisValue pattern, int pageSize, CommandFlags flags)
=> GetActiveDatabase().SortedSetScan(key, pattern, pageSize, flags);
- public IEnumerable SortedSetScan(RedisKey key, RedisValue pattern = default, int pageSize = RedisBase.CursorUtils.DefaultLibraryPageSize, long cursor = RedisBase.CursorUtils.Origin, int pageOffset = 0, CommandFlags flags = CommandFlags.None)
+ public override IEnumerable SortedSetScan(RedisKey key, RedisValue pattern = default, int pageSize = RedisBase.CursorUtils.DefaultLibraryPageSize, long cursor = RedisBase.CursorUtils.Origin, int pageOffset = 0, CommandFlags flags = CommandFlags.None)
=> GetActiveDatabase().SortedSetScan(key, pattern, pageSize, cursor, pageOffset, flags);
- public IEnumerable VectorSetRangeEnumerate(RedisKey key, RedisValue start = default, RedisValue end = default, long count = 100, Exclude exclude = Exclude.None, CommandFlags flags = CommandFlags.None)
+ public override IEnumerable VectorSetRangeEnumerate(RedisKey key, RedisValue start = default, RedisValue end = default, long count = 100, Exclude exclude = Exclude.None, CommandFlags flags = CommandFlags.None)
=> GetActiveDatabase().VectorSetRangeEnumerate(key, start, end, count, exclude, flags);
- public IAsyncEnumerable HashScanAsync(RedisKey key, RedisValue pattern = default, int pageSize = RedisBase.CursorUtils.DefaultLibraryPageSize, long cursor = RedisBase.CursorUtils.Origin, int pageOffset = 0, CommandFlags flags = CommandFlags.None)
+ public override IAsyncEnumerable HashScanAsync(RedisKey key, RedisValue pattern = default, int pageSize = RedisBase.CursorUtils.DefaultLibraryPageSize, long cursor = RedisBase.CursorUtils.Origin, int pageOffset = 0, CommandFlags flags = CommandFlags.None)
=> GetActiveDatabase().HashScanAsync(key, pattern, pageSize, cursor, pageOffset, flags);
- public IAsyncEnumerable HashScanNoValuesAsync(RedisKey key, RedisValue pattern = default, int pageSize = RedisBase.CursorUtils.DefaultLibraryPageSize, long cursor = RedisBase.CursorUtils.Origin, int pageOffset = 0, CommandFlags flags = CommandFlags.None)
+ public override IAsyncEnumerable HashScanNoValuesAsync(RedisKey key, RedisValue pattern = default, int pageSize = RedisBase.CursorUtils.DefaultLibraryPageSize, long cursor = RedisBase.CursorUtils.Origin, int pageOffset = 0, CommandFlags flags = CommandFlags.None)
=> GetActiveDatabase().HashScanNoValuesAsync(key, pattern, pageSize, cursor, pageOffset, flags);
- public IAsyncEnumerable SetScanAsync(RedisKey key, RedisValue pattern = default, int pageSize = RedisBase.CursorUtils.DefaultLibraryPageSize, long cursor = RedisBase.CursorUtils.Origin, int pageOffset = 0, CommandFlags flags = CommandFlags.None)
+ public override IAsyncEnumerable SetScanAsync(RedisKey key, RedisValue pattern = default, int pageSize = RedisBase.CursorUtils.DefaultLibraryPageSize, long cursor = RedisBase.CursorUtils.Origin, int pageOffset = 0, CommandFlags flags = CommandFlags.None)
=> GetActiveDatabase().SetScanAsync(key, pattern, pageSize, cursor, pageOffset, flags);
- public IAsyncEnumerable SortedSetScanAsync(RedisKey key, RedisValue pattern = default, int pageSize = RedisBase.CursorUtils.DefaultLibraryPageSize, long cursor = RedisBase.CursorUtils.Origin, int pageOffset = 0, CommandFlags flags = CommandFlags.None)
+ public override IAsyncEnumerable SortedSetScanAsync(RedisKey key, RedisValue pattern = default, int pageSize = RedisBase.CursorUtils.DefaultLibraryPageSize, long cursor = RedisBase.CursorUtils.Origin, int pageOffset = 0, CommandFlags flags = CommandFlags.None)
=> GetActiveDatabase().SortedSetScanAsync(key, pattern, pageSize, cursor, pageOffset, flags);
- public IAsyncEnumerable VectorSetRangeEnumerateAsync(RedisKey key, RedisValue start = default, RedisValue end = default, long count = 100, Exclude exclude = Exclude.None, CommandFlags flags = CommandFlags.None)
+ public override IAsyncEnumerable VectorSetRangeEnumerateAsync(RedisKey key, RedisValue start = default, RedisValue end = default, long count = 100, Exclude exclude = Exclude.None, CommandFlags flags = CommandFlags.None)
=> GetActiveDatabase().VectorSetRangeEnumerateAsync(key, start, end, count, exclude, flags);
}
diff --git a/src/StackExchange.Redis/Availability/MultiGroupDatabase.cs b/src/StackExchange.Redis/Availability/MultiGroupDatabase.cs
index 0d8b6e0693..3f7557dd03 100644
--- a/src/StackExchange.Redis/Availability/MultiGroupDatabase.cs
+++ b/src/StackExchange.Redis/Availability/MultiGroupDatabase.cs
@@ -1,98 +1,96 @@
-using System;
-using System.Threading;
-using System.Threading.Tasks;
-using StackExchange.Redis.Interfaces;
+using StackExchange.Redis.Interfaces;
namespace StackExchange.Redis.Availability;
-// The bulk of IDatabase/IDatabaseAsync is generated by [AutoDatabase]: every command is captured into a
-// state struct and replayed against the currently-active member via the Execute/ExecuteAsync funnels below
-// (so a call always lands on whichever member is active *now*). Only the members the generator deliberately
-// skips - the Wait family, IsConnected, the batch/transaction factories, and the streaming scans (see
-// MultiGroupDatabase.Scans.cs) - plus the properties and internal plumbing are hand-written here.
-[AutoDatabase]
-internal sealed partial class MultiGroupDatabase(MultiGroupMultiplexer parent, int database, object? asyncState)
- : IDatabase, IInternalDatabaseAsync
+///
+/// The group's database: the ordinary funnel over a context whose executor
+/// ( ) resolves the currently-active member per send.
+///
+///
+///
+/// This used to be 628 generated capture-and-replay members. Every one of them existed to capture a
+/// command's arguments, resolve the active member, and replay the call against it - because the decoration
+/// happened above the command surface. With the decoration an executor below it, those members have
+/// nothing left to do, and what remains here is only what the base funnel cannot know: the group's feature
+/// flags and diagnostic name, and the cursor scans, which must pin to one member (see
+/// MultiGroupDatabase.Scans.cs ).
+///
+///
+/// Note what is not here: nothing about connecting, reconnecting, backlogs, slots or routing.
+/// The active member is an entire multiplexer with its own executor chain, and the group executor hands
+/// the command to it. That is the whole of a group's job, and the reason this is short.
+///
+///
+/// The command map comes from configuration, not connection state - each member is configured
+/// separately, and the group takes the map from its members' configuration - so the context answers while
+/// every member is down. The database index is configuration too: a defaulted index resolves to the
+/// members' shared DefaultDatabase , which ValidateConsistentConfiguration demands they agree
+/// on - so the context is fully determined, buildable and cacheable with nothing reachable at all.
+///
+///
+/// The cache is the active member's, resolved per command. Not a shared group cache: a cached
+/// reply is only sound while the connection that produced it is the one being asked and its
+/// CLIENT TRACKING registration is still live, so serving member A's values while B is active
+/// would be wrong - and silently so. Per-member caches make a switch a no-op for correctness, and the
+/// existing "flush when tracking drops" rule already covers the case that actually matters, since a
+/// failover usually happens BECAUSE the old member's connection died. A switch away from a healthy
+/// member leaves its cache warm for switching back, which nuking a shared cache would throw away.
+///
+///
+/// Knowing the replication topology would not change this. The rule is not "the data might
+/// differ" - that is incidental - but that a cache entry carries an implicit subscription, and
+/// subscriptions do not transfer . CLIENT TRACKING is registered per connection, so
+/// inheriting A's entries while talking to B inherits no registration on B: those entries become
+/// unfalsifiable rather than merely possibly-stale, even if B's data is byte-identical. Active-active
+/// and geo-replication change the invalidation latency (bounded by replication lag rather than
+/// a round trip), which bounds a safe maximum age - not what happens on a switch.
+///
+///
+/// Our own writes are the exception, and travel to every member's cache
+/// ( ): a write made while B is active reaches A's server only by
+/// replication, so without that, failing back could hand a caller the value they replaced. An inactive
+/// member's tracking connection is kept honest the same way an active one is: group members always run
+/// heartbeat consistency checks, so every endpoint is pinged each heartbeat, a half-open connection trips
+/// the dead-socket rule, and the failure flushes that member's cache.
+///
+///
+internal sealed partial class MultiGroupDatabase : RedisDatabase
{
- ///
- public RespDatabaseContext Context => new(GetContext());
-
- private RespContext? _context;
-
- /// The context surface over whichever member is currently active.
- ///
- ///
- /// This used to throw. What it needed was an executor that resolves the active member per
- /// send rather than at construction - which is what is - because the
- /// context is built once and memoised, while the active member is the thing a group exists to change.
- ///
- ///
- /// Note what is not here: nothing about connecting, reconnecting, backlogs, slots or routing.
- /// The active member is an entire multiplexer with its own executor chain, and this hands the command
- /// to it. That is the whole of a group's job, and the reason this is short.
- ///
- ///
- /// The command map comes from configuration, not connection state - each member is configured
- /// separately, and the group takes the map from its members' configuration - so it answers while
- /// every member is down. The one thing that may not is the database INDEX: -1 means "whatever
- /// the active member defaults to", which needs a member. An explicit index does not, and that context
- /// is buildable and cacheable with nothing reachable at all.
- ///
- ///
- /// The cache is the active member's, resolved per command. Not a shared group cache: a cached
- /// reply is only sound while the connection that produced it is the one being asked and its
- /// CLIENT TRACKING registration is still live, so serving member A's values while B is active
- /// would be wrong - and silently so. Per-member caches make a switch a no-op for correctness, and the
- /// existing "flush when tracking drops" rule already covers the case that actually matters, since a
- /// failover usually happens BECAUSE the old member's connection died. A switch away from a healthy
- /// member leaves its cache warm for switching back, which nuking a shared cache would throw away.
- ///
- ///
- /// Knowing the replication topology would not change this. The rule is not "the data might
- /// differ" - that is incidental - but that a cache entry carries an implicit subscription, and
- /// subscriptions do not transfer . CLIENT TRACKING is registered per connection, so
- /// inheriting A's entries while talking to B inherits no registration on B: those entries become
- /// unfalsifiable rather than merely possibly-stale, even if B's data is byte-identical. Active-active
- /// and geo-replication change the invalidation latency (bounded by replication lag rather than
- /// a round trip), which bounds a safe maximum age - not what happens on a switch.
- ///
- ///
- /// Our own writes are the exception, and travel to every member's cache
- /// ( ): a write made while B is active reaches A's server only by
- /// replication, so without that, failing back could hand a caller the value they replaced. An inactive
- /// member's tracking connection is kept honest the same way an active one is: group members always run
- /// heartbeat consistency checks, so every endpoint is pinged each heartbeat, a half-open connection trips
- /// the dead-socket rule, and the failure flushes that member's cache.
- ///
- ///
- /// Where the 628 generated forwarding members eventually go. Every one of them exists to
- /// capture a command's arguments, resolve the active member, and replay the call against it - because
- /// the decoration happens above the command surface. Once the decoration is an executor below it,
- /// those members have nothing left to do, and this property is the seam through which they leave.
- ///
- ///
- private RespContext GetContext()
+ private readonly MultiGroupMultiplexer _parent;
+ private readonly int _database;
+ private readonly object? _asyncState;
+
+ /// Create the group's database over a group-executor context.
+ /// The group this database belongs to.
+ /// The database index; already resolved, never negative (see
+ /// MultiGroupMultiplexer.GetDatabase ).
+ /// The async-state stamped onto the tasks this database hands out.
+ internal MultiGroupDatabase(MultiGroupMultiplexer parent, int database, object? asyncState)
+ : base(BuildContext(parent, database), parent, asyncState)
{
- if (_context is { } existing) return existing;
+ _parent = parent;
+ _database = database;
+ _asyncState = asyncState;
+ }
- // `database` is the constructor's, not the Database PROPERTY: the property resolves -1 by asking
- // the active member what it defaults to, and therefore throws when the group is down. An explicit
- // index needs no member, so that context is fully determined and can be built and memoised while
- // nothing is reachable; a defaulted one genuinely cannot be known yet, and throwing there is what
- // the Database property already does.
- var resolved = database >= 0 ? database : Database;
- return _context = new RespContext(
+ /// The context over whichever member is currently active.
+ private static RespDatabaseContext BuildContext(MultiGroupMultiplexer parent, int database) => new(
+ new RespContext(
parent.CommandMap,
- database: resolved,
+ database: database,
serverType: ServerType.Standalone)
- .WithExecutor(new RespGroupExecutor(() => ActiveExecutor, resolved, DescribeUnavailable, parent.GetNextFailover) { Group = parent })
- .WithCacheResolver(() => parent.TryGetActive()?.ClientCache);
- }
-
- private RespExecutorBase? ActiveExecutor
- => TryGetActiveDatabase() is IRespTarget target ? target.Context.Executor : null;
-
- private string DescribeUnavailable()
+ .WithExecutor(new RespGroupExecutor(
+ () => ActiveExecutor(parent, database),
+ database,
+ () => DescribeUnavailable(parent),
+ parent.GetNextFailover)
+ { Group = parent })
+ .WithCacheResolver(() => parent.TryGetActive()?.ClientCache));
+
+ private static RespExecutorBase? ActiveExecutor(MultiGroupMultiplexer parent, int database)
+ => parent.TryGetActive()?.GetDatabase(database) is IRespTarget target ? target.Context.Executor : null;
+
+ private static string DescribeUnavailable(MultiGroupMultiplexer parent)
{
// the group's own wording rather than a second copy of it: this asks the same question the facade
// asks and reports the answer, so the two cannot drift apart
@@ -108,81 +106,22 @@ private string DescribeUnavailable()
}
///
- RespContext IRespTarget.Context => GetContext();
-
- public object? AsyncState => asyncState;
- public int Database => database < 0 ? GetActiveDatabase().Database : database;
-
- public IConnectionMultiplexer Multiplexer => parent;
-
- CancellationToken IInternalDatabaseAsync.GetNextFailover() => parent.GetNextFailover();
-
- DatabaseFeatureFlags IInternalDatabaseAsync.GetFeatures(out string name)
+ /// Folds in the currently-active member's features (when there is one) and labels with its name.
+ private protected override DatabaseFeatureFlags GetFeaturesCore(out string name)
{
- // fold in the currently-active member's features (when there is one) and label with its name
var active = TryGetActiveDatabase();
var features = active is null ? DatabaseFeatureFlags.None : active.GetFeatures(out _);
- name = ((IConnectionGroup)parent).ActiveMember?.Name ?? "";
+ name = ((IConnectionGroup)_parent).ActiveMember?.Name ?? "";
return features | DatabaseFeatureFlags.ConnectionGroup | DatabaseFeatureFlags.Failover;
}
- // uses the active member's name (via GetFeatures) when a member is active
+ // uses the active member's name (via GetFeaturesCore) when a member is active
public override string ToString() => this.BuildString();
// for high DB numbers this might allocate even for null async-state scenarios; unavoidable for now
- private IDatabase GetActiveDatabase() => parent.Active.GetDatabase(database, asyncState);
+ private IDatabase GetActiveDatabase() => _parent.Active.GetDatabase(_database, _asyncState);
// non-throwing twin of GetActiveDatabase: returns null when the group currently has no active
// member, for use by members that have an obvious trivial result when disconnected
- private IDatabase? TryGetActiveDatabase() => parent.TryGetActive()?.GetDatabase(database, asyncState);
-
- // ---- [AutoDatabase] funnels ---------------------------------------------------------------------
- // the generated explicit interface implementations funnel every captured call through these: we simply
- // forward to the currently-active member. Unlike RetryDatabase there is no key mapping to apply (we are
- // not rewriting keys), so the captured state's Map/UnMapper is never invoked.
- private TResult Execute(in TState state, AutoDatabaseSyncOperation operation)
- where TState : struct
- => operation(in state, GetActiveDatabase());
-
- private void Execute(in TState state, AutoDatabaseSyncOperation operation)
- where TState : struct
- => operation(in state, GetActiveDatabase());
-
- private Task ExecuteAsync(in TState state, AutoDatabaseAsyncOperation operation)
- where TState : struct
- => operation(in state, GetActiveDatabase());
-
- private Task ExecuteAsync(in TState state, AutoDatabaseAsyncOperation operation)
- where TState : struct
- => operation(in state, GetActiveDatabase());
-
- // ---- members the generator deliberately skips (see AutoDatabaseGenerator.SkipMethod) -------------
- public IBatch CreateBatch(object? asyncState = null)
- => GetActiveDatabase().CreateBatch(asyncState);
-
- public ITransaction CreateTransaction(object? asyncState = null)
- => GetActiveDatabase().CreateTransaction(asyncState);
-
- ITransactionAsync IDatabaseAsync.CreateTransaction(object? asyncState) => CreateTransaction(asyncState);
-
- // status probe, not a server round-trip: trivially "not connected" when there is no active member
- public bool IsConnected(RedisKey key, CommandFlags flags = CommandFlags.None)
- => TryGetActiveDatabase()?.IsConnected(key, flags) ?? false;
-
- // routing lookup against the currently-active member; null / NoEndpoint when the group has none
- public System.Net.EndPoint? IdentifyEndpoint(RedisKey key = default, CommandFlags flags = CommandFlags.None)
- => TryGetActiveDatabase()?.IdentifyEndpoint(key, flags);
-
- public Task IdentifyEndpointAsync(RedisKey key = default, CommandFlags flags = CommandFlags.None)
- => TryGetActiveDatabase()?.IdentifyEndpointAsync(key, flags) ?? MultiGroupMultiplexer.NoEndpoint;
-
- // the Wait family operates on caller-supplied Tasks, not server calls
- // forwarding is not using: these decorators must implement the interface in full, and the
- // implementation cannot be dropped while the interface declares it
- #pragma warning disable SER308 // Blocking on a task through the library's Wait helpers
- public bool TryWait(Task task) => GetActiveDatabase().TryWait(task);
- public void Wait(Task task) => GetActiveDatabase().Wait(task);
- public T Wait(Task task) => GetActiveDatabase().Wait(task);
- public void WaitAll(params Task[] tasks) => GetActiveDatabase().WaitAll(tasks);
- #pragma warning restore SER308
+ private IDatabase? TryGetActiveDatabase() => _parent.TryGetActive()?.GetDatabase(_database, _asyncState);
}
diff --git a/src/StackExchange.Redis/Availability/MultiGroupMultiplexer.cs b/src/StackExchange.Redis/Availability/MultiGroupMultiplexer.cs
index eb65816b91..b081490c77 100644
--- a/src/StackExchange.Redis/Availability/MultiGroupMultiplexer.cs
+++ b/src/StackExchange.Redis/Availability/MultiGroupMultiplexer.cs
@@ -1379,7 +1379,14 @@ public ISubscriber GetSubscriber(object? asyncState = null)
public IDatabase GetDatabase(int db = -1, object? asyncState = null)
{
- if ((asyncState is null) & (db >= -1) & (db <= ConnectionMultiplexer.MaxCachedDatabaseInstance))
+ if (db < -1) throw new ArgumentOutOfRangeException(nameof(db));
+
+ // a defaulted index is configuration, not connection state: every member must agree about
+ // DefaultDatabase (ValidateConsistentConfiguration refuses a group that disagrees), so the
+ // group's default is member 0's and needs no member to be reachable
+ if (db < 0) db = DefaultDatabase;
+
+ if ((asyncState is null) & (db <= ConnectionMultiplexer.MaxCachedDatabaseInstance))
{
return _databases[db + 1] ??= new MultiGroupDatabase(this, db, null);
}
@@ -1387,6 +1394,16 @@ public IDatabase GetDatabase(int db = -1, object? asyncState = null)
return new MultiGroupDatabase(this, db, asyncState);
}
+ /// The database a defaulted index resolves to; configuration, shared by every member.
+ internal int DefaultDatabase
+ {
+ get
+ {
+ var members = _members;
+ return (members.Length == 0 ? null : members[0].Configuration.DefaultDatabase) ?? 0;
+ }
+ }
+
private readonly IDatabase?[] _databases =
new IDatabase?[ConnectionMultiplexer.MaxCachedDatabaseInstance + 2];
diff --git a/src/StackExchange.Redis/Availability/RespRetryExecutor.cs b/src/StackExchange.Redis/Availability/RespRetryExecutor.cs
index d72ea1a63b..c9f2fbae2f 100644
--- a/src/StackExchange.Redis/Availability/RespRetryExecutor.cs
+++ b/src/StackExchange.Redis/Availability/RespRetryExecutor.cs
@@ -12,13 +12,13 @@ namespace StackExchange.Redis.Availability;
///
///
///
-/// The same policy as , and a fraction of the code. That one has to
-/// capture every argument of every command into a generated state struct so it can replay the call, own
-/// pooled copies of any Memory<T> arguments for as long as the replaying lasts, and dispose
-/// the capture when the last attempt is done - because what it is replaying is a method call . Here
-/// the thing being replayed is a rendered frame that already exists, so there is nothing to capture,
-/// nothing to own and nothing to map: the loop is the whole of it. Both call the same
-/// , so the two paths cannot disagree about policy.
+/// A rendered frame is the thing replayed, which is why this is small. The capture-and-replay
+/// wrapper this replaced had to capture every argument of every command into a generated state struct so
+/// it could replay the call, own pooled copies of any Memory<T> arguments for as long as the
+/// replaying lasted, and dispose the capture when the last attempt was done - because what it replayed
+/// was a method call . Here the frame already exists, so there is nothing to capture, nothing to
+/// own and nothing to map: the loop is the whole of it, and makes every
+/// policy decision.
///
///
/// Synchronous too. A synchronous send - which is what a context
@@ -29,11 +29,11 @@ namespace StackExchange.Redis.Availability;
/// context the one kind that could not serve a library's synchronous methods.
///
///
-/// Failover is not wired up yet. takes its next-failover token from
-/// IDatabaseAsync.GetNextFailover() ; an executor has no equivalent, so this takes an optional
-/// source and is built without when there is none - which
-/// makes false and the failover rungs unreachable, rather
-/// than silently pretending a failover could happen.
+/// Failover comes from the executor chain. The source is optional, and this is built without
+/// when there is none - which makes
+/// false and the failover rungs unreachable, rather than
+/// silently pretending a failover could happen. A multi-group chain supplies one
+/// (RespGroupExecutor.GetFailoverSource ); a single connection has nothing to fail over to.
///
///
internal sealed class RespRetryExecutor : RespExecutorBase
@@ -43,32 +43,21 @@ internal sealed class RespRetryExecutor : RespExecutorBase
private readonly Func? _failoverSource;
internal RespRetryExecutor(RespExecutorBase inner, RetryPolicy policy, Func? failoverSource = null)
- : this(
- inner,
- new RetryController(
- policy ?? throw new ArgumentNullException(nameof(policy)),
- failoverSource is null ? DatabaseFeatureFlags.None : DatabaseFeatureFlags.Failover),
- failoverSource)
- {
- }
-
- /// Share an existing controller, rather than deriving a second one from the same policy.
- ///
- /// For , whose context is this executor over the inner one: sharing the
- /// controller means the database path and the context path are not merely configured alike, they are
- /// configured by the same object - including the failover feature flag, which a policy alone does not
- /// carry.
- ///
- internal RespRetryExecutor(RespExecutorBase inner, RetryController controller, Func? failoverSource)
{
_inner = inner ?? throw new ArgumentNullException(nameof(inner));
- _controller = controller ?? throw new ArgumentNullException(nameof(controller));
+ _controller = new RetryController(
+ policy ?? throw new ArgumentNullException(nameof(policy)),
+ failoverSource is null ? DatabaseFeatureFlags.None : DatabaseFeatureFlags.Failover);
_failoverSource = failoverSource;
}
/// The policy in force; read by the tests, which assert how a policy was resolved.
internal RetryPolicy Policy => _controller.Policy;
+ /// The controller, shared with so a transaction
+ /// created from a retrying database applies exactly the policy the database does.
+ internal RetryController Controller => _controller;
+
/// The executor underneath, so a second WithRetry can refuse rather than nest.
internal RespExecutorBase Inner => _inner;
@@ -208,7 +197,7 @@ internal override RespPayload Send(RespRequest preamble, RespRequest request, IR
}
}
- /// The retry loop, borrowed whole from .
+ /// The retry loop.
///
///
/// Every decision is the controller's: whether the fault is transient, whether attempts remain,
@@ -216,9 +205,9 @@ internal override RespPayload Send(RespRequest preamble, RespRequest request, IR
/// shape of the loop.
///
///
- /// The failover token is captured before the first attempt is awaited , as it is there and for
- /// the same reason: taken afterwards, a failover happening between the failure and the fetch would be
- /// missed, and the retry would wait for one that had already been and gone.
+ /// The failover token is captured before the first attempt is awaited : taken afterwards, a
+ /// failover happening between the failure and the fetch would be missed, and the retry would wait
+ /// for one that had already been and gone.
///
///
private async ValueTask Awaited(ValueTask pending, RespRequest request, CancellationToken cancellationToken)
diff --git a/src/StackExchange.Redis/Availability/RespRetryTransactionExecutor.cs b/src/StackExchange.Redis/Availability/RespRetryTransactionExecutor.cs
new file mode 100644
index 0000000000..4236ca5645
--- /dev/null
+++ b/src/StackExchange.Redis/Availability/RespRetryTransactionExecutor.cs
@@ -0,0 +1,631 @@
+using System;
+using System.Collections.Generic;
+using System.Threading;
+using System.Threading.Tasks;
+using StackExchange.Redis.Protocol;
+
+namespace StackExchange.Redis.Availability;
+
+///
+/// A transaction that replays as a unit: the frame-level successor to the capture-and-replay
+/// RetryTransaction .
+///
+///
+///
+/// What is stored is the rendered request, not the method call. Where RetryTransaction
+/// recorded every builder invocation into a generated state struct and replayed it against a fresh
+/// , this accumulates what the command surface already produced - the rendered
+/// , its handler, and the conditions in semantic form - and each attempt feeds
+/// them into a fresh, one-shot . Same unit, same loop, no generator.
+///
+///
+/// Why replay cannot reuse the attempt's operations. Once a run is written, each queued operation
+/// is a pooled, single-completion source enrolled with that connection: the connection's own teardown
+/// faults it, and a second enrollment while the first may still touch it is a use-after-release on the
+/// pool. So the operations enrolled per attempt are the attempt's own, and the caller holds durable
+/// proxies that settle only when the unit has finished for good - exactly the shape
+/// RetryTransaction used, one layer down.
+///
+///
+/// Why replaying the unit is safe at all : the WATCH constraints live in the conditions, not the
+/// queue, and each attempt re-issues them on its own connection - so a replay re-adjudicates against
+/// fresh state rather than running with a dead connection's guard silently gone. The queued commands
+/// run only if the re-issued conditions hold and the EXEC commits. An EXEC that was
+/// written and never answered is NOT replayed blindly: the fault carries the queue's aggregate retry
+/// category, so the shared policy gates the whole transaction exactly like one command.
+///
+///
+internal sealed class RespRetryTransactionExecutor : RespExecutorBase, ITransactionExecutor
+{
+ private readonly RespExecutorBase _inner;
+ private readonly RespContext _context;
+ private readonly RetryController _controller;
+ private readonly Func? _failoverSource;
+ private readonly object _sync = new();
+
+ private List? _recorded;
+ private List? _conditions;
+ private int _executed;
+ private volatile bool _watchConflict;
+
+ /// Create a retrying transaction over an executor.
+ /// The executor underneath the retry link; each attempt resolves through it.
+ /// The context conditions render through; it must NOT carry the retry link.
+ /// The shared retry controller, from the database's RespRetryExecutor .
+ internal RespRetryTransactionExecutor(RespExecutorBase inner, RespContext context, RetryController controller)
+ {
+ _inner = inner ?? throw new ArgumentNullException(nameof(inner));
+ _context = context ?? throw new ArgumentNullException(nameof(context));
+ _controller = controller ?? throw new ArgumentNullException(nameof(controller));
+ _failoverSource = inner.GetFailoverSource();
+ }
+
+ ///
+ internal override bool Accumulates => true;
+
+ ///
+ internal override bool Transactional => true;
+
+ ///
+ public override int Database => _inner.Database;
+
+ ///
+ internal override IConnectionMultiplexer? ExposedMultiplexer => _inner.ExposedMultiplexer;
+
+ ///
+ internal override RespExecutorBase? ResolveFor(in RedisKey key, RedisCommand command, CommandFlags flags)
+ => _inner.ResolveFor(in key, command, flags);
+
+ ///
+ /// Yes: the recorded request is this executor's own reference (or copy) by the time this returns.
+ internal override bool CopiesRequestOnSend => true;
+
+ ///
+ public bool WasWatchConflict => _watchConflict;
+
+ ///
+ public override RespPayload Send(in RespRequest request)
+ => throw new NotSupportedException("A queued command cannot be waited on before the transaction is executed.");
+
+ ///
+ ///
+ /// The payload shape: the recorded command owns no handler, and the final attempt's payload is handed
+ /// to the caller intact rather than parsed - the same contract as the plain executor's untyped path.
+ /// The request is NOT retained here: by that path's convention the caller holds its reference until
+ /// the returned task completes, which is exactly the final attempt.
+ ///
+ public override ValueTask SendAsync(RespRequest request, CancellationToken cancellationToken = default)
+ {
+ if ((request.Flags & CommandFlags.FireAndForget) != 0)
+ {
+ Record(new RecordedPayload(request, ownsRequest: false, proxy: null, cancellationToken));
+ return default;
+ }
+
+ var proxy = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
+ Record(new RecordedPayload(request, ownsRequest: false, proxy, cancellationToken));
+ return new ValueTask(proxy.Task);
+ }
+
+ ///
+ internal override ValueTask SendTypedAsync(
+ RespRequest request, IRespHandler handler, CancellationToken cancellationToken)
+ {
+ // the same special case as the plain executor: a payload-typed result goes the untyped route
+ if (typeof(TResult) == typeof(RespPayload)) return RespExecutor.AwaitUncached(this, request, handler, cancellationToken);
+
+ // ToOwned: a borrowed request is copied, an owned one is kept - this path's convention
+ // (CopiesRequestOnSend) makes the incoming reference ours to keep, and Release gives it back
+ var owned = request.ToOwned();
+
+ if ((owned.Flags & CommandFlags.FireAndForget) != 0)
+ {
+ Record(new Recorded(owned, ownsRequest: true, handler, proxy: null, _inner, cancellationToken));
+
+ // the one shared completed-default task, as the plain transaction hands out for the same case
+ return new ValueTask(CompletedTask.Default(null)!);
+ }
+
+ var proxy = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
+ Record(new Recorded(owned, ownsRequest: true, handler, proxy, _inner, cancellationToken));
+ return new ValueTask(proxy.Task);
+ }
+
+ ///
+ internal override ValueTask SendVoidAsync(RespRequest request, IRespHandler handler, CancellationToken cancellationToken)
+ {
+ var pending = SendTypedAsync(request, handler, cancellationToken);
+ if (pending.IsCompletedSuccessfully)
+ {
+ _ = pending.Result;
+ return default;
+ }
+
+ return new ValueTask(pending.AsTask());
+ }
+
+ private void Record(IRecorded recorded)
+ {
+ lock (_sync)
+ {
+ if (_executed != 0) throw new InvalidOperationException("This transaction has already been executed.");
+ (_recorded ??= []).Add(recorded);
+ }
+ }
+
+ ///
+ public void AddCondition(Condition condition, Action? onVerdict = null)
+ {
+ if (condition is null) throw new ArgumentNullException(nameof(condition));
+ lock (_sync)
+ {
+ if (_executed != 0) throw new InvalidOperationException("Operations cannot be added after the transaction has been executed.");
+ (_conditions ??= []).Add(new RecordedCondition(condition, onVerdict));
+ }
+ }
+
+ ///
+ /// The fold the retry policy gates the whole unit with; see the plain executor's twin.
+ public CommandFlags AggregateRetryCategory
+ {
+ get
+ {
+ var result = CommandFlags.None;
+ lock (_sync)
+ {
+ if (_recorded is { } recorded)
+ {
+ foreach (var op in recorded)
+ {
+ var category = op.Flags & CommandFlagsInternal.MaskRetryCategory;
+ if (category > result) result = category;
+ }
+ }
+ }
+
+ return result;
+ }
+ }
+
+ ///
+ public async Task ExecuteAsync(CommandFlags flags = CommandFlags.None)
+ {
+ List? recorded;
+ List? conditions;
+ lock (_sync)
+ {
+ if (_executed != 0) throw new InvalidOperationException("This transaction has already been executed.");
+ _executed = 1;
+
+ // taken under the lock, so the loops below run over lists nothing can still be adding to
+ recorded = _recorded;
+ conditions = _conditions;
+ _recorded = null;
+ _conditions = null;
+ }
+
+ try
+ {
+ return await ExecuteCoreAsync(flags, recorded ?? [], conditions).ConfigureAwait(false);
+ }
+ finally
+ {
+ if (recorded is not null)
+ {
+ foreach (var op in recorded) op.Release();
+ }
+ }
+ }
+
+ private async Task ExecuteCoreAsync(CommandFlags flags, List recorded, List? conditions)
+ {
+ var attemptCount = 0;
+
+ // captured BEFORE the first attempt - otherwise a failover between a failed attempt and
+ // re-reading the token could be missed (same reasoning as RespRetryExecutor)
+ var failover = _controller.TracksFailover ? (_failoverSource?.Invoke() ?? CancellationToken.None) : CancellationToken.None;
+
+ // watch contention gets its own budget; only meaningful when there are conditions to WATCH
+ var watchAttempt = 0;
+ var maxWatchAttempts = conditions is null ? 1 : _controller.MaxWatchConflictAttempts;
+ while (true)
+ {
+ // a fresh, one-shot unit per attempt: the conditions re-render and re-WATCH on whatever
+ // connection this attempt lands on, and the queued frames re-enroll as that attempt's own
+ // operations - the durable proxies the caller holds are settled only at the end
+ var attempt = new RespTransactionExecutor(_inner, _context, reusable: false);
+ if (conditions is not null)
+ {
+ foreach (var condition in conditions) condition.Replay(attempt);
+ }
+
+ foreach (var op in recorded) op.Replay(attempt);
+
+ // the aggregate category rides on the EXEC's flags, so the fault it reports carries it and
+ // the shared policy gates the whole transaction exactly like one command
+ var effectiveFlags = (flags & ~CommandFlagsInternal.MaskRetryCategory) | attempt.AggregateRetryCategory;
+
+ try
+ {
+ var committed = await attempt.ExecuteAsync(effectiveFlags).ConfigureAwait(false);
+ _watchConflict = attempt.WasWatchConflict;
+
+ // the server rejected an EXEC we really did issue because a watched key changed under us:
+ // contention rather than a fault, so it has its own budget, waits its own delay, and the
+ // side-effect category does not apply - nothing happened
+ if (!committed && _watchConflict && ++watchAttempt < maxWatchAttempts)
+ {
+ DiscardAttempt(recorded, conditions);
+ await _controller.WatchConflictDelayAsync().ConfigureAwait(false);
+ continue;
+ }
+
+ // clean completion (committed, or electively aborted): forward the per-attempt outcomes
+ // onto the durable proxies - settled before we return, unless the caller declined the
+ // EXEC's own reply, in which case waiting is the opposite of what they asked
+ if (conditions is not null)
+ {
+ foreach (var condition in conditions) condition.Forward();
+ }
+
+ List? settling = null;
+ foreach (var op in recorded)
+ {
+ if (op.ForwardOutcome() is { } pending) (settling ??= []).Add(pending);
+ }
+
+ if (settling is not null && (effectiveFlags & CommandFlags.FireAndForget) == 0)
+ {
+ foreach (var pending in settling)
+ {
+ await pending.ConfigureAwait(false); // never faults: the forwarders catch and settle the proxy
+ }
+ }
+
+ return committed;
+ }
+ catch (Exception ex)
+ {
+ if (_controller.CanRetry(++attemptCount, ex, ref failover, out var delay))
+ {
+ DiscardAttempt(recorded, conditions);
+ await _controller.FailoverOrDelayAsync(delay).ConfigureAwait(false);
+ continue;
+ }
+
+ // out of road: fault the durable proxies and surface the failure to the caller
+ foreach (var op in recorded) op.Fault(ex);
+ throw;
+ }
+ }
+ }
+
+ /// Consume a discarded attempt's results and reset for the next.
+ private static void DiscardAttempt(List recorded, List? conditions)
+ {
+ foreach (var op in recorded) op.Drain();
+ if (conditions is not null)
+ {
+ foreach (var condition in conditions) condition.Reset();
+ }
+ }
+
+ // ---- recorded work -----------------------------------------------------------------------------
+ private interface IRecorded
+ {
+ /// The recorded request's flags, for the aggregate retry category.
+ CommandFlags Flags { get; }
+
+ /// Queue the recorded request onto this attempt's unit.
+ void Replay(RespTransactionExecutor attempt);
+
+ ///
+ /// Copy this attempt's outcome onto the durable proxy; the returned task is the settling still in
+ /// flight (a fire-and-forget EXEC completes before the replies land), or null when it is done.
+ ///
+ Task? ForwardOutcome();
+
+ /// Consume a discarded attempt's result, so a pooled source is released and a fault is observed.
+ void Drain();
+
+ /// Fault the durable proxy; the unit is out of attempts.
+ void Fault(Exception ex);
+
+ /// Give back the recorded request, once, after the unit has finished with it for good.
+ void Release();
+ }
+
+ /// A recorded command whose caller wants a parsed .
+ private sealed class Recorded : IRecorded
+ {
+ private readonly RespRequest _request;
+ private readonly bool _ownsRequest;
+ private readonly IRespHandler _handler;
+ private readonly TaskCompletionSource? _proxy; // null: fire-and-forget declined the reply
+ private readonly RespExecutorBase _authSource;
+ private readonly CancellationToken _cancellationToken;
+ private ValueTask _attempt;
+ private bool _hasAttempt;
+
+ public Recorded(
+ in RespRequest request,
+ bool ownsRequest,
+ IRespHandler handler,
+ TaskCompletionSource? proxy,
+ RespExecutorBase authSource,
+ CancellationToken cancellationToken)
+ {
+ _request = request;
+ _ownsRequest = ownsRequest;
+ _handler = handler;
+ _proxy = proxy;
+ _authSource = authSource;
+ _cancellationToken = cancellationToken;
+ }
+
+ public CommandFlags Flags => _request.Flags;
+
+ public void Replay(RespTransactionExecutor attempt)
+ {
+ _attempt = attempt.SendAsync(_request, _cancellationToken);
+ _hasAttempt = true;
+ }
+
+ public Task? ForwardOutcome()
+ {
+ if (_proxy is null)
+ {
+ Drain(); // fire-and-forget: nothing to carry, but a pooled source still has to be consumed
+ return null;
+ }
+
+ if (!_hasAttempt) return null; // loud failure below would hide the real bug; Replay always precedes
+ var attempt = _attempt;
+ _attempt = default;
+ _hasAttempt = false;
+ if (attempt.IsCompleted)
+ {
+ Forward(attempt);
+ return null;
+ }
+
+ return ForwardAsync(attempt);
+ }
+
+ private void Forward(ValueTask attempt)
+ {
+ RespPayload? payload = null;
+ try
+ {
+ payload = attempt.GetAwaiter().GetResult();
+ _proxy!.TrySetResult(RespExecutor.Parse(_handler, payload));
+ }
+ catch (OperationCanceledException)
+ {
+ _proxy!.TrySetCanceled();
+ }
+ catch (RedisServerException ex) when (RespExecutor.AuthFault(_authSource, ex) is { } authFault)
+ {
+ _proxy!.TrySetException(authFault);
+ }
+ catch (Exception ex)
+ {
+ _proxy!.TrySetException(ex);
+ }
+ finally
+ {
+ payload?.Release();
+ }
+ }
+
+ private async Task ForwardAsync(ValueTask attempt)
+ {
+ RespPayload? payload = null;
+ try
+ {
+ payload = await attempt.ConfigureAwait(false);
+ _proxy!.TrySetResult(RespExecutor.Parse(_handler, payload));
+ }
+ catch (OperationCanceledException)
+ {
+ _proxy!.TrySetCanceled();
+ }
+ catch (RedisServerException ex) when (RespExecutor.AuthFault(_authSource, ex) is { } authFault)
+ {
+ _proxy!.TrySetException(authFault);
+ }
+ catch (Exception ex)
+ {
+ _proxy!.TrySetException(ex);
+ }
+ finally
+ {
+ payload?.Release();
+ }
+ }
+
+ public void Drain()
+ {
+ if (!_hasAttempt) return;
+ var attempt = _attempt;
+ _attempt = default;
+ _hasAttempt = false;
+ DrainCore(attempt);
+ }
+
+ public void Fault(Exception ex)
+ {
+ Drain();
+ _proxy?.TrySetException(ex);
+ }
+
+ public void Release()
+ {
+ if (_ownsRequest) _request.Dispose();
+ }
+ }
+
+ /// A recorded command whose caller wants the raw payload, handed over intact.
+ private sealed class RecordedPayload : IRecorded
+ {
+ private readonly RespRequest _request;
+ private readonly bool _ownsRequest;
+ private readonly TaskCompletionSource? _proxy;
+ private readonly CancellationToken _cancellationToken;
+ private ValueTask _attempt;
+ private bool _hasAttempt;
+
+ public RecordedPayload(in RespRequest request, bool ownsRequest, TaskCompletionSource? proxy, CancellationToken cancellationToken)
+ {
+ _request = request;
+ _ownsRequest = ownsRequest;
+ _proxy = proxy;
+ _cancellationToken = cancellationToken;
+ }
+
+ public CommandFlags Flags => _request.Flags;
+
+ public void Replay(RespTransactionExecutor attempt)
+ {
+ _attempt = attempt.SendAsync(_request, _cancellationToken);
+ _hasAttempt = true;
+ }
+
+ public Task? ForwardOutcome()
+ {
+ if (_proxy is null)
+ {
+ Drain();
+ return null;
+ }
+
+ if (!_hasAttempt) return null;
+ var attempt = _attempt;
+ _attempt = default;
+ _hasAttempt = false;
+ if (attempt.IsCompleted)
+ {
+ Forward(attempt);
+ return null;
+ }
+
+ return ForwardAsync(attempt);
+ }
+
+ // ownership transfers to the caller: the payload is NOT released here
+ private void Forward(ValueTask attempt)
+ {
+ try
+ {
+ _proxy!.TrySetResult(attempt.GetAwaiter().GetResult());
+ }
+ catch (OperationCanceledException)
+ {
+ _proxy!.TrySetCanceled();
+ }
+ catch (Exception ex)
+ {
+ _proxy!.TrySetException(ex);
+ }
+ }
+
+ private async Task ForwardAsync(ValueTask attempt)
+ {
+ try
+ {
+ _proxy!.TrySetResult(await attempt.ConfigureAwait(false));
+ }
+ catch (OperationCanceledException)
+ {
+ _proxy!.TrySetCanceled();
+ }
+ catch (Exception ex)
+ {
+ _proxy!.TrySetException(ex);
+ }
+ }
+
+ public void Drain()
+ {
+ if (!_hasAttempt) return;
+ var attempt = _attempt;
+ _attempt = default;
+ _hasAttempt = false;
+ DrainCore(attempt);
+ }
+
+ public void Fault(Exception ex)
+ {
+ Drain();
+ _proxy?.TrySetException(ex);
+ }
+
+ public void Release()
+ {
+ if (_ownsRequest) _request.Dispose();
+ }
+ }
+
+ /// Consume a discarded attempt's result: release any payload, observe any fault.
+ private static void DrainCore(ValueTask attempt)
+ {
+ if (attempt.IsCompleted)
+ {
+ try
+ {
+ attempt.GetAwaiter().GetResult()?.Release();
+ }
+ catch
+ {
+ // a discarded attempt; the outcome that matters is the retry decision already made
+ }
+
+ return;
+ }
+
+ _ = Awaited(attempt);
+
+ static async Task Awaited(ValueTask pending)
+ {
+ try
+ {
+ (await pending.ConfigureAwait(false))?.Release();
+ }
+ catch
+ {
+ // observed; see above
+ }
+ }
+ }
+
+ /// A condition, re-issued per attempt, whose durable verdict sink hears only the final attempt.
+ private sealed class RecordedCondition
+ {
+ private readonly Condition _condition;
+ private readonly Action? _sink;
+ private bool _hasVerdict;
+ private bool _verdict;
+
+ public RecordedCondition(Condition condition, Action? sink)
+ {
+ _condition = condition;
+ _sink = sink;
+ }
+
+ public void Replay(RespTransactionExecutor attempt)
+ => attempt.AddCondition(_condition, OnVerdict);
+
+ private void OnVerdict(bool satisfied)
+ {
+ _verdict = satisfied;
+ _hasVerdict = true;
+ }
+
+ public void Reset() => _hasVerdict = false;
+
+ public void Forward()
+ {
+ if (_hasVerdict) _sink?.Invoke(_verdict);
+ }
+ }
+}
diff --git a/src/StackExchange.Redis/Availability/RetryController.cs b/src/StackExchange.Redis/Availability/RetryController.cs
index 97fe6eae28..e115c88e29 100644
--- a/src/StackExchange.Redis/Availability/RetryController.cs
+++ b/src/StackExchange.Redis/Availability/RetryController.cs
@@ -8,8 +8,8 @@ namespace StackExchange.Redis.Availability;
///
/// Holds the retry configuration derived from a (attempt counts, delays,
-/// failover gating) and makes the per-attempt retry decision. This is shared by
-/// and so the two paths apply identical policy math.
+/// failover gating) and makes the per-attempt retry decision, so that
+/// is only the shape of the loop.
///
internal sealed class RetryController
{
diff --git a/src/StackExchange.Redis/Availability/RetryDatabase.cs b/src/StackExchange.Redis/Availability/RetryDatabase.cs
deleted file mode 100644
index 7aa5fd93ee..0000000000
--- a/src/StackExchange.Redis/Availability/RetryDatabase.cs
+++ /dev/null
@@ -1,222 +0,0 @@
-using System;
-using System.Threading;
-using System.Threading.Tasks;
-using StackExchange.Redis.Interfaces;
-
-namespace StackExchange.Redis.Availability;
-
-[AutoDatabase(Replays = true)]
-internal partial class RetryDatabase : IDatabaseAsync, IInternalDatabaseAsync
- // IRedisArgsMutator <==== if we ever want to support key-mapping
-{
- ///
- public RespDatabaseContext Context => new(GetContextCore());
- // Note: we very deliberately do not include synchronous support for retry; it is inherently delay-ish -
- // which the context surface inherits: RespRetryExecutor.Send throws rather than quietly not retrying.
-
- // Note that only transient faults result in retries; this is defined by the RetryPolicy, along with
- // understanding the category. The default RetryPolicy works the same as the default CircuitBreaker.
- DatabaseFeatureFlags IInternalDatabaseAsync.GetFeatures(out string name)
- => _inner.GetFeatures(out name) | DatabaseFeatureFlags.Retry;
-
- // never: we refuse to wrap a database that carries one (see Validate)
- object? IInternalDatabaseAsync.AsyncState => null;
-
- /// The inner context, with this database's retry decorating its executor.
- ///
- ///
- /// Not the inner context as it stands. Handing that back would compile, read naturally and be
- /// wrong: commands composed from it go through the inner executor, so every call through the
- /// group surface would quietly lose the retry this wrapper exists to provide - invisibly, because the
- /// command still succeeds whenever nothing fails. It threw for exactly that reason until the retry
- /// executor existed.
- ///
- ///
- /// The controller is shared rather than rebuilt. The two paths are then not merely configured
- /// alike but configured by the same object, including the failover feature flag - which a
- /// alone does not carry, because whether failover is available is a fact
- /// about the inner database. is handed over for the same reason.
- ///
- ///
- internal RespContext GetContextCore()
- => _inner.Raw.WithExecutor(
- new RespRetryExecutor(_inner.Raw.Executor ?? ThrowNoExecutor(), _controller, GetNextFailover));
-
- private static RespExecutorBase ThrowNoExecutor() => throw new InvalidOperationException(
- "The inner database's context has no executor, so there is nothing to retry through.");
-
- ///
- RespContext IRespTarget.Context => GetContextCore();
-
- ///
- public override string ToString() => this.BuildString();
-
- private readonly IDatabaseAsync _inner;
- private readonly RetryController _controller;
-
- internal RetryPolicy Policy => _controller.Policy;
-
- public CancellationToken GetNextFailover()
- => _controller.TracksFailover ? _inner.GetNextFailover() : CancellationToken.None;
-
- public RetryDatabase(IDatabaseAsync inner, RetryPolicy policy)
- : this(inner, policy, Validate(inner))
- {
- }
-
- private static DatabaseFeatureFlags Validate(IDatabaseAsync inner)
- {
- // cannot nest retry, and cannot issue retries *inside* a batch/transaction
- var features = inner.RejectFlags(DatabaseFeatureFlags.Batch | DatabaseFeatureFlags.Transaction | DatabaseFeatureFlags.Retry);
-
- // async-state is stamped onto the task that a *single* attempt produces; a retrying database hands
- // back its own durable task that spans however many attempts it takes, so it cannot preserve the
- // state. Refuse rather than dropping it silently. See also CreateTransaction, below.
- if (inner.GetAsyncState() is not null) ThrowAsyncState();
- return features;
- }
-
- internal static void ThrowAsyncState() => throw new InvalidOperationException(
- "Retrying databases do not support asyncState; the tasks they hand back are not the tasks that were sent to the server.");
-
- // test-only: supply the inner database's feature set directly (in particular whether failover is
- // available), instead of probing a live inner - so that failover behaviour can be exercised over a
- // null inner without a full IDatabaseAsync double.
- internal RetryDatabase(IDatabaseAsync inner, RetryPolicy policy, DatabaseFeatureFlags features)
- {
- _controller = new RetryController(policy, features);
- _inner = inner;
- }
-
- ITransactionAsync IDatabaseAsync.CreateTransaction(object? asyncState)
- {
- // as per the constructor: the per-operation tasks handed out at build time are durable proxies
- // that outlive any single attempt, so they cannot carry a per-attempt async-state
- if (asyncState is not null) ThrowAsyncState();
-
- // the inner database creates the "real" (one-shot) transactions we replay against each attempt
- return new RetryTransaction(_inner, _controller);
- }
-
- public int Database => _inner.Database;
-
- public IConnectionMultiplexer Multiplexer => _inner.Multiplexer;
-
- // the generated explicit interface implementations funnel every call through these two
- // overloads: the arguments are captured in a generated state struct and replayed against
- // the inner database via a cacheable static projection (no per-call closure). Retry/failover
- // policy will live here in due course; for now it is a straight pass-through.
-
- // async counterparts (Task / Task); these get their own retry/failover policy in due course.
- // note: the state cannot be taken by `in` here (async methods forbid by-ref parameters);
- // only the projection takes it by readonly-ref, avoiding a copy per attempt
- private async Task ExecuteAsync(TState state, AutoDatabaseAsyncOperation operation)
- where TState : struct, IDisposable
- {
- /* key mapping, not used currently
- * state.MapInPlace(this); */
-
- // the capture owns a pooled copy of any Memory arguments it holds: the caller's own buffer is
- // theirs again once the call returns, and we may still be replaying long after that. Disposed here
- // rather than by the capture's creator, because this is the only point that knows the last attempt
- // is done. The IDisposable constraint makes that call constrained rather than boxed.
- try
- {
- int attempt = 0;
- TResult result;
- // note we need to capture this *before* the attempt - otherwise the failover could happen
- // between the failed attempt and fetching this, and we'd miss it
- CancellationToken failover = GetNextFailover();
- while (true)
- {
- try
- {
- result = await operation(in state, _inner).ConfigureAwait(false);
- break;
- }
- catch (Exception ex) when (_controller.CanRetry(++attempt, ex, ref failover, out var delay))
- {
- await _controller.FailoverOrDelayAsync(delay).ConfigureAwait(false);
- }
- }
-
- /* key mapping, not used currently
- // post-process results outside the loop
- return this.UnMap(state, result);*/
- return result;
- }
- finally
- {
- state.Dispose();
- }
- }
-
- private async Task ExecuteAsync(TState state, AutoDatabaseAsyncOperation operation)
- where TState : struct, IDisposable
- {
- /* key mapping, not used currently
- * state.MapInPlace(this); */
-
- // see the TResult overload
- try
- {
- int attempt = 0;
- // note we need to capture this *before* the attempt - otherwise the failover could happen
- // between the failed attempt and fetching this, and we'd miss it
- CancellationToken failover = GetNextFailover();
- while (true)
- {
- try
- {
- await operation(in state, _inner).ConfigureAwait(false);
- break;
- }
- catch (Exception ex) when (_controller.CanRetry(++attempt, ex, ref failover, out var delay))
- {
- await _controller.FailoverOrDelayAsync(delay).ConfigureAwait(false);
- }
- }
-
- // (nothing to post-process)
- }
- finally
- {
- state.Dispose();
- }
- }
-
- // forwarding is not using: these decorators must implement the interface in full, and the
- // implementation cannot be dropped while the interface declares it
- #pragma warning disable SER308 // Blocking on a task through the library's Wait helpers
- void IRedisAsync.Wait(Task task) => _inner.Wait(task);
- T IRedisAsync.Wait(Task task) => _inner.Wait(task);
- void IRedisAsync.WaitAll(Task[] tasks) => _inner.WaitAll(tasks);
- bool IRedisAsync.TryWait(Task task) => _inner.TryWait(task);
- #pragma warning restore SER308
-
- // Methods the generator deliberately skips (see AutoDatabaseGenerator.SkipMethod): the Wait
- // family, the synchronous IsConnected probe, and the streaming IEnumerable/IAsyncEnumerable scans
- // don't fit the capture-and-replay shape, so they are implemented by hand.
- // IsConnected is a straight pass-through: it is a cheap status check, not a server round-trip to retry.
- bool IDatabaseAsync.IsConnected(RedisKey key, CommandFlags flags) => _inner.IsConnected(key, flags);
-
- // routing lookup, not a replayable server command - forward straight through (no retry)
- Task IDatabaseAsync.IdentifyEndpointAsync(RedisKey key, CommandFlags flags) => _inner.IdentifyEndpointAsync(key, flags);
-
- // Scans are streaming/cursored, so they can't be captured-and-replayed as a single unit; rather than
- // failing outright we forward straight to the inner database - giving up retry, but keeping the scan working.
- System.Collections.Generic.IAsyncEnumerable IDatabaseAsync.HashScanAsync(RedisKey key, RedisValue pattern, int pageSize, long cursor, int pageOffset, CommandFlags flags) => _inner.HashScanAsync(key, pattern, pageSize, cursor, pageOffset, flags);
- System.Collections.Generic.IAsyncEnumerable IDatabaseAsync.HashScanNoValuesAsync(RedisKey key, RedisValue pattern, int pageSize, long cursor, int pageOffset, CommandFlags flags) => _inner.HashScanNoValuesAsync(key, pattern, pageSize, cursor, pageOffset, flags);
- System.Collections.Generic.IAsyncEnumerable IDatabaseAsync.SetScanAsync(RedisKey key, RedisValue pattern, int pageSize, long cursor, int pageOffset, CommandFlags flags) => _inner.SetScanAsync(key, pattern, pageSize, cursor, pageOffset, flags);
- System.Collections.Generic.IAsyncEnumerable IDatabaseAsync.VectorSetRangeEnumerateAsync(RedisKey key, RedisValue start, RedisValue end, long count, Exclude exclude, CommandFlags flags) => _inner.VectorSetRangeEnumerateAsync(key, start, end, count, exclude, flags);
- System.Collections.Generic.IAsyncEnumerable IDatabaseAsync.SortedSetScanAsync(RedisKey key, RedisValue pattern, int pageSize, long cursor, int pageOffset, CommandFlags flags) => _inner.SortedSetScanAsync(key, pattern, pageSize, cursor, pageOffset, flags);
-
- /* optional: key mapping
- RedisKey IRedisArgsMutator.Map(RedisKey key) => key;
-
- RedisChannel IRedisArgsMutator.Map(RedisChannel channel) => channel;
-
- RedisKey IRedisArgsMutator.UnMap(RedisKey key) => key;
- RedisChannel IRedisArgsMutator.UnMap(RedisChannel channel) => channel;
- */
-}
diff --git a/src/StackExchange.Redis/Availability/RetryTransaction.cs b/src/StackExchange.Redis/Availability/RetryTransaction.cs
deleted file mode 100644
index 513d4718b7..0000000000
--- a/src/StackExchange.Redis/Availability/RetryTransaction.cs
+++ /dev/null
@@ -1,537 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Runtime.CompilerServices;
-using System.Threading;
-using System.Threading.Tasks;
-using StackExchange.Redis.Interfaces;
-
-namespace StackExchange.Redis.Availability;
-
-// A retryable transaction. Unlike RetryDatabase - which replays a single captured typed call each attempt -
-// a transaction is built up across many builder calls plus an Execute, so we *record* each captured call
-// (the AutoDatabase (state, projection) pair) and hand the caller a durable, still-incomplete proxy task.
-// Only ExecuteAsync actually runs anything: for each attempt it spins up a fresh, one-shot inner transaction
-// against the underlying database (which, for a multi-group connection, resolves the currently-active member,
-// so a retry after failover lands on the new member), replays every recorded operation and constraint onto
-// it, and awaits it. On a clean execution the per-attempt results are forwarded onto the durable proxies; on
-// a transient fault the whole attempt is discarded and replayed; on terminal failure the proxies are faulted.
-//
-// ITransaction (rather than just ITransactionAsync) so that callers written against the long-standing
-// interface can move to a retrying database without rewriting their transaction code; the synchronous
-// Execute is sync-over-async (see below). Note that ITransaction : IBatch : IDatabaseAsync, so the only
-// members this adds over ITransactionAsync are the two Execute overloads.
-// Replays: the recorded operations are re-run as a unit on every attempt, and a capture is held from the
-// moment it is recorded until Execute - longer than RetryDatabase holds one - so the captured arguments must
-// be copies of the caller's memory rather than the caller's own buffer. They are released in ExecuteAsync,
-// which is the only point that knows an operation will not be replayed again; a transaction that is never
-// executed keeps its captures, and nothing here could know otherwise.
-[AutoDatabase(Replays = true)]
-internal sealed partial class RetryTransaction : IDatabaseAsync, ITransaction
-{
- ///
- public RespDatabaseContext Context => new(GetContextCore());
- // Note: the *command* surface is async-only, exactly like RetryDatabase - retrying is inherently
- // delay-ish; only the terminal Execute is offered synchronously.
- private readonly IDatabaseAsync _source;
- private readonly RetryController _controller;
-
- /// Refuse to build a context, saying why.
- ///
- /// Still refused, where 's is not. A retrying database replays one
- /// operation, so decorating its executor gives the context surface exactly the same behaviour. A
- /// retrying transaction replays the whole recorded unit - conditions, queued operations and
- /// EXEC together - and a retry executor knows nothing of that: it would re-send individual
- /// frames inside a transaction, which is not a retry of anything the caller asked for. Retry arrives
- /// here when the context surface has transactions, and not before.
- ///
- internal static RespContext GetContextCore()
- => throw new NotImplementedException(
- "The context surface does not support retrying transactions; a transaction is replayed as a "
- + "unit, which a per-frame retry executor cannot express.");
-
- ///
- RespContext IRespTarget.Context => GetContextCore();
-
- // not readonly, and null until something is recorded: ExecuteAsync takes it and clears it, so the
- // replay loop below runs over a list nothing else can still be adding to. A caller doing something
- // strange - recording from another thread while executing - then gets an empty transaction rather than
- // a collection mutated mid-enumeration, and the captures it recorded are its own to lose.
- private List? _ops;
- private List? _conditions;
- private int _executed;
- private volatile bool _watchConflict;
-
- ///
- // reports the *final* attempt's outcome: false if we eventually committed (or aborted electively),
- // true if we ran out of watch-conflict attempts still losing the race
- public bool WasWatchConflict => _watchConflict;
-
- public RetryTransaction(IDatabaseAsync source, RetryController controller)
- {
- _source = source;
- _controller = controller;
- }
-
- public int Database => _source.Database;
-
- public IConnectionMultiplexer Multiplexer => _source.Multiplexer;
-
- ///
- public override string ToString() => "retry-transaction: " + _source;
-
- // the generated explicit interface implementations funnel every builder call through these two
- // overloads, capturing the arguments in a generated state struct plus a cacheable static projection
- // (no per-call closure). Here we simply *record* them and return a durable proxy task.
- private Task ExecuteAsync(in TState state, AutoDatabaseAsyncOperation operation)
- where TState : struct, IDisposable
- {
- CheckNotExecuted();
- var op = new RecordedOp(state, operation, IsFireAndForget(in state));
- (_ops ??= new List()).Add(op);
- return op.Proxy;
- }
-
- private Task ExecuteAsync(in TState state, AutoDatabaseAsyncOperation operation)
- where TState : struct, IDisposable
- {
- CheckNotExecuted();
- var op = new RecordedVoidOp(state, operation, IsFireAndForget(in state));
- (_ops ??= new List()).Add(op);
- return op.Proxy;
- }
-
- // A fire-and-forget operation must hand back an already-completed task, because that is what a plain
- // RedisTransaction does (see its ExecuteAsync: F+F never gets a TaskCompletionSource at all). Without this
- // the durable proxy stays incomplete until Execute, so identical caller code returns instantly on a plain
- // transaction and blocks for good on a retrying one - which defeats this class's stated goal of letting
- // ITransaction code move onto a retrying database unchanged.
- //
- // The op is still recorded and replayed like any other: fire-and-forget declines the *reply*, not the
- // command. What it does not get is a proxy - see RecordedOp - so forwarding and faulting both become
- // no-ops for it, and a discarded attempt can never fault a result the caller was told not to expect.
- //
- // The flags are captured inside TState, so this is the one thing the generated struct is asked to expose
- // (IFlaggedRedisArgs). Testing a generic value against an interface boxes in IL, and this sits on every
- // queued operation - but value-type generics are not shared, so the JIT knows the exact TState and
- // compiles the whole thing to a field load with no allocator call at all (11 bytes of machine code).
- //
- // Measured on net10.0 rather than reasoned about, because none of it is obvious - bytes per call:
- //
- // `is` pattern, tier-0 ......... 24 `is` pattern, optimized ....... 0
- // cast instead of `is` ......... 24 ...with AggressiveOptimization 0
- //
- // Two findings worth keeping. Rewriting the `is` pattern as a cast does *not* avoid the box - both
- // spellings emit the same one - so the attribute below is the fix rather than a different expression.
- // And a TState *without* the interface costs nothing even in tier-0: the test folds to a constant and
- // the dead box is removed, so the states that captured no flags never pay for this at all.
-
- // skips tiering, so the above is free from the first call rather than only after tier-1 promotion
-#if NET
- [MethodImpl(MethodImplOptions.AggressiveOptimization)]
-#endif
- private static bool IsFireAndForget(in TState state)
- where TState : struct
- => state is IFlaggedRedisArgs flagged && (flagged.Flags & CommandFlags.FireAndForget) != 0;
-
- public ConditionResult AddCondition(Condition condition)
- {
- if (condition is null) throw new ArgumentNullException(nameof(condition));
- CheckNotExecuted();
- var recorded = new RecordedCondition(condition);
- (_conditions ??= new List()).Add(recorded);
- return recorded.Result;
- }
-
- public async Task ExecuteAsync(CommandFlags flags = CommandFlags.None)
- {
- if (Interlocked.CompareExchange(ref _executed, 1, 0) != 0)
- {
- throw new InvalidOperationException("This transaction has already been executed");
- }
-
- // take the recordings off the instance before replaying any of them, so the loops below run over
- // lists nothing else can still be adding to; a caller recording from another thread mid-execution
- // then gets left out rather than mutating a collection under enumeration. The operations' captured
- // arguments are released once we are done with them, however that turns out - though a transaction
- // that is never executed keeps its captures, since nothing here could know.
- var ops = _ops;
- var conditions = _conditions;
- _ops = null;
- _conditions = null;
- try
- {
- return await ExecuteAsync(flags, ops ?? EmptyOps, conditions).ConfigureAwait(false);
- }
- finally
- {
- if (ops is not null)
- {
- foreach (var op in ops) op.Release();
- }
- }
- }
-
- private static readonly List EmptyOps = new();
-
- private async Task ExecuteAsync(CommandFlags flags, List ops, List? conditions)
- {
- int attempt = 0;
- // capture the next-failover token *before* the first attempt - otherwise a failover between a
- // failed attempt and re-reading the token could be missed
- CancellationToken failover = _controller.TracksFailover ? _source.GetNextFailover() : CancellationToken.None;
-
- // watch contention gets its own budget; only meaningful when there are conditions to WATCH
- int watchAttempt = 0;
- int maxWatchAttempts = conditions is null ? 1 : _controller.MaxWatchConflictAttempts;
- while (true)
- {
- // no async-state: RetryDatabase refuses one (the durable proxies below cannot carry it)
- var inner = _source.CreateTransaction();
-
- // replay the recorded constraints and operations onto this fresh, one-shot transaction; the
- // per-attempt tasks they return are forwarded to the durable proxies only on a clean execution
- if (conditions is not null)
- {
- foreach (var c in conditions) c.Replay(inner);
- }
- foreach (var op in ops) op.Replay(inner);
-
- // inject the aggregate retry category onto the EXEC flags so the resulting fault carries it, and
- // the shared RetryPolicy/FaultContext logic gates the whole transaction exactly like one command
- var category = inner is IInternalTransaction it ? it.GetAggregateRetryCategory() : CommandFlags.CommandRetryNever;
- var effectiveFlags = (flags & ~CommandFlagsInternal.MaskRetryCategory) | category;
-
- try
- {
- bool committed = await inner.ExecuteAsync(effectiveFlags).ConfigureAwait(false);
- _watchConflict = inner.WasWatchConflict; // surfaced to our own caller, per attempt
-
- // The server rejected an EXEC we really did issue, because another connection changed a
- // watched key: the conditions still held, nothing was applied, and we simply lost a race.
- // Re-read and try again (which re-issues the WATCH constraints, so a condition that has
- // genuinely stopped holding converges on an elective abort instead of looping). This is
- // contention rather than a fault, so it neither consumes the fault budget nor waits for a
- // failover, and the side-effect category does not apply - nothing happened.
- if (!committed
- && _watchConflict
- && ++watchAttempt < maxWatchAttempts)
- {
- foreach (var op in ops) op.Observe();
- await _controller.WatchConflictDelayAsync().ConfigureAwait(false);
- continue;
- }
-
- // clean completion (committed, or aborted); forward the per-attempt outcomes onto the
- // durable proxies and we're done
- if (conditions is not null)
- {
- foreach (var c in conditions) c.ForwardSuccess();
- }
- List? settling = null;
- foreach (var op in ops)
- {
- if (op.ForwardSuccess() is { } pending) (settling ??= new()).Add(pending);
- }
-
- // SETTLED before we return, not merely scheduled - unless the caller declined the EXEC's own
- // reply, in which case there is nothing to wait for and waiting would be the opposite of what
- // they asked. Faults are swallowed here on purpose: they belong on the per-command proxy,
- // where the caller reads them, and must not fail the transaction as a whole.
- if (settling is not null && (effectiveFlags & CommandFlags.FireAndForget) == 0)
- {
- foreach (var pending in settling)
- {
- try
- {
- await pending.ConfigureAwait(false);
- }
- catch
- {
- // carried by the proxy; see above
- }
- }
- }
-
- return committed;
- }
- catch (Exception ex)
- {
- if (_controller.CanRetry(++attempt, ex, ref failover, out var delay))
- {
- // discard this attempt; observe its faulted per-attempt tasks so they don't surface as
- // unobserved, then wait / failover and replay from the recorded snapshot
- foreach (var op in ops) op.Observe();
- await _controller.FailoverOrDelayAsync(delay).ConfigureAwait(false);
- continue;
- }
-
- // out of road: fault the durable proxies and surface the failure to the caller
- foreach (var op in ops) op.Fault(ex);
- throw;
- }
- }
- }
-
- // ---- the synchronous ITransaction surface -------------------------------------------------------
- // Both are explicit implementations: they exist purely so that callers written against ITransaction can
- // move onto a retrying database, so they should be reachable only *through* that interface - internal
- // code (which has ExecuteAsync) has no business blocking, and this also keeps Execute() and
- // Execute(flags) from competing in overload resolution on the concrete type.
-
- ///
- // The IBatch shape: enqueue, and don't ask about the outcome. Mirrors RedisTransaction by mapping onto
- // fire-and-forget - which for a *retrying* transaction means there is nothing for the retry machinery to
- // observe (no reply is requested, so no fault is ever reported) and it collapses to a single attempt:
- // the trade-off fire-and-forget always makes, here extending to the retries as well.
- void IBatch.Execute() => ((ITransaction)this).Execute(CommandFlags.FireAndForget);
-
- ///
- // Sync-over-async, deliberately: retrying is inherently delay-ish, which is why the *command* surface
- // here is async-only - but a caller written against ITransaction has no async alternative for the
- // terminal Execute, and refusing it would mean such code cannot adopt a retrying database at all.
- // Blocking here is safe against a captured synchronization context: every await in ExecuteAsync (and in
- // RetryController) is ConfigureAwait(false), and the per-operation proxies complete asynchronously.
- //
- // The wait is *not* bounded by the multiplexer's SyncTimeout - the whole point of a retry is to outlast
- // the fault, so the delays between attempts are expected to exceed it. Each individual attempt is still
- // bounded by the inner connection's own timeout, so the total remains bounded by the attempt budget.
- // GetResult (rather than Wait) so the original exception surfaces, not an AggregateException wrapping it.
- bool ITransaction.Execute(CommandFlags flags) => ExecuteAsync(flags).GetAwaiter().GetResult();
-
- private void CheckNotExecuted()
- {
- if (Volatile.Read(ref _executed) != 0)
- {
- throw new InvalidOperationException("Operations cannot be added after the transaction has been executed");
- }
- }
-
- // ---- recorded work -------------------------------------------------------------------------------
- private interface IRecordedOp
- {
- void Replay(IDatabaseAsync inner);
-
- // Copy this attempt's outcome onto the durable proxy, and say whether that had to be DEFERRED: the
- // returned task is the attempt whose completion will settle the proxy, or null when it already has.
- //
- // A *replied* EXEC populates every queued operation's result before its own task completes
- // (TransactionProcessor does both while processing that one reply), so the outcome is normally
- // available inline. Two cases are not:
- //
- // - a fire-and-forget EXEC completes as soon as it has been written, with the replies still in
- // flight. Waiting there would block for a round trip the caller explicitly declined, which is
- // what F+F means and what a plain RedisTransaction does in the same situation - so the caller
- // ignores the returned task;
- // - the NEW core sets those results inline too, but publishes each caller-facing task through a
- // queued continuation, deliberately, so that a reply never runs user code on the IO thread. The
- // result is there and the Task has not caught up, which is a distinction no caller should be able
- // to see: `await ExecuteAsync()` has always meant the per-command tasks are settled. So the
- // caller waits on what is returned, unless the EXEC itself was declined.
- Task? ForwardSuccess();
- void Fault(Exception ex);
- void Observe();
-
- ///
- /// Give back anything the captured arguments own. Called once, after the transaction has finished
- /// with this operation for good - not per attempt, since every attempt replays the same capture.
- ///
- void Release();
- }
-
- private sealed class RecordedOp : IRecordedOp
- where TState : struct, IDisposable
- {
- // not readonly: releasing clears the capture in place, which a defensive copy would not
- private TState _state;
- private readonly AutoDatabaseAsyncOperation _operation;
- private readonly TaskCompletionSource? _proxy;
- private Task? _attempt;
-
- public RecordedOp(in TState state, AutoDatabaseAsyncOperation operation, bool fireAndForget)
- {
- _state = state;
- _operation = operation;
-
- // Fire-and-forget declines the reply, so there is nothing for a proxy to carry and none is built -
- // saving *both* objects, the TaskCompletionSource and the Task it creates in its own constructor,
- // on every fire-and-forget operation queued. Proxy hands back the shared completed task instead,
- // which is the same instance a plain RedisTransaction returns for this case.
- //
- // The value is default(TResult) rather than the command's own "no reply" value, which lives inside
- // the command implementation and is not reachable from here - a distinction without a difference,
- // since neither is an answer from the server.
- _proxy = fireAndForget ? null : new(TaskCreationOptions.RunContinuationsAsynchronously);
- }
-
- // the ! is an annotation artifact, not a null: TResult is unconstrained, so Task and
- // Task are the same type - Default simply spells its return the other way round
- public Task Proxy => _proxy?.Task ?? CompletedTask.Default(null)!;
-
- public void Replay(IDatabaseAsync inner) => _attempt = _operation(in _state, inner);
-
- public Task? ForwardSuccess()
- {
- // fire-and-forget: Forward guards too, so this is here to skip the continuation below rather than
- // for correctness - there is no point registering one to settle a proxy that does not exist
- if (_proxy is null) return null;
-
- // ForwardSuccess only runs after Replay, so this cannot be null; `?? throw` says that to the
- // compiler as well as the reader, and keeps the failure loud if the order ever changes
- var attempt = _attempt ?? throw new InvalidOperationException("Cannot forward a result before the operation has been replayed");
- if (attempt.IsCompleted)
- {
- Forward(attempt);
- return null;
- }
-
- ForwardLater(attempt);
- return attempt;
- }
-
- private void ForwardLater(Task attempt) => attempt.ContinueWith(
- static (completed, state) => ((RecordedOp)state!).Forward(completed),
- this,
- CancellationToken.None,
- TaskContinuationOptions.ExecuteSynchronously,
- TaskScheduler.Default);
-
- private void Forward(Task attempt)
- {
- // a null proxy is fire-and-forget; `?.` then skips the argument too, including the Exception
- // access that would otherwise observe a fault. Safe only because such an attempt is the shared
- // completed task RedisTransaction hands back for F+F, so it cannot fault - see Observe for the
- // attempts that can.
- if (attempt.IsCanceled) _proxy?.TrySetCanceled();
- else if (attempt.IsFaulted) _proxy?.TrySetException(attempt.Exception!.InnerExceptions);
- else _proxy?.TrySetResult(attempt.GetAwaiter().GetResult());
- }
-
- // observe the (faulted) inner attempt before faulting the durable proxy, so the discarded
- // per-attempt task doesn't surface as an unobserved exception
- public void Fault(Exception ex)
- {
- Observe();
- _proxy?.TrySetException(ex);
- }
-
- public void Observe() => _ = _attempt?.Exception;
-
- public void Release() => _state.Dispose();
- }
-
- private sealed class RecordedVoidOp : IRecordedOp
- where TState : struct, IDisposable
- {
- // not readonly: releasing clears the capture in place, which a defensive copy would not
- private TState _state;
- private readonly AutoDatabaseAsyncOperation _operation;
- private readonly TaskCompletionSource? _proxy;
- private Task? _attempt;
-
- public RecordedVoidOp(in TState state, AutoDatabaseAsyncOperation operation, bool fireAndForget)
- {
- _state = state;
- _operation = operation;
- _proxy = fireAndForget ? null : new(TaskCreationOptions.RunContinuationsAsynchronously); // see RecordedOp
- }
-
- public Task Proxy => _proxy?.Task ?? Task.CompletedTask;
-
- public void Replay(IDatabaseAsync inner) => _attempt = _operation(in _state, inner);
-
- public Task? ForwardSuccess()
- {
- if (_proxy is null) return null; // fire-and-forget: see RecordedOp.ForwardSuccess
-
- // ForwardSuccess only runs after Replay, so this cannot be null; `?? throw` says that to the
- // compiler as well as the reader, and keeps the failure loud if the order ever changes
- var attempt = _attempt ?? throw new InvalidOperationException("Cannot forward a result before the operation has been replayed");
- if (attempt.IsCompleted)
- {
- Forward(attempt);
- return null;
- }
-
- ForwardLater(attempt);
- return attempt;
- }
-
- private void ForwardLater(Task attempt) => attempt.ContinueWith(
- static (completed, state) => ((RecordedVoidOp)state!).Forward(completed),
- this,
- CancellationToken.None,
- TaskContinuationOptions.ExecuteSynchronously,
- TaskScheduler.Default);
-
- private void Forward(Task attempt)
- {
- // see RecordedOp.Forward for why `?.` is safe here
- if (attempt.IsCanceled) _proxy?.TrySetCanceled();
- else if (attempt.IsFaulted) _proxy?.TrySetException(attempt.Exception!.InnerExceptions);
- else _proxy?.TrySetResult(true);
- }
-
- // observe the (faulted) inner attempt before faulting the durable proxy, so the discarded
- // per-attempt task doesn't surface as an unobserved exception
- public void Fault(Exception ex)
- {
- Observe();
- _proxy?.TrySetException(ex);
- }
-
- public void Observe() => _ = _attempt?.Exception;
-
- public void Release() => _state.Dispose();
- }
-
- private sealed class RecordedCondition
- {
- private readonly Condition _condition;
- private ConditionResult? _attempt;
-
- public RecordedCondition(Condition condition)
- {
- _condition = condition;
- Result = new ConditionResult(condition);
- }
-
- // the durable result handed back to the caller from AddCondition
- public ConditionResult Result { get; }
-
- public void Replay(ITransactionAsync inner) => _attempt = inner.AddCondition(_condition);
-
- // Unlike the operations, this needs no deferral for a fire-and-forget EXEC: a conditional transaction
- // has to know whether its constraints held before it can decide between EXEC and DISCARD, so the
- // condition replies are resolved as part of writing it - even when the EXEC itself wants no reply.
- public void ForwardSuccess()
- {
- if (_attempt is not null) Result.SetSatisfied(_attempt.WasSatisfied);
- }
- }
-
- // ---- hand-implemented members the generator deliberately skips ----------------------------------
- // (the Wait family, the synchronous IsConnected probe, and the streaming scans). Wait/IsConnected are
- // straight pass-throughs; scans cannot participate in a transaction.
- // forwarding is not using: these decorators must implement the interface in full, and the
- // implementation cannot be dropped while the interface declares it
- #pragma warning disable SER308 // Blocking on a task through the library's Wait helpers
- void IRedisAsync.Wait(Task task) => _source.Wait(task);
- T IRedisAsync.Wait(Task task) => _source.Wait(task);
- void IRedisAsync.WaitAll(Task[] tasks) => _source.WaitAll(tasks);
- bool IRedisAsync.TryWait(Task task) => _source.TryWait(task);
- #pragma warning restore SER308
-
- bool IDatabaseAsync.IsConnected(RedisKey key, CommandFlags flags) => _source.IsConnected(key, flags);
-
- // routing lookup against the underlying database, not a queued transaction operation
- Task IDatabaseAsync.IdentifyEndpointAsync(RedisKey key, CommandFlags flags) => _source.IdentifyEndpointAsync(key, flags);
-
- // nested transactions are not supported (mirrors RedisTransaction)
- ITransactionAsync IDatabaseAsync.CreateTransaction(object? asyncState) => throw new NotSupportedException("Nested transactions are not supported");
-
- IAsyncEnumerable IDatabaseAsync.HashScanAsync(RedisKey key, RedisValue pattern, int pageSize, long cursor, int pageOffset, CommandFlags flags) => throw new NotSupportedException("Scans cannot be used inside a transaction");
- IAsyncEnumerable IDatabaseAsync.HashScanNoValuesAsync(RedisKey key, RedisValue pattern, int pageSize, long cursor, int pageOffset, CommandFlags flags) => throw new NotSupportedException("Scans cannot be used inside a transaction");
- IAsyncEnumerable IDatabaseAsync.SetScanAsync(RedisKey key, RedisValue pattern, int pageSize, long cursor, int pageOffset, CommandFlags flags) => throw new NotSupportedException("Scans cannot be used inside a transaction");
- IAsyncEnumerable IDatabaseAsync.VectorSetRangeEnumerateAsync(RedisKey key, RedisValue start, RedisValue end, long count, Exclude exclude, CommandFlags flags) => throw new NotSupportedException("Scans cannot be used inside a transaction");
- IAsyncEnumerable IDatabaseAsync.SortedSetScanAsync(RedisKey key, RedisValue pattern, int pageSize, long cursor, int pageOffset, CommandFlags flags) => throw new NotSupportedException("Scans cannot be used inside a transaction");
-}
diff --git a/src/StackExchange.Redis/CapturedArgs.cs b/src/StackExchange.Redis/CapturedArgs.cs
deleted file mode 100644
index dcdd6fbb3c..0000000000
--- a/src/StackExchange.Redis/CapturedArgs.cs
+++ /dev/null
@@ -1,88 +0,0 @@
-using System;
-using System.Buffers;
-using System.Runtime.CompilerServices;
-using System.Runtime.InteropServices;
-
-namespace StackExchange.Redis;
-
-///
-/// Helpers for the captured-argument structs emitted by [AutoDatabase(Replays = true)] .
-///
-///
-/// A database that replays re-invokes with the same captured arguments after the caller has regained
-/// control, and a argument still belongs to that caller - who is entitled to reuse
-/// the buffer once the call returns. So a replaying capture takes a shallow copy and gives it back when the
-/// operation is finally done with.
-///
-/// Shallow: the elements are copied, not anything they refer to. A wrapping a
-/// caller's Memory<byte> still points at the caller's bytes, so mutating *those* would still
-/// be seen by a replay. That gap closes when serialization moves to the calling thread; this covers the
-/// buffer the caller is most likely to reuse.
-///
-///
-internal static class CapturedArgs
-{
- /// Take a pooled shallow copy of a captured argument.
- /// The element type.
- /// The caller's memory to copy.
- /// A copy owned by us, to be given back via .
- public static ReadOnlyMemory Clone(ReadOnlyMemory value)
- {
- if (value.IsEmpty) return default; // nothing rented, so nothing for Release to give back
-
- var rented = ArrayPool.Shared.Rent(value.Length);
- value.Span.CopyTo(rented);
- return new ReadOnlyMemory(rented, 0, value.Length);
- }
-
- ///
- public static Memory Clone(Memory value)
- {
- if (value.IsEmpty) return default;
-
- var rented = ArrayPool.Shared.Rent(value.Length);
- value.Span.CopyTo(rented);
- return new Memory(rented, 0, value.Length);
- }
-
- /// Give a cloned argument back to the pool.
- /// The element type.
- /// The captured field, cleared as it is released.
- ///
- /// Clears the field first, so a second call has nothing to give back. Returning the same array twice is
- /// not an error the pool reports - it simply pools it twice, and two later rents then hand out the same
- /// array to different callers - so this is worth the cheek of writing through a readonly field.
- ///
- /// Sequential only: the clear is not atomic with the read. That is sufficient here because a captured
- /// state is a local within a single async flow, never shared. Note also that calling this on a
- /// defensive copy - i.e. via a readonly holder - would clear the copy and leak; the generated
- /// funnels hold their state in a plain local.
- ///
- ///
- public static void Release(in ReadOnlyMemory field)
- {
- var captured = field;
- Unsafe.AsRef(in field) = default;
- Return(captured);
- }
-
- ///
- public static void Release(in Memory field)
- {
- var captured = field;
- Unsafe.AsRef(in field) = default;
- Return(captured);
- }
-
- private static void Return(ReadOnlyMemory captured)
- {
- // note the Length check rather than a null check: an empty ReadOnlyMemory reports a non-null,
- // zero-length array through TryGetArray, so testing for null here would never be true
- if (MemoryMarshal.TryGetArray(captured, out var segment) && segment.Array is { Length: > 0 })
- {
- // cleared on return: these elements can hold references (RedisValue, RedisKeyOrValue), and a
- // pooled array would otherwise keep the caller's keys and values alive indefinitely
- ArrayPool.Shared.Return(segment.Array, clearArray: true);
- }
- }
-}
diff --git a/src/StackExchange.Redis/Contexts/RespContext.cs b/src/StackExchange.Redis/Contexts/RespContext.cs
index 635c5d171f..1d91a30342 100644
--- a/src/StackExchange.Redis/Contexts/RespContext.cs
+++ b/src/StackExchange.Redis/Contexts/RespContext.cs
@@ -352,15 +352,9 @@ internal bool TryGetFeatures(RedisCommand command, in RedisKey key, CommandFlags
// the key prefix is part of the CONTEXT here, not of the key, and it is applied at write
// time - so the key a caller hands us is not yet the key the server will see, and in a
// cluster those bytes are what pick the node. Compose first, exactly as AppendFormatted
- // will, or we would sample the version of a node that never sees this command. A null key
- // means "routes to no particular key" and stays null: prefixing it would invent one.
- if (_keyPrefix is { Length: > 0 } && !key.IsNull)
- {
- var prefixed = RedisKey.WithPrefix(_keyPrefix, key);
- return probe.TryGetFeatures(command, in prefixed, flags, out features);
- }
-
- return probe.TryGetFeatures(command, in key, flags, out features);
+ // will, or we would sample the version of a node that never sees this command.
+ var prefixed = PrefixKey(in key);
+ return probe.TryGetFeatures(command, in prefixed, flags, out features);
}
// no probe: a bare context, a test fake, a hand-wired executor. Nothing is known, and every
@@ -384,6 +378,16 @@ internal bool TryGetFeatures(RedisCommand command, in RedisKey key, CommandFlags
/// The key prefix as raw bytes, so the writer never pays a conversion per command.
internal ReadOnlySpan KeyPrefixSpan => _keyPrefix;
+ /// The key as the server will see it: the context's prefix applied, exactly as render time will.
+ /// The key being asked about.
+ ///
+ /// For the ROUTING questions - features, connectivity, endpoint identity - which take the key out
+ /// of band rather than rendering it, and so would otherwise ask about a key the server never sees.
+ /// A null key means "routes to no particular key" and stays null: prefixing it would invent one.
+ ///
+ internal RedisKey PrefixKey(in RedisKey key)
+ => _keyPrefix is { Length: > 0 } && !key.IsNull ? RedisKey.WithPrefix(_keyPrefix, key) : key;
+
/// The prefix applied to channels written through this context.
///
/// Held as a service rather than a field. As a field it was a -
@@ -496,8 +500,8 @@ internal RespContext WithDatabase(int database)
/// is true: With says the result differs in this respect, which invites "so the second call
/// wins". It does not - AppendKeyPrefix("a").AppendKeyPrefix("b") sends key k as
/// abk , and there is deliberately no way back to k . That matches nesting the
- /// KeyPrefixed* decorators, and ,
- /// which folds the two prefixes and re-wraps the inner database.
+ /// old KeyPrefixed* decorators, and is how
+ /// composes when called twice.
///
///
/// A null or empty prefix appends nothing, rather than resetting. The shipped
@@ -507,14 +511,28 @@ internal RespContext WithDatabase(int database)
///
///
internal RespContext AppendKeyPrefix(RedisKey keyPrefix)
- => new(
+ => new RespContext(
CommandMap,
_keyPrefix is null ? keyPrefix : RedisKey.WithPrefix(_keyPrefix, keyPrefix),
default,
Database,
- ServerType,
+ _serverType,
Executor,
- _services);
+ _services).WithSameTopology(this);
+
+ /// A copy of this context with no key prefix at all.
+ ///
+ /// Not an escape from isolation, and deliberately unreachable from one. "No way back to
+ /// k " (see ) is the public contract; this exists for the one
+ /// internal path that composes the prefix itself - LuaScript parameter extraction, where a
+ /// key's bytes travel in ARGV and must be prefixed at extraction, keys and arguments together. The
+ /// keys that path sends are already fully composed, so rendering them through the prefixed context
+ /// would prefix the KEYS declaration twice while ARGV carried it once.
+ ///
+ internal RespContext WithoutKeyPrefix()
+ => _keyPrefix is null
+ ? this
+ : new RespContext(CommandMap, RedisKey.Null, default, Database, _serverType, Executor, _services).WithSameTopology(this);
///
/// Returns a context whose channels carry , appended to any
diff --git a/src/StackExchange.Redis/Contexts/RespGroupExecutor.cs b/src/StackExchange.Redis/Contexts/RespGroupExecutor.cs
index 73a25c6d0b..5ee359bb5a 100644
--- a/src/StackExchange.Redis/Contexts/RespGroupExecutor.cs
+++ b/src/StackExchange.Redis/Contexts/RespGroupExecutor.cs
@@ -128,6 +128,16 @@ internal override RespPayload Send(RespRequest preamble, RespRequest request, IR
internal override RespExecutorBase? ResolveFor(in RedisKey key, RedisCommand command, CommandFlags flags)
=> _active()?.ResolveFor(in key, command, flags);
+ ///
+ ///
+ /// A router resolves one step and recurses, exactly as does. Without
+ /// this, a batch or transaction run - which resolves by its folded slot, not by a key - stopped
+ /// AT the group, whose base implementation declines to write runs, and the transaction reported
+ /// itself unexecuted without anything having been sent.
+ ///
+ internal override RespExecutorBase? ResolveForSlot(int slot, RedisCommand command, CommandFlags flags)
+ => _active()?.ResolveForSlot(slot, command, flags);
+
///
/// Null when nothing is active; the same "no honest answer" default as elsewhere.
public override ValueTask IdentifyEndpointAsync(
@@ -155,7 +165,7 @@ public override ValueTask SendAsync(RespRequest request, Cancellati
///
private RespExecutorBase ThrowUnavailable()
=> throw new RedisConnectionException(
- ConnectionFailureType.UnableToResolvePhysicalConnection,
+ ConnectionFailureType.UnableToConnect, // the facade's classification, so the two agree
CommandFlags.CommandRetryNever,
_describeUnavailable?.Invoke() ?? "No connection group member is available.",
null,
diff --git a/src/StackExchange.Redis/Contexts/RespTransaction.cs b/src/StackExchange.Redis/Contexts/RespTransaction.cs
index 6f71f2c8fd..834f484875 100644
--- a/src/StackExchange.Redis/Contexts/RespTransaction.cs
+++ b/src/StackExchange.Redis/Contexts/RespTransaction.cs
@@ -36,7 +36,28 @@ namespace StackExchange.Redis
/// exactly this distinction, and §7f, where the handshake collapsed the same way.
///
///
- internal sealed class RespTransactionExecutor : RespExecutorBase
+ ///
+ /// What needs from the executor underneath it, beyond
+ /// : the shape is shared by the plain one-connection unit
+ /// ( ) and the retrying one that replays the unit per attempt
+ /// (RespRetryTransactionExecutor ).
+ ///
+ internal interface ITransactionExecutor
+ {
+ ///
+ void AddCondition(Condition condition, Action? onVerdict = null);
+
+ ///
+ Task ExecuteAsync(CommandFlags flags = CommandFlags.None);
+
+ ///
+ bool WasWatchConflict { get; }
+
+ ///
+ CommandFlags AggregateRetryCategory { get; }
+ }
+
+ internal sealed class RespTransactionExecutor : RespExecutorBase, ITransactionExecutor
{
private readonly RespExecutorBase _inner;
private readonly RespContext _context;
@@ -89,7 +110,7 @@ internal RespTransactionExecutor(RespExecutorBase inner, RespContext? context =
/// retry: a failed condition means the state is not what you wanted, where a watch conflict means
/// it was, and somebody moved first. Only the second is worth re-reading and trying again.
///
- internal bool WasWatchConflict => _watchConflict;
+ public bool WasWatchConflict => _watchConflict;
/// Whether this transaction has been executed or discarded; either way, nothing more will be sent.
internal bool IsSent
@@ -133,7 +154,9 @@ internal override ValueTask SendTypedAsync(
var operation = RespPayloadOperation.Rent(handler, this);
try
{
- if (!Enqueue(operation, in request, cancellationToken)) return new ValueTask(default(TResult)!);
+ // the SHARED completed-default task, not a fresh default(TResult): a declined reply has
+ // nothing per-call to carry, and TaskBridge hands the backing task out untouched
+ if (!Enqueue(operation, in request, cancellationToken)) return new ValueTask(CompletedTask.Default(null)!);
}
catch (Exception ex)
{
@@ -220,7 +243,7 @@ private bool Enqueue(RespPayloadOperation operation, in RespRequest request, Can
/// surface hands the caller a ConditionResult when the condition is added and fills it in
/// later, so "which one failed?" stays answerable; a single overall bool cannot say that.
///
- internal void AddCondition(Condition condition, Action? onVerdict = null)
+ public void AddCondition(Condition condition, Action? onVerdict = null)
{
if (condition is null) throw new ArgumentNullException(nameof(condition));
lock (_sync)
@@ -240,7 +263,7 @@ internal void AddCondition(Condition condition, Action? onVerdict = null)
/// does it: they live in the conditions rather than the queue, and re-issuing them is what makes a
/// replay safe in the first place.
///
- internal CommandFlags AggregateRetryCategory
+ public CommandFlags AggregateRetryCategory
{
get
{
@@ -278,7 +301,7 @@ internal CommandFlags AggregateRetryCategory
/// Monitor handshakes on result boxes inside the write lock to get the same effect.
///
///
- internal async Task ExecuteAsync(CommandFlags flags = CommandFlags.None)
+ public async Task ExecuteAsync(CommandFlags flags = CommandFlags.None)
{
List? queue;
List? conditions;
diff --git a/src/StackExchange.Redis/Database/RedisDatabase.Scans.cs b/src/StackExchange.Redis/Database/RedisDatabase.Scans.cs
index eb6e7d8807..e7080b5dfb 100644
--- a/src/StackExchange.Redis/Database/RedisDatabase.Scans.cs
+++ b/src/StackExchange.Redis/Database/RedisDatabase.Scans.cs
@@ -10,10 +10,10 @@ namespace StackExchange.Redis;
///
///
///
-/// These are hand-written because [AutoDatabase] skips them , and it skips them for a real
-/// reason: deferred execution does not fit capture-and-replay, so an -returning
-/// member cannot be generated. That also means the generator cannot see whether they are implemented, so
-/// SER352 has never counted them - ScanGapTests is what watches this file instead.
+/// These were hand-written from the first day, because [AutoDatabase] skipped them - deferred
+/// execution does not fit capture-and-replay, so an -returning member could not
+/// be generated. That also meant the generator could not see whether they were implemented, so SER352 never
+/// counted them. Generator and rule are both gone now; ScanGapTests still watches this file.
///
///
/// Each pair of members returns the same object , because the shipped contract says a scan is both
@@ -56,29 +56,29 @@ private bool Scannable(RedisCommand command, in RedisKey key, CommandFlags flags
// ---- HSCAN --------------------------------------------------------------------------------------
///
- public IEnumerable HashScan(RedisKey key, RedisValue pattern, int pageSize, CommandFlags flags)
+ public virtual IEnumerable HashScan(RedisKey key, RedisValue pattern, int pageSize, CommandFlags flags)
=> HashScan(key, pattern, pageSize, RedisBase.CursorUtils.Origin, 0, flags);
///
- public IEnumerable HashScan(RedisKey key, RedisValue pattern = default, int pageSize = RedisBase.CursorUtils.DefaultLibraryPageSize, long cursor = RedisBase.CursorUtils.Origin, int pageOffset = 0, CommandFlags flags = CommandFlags.None)
+ public virtual IEnumerable HashScan(RedisKey key, RedisValue pattern = default, int pageSize = RedisBase.CursorUtils.DefaultLibraryPageSize, long cursor = RedisBase.CursorUtils.Origin, int pageOffset = 0, CommandFlags flags = CommandFlags.None)
=> Scannable(RedisCommand.HSCAN, key, flags)
? _inner.Hashes.ScanCore(key, pattern, pageSize, cursor, pageOffset, flags)
: Emulate(() => HashGetAllAsync(key, flags), cursor, pageOffset, RedisCommand.HSCAN, RedisCommand.HGETALL, !pattern.IsNull);
///
- public IAsyncEnumerable HashScanAsync(RedisKey key, RedisValue pattern = default, int pageSize = RedisBase.CursorUtils.DefaultLibraryPageSize, long cursor = RedisBase.CursorUtils.Origin, int pageOffset = 0, CommandFlags flags = CommandFlags.None)
+ public virtual IAsyncEnumerable HashScanAsync(RedisKey key, RedisValue pattern = default, int pageSize = RedisBase.CursorUtils.DefaultLibraryPageSize, long cursor = RedisBase.CursorUtils.Origin, int pageOffset = 0, CommandFlags flags = CommandFlags.None)
=> Scannable(RedisCommand.HSCAN, key, flags)
? _inner.Hashes.ScanCore(key, pattern, pageSize, cursor, pageOffset, flags)
: EmulateAsync(() => HashGetAllAsync(key, flags), cursor, pageOffset, RedisCommand.HSCAN, RedisCommand.HGETALL, !pattern.IsNull);
///
- public IEnumerable HashScanNoValues(RedisKey key, RedisValue pattern = default, int pageSize = RedisBase.CursorUtils.DefaultLibraryPageSize, long cursor = RedisBase.CursorUtils.Origin, int pageOffset = 0, CommandFlags flags = CommandFlags.None)
+ public virtual IEnumerable HashScanNoValues(RedisKey key, RedisValue pattern = default, int pageSize = RedisBase.CursorUtils.DefaultLibraryPageSize, long cursor = RedisBase.CursorUtils.Origin, int pageOffset = 0, CommandFlags flags = CommandFlags.None)
=> Scannable(RedisCommand.HSCAN, key, flags)
? _inner.Hashes.ScanNoValuesCore(key, pattern, pageSize, cursor, pageOffset, flags)
: Emulate(() => HashKeysAsync(key, flags), cursor, pageOffset, RedisCommand.HSCAN, RedisCommand.HKEYS, !pattern.IsNull);
///
- public IAsyncEnumerable HashScanNoValuesAsync(RedisKey key, RedisValue pattern = default, int pageSize = RedisBase.CursorUtils.DefaultLibraryPageSize, long cursor = RedisBase.CursorUtils.Origin, int pageOffset = 0, CommandFlags flags = CommandFlags.None)
+ public virtual IAsyncEnumerable HashScanNoValuesAsync(RedisKey key, RedisValue pattern = default, int pageSize = RedisBase.CursorUtils.DefaultLibraryPageSize, long cursor = RedisBase.CursorUtils.Origin, int pageOffset = 0, CommandFlags flags = CommandFlags.None)
=> Scannable(RedisCommand.HSCAN, key, flags)
? _inner.Hashes.ScanNoValuesCore(key, pattern, pageSize, cursor, pageOffset, flags)
: EmulateAsync(() => HashKeysAsync(key, flags), cursor, pageOffset, RedisCommand.HSCAN, RedisCommand.HKEYS, !pattern.IsNull);
@@ -86,17 +86,17 @@ public IAsyncEnumerable HashScanNoValuesAsync(RedisKey key, RedisVal
// ---- SSCAN --------------------------------------------------------------------------------------
///
- public IEnumerable SetScan(RedisKey key, RedisValue pattern, int pageSize, CommandFlags flags)
+ public virtual IEnumerable SetScan(RedisKey key, RedisValue pattern, int pageSize, CommandFlags flags)
=> SetScan(key, pattern, pageSize, RedisBase.CursorUtils.Origin, 0, flags);
///
- public IEnumerable SetScan(RedisKey key, RedisValue pattern = default, int pageSize = RedisBase.CursorUtils.DefaultLibraryPageSize, long cursor = RedisBase.CursorUtils.Origin, int pageOffset = 0, CommandFlags flags = CommandFlags.None)
+ public virtual IEnumerable SetScan(RedisKey key, RedisValue pattern = default, int pageSize = RedisBase.CursorUtils.DefaultLibraryPageSize, long cursor = RedisBase.CursorUtils.Origin, int pageOffset = 0, CommandFlags flags = CommandFlags.None)
=> Scannable(RedisCommand.SSCAN, key, flags)
? _inner.Sets.ScanCore(key, pattern, pageSize, cursor, pageOffset, flags)
: Emulate(() => SetMembersAsync(key, flags), cursor, pageOffset, RedisCommand.SSCAN, RedisCommand.SMEMBERS, !pattern.IsNull);
///
- public IAsyncEnumerable SetScanAsync(RedisKey key, RedisValue pattern = default, int pageSize = RedisBase.CursorUtils.DefaultLibraryPageSize, long cursor = RedisBase.CursorUtils.Origin, int pageOffset = 0, CommandFlags flags = CommandFlags.None)
+ public virtual IAsyncEnumerable SetScanAsync(RedisKey key, RedisValue pattern = default, int pageSize = RedisBase.CursorUtils.DefaultLibraryPageSize, long cursor = RedisBase.CursorUtils.Origin, int pageOffset = 0, CommandFlags flags = CommandFlags.None)
=> Scannable(RedisCommand.SSCAN, key, flags)
? _inner.Sets.ScanCore(key, pattern, pageSize, cursor, pageOffset, flags)
: EmulateAsync(() => SetMembersAsync(key, flags), cursor, pageOffset, RedisCommand.SSCAN, RedisCommand.SMEMBERS, !pattern.IsNull);
@@ -104,17 +104,17 @@ public IAsyncEnumerable SetScanAsync(RedisKey key, RedisValue patter
// ---- ZSCAN --------------------------------------------------------------------------------------
///
- public IEnumerable SortedSetScan(RedisKey key, RedisValue pattern, int pageSize, CommandFlags flags)
+ public virtual IEnumerable SortedSetScan(RedisKey key, RedisValue pattern, int pageSize, CommandFlags flags)
=> SortedSetScan(key, pattern, pageSize, RedisBase.CursorUtils.Origin, 0, flags);
///
- public IEnumerable SortedSetScan(RedisKey key, RedisValue pattern = default, int pageSize = RedisBase.CursorUtils.DefaultLibraryPageSize, long cursor = RedisBase.CursorUtils.Origin, int pageOffset = 0, CommandFlags flags = CommandFlags.None)
+ public virtual IEnumerable SortedSetScan(RedisKey key, RedisValue pattern = default, int pageSize = RedisBase.CursorUtils.DefaultLibraryPageSize, long cursor = RedisBase.CursorUtils.Origin, int pageOffset = 0, CommandFlags flags = CommandFlags.None)
=> Scannable(RedisCommand.ZSCAN, key, flags)
? _inner.SortedSets.ScanCore(key, pattern, pageSize, cursor, pageOffset, flags)
: Emulate(() => SortedSetRangeByRankWithScoresAsync(key, flags: flags), cursor, pageOffset, RedisCommand.ZSCAN, RedisCommand.ZRANGE, !pattern.IsNull);
///
- public IAsyncEnumerable SortedSetScanAsync(RedisKey key, RedisValue pattern = default, int pageSize = RedisBase.CursorUtils.DefaultLibraryPageSize, long cursor = RedisBase.CursorUtils.Origin, int pageOffset = 0, CommandFlags flags = CommandFlags.None)
+ public virtual IAsyncEnumerable SortedSetScanAsync(RedisKey key, RedisValue pattern = default, int pageSize = RedisBase.CursorUtils.DefaultLibraryPageSize, long cursor = RedisBase.CursorUtils.Origin, int pageOffset = 0, CommandFlags flags = CommandFlags.None)
=> Scannable(RedisCommand.ZSCAN, key, flags)
? _inner.SortedSets.ScanCore(key, pattern, pageSize, cursor, pageOffset, flags)
: EmulateAsync(() => SortedSetRangeByRankWithScoresAsync(key, flags: flags), cursor, pageOffset, RedisCommand.ZSCAN, RedisCommand.ZRANGE, !pattern.IsNull);
@@ -129,11 +129,11 @@ public IAsyncEnumerable SortedSetScanAsync(RedisKey key, RedisVa
// signature is shipped, and spelled `pageSize` on the context surface where it is not.
///
- public IEnumerable VectorSetRangeEnumerate(RedisKey key, RedisValue start = default, RedisValue end = default, long count = 100, Exclude exclude = Exclude.None, CommandFlags flags = CommandFlags.None)
+ public virtual IEnumerable VectorSetRangeEnumerate(RedisKey key, RedisValue start = default, RedisValue end = default, long count = 100, Exclude exclude = Exclude.None, CommandFlags flags = CommandFlags.None)
=> CanScan ? _inner.VectorSets.RangeEnumerateCore(key, start, end, count, exclude, flags) : throw NoScanning();
///
- public IAsyncEnumerable VectorSetRangeEnumerateAsync(RedisKey key, RedisValue start = default, RedisValue end = default, long count = 100, Exclude exclude = Exclude.None, CommandFlags flags = CommandFlags.None)
+ public virtual IAsyncEnumerable VectorSetRangeEnumerateAsync(RedisKey key, RedisValue start = default, RedisValue end = default, long count = 100, Exclude exclude = Exclude.None, CommandFlags flags = CommandFlags.None)
=> CanScan ? _inner.VectorSets.RangeEnumerateCore(key, start, end, count, exclude, flags) : throw NoScanning();
// ---- the pre-SCAN emulation ----------------------------------------------------------------------
diff --git a/src/StackExchange.Redis/Database/RedisDatabase.Scripts.cs b/src/StackExchange.Redis/Database/RedisDatabase.Scripts.cs
index 71bc11f959..5f1e65951c 100644
--- a/src/StackExchange.Redis/Database/RedisDatabase.Scripts.cs
+++ b/src/StackExchange.Redis/Database/RedisDatabase.Scripts.cs
@@ -107,19 +107,52 @@ public Task ScriptEvaluateReadOnlyAsync(byte[] hash, RedisKey[]? ke
///
public RedisResult ScriptEvaluate(LuaScript script, object? parameters = null, CommandFlags flags = CommandFlags.None)
- => script.Evaluate(this, parameters, null, flags);
+ => script.Evaluate(ScriptTarget(out var prefix), parameters, prefix, flags);
///
public Task ScriptEvaluateAsync(LuaScript script, object? parameters = null, CommandFlags flags = CommandFlags.None)
- => script.EvaluateAsync(this, parameters, null, flags);
+ => script.EvaluateAsync(ScriptTarget(out var prefix), parameters, prefix, flags);
///
public RedisResult ScriptEvaluate(LoadedLuaScript script, object? parameters = null, CommandFlags flags = CommandFlags.None)
- => script.Evaluate(this, parameters, withKeyPrefix: null, flags);
+ => script.Evaluate(ScriptTarget(out var prefix), parameters, prefix, flags);
///
public Task ScriptEvaluateAsync(LoadedLuaScript script, object? parameters = null, CommandFlags flags = CommandFlags.None)
- => script.EvaluateAsync(this, parameters, withKeyPrefix: null, flags);
+ => script.EvaluateAsync(ScriptTarget(out var prefix), parameters, prefix, flags);
+
+ ///
+ /// Where a evaluation should be sent from, and the key prefix its parameter
+ /// extraction must apply.
+ ///
+ /// The context's composed key prefix, or null when there is none.
+ ///
+ ///
+ /// The one place a key's bytes travel as a value. A @key hole in the script text becomes
+ /// ARGV[n] , so the key's bytes go out in the ARGV list, where the render-time key prefix cannot
+ /// see them; only the KEYS declaration is -typed. So the prefix has to be applied
+ /// where keys and arguments are extracted together - which is what ExtractParameters 's prefix
+ /// parameter is for, and what the old KeyPrefixedDatabase passed its prefix to.
+ ///
+ ///
+ /// The extraction then owns the WHOLE composition: the keys it hands back are already the bytes the
+ /// server must see, so the send goes through an unprefixed view of the same context, or render time
+ /// would prefix the KEYS declaration a second time while ARGV kept the single prefix - a mismatch the
+ /// server cannot flag, because both spell valid keys.
+ ///
+ ///
+ private IDatabase ScriptTarget(out RedisKey? keyPrefix)
+ {
+ var raw = _inner.Raw;
+ if (raw.KeyPrefixSpan.IsEmpty)
+ {
+ keyPrefix = null;
+ return this;
+ }
+
+ keyPrefix = raw.KeyPrefix;
+ return new RedisDatabase(new RespDatabaseContext(raw.WithoutKeyPrefix()), multiplexer, AsyncState);
+ }
/// The low-allocation shipped shape, which travels the same uncached route.
///
diff --git a/src/StackExchange.Redis/Database/RedisDatabase.Strings.cs b/src/StackExchange.Redis/Database/RedisDatabase.Strings.cs
index 502af10c6c..51e347de88 100644
--- a/src/StackExchange.Redis/Database/RedisDatabase.Strings.cs
+++ b/src/StackExchange.Redis/Database/RedisDatabase.Strings.cs
@@ -16,9 +16,10 @@ namespace StackExchange.Redis
/// visibly not.
///
///
- /// Implementing a member here removes it from the generated set automatically, because
- /// [AutoDatabase] skips whatever the class declares itself - so nothing has to be deleted from
- /// a list of stubs, and SER352's count falls by itself.
+ /// During the port, implementing a member here removed it from the generated set automatically,
+ /// because [AutoDatabase] skipped whatever the class declared itself - so nothing had to be
+ /// deleted from a list of stubs, and SER352's count fell by itself until both hit zero and the
+ /// generator was deleted. The per-group layout it drove remains.
///
///
/// Note how little each one is. The body is the whole implementation - no message type, no result
diff --git a/src/StackExchange.Redis/Database/RedisDatabase.cs b/src/StackExchange.Redis/Database/RedisDatabase.cs
index 64baaefb5a..73c75acd15 100644
--- a/src/StackExchange.Redis/Database/RedisDatabase.cs
+++ b/src/StackExchange.Redis/Database/RedisDatabase.cs
@@ -26,8 +26,9 @@ namespace StackExchange.Redis
/// Losing it is an improvement, not a regression. A command added to the interface used to
/// produce a generated throw and a warning; now it does not compile until it is implemented, which is
/// the same guarantee RedisDatabase has always had and a better one than a tripwire. The
- /// generator itself stays - RetryDatabase and MultiGroupDatabase are capture-and-replay
- /// wrappers, which is what it is really for.
+ /// generator itself is gone too: its last consumer, the capture-and-replay RetryTransaction ,
+ /// was replaced by RespRetryTransactionExecutor , which replays rendered frames instead of
+ /// method calls and needs nothing generated.
///
///
/// There is no fallback. This once forwarded anything not yet moved to the v3 RedisDatabase , and
@@ -90,13 +91,24 @@ internal partial class RedisDatabase(RespDatabaseContext inner, IConnectionMulti
// Found by trying the GetDatabase swap: nothing failed, which is exactly the problem.
///
- /// The cluster flag is read from the context, which is where this surface keeps that fact.
- DatabaseFeatureFlags IInternalDatabaseAsync.GetFeatures(out string name)
+ DatabaseFeatureFlags IInternalDatabaseAsync.GetFeatures(out string name) => GetFeaturesCore(out name);
+
+ /// The features and diagnostic name this database reports.
+ ///
+ /// The cluster flag is read from the context, which is where this surface keeps that fact; the
+ /// retry flag from the executor, because a retrying database IS this type over a retrying chain.
+ /// Virtual so a database with more to say - MultiGroupDatabase , which folds in the active
+ /// member's features and reports its name - can say it without re-implementing the interface.
+ ///
+ private protected virtual DatabaseFeatureFlags GetFeaturesCore(out string name)
{
name = multiplexer?.ClientName ?? "";
- return (_inner.Raw.ServerType == ServerType.Cluster
+ var features = _inner.Raw.ServerType == ServerType.Cluster
? DatabaseFeatureFlags.Cluster
- : DatabaseFeatureFlags.None) | OwnFeatures;
+ : DatabaseFeatureFlags.None;
+ if (_inner.Raw.Executor is Availability.RespRetryExecutor) features |= DatabaseFeatureFlags.Retry;
+ if (!_inner.Raw.KeyPrefixSpan.IsEmpty) features |= DatabaseFeatureFlags.KeyPrefix;
+ return features | OwnFeatures;
}
/// What THIS wrapper is, as opposed to what the connection underneath can do.
@@ -111,10 +123,12 @@ DatabaseFeatureFlags IInternalDatabaseAsync.GetFeatures(out string name)
///
///
- /// This surface has no failover notion of its own; the databases that do - RetryDatabase ,
- /// MultiGroupDatabase - sit above it and hand their own token down.
+ /// Answered by the executor chain, which is where a failover notion lives when there is one
+ /// (RespGroupExecutor , read through GetFailoverSource ). Fetched per call, never
+ /// captured: the token is replaced each time a failover happens, which is how it signals.
///
- CancellationToken IInternalDatabaseAsync.GetNextFailover() => CancellationToken.None;
+ CancellationToken IInternalDatabaseAsync.GetNextFailover()
+ => _inner.Raw.Executor?.GetFailoverSource()?.Invoke() ?? CancellationToken.None;
// The [AutoDatabase] funnels used to be here - four of them, the landing place for every member
// this class did not implement. They are gone with the attribute: there is no longer a member that
@@ -171,7 +185,7 @@ DatabaseFeatureFlags IInternalDatabaseAsync.GetFeatures(out string name)
/// The operation to wait for.
private void Wait(ValueTask pending) => SyncWait.Wait(pending, multiplexer);
- // ---- members the generator deliberately skips (see AutoDatabaseGenerator.SkipMethod) -------------
+ // ---- members the (now deleted) [AutoDatabase] generator deliberately skipped -------------
///
///
@@ -209,6 +223,17 @@ public IBatch CreateBatch(object? asyncState = null)
public ITransaction CreateTransaction(object? asyncState = null)
{
if (this is IBatch) throw new NotSupportedException("Nested transactions are not supported");
+
+ // A retrying database replays a transaction AS A UNIT - conditions, queued commands and EXEC
+ // together - which the per-frame retry executor cannot express. RespRetryTransactionExecutor
+ // records the rendered frames and the conditions, replays them into a fresh one-shot unit per
+ // attempt, and settles the durable tasks it handed out only when the unit has finished for
+ // good - which is also why asyncState works here: the tasks the caller holds are ours.
+ if (_inner.Raw.Executor is Availability.RespRetryExecutor retry)
+ {
+ return RedisTransaction.CreateRetryingTransaction(_inner, retry, multiplexer, asyncState ?? AsyncState);
+ }
+
// CanWriteTransactions, not CanWriteRuns: an executor can write a batch without being able to
// hold a connection across MULTI/EXEC, and the old Message shim was exactly that
return _inner.Raw.Executor is { CanWriteTransactions: true }
@@ -224,9 +249,17 @@ public ITransaction CreateTransaction(object? asyncState = null)
/// sent - the question is what routing would do with this key, which is the one thing the
/// context cannot answer for itself. An executor with no routing says yes; see
/// RespExecutorBase.IsConnected .
+ ///
+ /// The key is prefixed first, here and in the other routing questions: a send renders the prefix
+ /// into the frame, but these take the key out of band, and in a cluster the prefixed bytes are
+ /// what pick the node.
+ ///
///
public bool IsConnected(RedisKey key, CommandFlags flags = CommandFlags.None)
- => Router.IsConnected(in key, flags);
+ {
+ key = _inner.Raw.PrefixKey(in key);
+ return Router.IsConnected(in key, flags);
+ }
///
/// with the detail a boolean cannot carry; internal while the shape settles.
@@ -234,19 +267,22 @@ public bool IsConnected(RedisKey key, CommandFlags flags = CommandFlags.None)
/// The key whose routing is being asked about; null means "anywhere".
/// The flags that would be used; they decide primary versus replica, and so which endpoint is being asked about.
internal RespConnectionState GetConnectionState(RedisKey key, CommandFlags flags = CommandFlags.None)
- => Router.GetConnectionState(in key, flags);
+ {
+ key = _inner.Raw.PrefixKey(in key);
+ return Router.GetConnectionState(in key, flags);
+ }
internal string RouterKindForTest => Router.GetType().Name;
///
/// Off the fallback: the executor is the router, so it is the one that can answer.
public System.Net.EndPoint? IdentifyEndpoint(RedisKey key = default, CommandFlags flags = CommandFlags.None)
- => Wait(Router.IdentifyEndpointAsync(key, flags));
+ => Wait(Router.IdentifyEndpointAsync(_inner.Raw.PrefixKey(in key), flags));
///
/// Off the fallback; see the synchronous twin.
public Task IdentifyEndpointAsync(RedisKey key = default, CommandFlags flags = CommandFlags.None)
- => Router.IdentifyEndpointAsync(key, flags).AsTask(AsyncState, flags);
+ => Router.IdentifyEndpointAsync(_inner.Raw.PrefixKey(in key), flags).AsTask(AsyncState, flags);
///
///
diff --git a/src/StackExchange.Redis/Database/RedisTransaction.cs b/src/StackExchange.Redis/Database/RedisTransaction.cs
index 4dbf8a06d2..14ee0d69a9 100644
--- a/src/StackExchange.Redis/Database/RedisTransaction.cs
+++ b/src/StackExchange.Redis/Database/RedisTransaction.cs
@@ -23,7 +23,7 @@ namespace StackExchange.Redis
/// notes §3c and §7r.
///
///
- internal sealed class RedisTransaction : RedisBatch, ITransaction, IInternalTransaction
+ internal sealed class RedisTransaction : RedisBatch, ITransaction
{
///
///
@@ -32,11 +32,11 @@ internal sealed class RedisTransaction : RedisBatch, ITransaction, IInternalTran
///
private protected sealed override DatabaseFeatureFlags OwnFeatures => DatabaseFeatureFlags.Transaction;
- private readonly RespTransactionExecutor _executor;
+ private readonly ITransactionExecutor _executor;
private RedisTransaction(
RespDatabaseContext queueing,
- RespTransactionExecutor executor,
+ ITransactionExecutor executor,
IConnectionMultiplexer multiplexer,
object? asyncState)
: base(queueing, executor: null, multiplexer, asyncState)
@@ -53,6 +53,33 @@ internal static RedisTransaction CreateTransaction(RespDatabaseContext source, I
return new RedisTransaction(new RespDatabaseContext(raw.WithExecutor(executor)), executor, multiplexer, asyncState);
}
+ /// Wrap a retrying context so its transaction replays as a unit.
+ ///
+ ///
+ /// The queueing context keeps everything the database's context had EXCEPT the retry link - the
+ /// unit is what retries, so a per-frame retry inside it would re-send individual queued commands,
+ /// which is not a retry of anything the caller asked for. The retrying executor shares the
+ /// database's , so budgets and failover tracking are the
+ /// same ones a plain command sees.
+ ///
+ ///
+ /// Not reusable, where the plain transaction is : a replayed unit releases its recorded
+ /// requests when it finishes, so "execute, then queue more onto the same object" has nothing left
+ /// to compose onto. The capture-replay RetryTransaction made the same call.
+ ///
+ ///
+ internal static RedisTransaction CreateRetryingTransaction(
+ RespDatabaseContext source,
+ Availability.RespRetryExecutor retry,
+ IConnectionMultiplexer multiplexer,
+ object? asyncState)
+ {
+ var raw = source.Raw;
+ var plain = raw.WithExecutor(retry.Inner);
+ var executor = new Availability.RespRetryTransactionExecutor(retry.Inner, plain, retry.Controller);
+ return new RedisTransaction(new RespDatabaseContext(raw.WithExecutor(executor)), executor, multiplexer, asyncState);
+ }
+
///
///
/// The result is handed back now and filled in when the check is answered, which is what
@@ -72,15 +99,6 @@ public ConditionResult AddCondition(Condition condition)
///
public bool WasWatchConflict => _executor.WasWatchConflict;
- ///
- ///
- /// Without this the retry layer cannot retry a transaction at all. It asks the transaction
- /// what a replay would do, and a transaction that does not answer is assumed to be
- /// - so a transient fault the caller explicitly asked
- /// to ride out is rethrown instead, and their retry policy silently does nothing.
- ///
- CommandFlags IInternalTransaction.GetAggregateRetryCategory() => _executor.AggregateRetryCategory;
-
///
///
/// Sync-over-async, suppressed for the same reason and with the same reservations as
diff --git a/src/StackExchange.Redis/Database/TaskBridge.cs b/src/StackExchange.Redis/Database/TaskBridge.cs
index a79cdde96d..2d0981b6d9 100644
--- a/src/StackExchange.Redis/Database/TaskBridge.cs
+++ b/src/StackExchange.Redis/Database/TaskBridge.cs
@@ -59,7 +59,16 @@ internal static class TaskBridge
///
internal static Task AsTask(this ValueTask pending, object? asyncState, CommandFlags flags)
{
- if ((flags & CommandFlags.FireAndForget) != 0) asyncState = null;
+ if ((flags & CommandFlags.FireAndForget) != 0)
+ {
+ asyncState = null;
+
+ // a declined reply that is already answered travels exactly as the executor shaped it,
+ // which is what lets a transaction hand every fire-and-forget caller ONE shared completed
+ // task instead of a fresh Task.FromResult per queued command; a result-backed ValueTask
+ // comes out of AsTask as Task.FromResult anyway, so nothing else changes
+ if (pending.IsCompletedSuccessfully) return pending.AsTask();
+ }
if (pending.IsCompletedSuccessfully)
{
diff --git a/src/StackExchange.Redis/Groups/Keys.Methods.cs b/src/StackExchange.Redis/Groups/Keys.Methods.cs
index db3c812d05..e2705e4f71 100644
--- a/src/StackExchange.Redis/Groups/Keys.Methods.cs
+++ b/src/StackExchange.Redis/Groups/Keys.Methods.cs
@@ -294,9 +294,20 @@ internal static ValueTask MatchingArray(this RespKeys keys, RedisVal
/// and the command names no key, so nothing could ever invalidate an entry for it. Either one alone
/// would be enough.
///
+ /// The context has a key prefix in force.
public static ValueTask RandomAsync(this RespKeys keys, CommandFlags flags = CommandFlags.None, CancellationToken cancellationToken = default)
- => keys.Context.SendAsync(
+ {
+ // RANDOMKEY samples the WHOLE keyspace: a prefixed context cannot restrict it to its own keys,
+ // and the result comes back un-prefixed, so there is no honest answer to give. The old
+ // KeyPrefixedDatabase refused this the same way.
+ if (!keys.Context.KeyPrefixSpan.IsEmpty)
+ {
+ throw new NotSupportedException("RANDOMKEY is not supported when a key prefix is in force: it samples the entire keyspace, not the prefixed one.");
+ }
+
+ return keys.Context.SendAsync(
$"{RedisCommand.RANDOMKEY}", flags.NeverCached(), cancellationToken: cancellationToken);
+ }
/// TYPE.
/// The key command group.
diff --git a/src/StackExchange.Redis/Groups/Keys.Sort.cs b/src/StackExchange.Redis/Groups/Keys.Sort.cs
index 5828e2b705..ad78b8e3e9 100644
--- a/src/StackExchange.Redis/Groups/Keys.Sort.cs
+++ b/src/StackExchange.Redis/Groups/Keys.Sort.cs
@@ -155,6 +155,25 @@ private static ValueTask SortCore(
// pattern with a '*' looks anything up: BY nosort, a starless BY, and GET # read nothing else.
if (ReadsOtherKeys(by, get)) flags = flags.NeverCached();
+ // The patterns name keys, but travel as VALUES, so the render-time key prefix cannot see them;
+ // a prefixed context maps them here instead, exactly as the old KeyPrefixedDatabase did. The two
+ // operand spellings are exempt: BY nosort and GET # are instructions, not patterns.
+ if (!context.KeyPrefixSpan.IsEmpty)
+ {
+ if (!by.IsNull && by != RedisLiterals.nosort) by = PrefixPattern(context, by);
+ if (!get.IsEmpty)
+ {
+ var mapped = new RedisValue[get.Length];
+ for (var i = 0; i < get.Length; i++)
+ {
+ var pattern = get[i];
+ mapped[i] = pattern == RedisLiterals.HashSymbol ? pattern : PrefixPattern(context, pattern);
+ }
+
+ get = mapped;
+ }
+ }
+
var command = SelectCommand(context, in destination, in key, ref flags);
// these defaults mean "everything", and the server already assumes them
@@ -205,6 +224,10 @@ private static ValueTask SortCore(
return context.SendAsync(ref frame, flags, RespHandlers.Inbuilt.Require(), default);
}
+ /// A BY/GET pattern with the context's key prefix prepended.
+ private static RedisValue PrefixPattern(RespContext context, RedisValue pattern)
+ => RedisKey.ConcatenateBytes((byte[]?)context.KeyPrefix, null, (byte[]?)pattern);
+
/// SORT or SORT_RO, and what that means for retries and routing.
private static bool ReadsOtherKeys(RedisValue by, ReadOnlySpan get)
{
diff --git a/src/StackExchange.Redis/Interfaces/IInternalDatabaseAsync.cs b/src/StackExchange.Redis/Interfaces/IInternalDatabaseAsync.cs
index 6aea5db572..b6eb0cea38 100644
--- a/src/StackExchange.Redis/Interfaces/IInternalDatabaseAsync.cs
+++ b/src/StackExchange.Redis/Interfaces/IInternalDatabaseAsync.cs
@@ -23,26 +23,13 @@ internal interface IInternalDatabaseAsync : IDatabaseAsync
CancellationToken GetNextFailover();
///
- /// The async-state that this database stamps onto the tasks it hands out, if any; wrappers that
- /// cannot preserve it (see RetryDatabase ) need to know when one is present rather than
- /// dropping it silently.
+ /// The async-state that this database stamps onto the tasks it hands out, if any; anything that
+ /// rebuilds a database over the same context (see WithRetry ) reads it here so the state
+ /// travels rather than being dropped silently.
///
object? AsyncState { get; }
}
-///
-/// Exposes transaction-level detail needed by the retry machinery. Implemented by the concrete
-/// transaction types so a RetryTransaction can inspect the transaction it is replaying against.
-///
-internal interface IInternalTransaction
-{
- ///
- /// The most side-effecting retry category across all queued operations (excluding WATCH
- /// constraints); this describes what replaying the whole transaction would do.
- ///
- CommandFlags GetAggregateRetryCategory();
-}
-
internal static class InternalDatabaseExtension
{
internal static DatabaseFeatureFlags GetFeatures(this IDatabaseAsync database, out string name)
diff --git a/src/StackExchange.Redis/KeyspaceIsolation/DatabaseExtension.cs b/src/StackExchange.Redis/KeyspaceIsolation/DatabaseExtension.cs
index 742bc06eb7..1e145306b1 100644
--- a/src/StackExchange.Redis/KeyspaceIsolation/DatabaseExtension.cs
+++ b/src/StackExchange.Redis/KeyspaceIsolation/DatabaseExtension.cs
@@ -1,4 +1,5 @@
using System;
+using StackExchange.Redis.Interfaces;
namespace StackExchange.Redis.KeyspaceIsolation
{
@@ -54,14 +55,29 @@ public static IDatabase WithKeyPrefix(this IDatabase database, RedisKey keyPrefi
return database; // fine - you can keep using the original, then
}
- if (database is KeyPrefixedDatabase prefixed)
+ // The prefix is CONTEXT state, applied to every RedisKey at render time - so the result is a
+ // plain database over a prefixed context, not a wrapper. Nesting composes the same way the
+ // old decorators did: the prefixes concatenate, outermost call innermost on the wire.
+ //
+ // A foreign IDatabase has no context to re-point, and - unlike WithRetry, where "no retry" is
+ // merely the behaviour the caller already had - quietly not prefixing would hand every command
+ // to the WRONG KEYSPACE; that must throw rather than degrade.
+ if (database.Context is not { Raw: { Executor: not null } raw })
{
- // combine the key in advance to minimize indirection
- keyPrefix = prefixed.ToInner(keyPrefix);
- database = prefixed.Inner;
+ throw new NotSupportedException(
+ $"WithKeyPrefix requires a database from this library; {database.GetType().Name} exposes no context to apply the prefix to.");
}
- return new KeyPrefixedDatabase(database, keyPrefix.AsPrefix()!);
+ // a batch or transaction cannot be re-contexted into a plain database without silently losing
+ // what it is; take the prefix BEFORE creating it (the batch inherits the prefixed context)
+ database.RejectFlags(DatabaseFeatureFlags.Batch | DatabaseFeatureFlags.Transaction);
+
+ // the channel prefix too: the old decorator prefixed the channel on Publish, and a tenant
+ // boundary that covered keys but not the messages about them would be a silent hole
+ var context = new RespDatabaseContext(raw
+ .AppendKeyPrefix(keyPrefix)
+ .AppendChannelPrefix(new RedisChannel((byte[]?)keyPrefix, RedisChannel.PatternMode.Literal)));
+ return new RedisDatabase(context, database.Multiplexer, database.GetAsyncState());
}
}
}
diff --git a/src/StackExchange.Redis/KeyspaceIsolation/KeyPrefixed.Arrays.cs b/src/StackExchange.Redis/KeyspaceIsolation/KeyPrefixed.Arrays.cs
deleted file mode 100644
index 2ad2d6dc82..0000000000
--- a/src/StackExchange.Redis/KeyspaceIsolation/KeyPrefixed.Arrays.cs
+++ /dev/null
@@ -1,76 +0,0 @@
-using System.Threading.Tasks;
-
-// ReSharper disable once CheckNamespace
-namespace StackExchange.Redis.KeyspaceIsolation;
-
-internal partial class KeyPrefixed
-{
- public Task ArraySetAsync(RedisKey key, RedisArrayIndex index, RedisValue value, CommandFlags flags = CommandFlags.None) =>
- Inner.ArraySetAsync(ToInner(key), index, value, flags);
-
- public Task ArraySetAsync(RedisKey key, RedisArrayIndex index, RedisValue[] values, CommandFlags flags = CommandFlags.None) =>
- Inner.ArraySetAsync(ToInner(key), index, values, flags);
-
- public Task ArraySetAsync(RedisKey key, RedisArrayEntry[] values, CommandFlags flags = CommandFlags.None) =>
- Inner.ArraySetAsync(ToInner(key), values, flags);
-
- public Task ArrayGetAsync(RedisKey key, RedisArrayIndex index, CommandFlags flags = CommandFlags.None) =>
- Inner.ArrayGetAsync(ToInner(key), index, flags);
-
- public Task ArrayGetAsync(RedisKey key, RedisArrayIndex[] indices, CommandFlags flags = CommandFlags.None) =>
- Inner.ArrayGetAsync(ToInner(key), indices, flags);
-
- public Task ArrayGetRangeAsync(RedisKey key, RedisArrayIndex start, RedisArrayIndex end, CommandFlags flags = CommandFlags.None) =>
- Inner.ArrayGetRangeAsync(ToInner(key), start, end, flags);
-
- public Task ArrayLengthAsync(RedisKey key, CommandFlags flags = CommandFlags.None) =>
- Inner.ArrayLengthAsync(ToInner(key), flags);
-
- public Task ArrayCountAsync(RedisKey key, CommandFlags flags = CommandFlags.None) =>
- Inner.ArrayCountAsync(ToInner(key), flags);
-
- public Task ArrayDeleteAsync(RedisKey key, RedisArrayIndex index, CommandFlags flags = CommandFlags.None) =>
- Inner.ArrayDeleteAsync(ToInner(key), index, flags);
-
- public Task ArrayDeleteAsync(RedisKey key, RedisArrayIndex[] indices, CommandFlags flags = CommandFlags.None) =>
- Inner.ArrayDeleteAsync(ToInner(key), indices, flags);
-
- public Task ArrayDeleteRangeAsync(RedisKey key, RedisArrayIndex start, RedisArrayIndex end, CommandFlags flags = CommandFlags.None) =>
- Inner.ArrayDeleteRangeAsync(ToInner(key), start, end, flags);
-
- public Task ArrayDeleteRangeAsync(RedisKey key, RedisArrayRange[] ranges, CommandFlags flags = CommandFlags.None) =>
- Inner.ArrayDeleteRangeAsync(ToInner(key), ranges, flags);
-
- public Task ArrayScanAsync(RedisKey key, RedisArrayIndex start, RedisArrayIndex end, int limit = 0, CommandFlags flags = CommandFlags.None) =>
- Inner.ArrayScanAsync(ToInner(key), start, end, limit, flags);
-
- public Task ArrayGrepAsync(RedisKey key, ArrayGrepRequest request, CommandFlags flags = CommandFlags.None) =>
- Inner.ArrayGrepAsync(ToInner(key), request, flags);
-
- public Task ArrayOperationAsync(RedisKey key, RedisArrayIndex start, RedisArrayIndex end, ArrayOperation operation, RedisValue operand = default, CommandFlags flags = CommandFlags.None) =>
- Inner.ArrayOperationAsync(ToInner(key), start, end, operation, operand, flags);
-
- public Task ArrayRingAsync(RedisKey key, RedisArrayIndex maxLength, RedisValue value, CommandFlags flags = CommandFlags.None) =>
- Inner.ArrayRingAsync(ToInner(key), maxLength, value, flags);
-
- public Task ArrayRingAsync(RedisKey key, RedisArrayIndex maxLength, RedisValue[] values, CommandFlags flags = CommandFlags.None) =>
- Inner.ArrayRingAsync(ToInner(key), maxLength, values, flags);
-
- public Task ArrayNextAsync(RedisKey key, CommandFlags flags = CommandFlags.None) =>
- Inner.ArrayNextAsync(ToInner(key), flags);
-
- public Task ArrayInsertAsync(RedisKey key, RedisValue value, CommandFlags flags = CommandFlags.None) =>
- Inner.ArrayInsertAsync(ToInner(key), value, flags);
-
- public Task ArrayInsertAsync(RedisKey key, RedisValue[] values, CommandFlags flags = CommandFlags.None) =>
- Inner.ArrayInsertAsync(ToInner(key), values, flags);
-
- public Task ArraySeekAsync(RedisKey key, RedisArrayIndex index, CommandFlags flags = CommandFlags.None) =>
- Inner.ArraySeekAsync(ToInner(key), index, flags);
-
- public Task ArrayLastItemsAsync(RedisKey key, int count, bool reverse = false, CommandFlags flags = CommandFlags.None) =>
- Inner.ArrayLastItemsAsync(ToInner(key), count, reverse, flags);
-
- public Task ArrayInfoAsync(RedisKey key, bool full = false, CommandFlags flags = CommandFlags.None) =>
- Inner.ArrayInfoAsync(ToInner(key), full, flags);
-}
diff --git a/src/StackExchange.Redis/KeyspaceIsolation/KeyPrefixed.VectorSets.cs b/src/StackExchange.Redis/KeyspaceIsolation/KeyPrefixed.VectorSets.cs
deleted file mode 100644
index 2c4f1b0c3f..0000000000
--- a/src/StackExchange.Redis/KeyspaceIsolation/KeyPrefixed.VectorSets.cs
+++ /dev/null
@@ -1,76 +0,0 @@
-using System.Diagnostics.CodeAnalysis;
-using System.Threading.Tasks;
-using RESPite;
-
-// ReSharper disable once CheckNamespace
-namespace StackExchange.Redis.KeyspaceIsolation;
-
-internal partial class KeyPrefixed
-{
- // Vector Set operations - async methods
- public Task VectorSetAddAsync(
- RedisKey key,
- VectorSetAddRequest request,
- CommandFlags flags = CommandFlags.None) =>
- Inner.VectorSetAddAsync(ToInner(key), request, flags);
-
- public Task VectorSetLengthAsync(RedisKey key, CommandFlags flags = CommandFlags.None) =>
- Inner.VectorSetLengthAsync(ToInner(key), flags);
-
- public Task VectorSetDimensionAsync(RedisKey key, CommandFlags flags = CommandFlags.None) =>
- Inner.VectorSetDimensionAsync(ToInner(key), flags);
-
- public Task?> VectorSetGetApproximateVectorAsync(RedisKey key, RedisValue member, CommandFlags flags = CommandFlags.None) =>
- Inner.VectorSetGetApproximateVectorAsync(ToInner(key), member, flags);
-
- public Task VectorSetGetAttributesJsonAsync(RedisKey key, RedisValue member, CommandFlags flags = CommandFlags.None) =>
- Inner.VectorSetGetAttributesJsonAsync(ToInner(key), member, flags);
-
- public Task VectorSetInfoAsync(RedisKey key, CommandFlags flags = CommandFlags.None) =>
- Inner.VectorSetInfoAsync(ToInner(key), flags);
-
- public Task VectorSetContainsAsync(RedisKey key, RedisValue member, CommandFlags flags = CommandFlags.None) =>
- Inner.VectorSetContainsAsync(ToInner(key), member, flags);
-
- public Task?> VectorSetGetLinksAsync(RedisKey key, RedisValue member, CommandFlags flags = CommandFlags.None) =>
- Inner.VectorSetGetLinksAsync(ToInner(key), member, flags);
-
- public Task?> VectorSetGetLinksWithScoresAsync(RedisKey key, RedisValue member, CommandFlags flags = CommandFlags.None) =>
- Inner.VectorSetGetLinksWithScoresAsync(ToInner(key), member, flags);
-
- public Task VectorSetRandomMemberAsync(RedisKey key, CommandFlags flags = CommandFlags.None) =>
- Inner.VectorSetRandomMemberAsync(ToInner(key), flags);
-
- public Task VectorSetRandomMembersAsync(RedisKey key, long count, CommandFlags flags = CommandFlags.None) =>
- Inner.VectorSetRandomMembersAsync(ToInner(key), count, flags);
-
- public Task VectorSetRemoveAsync(RedisKey key, RedisValue member, CommandFlags flags = CommandFlags.None) =>
- Inner.VectorSetRemoveAsync(ToInner(key), member, flags);
-
- public Task VectorSetSetAttributesJsonAsync(RedisKey key, RedisValue member, string attributesJson, CommandFlags flags = CommandFlags.None) =>
- Inner.VectorSetSetAttributesJsonAsync(ToInner(key), member, attributesJson, flags);
-
- public Task?> VectorSetSimilaritySearchAsync(
- RedisKey key,
- VectorSetSimilaritySearchRequest query,
- CommandFlags flags = CommandFlags.None) =>
- Inner.VectorSetSimilaritySearchAsync(ToInner(key), query, flags);
-
- public Task?> VectorSetRangeAsync(
- RedisKey key,
- RedisValue start = default,
- RedisValue end = default,
- long count = -1,
- Exclude exclude = Exclude.None,
- CommandFlags flags = CommandFlags.None) =>
- Inner.VectorSetRangeAsync(ToInner(key), start, end, count, exclude, flags);
-
- public System.Collections.Generic.IAsyncEnumerable VectorSetRangeEnumerateAsync(
- RedisKey key,
- RedisValue start = default,
- RedisValue end = default,
- long count = 100,
- Exclude exclude = Exclude.None,
- CommandFlags flags = CommandFlags.None) =>
- Inner.VectorSetRangeEnumerateAsync(ToInner(key), start, end, count, exclude, flags);
-}
diff --git a/src/StackExchange.Redis/KeyspaceIsolation/KeyPrefixed.cs b/src/StackExchange.Redis/KeyspaceIsolation/KeyPrefixed.cs
deleted file mode 100644
index 3daa10b6d1..0000000000
--- a/src/StackExchange.Redis/KeyspaceIsolation/KeyPrefixed.cs
+++ /dev/null
@@ -1,1261 +0,0 @@
-using System;
-using System.Buffers;
-using System.Collections.Generic;
-using System.Diagnostics.CodeAnalysis;
-using System.Linq;
-using System.Net;
-using System.Threading;
-using System.Threading.Tasks;
-using StackExchange.Redis.Interfaces;
-
-namespace StackExchange.Redis.KeyspaceIsolation
-{
- internal partial class KeyPrefixed