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
96 changes: 92 additions & 4 deletions src/StackExchange.Redis/Contexts/RespExecutor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -729,8 +729,8 @@ internal static ValueTask<TResult> SendWithPreambleAsync<TResult>(
ref RespRequestFrame request,
CommandFlags flags,
IRespHandler<TResult> handler,
IRespPreambleGate? gate = null,
CancellationToken cancellationToken = default)
IRespPreambleGate? gate,
CancellationToken cancellationToken)
{
if (handler is null) throw new ArgumentNullException(nameof(handler));
flags = flags.WithDefaultCategory(request.Command); // see the note in SendAsync
Expand All @@ -749,6 +749,50 @@ internal static ValueTask<TResult> SendWithPreambleAsync<TResult>(
: AwaitPair(executor, head, body, gate, handler, cancellationToken);
}

/// <summary>
/// As above, and also hands back <b>a reference of the caller's own</b> to the rendered request.
/// </summary>
/// <typeparam name="TResult">What parsing the request's reply produces.</typeparam>
/// <param name="context">The context to send through.</param>
/// <param name="preamble">Written first; its reply is consumed and discarded.</param>
/// <param name="request">The request whose reply the caller wants.</param>
/// <param name="flags">The request's flags.</param>
/// <param name="handler">Turns the request's reply into a result.</param>
/// <param name="gate">If set, decides at write time whether the preamble is still needed.</param>
/// <param name="retained">The rendered request, which the caller must dispose exactly once.</param>
/// <param name="cancellationToken">Reserved; must not be cancellable yet.</param>
/// <remarks>
/// For a caller that may have to send something built from the same arguments once the reply is
/// in: a script evaluation, whose <c>NOSCRIPT</c> repair re-sends the arguments behind <c>EVAL</c>.
/// The rendered bytes are the only copy of those arguments that the caller is entitled to keep: the
/// spans it was given are borrowed, and may be back in somebody's pool by the time the reply lands.
/// Taking a reference costs a reference count, rather than copying the arguments on every call.
/// </remarks>
internal static ValueTask<TResult> SendWithPreambleAsync<TResult>(
this RespContext context,
ref RespRequestFrame preamble,
ref RespRequestFrame request,
CommandFlags flags,
IRespHandler<TResult> handler,
IRespPreambleGate? gate,
out RespRequest retained,
CancellationToken cancellationToken)
{
if (handler is null) throw new ArgumentNullException(nameof(handler));
flags = flags.WithDefaultCategory(request.Command); // see the note in SendAsync
var executor = context.Executor ?? throw new InvalidOperationException("No executor is configured for this context.");

// detached here for the same reason as above; retained before anything is sent, so the send
// cannot release the buffer first
DemandCacheFlags(flags, ref request);
var head = preamble.Detach(CommandFlags.CommandRetryAlways);
var body = request.Detach(flags, UncachedPrefix(executor, context.Cache, flags));
retained = Retain(in body);
return Blocks(context)
? SendPairBlocking(executor, head, body, gate, handler)
: AwaitPair(executor, head, body, gate, handler, cancellationToken);
}

/// <summary>
/// As above, for a preamble that is <b>already detached</b> and owns nothing poolable.
/// </summary>
Expand All @@ -771,20 +815,64 @@ internal static ValueTask<TResult> SendWithPreambleAsync<TResult>(
ref RespRequestFrame request,
CommandFlags flags,
IRespHandler<TResult> handler,
IRespPreambleGate? gate = null,
CancellationToken cancellationToken = default)
IRespPreambleGate? gate,
CancellationToken cancellationToken)
{
if (handler is null) throw new ArgumentNullException(nameof(handler));
flags = flags.WithDefaultCategory(request.Command); // see the note in SendAsync
var executor = context.Executor ?? throw new InvalidOperationException("No executor is configured for this context.");

DemandCacheFlags(flags, ref request);
var body = request.Detach(flags, UncachedPrefix(executor, context.Cache, flags));
return Blocks(context)
? SendPairBlocking(executor, preamble, body, gate, handler)
: AwaitPair(executor, preamble, body, gate, handler, cancellationToken);
}

