Skip to content
trestle

How the code and tests are written

Pick another answer

Processes that read like your code

Durability should not dictate your style. You can write processes in plain async/await, Effect, RxJS, or a state-machine style familiar to XState users, and Trestle draws the diagram straight from your code.

async/await

The insurance claim runs as one async function with ordinary control flow.

export const claim = process({
  name: 'claim',
  body: async ({ policy, amount }: Claim) => {
    const value = await act({
      name: 'Appraise the claim',
      body: () => surveyor.appraise(policy),
    });

    const isOver = await choice({
      name: 'Over the appraisal?',
      condition: amount > value,
    });

    if (isOver) {
      const review = await wait({
        name: 'Adjuster approves',
        party: adjuster,
        window: '3 days',
      });

      const isApproved = await choice({
        name: 'Approved?',
        condition: review.isAnswered && review.answer === true,
      });

      if (!isApproved) {
        return 'refused';
      }
    }

    await act({
      name: 'Pay the claim',
      body: ({ actKey }) => bank.pay(amount, actKey),
    });

    return 'paid';
  },
});
export const claim = process({
  name: 'claim',
  body: async ({ policy, amount }: Claim) => {
    const value = await act({
      name: 'Appraise the claim',
      body: () => surveyor.appraise(policy),
    });

    const isOver = await choice({
      name: 'Over the appraisal?',
      condition: amount > value,
    });

    if (isOver) {
      const review = await wait({
        name: 'Adjuster approves',
        party: adjuster,
        window: '3 days',
      });

      const isApproved = await choice({
        name: 'Approved?',
        condition:
          review.isAnswered &&
          review.answer === true,
      });

      if (!isApproved) {
        return 'refused';
      }
    }

    await act({
      name: 'Pay the claim',
      body: ({ actKey }) =>
        bank.pay(amount, actKey),
    });

    return 'paid';
  },
});
export const claim = process({
  name: 'claim',
  body: async ({
    policy,
    amount,
  }: Claim) => {
    const value = await act({
      name: 'Appraise the claim',
      body: () =>
        surveyor.appraise(policy),
    });

    const isOver = await choice({
      name: 'Over the appraisal?',
      condition: amount > value,
    });

    if (isOver) {
      const review = await wait({
        name: 'Adjuster approves',
        party: adjuster,
        window: '3 days',
      });

      const isApproved =
        await choice({
          name: 'Approved?',
          condition:
            review.isAnswered &&
            review.answer === true,
        });

      if (!isApproved) {
        return 'refused';
      }
    }

    await act({
      name: 'Pay the claim',
      body: ({ actKey }) =>
        bank.pay(amount, actKey),
    });

    return 'paid';
  },
});

Effect

The same insurance claim runs as a pipeline of Effects, passing each step's result to the next, and draws an identical diagram.

const approved = pipe(
  wait({
    name: 'Adjuster approves',
    party: adjuster,
    window: '3 days',
  }),
  Effect.flatMap((review) =>
    choice({
      name: 'Approved?',
      condition: review.isAnswered && review.answer === true,
    }),
  ),
);

// The claim, written with Effect: each statement is an effect, piped
// into the next, and the graph, the record and the replay are those of
// the same claim written with async and await.
export const claim = process({
  name: 'claim',
  body: ({ policy, amount }: Claim) =>
    pipe(
      act({
        name: 'Appraise the claim',
        body: () => appraise(policy),
      }),
      Effect.flatMap((value) =>
        choice({
          name: 'Over the appraisal?',
          condition: amount > value,
        }),
      ),
      Effect.flatMap((isOver) =>
        isOver ? approved : Effect.succeed(true),
      ),
      Effect.flatMap((isApproved) =>
        isApproved
          ? pipe(
              act({
                name: 'Pay the claim',
                body: ({ actKey }) => pay(amount, actKey),
              }),
              Effect.as('paid' as const),
            )
          : Effect.succeed('refused' as const),
      ),
    ),
});
const approved = pipe(
  wait({
    name: 'Adjuster approves',
    party: adjuster,
    window: '3 days',
  }),
  Effect.flatMap((review) =>
    choice({
      name: 'Approved?',
      condition:
        review.isAnswered &&
        review.answer === true,
    }),
  ),
);

