Skip to content

eclipse ​

@c9up/eclipse: distributed locks: one key, one holder, with memory, Redis and SQL database stores behind one store contract. Guide: Locks.

Installation ​

bash
pnpm add @c9up/eclipse

ream configure @c9up/eclipse registers the provider, writes config/lock.ts and adds LOCK_STORE=redis to .env with its validation rule. The Redis store needs @c9up/quasar (an optional peer) when it names a connection; the database store needs @c9up/atlas when it is not handed a client.

Entry points ​

ImportContents
@c9up/eclipseLockManager, LockFactory, Lock, defineConfig, stores, the three stores, durations, errors, types
@c9up/eclipse/providerEclipseProvider (default export)
@c9up/eclipse/services/mainThe booted LockManager (default export), setLocks, getLocks, clearLocks
@c9up/eclipse/schedulerschedulerBackend, the lock backend of ream's scheduler
@c9up/eclipse/testingfakeLocks
@c9up/eclipse/configureconfigure(codemods), run by ream configure

Exports ​

@c9up/eclipse ​

ExportKindDescription
LockManagerclassThe configured stores, built on first use; creates and restores locks.
LockFactoryclassOne store with the defaults its locks inherit.
LockclassA lease on one key, not acquired until asked.
defineConfigfunctionChecks config/lock.ts where it is written: stores present, default a declared store.
storesconstStore factories for a config: memory(), redis(options), database(options?).
MemoryStoreclassIn-process store. Locks nothing across processes; for tests and a single process.
RedisStoreclassSET NX PX to take a lease, Lua scripts to release and extend only the holder's own.
DatabaseStoreclassOne table on PostgreSQL, MySQL or SQLite, shared by every replica reaching the database.
parseDurationfunctionparseDuration(value: string): number: '30s', '5m', '500ms' to milliseconds; a bare number string is milliseconds.
resolveMsfunctionresolveMs(value: Duration | undefined, fallback: number | null): number | null.
assertValidTtlfunctionassertValidTtl(ttl: number | null): void: throws E_ECLIPSE_INVALID_TTL unless finite and positive, or null.
errorsnamespaceThe package's errors, one class per code, see Errors.
Durationtypenumber | string | null: milliseconds, a duration string, or null for never expires.
LockConfiginterface{ default: string; stores: Record<string, StoreFactory>; retry?: RetryConfig; ttl?: Duration }.
StoreFactorytype() => LockStore.
LockStoreinterfaceThe store contract: save, delete, forceDelete, exists, extend, optional disconnect.
RetryConfiginterface{ attempts?: number; delay?: Duration; timeout?: Duration }.
LockAcquireOptionsinterface{ retry?: RetryConfig }.
LockFactoryOptionsinterface{ retry?: RetryConfig; ttl?: Duration }.
ResolvedLockConfiginterfaceLockFactoryOptions with every value resolved to milliseconds.
SerializedLockinterface{ key: string; owner: string; ttl: number | null; expirationTime: number | null }.
RedisStoreOptionsinterface{ prefix?: string }, default 'eclipse:lock:'.
LockRedisClientinterfaceThe commands the Redis store sends: set, evalsha, script, del, exists.
LockRedisResolvertypeLockRedisClient | (() => LockRedisClient | Promise<LockRedisClient>).
DatabaseStoreOptionsinterface{ tableName?: string; sweepIntervalMs?: number }.
LockDatabaseinterface{ readonly dialect: string; rawQuery(sql: string, bindings: unknown[]): PromiseLike<readonly LockRow[]> }.
LockDatabaseSourcetypeLockDatabase | (() => LockDatabase | Promise<LockDatabase>).
LockRowtypeRecord<string, unknown>.

@c9up/eclipse/provider ​

ExportKindDescription
default (EclipseProvider)providerregister() binds the LockManager built from the lock config; boot() seats it on services/main; shutdown() calls disconnectAll().
EclipseAppContextinterface{ container; config }: the host the provider needs.

@c9up/eclipse/services/main ​

