Your code
On this page
- Which operations are yours
- Your first handler
- An operation's handler
- An answer that is not a row
- A flow step
- A job
- Writing a job's body
- Who is asking, and in which organisation
- Calling another service
- Receiving events
- State transitions
- Versions
- Idempotency keys
- Rate limits
- Many-to-many links
- Rows of an organisation
- One row per person
- Wiring
- Your own tests
- In Rust
$ cd backend && uv run pytest tests/test_mine.pyThe design says what an operation is. You write what it does when the design
cannot say: the handler of an operation, a flow step or a job, and the module that
wires them in. Everything around your code is generated. This page uses real
code from examples/*/backend/packages/*_impl. The Rust equivalents are at the
end.
Which operations are yours
A create, update, delete or restore command, and a list or get query
over one entity, are generated whole. A command added with the name add,
create or new in a service about one entity is a create. These are yours:
- a command with
does: custom; - a create whose params do not give every field its entity needs
(lint:
create-lacks-field); - a page's data that is not a list of the entity's own fields (or, for one row per person, a group of them);
- a page's data that shows a field as another type than its entity keeps it (a text column shown as a number): both targets say which, and
lintleaves it to the 501, since only the pair of page and service knows; - an update with no param that names the row, unless its entity is one row per person;
- an operation that answers a
Shapewith nofrom(a command that answers a Shape too): its method is typed, and yours.
The studio's Command card says which it is, and why, under Why and To have it generated; the 501 says the same words. Until you write one, it answers 501 naming the method and the file. sync,
service_status and the studio's Status list them as "still to write". An
unwritten step or job fails its runs the same way.
Your first handler
On a project made by the quickstart with a Notes service,
add a custom command shout (an id param, returns: note) to the design
and run sync. npx globetrotter status names the method to write (1 to do). Put it in
backend/packages/my_api_impl/src/my_api_impl/notes.py:
from uuid import UUID
from my_api_contract import models as m
from my_api_core.errors import NotFound
from my_api_core.services import NotesBase
class NotesImpl(NotesBase):
async def shout(self, ctx, *, id: UUID) -> m.NotesShoutResponse:
note = await ctx.db.note.get(id)
if note is None:
raise NotFound("note", id)
note = await ctx.db.note.update(id, text=note.text.upper())
return m.NotesShoutResponse(note=m.Note.model_validate(note, from_attributes=True, context=m.ROW))context=m.ROW says the model is reading a row back: a column left empty is a
field left out, not a null sent. Without it, a row with an empty optional
field is a 500.
and a test in backend/tests/test_mine.py:
def test_shout_upper_cases(client):
made = client.post("/notes/actions/add", json={"text": "hi"}).json()["note"]
r = client.post("/notes/actions/shout", json={"id": made["id"]})
assert r.status_code == 200
assert r.json()["note"]["text"] == "HI"$ uv run pytest tests/test_mine.py
tests/test_mine.py . [100%]
1 passed in 0.18sA server running as local reloads on the save, and POST /notes/actions/shout
answers {"note": {"id": "…", "text": "HI"}}. A command's response model is
named <Service><Operation>Response. Raising NotFound for a row the
contract never promised a 404 for is a to-do in service_status: set
finds: "note" on the id param (the studio's Finds), and the contract lists
the 404.
An operation's handler
Each service has a module in <app>_impl, with a class that subclasses the
generated Base. Write a method named for the operation (snake case). Mail's
reply:
class ThreadsImpl(ThreadsBase):
async def reply(self, ctx: Context, *, id: UUID, body: str) -> m.ThreadsData:
if await ctx.db.thread.get(id) is None:
raise NotFound("thread", id)
if not body.strip():
raise InvalidInput({"body": "A reply needs some words."})
await ctx.db.message.create(thread_id=id, body=body.strip())
return await self.list(ctx)ctxcarries who is asking andctx.db, a repository per entity on one unit of work. A write through a repository applies the design's rules and leaves its audit row and its event in the same transaction. Both targets hold a create and an update to the rules: an empty required value is a missing one, a 400 under the field (A job needs a title.), before the row is written (transcript). Python checks the values you give, so a required field left out meets the column's NOT NULL instead. A generated create on Rust refuses in Python's words, what is missing and what breaks a rule in one 400 (transcript). Astringwith nomaxtakes 255 characters, and no text takes a NUL.- Params arrive as keyword arguments, typed. A param your method does not take yet is named by sync, with its type.
- Raise
NotFound,InvalidInputand the errors in<app>_core.errorsto refuse. Each carries its status and the words the caller sees. - Return the model the contract names (
m.ThreadsData). One that does not fit is a 500 naming the field.
A handler that needs the rules by hand uses check, which says every wrong field
at once, by its path. Storefront's placeOrder does:
check("order", values, prefix="draft.")A field the entity does not have is refused in words ("Booking has no field
state …: did you mean status?"), never a 200 that changed nothing. On a laptop a
500 carries the exception and the line of your code, so a press shows it.
Every 500, there or not, carries the request's x-request-id, and the server's log says it in one line before the
traceback: POST /members/actions/invite (request 01a2…): your method Members.invite raised RuntimeError: boom (app_impl/members.py:8).
Raising a refusal from your code uses the design's own words where it has them:
EmptyCart in the same file is the emptyCart Refusal's message.
The same handler takes each product's stock in the order's own transaction, on
ctx.db.session: it reads the row locked, lowers stock through the ORM (so
the audit sees it) and writes the order and one orderLine per product with
the name and price as they were. Too little stock raises OutOfStock (409,
… just sold out.) and nothing of the order is kept. Run on sqlite only; a
race of two orders for the last one was not tested.
An answer that is not a row
A Shape with a from is written for you (a query that
returns it counts, sums and groups on the database). One with no from is a typed
answer you build. The method's signature says what it answers; the model is the
contract's, so a part you leave out or get wrong is an error where you wrote it,
not on a page. A cart's totals, with lines an entity's rows:
class ReportsImpl(ReportsBase):
async def cart(self, ctx: Context) -> m.CartSummary:
rows = await ctx.db.orderline.find(limit=3, newest=True)
lines = [m.Orderline.model_validate(r, from_attributes=True, context=m.ROW) for r in rows]
return m.CartSummary(items=sum(line.qty for line in lines), total=Decimal("12.50"), lines=lines)impl ReportsService for Reports {
async fn cart(&self) -> Result<models::CartSummary, Error> {
Ok(models::CartSummary { items: 3, total: Decimal::from_str("12.50").map_err(Error::failed)?, lines: Vec::new(), first: None })
}
}A part that is not required is None (Option<…>) and left out of the answer.
For SQL beyond the vocabulary, write the statement in the method; the shape is
still what it answers. A command that answers a shape answers it as it is, not
wrapped in an object.
A flow step
A flow's steps are methods of a class in <app>_impl/flows.py, one class per
flow, one method per step (flow_steps.py when a service is itself named
Flows). Storefront's onOrderPlaced:
class OnOrderPlaced(OnOrderPlacedSteps):
"""onOrderPlaced, on order.placed: sendReceipt, then notifyWarehouse."""
async def send_receipt(self, event: Event) -> None:
order = event.data
await notify.send("orderReceipt", order["email"], **order)
async def notify_warehouse(self, event: Event) -> None:
order = event.data
await notify.send(
"packingSlip",
"warehouse",
**{**order, "gift": "yes" if order.get("gift") else "no"},
)A step runs at least once for an event, so write it to be safe to repeat: a
receipt sent twice is the cost of never losing one. Raise to fail a try; the
step is tried again as its retry says. Log with the standard logging
module; your lines show in the app and the relay. See
Flows and jobs.
A job
<app>_impl/jobs.py (scheduled_jobs.py when a service is itself named Jobs)
has a class with one method per job. The stub fails its
run until you write it:
class Jobs:
async def send_daily_sales(self) -> None:
"""Emails yesterday's orders and their total to the shop."""
raise NotImplementedError("job sendDailySales is not written yet …")Run it by hand with uv run python -m <app>_core.jobs run <name>.
Writing a job's body
A job's method takes ctx, as an operation of a service does: the repositories (ctx.db.<entity>) on one transaction that commits when the method returns and rolls back when it raises. Write through them: the audit and check_tenancy see a repository's writes, not a raw SQL statement's. A job runs outside any request, so under organisations it reads and writes every organisation's rows; every=True says so on purpose. A method written without ctx (async def mark_overdue(self) -> None) still runs, and reaches the data by engine("db").
from datetime import date
class Jobs:
async def mark_overdue(self, ctx: Context) -> None:
rows = await ctx.db.task.find(where=[("due_date", "lt", date.today())], every=True, unbounded=True)
for row in rows:
await ctx.db.task.update(row.id, overdue=True)A field a state machine holds (status, moved by flow) is refused by a plain update: a job that moves it passes the machine and the states the row must still be in (update takes no every=; it does not scope a write outside a request). The stub shows this call when the job's name or words name a state:
await ctx.db.appointment.update(row.id, _machine="flow", _from=["Booked"], status="NoShow")None comes back when another request moved the row first.
The stub names the repository the job's name or words mention and shows this example for it. Run on sqlite in a scratch project: python -m <app>_core.jobs run markOverdue answered done.
Who is asking, and in which organisation
A command of your own learns who asks from asking, and the organisation from acting; neither is a parameter, and ctx carries only the repositories. The stub says both in one line each when the design has sign-in or organisations.
from app_core.auth import asking # the principal (.id, .role, .via), or None when nobody is signed in
from app_core.tenancy import Acting, acting # now = acting.get(); isinstance(now, Acting): now.org, now.roleCalling another service
A design's Client nodes become typed clients: one method per Call, a timeout
on every try, retries only for a call that is safe to repeat, a circuit breaker,
the request's id passed on and the key read from the environment (the settings
are in Reference). In an operation they are on the
context (a sketch, not an example's code; CardDeclined is a Refusal you declare):
async def bill(self, ctx: Context, *, amount: int, currency: str, source: str) -> m.JobsData:
try:
charge = await ctx.clients.payments.charge(amount=amount, currency=currency, source=source)
except UpstreamRefused as refused: # a 4xx: the card was declined, the amount is wrong
raise CardDeclined(refused.body["error"]["message"]) from refused
return await jobs_page(ctx, charge["id"]) # anything else (UpstreamUnavailable) is a 502 in the service's wordsA call whose returns names a Shape answers a model: charge.id,
not charge["id"], and its parts typed (Decimal for a decimal). Python's fake reads
what a test scripts as the model too: .returns({"id": "ch_1", "status": "paid"}). In
Rust the method returns the generated struct (crate::models::ChargeResult); a call
with no returns is still Value. An answer that does not read as its Shape is an
UpstreamUnavailable / ClientError::Unavailable whose why says which part.
UpstreamRefused carries .upstream_status and .body, the other side's own
words, which your caller never sees unless you say them. Uncaught, it is a 502:
Payments refused the request (402). UpstreamUnavailable is a 502 too, and
means the other side is not answering (a 5xx, a timeout or an open breaker): do
not retry it in your code, the client already has. A POST marked idempotent
takes an idempotency_key= of your own, so a charge repeated from a flow step
after a restart is the same charge: pass the event's id.
Where to call from. A call from an operation holds the request, and the
database transaction unit() opened, for up to timeout times retries + 1.
Call from a flow step when the answer is not needed to
reply (a receipt, a notice, a sync): a step runs after the commit and is tried
again as its retry says. In a step or a job, from <app>_core.clients import get_clients.
Testing. tests/conftest.py installs a fake of every client for every test,
so no test calls out. Script one, and read what it was asked:
def test_a_declined_card(as_role, fake_clients):
fake_clients.payments.when("charge").fails(402, {"error": {"message": "Declined."}})
r = as_role("member").post("/jobs/actions/bill", json={"amount": 500, "currency": "usd", "source": "tok"})
assert r.status_code == 409
assert fake_clients.payments.calls == [("charge", {"amount": 500, "currency": "usd", "source": "tok"})]when(call) takes a chain: .fails(503).returns({...}) fails once, then
answers; the last step repeats. A call nobody scripted fails the test with
NotScripted. tests/test_clients.py is the policy itself, run against a
fake transport (httpx.MockTransport): what is retried and what never is, the
breaker, the ids, the key kept out of the log.
Starting. python -m <app>_fastapi builds the clients before it serves:
outside local, a missing key or address is one line on stderr and exit 1
(Export PAYMENTS_KEY: it is the Payments client's key.), not a 500 at the
first call. In local the address is GLOBETROTTER_PAYMENTS_URL (or the
components file's) and the key a placeholder with a warning, so a laptop boots.
Receiving events
A design's Webhook nodes are routes outside services post events to, each
checked before any of your code runs (Reference: the
signature over the raw body in constant time, the signed time against a
tolerance, the event's id remembered). What a Handler does with an event
needs no code of yours when it only emits (a flow listens) or calls a
command whose params its args read from the body. For a command that is
yours, write it as any other and map its params:
{ "id": "stripe-paid", "type": "Handler", "props": { "name": "paid", "match": "payment_intent.succeeded", "calls": "orders-pay",
"args": "orderId=/data/object/metadata/order_id, amount=/data/object/amount" } }Orders.pay is then called as it is from its own route, in the one unit of
work, as the webhook's role. Write it so that running it twice does no harm
(the sender may retry, and on Rust a process that dies mid-handler lets the
event run again). A refusal or an error in it is a 500 and keeps nothing: the
event is not recorded, and the sender's retry runs it again. The log says
webhook Stripe: event evt_1: NotFound; nothing was kept, the sender will retry;
the body and the secret are never logged.
Testing. tests/test_webhooks.py calls each webhook in process (right,
wrong, old, twice, too big, broken). For yours, webhooks.delivery builds a
signed delivery:
from <app>_core import webhooks
def test_a_paid_event_marks_the_order(client, fresh_db):
hook = webhooks.HOOKS["Stripe"]
raw, headers = webhooks.delivery(hook, "evt_1", "payment_intent.succeeded",
{"data": {"object": {"metadata": {"order_id": ORDER}, "amount": 1999}}})
assert client.post(hook.path, content=raw, headers=headers).json() == {"received": True}
again = client.post(hook.path, content=raw, headers=headers)
assert again.json() == {"received": True, "duplicate": True}Send the same bytes you signed (content=raw, not json=: a body serialised
again is not what was signed). On Rust, webhooks::delivery(&webhooks::STRIPE, "evt_1", "payment_intent.succeeded", json!({...}), now) returns the body and
the headers; sign_with and verify_with take a key of the test's own. In
local the secret is whsec_local_development when the variable is not set,
so a delivery built in a test is accepted by the app in the same run. Calling
one by hand: press_operation(design, "webhookStripe", body: {...}) signs it
with the development secret.
Starting. python -m <app>_fastapi (and the Rust binary) checks every
webhook's secret before it serves: outside local, a missing one is one line on
stderr naming every missing variable, and exit 1.
State transitions
A command that does a transition is generated whole: you write nothing unless it
should do more. What the generated Python method does (<app>_core/services.py), in order:
async def ship(self, ctx: Context, *, order_id: str) -> m.OrdersShipResponse:
require_role("admin") # the move's own role, on top of the command's
row = await ctx.db.order.get(order_id)
if row is None:
raise NotFound("order", order_id) # 404
if row.status not in ("Paid", "Packed"):
raise TransitionRefused("order", "ship", row.status, ("Paid", "Packed")) # 409
if not (row.address is not None): # the guard
raise TransitionRefused("order", "ship", row.status, (), message="An order needs an address before it ships.", status=422)
moved = await ctx.db.order.update(order_id, status="Shipped", _machine="fulfilment", _from=("Paid", "Packed"))
if moved is None: # another request moved it first
now = await ctx.db.order.get(order_id) # 404 if it is gone, else the same 409 with its state now
...To add behaviour override the method in your service class, call the Base's
(await super().ship(ctx, order_id=order_id)) and do your part after: it ran in
the same transaction, and its event is written with it. To move a row from
code of yours call the same repository method with the machine's name:
await ctx.db.order.update(order_id, status="Shipped", _machine="fulfilment")
(add _from=(…) to make the write conditional on the state, as the generated method does: it answers None when the row is no longer in one of them). The part of a guard SQL can say goes into that same write (_guard=; Rust's update_when takes it too): Limits.
Without _machine, an update that sets the field raises ValueError("status is moved by the fulfilment machine: use a transition"); a transition does not
check the state for you when you call it that way, so check it as the generated method
does. A refusal of your own is raise TransitionRefused(entity, move, state, allowed) (409), or with message= and status=422.
On Rust it is the trait's default method in <service>_api.rs; the repository's
update refuses the field (a 500, said as the machine's) and
update_moving(&key, changes) is the one that may change it, and update_when(&key, changes, Some(("status", &["Paid"]))) writes only while the row is in one of the states (None when it is not). The refusals are
crate::machines::refused(entity, move, state, &allowed) and
crate::machines::guard_said(words).
Testing. Python's tests/test_transitions.py (uv run pytest tests/test_transitions.py -rs in backend/) and Rust's crates/<app>-generated/tests/machines.rs press each move through the app:
| Pressed | Must answer |
|---|---|
| From a state it may be made from | 200, state changed; one audit row if audited; the event once in the outbox |
| From any other state | 409 in the state's words; row, audit and outbox unchanged |
| A row that is not there | 404 |
| No credential / a rung below the move's role | 401 / 403 |
Another person's row (an owner) |
404 |
| Eight presses at once | exactly one 200 |
| A guard made true / made false | 200 / 422 in the guard's words, row unchanged |
A guard it cannot set up (a field through a link, a date) or an entity with a required link is a skipped case that says so: -rs lists them in Python, plain cargo test in Rust, which prints ignored, <reason> beside each one (-- --ignored --list gives the names alone, and -- --ignored runs them, so each fails). Python runs in process only. Rust also writes crates/<app>/tests/machines.rs once (yours once edited): the same presses with your services wired as main.rs wires them, so a move you override is the one tested. Edited, it follows the design no more, and service_status says what its //! Moves: and //! Cases: lines no longer match. With organisations on, crates/<app>/tests/tenancy.rs (written once, a //! Presses: line sync compares) presses every list and get of an organisation's rows: your list must hold this organisation's row and not the other's.
Events. The event a move emits is its transition's emits (the command's own
if it names one), written to the outbox in the move's transaction with the row's
fields as they are after it. Flows listen for it as for any command's.
Versions
On a versioned entity the route reads If-Match
before your handler runs: a tag it cannot read is a 400, none where one is
required is a 428. What reaches you is ctx.if_match: the number the tag
named, or None when no tag came or it was *. The generated handler hands it
to the repository:
async def rename(self, ctx: Context, *, id: UUID, title: str) -> m.DocsRenameResponse:
row = await ctx.db.doc.update(id, title=title, _version=ctx.if_match)
if row is None:
raise NotFound("doc", id)
return m.DocsRenameResponse.model_validate({"doc": m.Doc.model_validate(row, from_attributes=True, context=m.ROW)})update, delete and restore take _version. With a number, a row that is
not at that version raises Stale("doc") (<app>_core.versions), the 412,
and nothing is written. With None nothing is held. A handler of your own for an
update, a delete, a restore or a transition does the same: pass
_version=ctx.if_match, or compare row.version yourself and raise Stale.
Leave it out and the header is read and then ignored.
The version itself is never yours to raise. The column is SQLAlchemy's
version_id_col, so every write of a row through the session raises it by
one, in a custom command and in a flow step too. Two handlers that load one
row and both save it do not both win: the second is a 409 (Another request changed the same row at the same moment: try again.), or the 412 when its
route takes If-Match and the request sent one. A write around the ORM (raw
SQL, a Core update) raises nothing: raise version in the statement.
The answer's ETag is written by the route from the row you return. You set
no header.
Testing. tests/test_versions.py follows the design until you edit it,
then it is yours. It sends each write with the right tag, a wrong one, an old one, *, tags that
are not tags and none, sends ten writes with one tag at once (one wins), and
checks a read answers the ETag and a list does not. It runs in process only.
It is not written for a design with organisations, or with sign-in on and no
key to send with.
Rust. The answers are the same; how the tag reaches the write is not. The
route reads If-Match and keeps the tag in a task-local while your handler runs
(src/version.rs). Nothing is handed to your handler and it passes nothing on.
The first write of that entity through the generated repository in the request
(tx.doc().update, delete, restore, a transition's update_when) is held
to the tag in its own statement and raises the version: a row at another
version is the 412 and nothing is written. A handler of your own that writes
through tx.<entity>() needs no change.
What the repository does not see is yours. SQL of your own around it is neither
held nor raised: raise version in the statement, and hold it with the tag
the request sent:
let want = crate::version::expecting("doc", row.version)?;(from your crate the path starts at the generated crate, <app>_generated).
It answers the 412 or the 428 itself; otherwise want is the version to put
in AND version = …, or None when no tag came or it was *. Only the first
write of the entity in a request is held; a second runs unchecked. A write in
a task you tokio::spawn sees no tag. A write no request named (a flow step,
a job, a webhook) runs unchecked and still raises the version.
tests/versions.rs is generated and written again on every sync. It runs
each versioned entity through the app's routes on a sqlite file of its own:
the ETag on a read, a write that raises the version, a stale tag (412,
nothing changed), *, tags that are not tags, no tag, a delete and a restore,
a stale move told before a wrong state, and twenty writers with one tag (one
wins). It is not written for a design with sign-in or organisations, and it
leaves out an entity it cannot make a create, a read and a write for.
Idempotency keys
An idempotent command's handler is written as
any other. Its signature does not change and nothing about the key reaches
it: no argument, nothing on the context. The route reads Idempotency-Key,
takes it, runs your handler and keeps the answer; on a repeat your handler does not
run.
Python. The route takes the key as the first statement of the unit of
work your handler runs in, and keeps the answer in it before the commit. So the
key, your writes through ctx.<store>, their audit rows and their events
commit together or not at all, and a handler that raises keeps no key.
Rust. The route keeps the key in a task-local while your handler runs
(src/idempotency.rs). The first unit of work your handler opens on the
command's store (self.repos().db.begin()) takes it as its first statement,
so the key commits with what you write. The answer is kept after your
commit. On a repeat the handler stops at its begin, before it writes anything.
What not to do in the handler of an idempotent command:
- Do not write through a session, a pool or a store that is not the command's own. That write is not in the key's transaction: a crash after it and before the commit runs it again on the retry.
- Do not call an outside service whose call is not itself safe to repeat. The
call is outside the transaction. Mark the
Callidempotentand pass a key of your own (idempotency_key=): Calling another service. Lint warns where it can see one (idempotent-calls-out). - Do not answer something that changes between two reads (the time, a random value) and expect a repeat to differ: a repeat is the first answer, byte for byte.
- Rust: do the write before anything you
tokio::spawn. A task you spawn sees no key, and a second unit of work in the handler does not hold the key. - Do not catch the 422 or the 409 to hide them: they are the caller's to act on.
Testing. tests/test_idempotency.py follows the design until you edit it,
then it is yours; it runs in process. It sends a key that cannot be one
(400), a repeat (the first answer, one row), the key with another request
(422), no key (runs each time), an expired key (runs again), ten requests at
once with one key (one row), a write refused after its key was taken (no key kept),
and with organisations another organisation's same key. Rust's
tests/idempotency.rs is generated and written again on every sync. Where
each has been run: Targets.
Rate limits
A limited operation is checked before your handler
runs: after sign-in, the role and the organisation, before the request body
is read (the order).
Your handler sees nothing of it and counts nothing. To refuse for a reason of
your own (a quota, a plan), declare a Refusal with
status 429 and raise it. In your own tests set GLOBETROTTER_LIMITS=off
unless the limit is what you are testing; the generated contract tests do.
Many-to-many links
A joined relation's links are set through the owner's repository, each id looked up first (an id with no row is a 404):
await ctx.db.product.link(row, "tags", [tag_id]) # add; one already there stays one
await ctx.db.product.unlink(row, "tags", [tag_id]) # take away
await ctx.db.product.set_links(row, "tags", tag_ids) # exactly theseIn Rust they are link_tags, unlink_tags and set_tags on the repository. A
generated create or update takes <relation>Ids and does this for you. A
relation that goes through an entity is read only: write the through entity's
rows.
Rows of an organisation
With tenants on, the repositories
read and write only the current organisation's rows, so a handler needs nothing
more. Asking for every row is on purpose: every=True on a repository's read
in Python, the *_every methods (find_every, get_every, insert_every) in
Rust. Those, and SQL of your own, are not scoped; check_tenancy lists each by
file and line. Outside a request (a script, a job) there is no organisation and
the scope is off. In your own tests, conftest.py gives TEST_ORG and OTHER_ORG (seeded, with the development people in the first): send TEST_ORG in the organisation header and create rows in it.
One row per person
A settings page saves one row for each person: the form sends fields and no id. Say so in the entity, with what the vocabulary already has: its owner names a text field (the person), and that field is marked Unique.
{ "type": "Entity", "props": { "name": "setting", "owner": "person" },
"slots": { "fields": [
{ "type": "Field", "props": { "name": "id", "type": "uuid", "key": true } },
{ "type": "Field", "props": { "name": "person", "type": "string", "required": false, "unique": true } },
{ "type": "Field", "props": { "name": "theme", "type": "string", "default": "light" } } ] } }With sign-in on, both targets then write whole:
- an
updatewith no key param (a form's save, or params named after fields): it reads the asker's own row, changes it, and makes it on the first save, so what a new row needs must be given as a create's is. The owner is the asker's, never what the form sends; the top of the ladder saves its own row like everyone else. In Python this isrepo.save_own(**values), in Rusttx.setting().save_own(new);get_ownreads the row (both are yours to call too); - the page's data, the query named
listat the service's route: its groups of the entity's fields (draft) come from the asker's own row; before the first save there are none. A query that answers one row with no key (manyoff) is the asker's own row, a 404 before the first save.
A second create of such an entity is a 409 in the ownRow words ("You already have a setting: change it instead.", which words can change), not the race's.
The update stays yours, said in the 501, when sign-in is off (nobody is anyone,
so there is no row of the asker's: a single row for everybody would be left
behind by the first sign-in), when the entity is versioned or belongs to
organisations, when the update has a sets, or when the form posts its fields
in more than one group. Without the marker the update's 501 names it: add a
param named id, the row's key, or mark setting's person field Unique….
A person who deletes their own row (soft delete on) is not locked out: the
next save finds the row, deleted or not, clears deleted_at and writes the
saved values in the same write, so the audit has one update row that says
both (deletedAt back to null, the values changed). Fields the save does not
send keep what the row held. Until then GET the row answers 404 and the page's
data has no groups, as before the first save. A hard delete leaves nothing to
bring back.
Null. A form's fields (draft.nickname) stay as the contract has them: left
out keeps the field, null is the 400 "nickname may be left out, but not sent
as null.". A param that says clears (an update with params named after
fields, an optional field) takes null to empty the field and leaves it when
left out, as a keyed update's does; the contract says [string, null] for it.
null on a required field is the usual 400 naming it. In Python a left-out
clears param is Keep.KEEP, never written; in Rust
save_own_clearing(new, &clear) takes the fields to empty (save_own(new)
empties none).
Two first saves at the same instant end as one row and two 200s. Python
makes the row inside a savepoint; the save the database refuses (the Unique
owner) reads the other's row (FOR UPDATE where the engine has it) and changes
it. Rust's insert_once is an INSERT … ON CONFLICT (person) DO NOTHING on
sqlite and Postgres (MySQL: ON DUPLICATE KEY UPDATE with the row read back by
the key it was given), and a save that finds the other's row changes it. Run:
20 parallel first saves by one person against each target on sqlite and on
Postgres 16 gave 20 times 200 and one row each time. On MySQL 8.4 (20 November,
a scratch container) both targets keep one row, and the sequence save, delete
own, get, save, get answers as on the other engines (the second save brings the
same row back, one audit row). InnoDB does not give every one of 20 at once a
200: the database picks some as the victims of a deadlock and both targets
answer those the race's 409, "Another request wrote a row with the same key at
the same moment: try again.", never a 500 (Python: 13 to 16 of 20 answered 200
in three runs; Rust's insert_once was seen answering that 409 to 8 to 13 of
20 because the save that lost read the other's row with a plain read, which
still sees the rows as they were when its unit of work began; it now reads with
FOR UPDATE, written and compiled, not run again). The run of two people on both targets, and the sequence save, delete own,
get, save, get with the null cases:
settings-one-row-per-person.
Wiring
<app>_impl/wiring.py (app_wiring.py when a service is itself named Wiring;
the key store is then key_store.py beside a service named Auth) is the one
module of yours the generated code imports:
three factories with fixed signatures, plus flow_steps and jobs.
def services(settings: Settings) -> Services:
return Services(shop=ShopImpl(), cart=CartImpl(), checkout=CheckoutImpl())
def auth_strategies(settings: Settings) -> list[Any]:
return [SessionCookie(DevPeople(settings), secret=session_secret(settings.env)),
ApiKey(DevKeys(settings), header="X-Api-Key")]
def flow_steps(settings: Settings) -> dict[str, Any]:
return {"onOrderPlaced": OnOrderPlaced()}
def jobs(settings: Settings) -> Any:
return Jobs()Sync keeps it in step with the design until you edit it. After that, a
service, flow or job you add to the design needs its line added by you. auth.py beside it holds DevKeys and DevPeople, which you
replace for real sign-in: see Auth and security.
Your own tests
backend/tests/test_*.py are yours. Sync writes conftest.py and
test_contract.py there, and, when the design has them, test_clients.py,
test_webhooks.py, test_transitions.py, test_tenancy.py,
test_given_keys.py, test_update_rules.py, test_credentials.py and the ones of the pages above (test_versions.py, test_idempotency.py, test_limits.py, test_apikeys.py, …) (a
malformed API key or session cookie is the same 401 as a wrong one): each a stub,
yours once edited (an edited test_tenancy.py or test_transitions.py that no longer presses a list, get or move the design now has is named by service_status: "your … does not press …"). The conftest gives you these fixtures:
| Fixture | Gives |
|---|---|
client |
The app in process, on fresh rows. client.get("/…"), client.post("/…", json={…}). |
as_role("member") |
A client signed in as that role, by its test key. |
fresh_db |
Every store put back to the run's migrated rows before the test. |
fake_clients |
With clients in the design: every outside service faked. fake_clients.payments.when("charge").returns({…}); a call nobody scripted fails the test. |
client and as_role both start from fresh_db, so no test sees what another
left. A test:
# mail: replying takes a member, so a reader is refused (any thread id will do)
def test_a_reader_cannot_reply(as_role):
body = {"id": "00000000-0000-0000-0000-000000000000", "body": "hi"}
r = as_role("reader").post("/threads/actions/reply", json=body)
assert r.status_code == 403uv run pytest tests/test_mine.py runs only yours, in a few hundred
milliseconds. The client is Starlette's TestClient: a workspace made before it
was in the dev group needs uv add --dev httpx2 once. fresh_db is skipped
when GLOBETROTTER_TEST_BASE_URL calls a served backend.
The generated contract test runs a fresh sqlite file per run, signed in as the top role's development person when sign-in is on (a stranger's 401s check nothing). It is a stub: yours once edited.
In Rust
Your crate is crates/<app>. Each service is
crates/<app>/src/services/<service>.rs: a type implementing the generated
trait. Write any operation of the trait by its name; one you do not write
answers 501 with where to write it. A handler:
- opens a unit of work,
self.repos().db.begin().await?; - reads and writes through the repositories,
tx.thread().insert(…): the design's rules, the audit row and the event come with each write; - commits with
tx.commit().await?. A handler that writes and never commits answers 500 saying so, never a 200 that kept nothing.
It refuses with Error::invalid(field, words) (400), Error::not_found(entity)
(404) or Error::new(StatusCode::CONFLICT, words). It answers with the model,
or with shape::model(json!({…})); one that does not fit the contract is a 500
naming the field and your line. Its own SQL runs on the transaction inside
DbTx::Sqlite(tx). sync --check wants cargo fmt on your crate too.
A client is on the process: clients::clients()?.payments.charge(…), the
arguments a struct per call, an error that becomes a 502 through ?:
use mail_generated::clients::{self, ClientError, payments::ChargeArgs};
async fn bill(&self, amount: i64, currency: String, source: String) -> Result<models::ThreadsData, Error> {
let charge = match clients::clients()?.payments.charge(ChargeArgs { amount, currency, source, ..Default::default() }).await {
Err(ClientError::Refused { body, .. }) => return Err(Error::new(StatusCode::CONFLICT, body["error"]["message"].as_str().unwrap_or("Declined."))),
other => other?, // Unavailable is a 502 in the service's words
};
shape::model(json!({ "selected": { "subject": format!("charged {}", charge["id"]) } }))
}In a test, let (clients, fakes) = Clients::faked(); fakes.payments.when("charge") .fails(503, json!({})).returns(json!({…})); clients::install(clients); fakes the
other service, and fakes.payments.calls() says what it was asked. A call
nobody scripted panics, naming it. tests/clients.rs (generated) calls the
policy the way Python's test_clients.py does. At start, serve refuses a
missing key or address outside local.
Rust tests live in crates/<app>/tests/*.rs; sync writes there only machines.rs and tenancy.rs (once, above), never over a file you edited. Put
<app>_generated::testing::fresh_db() first in each test: it gives every store
as its migrations leave it (a sqlite file per store under the temp folder, made
once per test binary, its rows put back before each test, tests taking turns so
none sees another's). press(app, request) sends a request through
app::router(…) as main.rs builds it, and as_role("member", request) signs
it in by that role's development key. cargo test --workspace runs them beside
the contract's examples. The generated crate is quiet under clippy::pedantic
and cargo doc; the lints of your own crate are yours to choose.
A page's data that the design cannot fill answers 501 in both targets,
naming the method and the file, until you write it. A page's data with no
fields still answers {}.