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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,8 @@ pwsh ./build.ps1 -StartServers
# Start the Redis test servers in the background (preferred; see "Testing topology")
docker compose --file tests/RedisConfigs/docker-compose.yml up -d --wait

# Run the main test suite against one target framework (fastest inner loop)
dotnet test --project tests/StackExchange.Redis.Tests/StackExchange.Redis.Tests.csproj -c Release -f net10.0
# Run the main test suite against one target framework (fastest inner loop; Debug locally, see below)
dotnet test --project tests/StackExchange.Redis.Tests/StackExchange.Redis.Tests.csproj -c Debug -f net10.0

# Run a single test class / method (xUnit v3 on Microsoft.Testing.Platform; names are fully qualified, '*' allowed at either end)
dotnet test --project tests/StackExchange.Redis.Tests/StackExchange.Redis.Tests.csproj -f net10.0 --filter-class StackExchange.Redis.Tests.ClassName
Expand All @@ -43,6 +43,7 @@ dotnet test --solution StackExchange.Redis.slnx -c Release --no-build
dotnet pack src/StackExchange.Redis/StackExchange.Redis.csproj --no-build -c Release /p:Packing=true
```

- **Test locally in Debug.** CI builds and tests Release, so DEBUG-only checks never run there: `Debug.Assert`s, the buffer leak-tracking finalizers in RESPite, and instrumentation that some tests read (e.g. `RespRequest.HashComputations`, which pins "a request is hashed once"; those tests skip in Release). Use Release for benchmarks and when reproducing a CI failure.
- SDK is pinned (`global.json`, `allowPrerelease: false`); CI installs the 6/8/10 runtimes. `LangVersion` is 14.
- `TreatWarningsAsErrors=true` everywhere and `Features=strict` — warnings fail the build. Analyzers (StyleCop + the custom `eng` analyzer + PublicApiAnalyzers) run as part of the build.
- Analyzers run on **one TFM per project** — the newest it builds (see `Directory.Build.targets`), because they cost ~40% of a clean build otherwise and every rule is TFM-agnostic. Source generators still run on every TFM. If you touch code inside a down-level `#if`, build it with `/p:RunAnalyzers=true` to get the full per-TFM sweep. StyleCop applies to `src/` only, not `tests/` or `toys/`.
Expand Down
1 change: 1 addition & 0 deletions docs/Configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,7 @@ Additional code-only options:
- Whether exceptions include performance counter details (CPU usage, etc); note that this can be problematic on some platforms
- RequestBufferPool (`MemoryPool<byte>`) - Default: `null`
- The buffer pool to use when buffering requests; when `null`, a shared default pool is used
- Covers the socket's write buffers and the copy a request is held in until it is written (requests too large for the client's small inline buffer). Short-lived scratch space used while a request is being composed is not rented from it. A write buffer that is in use when a connection is torn down is left to the garbage collector rather than returned, so a pool that counts outstanding rentals can see one per closed connection.
- ResponseBufferPool (`MemoryPool<byte>`) - Default: `null`
- The buffer pool to use when buffering responses (and for allocating `Lease<byte>` results); when `null`, a shared default pool is used
- CircuitBreaker (`CircuitBreaker`) - Default: `null`
Expand Down
2 changes: 1 addition & 1 deletion src/StackExchange.Redis/Caching/RespClientCache.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1066,7 +1066,7 @@ public bool TryBeginFill(ref RespRequestFrame frame, int database, CommandFlags
if (_doorkeeper is not null
&& (flags & CommandFlags.CacheOptIn) == 0
&& !byPrefix
&& !_doorkeeper.SeenBefore((frame.AsLookupKey().GetHashCode() * 397) ^ database))
&& !_doorkeeper.SeenBefore((frame.Hash * 397) ^ database))
{
Interlocked.Increment(ref _refusedNotAdmitted);
fill = default;
Expand Down
1 change: 1 addition & 0 deletions src/StackExchange.Redis/Contexts/RespConnectionManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -930,6 +930,7 @@ private RespEndpointExecutor Endpoint(EndPoint endpoint)
() => ModelledServer(endpoint))
{
RerouteSubscription = operation => TryRerouteSubscription(endpoint, operation),
ConfiguredRequestBufferPool = _multiplexer.RawConfig.RequestBufferPool,
HeartbeatDriven = true,
SyncTimeoutMilliseconds = () => _multiplexer.TimeoutMilliseconds,
};
Expand Down
3 changes: 3 additions & 0 deletions src/StackExchange.Redis/Contexts/RespDatabaseExecutor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,9 @@ internal override ValueTask<TResult> SendTypedAsync<TResult>(
/// <inheritdoc/>
internal override bool CopiesRequestOnSend => true; // a view over an endpoint executor, which does

/// <inheritdoc/>
internal override System.Buffers.MemoryPool<byte>? RequestBufferPool => _inner.RequestBufferPool;

/// <inheritdoc/>
internal override ValueTask SendVoidAsync(RespRequest request, IRespHandler<bool> handler, CancellationToken cancellationToken)
=> _inner.SendVoidAsync(request, handler, Database, cancellationToken);
Expand Down
16 changes: 14 additions & 2 deletions src/StackExchange.Redis/Contexts/RespEndpointExecutor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -466,6 +466,18 @@ internal RespPayload WaitBlocking(RespPayloadOperation operation)
/// <inheritdoc/>
internal override ConnectionMultiplexer? Multiplexer => Server?.Multiplexer;

/// <inheritdoc/>
/// <remarks>Set once by the owner, from configuration; null for an executor built directly in tests.</remarks>
internal override System.Buffers.MemoryPool<byte>? RequestBufferPool => _requestBufferPool;

private System.Buffers.MemoryPool<byte>? _requestBufferPool;

/// <summary>Supplied by the owner; see <see cref="RequestBufferPool"/>.</summary>
internal System.Buffers.MemoryPool<byte>? ConfiguredRequestBufferPool
{
init => _requestBufferPool = value;
}

/// <inheritdoc/>
/// <remarks>
/// <b>A view over this connection, which is the whole point of <see cref="RespDatabaseExecutor"/>.</b>
Expand Down Expand Up @@ -955,7 +967,7 @@ internal override RespPayload Send(RespRequest preamble, RespRequest request, IR
pre.Database = Database;

var body = RespPayloadOperation.Rent();
body.Attach(request.Span, request.Flags, cancellationToken, request.Prefix);
body.Attach(request.Span, request.Flags, cancellationToken, request.Prefix, _requestBufferPool);
body.Slot = request.Slot;
body.Command = request.Command;
body.Observer = this;
Expand Down Expand Up @@ -2155,7 +2167,7 @@ private RespPayloadOperation Dispatch(
Validate(in request, database);

var operation = rented ?? RespPayloadOperation.Rent();
operation.Attach(in request, cancellationToken);
operation.Attach(in request, cancellationToken, _requestBufferPool);
operation.Database = database;
operation.Command = request.Command;
operation.Observer = this;
Expand Down
11 changes: 9 additions & 2 deletions src/StackExchange.Redis/Contexts/RespExecutor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,13 @@ internal abstract class RespExecutorBase
/// </remarks>
internal virtual ConnectionMultiplexer? Multiplexer => null;

/// <summary>Where a large request's own copy is rented from: the configured <c>RequestBufferPool</c>, or null.</summary>
/// <remarks>
/// Null means <see cref="System.Buffers.ArrayPool{T}.Shared"/>, as before. Only what an operation holds until
/// it is written comes from here; see <c>RespPayloadOperation.Attach</c> for which requests that is.
/// </remarks>
internal virtual System.Buffers.MemoryPool<byte>? RequestBufferPool => null;

/// <summary>The multiplexer a context reports publicly, as <see cref="RespContext.Multiplexer"/>.</summary>
/// <remarks>
/// <para>
Expand Down Expand Up @@ -1334,7 +1341,7 @@ public static ValueTask<TResult> SendAsync<TResult>(
// Not under CacheNoLocalServe: the in-flight reply answers a question asked before this
// one, and the wait resolves by re-probing the cache - both are what that flag declines.
if ((flags & CommandFlags.CacheNoLocalServe) == 0
&& cache.TryAwaitInFlight(request.AsLookupKey(), executor.Database, out var pending))
&& cache.TryAwaitInFlight(request.AsHashedLookupKey(), executor.Database, out var pending))
{
return AwaitShared(executor, request.Detach(flags), pending, handler, cache, context.CachePolicy, cancellationToken);
}
Expand Down Expand Up @@ -1662,7 +1669,7 @@ private static bool TryServeFromCache<TResult>(
return false;
}

if (!cache.TryGet(request.AsLookupKey(), executor.Database, policy, out var hit, out var refresh, out var reuse))
if (!cache.TryGet(request.AsHashedLookupKey(), executor.Database, policy, out var hit, out var refresh, out var reuse))
{
result = default;
return false;
Expand Down
7 changes: 5 additions & 2 deletions src/StackExchange.Redis/Contexts/RespOperationBatch.cs
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,9 @@ internal RespOperationBatchExecutor(RespExecutorBase inner, bool reusable = fals
/// <inheritdoc/>
public override int Database => _inner.Database;

/// <inheritdoc/>
internal override System.Buffers.MemoryPool<byte>? RequestBufferPool => _inner.RequestBufferPool;

/// <inheritdoc/>
internal override IConnectionMultiplexer? ExposedMultiplexer => _inner.ExposedMultiplexer;

Expand Down Expand Up @@ -215,7 +218,7 @@ internal override ValueTask SendVoidAsync(RespRequest request, IRespHandler<bool
/// <returns>False if the command is fire-and-forget, and so already answered.</returns>
private bool Enqueue(RespPayloadOperation operation, in RespRequest request, CancellationToken cancellationToken)
{
operation.Attach(request.Span, request.Flags, cancellationToken, request.Prefix);
operation.Attach(request.Span, request.Flags, cancellationToken, request.Prefix, RequestBufferPool);
operation.Diagnostics.Status = RespCommandStatus.WaitingInBacklog;
operation.Slot = request.Slot;
operation.Database = Database; // read if it is ever re-sent on its own, after a redirect
Expand Down Expand Up @@ -280,7 +283,7 @@ public override ValueTask<RespPayload> SendAsync(
head.Database = Database;

var body = RespPayloadOperation.Rent();
body.Attach(request.Span, request.Flags, cancellationToken, request.Prefix);
body.Attach(request.Span, request.Flags, cancellationToken, request.Prefix, RequestBufferPool);
body.Diagnostics.Status = RespCommandStatus.WaitingInBacklog;
body.Slot = request.Slot;
body.Database = Database;
Expand Down
38 changes: 29 additions & 9 deletions src/StackExchange.Redis/Contexts/RespPayloadOperation.cs
Original file line number Diff line number Diff line change
Expand Up @@ -605,7 +605,7 @@ protected override void OnReset()
/// </remarks>
protected override void OnRecyclable() => Return(this);

/// <summary>The operation's own request buffer, kept across pooled lives; see <see cref="Attach(in RespRequest, CancellationToken)"/>.</summary>
/// <summary>The operation's own request buffer, kept across pooled lives; see <see cref="Attach(in RespRequest, CancellationToken, MemoryPool{byte})"/>.</summary>
private byte[]? _requestBuffer;

/// <summary>Requests up to this size are copied into the operation; larger ones share the caller's buffer.</summary>
Expand All @@ -628,7 +628,7 @@ protected override void OnReset()
/// is neither copied nor retained by a pooled operation; a borrowed large one is copied into a rented array.
/// </para>
/// </remarks>
internal void Attach(in RespRequest request, CancellationToken cancellationToken)
internal void Attach(in RespRequest request, CancellationToken cancellationToken, MemoryPool<byte>? pool = null)
{
var span = request.Span;
if (span.Length <= InlineRequestLimit)
Expand All @@ -646,29 +646,49 @@ internal void Attach(in RespRequest request, CancellationToken cancellationToken
return;
}

if (request.TryShare(out var memory, out var owner))
// Shared only when no pool was configured: sharing keeps the builder's ArrayPool array alive until the
// write, and a caller who configured RequestBufferPool asked for that memory to be theirs. Copying costs
// one memcpy of a large request, and only for them; everyone else keeps the zero-copy hand-off.
if (pool is null && request.TryShare(out var memory, out var owner))
{
_flags = request.Flags;
SetRequest(memory, owner, cancellationToken);
Prefix = request.Prefix;
return;
}

Attach(request.Span, request.Flags, cancellationToken, request.Prefix);
Attach(request.Span, request.Flags, cancellationToken, request.Prefix, pool);
}

/// <summary>Begin a life for a request given as raw bytes, which are copied.</summary>
/// <param name="request">The request bytes, copied.</param>
/// <param name="flags">The request's flags.</param>
/// <param name="cancellationToken">Cancels the request.</param>
/// <param name="prefix">A frame the connection writes ahead of the request, or null; see <see cref="RespRequest.Prefix"/>.</param>
internal void Attach(ReadOnlySpan<byte> request, CommandFlags flags, CancellationToken cancellationToken, byte[]? prefix = null)
/// <param name="pool">
/// The configured <c>RequestBufferPool</c>, or null for <see cref="ArrayPool{T}.Shared"/>. A caller who configured
/// one asked to own the memory requests are buffered in, as v3 honoured it for every request it wrote; this is the
/// copy that lives until the request is written, so it is the one that has to come from there. The owner is
/// released through <c>IDisposable</c> when the last reference to the request goes, exactly once.
/// </param>
internal void Attach(ReadOnlySpan<byte> request, CommandFlags flags, CancellationToken cancellationToken, byte[]? prefix = null, MemoryPool<byte>? pool = null)
{
_flags = flags;
var pool = ArrayPool<byte>.Shared;
var buffer = pool.Rent(request.Length);
request.CopyTo(buffer);
SetRequest(new ReadOnlyMemory<byte>(buffer, 0, request.Length), pool, cancellationToken);
if (pool is not null && request.Length <= pool.MaxBufferSize)
{
var owner = pool.Rent(request.Length);
var memory = owner.Memory.Slice(0, request.Length);
request.CopyTo(memory.Span);
SetRequest(memory, owner, cancellationToken);
}
else
{
var arrays = ArrayPool<byte>.Shared;
var buffer = arrays.Rent(request.Length);
request.CopyTo(buffer);
SetRequest(new ReadOnlyMemory<byte>(buffer, 0, request.Length), arrays, cancellationToken);
}

Prefix = prefix;
}

Expand Down
5 changes: 4 additions & 1 deletion src/StackExchange.Redis/Contexts/RespTransaction.cs
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,9 @@ internal RespTransactionExecutor(RespExecutorBase inner, RespContext? context =
/// <inheritdoc/>
public override int Database => _inner.Database;

/// <inheritdoc/>
internal override System.Buffers.MemoryPool<byte>? RequestBufferPool => _inner.RequestBufferPool;

/// <inheritdoc/>
internal override IConnectionMultiplexer? ExposedMultiplexer => _inner.ExposedMultiplexer;

Expand Down Expand Up @@ -200,7 +203,7 @@ internal override ValueTask SendVoidAsync(RespRequest request, IRespHandler<bool
/// <returns>False if the command is fire-and-forget, and so already answered.</returns>
private bool Enqueue(RespPayloadOperation operation, in RespRequest request, CancellationToken cancellationToken)
{
operation.Attach(request.Span, request.Flags, cancellationToken);
operation.Attach(request.Span, request.Flags, cancellationToken, pool: RequestBufferPool);
operation.Diagnostics.Status = RespCommandStatus.WaitingInBacklog;
operation.Slot = request.Slot;
operation.Command = request.Command; // RoutingFlags asks whether any queued command is primary-only
Expand Down
Loading
Loading