Skip to content
Closed
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
10 changes: 6 additions & 4 deletions DistributedLock.Redis/Primitives/RedisScript.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,13 @@ public RedisScript(string script, Func<TArgument, object> parameters)
this._parameters = parameters;
}

public RedisResult Execute(IDatabase database, TArgument argument, bool fireAndForget = false) =>
this._script.Evaluate(database, this._parameters(argument), flags: RedLockHelper.GetCommandFlags(fireAndForget));
public RedisResult Execute(IDatabase database, TArgument argument, bool fireAndForget = false) =>
// database.ScriptEvaluate must be called instead of _script.Evaluate in order to respect the database's key prefix
database.ScriptEvaluate(this._script, this._parameters(argument), flags: RedLockHelper.GetCommandFlags(fireAndForget));

public Task<RedisResult> ExecuteAsync(IDatabaseAsync database, TArgument argument, bool fireAndForget = false) =>
this._script.EvaluateAsync(database, this._parameters(argument), flags: RedLockHelper.GetCommandFlags(fireAndForget));
public Task<RedisResult> ExecuteAsync(IDatabaseAsync database, TArgument argument, bool fireAndForget = false) =>
// database.ScriptEvaluate must be called instead of _script.Evaluate in order to respect the database's key prefix
database.ScriptEvaluateAsync(this._script, this._parameters(argument), flags: RedLockHelper.GetCommandFlags(fireAndForget));
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wow this change is super subtle. Is the idea that all other IDatabase methods will add the key prefix too? We do use non-script evaluations in a few places.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thats right, .WithKeyPrefix(..) returns IDatabase decorator with the key prefix as context data.


// send the smallest possible script to the server
private static string RemoveExtraneousWhitespace(string script) => Regex.Replace(script.Trim(), @"\s+", " ");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -443,7 +443,7 @@ private void CrossProcessAbandonmentHelper(bool asyncWait, bool kill)
}
}

