cratefield_core/module.rs
1//! The module contract (architecture section 4). A module is a crate that
2//! contributes one router under `/v1/<name>`, its migrations, its events and
3//! its scheduled work — and sees nothing but ports.
4
5use crate::config::{Config, ConfigError};
6use crate::events::{AnyError, EventBus, EventHandler, EventName};
7use crate::ports::{Port, Ports};
8use crate::scheduled::ScheduledBudget;
9use crate::surface::Surface;
10use crate::template::TemplateRegistry;
11use crate::venture::Venture;
12use std::sync::Arc;
13
14pub use futures_core::future::BoxFuture;
15
16/// Contract version shared by core and every module. `Harness::build`
17/// rejects modules whose `harness_api` differs. Bumped only on breaking
18/// contract changes; `cratefield-core`'s major follows it.
19pub const HARNESS_API: u32 = 1;
20
21/// The message `Harness::build` and `fz doctor` report for a module whose
22/// [`Module::harness_api`] differs from core's: it names the module, the
23/// module crate's version, the API it targets, and the `cratefield-core`
24/// crate with its version and API (issue #17).
25#[must_use]
26pub fn harness_api_mismatch(module: &dyn Module) -> String {
27 format!(
28 "module `{name}` v{version} targets harness API {api}, but {core} v{core_version} \
29 provides harness API {harness_api}: rebuild `{name}` against this core — the supported \
30 ranges are in docs/COMPATIBILITY.md",
31 name = module.name(),
32 version = module.version(),
33 api = module.harness_api(),
34 core = env!("CARGO_PKG_NAME"),
35 core_version = env!("CARGO_PKG_VERSION"),
36 harness_api = HARNESS_API,
37 )
38}
39
40/// One migration step, embedded with `include_str!` from
41/// `crates/<module>/migrations/<dialect>/NNNN_name.sql` (issue #8).
42///
43/// `#[non_exhaustive]` plus [`SqlMigration::new`] is the same fix `Message`
44/// got (issue #189): a module crate cannot build this by literal, so adding
45/// a field here stops being a breaking change across the 70+ migration sets
46/// in the workspace (issue #255).
47#[non_exhaustive]
48#[derive(Debug, Clone)]
49pub struct SqlMigration {
50 /// Sortable id: `0001`, `0002`, ... — zero-padded so lexical order is
51 /// apply order.
52 pub id: &'static str,
53 /// Short slug from the file name (`0001_init.sql` -> `init`), used in
54 /// the wrangler-facing collected file names.
55 pub name: &'static str,
56 pub sql: &'static str,
57 /// Whether the migration and its tracking row commit atomically
58 /// (the default). `false` marks the statements Postgres refuses inside
59 /// a transaction block (`CREATE INDEX CONCURRENTLY`): they run alone,
60 /// the tracking row follows, and the SQL must be idempotent —
61 /// RECONCILIATION.md §4.
62 pub transactional: bool,
63}
64
65impl SqlMigration {
66 /// The ordinary migration: the four-digit id, the slug from the file
67 /// name, the embedded SQL, transactional. `const` because every
68 /// migration set is a `const` array checked by
69 /// [`assert_migration_set`], itself a `const fn`.
70 #[must_use]
71 pub const fn new(id: &'static str, name: &'static str, sql: &'static str) -> Self {
72 Self {
73 id,
74 name,
75 sql,
76 transactional: true,
77 }
78 }
79
80 /// Marks the migration as running outside a transaction: for statements
81 /// Postgres refuses inside one (`CREATE INDEX CONCURRENTLY`).
82 #[must_use]
83 pub const fn non_transactional(mut self) -> Self {
84 self.transactional = false;
85 self
86 }
87}
88
89/// Rejects a malformed migration set **at compile time**.
90///
91/// The array a module hands to [`Migrations`] is the apply order, and
92/// nothing checked that it agreed with the ids in it. `auth-core` defines
93/// its six migration constants in the file in the order 1, 2, 5, 6, 4, 3
94/// and lists them in the arrays correctly; that is one careless edit away
95/// from applying `0005` before `0003`, against a database that would
96/// record both as applied and never notice (issue #27).
97///
98/// Call it in a `const` item beside the set, where a failure is a build
99/// error rather than something a boot discovers:
100///
101/// ```
102/// # use cratefield_core::{SqlMigration, assert_migration_set};
103/// const MIGRATIONS: [SqlMigration; 2] = [
104/// SqlMigration::new("0001", "init", ""),
105/// SqlMigration::new("0002", "next", ""),
106/// ];
107/// const _: () = assert_migration_set(&MIGRATIONS);
108/// ```
109///
110/// A gap does not compile:
111///
112/// ```compile_fail
113/// # use cratefield_core::{SqlMigration, assert_migration_set};
114/// const MIGRATIONS: [SqlMigration; 2] = [
115/// SqlMigration::new("0001", "init", ""),
116/// SqlMigration::new("0003", "skipped", ""),
117/// ];
118/// const _: () = assert_migration_set(&MIGRATIONS);
119/// ```
120///
121/// Nor a duplicate, nor an id out of order, nor one that is not four
122/// digits:
123///
124/// ```compile_fail
125/// # use cratefield_core::{SqlMigration, assert_migration_set};
126/// const MIGRATIONS: [SqlMigration; 2] = [
127/// SqlMigration::new("0002", "second", ""),
128/// SqlMigration::new("0001", "first", ""),
129/// ];
130/// const _: () = assert_migration_set(&MIGRATIONS);
131/// ```
132///
133/// ```compile_fail
134/// # use cratefield_core::{SqlMigration, assert_migration_set};
135/// const MIGRATIONS: [SqlMigration; 1] =
136/// [SqlMigration::new("1", "unpadded", "")];
137/// const _: () = assert_migration_set(&MIGRATIONS);
138/// ```
139///
140/// # Panics
141///
142/// At compile time when called in a `const` item, at run time otherwise.
143/// The message is a fixed string: `panic!` in a `const fn` cannot format,
144/// so the offending id is not in it. The compile error points at the
145/// `const` item, which names the crate and the line — enough to find the
146/// set, which is the whole array anyway.
147pub const fn assert_migration_set(set: &[SqlMigration]) {
148 let mut index = 0;
149 while index < set.len() {
150 let id = set[index].id.as_bytes();
151 assert!(
152 id.len() == 4,
153 "a migration id is four digits, zero-padded: `0001`, not `1`"
154 );
155 let mut digit = 0;
156 while digit < 4 {
157 assert!(
158 id[digit] >= b'0' && id[digit] <= b'9',
159 "a migration id is four digits, zero-padded: `0001`, not `init`"
160 );
161 digit += 1;
162 }
163 let value = (id[0] - b'0') as usize * 1000
164 + (id[1] - b'0') as usize * 100
165 + (id[2] - b'0') as usize * 10
166 + (id[3] - b'0') as usize;
167 assert!(
168 value == index + 1,
169 "migration ids run contiguously from 0001 in apply order: a gap, a duplicate, or an entry listed out of order"
170 );
171 index += 1;
172 }
173}
174
175/// The sha256 of a migration's SQL, lowercase hex. Recorded in
176/// `harness_migrations` when the migration is applied, so a later run
177/// can tell "already applied" from "applied, then edited" — the rule
178/// forward-only migrations rest on, enforced by the database rather
179/// than by a lockfile in one repository (issues #28, #34).
180///
181/// The lockfile's hash covers the collected *file*; this covers the
182/// embedded SQL. They answer different questions and are not compared.
183#[must_use]
184pub fn migration_checksum(sql: &str) -> String {
185 use sha2::{Digest, Sha256};
186 let digest = Sha256::digest(sql.as_bytes());
187 let mut hex = String::with_capacity(64);
188 for byte in digest {
189 use std::fmt::Write as _;
190 let _ = write!(hex, "{byte:02x}");
191 }
192 hex
193}
194
195/// True when the SQL carries an idempotence guard, so re-running it
196/// after a crash is safe. Required of every migration marked
197/// `transactional: false` (RECONCILIATION.md §4).
198#[must_use]
199pub fn is_idempotent_sql(sql: &str) -> bool {
200 // Comments are stripped first. A guard that reads the whole file
201 // accepts `-- we could use IF NOT EXISTS here but did not` above SQL
202 // that has no guard at all — which is precisely the migration this
203 // check exists to refuse, waved through by a sentence about it.
204 let sql = strip_sql_comments(sql).to_ascii_lowercase();
205 sql.contains("if not exists") || sql.contains("if exists") || sql.contains("or replace")
206}
207
208/// SQL with `--` line comments and `/* */` blocks removed.
209///
210/// Not a parser: it does not know that a `--` inside a string literal is
211/// not a comment. That direction is safe here — it can only remove text
212/// the guard would have read, so the guard refuses rather than accepts.
213fn strip_sql_comments(sql: &str) -> String {
214 let mut out = String::with_capacity(sql.len());
215 let mut rest = sql;
216 while let Some(at) = rest.find("--").into_iter().chain(rest.find("/*")).min() {
217 out.push_str(&rest[..at]);
218 let tail = &rest[at..];
219 if tail.starts_with("--") {
220 rest = tail.find('\n').map_or("", |end| &tail[end..]);
221 } else {
222 rest = tail.find("*/").map_or("", |end| &tail[end + 2..]);
223 }
224 }
225 out.push_str(rest);
226 out
227}
228
229/// The message a non-transactional migration without an idempotence
230/// guard gets. Shared so both engines say the same thing.
231#[must_use]
232pub fn migration_missing_guard(key: &str) -> String {
233 format!(
234 "migration `{key}` is marked transactional: false, so it runs outside a transaction and \
235 must be idempotent: give the SQL an `IF NOT EXISTS` or `OR REPLACE` guard \
236 (RECONCILIATION.md, section 4)"
237 )
238}
239
240/// The message a migration whose recorded checksum no longer matches
241/// gets. Shared so both engines say the same thing.
242#[must_use]
243pub fn migration_edited(key: &str, recorded: &str, found: &str) -> String {
244 format!(
245 "migration `{key}` was already applied to this database with different SQL \
246 (recorded sha256 {}…, embedded {}…). Applied migrations are never edited: \
247 revert the change and write a new migration instead \
248 (docs/MODULE-AUTHORING.md, step 3)",
249 &recorded[..recorded.len().min(12)],
250 &found[..found.len().min(12)]
251 )
252}
253
254/// The module's migrations, per dialect. `postgres` differs from `sqlite`
255/// only where the SQL truly differs (ADR 0004).
256#[derive(Debug, Clone)]
257pub struct Migrations {
258 pub sqlite: &'static [SqlMigration],
259 pub postgres: &'static [SqlMigration],
260}
261
262impl Migrations {
263 pub const EMPTY: Migrations = Migrations {
264 sqlite: &[],
265 postgres: &[],
266 };
267
268 pub const fn sqlite(migrations: &'static [SqlMigration]) -> Self {
269 Migrations {
270 sqlite: migrations,
271 postgres: &[],
272 }
273 }
274}
275
276impl Default for Migrations {
277 fn default() -> Self {
278 Self::EMPTY
279 }
280}
281
282/// Everything a module's router needs: its declared ports, the typed
283/// config, the bus, the templates and the venture identity.
284pub struct ModuleContext {
285 /// Only the ports the module declared in `requires()`/`optional()`.
286 pub ports: Ports,
287 /// Full config; module keys are prefixed (`EMAIL_SIGNUP_CONFIRM_TTL_DAYS`).
288 pub config: Arc<dyn Config>,
289 pub events: EventBus,
290 pub templates: Arc<TemplateRegistry>,
291 pub venture: Arc<Venture>,
292 /// Whether an operator has recorded an explicit acceptance that this
293 /// deployment serves guarded routes it cannot fully protect
294 /// (`HARNESS_ALLOW_UNPROTECTED_WRITES`, issue #143).
295 ///
296 /// It exists because the acceptance has to mean the same thing at
297 /// both layers. The boot gate honours it and serves; if the
298 /// per-request gate did not, the deployment would refuse every write
299 /// anyway — the same outage, with a different status code. A module
300 /// enforcing an abuse control passes this to
301 /// [`verify_human_form`](crate::route_policy::verify_human_form)
302 /// rather than deciding from the environment alone.
303 pub unprotected_writes_accepted: bool,
304 /// Every personal-data declaration in this composition, composed once at
305 /// build (issue: privacy module). A module reads it to export or erase a
306 /// subject's data without knowing which other modules the venture chose;
307 /// most modules ignore it, which costs them an `Arc` clone per request.
308 pub personal_data: std::sync::Arc<crate::PersonalDataCatalog>,
309 /// `true` when the venture mounted a UI renderer (ADR 0010). A module
310 /// then defaults its landing redirects (confirmed, expired,
311 /// unsubscribed, status) to `<api base>/ui/<module>/<action>/<page>`
312 /// instead of pages the venture site has to provide.
313 pub ui_mounted: bool,
314 /// The budget for the current scheduled invocation (issue #537):
315 /// cooperative, so a module checks it around each unit of work and
316 /// stops — never cancelled — when it has run out. Split across the
317 /// modules by the runtime with each module's unspent share rolling
318 /// forward. **Unbounded outside `scheduled`**: request handlers can
319 /// read it and never see a limit that does not apply to them.
320 pub scheduled: Arc<ScheduledBudget>,
321}
322
323/// A Factory Zero module. Object-safe; composed as `Arc<dyn Module>`.
324///
325/// Handlers get the request scope as an axum extractor:
326/// `async fn join(scope: Scope, State(ctx): State<Arc<ModuleContext>>, ...)`.
327/// There is no ambient "current request" (ADR 0007).
328pub trait Module: Send + Sync + 'static {
329 /// Kebab-case name; mounted at `/v1/<name>`.
330 fn name(&self) -> &'static str;
331 /// `env!("CARGO_PKG_VERSION")`, surfaced by `/__health`.
332 fn version(&self) -> &'static str;
333 /// Contract version, checked by `Harness::build`.
334 fn harness_api(&self) -> u32 {
335 HARNESS_API
336 }
337 /// Ports the module cannot run without; missing = build error.
338 fn requires(&self) -> &'static [Port];
339 /// Ports the module uses when present.
340 fn optional(&self) -> &'static [Port] {
341 &[]
342 }
343 /// Modules this one's schema sits on top of, by name.
344 ///
345 /// A partial order, not a load order for routes: it exists so
346 /// migrations apply in an order where a foreign key can point at a
347 /// table another module owns (RECONCILIATION.md §2). Naming a module
348 /// the venture did not compose is a build error, and so is a cycle —
349 /// both at `HarnessBuilder::build`, never at boot, because a boot
350 /// error is one a deployment discovers in production.
351 ///
352 /// Declaring nothing is the common case and costs nothing: with no
353 /// dependencies anywhere the resolved order is composition order,
354 /// unchanged.
355 fn depends_on(&self) -> &'static [&'static str] {
356 &[]
357 }
358 /// Table names this module owns; duplicates across modules are a build
359 /// error.
360 fn tables(&self) -> &'static [&'static str] {
361 &[]
362 }
363 /// What this module holds about a person, per table.
364 ///
365 /// Read by `cratefield-module-privacy` to export a subject's data, to
366 /// erase it, and to publish the "what is stored" table. Declaring it here
367 /// rather than in the privacy module is what makes that module reusable:
368 /// it never names a venture's tables, so a schema change cannot leave it
369 /// describing something that no longer exists.
370 ///
371 /// Validated at [`HarnessBuilder::build`]: a table this module does not
372 /// own is an error, and so is a declaration that cannot mean anything —
373 /// an `Anonymise` naming no columns, a `Retain` with no reason, a
374 /// published description left blank. See [`PersonalDataSet::none`] for a
375 /// table that legitimately holds nothing personal, which says so rather
376 /// than staying silent.
377 ///
378 /// Defaulting to empty keeps every existing module compiling unchanged,
379 /// and a module with no tables has nothing to say. A module that **owns**
380 /// tables and declares nothing is a different thing, and since issue #244
381 /// it fails [`cratefield_testing::conformance`] rather than the build:
382 /// see [`undeclared_tables`](crate::undeclared_tables) for why the kit is
383 /// the place that refuses it and a running deployment is not.
384 ///
385 /// [`cratefield_testing::conformance`]: https://docs.rs/cratefield-testing
386 ///
387 /// [`HarnessBuilder::build`]: crate::HarnessBuilder::build
388 /// [`PersonalDataSet::none`]: crate::PersonalDataSet::none
389 fn personal_data(&self) -> &'static [crate::PersonalDataSet] {
390 &[]
391 }
392 /// Event names this module emits (`"<module>.<event>"`), listed by
393 /// `/__health`.
394 fn emits(&self) -> &'static [&'static str] {
395 &[]
396 }
397 /// Whether the module has public write endpoints.
398 ///
399 /// **Advisory since issue #133.** The enforcement point is each
400 /// route's [`RoutePolicy`] on the declared surface, collected by
401 /// [`WriteGuards::collect`] and gated at `HarnessBuilder::build`.
402 /// A module that writes publicly but declares **no** policy on any
403 /// action counts as a [`HumanForm`] writer (the conservative
404 /// fallback for pre-surface modules); declaring an explicit
405 /// `Open`/`Signature` policy on every action opts out of the
406 /// fallback.
407 ///
408 /// [`RoutePolicy`]: crate::route_policy::RoutePolicy
409 /// [`WriteGuards::collect`]: crate::route_policy::WriteGuards::collect
410 /// [`HumanForm`]: crate::route_policy::RoutePolicy::HumanForm
411 fn public_writes(&self) -> bool {
412 false
413 }
414 /// What actually protects those public writes, for a module with no
415 /// ADR 0010 surface to hang a per-action [`RoutePolicy`] on
416 /// (issue #143).
417 ///
418 /// Consulted **only** when [`public_writes`] is true and the surface
419 /// declares no guarded action, so a module with a surface is
420 /// unaffected and the conservative default is unchanged: say nothing
421 /// and you are still a [`HumanForm`] writer. The auth login methods
422 /// are the reason it exists — they are public writers whose proof is
423 /// a single-use challenge or a signed link, never a CAPTCHA widget,
424 /// and before this they could only be filed under a gate they can
425 /// never satisfy.
426 ///
427 /// [`public_writes`]: Module::public_writes
428 /// [`RoutePolicy`]: crate::route_policy::RoutePolicy
429 /// [`HumanForm`]: crate::route_policy::RoutePolicy::HumanForm
430 fn public_write_policy(&self) -> crate::route_policy::RoutePolicy {
431 crate::route_policy::RoutePolicy::HumanForm
432 }
433 /// Which verifier proves this module's [`RoutePolicy::Signature`]
434 /// deliveries (issue #533): how a webhook handler checks a machine
435 /// signature before acting.
436 ///
437 /// This is the **default** for the module's signature routes. A route
438 /// that declares its own verifier — `.verification(..)` on the
439 /// [`Action`](crate::surface::Action) (issue #595) — overrides it, so
440 /// one module can verify a Stripe webhook through `Payments` and a
441 /// `RevenueCat` webhook with its own HMAC secret.
442 ///
443 /// Consulted only when the module actually has signature-guarded
444 /// routes — [`WriteGuards::collect`] resolves each route's verifier
445 /// (its own, else this) and the production gate demands exactly what
446 /// was declared:
447 ///
448 /// - [`SignatureVerification::Payments`](crate::route_policy::SignatureVerification::Payments)
449 /// (the default): the handler
450 /// proves deliveries with `Payments::verify_webhook` plus the Inbox
451 /// dedup ledger, and production requires an effective `Payments`
452 /// port. Every module built before this existed gets this, unchanged.
453 /// - [`SignatureVerification::Hmac`](crate::route_policy::SignatureVerification::Hmac):
454 /// the handler proves deliveries
455 /// with the core `webhook_signature` scheme (Svix, Stripe-style, or
456 /// a provider-specific layout), keyed by the module-scoped config
457 /// secret named here — a [`ModuleConfig`] suffix, so `"WEBHOOK_SECRET"`
458 /// on module `pos` is read from `POS_WEBHOOK_SECRET`. Production
459 /// requires that key and no `Payments` port.
460 ///
461 /// [`RoutePolicy::Signature`]: crate::route_policy::RoutePolicy::Signature
462 /// [`WriteGuards::collect`]: crate::route_policy::WriteGuards::collect
463 /// [`ModuleConfig`]: crate::config::ModuleConfig
464 fn signature_verification(&self) -> crate::route_policy::SignatureVerification {
465 crate::route_policy::SignatureVerification::Payments
466 }
467 /// The module's migrations, embedded per dialect.
468 fn migrations(&self) -> Migrations;
469 /// Rejects invalid configuration: missing required keys or malformed
470 /// values, reported together with the module name.
471 ///
472 /// **When it runs.** The conformance kit calls it, and a module's own
473 /// tests should. It cannot run at `Harness::build` or in `fz doctor`,
474 /// because neither has the deploy config — the values live on the runtime
475 /// `Env` and only exist per request. The Cloudflare runtime therefore runs
476 /// it **once at cold start** and logs any failure loudly (`console_error!`,
477 /// so it reaches Workers Logs); it does not fail the boot, so a
478 /// misconfigured module still degrades per request (issue #101) rather
479 /// than taking the whole Worker down. Turning that into a hard boot
480 /// failure is a deployment decision for an ADR.
481 ///
482 /// # Errors
483 ///
484 /// `Err` listing every invalid or missing key for this module.
485 fn validate_config(&self, cfg: &dyn Config) -> Result<(), ConfigError>;
486 /// The largest request body any route of this module accepts, so a
487 /// runtime can refuse an oversize body **before** buffering it
488 /// (issue #440).
489 ///
490 /// This is a coarse per-module ceiling, not a per-route limit. A
491 /// runtime with a fixed memory budget — a Workers isolate, say — reads
492 /// it through [`Harness::max_body_bytes`] when a request arrives and
493 /// refuses everything above it at the door, because the precise
494 /// enforcement, axum's `DefaultBodyLimit` inside [`Module::router`],
495 /// only fires once the body is already resident in memory. It must
496 /// never return less than the harness-wide [`MAX_BODY_BYTES`]: the
497 /// runtime guard sits **in front of** the router, and a module that
498 /// tightened it would 413 requests the router itself would have
499 /// accepted. Raising it is legitimate — LinkedIn's image upload does —
500 /// but the route that justifies the raise keeps its own
501 /// `DefaultBodyLimit`, which stays the precise per-route enforcer.
502 ///
503 /// `cfg` is the live deployment config, so a module that moves a cap
504 /// from configuration must read it here too: if an operator raises
505 /// `MAX_IMAGE_BYTES` above the compiled default, the runtime guard must
506 /// not refuse a body the route would have accepted.
507 ///
508 /// Default: [`MAX_BODY_BYTES`], so a module that says nothing changes
509 /// nothing.
510 ///
511 /// [`Harness::max_body_bytes`]: crate::Harness::max_body_bytes
512 /// [`MAX_BODY_BYTES`]: crate::http::MAX_BODY_BYTES
513 fn max_body_bytes(&self, _cfg: &dyn Config) -> usize {
514 crate::http::MAX_BODY_BYTES
515 }
516
517 /// Routes this module serves in **streaming** mode (issue #585), each
518 /// with its own [`StreamRoute::max_bytes`] ceiling. Opt-in: the default
519 /// is empty, and every existing route keeps the buffered behaviour it
520 /// always had.
521 ///
522 /// On a declared route the router reads the body as a stream instead of
523 /// buffering it: the handler extracts a [`RequestStream`], the route's
524 /// `max_bytes` replaces [`Module::max_body_bytes`] for the declared
525 /// `content-length` pre-check, and the handler may answer with a
526 /// [`ResponseStream`]. The paths are relative to the module's
527 /// `/v1/<name>` mount and use axum's pattern syntax (`/upload`,
528 /// `/files/{id}`, `/files/{*rest}`). A `(method, path)` that names no
529 /// declared route is untouched.
530 ///
531 /// [`RequestStream`]: crate::RequestStream
532 /// [`ResponseStream`]: crate::ResponseStream
533 /// [`StreamRoute::max_bytes`]: crate::StreamRoute::max_bytes
534 fn streaming_routes(&self) -> &'static [crate::StreamRoute] {
535 &[]
536 }
537
538 /// Problems the module can find in **itself**, with no configuration
539 /// and no environment: its own embedded data, checked against its own
540 /// declarations.
541 ///
542 /// This is the half of [`Module::validate_config`] that `fz doctor`
543 /// can actually run. The doctor has no deploy config — those values
544 /// live on the runtime `Env` and exist only per request — so it cannot
545 /// ask a module whether its *deployment* is valid. It can ask whether
546 /// what the module compiled in is coherent, and that answer is the
547 /// same on a laptop, in CI and in production.
548 ///
549 /// The notifications module answers with every translation its catalog
550 /// is missing (issue #190), so a translation gap is a pull request
551 /// rather than a person reading a message id on a lock screen.
552 ///
553 /// Each string is one problem, already naming the module. Return
554 /// **identifiers**, never values: this is printed by a CLI and copied
555 /// into issues, so nothing read from the environment, a recipient or a
556 /// URL may appear in one. Default: nothing, so no existing module
557 /// changes.
558 fn self_check(&self) -> Vec<String> {
559 Vec::new()
560 }
561 /// The module's router, nested under `/v1/<name>`.
562 fn router(&self, ctx: ModuleContext) -> axum::Router;
563 /// Routes this module serves at the root under `/.well-known`, for
564 /// spec-mandated discovery documents (OIDC `openid-configuration`,
565 /// `jwks.json`) that must live outside `/v1` (issue #46). Paths are
566 /// relative to the prefix: register `/jwks.json`, not
567 /// `/.well-known/jwks.json`.
568 ///
569 /// At most one module may provide one: discovery URLs are a singleton
570 /// namespace, so `Harness::build` fails (naming every provider) when
571 /// two modules return a router here. `None` by default.
572 fn well_known(&self) -> Option<axum::Router> {
573 None
574 }
575 /// The module's UI surface (ADR 0010): the actions a renderer may
576 /// offer and the views that compose them. Input schemas come from
577 /// the handler's own body types (`Action::input::<Body>()`), so the
578 /// declaration cannot drift from the route. `Harness::build`
579 /// validates it; `GET /__surface` serves the composition. Default:
580 /// nothing, and a module that declares nothing renders nothing.
581 fn surface(&self) -> Surface {
582 Surface::none()
583 }
584 /// Handlers for events other modules emit; registered at
585 /// `Harness::build`.
586 fn events(&self) -> Vec<(EventName, EventHandler)> {
587 Vec::new()
588 }
589 /// Scheduled work (`cron` is the trigger expression). Default: none.
590 fn scheduled<'a>(
591 &'a self,
592 ctx: &'a ModuleContext,
593 cron: &'a str,
594 ) -> BoxFuture<'a, Result<(), AnyError>> {
595 let _ = (ctx, cron);
596 Box::pin(async { Ok(()) })
597 }
598}
599
600#[cfg(test)]
601mod reconciliation_guard_tests {
602 use super::{SqlMigration, is_idempotent_sql, migration_missing_guard};
603
604 #[test]
605 fn a_migration_is_transactional_unless_marked_otherwise() {
606 // The flag exists so RECONCILIATION.md §4 has something to read;
607 // every module that does not say a word keeps the atomic
608 // behaviour both runners have always had.
609 let migration = SqlMigration::new("0001", "init", "CREATE TABLE t (id TEXT PRIMARY KEY);");
610 assert!(migration.transactional);
611 assert!(!migration.clone().non_transactional().transactional);
612 }
613
614 #[test]
615 fn guarded_ddl_is_idempotent_plain_ddl_is_not() {
616 assert!(is_idempotent_sql(
617 "CREATE INDEX CONCURRENTLY IF NOT EXISTS i ON t (c)"
618 ));
619 assert!(is_idempotent_sql(
620 "CREATE OR REPLACE FUNCTION f() RETURNS void AS $$ BEGIN END $$;"
621 ));
622 assert!(is_idempotent_sql("DROP INDEX CONCURRENTLY IF EXISTS i"));
623 assert!(!is_idempotent_sql("CREATE INDEX CONCURRENTLY i ON t (c)"));
624 // Case-insensitive: SQL is written in any case.
625 assert!(is_idempotent_sql("create index if not exists i on t (c)"));
626
627 // A sentence about the guard is not the guard. Reading the whole
628 // file waves through exactly the migration this refuses: one that
629 // runs outside a transaction, is re-run after a crash, and fails.
630 assert!(!is_idempotent_sql(
631 "-- we could use IF NOT EXISTS here but did not\nCREATE INDEX CONCURRENTLY i ON t (c)"
632 ));
633 assert!(!is_idempotent_sql(
634 "/* IF NOT EXISTS is unavailable on this engine */ CREATE INDEX i ON t (c)"
635 ));
636 // And a real guard after a comment is still found.
637 assert!(is_idempotent_sql(
638 "-- concurrently, so it must be idempotent\nCREATE INDEX CONCURRENTLY IF NOT EXISTS i ON t (c)"
639 ));
640 }
641
642 #[test]
643 fn the_missing_guard_message_names_the_migration_and_the_rule() {
644 let message = migration_missing_guard("waitlist/0005");
645 assert!(message.contains("waitlist/0005"), "{message}");
646 assert!(message.contains("IF NOT EXISTS"), "{message}");
647 }
648}