Lock usage
The eridu-tech/lock component provides a way for managing locks independent of underlying platform or storage.
Initial configuration
To begin using the LockFactory class, you'll need to create and configure an instance:
import { TimeSpan } from "eridu-tech/time-span";
import { MemoryLockAdapter } from "eridu-tech/lock/memory-lock-adapter";
import { LockFactory } from "eridu-tech/lock";
const lockFactory = new LockFactory({
// You can provide default TTL value
// If you set it to null it means locks will not expire and most be released manually by default.
defaultTtl: TimeSpan.fromSeconds(2),
// You can choose the adapter to use
adapter: new MemoryLockAdapter(),
});
Here is a complete list of settings for the LockFactory class.
Lock basics
Creating a lock
const lock = lockFactory.create("shared-resource");
Acquiring and releasing the lock
const hasAquired = await lock.acquire();
if (hasAquired) {
try {
// The critical section
} finally {
await lock.release();
}
}
Alternatively you could write it as follows:
try {
// This method will throw if the lock is not acquired
await lock.acquireOrFail();
// The critical section
} finally {
await lock.release();
}
You need always to wrap the critical section with try-finally so the lock get released when error occurs.
Locks with custom TTL
You can provide a custom TTL for the lock.
const lock = lockFactory.create("shared-resource", {
// Default TTL is 5min if not overrided
// If you set it to null it means locks will not expire and most be released manually.
ttl: TimeSpan.fromSeconds(30),
});
Checking lock state
You can get the lock state by using the getState method, it returns ILockState.
import { LOCK_STATE } from "eridu-tech/lock/contracts";
const lock = lockFactory.create("shared-resource");
const state = await lock.getState();
if (state.type === LOCK_STATE.EXPIRED) {
console.log("The lock doesnt exists");
}
if (state.type === LOCK_STATE.UNAVAILABLE) {
console.log("Lock is acquired by different owner");
}
if (state.type === LOCK_STATE.ACQUIRED) {
console.log("The lock is acquired");
}
Patterns
Refreshing locks
The lock can be refreshed by the current owner before it expires. This is particularly useful for long-running tasks,
instead of setting an excessively long TTL initially, you can start with a shorter one and use the refresh method to set the TTL of the lock:
import { delay } from "eridu-tech/utilities/functions";
const lock = lockFactory.create("resource", {
ttl: TimeSpan.fromMinutes(1),
});
async function doWork(): Promise<boolean> {
// ... critical section
}
const hasAcquired = await lock.acquire();
if (hasAcquired) {
try {
while (true) {
await lock.refresh(TimeSpan.fromMinutes(1));
const hasFinished = await doWork();
if (hasFinished) {
break;
}
await delay(TimeSpan.fromSeconds(1));
}
} finally {
await lock.release();
}
}
Note: A lock must have an expiration (a ttl value) to be refreshed. You cannot refresh a lock that was created without an expiration (with ttl: null)
// Create a lock with no expiration (non-refreshable)
const lock = lockFactory.create("resource", {
ttl: null,
});
// A refresh attempt on this lock will fail
const hasRefreshed = await lock.refresh();
// This will log 'false' because the lock cannot be refreshed
console.log(hasRefreshed);
Additional methods
The releaseOrFail method is the same release method but it throws an error when not enable to release the lock:
const lock = lockFactory.create("resource");
await lock.releaseOrFail();
The forceRelease method releases the lock regardless of the owner:
const lock = lockFactory.create("resource");
await lock.forceRelease();
The refreshOrFail method is the same refresh method but it throws an error when not enable to refresh the lock:
const lock = lockFactory.create("resource");
await lock.refreshOrFail();
The runOrFail method automatically manages lock acquisition and release around function execution.
It calls acquireOrFail before invoking the function and calls release in a finally block, ensuring the lock is always freed, even if an error occurs during execution.
const lock = lockFactory.create("resource");
await lock.runOrFail(async () => {
// ... critical section
});
Note the method throws an error when the lock cannot be acquired.
You can provide synchronous or asynchronous Invocable<[], TValue | Promise<TValue>> as values for the runOrFail method.
Lock instance variables
The Lock class exposes instance variables such as:
const lock = lockFactory.create("resource");
// Will return the key of the lock which is "resource"
console.log(lock.key);
// Will return the id of the lock
console.log(lock.id);
// Will return the ttl of the lock
console.log(lock.ttl);
Lock id
By default the lock id is autogenerated but it can also manually defined.
const lock = lockFactory.create("lock", {
lockId: "my-lock-id",
});
const hasAcquire = await lock.acquire();
if (hasAcquired) {
console.log("Shared resource");
await lock.release();
}
Manually defining lock id is primarily useful for debugging or implementing manual resource locking by the end user.
An example of manual resource locking by the end user can be found in a multi-user CMS, the end user manually locks a document during editing, this resource lock prevents simultaneous edits and data corruption.
In most cases, setting a custom lock id is unnecessary. Misusing this feature could result in different locks sharing the same lock id while modifying the same resource simultaneously, which may lead to race conditions.
Retrying acquiring lock by attempts
To retry acquiring lock you can use the retry middleware.
Retrying acquiring lock with acquireOrFail method:
import { retry } from "eridu-tech/resilience";
import { FailedAcquireLockError } from "eridu-tech/lock/contracts";
import { use } from "eridu-tech/middleware";
const lock = lockFactory.create("lock");
try {
await use(async () => {
await lock.acquireOrFail();
}, [
retry({
maxAttempts: 4,
errorPolicy: FailedAcquireLockError,
}),
])();
// The critical section
} finally {
await lock.release();
}
Retrying acquiring lock with acquire method:
import { retry } from "eridu-tech/resilience";
import { use } from "eridu-tech/middleware";
const lock = lockFactory.create("lock");
const hasAquired = await use(async () => {
return await lock.acquire();
}, [
retry({
maxAttempts: 4,
errorPolicy: {
treatFalseAsError: true,
},
}),
])();
if (hasAquired) {
try {
// The critical section
} finally {
await lock.release();
}
}
Retrying acquiring lock with runOrFail method:
import { retry } from "eridu-tech/resilience";
import { FailedAcquireLockError } from "eridu-tech/lock/contracts";
import { use } from "eridu-tech/middleware";
const lock = lockFactory.create("lock");
await use(async () => {
await lock.runOrFail(async () => {
// The critical section
});
}, [
retry({
maxAttempts: 4,
errorPolicy: FailedAcquireLockError,
}),
])();
Retrying acquiring lock by interval
To retry acquiring lock at regular intervals you can use the retryInterval middleware:
Retrying acquiring lock with acquireOrFail method:
import { retryInterval } from "eridu-tech/resilience";
import { FailedAcquireLockError } from "eridu-tech/lock/contracts";
import { use } from "eridu-tech/middleware";
import { TimeSpan } from "eridu-tech/time-span";
const lock = lockFactory.create("resource");
try {
await use(async () => {
await lock.acquireOrFail();
}, [
retryInterval({
// Time to wait 1 minute
time: TimeSpan.fromMinutes(1),
// Interval to try acquire the lock
interval: TimeSpan.fromSeconds(1),
errorPolicy: FailedAcquireLockError,
}),
])();
// ... critical section
} finally {
await lock.release();
}
Retrying acquiring lock with acquire method:
import { retryInterval } from "eridu-tech/resilience";
import { use } from "eridu-tech/middleware";
import { TimeSpan } from "eridu-tech/time-span";
const lock = lockFactory.create("resource");
const hasAcquired = await use(async () => {
return await lock.acquire();
}, [
retryInterval({
time: TimeSpan.fromMinutes(1),
interval: TimeSpan.fromSeconds(1),
errorPolicy: {
treatFalseAsError: true,
},
}),
])();
if (hasAcquired) {
try {
// ... critical section
} finally {
await lock.release();
}
}
Retrying acquiring lock with runOrFail method:
import { retryInterval } from "eridu-tech/resilience";
import { FailedAcquireLockError } from "eridu-tech/lock/contracts";
import { use } from "eridu-tech/middleware";
import { TimeSpan } from "eridu-tech/time-span";
const lock = lockFactory.create("resource");
await use(async () => {
await lock.runOrFail(async () => {
// ... critical section
});
}, [
retryInterval({
time: TimeSpan.fromMinutes(1),
interval: TimeSpan.fromSeconds(1),
errorPolicy: FailedAcquireLockError,
}),
])();
Note using retryInterval middleware with lock acquiring in a HTTP request handler is discouraged because it blocks the HTTP request handler causing the handler wait until the lock becomes available or the timeout is reached. This will delay HTTP request handler to generate response and will make frontend app slow because of HTTP request handler.
Serialization and deserialization of lock
Locks can be serialized, allowing them to be transmitted over the network to another server and later deserialized for reuse.
This means you can, for example, acquire the lock on the main server, transfer it to a queue worker server, and release it there.
In order to serialize or deserialize a lock you need pass an object that implements ISerderRegister contract like the Serde class to LockFactory.
Manually serializing and deserializing the lock:
import { RedisLockAdapter } from "eridu-tech/lock/redis-lock-adapter";
import { LockFactory } from "eridu-tech/lock";
import { Serde } from "eridu-tech/serde";
import { SuperJsonSerdeAdapter } from "eridu-tech/serde/super-json-serde-adapter";
const serde = new Serde(new SuperJsonSerdeAdapter());
const redisClient = new Redis("YOUR_REDIS_CONNECTION");
const lockFactory = new LockFactory({
// You can laso pass in an array of Serde class instances
serde,
adapter: new RedisLockAdapter(redisClient),
});
const lock = lockFactory.create("resource");
const serializedLock = serde.serialize(lock);
const deserializedLock = serde.deserialize(lock);
When serializing or deserializing a lock, you must use the same Serde instances that were provided to the LockFactory. This is required because the LockFactory injects custom serialization logic for ILock instance into Serde instances.
Note you only need manuall serialization and deserialization when integrating with external libraries.
As long you pass the same Serde instances with all other components you dont need to serialize and deserialize the lock manually.
import { RedisLockAdapter } from "eridu-tech/lock/redis-lock-adapter";
import type { ILock } from "eridu-tech/lock/contracts";
import { LockFactory } from "eridu-tech/lock";
import { RedisPubSubEventBusAdapter } from "eridu-tech/event-bus/redis-pub-sub-event-bus-adapter";
import { EventBus } from "eridu-tech/event-bus";
import { Serde } from "eridu-tech/serde";
import { SuperJsonSerdeAdapter } from "eridu-tech/serde/super-json-serde-adapter";
const serde = new Serde(new SuperJsonSerdeAdapter());
const redis = new Redis("YOUR_REDIS_CONNECTION");
type EventMap = {
"sending-lock-over-network": {
lock: ILock;
};
};
const eventBus = new EventBus<EventMap>({
adapter: new RedisPubSubEventBusAdapter({
client: redis,
serde,
}),
});
const lockFactory = new LockFactory({
serde,
adapter: new RedisLockAdapter(redis),
eventBus,
});
const lock = lockFactory.create("resource");
// We are sending the lock over the network to other servers.
await eventBus.dispatch("sending-lock-over-network", {
lock,
});
// The other servers will recieve the serialized lock and automattically deserialize it.
await eventBus.addListener("sending-lock-over-network", ({ lock }) => {
// The lock is deserialized and can be used
console.log("LOCK:", lock);
});
Separating lock creation from manipulation
The library includes 2 additional contracts:
-
ILock- Allows only for manipulating of the lock. -
ILockFactory- Allows only for creation of locks.
Further information
For further information refer to eridu-tech/lock API docs.