steid

@jamesgill /

steid/plans/architecture.md
Markdown13.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## DB-plus-filesystem writes
121
122Creating a repo writes to two places that can't share a transaction: the
123`repositories` row and the bare repo on disk. Neither prior attempt fully solved this.
124
125Attempt #1 used a **compensating transaction** — create on disk first, and if the DB
126insert fails, delete the directory:
127
128```rust
129let repo = self.repository.create(&id).await?;
130if let Err(e) = self.repo_record_repo.create(&record).await {
131 let _ = self.repository.delete(&id).await; // compensate
132 return Err(e.into());
133}
134```
135
136That leaks an orphaned directory if the process dies between the two calls, and a
137directory without a row is worse than invisible — it silently blocks re-creating a
138repository by that name.
139
140**The durable fix is written.** `application/reconcile.rs` is the boot sweep: it lists
141the directories on disk, subtracts the rows, and quarantines the remainder under
142`orphaned/` rather than deleting it, so the name is freed and the objects are still
143there. It runs beside the interrupted-import and reflog sweeps, and for the same
144reason — nothing has been spawned yet, so a directory with no row is genuinely finished
145rather than half-written by a task still running. It covers all three ways to get one:
146a create that died before the insert, a rename that died after the directory moved, and
147an import whose repository was deleted mid-clone.
148
149The compensating transaction stays as the fast path. The sweep is what makes it safe to
150rely on, and it is a sweep rather than pending rows because a pending row still needs
151somebody to come along and resolve it.
152
153## Data access
154
155Topcoat's grain is async components that query the database directly and check
156permissions inline. State comes from `app_context::<T>(cx)`, and the framework's own
157guidance is to "prefer composable `cx: &Cx` functions over middleware/extractors for
158auth and request-scoped data."
159
160That reads as a view layer reaching for the data layer, which the rules above forbid.
161It was a genuinely hard question while SSH was the git transport, because an SSH
162channel handler has no `Cx` — so authorization expressed in a component was invisible
163to `serve_push`, and the two had to share something.
164
165[Decision 0001]decisions/0001-git-over-http-not-ssh.md removed that transport. Every
166caller now has a `Cx`, so nothing *forces* a transport-neutral use case layer. The
167position is therefore a choice, taken deliberately:
168
169**Writes and authorization go through use cases. Reads may go direct.**
170
171- Any mutation, and any decision about what an actor is allowed to do, lives in an
172 application use case that takes an `Actor` and the ports it needs. One place, one
173 answer, reachable from a page, an `/api` route, or a future SSH adapter alike.
174- Straightforward reads for display may query through the pool in a component.
175
176**This is what actually happened.** The 2026-09-06 organisation review found **all 34
177POST handlers going through a use case that takes an `Actor`** — not one writes through
178a repository port directly — and `infrastructure/web/` importing `domain::repository`
179nowhere. The rule held across four waves of parallel agents, which is the evidence it
180is a workable line rather than an aspiration.
181
182One thing the original position expected did *not* happen: `#[memoize]` was named as
183what would make per-component fetching pay, and **nothing in the tree uses it**. Reads
184are cheap enough, or already hoisted into a use case that returns a whole view struct,
185that no page has needed to deduplicate a query. Treat it as available, not as load-
186bearing; the earlier text credited it with earning its keep, and it had not been asked
187to.
188
189The tell for when a read has outgrown that: if it starts deciding whether the viewer is
190allowed to see something, it isn't a read any more — move it.
191
192Revisit if `/api` and the pages start duplicating query logic. That's the signal the
193line is in the wrong place.
194
195## Migrations
196
197**A shipped migration is immutable, comments included.** `sqlx::migrate!` checksums the
198whole file and refuses to boot when an applied one has changed; a comment edit in a
199shipped file stops every existing instance. A digest test pins the released set.
200
201**Every migration must be one the *previous release's* binary can run against.** The
202binary carries its schema (`sqlx::migrate!` runs on boot, see `infrastructure/
203database.rs`), so a migration lands the instant a new build starts — while the old
204build may still be serving from the same file.
205
206Two situations make that not hypothetical:
207
208- **A fleet upgrade runs unattended.** [Control-plane decision 0002]../../steid-control-plane/decisions/0002-machine-per-tenant.md
209 makes a fleet upgrade N `deploy.sh` runs against N machines nobody is watching. A
210 migration the running build cannot tolerate takes a customer's instance down between
211 the migration and the restart, with no one at the keyboard.
212- **Zero-downtime deploys, when they are built.** The plan in `current.md` runs the old
213 and new processes side by side over one SQLite file while Caddy is repointed. The new
214 one migrates on boot; the old one keeps serving. A dropped column breaks it mid-swap.
215
216So: **expand, deploy, contract.**
217
218| Phase | What it may do | When |
219|---|---|---|
220| **Expand** | `create table`; `create index`; `alter table … add column` **nullable, or with a `default`**; backfill with `update` | any release |
221| **Deploy** | ship the binary that writes the new shape and stops writing the old | the same release, or a later one |
222| **Contract** | drop the column, drop the table, rename, tighten to `not null` | **a release later**, once no deployed binary reads the old shape |
223
224Forbidden in the same release as the code that needs it, and the lexical guard in
225`database_compat_tests.rs` fails the build for each:
226
227- `drop column` — the old binary's `select *` still names it.
228- `drop table` — likewise, and a `select` against a missing table is an error, not a
229 null.
230- `rename` (table or column) — a drop and an add at once, so it is both failures.
231- `alter table … add column … not null` **without a `default`** — SQLite refuses it
232 outright on a non-empty table, and even where it succeeds the old binary's inserts
233 omit the column.
234
235Contracting is not forbidden, only deferred: it is a migration in the *next* release,
236written when that release is cut. `plans/releases.md` records which migrations each
237release shipped, so "what the previous release's binary reads" is a fact rather than a
238guess — check it before writing a contracting migration.
239
240The rule is enforced two ways, and only one of them is a real test:
241
242- **The lexical guard** reads `migrations/` at test time and rejects the four
243 statements above. It covers every migration automatically, including one added after
244 this was written. It is a grep, so it is fooled by a rebuild-the-table-and-swap done
245 in `create`/`insert`/`drop` steps — which is exactly why the rule is written down
246 here as well.
247- **The replay test** applies the previous release's migration set to a fresh database
248 and runs the *current* binary's reads against it. That is the honest half: proving
249 the *old* binary reads the *new* schema would need the old binary linked in, and it
250 is not. It still earns its place — `steid backup` opens the pool without migrating
251 (see `database::open`), so a new binary genuinely does read an old schema — but the
252 forward direction the rule is about is covered by the guard and by review, not by a
253 test.
254
255## Safety
256
257Safe Rust only. No `unsafe`.
258
259## Test files
260
261A module's tests live in `mod tests` at the bottom of the file until the file passes
262about 1,500 lines; past that they move to a sibling `<module>_tests.rs` declared as
263
264```rust
265#[cfg(test)]
266#[path = "repo_tests.rs"]
267mod tests;
268```
269
270`#[path]` changes only where the file is read from, not the module tree: the block is
271still `module::tests`, `use super::*` still means the module under test, and no
272private item needs widening — which is why it beats a `tests/` directory (that turns
273`repo.rs` into `repo/mod.rs`) for this. The sibling sorts beside its module. Six files
274follow it as of 2026-09-08; `web/pulls.rs` and `repository/in_memory.rs` are over the
275threshold and do not yet.