steid

@jamesgill /

steid/plans/architecture.md
Markdown15.9 KBRendered·Source·Blame·History·Raw
1# Architecture
2
3## Layers
4
5DDD + clean architecture. Dependencies point inward. The domain knows nothing about
6HTTP, SQL, git, or Topcoat.
7
8```
9web / ssh (interface) → application (use cases) → domain (entities, ports)
10 ↑
11 infrastructure (sqlite, git binary, argon2)
12 implements the ports the domain/application declare
13```
14
15| Layer | Holds | Must not import |
16|---|---|---|
17| `domain` | entities, value objects, typed IDs, repository traits, `DomainError` | anything infrastructural |
18| `application` | use cases, ports (`GitStorage`, `GitProtocolServer`, `PasswordHasher`), `AppConfig` | concrete adapters |
19| `infrastructure` | SQLite repos, `git` subprocess wrappers, Argon2, sessions, web handlers | — |
20
21**Every operation takes an `Actor`.** Authorization is checked in the use case, before
22any side effect. Not in the handler, not in the adapter. The previous attempt got this
23right and it paid off — `serve_push` could enforce `Role::Owner` in one place
24regardless of transport.
25
26### Access
27
28**`application/access.rs` is the one place that decides who may do what.** It holds
29`is_org_owner`, `is_org_member`, `instance_owner` and the four resolvers every
30repository use case starts with — `visible_repo` (the one visibility rule: public, or a
31member of the owning org), `readable_repo` (that plus the ownership flag),
32`writable_repo` and `changeable_repo` (owner-only, `NotFound` for what the actor cannot
33see and `Forbidden` for what they can). A use case asks this module; it does not read a
34`Role` or compare a `UserId` itself, and it does not repeat the visibility body — the
35three copies that existed on 2026-09-10 were folded back into `visible_repo`.
36
37**Two kinds of caller, two predicates, both named.** Everything above answers a question
38about an `Actor` — a person with a session. The other caller is a *machine*: a control
39plane holding `STEID_OPERATOR_TOKEN`, with no session and no user to be. That one is
40authenticated by `web::operator::operator_authorized`, a constant-time bearer-token
41comparison living in the web layer because a transport credential is a transport
42concern, and it grants exactly the operator routes — never a repository, never a user's
43data. A page never decides either question inline: it asks `context::owned_repo`,
44`context::owned_profile` or `context::instance_owner`.
45
46The same module holds **`Stores`**, the bundle of the three ports a repository is
47reached through — organisations, memberships, repositories. Fifty-six use cases needed
48exactly those three together, so they travel as one borrowed value rather than three
49parameters. Ports only some use cases need (issues, labels, pulls, users, git) stay
50separate arguments; a bundle that grows to hold everything is a service locator.
51
52That is not tidiness. Milestone 7's graded permissions — a collaborator who may comment
53but not merge — are a change to these predicates and, where a permission has to be
54named, to their signatures. Roughly twenty lines there instead of thirty use cases,
55*provided* no use case decided authorization inline in the meantime.
56
57## Conventions
58
59These come from two prior attempts. They earned their place.
60
61### Typed IDs — never raw strings for entity references
62
63```rust
64// CORRECT — the compiler catches a swapped argument
65fn get_member(&self, org_id: &OrgId, user_id: &UserId) -> ...
66
67// WRONG — silently compiles, fails at runtime
68fn get_member(&self, org_id: &str, user_id: &str) -> ...
69```
70
71`UserId`, `OrgId`, `MembershipId`, `RepoId`, `InviteCodeId`, `SshKeyId`.
72
73### `new()` validates, `from_trusted()` doesn't
74
75`new()` is for user input and returns `Result`. `from_trusted()` is for rows loaded
76out of the database, which were validated on the way in. Infrastructure repos should
77always use `from_trusted()` — re-validating DB rows means a validation-rule change
78turns old rows unreadable.
79
80### `from_str` returns `Result`, never `Option`
81
82A silently-defaulted enum parse is a bug that surfaces days later as wrong
83permissions. Applies to `Role`, `Visibility`, `ImportState`, `IssueState`.
84
85### Every repository port gets two implementations
86
87An in-memory one and a SQLite one. The in-memory one is what makes use cases testable
88without a database — attempt #2 reached 60 tests this way and they ran fast enough to
89stay in the loop.
90
91### Ports live where they're consumed
92
93Repository traits in `domain/repository/`. Service ports the application needs
94(`GitStorage`, `GitProtocolServer`, `PasswordHasher`) in `application/port.rs`. Use
95cases take `&impl Port`, not a boxed trait object.
96
97Git is deliberately several narrow ports rather than one service, and how the binary is
98actually invoked lives in one place — `git_command`, `count_spawn` and `run_git` in
99`infrastructure/git/mod.rs`, which the per-port adapter files beneath it all call.
100[0006]decisions/0006-git-binary-behind-narrow-ports.md. One file per port:
101`git/{storage,protocol,archive,import,merge}.rs`, and the read port's two
102implementations sit together in `infrastructure/git_query/`.
103
104### Every form carries a CSRF token, and every POST handler checks it
105
106`csrf_field()` in the form, `csrf_verified(cx, &submitted.csrf_token).await?` as the
107first line of the handler — before the ownership guard and before the use case. The
108token is `HMAC-SHA-256(per-boot secret, session token hash)`, so nothing is stored.
109[0008]decisions/0008-csrf-double-submit-bound-to-the-session.md.
110
111A `#[route]` handler returns a response rather than a view and so cannot reach the 403
112page the root layout renders; it uses `csrf_verified_response` instead, in the `if let
113Some(response) = …` shape `throttled` established.
114
115A route that genuinely cannot carry a token goes in `csrf::EXEMPT` **with the reason**.
116`web/csrf_scan.rs` reads this directory's source and fails the build for any POST route
117that does neither — which is the only thing making a hand-written check in thirty-one
118handlers safe.
119
120**Signing in is the one form submitted signed out that is checked anyway.** It has no
121session to bind a token to, so `sign_in_route` calls `csrf_verified_signed_out(cx)`
122after `throttled`, which refuses a POST carrying neither `Origin` nor `Sec-Fetch-Site`
123(0008's note of 2026-10-07). The scan counts it, because its name contains
124`csrf_verified`.
125
126## DB-plus-filesystem writes
127
128Creating a repo writes to two places that can't share a transaction: the
129`repositories` row and the bare repo on disk. Neither prior attempt fully solved this.
130
131Attempt #1 used a **compensating transaction** — create on disk first, and if the DB
132insert fails, delete the directory:
133
134```rust
135let repo = self.repository.create(&id).await?;
136if let Err(e) = self.repo_record_repo.create(&record).await {
137 let _ = self.repository.delete(&id).await; // compensate
138 return Err(e.into());
139}
140```
141
142That leaks an orphaned directory if the process dies between the two calls, and a
143directory without a row is worse than invisible — it silently blocks re-creating a
144repository by that name.
145
146**The durable fix is written.** `application/reconcile.rs` is the boot sweep: it lists
147the directories on disk, subtracts the rows, and quarantines the remainder under
148`orphaned/` rather than deleting it, so the name is freed and the objects are still
149there. It runs beside the interrupted-import and reflog sweeps, and for the same
150reason — nothing has been spawned yet, so a directory with no row is genuinely finished
151rather than half-written by a task still running. It covers all three ways to get one:
152a create that died before the insert, a rename that died after the directory moved, and
153an import whose repository was deleted mid-clone.
154
155The compensating transaction stays as the fast path. The sweep is what makes it safe to
156rely on, and it is a sweep rather than pending rows because a pending row still needs
157somebody to come along and resolve it.
158
159## Data access
160
161Topcoat's grain is async components that query the database directly and check
162permissions inline. State comes from `app_context::<T>(cx)`, and the framework's own
163guidance is to "prefer composable `cx: &Cx` functions over middleware/extractors for
164auth and request-scoped data."
165
166That reads as a view layer reaching for the data layer, which the rules above forbid.
167It was a genuinely hard question while SSH was the git transport, because an SSH
168channel handler has no `Cx` — so authorization expressed in a component was invisible
169to `serve_push`, and the two had to share something.
170
171[Decision 0001]decisions/0001-git-over-http-not-ssh.md removed that transport. Every
172caller now has a `Cx`, so nothing *forces* a transport-neutral use case layer. The
173position is therefore a choice, taken deliberately:
174
175**Writes and authorization go through use cases. Reads may go direct.**
176
177- Any mutation, and any decision about what an actor is allowed to do, lives in an
178 application use case that takes an `Actor` and the ports it needs. One place, one
179 answer, reachable from a page, an `/api` route, or a future SSH adapter alike.
180- Straightforward reads for display may query through the pool in a component.
181
182**This is what actually happened.** The 2026-09-06 organisation review found **all 34
183POST handlers going through a use case that takes an `Actor`** — not one writes through
184a repository port directly — and `infrastructure/web/` importing `domain::repository`
185nowhere. The rule held across four waves of parallel agents, which is the evidence it
186is a workable line rather than an aspiration.
187
188One thing the original position expected did *not* happen: `#[memoize]` was named as
189what would make per-component fetching pay, and **nothing in the tree uses it**. Reads
190are cheap enough, or already hoisted into a use case that returns a whole view struct,
191that no page has needed to deduplicate a query. Treat it as available, not as load-
192bearing; the earlier text credited it with earning its keep, and it had not been asked
193to.
194
195The tell for when a read has outgrown that: if it starts deciding whether the viewer is
196allowed to see something, it isn't a read any more — move it.
197
198Revisit if `/api` and the pages start duplicating query logic. That's the signal the
199line is in the wrong place.
200
201## Migrations
202
203**A shipped migration is immutable, comments included.** `sqlx::migrate!` checksums the
204whole file and refuses to boot when an applied one has changed; a comment edit in a
205shipped file stops every existing instance. A digest test pins every released set
206since 0.5.0, which between them hold every migration that has ever shipped
207([releases.md]releases.md#where-each-releases-set-actually-lives).
208
209**Every migration must be one the *previous release's* binary can run against.** The
210binary carries its schema (`sqlx::migrate!` runs on boot, see `infrastructure/
211database.rs`), so a migration lands the instant a new build starts — while the old
212build may still be serving from the same file.
213
214Two situations make that not hypothetical:
215
216- **A fleet upgrade runs unattended.** [Control-plane decision 0002]../../steid-control-plane/decisions/0002-machine-per-tenant.md
217 makes a fleet upgrade N `deploy.sh` runs against N machines nobody is watching. A
218 migration the running build cannot tolerate takes a customer's instance down between
219 the migration and the restart, with no one at the keyboard.
220- **Zero-downtime deploys, when they are built.** The plan in `current.md` runs the old
221 and new processes side by side over one SQLite file while Caddy is repointed. The new
222 one migrates on boot; the old one keeps serving. A dropped column breaks it mid-swap.
223
224So: **expand, deploy, contract.**
225
226| Phase | What it may do | When |
227|---|---|---|
228| **Expand** | `create table`; `create index`; `alter table … add column` **nullable, or with a `default`**; backfill with `update` | any release |
229| **Deploy** | ship the binary that writes the new shape and stops writing the old | the same release, or a later one |
230| **Contract** | drop the column, drop the table, rename, tighten to `not null` | **a release later**, once no deployed binary reads the old shape |
231
232Forbidden in the same release as the code that needs it, and the lexical guard in
233`database_compat_tests.rs` fails the build for each:
234
235- `drop column` — the old binary's `select *` still names it.
236- `drop table` — likewise, and a `select` against a missing table is an error, not a
237 null.
238- `rename` (table or column) — a drop and an add at once, so it is both failures.
239- `alter table … add column … not null` **without a `default`** — SQLite refuses it
240 outright on a non-empty table, and even where it succeeds the old binary's inserts
241 omit the column.
242
243Contracting is not forbidden, only deferred: it is a migration in the *next* release,
244written when that release is cut. `plans/releases.md` records which migrations each
245release shipped, so "what the previous release's binary reads" is a fact rather than a
246guess — check it before writing a contracting migration.
247
248The rule is enforced two ways, and only one of them is a real test:
249
250- **The lexical guard** reads `migrations/` at test time and rejects the four
251 statements above. It covers every migration automatically, including one added after
252 this was written. It is a grep, so it is fooled by a rebuild-the-table-and-swap done
253 in `create`/`insert`/`drop` steps — which is exactly why the rule is written down
254 here as well.
255- **The replay test** applies the previous release's migration set to a fresh database
256 and runs the *current* binary's reads against it. That is the honest half: proving
257 the *old* binary reads the *new* schema would need the old binary linked in, and it
258 is not. It still earns its place — `steid backup` opens the pool without migrating
259 (see `database::open`), so a new binary genuinely does read an old schema — but the
260 forward direction the rule is about is covered by the guard and by review, not by a
261 test.
262
263**A binary started against a newer database must boot**, because that is what a rollback
264is: a newer release migrated the file, failed, and the previous binary was put back.
265An old process that is *already running* keeps serving under the rule above; one
266*started* against the newer file meets sqlx's migrator first. Expand-only makes it
267*able* to read the newer schema, but sqlx's default `ignore_missing: false` stops it
268from trying: an applied migration it does not know is `VersionMissing`, the binary
269exits, and systemd restarts it for ever. So `migrate()` calls
270`set_ignore_missing(true)`. Only the unknown versions are excused — every migration the
271binary carries is still checked against its stored checksum, so an edited shipped
272migration is still `VersionMismatch`.
273
274- **Since 0.8.1.** The fix only helps a rollback *to* a version that carries it. 0.8.0 →
275 0.7.0 can never roll back; the first rollback that can work is onto 0.8.1 or later
276 ([launch 1.2]../../plans/launch.md#phase-1-before-anything-else).
277- **Tested in process, not against a real binary.**
278 `a_database_one_migration_ahead_still_boots` starts *this* binary's migrator against
279 a database one migration ahead, after checking that sqlx's default refuses that same
280 database, and then reads the table the newer migration widened.
281 `an_edited_migration_is_still_refused` checks the strictness that is kept. Booting
282 the real previous release's binary against the current schema needs a Linux binary,
283 so it belongs with the contract tests (launch 5.6), not in `cargo test`.
284
285## Safety
286
287Safe Rust only. No `unsafe`.
288
289## Test files
290
291A module's tests live in `mod tests` at the bottom of the file until the file passes
292about 1,500 lines; past that they move to a sibling `<module>_tests.rs` declared as
293
294```rust
295#[cfg(test)]
296#[path = "repo_tests.rs"]
297mod tests;
298```
299
300`#[path]` changes only where the file is read from, not the module tree: the block is
301still `module::tests`, `use super::*` still means the module under test, and no
302private item needs widening — which is why it beats a `tests/` directory (that turns
303`repo.rs` into `repo/mod.rs`) for this. The sibling sorts beside its module. Six files
304follow it as of 2026-09-08; `web/pulls.rs` and `repository/in_memory.rs` are over the
305threshold and do not yet.