// The claim, written with Effect: each statement
// is an effect, piped into the next, and the
// graph, the record and the replay are those of
// the same claim written with async and await.
export const claim = process({
  name: 'claim',
  body: ({ policy, amount }: Claim) =>
    pipe(
      act({
        name: 'Appraise the claim',
        body: () => appraise(policy),
      }),
      Effect.flatMap((value) =>
        choice({
          name: 'Over the appraisal?',
          condition: amount > value,
        }),
      ),
      Effect.flatMap((isOver) =>
        isOver ? approved : Effect.succeed(true),
      ),
      Effect.flatMap((isApproved) =>
        isApproved
          ? pipe(
              act({
                name: 'Pay the claim',
                body: ({ actKey }) =>
                  pay(amount, actKey),
              }),
              Effect.as('paid' as const),
            )
          : Effect.succeed('refused' as const),
      ),
    ),
});
const approved = pipe(
  wait({
    name: 'Adjuster approves',
    party: adjuster,
    window: '3 days',
  }),
  Effect.flatMap((review) =>
    choice({
      name: 'Approved?',
      condition:
        review.isAnswered &&
        review.answer === true,
    }),
  ),
);

// The claim, written with Effect:
// each statement is an effect,
// piped into the next, and the
// graph, the record and the replay
// are those of the same claim
// written with async and await.
export const claim = process({
  name: 'claim',
  body: ({
    policy,
    amount,
  }: Claim) =>
    pipe(
      act({
        name: 'Appraise the claim',
        body: () =>
          appraise(policy),
      }),
      Effect.flatMap((value) =>
        choice({
          name: 'Over the appraisal?',
          condition: amount > value,
        }),
      ),
      Effect.flatMap((isOver) =>
        isOver
          ? approved
          : Effect.succeed(true),
      ),
      Effect.flatMap(
        (isApproved) =>
          isApproved
            ? pipe(
                act({
                  name: 'Pay the claim',
                  body: ({
                    actKey,
                  }) =>
                    pay(
                      amount,
                      actKey,
                    ),
                }),
                Effect.as(
                  'paid' as const,
                ),
              )
            : Effect.succeed(
                'refused' as const,
              ),
      ),
    ),
});

RxJS

Unlike the branching claim, this refund sends an order through operators until the last value ends the run.

export const refund = process({
  name: 'refund',
  body: pipe(
    act({
      name: 'Price the return',
      input: (returned: Return) => returned,
      body: ({ input }) => input.quantity * input.unitPrice,
    }),
    wait({
      name: 'Finance approves',
      party: finance,
      window: '1 day',
      answerSchema: approvedAmount,
      timedOut: map(() => 0),
    }),
    choice({
      name: 'Anything to refund?',
      condition: (amount) => amount > 0,
      yes: pipe(
        act({
          name: 'Pay the refund',
          input: (amount: number) => ({ amount }),
          body: ({ input, actKey }) =>
            bank.refund(input.amount, actKey),
        }),
        map(() => 'refunded' as const),
      ),
      no: map(() => 'declined' as const),
    }),
  ),
});
export const refund = process({
  name: 'refund',
  body: pipe(
    act({
      name: 'Price the return',
      input: (returned: Return) => returned,
      body: ({ input }) =>
        input.quantity * input.unitPrice,
    }),
    wait({
      name: 'Finance approves',
      party: finance,
      window: '1 day',
      answerSchema: approvedAmount,
      timedOut: map(() => 0),
    }),
    choice({
      name: 'Anything to refund?',
      condition: (amount) => amount > 0,
      yes: pipe(
        act({
          name: 'Pay the refund',
          input: (amount: number) => ({ amount }),
          body: ({ input, actKey }) =>
            bank.refund(input.amount, actKey),
        }),
        map(() => 'refunded' as const),
      ),
      no: map(() => 'declined' as const),
    }),
  ),
});
export const refund = process({
  name: 'refund',
  body: pipe(
    act({
      name: 'Price the return',
      input: (returned: Return) =>
        returned,
      body: ({ input }) =>
        input.quantity *
        input.unitPrice,
    }),
    wait({
      name: 'Finance approves',
      party: finance,
      window: '1 day',
      answerSchema: approvedAmount,
      timedOut: map(() => 0),
    }),
    choice({
      name: 'Anything to refund?',
      condition: (amount) =>
        amount > 0,
      yes: pipe(
        act({
          name: 'Pay the refund',
          input: (
            amount: number,
          ) => ({ amount }),
          body: ({
            input,
            actKey,
          }) =>
            bank.refund(
              input.amount,
              actKey,
            ),
        }),
        map(
          () => 'refunded' as const,
        ),
      ),
      no: map(
        () => 'declined' as const,
      ),
    }),
  ),
});

