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.
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().
function asObjectContext<C>(ctx: FakeAttemptContext): CType parameters
| Name | Description |
|---|---|
| C |
Parameters
| Name | Type | Description |
|---|---|---|
| ctx | FakeAttemptContext | The |
Returns
CfakeRestateObjectFunction#
A fake virtual object with the key key and an empty state.
function fakeRestateObject(
key?: string,
options?: { now?: () => number },
): FakeRestateObjectParameters
| Name | Type | Default | Description |
|---|---|---|---|
| key? | string | 'object-1' | The object key. Default |
| options? | { now?: () => number } | {} | The object's clock. |
Returns
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.
function fakeSharedContext(
object: FakeRestateObject,
): { get: <T>(name: string) => Promise<T | null>; key: string; stateKeys: () => Promise<string[]> }Parameters
| Name | Type | Description |
|---|---|---|
| object | FakeRestateObject | The object to read. |
Returns
{ get: <T>(name: string) => Promise<T | null>; key: string; stateKeys: () => Promise<string[]> }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.
function runAttempts<T>(
object: FakeRestateObject,
invocation: FakeInvocation,
handler: (ctx: FakeAttemptContext) => Promise<T>,
options?: RunAttemptsOptions,
): Promise<T>Type parameters
| Name | Description |
|---|---|
| T |
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
| object | FakeRestateObject | The object the invocation belongs to. | |
| invocation | FakeInvocation | The invocation to run ( | |
| handler | (ctx: FakeAttemptContext) => Promise<T> | The handler. It gets the | |
| options? | RunAttemptsOptions | {} | The attempt budget and the crash points. |
Returns
Promise<T>What the attempt that finished answered.
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.
class FakeCrash extends ErrorConstructor
FakeJournalMismatchErrorClass#
A re-run made another journal call than the journaled one.
class FakeJournalMismatchError extends ErrorConstructor
new FakeJournalMismatchError(index: number, expected: unknown, actual: unknown)Parameters
| Name | Type | Description |
|---|---|---|
| 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
Properties
| Name | Type | Description |
|---|---|---|
| indexreadonly | number | The position of the entry in the journal. |
Interfaces#
FakeAttemptContextInterface#
The ctx of one attempt.
interface FakeAttemptContext extends RestateObjectContextLikeProperties
| Name | Type | Description |
|---|---|---|
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 |
datefrom RestateObjectContextLike | { now: () => Promise<number> } | The journaled clock. |
| deadreadonly | boolean | Whether the attempt died. |
| diedreadonly | Promise<void> | Resolves when the attempt dies. |
getfrom RestateObjectContextLike | <T>(name: string) => Promise<T | null> | Read one state value. |
| isProcessing | () => boolean |
|
keyreadonlyfrom RestateObjectContextLike | string | 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 |
runfrom RestateObjectContextLike | <T>(name: string, fn: () => T | Promise<T>, options?: RestateCtxRunOptions) => Promise<T> | Run |
setfrom RestateObjectContextLike | <T>(name: string, value: T) => void | Write one state value. |
sleepfrom RestateObjectContextLike | (millis: number) => Promise<void> | A durable timer of |
stateKeysfrom RestateObjectContextLike | () => Promise<string[]> | Every state key of the object. |
FakeAttemptOptionsInterface#
Options of FakeRestateObject.attempt.
interface FakeAttemptOptionsProperties
| Name | Type | Description |
|---|---|---|
| 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 |
FakeInvocationInterface#
One invocation: its journal, which every attempt replays.
interface FakeInvocationProperties
| Name | Type | Description |
|---|---|---|
| attempts | number | Attempts made so far. |
| idreadonly | string | The invocation id. |
| idempotencyKey?readonly | string | The idempotency key the invocation was sent with, if any. |
| journalreadonly | FakeJournalEntry[] | The calls the invocation made, in order. |
FakeRestateObjectInterface#
The object: the state every invocation shares, and the answers of its awakeables. An awakeable is a promise another caller resolves by id.
interface FakeRestateObjectProperties
| Name | Type | Description |
|---|---|---|
| answersreadonly | Map<string, Json> | Answers of awakeables, by id. |
| attempt | (invocation: FakeInvocation, options?: FakeAttemptOptions) => FakeAttemptContext | The |
| invocation | (options?: { idempotencyKey?: string }) => FakeInvocation | A new invocation, sent with |
| keyreadonly | string | The object key. |
| mismatchesreadonly | FakeJournalMismatchError[] | Journal mismatches every attempt met. Each one kills its attempt. |
| resolve | (id: string, value: Json) => void | Resolve an awakeable that any attempt minted. |
| statereadonly | Map<string, Json> | The object's state, by state key. Invocations change it at once. |
FakeRunEntryInterface#
A ctx.run entry of a journal.
interface FakeRunEntryProperties
| Name | Type | Description |
|---|---|---|
| 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. |
RunAttemptsOptionsInterface#
Options of runAttempts.
interface RunAttemptsOptionsProperties
| Name | Type | Description |
|---|---|---|
| crashAfter? | readonly (number | undefined)[] | Crash points, one for each attempt of this call, in order. Attempt |
| maxAttempts? | number | Attempts before |
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.
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' }