Skip to content
Open
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
112 changes: 99 additions & 13 deletions src/DistributedLock.Core/CompositeDistributedSynchronizationHandle.cs
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ public static async ValueTask<AcquireResult> TryAcquireAllAsync<TPrimitive>(
IReadOnlyList<TPrimitive> primitives,
Func<TPrimitive, TimeSpan, CancellationToken, ValueTask<IDistributedSynchronizationHandle?>> acquireFunc,
TimeoutValue timeout,
bool observeLockLostToken,
CancellationToken cancellationToken)
where TPrimitive : class
{
Expand All @@ -68,22 +69,42 @@ public static async ValueTask<AcquireResult> TryAcquireAllAsync<TPrimitive>(
TimeoutTracker timeoutTracker = new(timeout);
List<IDistributedSynchronizationHandle> handles = new(primitives.Count);
CompositeDistributedSynchronizationHandle? result = null;

using var cancellationAggregator = observeLockLostToken ? new CancellationAggregator(primitives.Count) : null;
cancellationAggregator?.Add(cancellationToken);
try
{
foreach (var primitive in primitives)
for (var i = 0; i < primitives.Count; i++)
{
var handle = await acquireFunc(primitive, timeoutTracker.Remaining, cancellationToken)
.ConfigureAwait(false);
if (GetLostPrimitiveOrDefault() is { } lostBeforeAcquire)
{
return new(lostBeforeAcquire, isLost: true);
}

if (handle is null)
IDistributedSynchronizationHandle? handle;
try
{
handle = await acquireFunc(primitives[i], timeoutTracker.Remaining, cancellationAggregator?.Token ?? cancellationToken)
.ConfigureAwait(false);
}
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested && GetLostPrimitiveOrDefault() != null)
{
return new(primitive); // failure
return new(GetLostPrimitiveOrDefault()!, isLost: true);
}

if (handle is null)
{
return new(primitives[i]); // failure
}
handles.Add(handle);
cancellationAggregator?.Add(handle.HandleLostToken);
}

if (GetLostPrimitiveOrDefault() is { } lostAfterAcquire)
{
return new(lostAfterAcquire, isLost: true);
}
if (cancellationAggregator != null) { cancellationToken.ThrowIfCancellationRequested(); }

result = new(handles);
}
finally
Expand All @@ -93,16 +114,29 @@ public static async ValueTask<AcquireResult> TryAcquireAllAsync<TPrimitive>(
await DisposeHandlesAsync(handles).ConfigureAwait(false);
}
}

return new(result);

// handles[i] was acquired from primitives[i]
object? GetLostPrimitiveOrDefault()
{
if (cancellationAggregator is null) { return null; }
for (var j = 0; j < handles.Count; j++)
{
if (handles[j].HandleLostToken.IsCancellationRequested) { return primitives[j]; }
}
return null;
}
}

public readonly struct AcquireResult(object handleOrFailedPrimitive)
public readonly struct AcquireResult(object handleOrFailedPrimitive, bool isLost = false)
{
public IDistributedSynchronizationHandle? GetHandleOrDefault() =>
handleOrFailedPrimitive as IDistributedSynchronizationHandle;
public IDistributedSynchronizationHandle Handle =>
this.GetHandleOrDefault() ?? throw new TimeoutException($"Timed out acquiring '{this.GetFailedName()}'");
this.GetHandleOrDefault()
?? throw (isLost
? new DistributedLockLostException($"Lost '{this.GetFailedName()}' while acquiring remaining locks")
: new TimeoutException($"Timed out acquiring '{this.GetFailedName()}'"));

private string GetFailedName() => handleOrFailedPrimitive switch
{
Expand All @@ -113,6 +147,54 @@ public readonly struct AcquireResult(object handleOrFailedPrimitive)
};
}

private sealed class CancellationAggregator : IDisposable
{
private readonly CancellationTokenSource _cts = new();
private readonly object _gate = new();
private readonly List<CancellationTokenRegistration> _registrations;
private bool _disposed;

public CancellationAggregator(int capacity)
{
_registrations = new List<CancellationTokenRegistration>(capacity);
}
public CancellationToken Token => _cts.Token;

public void Add(CancellationToken token)
{
if (!token.CanBeCanceled) { return; }

lock (_gate)
{
if (_disposed)
{
throw new ObjectDisposedException(nameof(CancellationAggregator));
}
_registrations.Add(
token.Register(static s => ((CancellationTokenSource)s!).Cancel(), _cts));
}
}

public void Dispose()
{
CancellationTokenRegistration[] toDispose;
lock (_gate)
{
if (_disposed) return;
_disposed = true;
toDispose = [.. _registrations];
_registrations.Clear();
}

foreach (var registration in toDispose)
{
registration.Dispose();
}

_cts.Dispose();
}
}