ExportKindDescription
defaultconstThe booted LockManager; a member read before boot throws.
setLocksfunctionsetLocks(value: LockManager): void.
getLocksfunctiongetLocks(): LockManager | undefined.
clearLocksfunctionclearLocks(): void.

@c9up/eclipse/scheduler ​

ExportKindDescription
schedulerBackendfunctionschedulerBackend(manager: LockManager | (() => LockManager), options?: SchedulerBackendOptions): SchedulerLockBackend. Takes each task's lease with acquireImmediately() and renews it every third of its TTL while the task runs.
SchedulerBackendOptionsinterface{ store?: string; prefix?: string; ttl?: Duration; onLeaseLost?: (name: string, error: Exception) => void }. prefix defaults to 'schedule:'; ttl overrides the scheduler's; onLeaseLost defaults to a process warning.
SchedulerLockBackendinterface{ acquire(name: string, ttlMs: number): Promise<boolean>; release(name: string): Promise<void> }.

@c9up/eclipse/testing ​

ExportKindDescription
fakeLocksfunctionfakeLocks(container?: FakeableContainer): () => void. Seats a memory-store LockManager on services/main and, given a container, swaps the three tokens; the returned function restores both.
FakeableContainerinterface{ swap(token: unknown, factory: () => unknown): void; restore(token: unknown): void }.

LockManager ​

new LockManager(config: LockConfig); throws on an invalid config.

MemberSignatureDescription
useuse(name?: string): LockFactoryThe named store (default one without a name), built once. Throws E_ECLIPSE_UNKNOWN_STORE.
createLockcreateLock(key: string, ttl?: Duration): LockA lock on the default store.
restoreLockrestoreLock(serialized: SerializedLock): LockRebuild a lock serialized by another process.
disconnectAlldisconnectAll(): Promise<void>Release what each built store opened itself; a client passed in is left open.

LockFactory ​

new LockFactory(store: LockStore, options?: LockFactoryOptions).

MemberSignatureDescription
getStoregetStore(): LockStoreThe store this factory leases from.
createLockcreateLock(key: string, ttl?: Duration): LockA lock on key, not yet acquired. ttl bounds how long a crashed holder keeps the key.
restoreLockrestoreLock(serialized: SerializedLock): LockRebuild a lock from Lock.serialize().

Lock ​