/// <summary>
/// As above, and also hands back a reference of the caller's own to the rendered request; see the
/// overload that takes the preamble as a frame.
/// </summary>
/// <typeparam name="TResult">What parsing the request's reply produces.</typeparam>
/// <param name="context">The context to send through.</param>
/// <param name="preamble">A request over a fixed buffer - a cached rendering, typically.</param>
/// <param name="request">The request whose reply the caller wants.</param>
/// <param name="flags">The request's flags.</param>
/// <param name="handler">Turns the request's reply into a result.</param>
/// <param name="gate">If set, decides at write time whether the preamble is still needed.</param>
/// <param name="retained">The rendered request, which the caller must dispose exactly once.</param>
/// <param name="cancellationToken">Reserved; must not be cancellable yet.</param>
internal static ValueTask<TResult> SendWithPreambleAsync<TResult>(
this RespContext context,
RespRequest preamble,
ref RespRequestFrame request,
CommandFlags flags,
IRespHandler<TResult> handler,
IRespPreambleGate? gate,
out RespRequest retained,
CancellationToken cancellationToken)
{
if (handler is null) throw new ArgumentNullException(nameof(handler));
flags = flags.WithDefaultCategory(request.Command); // see the note in SendAsync
var executor = context.Executor ?? throw new InvalidOperationException("No executor is configured for this context.");

DemandCacheFlags(flags, ref request);
var body = request.Detach(flags, UncachedPrefix(executor, context.Cache, flags));
retained = Retain(in body);
return Blocks(context)
? SendPairBlocking(executor, preamble, body, gate, handler)
: AwaitPair(executor, preamble, body, gate, handler, cancellationToken);
}

/// <summary>A second reference to a freshly detached request, or a copy if it has no lease.</summary>
/// <remarks>
/// A request detached from a rendered frame always owns a lease, so the copy is a backstop rather
/// than a path: if that ever changes, the caller still gets bytes of its own rather than a borrowed
/// view of a buffer the send is about to release.
/// </remarks>
private static RespRequest Retain(in RespRequest body)
=> body.TryRetain(out var retained) ? retained : body.CopyForCacheKey();

/// <summary>
/// <see cref="AwaitPair"/> for a <see cref="RespContext.Blocking"/> context: the same cases, each sent and
/// waited for on this thread, and handed back as a completed (or faulted) task.
Expand Down
135 changes: 95 additions & 40 deletions src/StackExchange.Redis/Groups/Scripts.Methods.cs
Original file line number Diff line number Diff line change
Expand Up @@ -113,16 +113,8 @@ private static ValueTask<TResult> Evaluate<TResult>(
// context has a registry - so a SCRIPT FLUSH under a registry-less context produced a
// NOSCRIPT that nothing repaired. That is how the new core presented, having never been
// given a registry at all.
return Repairable(
SendPair(context, ref fresh, hash, keys, args, flags, readOnly, new ScriptLoadGate(script, hash), handler, cancellationToken),
context,
script,
keys,
args,
flags,
readOnly,
handler,
cancellationToken);
var sent = SendPair(context, ref fresh, hash, keys, args, flags, readOnly, new ScriptLoadGate(script, hash), handler, out var retained, cancellationToken);
return Repairable(sent, retained, context, script, keys.Length, flags, readOnly, handler, cancellationToken);
}
finally
{
Expand All @@ -131,16 +123,8 @@ private static ValueTask<TResult> Evaluate<TResult>(
}

var preamble = registry.GetPreamble(context, script, out var known, out var gate);
return Repairable(
SendPair(context, preamble, known, keys, args, flags, readOnly, gate, handler, cancellationToken),
context,
script,
keys,
args,
flags,
readOnly,
handler,
cancellationToken);
var pending = SendPair(context, preamble, known, keys, args, flags, readOnly, gate, handler, out var request, cancellationToken);
return Repairable(pending, request, context, script, keys.Length, flags, readOnly, handler, cancellationToken);
}

