Skip to content

zidane/restate/testing

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

import { … } from 'zidane/restate/testing'src/durable/testing/restate.ts

Use this entry point in the tests of a Restate service built on zidane/restate. 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.

TypeScript
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#

asObjectContextFunction#

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().

TypeScript
function asObjectContext<C>(ctx: FakeAttemptContext): C
Type parameters
NameDescription
C
Parameters
NameTypeDescription
ctxFakeAttemptContext

The ctx of a fake attempt.

C

src/durable/testing/restate.ts:74

fakeRestateObjectFunction#

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

TypeScript
function fakeRestateObject(
  key?: string,
  options?: { now?: () => number },
): FakeRestateObject
Parameters
NameTypeDefaultDescription
key?string'object-1'

The object key. Default object-1.

options?{ now?: () => number }{}

The object's clock.

src/durable/testing/restate.ts:189

fakeSharedContextFunction#

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.

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

The object to read.

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

src/durable/testing/restate.ts:437

runAttemptsFunction#

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.

TypeScript
function runAttempts<T>(
  object: FakeRestateObject,
  invocation: FakeInvocation,
  handler: (ctx: FakeAttemptContext) => Promise<T>,
  options?: RunAttemptsOptions,
): Promise<T>
Type parameters
NameDescription
T
Parameters
NameTypeDefaultDescription
objectFakeRestateObject

The object the invocation belongs to.

invocationFakeInvocation

The invocation to run (object.invocation()).

handler(ctx: FakeAttemptContext) => Promise<T>

The handler. It gets the ctx of each attempt.

options?RunAttemptsOptions{}

The attempt budget and the crash points.

Promise<T>

What the attempt that finished answered.

src/durable/testing/restate.ts:412

Classes#

FakeCrashClass#

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.

TypeScript
class FakeCrash extends Error
TypeScript
new FakeCrash()

A process death.

src/durable/testing/restate.ts:58

FakeJournalMismatchErrorClass#

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

TypeScript
class FakeJournalMismatchError extends Error
TypeScript
new FakeJournalMismatchError(index: number, expected: unknown, actual: unknown)
Parameters
NameTypeDescription
indexnumber

The position of the entry in the journal.

expectedunknown

The journaled entry.

actualunknown

The call that the re-run made.

FakeJournalMismatchError properties
NameTypeDescription
indexreadonlynumber

The position of the entry in the journal.

src/durable/testing/restate.ts:79

Interfaces#

FakeAttemptContextInterface#

The ctx of one attempt.

TypeScript
interface FakeAttemptContext extends RestateObjectContextLike
FakeAttemptContext properties
NameTypeDescription
awakeablefrom RestateObjectContextLike<T>() => { id: string; promise: Promise<T> }

A new awakeable, a promise that another caller resolves by id. It answers that id and the promise.

clearfrom RestateObjectContextLike(name: string) => void

Remove one state value.

crash() => never

Kill the attempt, as a process death does. Throws FakeCrash.

datefrom RestateObjectContextLike{ now: () => Promise<number> }

The journaled clock.

deadreadonlyboolean

Whether the attempt died.

diedreadonlyPromise<void>

Resolves when the attempt dies.

getfrom RestateObjectContextLike<T>(name: string) => Promise<T | null>

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.

keyreadonlyfrom RestateObjectContextLikestring

The object's key.

kill() => void

Kill the attempt from outside (the process died while it waited).

randfrom RestateObjectContextLike{ uuidv4: () => string }

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?from RestateObjectContextLike<T>(id: string, payload?: T) => void

Resolve the awakeable id with payload.

runfrom RestateObjectContextLike<T>(name: string, fn: () => T | Promise<T>, options?: RestateCtxRunOptions) => Promise<T>

Run fn once and journal its result (ctx.run).

setfrom RestateObjectContextLike<T>(name: string, value: T) => void

Write one state value.

sleepfrom RestateObjectContextLike(millis: number) => Promise<void>

A durable timer of millis ms.

stateKeysfrom RestateObjectContextLike() => Promise<string[]>

Every state key of the object.

src/durable/testing/restate.ts:146

FakeAttemptOptionsInterface#

Options of FakeRestateObject.attempt.

TypeScript
interface FakeAttemptOptions
FakeAttemptOptions properties
NameTypeDescription
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.

src/durable/testing/restate.ts:136

FakeInvocationInterface#

One invocation: its journal, which every attempt replays.

TypeScript
interface FakeInvocation
FakeInvocation properties
NameTypeDescription
attemptsnumber

Attempts made so far.

idreadonlystring

The invocation id.

idempotencyKey?readonlystring

The idempotency key the invocation was sent with, if any. ctx.request() hands it to the handler.

journalreadonlyFakeJournalEntry[]

The calls the invocation made, in order.

src/durable/testing/restate.ts:124

FakeRestateObjectInterface#

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

TypeScript
interface FakeRestateObject
FakeRestateObject properties
NameTypeDescription
answersreadonlyMap<string, Json>

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.

keyreadonlystring

The object key.

mismatchesreadonlyFakeJournalMismatchError[]

Journal mismatches every attempt met. Each one kills its attempt.

resolve(id: string, value: Json) => void

Resolve an awakeable that any attempt minted.

statereadonlyMap<string, Json>

The object's state, by state key. Invocations change it at once.

src/durable/testing/restate.ts:162

FakeRunEntryInterface#

A ctx.run entry of a journal.

TypeScript
interface FakeRunEntry
FakeRunEntry properties
NameTypeDescription
at?number

The length of the journal when it completed.

doneboolean

Whether the run finished. A run that an attempt left unfinished runs again on the next attempt.

kind'run'

The kind of call.

namestring

The name the call gave.

order?number

Its rank among the completions of the invocation.

value?Json

The value the run journaled.

src/durable/testing/restate.ts:92

RunAttemptsOptionsInterface#

Options of runAttempts.

TypeScript
interface RunAttemptsOptions
RunAttemptsOptions properties
NameTypeDescription
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.

src/durable/testing/restate.ts:389

Types#

FakeJournalEntryType#

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.

TypeScript
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' }

src/durable/testing/restate.ts:112