Skip to content

Use cases

How to write a use case with Sypnorm, what each part means, and how failures work.

Applies to EngineCloud
View as Markdown
On this page
  1. A whole use case
  2. The parts
  3. ctx
  4. Every run ends in ctx.outcome
  5. A case that starts on an event
  6. Seen in production

A whole use case

The example is La Espiga, a bakery that sells today’s batch for pick-up. The case place-order is already on its map, with its start, its outcome and its failures:

cases/orders/place-order.case.yaml
id: place-order
title: Order for today
actor: customer
goal: Get fresh bread reserved for pick-up today
starts: in_app
where: shop.order-for-today
input:
  items: [{ product_id: uuid, qty: int }]
  pickup_at: datetime
outcomes:
  OrderPlaced: { order_id: uuid, pickup_code: string }
failures:
  BakeryClosed: «We are closed at that time. Pick another one.»
  OutOfStock:
    tell: «This one just ran out. The rest of your order is kept.»
    payload: { name: string, left: int }
data:
  reads: [product, opening_hours]
  writes: [order, order_item, product]
allowed: [customer]

npx @sypnia/cases generate writes the skeleton and the types from that file. You write the rules inside run:

src/cases/orders/place-order.ts
import { useCase } from '@sypnia/cases/sypnorm';
import { db } from '../../db';                    // written by `npx @sypnia/cases tables`

export const placeOrder = useCase('place-order', {
  summary: "A customer orders today's bread for pick-up",
  actor: 'customer',
  touches: { reads: [db.products, db.opening_hours], writes: [db.orders, db.order_items, db.products] },
  preconditions: [({ actor }) => actor.signedIn],

  async run(ctx) {
    const { input } = ctx;
    if (!(await ctx.db.opening_hours.isOpenAt(input.pickup_at))) return ctx.outcome('BakeryClosed');
    const products = await ctx.db.products.where({ id: { in: input.items.map(i => i.product_id) } }).forUpdate().all();
    for (const item of input.items) {
      const p = products.find(x => x.id === item.product_id)!;
      if (p.left_today < item.qty) return ctx.outcome('OutOfStock', { name: p.name, left: p.left_today });
    }
    const order = await ctx.db.orders.insert({ customer_id: ctx.actor.userId, pickup_at: input.pickup_at }).returning();
    await ctx.db.order_items.insertMany(input.items.map(i => ({ order_id: order.id, product_id: i.product_id, qty: i.qty })));
    for (const item of input.items) await ctx.db.products.update({ id: item.product_id }).decrement('left_today', item.qty);
    return ctx.outcome('OrderPlaced', { order_id: order.id, pickup_code: order.pickup_code });
  },
});

The parts

PartSaysChecked
idthe case’s id on the map, written as it is there (place-order); this is how the code and its case file find each othera case on the map, once in the app
summaryone sentence a client would understandcompared with the case’s title
actorwho does it: a role of your app (customer, baker, admin, a machine)by preconditions and your database’s policies
inputwhat it receives. Generated from the case’s input; you may pass a zod schema insteadbefore run; invalid input never reaches your code
touchesthe tables it reads and writesat runtime: touching another table is an error
preconditionswhat must be true beforebefore run
run(ctx)the stepsin one transaction (Runners)

touches and the outcomes are exactly what the map’s data, outcomes and failures say for this case. When they differ, the check reports drift.

ctx

What it is
ctx.inputthe input, already checked and typed
ctx.actorwho is running it: userId, role, signedIn
ctx.dbthe transaction: typed tables, limited to touches (Tables and queries)
ctx.outcome(name, payload)ends the run with one of the case’s outcomes or failures. Only declared names and payloads type-check
ctx.eventfor a case that starts on an event: the event’s envelope; ctx.event.data is its payload. With on_all, ctx.event.data holds every payload, keyed both by outcome name (PaymentTaken) and by full event name, ctx.event.events lists every envelope, and ctx.event.key is the correlation key
ctx.run_id, ctx.tracethe run’s id and its trace, for logs and calls to other services

Every run ends in ctx.outcome

run must return ctx.outcome(…). A run that returns anything else does not type-check, so a case can never end in silence. Failures are ended the same way, because failures are outcomes too.

The caller gets the outcome, typed:

TypeScript
{ ok: true,  outcome: 'OrderPlaced', data: { order_id, pickup_code } }
{ ok: false, outcome: 'OutOfStock',  tell: 'This one just ran out. The rest of your order is kept.', data: { name, left } }

The words a person reads (tell) come from the map, so the words people approved are the words people see.

When some case listens to the outcome, the area’s service writes it to the outbox in the same transaction as the run’s rows (Delivery). You never publish an event by hand. Such a case runs in its area’s service, called at POST /_cases/<case-id>, never from the browser (Runners).

A declared failure undoes the run’s own writes: the body runs under a savepoint, and ending in a failure rolls it back, on every runner (the Data API runner sends no writes for it). The failure’s event, when some case listens to it, and the record of the delivery still commit. So «Out of stock» never leaves half an order behind.

A thrown error means a bug: the transaction rolls back, nothing is published, the person sees a short generic message with a reference, and Telemetry records a problem. It is never shown as if it were an expected failure.

A case that starts on an event

src/cases/deliveries/pause-deliveries.ts
import { useCase } from '@sypnia/cases/sypnorm';
import { addHours } from 'date-fns';
import { db } from '../../db';

export const pauseDeliveries = useCase('pause-deliveries', {
  actor: 'system',
  touches: { writes: [db.delivery_pauses] },
  async run(ctx) {
    const { from } = ctx.event.data;                 // weather.check-weather.RainExpected.v1
    const until = addHours(from, 3);
    await ctx.db.delivery_pauses.insert({ from, until });
    return ctx.outcome('DeliveriesPaused', { until });
  },
});

The runtime has already checked that this event was not handled before; if it arrives twice, the second time does nothing (Delivery).

Seen in production

When @sypnia/telemetry is installed, each run is a span usecase place-order with the attributes sypnia.case=place-order and sypnia.case.outcome=OrderPlaced (or OutOfStock, BakeryClosed, error). You read your traces by use case and by how they end, not by URL.

  1. A whole use case
  2. The parts
  3. ctx
  4. Every run ends in ctx.outcome
  5. A case that starts on an event
  6. Seen in production

    Search pages, sections and terms