State machine

A support ticket moves between open and answered states as typed messages arrive.

const STATES = {
  open: { window: '1 day', reply: 'answered', timeout: 'open' },
  answered: { window: '7 days', reply: 'open', timeout: 'resolved' },
} as const;

export const ticket = process({
  name: 'ticket',
  body: async (): Promise<Resolved> => {
    let state: Next = 'open';
    let lastReply: string | undefined;

    while (state !== 'resolved') {
      const current: State = state;
      const { window, reply, timeout } = STATES[current];

      state = await box({
        name: current,
        body: async (): Promise<Next> => {
          await act({
            name: 'enter',
            input: { state: current },
            body: ({ input, actKey }) =>
              desk.enter(input.state, actKey),
          });

          const message = await wait({
            name: 'message',
            party: helpDesk,
            answerSchema: ticketMessage,
            window,
          });

          if (message.isAnswered && message.answer.kind === 'reply') {
            lastReply = message.answer.text;
          }

          let next: Next = timeout;

          if (message.isAnswered) {
            next = await choice({
              name: 'kind',
              value: message.answer,
              selector: 'kind',
              cases: {
                reply: (): Next => reply,
                resolve: (): Next => 'resolved',
              },
            });
          }
          await act({
            name: 'leave',
            input: { state: current },
            body: ({ input, actKey }) =>
              desk.leave(input.state, actKey),
          });

          return next;
        },
      });
    }

    return { end: 'resolved', value: lastReply };
  },
});
const STATES = {
  open: {
    window: '1 day',
    reply: 'answered',
    timeout: 'open',
  },
  answered: {
    window: '7 days',
    reply: 'open',
    timeout: 'resolved',
  },
} as const;

export const ticket = process({
  name: 'ticket',
  body: async (): Promise<Resolved> => {
    let state: Next = 'open';
    let lastReply: string | undefined;

    while (state !== 'resolved') {
      const current: State = state;
      const { window, reply, timeout } =
        STATES[current];

      state = await box({
        name: current,
        body: async (): Promise<Next> => {
          await act({
            name: 'enter',
            input: { state: current },
            body: ({ input, actKey }) =>
              desk.enter(input.state, actKey),
          });

          const message = await wait({
            name: 'message',
            party: helpDesk,
            answerSchema: ticketMessage,
            window,
          });

          if (
            message.isAnswered &&
            message.answer.kind === 'reply'
          ) {
            lastReply = message.answer.text;
          }

          let next: Next = timeout;

          if (message.isAnswered) {
            next = await choice({
              name: 'kind',
              value: message.answer,
              selector: 'kind',
              cases: {
                reply: (): Next => reply,
                resolve: (): Next => 'resolved',
              },
            });
          }
          await act({
            name: 'leave',
            input: { state: current },
            body: ({ input, actKey }) =>
              desk.leave(input.state, actKey),
          });

          return next;
        },
      });
    }

    return { end: 'resolved', value: lastReply };
  },
});
const STATES = {
  open: {
    window: '1 day',
    reply: 'answered',
    timeout: 'open',
  },
  answered: {
    window: '7 days',
    reply: 'open',
    timeout: 'resolved',
  },
} as const;

