Reference / Locks API for Bun and Node
Locks API for Bun and Node
Every public class, function and type of the Locks engine in @tinyshed/tinystore, generated from its source. The Locks guide explains how to use them, and the Python, Go and Rust pages list the same API.
LockOptions
interface LockOptions {
/** how long a lease lasts from its last renewal: 10 s unless said, 1 s to 1 hour */
ttl?: Duration | undefined
/** how long a lease lasts from its grant, however it is renewed: past it the next in line holds the key */
maxHold?: Duration | undefined
}SemaphoreOptions
interface SemaphoreOptions extends LockOptions {
/** how many may hold a key at once, 1 to 1000 */
limit: number
}HoldOptions
interface HoldOptions {
/** how long the hold waits in line: 10 s unless said, then InUseError */
wait?: Duration | undefined
}Tried
type Tried<T> = {
acquired: true
value: T
} | {
acquired: false
}What tryHold gives: the function's value, or that the key was held.
Lease
interface Lease {
/** grows with every lease the store gives: hand it to whatever must refuse a late holder */
readonly fence: bigint
/** aborts when the lease is lost: run out, revoked at maxHold, or its store closed */
readonly signal: AbortSignal
}A holding of a lock's key, given to the function that holds it.
Permit
interface Permit {
readonly signal: AbortSignal
}A holding of a semaphore's key: one of its limit.
Lock
class Lock {
readonly name: string
}Keys held one holder at a time: open them with store.lock(name).
Lock.hold
hold<T>(key: Key, fn: (lease: Lease) => T | Promise<T>, options?: HoldOptions): Promise<T>Waits for key, holds it while fn runs and lets it go, giving what fn gives. A key still held after the wait is InUseError; a lease lost while fn ran is LostError, though fn succeeded.
await invoices.hold(invoice.id, lease => charge(invoice, { fence: lease.fence, signal: lease.signal }))Lock.tryHold
tryHold<T>(key: Key, fn: (lease: Lease) => T | Promise<T>): Promise<Tried<T>>Holds key while fn runs if nobody holds it, and says it was held without waiting if somebody does.
Semaphore
class Semaphore {
readonly name: string
readonly limit: number
}Keys held by up to their limit at a time: open them with store.semaphore(name, { limit }).
Semaphore.hold
hold<T>(key: Key, fn: (permit: Permit) => T | Promise<T>, options?: HoldOptions): Promise<T>Semaphore.tryHold
tryHold<T>(key: Key, fn: (permit: Permit) => T | Promise<T>): Promise<Tried<T>>