private Command RunLockTaker(TLockProvider engine, params string[] args)
private Command RunLockTaker(TLockProvider engine, string lockType, string lockName)
{
const string Configuration =
#if DEBUG
Expand All @@ -454,6 +454,8 @@ private Command RunLockTaker(TLockProvider engine, params string[] args)
var exeExtension = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? ".exe" : string.Empty;
var exePath = Path.Combine(TestContext.CurrentContext.TestDirectory, "..", "..", "..", "..", "DistributedLockTaker", "bin", Configuration, TargetFramework.Current, "DistributedLockTaker" + exeExtension);

var args = new object[] { lockType, $"{engine.GetLockPrefix()}{lockName}" };

var command = Command.Run(exePath, args, o => o.WorkingDirectory(TestContext.CurrentContext.TestDirectory).ThrowOnError(true))
.RedirectStandardErrorTo(Console.Error);
this._cleanupActions.Add(() =>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
using Moq;
using NUnit.Framework;
using StackExchange.Redis;
using StackExchange.Redis.KeyspaceIsolation;

using System;
using System.Collections.Generic;
using System.Linq;
Expand Down Expand Up @@ -124,6 +126,27 @@ public async Task TestFailedAcquireReleasesWhatHasAlreadyBeenAcquired()
Assert.IsNotNull(handle);
}

[Test]
public void TestAcquireWithLockPrefix()
{
this._provider.Strategy.DatabaseProvider.Databases = new[] { CreateDatabase(keyPrefix: "P") };
var lock1 = this._provider.CreateLock("N");

this._provider.Strategy.DatabaseProvider.Databases = new[] { CreateDatabase() };
var lock2 = this._provider.CreateLock("N");
var lock3 = this._provider.CreateLock("PN");

Assert.NotNull(lock1.TryAcquire());
Assert.NotNull(lock2.TryAcquire());
Assert.Null(lock3.TryAcquire());

IDatabase CreateDatabase(string? keyPrefix = null)
{
var database = RedisServer.GetDefaultServer(0).Multiplexer.GetDatabase();
return keyPrefix is null ? database : database.WithKeyPrefix(keyPrefix);
}
}

private static Mock<IDatabase> CreateDatabaseMock()
{
var mock = new Mock<IDatabase>(MockBehavior.Strict);
Expand All @@ -141,6 +164,10 @@ private static void MockDatabase(Mock<IDatabase> mockDatabase, Func<bool> return
.Returns(() => RedisResult.Create(returns()));
mockDatabase.Setup(d => d.ScriptEvaluateAsync(It.IsAny<string>(), It.IsAny<RedisKey[]>(), It.IsAny<RedisValue[]>(), It.IsAny<CommandFlags>()))
.Returns(() => Task.Run(() => RedisResult.Create(returns())));
mockDatabase.Setup(d => d.ScriptEvaluate(It.IsAny<LuaScript>(), It.IsAny<object>(), It.IsAny<CommandFlags>()))
.Returns(() => RedisResult.Create(returns()));
mockDatabase.Setup(d => d.ScriptEvaluateAsync(It.IsAny<LuaScript>(), It.IsAny<object>(), It.IsAny<CommandFlags>()))
.Returns(() => Task.Run(() => RedisResult.Create(returns())));
mockDatabase.Setup(d => d.SortedSetRemove(It.IsAny<RedisKey>(), It.IsAny<RedisValue>(), It.IsAny<CommandFlags>()))
.Returns(() => (bool)RedisResult.Create(returns()));
mockDatabase.Setup(d => d.SortedSetRemoveAsync(It.IsAny<RedisKey>(), It.IsAny<RedisValue>(), It.IsAny<CommandFlags>()))
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
using Medallion.Threading.Tests.Redis;
using NUnit.Framework;
using StackExchange.Redis;
using StackExchange.Redis.KeyspaceIsolation;

using System;
using System.Collections.Generic;
using System.Diagnostics;
Expand All @@ -22,17 +24,35 @@ protected TestingRedisDatabaseProvider(int count)
{
}

protected TestingRedisDatabaseProvider(int count, string keyPrefix)
: this(Enumerable.Range(0, count).Select(i => RedisServer.GetDefaultServer(i).Multiplexer.GetDatabase().WithKeyPrefix(keyPrefix)))
{
}

// publicly settable so that callers can alter the dbs in use
public IReadOnlyList<IDatabase> Databases { get; set; }

public virtual string CrossProcessLockTypeSuffix => this.Databases.Count.ToString();
}

public interface ITestingRedisWithKeyPrefixDatabaseProvider
{
string KeyPrefix { get; }
}

public sealed class TestingRedisSingleDatabaseProvider : TestingRedisDatabaseProvider
{
public TestingRedisSingleDatabaseProvider() : base(count: 1) { }
}

public sealed class TestingRedisWithKeyPrefixSingleDatabaseProvider : TestingRedisDatabaseProvider, ITestingRedisWithKeyPrefixDatabaseProvider
{
const string Prefix = "distributed_locks:";

public TestingRedisWithKeyPrefixSingleDatabaseProvider() : base(count: 1, keyPrefix: Prefix) { }
public string KeyPrefix => Prefix;
}

public sealed class TestingRedis3DatabaseProvider : TestingRedisDatabaseProvider
{
public TestingRedis3DatabaseProvider() : base(count: 3) { }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,15 @@ public void SetOptions(Action<RedisDistributedSynchronizationOptionsBuilder>? op
this._options = options;
}

public override string? GetLockPrefix()
{
return DatabaseProvider switch
{
ITestingRedisWithKeyPrefixDatabaseProvider p => p.KeyPrefix,
_ => base.GetLockPrefix(),
};
}

public void Options(RedisDistributedSynchronizationOptionsBuilder options)
{
if (this._preparedForHandleLost)
Expand Down
2 changes: 2 additions & 0 deletions DistributedLock.Tests/Infrastructure/TestingLockProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ public abstract class TestingLockProvider<TStrategy> : ITestingNameProvider, IDi
public virtual string GetCrossProcessLockType() => this.CreateLock(string.Empty).GetType().Name;
public virtual void Dispose() => this.Strategy.Dispose();

public string? GetLockPrefix() => Strategy.GetLockPrefix();

/// <summary>
/// Returns a lock whose name is based on <see cref="TestingNameProviderExtensions.GetUniqueSafeName(ITestingNameProvider, string)"/>
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,5 +21,6 @@ public virtual void PerformAdditionalCleanupForHandleAbandonment() { }
public virtual IDisposable? PrepareForHandleLost() => null;
public virtual void PrepareForHighContention() { }
public virtual void Dispose() { }
public virtual string? GetLockPrefix() => null;
}
}
Loading