MemberSignatureDescription
getKeygetKey(): stringThe key leased.
getOwnergetOwner(): stringThe owner token, random per lock unless restored.
serializeserialize(): SerializedLockFlatten to data for another process.
isExpiredisExpired(): booleanPast its expiry; a lock without TTL never is.
getRemainingTimegetRemainingTime(): number | nullMilliseconds left, at least 0; null without TTL.
isLockedisLocked(): Promise<boolean>Whether anyone holds the key.
acquireacquire(options?: LockAcquireOptions): Promise<boolean>Take the lock, retrying while it is held; false once the retry budget is spent.
acquireImmediatelyacquireImmediately(): Promise<boolean>Take it if free now, never wait.
runrun<T>(callback: () => Promise<T>): Promise<[true, T] | [false, null]>Acquire, run, release. Throws E_LOCK_NOT_OWNED when the work succeeded but the lease lapsed.
runImmediatelyrunImmediately<T>(callback: () => Promise<T>): Promise<[true, T] | [false, null]>run without waiting.
releaserelease(): Promise<void>Release; throws E_LOCK_NOT_OWNED when this holder no longer owns it.
forceReleaseforceRelease(): Promise<void>Release whoever holds it.
extendextend(duration?: Duration): Promise<void>Push the expiry out from now (the lock's TTL without an argument); throws E_LOCK_NOT_OWNED.

Stores ​

MemberSignatureDescription
stores.memorymemory(): StoreFactoryA MemoryStore.
stores.redisredis(options: ({ client: LockRedisClient } | { connection?: string }) & RedisStoreOptions): StoreFactoryA RedisStore on a client, or on a @c9up/quasar connection loaded on the first lock.
stores.databasedatabase(options?: { connection?: LockDatabaseSource | string; tableName?: string }): StoreFactoryA DatabaseStore on a client, an atlas connection name, or atlas' default connection.
new RedisStorenew RedisStore(client: LockRedisResolver, options?: RedisStoreOptions)
new DatabaseStorenew DatabaseStore(source: LockDatabaseSource, options?: DatabaseStoreOptions)Table locks by default, may be schema-qualified; lapsed rows are swept at most once a minute by default.
new MemoryStorenew MemoryStore()

The database store's table has key (primary), owner and expiration (epoch milliseconds, NULL never expires). The package ships the migration as stubs/database/migrations/9200_create_locks.stub.

Configuration ​

config/lock.ts, read under the lock key.

OptionTypeDefaultDescription
defaultstring—The store createLock() uses. The generated config reads LOCK_STORE.
storesRecord<string, StoreFactory>—Named stores, built on first use.
ttlDuration30sLease length when createLock names none; null never expires.
retry.attemptsnumberInfinityAttempts of a blocking acquire().
retry.delayDuration250msWait between attempts.
retry.timeoutDurationnoneTotal time budget of acquire(); 0 means do not wait.

The generated config declares memory: stores.memory() and redis: stores.redis({ connection: 'main' }).

Container bindings ​

TokenResolves to
LockManager (class)The LockManager built from config/lock.ts
'eclipse.lock'The same manager
'lock'The same manager

The two string tokens are typed on ContainerBindings once @c9up/eclipse is imported.

Errors ​

CodeRaised when
E_LOCK_NOT_OWNEDrelease() or extend() by a holder that no longer owns the lock, or run() whose work outlived the lease.
E_LOCK_STORAGE_ERRORThe store failed while saving, reading or deleting.
E_ECLIPSE_INVALID_TTLA TTL is not a finite positive number of milliseconds, or null.
E_ECLIPSE_INVALID_DURATIONA duration string cannot be read.
E_ECLIPSE_INVALID_RETRYA retry option is out of range.
E_ECLIPSE_INVALID_CONFIGThe config lacks stores or default, or is not a lock config.
E_ECLIPSE_MISSING_CONFIGconfig/lock.ts is missing.
E_ECLIPSE_UNKNOWN_STOREdefault or use(name) names a store that is not declared.
E_ECLIPSE_QUASAR_MISSINGA Redis store names a connection and @c9up/quasar is not installed.
E_ECLIPSE_INCOMPLETE_CONNECTIONThe quasar connection lacks a command the Redis store sends.
E_ECLIPSE_DATABASE_UNAVAILABLEA database store asks for atlas, which is not installed or has not booted.
E_ECLIPSE_UNSUPPORTED_DATABASEA database store was given a dialect other than PostgreSQL, MySQL or SQLite.
E_ECLIPSE_NOT_BOOTEDservices/main was used before EclipseProvider.boot() or setLocks().
E_ECLIPSE_INVALID_BINDINGThe container resolved the LockManager token to something that is not a LockManager.

Each one is a class of errors, a flare Exception: read error.code, or test error instanceof errors.E_LOCK_NOT_OWNED.

Migration ​

  • EclipseError is gone: test error.code, or instanceof a class of errors.
  • The classes are named by their code: LockNotOwnedError is errors.E_LOCK_NOT_OWNED, LockStorageError is errors.E_LOCK_STORAGE_ERROR, InvalidTtlError is errors.E_ECLIPSE_INVALID_TTL, InvalidRetryError is errors.E_ECLIPSE_INVALID_RETRY, InvalidDurationError is errors.E_ECLIPSE_INVALID_DURATION, MissingConfigError is errors.E_ECLIPSE_MISSING_CONFIG, InvalidConfigError is errors.E_ECLIPSE_INVALID_CONFIG, UnknownStoreError is errors.E_ECLIPSE_UNKNOWN_STORE.
  • E_LOCK_NOT_OWNED and E_LOCK_STORAGE_ERROR now carry the messages of the lock module they come from: "Looks like you are trying to update or release a lock that is not acquired by you" and "Lock storage error: <reason>". The lock's name is on error.key, and the failed store operation on error.operation; build them as new errors.E_LOCK_NOT_OWNED(undefined, { key }) and new errors.E_LOCK_STORAGE_ERROR([reason], { operation }).

See also ​