# 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](https://tinyshed.org/tinystore/docs/guides/locks) explains how to use them, and the [Python](https://tinyshed.org/tinystore/docs/reference/python/locks), [Go](https://tinyshed.org/tinystore/docs/reference/go/locks) and [Rust](https://tinyshed.org/tinystore/docs/reference/rust/locks) pages list the same API.

## LockOptions

```ts
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

```ts
interface SemaphoreOptions extends LockOptions {
    /** how many may hold a key at once, 1 to 1000 */
    limit: number
}
```

## HoldOptions

```ts
interface HoldOptions {
    /** how long the hold waits in line: 10 s unless said, then InUseError */
    wait?: Duration | undefined
}
```

## Tried

```ts
type Tried<T> = {
    acquired: true
    value: T
} | {
    acquired: false
}
```

What tryHold gives: the function's value, or that the key was held.

## Lease

```ts
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

```ts
interface Permit {
    readonly signal: AbortSignal
}
```

A holding of a semaphore's key: one of its limit.

## Lock

```ts
class Lock {
    readonly name: string
}
```

Keys held one holder at a time: open them with `store.lock(name)`.

### Lock.hold

```ts
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

```ts
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

```ts
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

```ts
hold<T>(key: Key, fn: (permit: Permit) => T | Promise<T>, options?: HoldOptions): Promise<T>
```

### Semaphore.tryHold

```ts
tryHold<T>(key: Key, fn: (permit: Permit) => T | Promise<T>): Promise<Tried<T>>
```
