From e0b464daf4fe53aaf0d36111578e4bee1f016ee9 Mon Sep 17 00:00:00 2001 From: Ivan Tikhonov Date: Thu, 19 Nov 2026 21:54:40 +0300 Subject: [PATCH 01/10] add CachedLuaScript --- .../Groups/Scripts.MethodsNew.cs | 218 ++++++++++++++++++ .../Protocol/CachedLuaScript.cs | 62 +++++ 2 files changed, 280 insertions(+) create mode 100644 src/StackExchange.Redis/Groups/Scripts.MethodsNew.cs create mode 100644 src/StackExchange.Redis/Protocol/CachedLuaScript.cs diff --git a/src/StackExchange.Redis/Groups/Scripts.MethodsNew.cs b/src/StackExchange.Redis/Groups/Scripts.MethodsNew.cs new file mode 100644 index 000000000..f93479276 --- /dev/null +++ b/src/StackExchange.Redis/Groups/Scripts.MethodsNew.cs @@ -0,0 +1,218 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using StackExchange.Redis.Protocol; + +namespace StackExchange.Redis; + +/// +/// The scripts commands. +/// +/// +/// Here rather than in a single surface-wide class, so that a group is one place. The extension methods +/// bind by namespace, and the namespace is StackExchange.Redis, so this costs a caller nothing. +/// +public static partial class Scripts +{ + private static ValueTask EvaluateCached( + RespScripts scripts, + CachedLuaScript script, + ReadOnlySpan keys, + ReadOnlySpan args, + CommandFlags flags, + bool readOnly, + IRespHandler handler) + { + if (script is null) throw new ArgumentNullException(nameof(script)); + var context = scripts.Context; + + if ((flags & CommandFlags.NoScriptCache) != 0 + || !context.CommandMap.IsAvailable(RedisCommand.SCRIPT) + || context.Executor is { Accumulates: true }) + { + // EVAL_RO can be DISABLED in the command map, and the fallback is not just a different name: + // EVAL_RO defaults to CommandRetryReadOnly where EVAL defaults to CommandRetryWriteAccumulating, + // so swapping the command alone would quietly make a script the caller asked for read-only + // retry like a write. ForReadOnlyScript pins the category before it falls back. + var eval = readOnly + ? ForReadOnlyScript(context.CommandMap, RedisCommand.EVAL_RO, ref flags) + : RedisCommand.EVAL; + var cmd = context.Render($"{eval}{(RedisValue)script.Bytes}{(RedisValue)keys.Length}{keys}{args}"); + return context.SendAsync(ref cmd, flags, handler); + } + + var preamble = script.AsRequest(); + return Repairable( + SendPair(context, preamble, (RedisValue)script.Hash, keys, args, flags, readOnly, script, handler), + context, + script, + keys, + args, + flags, + readOnly, + handler); + } + + /// Recover from NOSCRIPT by re-sending the script body. + /// + /// + /// A belief about a server's script cache can always be wrong. SCRIPT FLUSH, a restart, + /// or a failover to a replica that never saw the load all leave the endpoint believing a script is + /// present when it is not - and the reply is NOSCRIPT. The shipped surface repairs this in + /// ResultProcessor and re-issues with the body; without the same repair the new surface turns + /// an ordinary, expected event into an exception the caller has to handle. + /// + /// + /// Only where the source is known. A caller who supplied a hash and not a script cannot be + /// repaired - there is nothing to re-send - so EvaluateHash lets the error stand, which is + /// what the remarks there already say. + /// + /// + /// The belief is dropped before retrying, so the retry carries its own SCRIPT LOAD rather than + /// trusting the record that has just been proved wrong, and the next caller reloads too. + /// + /// + private static ValueTask Repairable( + ValueTask pending, + RespContext context, + CachedLuaScript script, + ReadOnlySpan keys, + ReadOnlySpan args, + CommandFlags flags, + bool readOnly, + IRespHandler handler) + { + if (pending.IsCompletedSuccessfully) 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); + + static async ValueTask Awaited( + ValueTask pending, + RespContext context, + CachedLuaScript script, + RedisKey[] keys, + RedisValue[] args, + CommandFlags flags, + bool readOnly, + IRespHandler handler) + { + try + { + return await pending.ConfigureAwait(false); + } + catch (RedisServerException ex) when (ex.Kind == RedisErrorKind.NoScript) + { + var eval = readOnly + ? ForReadOnlyScript(context.CommandMap, RedisCommand.EVAL_RO, ref flags) + : RedisCommand.EVAL; + var cmd = context.Render($"{eval}{(RedisValue)script.Bytes}{(RedisValue)keys.Length}{keys}{args}"); + return await context.SendAsync(ref cmd, flags, handler).ConfigureAwait(false); + } + } + } + + /// EVALSHA_RO, preceded by SCRIPT LOAD; the read-only form of Evaluate. + /// The scripting command group. + /// The Lua source; it must not write. + /// The keys the script accesses; these route the command. + /// Everything else the script needs. + /// Command flags. + /// Cancels the request: one not yet written is never sent; one already written still runs on the server, and its reply is discarded. + /// + /// + /// A separate method rather than a flag on Evaluate, because it is a separate command with a + /// different retry category: EVALSHA_RO is read-only, where EVALSHA must be treated as + /// a write. Hiding that behind a boolean would let a caller's retry semantics change invisibly. + /// + /// + /// Requires a server that has the read-only forms (7.0 and later). The older surface probes + /// the connection and falls back; this does not, because the frame is chosen before the connection + /// is - which is the same constraint that puts the loaded-script belief at write time. + /// + /// + internal static ValueTask EvaluateReadOnlyAsync( + this RespScripts scripts, + CachedLuaScript script, + ReadOnlySpan keys = default, + ReadOnlySpan args = default, + CommandFlags flags = CommandFlags.None, + CancellationToken cancellationToken = default) + => EvaluateCached(scripts, script, keys, args, flags, readOnly: true, RespHandlers.Result); + + /// Render the EVALSHA and send it behind the preamble. + private static ValueTask SendPair( + RespContext context, + ref RespRequestFrame preamble, + RedisValue hash, + ReadOnlySpan keys, + ReadOnlySpan args, + CommandFlags flags, + bool readOnly, + IRespPreambleGate gate, + IRespHandler handler) + { + var command = readOnly + ? ForReadOnlyScript(context.CommandMap, RedisCommand.EVALSHA_RO, ref flags) + : RedisCommand.EVALSHA; + var request = context.Render($"{command}{hash}{(RedisValue)keys.Length}{keys}{args}"); + try + { + return context.SendWithPreambleAsync( + ref preamble, ref request, flags, handler, gate); + } + finally + { + request.Dispose(); + } + } + + /// Render the EVALSHA and send it behind a preamble the registry already owns. + /// + /// The registry's preamble owns nothing poolable - it is a fixed array that is never returned - so + /// it needs no disposal and can be handed over directly. + /// + private static ValueTask SendPair( + RespContext context, + RespRequest preamble, + RedisValue hash, + ReadOnlySpan keys, + ReadOnlySpan args, + CommandFlags flags, + bool readOnly, + IRespPreambleGate gate, + IRespHandler handler) + { + var command = readOnly + ? ForReadOnlyScript(context.CommandMap, RedisCommand.EVALSHA_RO, ref flags) + : RedisCommand.EVALSHA; + var request = context.Render($"{command}{hash}{(RedisValue)keys.Length}{keys}{args}"); + try + { + return context.SendWithPreambleAsync( + preamble, ref request, flags, handler, gate); + } + finally + { + request.Dispose(); + } + } + + /// The shipped shape, for IDatabase.ScriptEvaluate. + /// + /// Permanent, not scaffolding, and internal for the same reason the *Array shims are: + /// materialises the whole reply, which is what the low-allocation + /// exists to avoid, so new code must not be able to pick it by accident. + /// It is the same parse either way - the handler reuses RedisResult.TryCreate - so the two + /// shapes cannot drift. + /// + internal static ValueTask EvaluateCachedResult( + this RespScripts scripts, + CachedLuaScript script, + ReadOnlySpan keys, + ReadOnlySpan args, + bool readOnly, + CommandFlags flags) + => EvaluateCached(scripts, script, keys, args, flags, readOnly, RedisResultHandler.Instance); +} diff --git a/src/StackExchange.Redis/Protocol/CachedLuaScript.cs b/src/StackExchange.Redis/Protocol/CachedLuaScript.cs new file mode 100644 index 000000000..b27ffaffe --- /dev/null +++ b/src/StackExchange.Redis/Protocol/CachedLuaScript.cs @@ -0,0 +1,62 @@ +using System; +using System.Security.Cryptography; +using System.Text; +using RESPite.Buffers; +using StackExchange.Redis.Protocol; + +namespace StackExchange.Redis +{ + internal class CachedLuaScript : IRespPreambleGate + { + private readonly string _str; + private readonly byte[] _bytes; + private readonly byte[] _hash; + private readonly int _argCount; + + public string String => _str; + public byte[] Bytes => _bytes; + public int Length => _bytes.Length; + + public byte[] Hash => _hash; + + public CachedLuaScript(string script) + { + _str = script; + _bytes = Encoding.UTF8.GetBytes(script); + _hash = Encoding.ASCII.GetBytes(Sha1Hex(_bytes)); + _argCount = 0; // TODO: calc? + } + + public bool IsNeeded(IRespPreambleTarget connection) + => connection.Server is not { } endpoint || !endpoint.IsScriptLoaded(_str); + + public void OnEstablished(IRespPreambleTarget connection) + => connection.Server?.AddScript(_str, _hash); + + internal RespRequest AsRequest() + => new(_bytes, RefCountedBuffer.CreateFixed(_bytes), 0, _bytes.Length, argCount: _argCount, command: RedisCommand.SCRIPT); + + private static string Sha1Hex(byte[] bytes) + { +#if NET + Span digest = stackalloc byte[20]; + SHA1.HashData(bytes, digest); +#else + using var sha = SHA1.Create(); + var digest = sha.ComputeHash(bytes); +#endif + // one path for every target: lower-case hex is what the server reports, and `ToHexStringLower` + // is too new to use here. Not hot - and once the rendered SCRIPT LOAD frame is cached, this + // runs once per script rather than once per call. + const string Hex = "0123456789abcdef"; + var chars = new char[40]; + for (var i = 0; i < 20; i++) + { + chars[i * 2] = Hex[digest[i] >> 4]; + chars[(i * 2) + 1] = Hex[digest[i] & 0xF]; + } + + return new string(chars); + } + } +} From 906402a377d07667218816e12e03808198c7724d Mon Sep 17 00:00:00 2001 From: Ivan Tikhonov Date: Thu, 19 Nov 2026 22:53:18 +0300 Subject: [PATCH 02/10] CachedLuaScript --- .../Groups/Scripts.MethodsNew.cs | 2 +- .../Protocol/CachedLuaScript.cs | 40 ++++++++++++++----- 2 files changed, 30 insertions(+), 12 deletions(-) diff --git a/src/StackExchange.Redis/Groups/Scripts.MethodsNew.cs b/src/StackExchange.Redis/Groups/Scripts.MethodsNew.cs index f93479276..ff8cc62aa 100644 --- a/src/StackExchange.Redis/Groups/Scripts.MethodsNew.cs +++ b/src/StackExchange.Redis/Groups/Scripts.MethodsNew.cs @@ -41,7 +41,7 @@ private static ValueTask EvaluateCached( return context.SendAsync(ref cmd, flags, handler); } - var preamble = script.AsRequest(); + var preamble = script.AsLoadRequest(); return Repairable( SendPair(context, preamble, (RedisValue)script.Hash, keys, args, flags, readOnly, script, handler), context, diff --git a/src/StackExchange.Redis/Protocol/CachedLuaScript.cs b/src/StackExchange.Redis/Protocol/CachedLuaScript.cs index b27ffaffe..a268753f5 100644 --- a/src/StackExchange.Redis/Protocol/CachedLuaScript.cs +++ b/src/StackExchange.Redis/Protocol/CachedLuaScript.cs @@ -1,4 +1,6 @@ using System; +using System.Buffers.Text; +using System.Diagnostics; using System.Security.Cryptography; using System.Text; using RESPite.Buffers; @@ -8,23 +10,39 @@ namespace StackExchange.Redis { internal class CachedLuaScript : IRespPreambleGate { + private const int LoadArgCount = 3; + private const int Start = 33; + private readonly string _str; - private readonly byte[] _bytes; + private readonly byte[] _request; private readonly byte[] _hash; - private readonly int _argCount; public string String => _str; - public byte[] Bytes => _bytes; - public int Length => _bytes.Length; + public ReadOnlyMemory Bytes => _request.AsMemory(Start); + public int RequestLength => _request.Length; public byte[] Hash => _hash; - public CachedLuaScript(string script) + public CachedLuaScript(byte[] bytes) { - _str = script; - _bytes = Encoding.UTF8.GetBytes(script); - _hash = Encoding.ASCII.GetBytes(Sha1Hex(_bytes)); - _argCount = 0; // TODO: calc? + _str = Encoding.UTF8.GetString(bytes); + _hash = Encoding.ASCII.GetBytes(Sha1Hex(bytes)); + ReadOnlySpan header = "*3\r\n$6\r\nSCRIPT\r\n$4\r\nLOAD\r\n"u8; + Span utf8len = stackalloc byte[10]; +#if NET + var status = bytes.Length.TryFormat(utf8len, out var written); +#else + var status = Utf8Formatter.TryFormat(bytes.Length, utf8len, out var written); +#endif + Debug.Assert(status); + var request = new byte[header.Length + written + 2 + bytes.Length]; + header.CopyTo(request); + + utf8len.CopyTo(request.AsSpan(header.Length)); + "\r\n"u8.CopyTo(request.AsSpan(header.Length + written)); + bytes.CopyTo(request.AsSpan(header.Length + written + 2)); + + _request = request; } public bool IsNeeded(IRespPreambleTarget connection) @@ -33,8 +51,8 @@ public bool IsNeeded(IRespPreambleTarget connection) public void OnEstablished(IRespPreambleTarget connection) => connection.Server?.AddScript(_str, _hash); - internal RespRequest AsRequest() - => new(_bytes, RefCountedBuffer.CreateFixed(_bytes), 0, _bytes.Length, argCount: _argCount, command: RedisCommand.SCRIPT); + internal RespRequest AsLoadRequest() + => new(_request, RefCountedBuffer.CreateFixed(_request), 0, _request.Length, argCount: LoadArgCount, command: RedisCommand.SCRIPT); private static string Sha1Hex(byte[] bytes) { From d05f2edfcbb4d3a84daf4c523d8916f1c28aff90 Mon Sep 17 00:00:00 2001 From: Ivan Tikhonov Date: Thu, 19 Nov 2026 22:55:23 +0300 Subject: [PATCH 03/10] _start --- .../Protocol/CachedLuaScript.cs | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/src/StackExchange.Redis/Protocol/CachedLuaScript.cs b/src/StackExchange.Redis/Protocol/CachedLuaScript.cs index a268753f5..f2ada7df4 100644 --- a/src/StackExchange.Redis/Protocol/CachedLuaScript.cs +++ b/src/StackExchange.Redis/Protocol/CachedLuaScript.cs @@ -11,14 +11,13 @@ namespace StackExchange.Redis internal class CachedLuaScript : IRespPreambleGate { private const int LoadArgCount = 3; - private const int Start = 33; - private readonly string _str; private readonly byte[] _request; private readonly byte[] _hash; + private readonly int _start; public string String => _str; - public ReadOnlyMemory Bytes => _request.AsMemory(Start); + public ReadOnlyMemory Bytes => _request.AsMemory(_start); public int RequestLength => _request.Length; public byte[] Hash => _hash; @@ -38,11 +37,17 @@ public CachedLuaScript(byte[] bytes) var request = new byte[header.Length + written + 2 + bytes.Length]; header.CopyTo(request); - utf8len.CopyTo(request.AsSpan(header.Length)); - "\r\n"u8.CopyTo(request.AsSpan(header.Length + written)); - bytes.CopyTo(request.AsSpan(header.Length + written + 2)); + var start = header.Length; + utf8len.CopyTo(request.AsSpan(start)); + start += written; + + "\r\n"u8.CopyTo(request.AsSpan(start)); + start += 2; + + bytes.CopyTo(request.AsSpan(start)); _request = request; + _start = start; } public bool IsNeeded(IRespPreambleTarget connection) From 89c9ddaffd0ae14c6b0578a7d6f2ed61f7aae210 Mon Sep 17 00:00:00 2001 From: Ivan Tikhonov Date: Thu, 19 Nov 2026 23:02:06 +0300 Subject: [PATCH 04/10] EvaluateCached public --- .../Groups/Scripts.MethodsNew.cs | 32 ++++++++++++++++++- .../Protocol/CachedLuaScript.cs | 26 ++++++++++++--- .../PublicAPI/PublicAPI.Unshipped.txt | 7 ++++ 3 files changed, 59 insertions(+), 6 deletions(-) diff --git a/src/StackExchange.Redis/Groups/Scripts.MethodsNew.cs b/src/StackExchange.Redis/Groups/Scripts.MethodsNew.cs index ff8cc62aa..316174437 100644 --- a/src/StackExchange.Redis/Groups/Scripts.MethodsNew.cs +++ b/src/StackExchange.Redis/Groups/Scripts.MethodsNew.cs @@ -14,6 +14,36 @@ namespace StackExchange.Redis; /// public static partial class Scripts { + /// EVALSHA, preceded by SCRIPT LOAD so the hash is certain to resolve. + /// The scripting command group. + /// The Lua source. + /// The keys the script accesses; these route the command. + /// Everything else the script needs. + /// Command flags. + /// Cancels the request: one not yet written is never sent; one already written still runs on the server, and its reply is discarded. + /// + /// + /// The hash is computed here rather than taken from the server's reply, which is what lets the body + /// go on the wire once. The existing path cannot do that - it has no hash until + /// SCRIPT LOAD answers, so its first call sends SCRIPT LOAD and then EVAL, + /// carrying the body twice. + /// + /// + /// Every key the script touches must be passed in . That is the + /// server's rule rather than ours - it is how a script routes in a cluster - and it is also what + /// lets a client-side cache know what to invalidate. A script that reaches a key it did not declare + /// is already broken before caching enters the picture. + /// + /// + public static ValueTask EvaluateCachedAsync( + this RespScripts scripts, + CachedLuaScript script, + ReadOnlySpan keys = default, + ReadOnlySpan args = default, + CommandFlags flags = CommandFlags.None, + CancellationToken cancellationToken = default) + => EvaluateCached(scripts, script, keys, args, flags, readOnly: false, RespHandlers.Result); + private static ValueTask EvaluateCached( RespScripts scripts, CachedLuaScript script, @@ -132,7 +162,7 @@ static async ValueTask Awaited( /// is - which is the same constraint that puts the loaded-script belief at write time. /// /// - internal static ValueTask EvaluateReadOnlyAsync( + public static ValueTask EvaluateCachedReadOnlyAsync( this RespScripts scripts, CachedLuaScript script, ReadOnlySpan keys = default, diff --git a/src/StackExchange.Redis/Protocol/CachedLuaScript.cs b/src/StackExchange.Redis/Protocol/CachedLuaScript.cs index f2ada7df4..291e34b75 100644 --- a/src/StackExchange.Redis/Protocol/CachedLuaScript.cs +++ b/src/StackExchange.Redis/Protocol/CachedLuaScript.cs @@ -8,20 +8,36 @@ namespace StackExchange.Redis { - internal class CachedLuaScript : IRespPreambleGate + /// + /// CachedLuaScript. + /// + public class CachedLuaScript : IRespPreambleGate { private const int LoadArgCount = 3; - private readonly string _str; private readonly byte[] _request; private readonly byte[] _hash; + private readonly string _str; private readonly int _start; + /// + /// String. + /// public string String => _str; + + /// + /// Bytes. + /// public ReadOnlyMemory Bytes => _request.AsMemory(_start); - public int RequestLength => _request.Length; + /// + /// Hash. + /// public byte[] Hash => _hash; + /// + /// Initializes a new instance of the class. + /// + /// bytes. public CachedLuaScript(byte[] bytes) { _str = Encoding.UTF8.GetString(bytes); @@ -50,10 +66,10 @@ public CachedLuaScript(byte[] bytes) _start = start; } - public bool IsNeeded(IRespPreambleTarget connection) + bool IRespPreambleGate.IsNeeded(IRespPreambleTarget connection) => connection.Server is not { } endpoint || !endpoint.IsScriptLoaded(_str); - public void OnEstablished(IRespPreambleTarget connection) + void IRespPreambleGate.OnEstablished(IRespPreambleTarget connection) => connection.Server?.AddScript(_str, _hash); internal RespRequest AsLoadRequest() diff --git a/src/StackExchange.Redis/PublicAPI/PublicAPI.Unshipped.txt b/src/StackExchange.Redis/PublicAPI/PublicAPI.Unshipped.txt index e7093f5c8..7e4194338 100644 --- a/src/StackExchange.Redis/PublicAPI/PublicAPI.Unshipped.txt +++ b/src/StackExchange.Redis/PublicAPI/PublicAPI.Unshipped.txt @@ -1,6 +1,11 @@ #nullable enable *REMOVED*static StackExchange.Redis.RespReaderExtensions.ReadLease(this in RESPite.Messages.RespReader reader) -> StackExchange.Redis.Lease? StackExchange.Redis.Arrays +StackExchange.Redis.CachedLuaScript +StackExchange.Redis.CachedLuaScript.Bytes.get -> System.ReadOnlyMemory +StackExchange.Redis.CachedLuaScript.CachedLuaScript(byte[]! bytes) -> void +StackExchange.Redis.CachedLuaScript.Hash.get -> byte[]! +StackExchange.Redis.CachedLuaScript.String.get -> string! static StackExchange.Redis.Arrays.CountAsync(this StackExchange.Redis.RespArrays arrays, StackExchange.Redis.RedisKey key, StackExchange.Redis.CommandFlags flags = StackExchange.Redis.CommandFlags.None, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask static StackExchange.Redis.Arrays.DeleteAsync(this StackExchange.Redis.RespArrays arrays, StackExchange.Redis.RedisKey key, StackExchange.Redis.RedisArrayIndex index, StackExchange.Redis.CommandFlags flags = StackExchange.Redis.CommandFlags.None, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask static StackExchange.Redis.Arrays.DeleteAsync(this StackExchange.Redis.RespArrays arrays, StackExchange.Redis.RedisKey key, System.ReadOnlySpan indices, StackExchange.Redis.CommandFlags flags = StackExchange.Redis.CommandFlags.None, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask @@ -45,6 +50,8 @@ StackExchange.Redis.Caching.CacheKeyRemovalReason.Expired = 3 -> StackExchange.R StackExchange.Redis.Caching.CacheKeyRemovalReason.Evicted = 4 -> StackExchange.Redis.Caching.CacheKeyRemovalReason StackExchange.Redis.Caching.CacheKeyRemovalReason.Flushed = 5 -> StackExchange.Redis.Caching.CacheKeyRemovalReason StackExchange.Redis.Caching.CacheKeyRemovedHandler +static StackExchange.Redis.Scripts.EvaluateCachedAsync(this StackExchange.Redis.RespScripts scripts, StackExchange.Redis.CachedLuaScript! script, System.ReadOnlySpan keys = default(System.ReadOnlySpan), System.ReadOnlySpan args = default(System.ReadOnlySpan), StackExchange.Redis.CommandFlags flags = StackExchange.Redis.CommandFlags.None, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +static StackExchange.Redis.Scripts.EvaluateCachedReadOnlyAsync(this StackExchange.Redis.RespScripts scripts, StackExchange.Redis.CachedLuaScript! script, System.ReadOnlySpan keys = default(System.ReadOnlySpan), System.ReadOnlySpan args = default(System.ReadOnlySpan), StackExchange.Redis.CommandFlags flags = StackExchange.Redis.CommandFlags.None, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask virtual StackExchange.Redis.Caching.CacheKeyRemovedHandler.Invoke(System.ReadOnlySpan key, StackExchange.Redis.Caching.CacheKeyRemovalReason reason) -> void StackExchange.Redis.Caching.CacheOptions.Admission.get -> StackExchange.Redis.Caching.CacheAdmission StackExchange.Redis.Caching.CacheOptions.Admission.init -> void From 13173ae5e7a48752b46e282b23902a7f46fcd402 Mon Sep 17 00:00:00 2001 From: Ivan Tikhonov Date: Thu, 19 Nov 2026 23:26:29 +0300 Subject: [PATCH 05/10] CachedLuaScript bugfix --- .../Protocol/CachedLuaScript.cs | 49 +++++++++++++------ .../PublicAPI/PublicAPI.Unshipped.txt | 1 + 2 files changed, 36 insertions(+), 14 deletions(-) diff --git a/src/StackExchange.Redis/Protocol/CachedLuaScript.cs b/src/StackExchange.Redis/Protocol/CachedLuaScript.cs index 291e34b75..fedbd4152 100644 --- a/src/StackExchange.Redis/Protocol/CachedLuaScript.cs +++ b/src/StackExchange.Redis/Protocol/CachedLuaScript.cs @@ -42,7 +42,36 @@ public CachedLuaScript(byte[] bytes) { _str = Encoding.UTF8.GetString(bytes); _hash = Encoding.ASCII.GetBytes(Sha1Hex(bytes)); - ReadOnlySpan header = "*3\r\n$6\r\nSCRIPT\r\n$4\r\nLOAD\r\n"u8; + _request = AddHeader(bytes, out var start); + _start = start; + } + + /// + /// Initializes a new instance of the class. + /// + /// str. + public CachedLuaScript(string str) + { + _str = str; + + var bytes = Encoding.UTF8.GetBytes(str); + _hash = Encoding.ASCII.GetBytes(Sha1Hex(bytes)); + _request = AddHeader(bytes, out var start); + _start = start; + } + + bool IRespPreambleGate.IsNeeded(IRespPreambleTarget connection) + => connection.Server is not { } endpoint || !endpoint.IsScriptLoaded(_str); + + void IRespPreambleGate.OnEstablished(IRespPreambleTarget connection) + => connection.Server?.AddScript(_str, _hash); + + internal RespRequest AsLoadRequest() + => new(_request, RefCountedBuffer.CreateFixed(_request), 0, _request.Length, argCount: LoadArgCount, command: RedisCommand.SCRIPT); + + private static byte[] AddHeader(byte[] bytes, out int start) + { + ReadOnlySpan header = "*3\r\n$6\r\nSCRIPT\r\n$4\r\nLOAD\r\n$"u8; Span utf8len = stackalloc byte[10]; #if NET var status = bytes.Length.TryFormat(utf8len, out var written); @@ -50,10 +79,10 @@ public CachedLuaScript(byte[] bytes) var status = Utf8Formatter.TryFormat(bytes.Length, utf8len, out var written); #endif Debug.Assert(status); - var request = new byte[header.Length + written + 2 + bytes.Length]; + var request = new byte[header.Length + written + 2 + bytes.Length + 2]; header.CopyTo(request); + start = header.Length; - var start = header.Length; utf8len.CopyTo(request.AsSpan(start)); start += written; @@ -62,18 +91,10 @@ public CachedLuaScript(byte[] bytes) bytes.CopyTo(request.AsSpan(start)); - _request = request; - _start = start; - } - - bool IRespPreambleGate.IsNeeded(IRespPreambleTarget connection) - => connection.Server is not { } endpoint || !endpoint.IsScriptLoaded(_str); - - void IRespPreambleGate.OnEstablished(IRespPreambleTarget connection) - => connection.Server?.AddScript(_str, _hash); + "\r\n"u8.CopyTo(request.AsSpan(start + bytes.Length)); - internal RespRequest AsLoadRequest() - => new(_request, RefCountedBuffer.CreateFixed(_request), 0, _request.Length, argCount: LoadArgCount, command: RedisCommand.SCRIPT); + return request; + } private static string Sha1Hex(byte[] bytes) { diff --git a/src/StackExchange.Redis/PublicAPI/PublicAPI.Unshipped.txt b/src/StackExchange.Redis/PublicAPI/PublicAPI.Unshipped.txt index 7e4194338..5e4487989 100644 --- a/src/StackExchange.Redis/PublicAPI/PublicAPI.Unshipped.txt +++ b/src/StackExchange.Redis/PublicAPI/PublicAPI.Unshipped.txt @@ -4,6 +4,7 @@ StackExchange.Redis.Arrays StackExchange.Redis.CachedLuaScript StackExchange.Redis.CachedLuaScript.Bytes.get -> System.ReadOnlyMemory StackExchange.Redis.CachedLuaScript.CachedLuaScript(byte[]! bytes) -> void +StackExchange.Redis.CachedLuaScript.CachedLuaScript(string! str) -> void StackExchange.Redis.CachedLuaScript.Hash.get -> byte[]! StackExchange.Redis.CachedLuaScript.String.get -> string! static StackExchange.Redis.Arrays.CountAsync(this StackExchange.Redis.RespArrays arrays, StackExchange.Redis.RedisKey key, StackExchange.Redis.CommandFlags flags = StackExchange.Redis.CommandFlags.None, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask From a65485678c05b0fdc68194f647ba20c0fc4ae54e Mon Sep 17 00:00:00 2001 From: Ivan Tikhonov Date: Thu, 19 Nov 2026 23:41:12 +0300 Subject: [PATCH 06/10] Sha1Hex --- .../Protocol/CachedLuaScript.cs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/StackExchange.Redis/Protocol/CachedLuaScript.cs b/src/StackExchange.Redis/Protocol/CachedLuaScript.cs index fedbd4152..885f042a0 100644 --- a/src/StackExchange.Redis/Protocol/CachedLuaScript.cs +++ b/src/StackExchange.Redis/Protocol/CachedLuaScript.cs @@ -41,7 +41,7 @@ public class CachedLuaScript : IRespPreambleGate public CachedLuaScript(byte[] bytes) { _str = Encoding.UTF8.GetString(bytes); - _hash = Encoding.ASCII.GetBytes(Sha1Hex(bytes)); + _hash = Sha1Hex(bytes); _request = AddHeader(bytes, out var start); _start = start; } @@ -55,7 +55,7 @@ public CachedLuaScript(string str) _str = str; var bytes = Encoding.UTF8.GetBytes(str); - _hash = Encoding.ASCII.GetBytes(Sha1Hex(bytes)); + _hash = Sha1Hex(bytes); _request = AddHeader(bytes, out var start); _start = start; } @@ -96,7 +96,7 @@ private static byte[] AddHeader(byte[] bytes, out int start) return request; } - private static string Sha1Hex(byte[] bytes) + private static byte[] Sha1Hex(byte[] bytes) { #if NET Span digest = stackalloc byte[20]; @@ -109,14 +109,14 @@ private static string Sha1Hex(byte[] bytes) // is too new to use here. Not hot - and once the rendered SCRIPT LOAD frame is cached, this // runs once per script rather than once per call. const string Hex = "0123456789abcdef"; - var chars = new char[40]; + var chars = new byte[40]; for (var i = 0; i < 20; i++) { - chars[i * 2] = Hex[digest[i] >> 4]; - chars[(i * 2) + 1] = Hex[digest[i] & 0xF]; + chars[i * 2] = (byte)Hex[digest[i] >> 4]; + chars[(i * 2) + 1] = (byte)Hex[digest[i] & 0xF]; } - return new string(chars); + return chars; } } } From 8cf43553068d736b110adf4a7a71eace71f600ea Mon Sep 17 00:00:00 2001 From: Ivan Tikhonov Date: Fri, 20 Nov 2026 00:01:13 +0300 Subject: [PATCH 07/10] del unused --- .../Groups/Scripts.MethodsNew.cs | 27 ------------------- 1 file changed, 27 deletions(-) diff --git a/src/StackExchange.Redis/Groups/Scripts.MethodsNew.cs b/src/StackExchange.Redis/Groups/Scripts.MethodsNew.cs index 316174437..c13f4f7eb 100644 --- a/src/StackExchange.Redis/Groups/Scripts.MethodsNew.cs +++ b/src/StackExchange.Redis/Groups/Scripts.MethodsNew.cs @@ -171,33 +171,6 @@ public static ValueTask EvaluateCachedReadOnlyAsync( CancellationToken cancellationToken = default) => EvaluateCached(scripts, script, keys, args, flags, readOnly: true, RespHandlers.Result); - /// Render the EVALSHA and send it behind the preamble. - private static ValueTask SendPair( - RespContext context, - ref RespRequestFrame preamble, - RedisValue hash, - ReadOnlySpan keys, - ReadOnlySpan args, - CommandFlags flags, - bool readOnly, - IRespPreambleGate gate, - IRespHandler handler) - { - var command = readOnly - ? ForReadOnlyScript(context.CommandMap, RedisCommand.EVALSHA_RO, ref flags) - : RedisCommand.EVALSHA; - var request = context.Render($"{command}{hash}{(RedisValue)keys.Length}{keys}{args}"); - try - { - return context.SendWithPreambleAsync( - ref preamble, ref request, flags, handler, gate); - } - finally - { - request.Dispose(); - } - } - /// Render the EVALSHA and send it behind a preamble the registry already owns. /// /// The registry's preamble owns nothing poolable - it is a fixed array that is never returned - so From cb130869d462d1ae611b807f78d3f6bcefc10d21 Mon Sep 17 00:00:00 2001 From: Ivan Tikhonov Date: Fri, 20 Nov 2026 09:48:17 +0300 Subject: [PATCH 08/10] CancellationToken --- .../Groups/Scripts.MethodsNew.cs | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/src/StackExchange.Redis/Groups/Scripts.MethodsNew.cs b/src/StackExchange.Redis/Groups/Scripts.MethodsNew.cs index c13f4f7eb..a6b54bd9d 100644 --- a/src/StackExchange.Redis/Groups/Scripts.MethodsNew.cs +++ b/src/StackExchange.Redis/Groups/Scripts.MethodsNew.cs @@ -42,7 +42,7 @@ public static ValueTask EvaluateCachedAsync( ReadOnlySpan args = default, CommandFlags flags = CommandFlags.None, CancellationToken cancellationToken = default) - => EvaluateCached(scripts, script, keys, args, flags, readOnly: false, RespHandlers.Result); + => EvaluateCached(scripts, script, keys, args, flags, readOnly: false, RespHandlers.Result, cancellationToken); private static ValueTask EvaluateCached( RespScripts scripts, @@ -51,7 +51,8 @@ private static ValueTask EvaluateCached( ReadOnlySpan args, CommandFlags flags, bool readOnly, - IRespHandler handler) + IRespHandler handler, + CancellationToken cancellationToken) { if (script is null) throw new ArgumentNullException(nameof(script)); var context = scripts.Context; @@ -68,7 +69,7 @@ private static ValueTask EvaluateCached( ? ForReadOnlyScript(context.CommandMap, RedisCommand.EVAL_RO, ref flags) : RedisCommand.EVAL; var cmd = context.Render($"{eval}{(RedisValue)script.Bytes}{(RedisValue)keys.Length}{keys}{args}"); - return context.SendAsync(ref cmd, flags, handler); + return context.SendAsync(ref cmd, flags, handler, cancellationToken); } var preamble = script.AsLoadRequest(); @@ -169,7 +170,7 @@ public static ValueTask EvaluateCachedReadOnlyAsync( ReadOnlySpan args = default, CommandFlags flags = CommandFlags.None, CancellationToken cancellationToken = default) - => EvaluateCached(scripts, script, keys, args, flags, readOnly: true, RespHandlers.Result); + => EvaluateCached(scripts, script, keys, args, flags, readOnly: true, RespHandlers.Result, cancellationToken); /// Render the EVALSHA and send it behind a preamble the registry already owns. /// @@ -216,6 +217,7 @@ internal static ValueTask EvaluateCachedResult( ReadOnlySpan keys, ReadOnlySpan args, bool readOnly, - CommandFlags flags) - => EvaluateCached(scripts, script, keys, args, flags, readOnly, RedisResultHandler.Instance); + CommandFlags flags, + CancellationToken cancellationToken = default) + => EvaluateCached(scripts, script, keys, args, flags, readOnly, RedisResultHandler.Instance, cancellationToken); } From c6771bd4a2a55569ded9cecbb2bf93ff0d050fa6 Mon Sep 17 00:00:00 2001 From: Ivan Tikhonov Date: Fri, 20 Nov 2026 09:51:07 +0300 Subject: [PATCH 09/10] cancellationToken --- .../Groups/Scripts.MethodsNew.cs | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/src/StackExchange.Redis/Groups/Scripts.MethodsNew.cs b/src/StackExchange.Redis/Groups/Scripts.MethodsNew.cs index a6b54bd9d..4331f1116 100644 --- a/src/StackExchange.Redis/Groups/Scripts.MethodsNew.cs +++ b/src/StackExchange.Redis/Groups/Scripts.MethodsNew.cs @@ -81,7 +81,8 @@ private static ValueTask EvaluateCached( args, flags, readOnly, - handler); + handler, + cancellationToken); } /// Recover from NOSCRIPT by re-sending the script body. @@ -111,13 +112,14 @@ private static ValueTask Repairable( ReadOnlySpan args, CommandFlags flags, bool readOnly, - IRespHandler handler) + IRespHandler handler, + CancellationToken cancellationToken) { if (pending.IsCompletedSuccessfully) 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); + return Awaited(pending, context, script, keys.ToArray(), args.ToArray(), flags, readOnly, handler, cancellationToken); static async ValueTask Awaited( ValueTask pending, @@ -127,7 +129,8 @@ static async ValueTask Awaited( RedisValue[] args, CommandFlags flags, bool readOnly, - IRespHandler handler) + IRespHandler handler, + CancellationToken cancellationToken) { try { @@ -139,7 +142,7 @@ static async ValueTask Awaited( ? ForReadOnlyScript(context.CommandMap, RedisCommand.EVAL_RO, ref flags) : RedisCommand.EVAL; var cmd = context.Render($"{eval}{(RedisValue)script.Bytes}{(RedisValue)keys.Length}{keys}{args}"); - return await context.SendAsync(ref cmd, flags, handler).ConfigureAwait(false); + return await context.SendAsync(ref cmd, flags, handler, cancellationToken).ConfigureAwait(false); } } } From a9195eed3587e484de99960803505321e4100d23 Mon Sep 17 00:00:00 2001 From: Ivan Tikhonov Date: Fri, 20 Nov 2026 10:19:14 +0300 Subject: [PATCH 10/10] add WithoutPreamble --- .../Groups/Scripts.MethodsNew.cs | 25 +-- .../Groups/Scripts.MethodsWithoutPreamble.cs | 200 ++++++++++++++++++ .../Protocol/CachedLuaScript.cs | 2 +- .../PublicAPI/PublicAPI.Unshipped.txt | 2 + 4 files changed, 207 insertions(+), 22 deletions(-) create mode 100644 src/StackExchange.Redis/Groups/Scripts.MethodsWithoutPreamble.cs diff --git a/src/StackExchange.Redis/Groups/Scripts.MethodsNew.cs b/src/StackExchange.Redis/Groups/Scripts.MethodsNew.cs index 4331f1116..f67007a22 100644 --- a/src/StackExchange.Redis/Groups/Scripts.MethodsNew.cs +++ b/src/StackExchange.Redis/Groups/Scripts.MethodsNew.cs @@ -74,7 +74,7 @@ private static ValueTask EvaluateCached( var preamble = script.AsLoadRequest(); return Repairable( - SendPair(context, preamble, (RedisValue)script.Hash, keys, args, flags, readOnly, script, handler), + SendPair(context, preamble, (RedisValue)script.Hash, keys, args, flags, readOnly, script, handler, cancellationToken), context, script, keys, @@ -189,7 +189,8 @@ private static ValueTask SendPair( CommandFlags flags, bool readOnly, IRespPreambleGate gate, - IRespHandler handler) + IRespHandler handler, + CancellationToken cancellationToken) { var command = readOnly ? ForReadOnlyScript(context.CommandMap, RedisCommand.EVALSHA_RO, ref flags) @@ -198,29 +199,11 @@ private static ValueTask SendPair( try { return context.SendWithPreambleAsync( - preamble, ref request, flags, handler, gate); + preamble, ref request, flags, handler, gate, cancellationToken); } finally { request.Dispose(); } } - - /// The shipped shape, for IDatabase.ScriptEvaluate. - /// - /// Permanent, not scaffolding, and internal for the same reason the *Array shims are: - /// materialises the whole reply, which is what the low-allocation - /// exists to avoid, so new code must not be able to pick it by accident. - /// It is the same parse either way - the handler reuses RedisResult.TryCreate - so the two - /// shapes cannot drift. - /// - internal static ValueTask EvaluateCachedResult( - this RespScripts scripts, - CachedLuaScript script, - ReadOnlySpan keys, - ReadOnlySpan args, - bool readOnly, - CommandFlags flags, - CancellationToken cancellationToken = default) - => EvaluateCached(scripts, script, keys, args, flags, readOnly, RedisResultHandler.Instance, cancellationToken); } diff --git a/src/StackExchange.Redis/Groups/Scripts.MethodsWithoutPreamble.cs b/src/StackExchange.Redis/Groups/Scripts.MethodsWithoutPreamble.cs new file mode 100644 index 000000000..2086f3ecb --- /dev/null +++ b/src/StackExchange.Redis/Groups/Scripts.MethodsWithoutPreamble.cs @@ -0,0 +1,200 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using StackExchange.Redis.Protocol; + +namespace StackExchange.Redis; + +/// +/// The scripts commands. +/// +/// +/// Here rather than in a single surface-wide class, so that a group is one place. The extension methods +/// bind by namespace, and the namespace is StackExchange.Redis, so this costs a caller nothing. +/// +public static partial class Scripts +{ + /// EVALSHA, preceded by SCRIPT LOAD so the hash is certain to resolve. + /// The scripting command group. + /// The Lua source. + /// The keys the script accesses; these route the command. + /// Everything else the script needs. + /// Command flags. + /// Cancels the request: one not yet written is never sent; one already written still runs on the server, and its reply is discarded. + /// + /// + /// The hash is computed here rather than taken from the server's reply, which is what lets the body + /// go on the wire once. The existing path cannot do that - it has no hash until + /// SCRIPT LOAD answers, so its first call sends SCRIPT LOAD and then EVAL, + /// carrying the body twice. + /// + /// + /// Every key the script touches must be passed in . That is the + /// server's rule rather than ours - it is how a script routes in a cluster - and it is also what + /// lets a client-side cache know what to invalidate. A script that reaches a key it did not declare + /// is already broken before caching enters the picture. + /// + /// + public static ValueTask EvaluateCached2Async( + this RespScripts scripts, + CachedLuaScript script, + ReadOnlySpan keys = default, + ReadOnlySpan args = default, + CommandFlags flags = CommandFlags.None, + CancellationToken cancellationToken = default) + => EvaluateCached2(scripts, script, keys, args, flags, readOnly: false, RespHandlers.Result, cancellationToken); + + private static ValueTask EvaluateCached2( + RespScripts scripts, + CachedLuaScript script, + ReadOnlySpan keys, + ReadOnlySpan args, + CommandFlags flags, + bool readOnly, + IRespHandler handler, + CancellationToken cancellationToken) + { + if (script is null) throw new ArgumentNullException(nameof(script)); + var context = scripts.Context; + + if ((flags & CommandFlags.NoScriptCache) != 0 + || !context.CommandMap.IsAvailable(RedisCommand.SCRIPT) + || context.Executor is { Accumulates: true }) + { + // EVAL_RO can be DISABLED in the command map, and the fallback is not just a different name: + // EVAL_RO defaults to CommandRetryReadOnly where EVAL defaults to CommandRetryWriteAccumulating, + // so swapping the command alone would quietly make a script the caller asked for read-only + // retry like a write. ForReadOnlyScript pins the category before it falls back. + var eval = readOnly + ? ForReadOnlyScript(context.CommandMap, RedisCommand.EVAL_RO, ref flags) + : RedisCommand.EVAL; + var cmd = context.Render($"{eval}{(RedisValue)script.Bytes}{(RedisValue)keys.Length}{keys}{args}"); + return context.SendAsync(ref cmd, flags, handler, cancellationToken); + } + + return Repairable2( + SendPair2(context, (RedisValue)script.Hash, keys, args, flags, readOnly, handler, cancellationToken), + context, + script, + keys, + args, + flags, + readOnly, + handler, + cancellationToken); + } + + /// Recover from NOSCRIPT by re-sending the script body. + /// + /// + /// A belief about a server's script cache can always be wrong. SCRIPT FLUSH, a restart, + /// or a failover to a replica that never saw the load all leave the endpoint believing a script is + /// present when it is not - and the reply is NOSCRIPT. The shipped surface repairs this in + /// ResultProcessor and re-issues with the body; without the same repair the new surface turns + /// an ordinary, expected event into an exception the caller has to handle. + /// + /// + /// Only where the source is known. A caller who supplied a hash and not a script cannot be + /// repaired - there is nothing to re-send - so EvaluateHash lets the error stand, which is + /// what the remarks there already say. + /// + /// + /// The belief is dropped before retrying, so the retry carries its own SCRIPT LOAD rather than + /// trusting the record that has just been proved wrong, and the next caller reloads too. + /// + /// + private static ValueTask Repairable2( + ValueTask pending, + RespContext context, + CachedLuaScript script, + ReadOnlySpan keys, + ReadOnlySpan args, + CommandFlags flags, + bool readOnly, + IRespHandler handler, + CancellationToken cancellationToken) + { + if (pending.IsCompletedSuccessfully) 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); + + static async ValueTask Awaited( + ValueTask pending, + RespContext context, + CachedLuaScript script, + RedisKey[] keys, + RedisValue[] args, + CommandFlags flags, + bool readOnly, + IRespHandler handler, + CancellationToken cancellationToken) + { + try + { + return await pending.ConfigureAwait(false); + } + catch (RedisServerException ex) when (ex.Kind == RedisErrorKind.NoScript) + { + var eval = readOnly + ? ForReadOnlyScript(context.CommandMap, RedisCommand.EVAL_RO, ref flags) + : RedisCommand.EVAL; + var cmd = context.Render($"{eval}{(RedisValue)script.Bytes}{(RedisValue)keys.Length}{keys}{args}"); + return await context.SendAsync(ref cmd, flags, handler, cancellationToken).ConfigureAwait(false); + } + } + } + + /// EVALSHA_RO, preceded by SCRIPT LOAD; the read-only form of Evaluate. + /// The scripting command group. + /// The Lua source; it must not write. + /// The keys the script accesses; these route the command. + /// Everything else the script needs. + /// Command flags. + /// Cancels the request: one not yet written is never sent; one already written still runs on the server, and its reply is discarded. + /// + /// + /// A separate method rather than a flag on Evaluate, because it is a separate command with a + /// different retry category: EVALSHA_RO is read-only, where EVALSHA must be treated as + /// a write. Hiding that behind a boolean would let a caller's retry semantics change invisibly. + /// + /// + /// Requires a server that has the read-only forms (7.0 and later). The older surface probes + /// the connection and falls back; this does not, because the frame is chosen before the connection + /// is - which is the same constraint that puts the loaded-script belief at write time. + /// + /// + public static ValueTask EvaluateCached2ReadOnlyAsync( + this RespScripts scripts, + CachedLuaScript script, + ReadOnlySpan keys = default, + ReadOnlySpan args = default, + CommandFlags flags = CommandFlags.None, + CancellationToken cancellationToken = default) + => EvaluateCached2(scripts, script, keys, args, flags, readOnly: true, RespHandlers.Result, cancellationToken); + + private static ValueTask SendPair2( + RespContext context, + RedisValue hash, + ReadOnlySpan keys, + ReadOnlySpan args, + CommandFlags flags, + bool readOnly, + IRespHandler handler, + CancellationToken cancellationToken) + { + var command = readOnly + ? ForReadOnlyScript(context.CommandMap, RedisCommand.EVALSHA_RO, ref flags) + : RedisCommand.EVALSHA; + var request = context.Render($"{command}{hash}{(RedisValue)keys.Length}{keys}{args}"); + try + { + return context.SendAsync(ref request, flags, handler, cancellationToken); + } + finally + { + request.Dispose(); + } + } +} diff --git a/src/StackExchange.Redis/Protocol/CachedLuaScript.cs b/src/StackExchange.Redis/Protocol/CachedLuaScript.cs index 885f042a0..5d36fa92c 100644 --- a/src/StackExchange.Redis/Protocol/CachedLuaScript.cs +++ b/src/StackExchange.Redis/Protocol/CachedLuaScript.cs @@ -27,7 +27,7 @@ public class CachedLuaScript : IRespPreambleGate /// /// Bytes. /// - public ReadOnlyMemory Bytes => _request.AsMemory(_start); + public ReadOnlyMemory Bytes => _request.AsMemory(_start, _request.Length - _start - 2); /// /// Hash. diff --git a/src/StackExchange.Redis/PublicAPI/PublicAPI.Unshipped.txt b/src/StackExchange.Redis/PublicAPI/PublicAPI.Unshipped.txt index 5e4487989..b85000340 100644 --- a/src/StackExchange.Redis/PublicAPI/PublicAPI.Unshipped.txt +++ b/src/StackExchange.Redis/PublicAPI/PublicAPI.Unshipped.txt @@ -53,6 +53,8 @@ StackExchange.Redis.Caching.CacheKeyRemovalReason.Flushed = 5 -> StackExchange.R StackExchange.Redis.Caching.CacheKeyRemovedHandler static StackExchange.Redis.Scripts.EvaluateCachedAsync(this StackExchange.Redis.RespScripts scripts, StackExchange.Redis.CachedLuaScript! script, System.ReadOnlySpan keys = default(System.ReadOnlySpan), System.ReadOnlySpan args = default(System.ReadOnlySpan), StackExchange.Redis.CommandFlags flags = StackExchange.Redis.CommandFlags.None, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask static StackExchange.Redis.Scripts.EvaluateCachedReadOnlyAsync(this StackExchange.Redis.RespScripts scripts, StackExchange.Redis.CachedLuaScript! script, System.ReadOnlySpan keys = default(System.ReadOnlySpan), System.ReadOnlySpan args = default(System.ReadOnlySpan), StackExchange.Redis.CommandFlags flags = StackExchange.Redis.CommandFlags.None, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +static StackExchange.Redis.Scripts.EvaluateCached2Async(this StackExchange.Redis.RespScripts scripts, StackExchange.Redis.CachedLuaScript! script, System.ReadOnlySpan keys = default(System.ReadOnlySpan), System.ReadOnlySpan args = default(System.ReadOnlySpan), StackExchange.Redis.CommandFlags flags = StackExchange.Redis.CommandFlags.None, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +static StackExchange.Redis.Scripts.EvaluateCached2ReadOnlyAsync(this StackExchange.Redis.RespScripts scripts, StackExchange.Redis.CachedLuaScript! script, System.ReadOnlySpan keys = default(System.ReadOnlySpan), System.ReadOnlySpan args = default(System.ReadOnlySpan), StackExchange.Redis.CommandFlags flags = StackExchange.Redis.CommandFlags.None, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask virtual StackExchange.Redis.Caching.CacheKeyRemovedHandler.Invoke(System.ReadOnlySpan key, StackExchange.Redis.Caching.CacheKeyRemovalReason reason) -> void StackExchange.Redis.Caching.CacheOptions.Admission.get -> StackExchange.Redis.Caching.CacheAdmission StackExchange.Redis.Caching.CacheOptions.Admission.init -> void