# zidane/durable/testing

> The conformance kit for durable storages, and the check that a scenario runs again the same way.

Import: `import { … } from 'zidane/durable/testing'`. Source: [src/durable/testing/index.ts](https://github.com/Tahul/zidane/blob/main/src/durable/testing/index.ts).

Use this entry point in the tests of a custom `DurableStorage` or of code that runs on the durable kernel. `registerStorageConformance` registers the storage contract's cases ([DURABILITY.md](https://github.com/Tahul/zidane/blob/main/docs/DURABILITY.md) section 4) with your test runner. The kit checks the receipts of every commit call, and compares random commit calls with the memory storage. `reopen` opens a second instance on the same data, as a restart does. Without it, the kit skips the persistence cases. `assertReplayDeterministic` runs a scenario and records its host calls. Then it runs the scenario again on fresh storage from the recorded host calls. With `prefixes: true`, it also runs the scenario once per crash point. It throws at the first commit or host call that differs. `memoryFileSystem` is an in-memory file system for `jsonlStorage`. Its `fail` option makes chosen calls throw. See [durable tasks and hosts](https://zidane.si/docs/durable-kernel.md).

```ts
import { describe, it } from 'bun:test'
import { memoryStorage, openDurable } from 'zidane/durable'
import { assertReplayDeterministic, registerStorageConformance } from 'zidane/durable/testing'

registerStorageConformance('memory', { open: async () => memoryStorage() }, { describe, it })

it('a session makes the same commits when it runs again', async () => {
  await assertReplayDeterministic(async ({ host, storage }) => {
    const durable = await openDurable({ storage, host })
    const session = await durable.session('s1')
    await session.commit(tx => tx.appendEntry(session.rootConversationId, { text: 'hi' }))
    const count = (await session.history()).length
    await durable.dispose()
    return count
  }, async () => memoryStorage(), { prefixes: true })
})
```

## Functions

### `assertReplayDeterministic`

Function.

Run `scenario` recorded, then replayed on fresh storage from `open`, then
once per journal prefix (a crash at every entry, continued live). Throws on
any divergence. Throws when the full replay's outcome differs from the
recorded one.

```ts
function assertReplayDeterministic(
  scenario: ReplayScenario,
  open: () => Promise<DurableStorage>,
  options?: { prefixes?: boolean },
): Promise<JournalEntry[]>
```

**Parameters**

- `scenario` (`ReplayScenario`): The run to check. It returns a JSON summary of its outcome.
- `open` (`() => Promise<DurableStorage>`): Opens a fresh, empty storage. Called once per run. The check does not close the storages. The caller closes what `open` opens.
- `options?` (`{ prefixes?: boolean }`, default `{}`): `prefixes: true` also replays every journal prefix, a crash at each entry.

**Returns** `Promise<JournalEntry[]>`

Source: [src/durable/testing/replay-check.ts:205](https://github.com/Tahul/zidane/blob/main/src/durable/testing/replay-check.ts#L205)

### `memoryFileSystem`

Function.

A file system in memory.

```ts
function memoryFileSystem(options?: MemoryFileSystemOptions): MemoryFileSystem
```

**Parameters**

- `options?` (`MemoryFileSystemOptions`, default `{}`): The map to share, the process identity, and the failure hook. Default: a new disk.

**Returns** `MemoryFileSystem`

Source: [src/durable/storage/fs-memory.ts:40](https://github.com/Tahul/zidane/blob/main/src/durable/storage/fs-memory.ts#L40)

### `recordingHost`

Function.

A recording host: a deterministic test clock whose calls and commits go to `journal`.

```ts
function recordingHost(options?: { start?: number }): ReplayCheck
```

**Parameters**

- `options?` (`{ start?: number }`, default `{}`): `start` sets the clock's first value.

**Returns** `ReplayCheck`

Source: [src/durable/testing/replay-check.ts:79](https://github.com/Tahul/zidane/blob/main/src/durable/testing/replay-check.ts#L79)

### `registerStorageConformance`

Function.

Register the suite under `name`.

```ts
function registerStorageConformance(
  name: string,
  target: ConformanceTarget,
  runner: ConformanceRunner,
): void
```

**Parameters**

- `name` (`string`): Name of the suite, such as the backend's name.
- `target` (`ConformanceTarget`): Opens the backend, and optionally reopens it on the same data.
- `runner` (`ConformanceRunner`): Your test runner's `describe` and `it`.

Source: [src/durable/testing/storage-conformance.ts:23](https://github.com/Tahul/zidane/blob/main/src/durable/testing/storage-conformance.ts#L23)

### `replayingHost`

Function.

A replaying host over `journal`. A divergence throws. Past the end it runs live.

```ts
function replayingHost(
  journal: readonly JournalEntry[],
  options?: { start?: number },
): ReplayCheck & { readonly diverged: Promise<never>; readonly position: number }
```

**Parameters**

- `journal` (`readonly JournalEntry[]`): The recorded journal to answer from.
- `options?` (`{ start?: number }`, default `{}`): `start` sets the clock's first value when the journal holds no clock reading.

**Returns** `ReplayCheck & { readonly diverged: Promise<never>; readonly position: number }`

Source: [src/durable/testing/replay-check.ts:120](https://github.com/Tahul/zidane/blob/main/src/durable/testing/replay-check.ts#L120)

## Classes

### `HostCallInsideEffectError`

Class.

Thrown when an effect's body calls the host. A replay skips the body, so the call shifts every later journal entry.

```ts
class HostCallInsideEffectError extends Error
```

**Constructor**

```ts
new HostCallInsideEffectError(effect: string, call: string)
```

**Parameters**

- `effect` (`string`): Name of the effect whose body made the call.
- `call` (`string`): The host method it called: `now`, `id` or `effect`.

**Returns** `HostCallInsideEffectError`

**Properties**

- `call` (`string`, readonly): The host method it called: `now`, `id` or `effect`.
- `effect` (`string`, readonly): Name of the effect whose body made the call.

Source: [src/durable/testing/replay-check.ts:58](https://github.com/Tahul/zidane/blob/main/src/durable/testing/replay-check.ts#L58)

### `ReplayDivergenceError`

Class.

A replayed call that is not the one the journal holds at its place.

```ts
class ReplayDivergenceError extends Error
```

**Constructor**

```ts
new ReplayDivergenceError(
  index: number,
  expected: JournalEntry | undefined,
  actual: unknown,
)
```

**Parameters**

- `index` (`number`): Position in the journal where the replay diverged.
- `expected` (`JournalEntry | undefined`): The journal entry at that position, or undefined past the end.
- `actual` (`unknown`): The call or commit the replay made instead.

**Returns** `ReplayDivergenceError`

**Properties**

- `actual` (`unknown`, readonly): The call or commit the replay made instead.
- `expected` (`JournalEntry | undefined`, readonly): The journal entry at that position, or undefined past the end.
- `index` (`number`, readonly): Position in the journal where the replay diverged.

Source: [src/durable/testing/replay-check.ts:27](https://github.com/Tahul/zidane/blob/main/src/durable/testing/replay-check.ts#L27)

## Interfaces

### `ConformanceRunner`

Interface.

The test functions the suite needs.

```ts
interface ConformanceRunner
```

**Properties**

- `describe` (`(name: string, body: () => void) => void`): Your runner's `describe`: groups cases under `name`.
- `it` (`(name: string, body: () => Promise<void>) => void`): Your runner's `it`: registers one async case.

Source: [src/durable/testing/storage-conformance-fixtures.ts:18](https://github.com/Tahul/zidane/blob/main/src/durable/testing/storage-conformance-fixtures.ts#L18)

### `ConformanceTarget`

Interface.

A backend under test.

```ts
interface ConformanceTarget
```

**Properties**

- `open` (`() => Promise<DurableStorage>`): Open the backend on fresh, empty storage.
- `reopen?` (`(storage: DurableStorage) => Promise<DurableStorage>`): Open a second instance on the same stored data, after `storage` closed (a restart). Without it, the suite skips the persistence cases.

Source: [src/durable/testing/storage-conformance-fixtures.ts:10](https://github.com/Tahul/zidane/blob/main/src/durable/testing/storage-conformance-fixtures.ts#L10)

### `MemoryFileSystem`

Interface.

A [`FileSystem`](https://zidane.si/docs/reference/durable.md#FileSystem) in memory.

```ts
interface MemoryFileSystem extends FileSystem
```

**Properties**

- `files` (`Map<string, Uint8Array<ArrayBufferLike>>`, readonly): The files, by path. Change or copy it freely between calls.
- `list` (`(path: string) => Promise<string[]>`, from `FileSystem`): Names of the entries in the directory `path`. Empty when the directory is missing.
- `mkdir` (`(path: string) => Promise<void>`, from `FileSystem`): Create the directory `path` and its missing parents.
- `openAppend` (`(path: string) => Promise<AppendFile>`, from `FileSystem`): Open a file for appending. Create it when it is missing.
- `owner` (`LeaseOwner`, readonly, from `FileSystem`): This process, as the lock file of a storage directory names it.
- `ownerDead` (`(owner: LeaseOwner) => boolean`, from `FileSystem`): Whether the process that wrote a lock file is known to be gone. Another
  writer then takes its lock over. `false` when this file system cannot
  tell, for example a process of another host.
- `read` (`(path: string, range?: ReadRange) => Promise<Uint8Array<ArrayBufferLike> | undefined>`, from `FileSystem`): The bytes of a file, or of `range` of it. `undefined` when the file is missing.
- `remove` (`(path: string) => Promise<void>`, from `FileSystem`): Remove a file. A missing file is not an error.
- `rename` (`(from: string, to: string) => Promise<void>`, from `FileSystem`): Rename a file. The rename replaces `to` atomically when `to` exists.
- `size` (`(path: string) => Promise<number | undefined>`, from `FileSystem`): Size of a file in bytes. `undefined` when the file is missing.
- `syncDir` (`(path: string) => Promise<void>`, from `FileSystem`): Flush the directory's entries (a create, rename or remove) to the disk, where the platform can.
- `truncate` (`(path: string, size: number) => Promise<void>`, from `FileSystem`): Cut a file down to `size` bytes.
- `writeFile` (`(path: string, data: Uint8Array, options: WriteFileOptions) => Promise<boolean>`, from `FileSystem`): Replace the file at `path` with `data`. Resolves `false` only for an `exclusive` write over an existing file.

Source: [src/durable/storage/fs-memory.ts:31](https://github.com/Tahul/zidane/blob/main/src/durable/storage/fs-memory.ts#L31)

### `MemoryFileSystemOptions`

Interface.

Options of [`memoryFileSystem`](https://zidane.si/docs/reference/durable-testing.md#memoryFileSystem).

```ts
interface MemoryFileSystemOptions
```

**Properties**

- `fail?` (`(op: MemoryFsOp, path: string) => unknown`): Called before each call. Return an error to make the call throw it and
  change nothing. `undefined` lets the call run.
- `files?` (`Map<string, Uint8Array<ArrayBufferLike>>`): The files, by path. Pass another file system's map to share its disk. Default: a new, empty map.
- `owner?` (`LeaseOwner`): This process as lock files name it. Default: host `memory`, pid 1 and a token of this file system's own.
- `ownerDead?` (`(owner: LeaseOwner) => boolean`): Whether a lock's owner is gone. Default: never (a lock is always held).

Source: [src/durable/storage/fs-memory.ts:16](https://github.com/Tahul/zidane/blob/main/src/durable/storage/fs-memory.ts#L16)

### `ReplayCheck`

Interface.

A host and a storage wrapper that share one journal.

```ts
interface ReplayCheck
```

**Properties**

- `host` (`DurableHost`, readonly): The host to run the scenario on.
- `journal` (`JournalEntry[]`, readonly): Every host call and commit this check made live, in order. A replaying check adds only what it ran past the journal's end.
- `wrap` (`(storage: DurableStorage) => DurableStorage`): Wrap a storage. A recording check writes its commits to the journal. A replaying check compares them with the journal.

Source: [src/durable/testing/replay-check.ts:40](https://github.com/Tahul/zidane/blob/main/src/durable/testing/replay-check.ts#L40)

## Types

### `JournalEntry`

Type.

One journal entry.

```ts
type JournalEntry =
  | { kind: 'now'; value: number }
  | { kind: 'id'; value: string }
  | { error?: ReturnType<typeof errorRecord>; kind: 'effect'; name: string; value?: Json }
  | { batches: Batch[]; kind: 'commit' }
```

Source: [src/durable/testing/replay-check.ts:20](https://github.com/Tahul/zidane/blob/main/src/durable/testing/replay-check.ts#L20)

### `MemoryFsOp`

Type.

A call of a [`MemoryFileSystem`](https://zidane.si/docs/reference/durable-testing.md#MemoryFileSystem) that `MemoryFileSystemOptions.fail` can fail.

```ts
type MemoryFsOp =
  | 'mkdir'
  | 'list'
  | 'read'
  | 'size'
  | 'writeFile'
  | 'openAppend'
  | 'append'
  | 'sync'
  | 'close'
  | 'truncate'
  | 'rename'
  | 'remove'
  | 'syncDir'
```

Source: [src/durable/storage/fs-memory.ts:13](https://github.com/Tahul/zidane/blob/main/src/durable/storage/fs-memory.ts#L13)

### `ReplayScenario`

Type.

A scenario the check runs twice. It gets a host and a storage, and returns a JSON summary of its outcome.

```ts
type ReplayScenario = (env: { host: DurableHost; storage: DurableStorage }) => Promise<Json>
```

Source: [src/durable/testing/replay-check.ts:194](https://github.com/Tahul/zidane/blob/main/src/durable/testing/replay-check.ts#L194)