export const ticket = process({
  name: 'ticket',
  body: async (): Promise<Resolved> => {
    let state: Next = 'open';
    let lastReply:
      | string
      | undefined;

    while (state !== 'resolved') {
      const current: State = state;
      const {
        window,
        reply,
        timeout,
      } = STATES[current];

      state = await box({
        name: current,
        body: async (): Promise<Next> => {
          await act({
            name: 'enter',
            input: {
              state: current,
            },
            body: ({
              input,
              actKey,
            }) =>
              desk.enter(
                input.state,
                actKey,
              ),
          });

          const message =
            await wait({
              name: 'message',
              party: helpDesk,
              answerSchema:
                ticketMessage,
              window,
            });

          if (
            message.isAnswered &&
            message.answer.kind ===
              'reply'
          ) {
            lastReply =
              message.answer.text;
          }

          let next: Next = timeout;

          if (message.isAnswered) {
            next = await choice({
              name: 'kind',
              value: message.answer,
              selector: 'kind',
              cases: {
                reply: (): Next =>
                  reply,
                resolve: (): Next =>
                  'resolved',
              },
            });
          }
          await act({
            name: 'leave',
            input: {
              state: current,
            },
            body: ({
              input,
              actKey,
            }) =>
              desk.leave(
                input.state,
                actKey,
              ),
          });

          return next;
        },
      });
    }

    return {
      end: 'resolved',
      value: lastReply,
    };
  },
});
Each tab runs tested code on one engine and draws its diagram from the source.
  1. Three steps inside normal functions

    Your helpers, if, loops, and try/catch work normally inside a process. Three steps handle durability: act calls outside systems, wait pauses for people, messages, or time, and choice puts a decision on the diagram.

  2. Types across your stack

    Inputs, answers, results, and outcomes use any Standard Schema library like Zod or Valibot, and a generated client contract catches mismatches at compile time. Definitions are TypeScript, while apps in any language start runs and answer approvals over HTTP via a generated OpenAPI spec.

  3. Tests that skip the clock

    Tests stub outside systems and advance the clock, so checking an unpaid invoice after fourteen days takes one line.

    Leaked side effects fail the test, and Trestle can generate path tests from the diagram. You can also replay production runs or simulate crashes.

    it('is unpaid when the customer has not paid a fortnight later', async () => {
      const run = await start(sendAnInvoice, { input: invoice });
    
      await run.advance('14 days');
    
      await expect(run).toHaveEnded('unpaid');
    });
    it('is unpaid when the customer has not paid a fortnight later', async () => {
      const run = await start(sendAnInvoice, {
        input: invoice,
      });
    
      await run.advance('14 days');
    
      await expect(run).toHaveEnded('unpaid');
    });
    it('is unpaid when the customer has not paid a fortnight later', async () => {
      const run = await start(
        sendAnInvoice,
        { input: invoice },
      );
    
      await run.advance('14 days');
    
      await expect(run).toHaveEnded(
        'unpaid',
      );
    });
  4. When a process grows

    Larger processes can parallelise or race branches while the losing branch undoes its work, call other processes, and cap loop concurrency. Polling, deadlines, messages, signed webhooks, queues, and schedules share the same model.

Constraints to know up front

Your visit is running on Trestle.

This is the real Trestle engine running a live process in your browser tab, not a simulation. Each of the eight topic pages you open answers its question once, showing the path you have taken and the pages you have not opened yet—until you copy npm create @trestlerun to finish it.