acquireLock method
Makes multiple attempts to acquire a lock by its key within give time interval.
context
(optional) a context to trace execution through call chain.key
a unique lock key to acquire.ttl
a lock timeout (time to live) in milliseconds.timeout
a lock acquisition timeout. Return Future that receives null for success. Throw error
Implementation
@override
Future acquireLock(
IContext? context, String key, int ttl, int timeout) async {
var retryTime = DateTime.now()
.toUtc()
.add(Duration(milliseconds: timeout))
.millisecondsSinceEpoch;
// Try to get lock first
var result = await tryAcquireLock(context, key, ttl);
if (result) {
return null;
}
// Start retrying
var now = DateTime.now().toUtc().millisecondsSinceEpoch;
for (; now <= retryTime;) {
await Future.delayed(Duration(milliseconds: _retryTimeout));
result = await tryAcquireLock(context, key, ttl);
if (result) {
return;
}
now = DateTime.now().toUtc().millisecondsSinceEpoch;
}
// When timeout expires throw exception
throw ConflictException(
context != null ? ContextResolver.getTraceId(context) : null,
'LOCK_TIMEOUT',
'Acquiring lock $key failed on timeout')
.withDetails('key', key);
}