| 1 | # Architecture |
| 2 | |
| 3 | ## Layers |
| 4 | |
| 5 | DDD + clean architecture. Dependencies point inward. The domain knows nothing about |
| 6 | HTTP, SQL, git, or Topcoat. |
| 7 | |
| 8 | ``` |
| 9 | web / 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 | |
| 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 |
| 22 | any side effect. Not in the handler, not in the adapter. The previous attempt got this |
| 23 | right and it paid off — `serve_push` could enforce `Role::Owner` in one place |
| 24 | regardless 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 |
| 30 | repository use case starts with — `visible_repo` (the one visibility rule: public, or a |
| 31 | member 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 |
| 33 | see 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 |
| 35 | three 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 |
| 38 | about an `Actor` — a person with a session. The other caller is a *machine*: a control |
| 39 | plane holding `STEID_OPERATOR_TOKEN`, with no session and no user to be. That one is |
| 40 | authenticated by `web::operator::operator_authorized`, a constant-time bearer-token |
| 41 | comparison living in the web layer because a transport credential is a transport |
| 42 | concern, and it grants exactly the operator routes — never a repository, never a user's |
| 43 | data. A page never decides either question inline: it asks `context::owned_repo`, |
| 44 | `context::owned_profile` or `context::instance_owner`. |
| 45 | |
| 46 | The same module holds **`Stores`**, the bundle of the three ports a repository is |
| 47 | reached through — organisations, memberships, repositories. Fifty-six use cases needed |
| 48 | exactly those three together, so they travel as one borrowed value rather than three |
| 49 | parameters. Ports only some use cases need (issues, labels, pulls, users, git) stay |
| 50 | separate arguments; a bundle that grows to hold everything is a service locator. |
| 51 | |
| 52 | That is not tidiness. Milestone 7's graded permissions — a collaborator who may comment |
| 53 | but not merge — are a change to these predicates and, where a permission has to be |
| 54 | named, 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 | |
| 59 | These come from two prior attempts. They earned their place. |
| 60 | |
| 61 | ### Typed IDs — never raw strings for entity references |
| 62 | |
| 63 | ```rust |
| 64 | |
| 65 | fn get_member(&self, org_id: &OrgId, user_id: &UserId) -> ... |
| 66 | |
| 67 | |
| 68 | fn 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 |
| 76 | out of the database, which were validated on the way in. Infrastructure repos should |
| 77 | always use `from_trusted()` — re-validating DB rows means a validation-rule change |
| 78 | turns old rows unreadable. |
| 79 | |
| 80 | ### `from_str` returns `Result`, never `Option` |
| 81 | |
| 82 | A silently-defaulted enum parse is a bug that surfaces days later as wrong |
| 83 | permissions. Applies to `Role`, `Visibility`, `ImportState`, `IssueState`. |
| 84 | |
| 85 | ### Every repository port gets two implementations |
| 86 | |
| 87 | An in-memory one and a SQLite one. The in-memory one is what makes use cases testable |
| 88 | without a database — attempt #2 reached 60 tests this way and they ran fast enough to |
| 89 | stay in the loop. |
| 90 | |
| 91 | ### Ports live where they're consumed |
| 92 | |
| 93 | Repository traits in `domain/repository/`. Service ports the application needs |
| 94 | (`GitStorage`, `GitProtocolServer`, `PasswordHasher`) in `application/port.rs`. Use |
| 95 | cases take `&impl Port`, not a boxed trait object. |
| 96 | |
| 97 | Git is deliberately several narrow ports rather than one service, and how the binary is |
| 98 | actually 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 |
| 102 | implementations 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 |
| 107 | first line of the handler — before the ownership guard and before the use case. The |
| 108 | token 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 | |
| 111 | A `#[route]` handler returns a response rather than a view and so cannot reach the 403 |
| 112 | page the root layout renders; it uses `csrf_verified_response` instead, in the `if let |
| 113 | Some(response) = …` shape `throttled` established. |
| 114 | |
| 115 | A 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 |
| 117 | that does neither — which is the only thing making a hand-written check in thirty-one |
| 118 | handlers safe. |
| 119 | |
| 120 | ## DB-plus-filesystem writes |
| 121 | |
| 122 | Creating 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 | |
| 125 | Attempt #1 used a **compensating transaction** — create on disk first, and if the DB |
| 126 | insert fails, delete the directory: |
| 127 | |
| 128 | ```rust |
| 129 | let repo = self.repository.create(&id).await?; |
| 130 | if let Err(e) = self.repo_record_repo.create(&record).await { |
| 131 | let _ = self.repository.delete(&id).await; |
| 132 | return Err(e.into()); |
| 133 | } |
| 134 | ``` |
| 135 | |
| 136 | That leaks an orphaned directory if the process dies between the two calls, and a |
| 137 | directory without a row is worse than invisible — it silently blocks re-creating a |
| 138 | repository by that name. |
| 139 | |
| 140 | **The durable fix is written.** `application/reconcile.rs` is the boot sweep: it lists |
| 141 | the 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 |
| 143 | there. It runs beside the interrupted-import and reflog sweeps, and for the same |
| 144 | reason — nothing has been spawned yet, so a directory with no row is genuinely finished |
| 145 | rather than half-written by a task still running. It covers all three ways to get one: |
| 146 | a create that died before the insert, a rename that died after the directory moved, and |
| 147 | an import whose repository was deleted mid-clone. |
| 148 | |
| 149 | The compensating transaction stays as the fast path. The sweep is what makes it safe to |
| 150 | rely on, and it is a sweep rather than pending rows because a pending row still needs |
| 151 | somebody to come along and resolve it. |
| 152 | |
| 153 | ## Data access |
| 154 | |
| 155 | Topcoat's grain is async components that query the database directly and check |
| 156 | permissions inline. State comes from `app_context::<T>(cx)`, and the framework's own |
| 157 | guidance is to "prefer composable `cx: &Cx` functions over middleware/extractors for |
| 158 | auth and request-scoped data." |
| 159 | |
| 160 | That reads as a view layer reaching for the data layer, which the rules above forbid. |
| 161 | It was a genuinely hard question while SSH was the git transport, because an SSH |
| 162 | channel handler has no `Cx` — so authorization expressed in a component was invisible |
| 163 | to `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 |
| 166 | caller now has a `Cx`, so nothing *forces* a transport-neutral use case layer. The |
| 167 | position 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 |
| 177 | POST handlers going through a use case that takes an `Actor`** — not one writes through |
| 178 | a repository port directly — and `infrastructure/web/` importing `domain::repository` |
| 179 | nowhere. The rule held across four waves of parallel agents, which is the evidence it |
| 180 | is a workable line rather than an aspiration. |
| 181 | |
| 182 | One thing the original position expected did *not* happen: `#[memoize]` was named as |
| 183 | what would make per-component fetching pay, and **nothing in the tree uses it**. Reads |
| 184 | are cheap enough, or already hoisted into a use case that returns a whole view struct, |
| 185 | that no page has needed to deduplicate a query. Treat it as available, not as load- |
| 186 | bearing; the earlier text credited it with earning its keep, and it had not been asked |
| 187 | to. |
| 188 | |
| 189 | The tell for when a read has outgrown that: if it starts deciding whether the viewer is |
| 190 | allowed to see something, it isn't a read any more — move it. |
| 191 | |
| 192 | Revisit if `/api` and the pages start duplicating query logic. That's the signal the |
| 193 | line is in the wrong place. |
| 194 | |
| 195 | ## Migrations |
| 196 | |
| 197 | **A shipped migration is immutable, comments included.** `sqlx::migrate!` checksums the |
| 198 | whole file and refuses to boot when an applied one has changed; a comment edit in a |
| 199 | shipped 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 |
| 202 | binary carries its schema (`sqlx::migrate!` runs on boot, see `infrastructure/ |
| 203 | database.rs`), so a migration lands the instant a new build starts — while the old |
| 204 | build may still be serving from the same file. |
| 205 | |
| 206 | Two 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 | |
| 216 | So: **expand, deploy, contract.** |
| 217 | |
| 218 | |
| 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 | |
| 224 | Forbidden 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 | |
| 235 | Contracting is not forbidden, only deferred: it is a migration in the *next* release, |
| 236 | written when that release is cut. `plans/releases.md` records which migrations each |
| 237 | release shipped, so "what the previous release's binary reads" is a fact rather than a |
| 238 | guess — check it before writing a contracting migration. |
| 239 | |
| 240 | The 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 | |
| 257 | Safe Rust only. No `unsafe`. |
| 258 | |
| 259 | ## Test files |
| 260 | |
| 261 | A module's tests live in `mod tests` at the bottom of the file until the file passes |
| 262 | about 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"] |
| 267 | mod tests; |
| 268 | ``` |
| 269 | |
| 270 | `#[path]` changes only where the file is read from, not the module tree: the block is |
| 271 | still `module::tests`, `use super::*` still means the module under test, and no |
| 272 | private 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 |
| 274 | follow it as of 2026-09-08; `web/pulls.rs` and `repository/in_memory.rs` are over the |
| 275 | threshold and do not yet. |