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
4 changes: 4 additions & 0 deletions src/StackExchange.Redis/Contexts/RespClientConnection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -431,6 +431,10 @@ protected override bool TryHandOff(ReadOnlySpan<byte> frame, IRespMessage messag
return true;
}
}
else if (message is RespExecOperation exec)
{
exec.Profile?.SetResponseReceived();
}

// one byte of work for every reply that is not an error, which is nearly all of them
if (!RespRedirect.TryParse(frame, out var redirect)) return false;
Expand Down
4 changes: 2 additions & 2 deletions src/StackExchange.Redis/Contexts/RespConnectionManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1630,7 +1630,7 @@ private async Task SubscribeToConfigurationChannelAsync(
/// the answer would profile the wrong session, or keep profiling after someone stopped.
/// </remarks>
private object? StartProfile(
RespPayloadOperation operation, RedisCommand command, CommandFlags flags, int database, EndPoint? endpoint)
IProfiledOperation operation, RedisCommand command, CommandFlags flags, int database, EndPoint? endpoint)
{
if (endpoint is null) return null;

Expand Down Expand Up @@ -1658,7 +1658,7 @@ private async Task SubscribeToConfigurationChannelAsync(
// Claiming "interactive" would be right most of the time, which is not the same as right.
profile.SetEnqueued(null);

operation.Profile = profile;
operation.Diagnostics.HostState = profile; // RespPayloadOperation.Profile, RespExecOperation.Profile
return profile;
}

Expand Down
22 changes: 15 additions & 7 deletions src/StackExchange.Redis/Contexts/RespEndpointExecutor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ internal sealed class RespEndpointExecutor : RespExecutorBase, IAsyncDisposable,
{
private readonly Func<CancellationToken, Task<RespConnection>> _connect;
private readonly Func<RedisFeatures?>? _features;
private readonly Func<RespPayloadOperation, RedisCommand, CommandFlags, int, EndPoint?, object?>? _startProfile;
private readonly Func<IProfiledOperation, RedisCommand, CommandFlags, int, EndPoint?, object?>? _startProfile;
private readonly EndPoint? _endpoint;
private readonly bool _queueWhileDisconnected;

Expand Down Expand Up @@ -226,7 +226,7 @@ internal RespEndpointExecutor(
EndPoint? endpoint = null,
bool queueWhileDisconnected = true,
Func<RedisFeatures?>? features = null,
Func<RespPayloadOperation, RedisCommand, CommandFlags, int, EndPoint?, object?>? startProfile = null,
Func<IProfiledOperation, RedisCommand, CommandFlags, int, EndPoint?, object?>? startProfile = null,
SelectPreamble? select = null,
int connectTimeoutMilliseconds = 0,
Func<IReconnectRetryPolicy?>? retryPolicy = null,
Expand Down Expand Up @@ -1254,11 +1254,13 @@ internal override bool TryWriteRun(RespConnection connection, RespRunEntry[] run

/// <summary>Write a run, preceded by a <c>SELECT</c> if this connection is on another database.</summary>
/// <remarks>
/// Only a batch asks for profiling (<paramref name="profile"/>): its commands are ordinary commands
/// that happen to travel together, and a batch used to skip profiling altogether because it bypasses
/// <c>Dispatch</c>, where single sends start their records (#2175). A transaction's run stays
/// unprofiled here, as it always was - its operations answer <c>QUEUED</c> and then answer again
/// inside <c>EXEC</c>, which is not the shape a <c>ProfiledCommand</c> describes.
/// Only a batch asks for its commands to be profiled (<paramref name="profile"/>): they are ordinary
/// commands that happen to travel together, and a batch used to skip profiling altogether because it
/// bypasses <c>Dispatch</c>, where single sends start their records (#2175). A transaction's queued
/// commands stay unprofiled - they answer <c>QUEUED</c> and then answer again inside <c>EXEC</c>, which
/// is not the shape a <c>ProfiledCommand</c> describes - but the transaction itself is profiled, as
/// ONE record named <c>EXEC</c>, which is what the v3 core reported for it (its transaction was a
/// single message whose command was <c>EXEC</c>).
/// </remarks>
internal bool SendRun(RespConnection connection, RespRunEntry[] run, int count, int database, bool profile = false)
{
Expand Down Expand Up @@ -1286,6 +1288,12 @@ internal bool SendRun(RespConnection connection, RespRunEntry[] run, int count,
_endpoint);
}
}
else if (run[i].Message is RespExecOperation exec && _startProfile is { } startExec)
{
// the transaction's own record (see the remarks): named EXEC, with the caller's flags
// and the run's database, as the v3 core's transaction message reported it
startExec(exec, RedisCommand.EXEC, exec.Flags, database, _endpoint);
}
}

if (_select is null || database < 0) return connection.Send(run, count);
Expand Down
13 changes: 12 additions & 1 deletion src/StackExchange.Redis/Contexts/RespPayloadOperation.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,17 @@

namespace StackExchange.Redis
{
/// <summary>An operation that can carry a profiling record: a single command, or a transaction's <c>EXEC</c>.</summary>
/// <remarks>
/// The record lives in <c>Diagnostics.HostState</c>; this is only the common view of where that is, because
/// the operations share no non-generic base that exposes it.
/// </remarks>
internal interface IProfiledOperation
{
/// <summary>The operation's diagnostics, whose <c>HostState</c> holds the profiling record.</summary>
ref RespOperationDiagnostics Diagnostics { get; }
}

/// <summary>An operation whose result is the reply frame itself.</summary>
/// <remarks>
/// <para>
Expand All @@ -23,7 +34,7 @@ namespace StackExchange.Redis
/// of the receive buffer instead is a real win and a separate piece of work.
/// </para>
/// </remarks>
internal class RespPayloadOperation : RespMessageBase<RespPayload>, IFaultSubject
internal class RespPayloadOperation : RespMessageBase<RespPayload>, IFaultSubject, IProfiledOperation
{
/// <summary>
/// Recycled operations, so a steady-state send allocates no operation at all.
Expand Down
55 changes: 53 additions & 2 deletions src/StackExchange.Redis/Contexts/RespTransaction.cs
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,7 @@ private bool Enqueue(RespPayloadOperation operation, in RespRequest request, Can
operation.Attach(request.Span, request.Flags, cancellationToken);
operation.Diagnostics.Status = RespCommandStatus.WaitingInBacklog;
operation.Slot = request.Slot;
operation.Command = request.Command; // RoutingFlags asks whether any queued command is primary-only
operation.Database = Database;

// its first reply will be the +QUEUED receipt; the real result arrives from EXEC
Expand Down Expand Up @@ -323,7 +324,7 @@ public async Task<bool> ExecuteAsync(CommandFlags flags = CommandFlags.None)
var empty = queue is null || queue.Count == 0;
if (empty && conditions is null) return true; // an empty transaction trivially succeeds

var target = _inner.ResolveForSlot(SlotOf(queue), RedisCommand.MULTI, CommandFlags.None);
var target = _inner.ResolveForSlot(SlotOf(queue), RedisCommand.MULTI, RoutingFlags(flags, queue));

// waits for a connection rather than declining when one is merely not up yet; a transaction
// that arrived before the first connect is early, not unservable
Expand Down Expand Up @@ -553,6 +554,38 @@ private async Task<bool> CheckAsync(
/// transaction as cross-slot. Wrong error, not wrong data.
/// </para>
/// </remarks>
/// <summary>The primary/replica preference the transaction is routed with.</summary>
/// <remarks>
/// <para>
/// <b>The caller's preference, as for any command.</b> This routed with no flags at all, so every
/// transaction went to the primary: harmless for writes, but a read-only transaction sent with
/// <c>PreferReplica</c> never reached a replica, unlike the v3 core.
/// </para>
/// <para>
/// <b>Primary-only work takes the whole transaction to the primary.</b> It runs on one server, so if
/// any queued command is primary-only the transaction must go where that command can run - the rule
/// <c>EndpointForAny</c> applies to a single command, and that the v3 core applied to a transaction
/// (main #3381: the <c>LockExtend</c>/<c>LockRelease</c> fallback, sent with <c>PreferReplica</c>,
/// went to a replica that rejected the queued <c>EXPIRE</c>/<c>DEL</c>). <c>DemandReplica</c> is left
/// alone, so that it still fails the same way.
/// </para>
/// </remarks>
private static CommandFlags RoutingFlags(CommandFlags flags, List<QueuedOperation>? queue)
{
var preference = CommandFlagsInternal.GetPrimaryReplicaFlags(flags);
if (preference == CommandFlags.DemandReplica || queue is null) return preference;

foreach (var (operation, _) in queue)
{
if (operation.Command.IsPrimaryOnly())
{
return CommandFlags.DemandMaster;
}
}

return preference;
}

private static int SlotOf(List<QueuedOperation>? queue)
{
var slot = ServerSelectionStrategy.NoSlot;
Expand Down Expand Up @@ -716,12 +749,29 @@ internal void Abandon(Exception fault)
/// alternative is pinning a potentially large array.
/// </para>
/// </remarks>
internal sealed class RespExecOperation : RespMessageBase<bool>
internal sealed class RespExecOperation : RespMessageBase<bool>, IProfiledOperation
{
private List<QueuedOperation>? _queued;
private Action? _onAborted;
private CommandFlags _flags;

/// <summary>The caller's flags for the transaction, which its profiling record reports.</summary>
internal CommandFlags Flags => _flags;

/// <summary>The transaction's profiling record, when anyone is profiling.</summary>
/// <remarks>Held where <see cref="RespPayloadOperation.Profile"/> holds a single command's.</remarks>
internal Profiling.ProfiledCommand? Profile
{
get => Diagnostics.HostState as Profiling.ProfiledCommand;
set => Diagnostics.HostState = value;
}

/// <inheritdoc/>
protected override void OnSent() => Profile?.SetRequestSent();

/// <inheritdoc/>
protected override void OnFinished(Exception? fault) => Profile?.SetCompleted();

internal void Attach(
ReadOnlySpan<byte> request,
List<QueuedOperation> queued,
Expand All @@ -743,6 +793,7 @@ protected override void OnReset()
_queued = null;
_onAborted = null;
_flags = CommandFlags.None;
Profile = null;
}

/// <inheritdoc/>
Expand Down
60 changes: 60 additions & 0 deletions tests/StackExchange.Redis.Tests/TransactionTests.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
using System;
using System.Linq;
using System.Threading.Tasks;
using StackExchange.Redis.Profiling;
using Xunit;

namespace StackExchange.Redis.Tests;
Expand Down Expand Up @@ -67,6 +69,64 @@ public async Task NestedTransactionThrows()
Assert.Throws<NotSupportedException>(() => ((IDatabaseAsync)tran).CreateTransaction(null));
}

[Fact]
public async Task PrimaryOnlyWorkWithPreferReplicaRunsOnThePrimary()
{
await using var conn = Create(configuration: TestConfig.Current.PrimaryServerAndPort + "," + TestConfig.Current.ReplicaServerAndPort);
Assert.SkipUnless(
conn.GetEndPoints().Any(ep => conn.GetServer(ep).IsReplica),
"No replica in this configuration");

var db = conn.GetDatabase();
RedisKey key = Me();
db.StringSet(key, "abc");

var session = new ProfilingSession();
conn.RegisterProfiler(() => session);

// this is what LockExtend / LockRelease fall back to on servers without SET IFEQ / DELEX
var tran = db.CreateTransaction();
tran.AddCondition(Condition.StringEqual(key, "abc"));
var expire = tran.KeyExpireAsync(key, TimeSpan.FromMinutes(1));
Assert.True(tran.Execute(CommandFlags.PreferReplica));
Assert.True(await expire);

tran = db.CreateTransaction();
tran.AddCondition(Condition.StringEqual(key, "abc"));
var set = tran.StringSetAsync(key, "def");
Assert.True(await tran.ExecuteAsync(CommandFlags.PreferReplica));
Assert.True(await set);

Assert.Equal("def", db.StringGet(key, CommandFlags.DemandMaster));
var execs = session.FinishProfiling().Where(cmd => cmd.Command == "EXEC").ToList();
Assert.Equal(2, execs.Count);
Assert.All(execs, exec => Assert.False(conn.GetServer(exec.EndPoint).IsReplica));
}

[Fact]
public async Task ReadOnlyWorkWithPreferReplicaStillRunsOnTheReplica()
{
await using var conn = Create(configuration: TestConfig.Current.PrimaryServerAndPort + "," + TestConfig.Current.ReplicaServerAndPort);
Assert.SkipUnless(
conn.GetEndPoints().Any(ep => conn.GetServer(ep).IsReplica),
"No replica in this configuration");

var db = conn.GetDatabase();
RedisKey key = Me();

var session = new ProfilingSession();
conn.RegisterProfiler(() => session);

var tran = db.CreateTransaction();
tran.AddCondition(Condition.KeyNotExists(key));
var get = tran.StringGetAsync(key);
Assert.True(await tran.ExecuteAsync(CommandFlags.PreferReplica));
Assert.True((await get).IsNull);

var exec = Assert.Single(session.FinishProfiling(), cmd => cmd.Command == "EXEC");
Assert.True(conn.GetServer(exec.EndPoint).IsReplica);
}

[Theory]
[InlineData(false, false, true)]
[InlineData(false, true, false)]
Expand Down
Loading