/// <summary>Recover from <c>NOSCRIPT</c> by re-sending the script body.</summary>
Expand All @@ -161,52 +145,121 @@ private static ValueTask<TResult> Evaluate<TResult>(
/// The belief is dropped before retrying, so the retry carries its own <c>SCRIPT LOAD</c> rather than
/// trusting the record that has just been proved wrong, and the next caller reloads too.
/// </para>
/// <para>
/// <b>The retry's arguments come from the rendered <c>EVALSHA</c>, never from the caller's spans.</b>
/// The spans are borrowed for the duration of the call, and a <see cref="RedisValue"/> over
/// <see cref="Memory{T}"/> points at the caller's buffer rather than copying it - so capturing the
/// spans (as this once did, with <c>ToArray()</c>) kept a view of memory the caller was entitled to
/// hand back to a pool the moment the call returned, and a <c>NOSCRIPT</c> then sent whatever was in
/// it by the time the reply arrived. The rendered request already owns a copy of every argument; holding
/// a reference to it costs a reference count, where the arrays cost two allocations on every call that
/// did not complete synchronously.
/// </para>
/// </remarks>
private static ValueTask<TResult> Repairable<TResult>(
ValueTask<TResult> pending,
RespRequest request,
RespContext context,
string script,
ReadOnlySpan<RedisKey> keys,
ReadOnlySpan<RedisValue> args,
int keyCount,
CommandFlags flags,
bool readOnly,
IRespHandler<TResult> handler,
CancellationToken cancellationToken)
{
if (pending.IsCompletedSuccessfully) return pending; // the overwhelmingly common case: no state machine
if (pending.IsCompletedSuccessfully)
{
request.Dispose();
return pending; // the overwhelmingly common case: no state machine
}

// the spans cannot cross an await, so the retry's arguments are captured now - only on the path
// that might need them, which is the one that has already suspended
return Awaited(pending, context, script, keys.ToArray(), args.ToArray(), flags, readOnly, handler, cancellationToken);
return Awaited(pending, request, context, script, keyCount, flags, readOnly, handler, cancellationToken);

static async ValueTask<TResult> Awaited(
ValueTask<TResult> pending,
RespRequest request,
RespContext context,
string script,
RedisKey[] keys,
RedisValue[] args,
int keyCount,
CommandFlags flags,
bool readOnly,
IRespHandler<TResult> handler,
CancellationToken cancellationToken)
{
RespRequestFrame cmd;
try
{
return await pending.ConfigureAwait(false);
try
{
return await pending.ConfigureAwait(false);
}
catch (RedisServerException ex) when (ex.Kind == RedisErrorKind.NoScript)
{
context.ScriptCache?.Forget(script);

var eval = readOnly
? ForReadOnlyScript(context.CommandMap, RedisCommand.EVAL_RO, ref flags)
: RedisCommand.EVAL;
cmd = RenderEval(context, eval, script, request.Span, keyCount);
}
}
catch (RedisServerException ex) when (ex.Kind == RedisErrorKind.NoScript)
finally
{
context.ScriptCache?.Forget(script);

var eval = readOnly
? ForReadOnlyScript(context.CommandMap, RedisCommand.EVAL_RO, ref flags)
: RedisCommand.EVAL;
var cmd = context.Render($"{eval}{script.AsRedisValue()}{(RedisValue)keys.Length}{keys}{args}");
return await context.SendAsync(ref cmd, flags, handler, cancellationToken).ConfigureAwait(false);
request.Dispose();
}

return await context.SendAsync(ref cmd, flags, handler, cancellationToken).ConfigureAwait(false);
}
}

/// <summary>
/// Render <c>EVAL</c> (or <c>EVAL_RO</c>) from the arguments of an <c>EVALSHA</c> frame we rendered.
/// </summary>
/// <param name="context">The context the original was rendered by.</param>
/// <param name="eval">The command to render.</param>
/// <param name="script">The Lua source, in place of the hash.</param>
/// <param name="evalSha">The rendered <c>EVALSHA</c>: command, hash, key count, keys, arguments.</param>
/// <param name="keyCount">How many of the trailing arguments are keys.</param>
/// <remarks>
/// <para>
/// Re-rendered rather than patched in place, so the key marks and slot come from the one place that
/// knows how to compute them. The cost is copying the arguments out of the frame, which happens only
/// on the <c>NOSCRIPT</c> path.
/// </para>
/// <para>
/// <b>Without the key prefix</b>, because the keys in the frame already carry it: rendering them
/// through the prefixed context would apply it twice, and the script would run against keys nobody
/// asked for. That is the case <see cref="RespContext.WithoutKeyPrefix"/> exists for.
/// </para>
/// </remarks>
internal static RespRequestFrame RenderEval(RespContext context, RedisCommand eval, string script, ReadOnlySpan<byte> evalSha, int keyCount)
{
// *N\r\n, then N bulk strings; our own rendering, so the shape is not in question
var i = evalSha.IndexOf((byte)'\n') + 1;
var argCount = 0;
for (var j = 1; evalSha[j] != (byte)'\r'; j++) argCount = (argCount * 10) + (evalSha[j] - (byte)'0');

const int Leading = 3; // the command, the hash and the key count
if (keyCount < 0 || argCount < Leading + keyCount) throw new InvalidOperationException("Unexpected EVALSHA frame.");

var keys = keyCount == 0 ? [] : new RedisKey[keyCount];
var args = argCount == Leading + keyCount ? [] : new RedisValue[argCount - Leading - keyCount];
for (var arg = 0; arg < argCount; arg++)
{
var bulk = 0;
var j = i + 1; // past the '$'
for (; evalSha[j] != (byte)'\r'; j++) bulk = (bulk * 10) + (evalSha[j] - (byte)'0');
var payload = evalSha.Slice(j + 2, bulk);
i = j + 2 + bulk + 2;

if (arg < Leading) continue;
if (arg < Leading + keyCount) keys[arg - Leading] = payload.ToArray();
else args[arg - Leading - keyCount] = payload.ToArray();
}

return context.WithoutKeyPrefix().Render($"{eval}{script.AsRedisValue()}{(RedisValue)keyCount}{keys}{args}");
}

/// <summary>EVALSHA_RO, preceded by SCRIPT LOAD; the read-only form of <c>Evaluate</c>.</summary>
/// <param name="scripts">The scripting command group.</param>
/// <param name="script">The Lua source; it must not write.</param>
Expand Down Expand Up @@ -235,7 +288,7 @@ public static ValueTask<RespResult> EvaluateReadOnlyAsync(
CancellationToken cancellationToken = default)
=> Evaluate(scripts, script, keys, args, flags, readOnly: true, RespHandlers.Result, cancellationToken);

/// <summary>Render the EVALSHA and send it behind the preamble.</summary>
/// <summary>Render the EVALSHA and send it behind the preamble, keeping a reference to it for <see cref="Repairable"/>.</summary>
private static ValueTask<TResult> SendPair<TResult>(
RespContext context,
ref RespRequestFrame preamble,
Expand All @@ -246,6 +299,7 @@ private static ValueTask<TResult> SendPair<TResult>(
bool readOnly,
IRespPreambleGate gate,
IRespHandler<TResult> handler,
out RespRequest retained,
CancellationToken cancellationToken)
{
var command = readOnly
Expand All @@ -255,7 +309,7 @@ private static ValueTask<TResult> SendPair<TResult>(
try
{
return context.SendWithPreambleAsync(
ref preamble, ref request, flags, handler, gate, cancellationToken);
ref preamble, ref request, flags, handler, gate, out retained, cancellationToken);
}
finally
{
Expand All @@ -278,6 +332,7 @@ private static ValueTask<TResult> SendPair<TResult>(
bool readOnly,
IRespPreambleGate gate,
IRespHandler<TResult> handler,
out RespRequest retained,
CancellationToken cancellationToken)
{
var command = readOnly
Expand All @@ -287,7 +342,7 @@ private static ValueTask<TResult> SendPair<TResult>(
try
{
return context.SendWithPreambleAsync(
preamble, ref request, flags, handler, gate, cancellationToken);
preamble, ref request, flags, handler, gate, out retained, cancellationToken);
}
finally
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using StackExchange.Redis.Protocol;
using Xunit;
Expand Down Expand Up @@ -44,7 +45,7 @@ public async Task PreamblePairsUnderLoadLeaveTheConnectionUsable()
ValueTask<bool> sent;
try
{
sent = ctx.Raw.SendWithPreambleAsync(ref preamble, ref request, CommandFlags.None, RespHandlers.Boolean, gate);
sent = ctx.Raw.SendWithPreambleAsync(ref preamble, ref request, CommandFlags.None, RespHandlers.Boolean, gate, CancellationToken.None);
}
finally
{
Expand Down
Loading
Loading