# zidane/restate/testing

> A fake Restate virtual object, to test Restate handlers from every crash point without a Restate server.

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

Use this entry point in the tests of a Restate service built on [`zidane/restate`](https://zidane.si/docs/reference/restate.md). A virtual object is a Restate service with one key/value state per key. `fakeRestateObject(key)` is a fake one. It keeps its state across invocations and one journal per invocation. An attempt that runs an invocation again replays that journal, as Restate does after a crash, and fails at the first journal mismatch.

`runAttempts(object, invocation, handler)` runs the handler as Restate runs an invocation: one attempt, then another each time an attempt dies. `crashAfter[i]` kills attempt `i` when it makes its journal call at that position (zero based). A test that crashes at each position proves that the handler answers the same from every crash point. `fakeSharedContext(object)` is a read-only `ctx` for `restateReader`. Throw `FakeCrash` from a `ctx.run` body to kill an attempt. `FakeJournalMismatchError` is the error of a re-run that made another call than the journal holds. The `ctx` of an attempt answers `isProcessing()` as the SDK does, so `durable.replaying()` works on it. See [RESTATE.md](https://github.com/Tahul/zidane/blob/main/docs/RESTATE.md#testing).

```ts
import type { Provider } from 'zidane'
import type { FakeAttemptContext } from 'zidane/restate/testing'
import { expect, it } from 'bun:test'
import { createAgent } from 'zidane'
import { restateDurable } from 'zidane/restate'
import { fakeRestateObject, runAttempts } from 'zidane/restate/testing'

/** The handler under test. In a test, `provider` is a scripted provider of yours. */
function handler(provider: Provider) {
  return async (ctx: FakeAttemptContext) => {
    const durable = await restateDurable(ctx)
    try {
      const agent = createAgent({ provider, durable: durable.runtime, session: await durable.session() })
      return (await durable.run(agent, { prompt: 'Summarize the README.', requestId: 'req-1' })).status
    }
    finally {
      await durable.close()
    }
  }
}

export function crashTest(provider: Provider) {
  it('answers the same from every crash point', async () => {
    const base = fakeRestateObject('job-1')
    const expected = await runAttempts(base, base.invocation(), handler(provider))
    for (let at = 1; ; at++) {
      const object = fakeRestateObject('job-1')
      const invocation = object.invocation()
      expect(await runAttempts(object, invocation, handler(provider), { crashAfter: [at] })).toBe(expected)
      expect(object.mismatches).toEqual([])
      // One attempt: the run made fewer journal calls than `at`, so no crash point is left.
      if (invocation.attempts === 1)
        break
    }
  })
}
```

## Functions

### `asObjectContext`

Function.

The fake `ctx` as the SDK's context type, for a handler typed with it
(`asObjectContext<restate.ObjectContext>(ctx)`). The fake implements what
zidane and a handler built on it call: the state, `run`, the clock, ids,
timers, awakeables and `request()`.

```ts
function asObjectContext<C>(ctx: FakeAttemptContext): C
```

**Type parameters**

- `C`

**Parameters**

- `ctx` (`FakeAttemptContext`): The `ctx` of a fake attempt.

**Returns** `C`

Source: [src/durable/testing/restate.ts:74](https://github.com/Tahul/zidane/blob/main/src/durable/testing/restate.ts#L74)

### `fakeRestateObject`

Function.

A fake virtual object with the key `key` and an empty state.

```ts
function fakeRestateObject(
  key?: string,
  options?: { now?: () => number },
): FakeRestateObject
```

**Parameters**

- `key?` (`string`, default `'object-1'`): The object key. Default `object-1`.
- `options?` (`{ now?: () => number }`, default `{}`): The object's clock.

**Returns** `FakeRestateObject`

Source: [src/durable/testing/restate.ts:189](https://github.com/Tahul/zidane/blob/main/src/durable/testing/restate.ts#L189)

### `fakeSharedContext`

Function.

A read-only `ctx` over the object's state, as a shared handler sees it
(`restateReader(ctx)`). It reads the state as it is now.

```ts
function fakeSharedContext(
  object: FakeRestateObject,
): { get: <T>(name: string) => Promise<T | null>; key: string; stateKeys: () => Promise<string[]> }
```

**Parameters**

- `object` (`FakeRestateObject`): The object to read.

**Returns** `{ get: <T>(name: string) => Promise<T | null>; key: string; stateKeys: () => Promise<string[]> }`

Source: [src/durable/testing/restate.ts:437](https://github.com/Tahul/zidane/blob/main/src/durable/testing/restate.ts#L437)

### `runAttempts`

Function.

Run `handler` as Restate runs an invocation: one attempt, and another
(replaying the journal) each time an attempt dies, up to `maxAttempts`.
A second call on an invocation that finished re-runs it against its
whole journal. It throws the first journal mismatch the object met.

```ts
function runAttempts<T>(
  object: FakeRestateObject,
  invocation: FakeInvocation,
  handler: (ctx: FakeAttemptContext) => Promise<T>,
  options?: RunAttemptsOptions,
): Promise<T>
```

**Type parameters**

- `T`

**Parameters**

- `object` (`FakeRestateObject`): The object the invocation belongs to.
- `invocation` (`FakeInvocation`): The invocation to run (`object.invocation()`).
- `handler` (`(ctx: FakeAttemptContext) => Promise<T>`): The handler. It gets the `ctx` of each attempt.
- `options?` (`RunAttemptsOptions`, default `{}`): The attempt budget and the crash points.

**Returns** `Promise<T>`: What the attempt that finished answered.

Source: [src/durable/testing/restate.ts:412](https://github.com/Tahul/zidane/blob/main/src/durable/testing/restate.ts#L412)

## Classes

### `FakeCrash`

Class.

Throw it from a `ctx.run` body to kill the attempt, as a process death
does. Made inside a body, it kills the attempt at once: code between the
throw and the `ctx.run` (a kernel effect's body, which the host catches
and would journal as the effect's failure) cannot turn it into a result.

```ts
class FakeCrash extends Error
```

**Constructor**

```ts
new FakeCrash()
```

A process death.

**Returns** `FakeCrash`

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

### `FakeJournalMismatchError`

Class.

A re-run made another journal call than the journaled one.

```ts
class FakeJournalMismatchError extends Error
```

**Constructor**

```ts
new FakeJournalMismatchError(index: number, expected: unknown, actual: unknown)
```

**Parameters**

- `index` (`number`): The position of the entry in the journal.
- `expected` (`unknown`): The journaled entry.
- `actual` (`unknown`): The call that the re-run made.

**Returns** `FakeJournalMismatchError`

**Properties**

- `index` (`number`, readonly): The position of the entry in the journal.

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

## Interfaces

### `FakeAttemptContext`

Interface.

The `ctx` of one attempt.

```ts
interface FakeAttemptContext extends RestateObjectContextLike
```

**Properties**

- `awakeable` (`<T>() => { id: string; promise: Promise<T> }`, from `RestateObjectContextLike`): A new awakeable, a promise that another caller resolves by id. It answers that id and the promise.
- `clear` (`(name: string) => void`, from `RestateObjectContextLike`): Remove one state value.
- `crash` (`() => never`): Kill the attempt, as a process death does. Throws [`FakeCrash`](https://zidane.si/docs/reference/restate-testing.md#FakeCrash).
- `date` (`{ now: () => Promise<number> }`, from `RestateObjectContextLike`): The journaled clock.
- `dead` (`boolean`, readonly): Whether the attempt died.
- `died` (`Promise<void>`, readonly): Resolves when the attempt dies.
- `get` (`<T>(name: string) => Promise<T | null>`, from `RestateObjectContextLike`): Read one state value. `null` when it is not set.
- `isProcessing` (`() => boolean`): `false` while the attempt re-runs journaled entries, `true` once it runs past them.
- `key` (`string`, readonly, from `RestateObjectContextLike`): The object's key.
- `kill` (`() => void`): Kill the attempt from outside (the process died while it waited).
- `rand` (`{ uuidv4: () => string }`, from `RestateObjectContextLike`): Journaled random ids.
- `request` (`() => { headers: Map<string, string>; id: string; idempotencyKey?: string }`): The request: it holds an idempotency key when the invocation carries one.
- `resolveAwakeable?` (`<T>(id: string, payload?: T) => void`, from `RestateObjectContextLike`): Resolve the awakeable `id` with `payload`.
- `run` (`<T>(name: string, fn: () => T | Promise<T>, options?: RestateCtxRunOptions) => Promise<T>`, from `RestateObjectContextLike`): Run `fn` once and journal its result (`ctx.run`).
- `set` (`<T>(name: string, value: T) => void`, from `RestateObjectContextLike`): Write one state value.
- `sleep` (`(millis: number) => Promise<void>`, from `RestateObjectContextLike`): A durable timer of `millis` ms.
- `stateKeys` (`() => Promise<string[]>`, from `RestateObjectContextLike`): Every state key of the object.

Source: [src/durable/testing/restate.ts:146](https://github.com/Tahul/zidane/blob/main/src/durable/testing/restate.ts#L146)

### `FakeAttemptOptions`

Interface.

Options of `FakeRestateObject.attempt`.

```ts
interface FakeAttemptOptions
```

**Properties**

- `crashAfter?` (`number`): Kill the attempt when it makes its journal call at this position (zero
  based): the attempt keeps at most this many entries, replayed ones
  included. Absent: the attempt dies only through `crash` or `kill`.

Source: [src/durable/testing/restate.ts:136](https://github.com/Tahul/zidane/blob/main/src/durable/testing/restate.ts#L136)

### `FakeInvocation`

Interface.

One invocation: its journal, which every attempt replays.

```ts
interface FakeInvocation
```

**Properties**

- `attempts` (`number`): Attempts made so far.
- `id` (`string`, readonly): The invocation id.
- `idempotencyKey?` (`string`, readonly): The idempotency key the invocation was sent with, if any. `ctx.request()` hands it to the handler.
- `journal` (`FakeJournalEntry[]`, readonly): The calls the invocation made, in order.

Source: [src/durable/testing/restate.ts:124](https://github.com/Tahul/zidane/blob/main/src/durable/testing/restate.ts#L124)

### `FakeRestateObject`

Interface.

The object: the state every invocation shares, and the answers of its awakeables. An awakeable is a promise another caller resolves by id.

```ts
interface FakeRestateObject
```

**Properties**

- `answers` (`Map<string, Json>`, readonly): Answers of awakeables, by id.
- `attempt` (`(invocation: FakeInvocation, options?: FakeAttemptOptions) => FakeAttemptContext`): The `ctx` of the next attempt of `invocation`.
- `invocation` (`(options?: { idempotencyKey?: string }) => FakeInvocation`): A new invocation, sent with `idempotencyKey` when you give one.
- `key` (`string`, readonly): The object key.
- `mismatches` (`FakeJournalMismatchError[]`, readonly): Journal mismatches every attempt met. Each one kills its attempt.
- `resolve` (`(id: string, value: Json) => void`): Resolve an awakeable that any attempt minted.
- `state` (`Map<string, Json>`, readonly): The object's state, by state key. Invocations change it at once.

Source: [src/durable/testing/restate.ts:162](https://github.com/Tahul/zidane/blob/main/src/durable/testing/restate.ts#L162)

### `FakeRunEntry`

Interface.

A `ctx.run` entry of a journal.

```ts
interface FakeRunEntry
```

**Properties**

- `at?` (`number`): The length of the journal when it completed.
- `done` (`boolean`): Whether the run finished. A run that an attempt left unfinished runs again on the next attempt.
- `kind` (`'run'`): The kind of call.
- `name` (`string`): The name the call gave.
- `order?` (`number`): Its rank among the completions of the invocation.
- `value?` (`Json`): The value the run journaled.

Source: [src/durable/testing/restate.ts:92](https://github.com/Tahul/zidane/blob/main/src/durable/testing/restate.ts#L92)

### `RunAttemptsOptions`

Interface.

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

```ts
interface RunAttemptsOptions
```

**Properties**

- `crashAfter?` (`readonly (number | undefined)[]`): Crash points, one for each attempt of this call, in order. Attempt `i`
  dies when it makes its journal call at position `crashAfter[i]` (see
  `FakeAttemptOptions.crashAfter`). An attempt with an `undefined`
  item, or past the end of the list, dies only through `ctx.crash()`.
- `maxAttempts?` (`number`): Attempts before `runAttempts` gives up and throws. Default 20.

Source: [src/durable/testing/restate.ts:389](https://github.com/Tahul/zidane/blob/main/src/durable/testing/restate.ts#L389)

## Types

### `FakeJournalEntry`

Type.

One entry of a journal: a `ctx.run`, a state read (`get`, `keys`), a
state write (`set`, `clear`), a durable timer (`sleep`) or a new
awakeable.

```ts
type FakeJournalEntry =
  | FakeRunEntry
  | { kind: 'get'; name: string; value: Json | null }
  | { kind: 'keys'; value: string[] }
  | { kind: 'set'; name: string; value: Json }
  | { kind: 'clear'; name: string }
  | { kind: 'sleep'; ms: number }
  | { id: string; kind: 'awakeable' }
```

Source: [src/durable/testing/restate.ts:112](https://github.com/Tahul/zidane/blob/main/src/durable/testing/restate.ts#L112)
