Skip to content

Commit

Permalink
Fix #464 - add lock timeout
Browse files Browse the repository at this point in the history
  • Loading branch information
johnml1135 committed Sep 3, 2024
1 parent b91a235 commit 76e5ed9
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,5 @@ public class ServiceOptions
public const string Key = "Service";

public string ServiceId { get; set; } = "machine_api";
public TimeSpan ReadWriteLockTimeout { get; set; } = TimeSpan.FromSeconds(55);
}
Original file line number Diff line number Diff line change
@@ -1,18 +1,25 @@
namespace Serval.Machine.Shared.Services;

public class DistributedReaderWriterLock(string hostId, IRepository<RWLock> locks, IIdGenerator idGenerator, string id)
: IDistributedReaderWriterLock
public class DistributedReaderWriterLock(
string hostId,
IRepository<RWLock> locks,
IIdGenerator idGenerator,
string id,
TimeSpan defaultLifetime
) : IDistributedReaderWriterLock
{
private readonly string _hostId = hostId;
private readonly IRepository<RWLock> _locks = locks;
private readonly IIdGenerator _idGenerator = idGenerator;
private readonly string _id = id;
private readonly TimeSpan _defaultLifetime = defaultLifetime;

public async Task<IAsyncDisposable> ReaderLockAsync(
TimeSpan? lifetime = default,
CancellationToken cancellationToken = default
)
{
lifetime ??= _defaultLifetime;
string lockId = _idGenerator.GenerateId();
if (!await TryAcquireReaderLock(lockId, lifetime, cancellationToken))
{
Expand Down Expand Up @@ -42,6 +49,7 @@ public async Task<IAsyncDisposable> WriterLockAsync(
CancellationToken cancellationToken = default
)
{
lifetime ??= _defaultLifetime;
string lockId = _idGenerator.GenerateId();
if (!await TryAcquireWriterLock(lockId, lifetime, cancellationToken))
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,13 @@ await _locks.InsertAsync(
// the lock is already made - no new one needs to be made
// This is done instead of checking if it exists first to prevent race conditions.
}
return new DistributedReaderWriterLock(_serviceOptions.ServiceId, _locks, _idGenerator, id);
return new DistributedReaderWriterLock(
_serviceOptions.ServiceId,
_locks,
_idGenerator,
id,
_serviceOptions.ReadWriteLockTimeout
);
}

public async Task<bool> DeleteAsync(string id, CancellationToken cancellationToken = default)
Expand Down

0 comments on commit 76e5ed9

Please sign in to comment.