private static CancellationTokenSource? CreateLinkedCancellationTokenSource(IReadOnlyList<IDistributedSynchronizationHandle> handles)
{
var cancellableTokens = handles
Expand Down Expand Up @@ -179,43 +261,47 @@ public static async ValueTask<IDistributedSynchronizationHandle> GetHandleOrTime
this IDistributedLockProvider provider,
IReadOnlyList<string> names,
TimeoutValue timeout,
bool observeLockLostToken,
CancellationToken cancellationToken) =>
CompositeDistributedSynchronizationHandle.TryAcquireAllAsync(
CompositeDistributedSynchronizationHandle.FromNames(names, provider ?? throw new ArgumentNullException(nameof(provider)), static (p, n) => p.CreateLock(n)),
static (p, t, c) => SyncViaAsync.IsSynchronous ? p.TryAcquire(t, c).AsValueTask() : p.TryAcquireAsync(t, c),
timeout, cancellationToken);
timeout, observeLockLostToken, cancellationToken);

public static ValueTask<CompositeDistributedSynchronizationHandle.AcquireResult> TryAcquireAllReadLocksInternalAsync(
this IDistributedReaderWriterLockProvider provider,
IReadOnlyList<string> names,
TimeoutValue timeout,
bool observeLockLostToken,
CancellationToken cancellationToken) =>
CompositeDistributedSynchronizationHandle.TryAcquireAllAsync(
CompositeDistributedSynchronizationHandle.FromNames(
names,
provider ?? throw new ArgumentNullException(nameof(provider)),
static (p, n) => p.CreateReaderWriterLock(n)),
static (p, t, c) => SyncViaAsync.IsSynchronous ? p.TryAcquireReadLock(t, c).AsValueTask() : p.TryAcquireReadLockAsync(t, c),
timeout, cancellationToken);
timeout, observeLockLostToken, cancellationToken);

public static ValueTask<CompositeDistributedSynchronizationHandle.AcquireResult> TryAcquireAllWriteLocksInternalAsync(
this IDistributedReaderWriterLockProvider provider,
IReadOnlyList<string> names,
TimeoutValue timeout,
bool observeLockLostToken,
CancellationToken cancellationToken) =>
CompositeDistributedSynchronizationHandle.TryAcquireAllAsync(
CompositeDistributedSynchronizationHandle.FromNames(
names,
provider ?? throw new ArgumentNullException(nameof(provider)),
static (p, n) => p.CreateReaderWriterLock(n)),
static (p, t, c) => SyncViaAsync.IsSynchronous ? p.TryAcquireWriteLock(t, c).AsValueTask() : p.TryAcquireWriteLockAsync(t, c),
timeout, cancellationToken);
timeout, observeLockLostToken, cancellationToken);

public static ValueTask<CompositeDistributedSynchronizationHandle.AcquireResult> TryAcquireAllSemaphoresInternalAsync(
this IDistributedSemaphoreProvider provider,
IReadOnlyList<string> names,
int maxCount,
TimeoutValue timeout,
bool observeLockLostToken,
CancellationToken cancellationToken) =>
CompositeDistributedSynchronizationHandle.TryAcquireAllAsync(
CompositeDistributedSynchronizationHandle.FromNames(
Expand All @@ -224,5 +310,5 @@ public static async ValueTask<IDistributedSynchronizationHandle> GetHandleOrTime
static (s, n) => s.provider.CreateSemaphore(n, s.maxCount)),
static (p, t, c) => SyncViaAsync.IsSynchronous ? p.TryAcquire(t, c).AsValueTask() : p.TryAcquireAsync(t, c),
timeout,
cancellationToken);
observeLockLostToken, cancellationToken);
}
29 changes: 29 additions & 0 deletions src/DistributedLock.Core/DistributedLockLostException.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
namespace Medallion.Threading;

/// <summary>
/// An exception thrown when acquiring multiple locks/primitives fails because an already-acquired
/// lock was lost before all of them could be acquired
/// </summary>
[Serializable]
public sealed class DistributedLockLostException : InvalidOperationException
{
/// <summary>
/// Constructs a new instance of <see cref="DistributedLockLostException"/> with a default message
/// </summary>
public DistributedLockLostException() : this("A lock was lost during acquisition") { }

/// <summary>
/// Constructs an instance of <see cref="DistributedLockLostException"/> with the given <paramref name="message"/>
/// </summary>
public DistributedLockLostException(string message) : base(message) { }

/// <summary>
/// Constructs an instance of <see cref="DistributedLockLostException"/> with the given <paramref name="message"/> and <paramref name="innerException"/>
/// </summary>
public DistributedLockLostException(string message, Exception innerException) : base(message, innerException) { }

#if NET8_0_OR_GREATER
[Obsolete] // calls obsolete constructor
#endif
private DistributedLockLostException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { }
}
Loading