arcature 2026.2.1

Arcature application framework: a high-level Application facade over the certified Arcature subsystems, with the low-level Axum/Tower escape hatch preserved.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
//! The [`ApplicationBuilder`] — the typed, consuming builder for
//! [`Application`].
//!
//! The builder is the normal configuration seam (engine spec §22): small
//! surface, typed configuration, deterministic construction, no globals, no
//! runtime reflection. Each method returns a builder so an application reads
//! as a fluent chain.
//!
//! State flows through the builder at the type level, mirroring
//! [`axum::Router`]:
//!
//! ```text
//! ApplicationBuilder<()>  --routes(Routes<S>)-->  ApplicationBuilder<S>
//! ApplicationBuilder<S>    --state(S)----------->  ApplicationBuilder<()>
//! ApplicationBuilder<()>  --build()------------->  Application<()>  (servable)
//! ```
//!
//! A stateless app skips `.state()`: `.routes(Routes<()>)` keeps `S = ()`.
//! For lifecycle-managed apps, use `.run_with_lifecycle(state_fn)` instead of
//! `.state()` + `.run()` — the engine starts subsystems, builds state from
//! [`Resources`](super::resources::Resources), serves, and shuts down.

use crate::Routes;
use crate::application::ty::{Application, DEFAULT_BIND_ADDR, DEFAULT_PORT, ProxyFn};
use crate::proxy::{ProxyAction, ProxyRequest};

#[cfg(feature = "inertia")]
use crate::inertia::InertiaConfig;
#[cfg(feature = "inertia")]
use crate::inertia::PageContracts;

#[cfg(feature = "pages")]
use crate::pages::{MaintenanceGuard, Pages};

#[cfg(feature = "db")]
use crate::db::DbConfig;

#[cfg(feature = "cache")]
use crate::cache::CacheConfig;

#[cfg(feature = "storage")]
use crate::storage::StorageConfig;

#[cfg(feature = "mail")]
use crate::mail::SmtpConfig;

#[cfg(feature = "jobs")]
use super::jobs_registry::JobsRegistry;
#[cfg(feature = "jobs")]
use crate::jobs::WorkerConfig;

/// A consuming builder for [`Application`].
///
/// Constructed via [`Application::new`](crate::Application::new). State `S` is
/// the Axum router state type tracked at compile time.
pub struct ApplicationBuilder<S = ()> {
    pub(crate) routes: Routes<S>,
    pub(crate) proxy: Option<ProxyFn>,
    pub(crate) bind_address: String,
    pub(crate) port: u16,

    #[cfg(feature = "inertia")]
    pub(crate) inertia_config: Option<InertiaConfig>,
    #[cfg(feature = "inertia")]
    pub(crate) page_contracts: Option<PageContracts>,
    #[cfg(feature = "pages")]
    pub(crate) pages: Option<Pages>,
    #[cfg(feature = "pages")]
    pub(crate) maintenance_guard: Option<MaintenanceGuard>,

    // Lifecycle config (consumed by `startup`).
    #[cfg(feature = "db")]
    pub(crate) database: Option<DbConfig>,
    #[cfg(feature = "cache")]
    pub(crate) cache_config: Option<CacheConfig>,
    #[cfg(feature = "storage")]
    pub(crate) storage_config: Option<StorageConfig>,
    #[cfg(feature = "mail")]
    pub(crate) mail_config: Option<SmtpConfig>,
    #[cfg(feature = "jobs")]
    pub(crate) jobs_registry: Option<JobsRegistry>,
    #[cfg(feature = "jobs")]
    pub(crate) worker_config: Option<WorkerConfig>,

    #[cfg(feature = "dx")]
    pub(crate) error_mapping: Option<crate::pipeline::error_mapping::ErrorMapFn>,

    #[cfg(feature = "dev-proxy")]
    pub(crate) dev_proxy_endpoint: Option<crate::dev_proxy::endpoint::IpcEndpoint>,
}

impl<S> ApplicationBuilder<S>
where
    S: Clone + Send + Sync + 'static,
{
    /// Install the application proxy function — application-owned global
    /// request policy that runs *before* route selection (engine spec §5).
    ///
    /// The engine owns all Axum/Tower plumbing; the application owns only the
    /// policy, expressed as a pure synchronous function from
    /// [`ProxyRequest`] to [`ProxyAction`]. The proxy is executed by the
    /// pre-routing Tower service (the `proxy::service` module) which rewrites the
    /// request URI before the Axum router sees it (engine spec §3/§4).
    #[must_use]
    pub fn proxy<F>(mut self, proxy: F) -> Self
    where
        F: Fn(ProxyRequest<'_>) -> ProxyAction + Send + Sync + 'static,
    {
        self.proxy = Some(std::sync::Arc::new(proxy));
        self
    }

    /// Set the bind address (host) for [`Application::run`](crate::Application).
    /// Default: `127.0.0.1`.
    #[must_use]
    pub fn bind(mut self, address: impl Into<String>) -> Self {
        self.bind_address = address.into();
        self
    }

    /// Set the bind port for [`Application::run`](crate::Application).
    /// Default: `3000`.
    #[must_use]
    pub fn port(mut self, port: u16) -> Self {
        self.port = port;
        self
    }

    /// Install the Inertia config. When set, the pipeline assembler applies
    /// `InertiaLayer` as a post-routing layer (engine spec §36) so Inertia
    /// protocol responses (page objects, version-mismatch 409, fragment
    /// redirects) are handled by the certified `arcature-inertia` middleware.
    ///
    /// Only available when the `inertia` feature is enabled.
    #[cfg(feature = "inertia")]
    #[must_use]
    pub fn inertia(mut self, config: InertiaConfig) -> Self {
        self.inertia_config = Some(config);
        self
    }

    /// Register typed Inertia page contracts with the application.
    ///
    /// This does not change Axum route selection. It gives the engine and
    /// Cross-Stack Linker one explicit page/props registry.
    #[cfg(feature = "inertia")]
    #[must_use]
    pub fn page_contracts(mut self, contracts: PageContracts) -> Self {
        self.page_contracts = Some(contracts);
        self
    }

    /// Install the special-pages renderer. When set, the pipeline assembler
    /// uses `Pages::not_found_service()` as the router's 404 fallback (engine
    /// spec §9/§37). When `None`, the engine uses `Pages::default()`.
    ///
    /// Only available when the `pages` feature is enabled.
    #[cfg(feature = "pages")]
    #[must_use]
    pub fn pages(mut self, pages: Pages) -> Self {
        self.pages = Some(pages);
        self
    }

    /// Install the maintenance guard. When set, the pipeline assembler applies
    /// `MaintenanceLayer` as a post-routing layer that short-circuits with 503
    /// and `Retry-After` when the application is in maintenance mode (engine
    /// spec §10). The guard is the single shared handle for maintenance state;
    /// clone it for the `arc down` / `arc up` CLI ops.
    ///
    /// Only available when the `pages` feature is enabled (maintenance is a
    /// special page).
    #[cfg(feature = "pages")]
    #[must_use]
    pub fn maintenance(mut self, guard: MaintenanceGuard) -> Self {
        self.maintenance_guard = Some(guard);
        self
    }

    /// Configure the database. When set, the engine builds one `PgPool` via
    /// `Db::connect` on `run_with_lifecycle`, shares it with jobs, and exposes
    /// the `Db` handle via `Resources::db()`.
    ///
    /// Only available when the `db` feature is enabled.
    #[cfg(feature = "db")]
    #[must_use]
    pub fn database(mut self, config: DbConfig) -> Self {
        self.database = Some(config);
        self
    }

    /// Configure the cache. When set, the engine connects via
    /// `Cache::connect` on `run_with_lifecycle`.
    #[cfg(feature = "cache")]
    #[must_use]
    pub fn cache(mut self, config: CacheConfig) -> Self {
        self.cache_config = Some(config);
        self
    }

    /// Configure the storage backend. When set, the engine connects via
    /// `Storage::connect` on `run_with_lifecycle`.
    #[cfg(feature = "storage")]
    #[must_use]
    pub fn storage(mut self, config: StorageConfig) -> Self {
        self.storage_config = Some(config);
        self
    }

    /// Configure the mailer. When set, the engine constructs a `Mailer` via
    /// `Mailer::smtp` on `run_with_lifecycle`.
    #[cfg(feature = "mail")]
    #[must_use]
    pub fn mail(mut self, config: SmtpConfig) -> Self {
        self.mail_config = Some(config);
        self
    }

    /// Configure the job handler registry, built before startup. When set,
    /// the engine spawns a worker over the shared `PgPool` on
    /// `run_with_lifecycle`. The worker runs until shutdown, then drains
    /// in-flight jobs before the pool closes.
    ///
    /// Use this when handlers need no runtime state (the registry is built
    /// before the `Db` connects). When a handler needs the database (the
    /// common dogfood case), use [`Self::jobs_with_db`] instead so the
    /// registry is built after the pool connects and handlers can capture a
    /// `Db` clone.
    #[cfg(feature = "jobs")]
    #[must_use]
    pub fn jobs(mut self, registry: crate::jobs::Registry) -> Self {
        self.jobs_registry = Some(JobsRegistry::Static(registry));
        self
    }

    /// Configure the job handler registry via a closure that runs *after* the
    /// engine connects the `PgPool` at startup. The closure receives the
    /// connected `Db` and returns a [`crate::jobs::Registry`]; handlers it
    /// registers may capture a `Db` clone (or any handle derived from the
    /// pool). The engine spawns the worker over the shared pool, exactly as
    /// with [`Self::jobs`].
    ///
    /// This keeps the A13 job-handler contract `Fn(J) -> Fut` unchanged —
    /// only the *registry-construction* moment moves into the lifecycle,
    /// after `Db::connect`. The `arcature-jobs` API is untouched.
    ///
    /// The `Db` is borrowed only for the duration of the closure call;
    /// handlers that need a handle must clone it (the handle is `Clone` —
    /// an `Arc`-backed pool reference). A handler that needs a resource not
    /// ready at the jobs step (e.g. cache, mail) requires a startup reorder
    /// to expose it — out of scope for this hook.
    #[cfg(feature = "jobs")]
    #[must_use]
    pub fn jobs_with_db<F>(mut self, build: F) -> Self
    where
        F: Fn(&crate::db::Db) -> crate::jobs::Registry + Send + Sync + 'static,
    {
        self.jobs_registry = Some(JobsRegistry::WithDb(std::sync::Arc::new(build)));
        self
    }

    /// Override the worker config. Defaults to `WorkerConfig::default()` when
    /// not called. Only used when `.jobs(registry)` is also set.
    #[cfg(feature = "jobs")]
    #[must_use]
    pub fn worker_config(mut self, config: WorkerConfig) -> Self {
        self.worker_config = Some(config);
        self
    }

    /// Install a global error-mapping function (A10). The pipeline applies
    /// it to every response after the handler has run. The function
    /// receives the `Response` and returns a new `Response` — typically
    /// reformatting error responses (e.g. 5xx → RFC 9457 Problem Details)
    /// or adding correlation IDs.
    ///
    /// The function must NOT leak internal error details (database
    /// connection strings, session internals, stack traces) to the client.
    /// The dogfood pattern logs the error to `eprintln!` and returns a
    /// generic `500 INTERNAL_SERVER_ERROR`.
    ///
    /// Only available when the `dx` feature is enabled.
    #[cfg(feature = "dx")]
    #[must_use]
    pub fn error_mapping<F>(mut self, f: F) -> Self
    where
        F: Fn(crate::axum::response::Response) -> crate::axum::response::Response
            + Send
            + Sync
            + 'static,
    {
        self.error_mapping = Some(crate::pipeline::error_mapping::ErrorMapFn::new(f));
        self
    }

    /// Set the Vite IPC endpoint for the one-port dev proxy explicitly
    /// (AP2.1-3). When `Some(path)`, the dev proxy forwards Vite-looking
    /// requests (`/@vite/`, `/src/...`, HMR WebSocket) to Vite over the IPC
    /// endpoint at `path`; when `None` (the default), the pipeline falls back
    /// to the `ARCATURE_VITE_IPC` environment variable — the convention `arc
    /// dev` sets. This is the explicit, typed configuration seam
    /// (AGENTS.md §21); the env var remains the default path so `arc dev`
    /// needs no application code change.
    ///
    /// Only available with the `dev-proxy` feature. The endpoint is
    /// process-private and per-invocation; it is never attacker-controlled
    /// (see the AP2.1-3 security review).
    #[cfg(feature = "dev-proxy")]
    #[must_use]
    pub fn dev_proxy_endpoint(mut self, endpoint: Option<std::path::PathBuf>) -> Self {
        self.dev_proxy_endpoint = endpoint.map(crate::dev_proxy::endpoint::IpcEndpoint::new);
        self
    }

    /// Resolve the router state to `()` (the engine analogue of
    /// [`axum::Router::with_state`]) so the application becomes servable.
    /// Consumes `state` and the builder; returns a builder with `S = ()`.
    #[must_use]
    pub fn state(self, state: S) -> ApplicationBuilder<()> {
        ApplicationBuilder {
            routes: self.routes.with_state(state),
            proxy: self.proxy,
            bind_address: self.bind_address,
            port: self.port,
            #[cfg(feature = "inertia")]
            inertia_config: self.inertia_config,
            #[cfg(feature = "inertia")]
            page_contracts: self.page_contracts,
            #[cfg(feature = "pages")]
            pages: self.pages,
            #[cfg(feature = "pages")]
            maintenance_guard: self.maintenance_guard,
            #[cfg(feature = "db")]
            database: self.database,
            #[cfg(feature = "cache")]
            cache_config: self.cache_config,
            #[cfg(feature = "storage")]
            storage_config: self.storage_config,
            #[cfg(feature = "mail")]
            mail_config: self.mail_config,
            #[cfg(feature = "jobs")]
            jobs_registry: self.jobs_registry,
            #[cfg(feature = "jobs")]
            worker_config: self.worker_config,
            #[cfg(feature = "dx")]
            error_mapping: self.error_mapping,
            #[cfg(feature = "dev-proxy")]
            dev_proxy_endpoint: self.dev_proxy_endpoint,
        }
    }

    /// Freeze the builder into an [`Application`]. Construction is
    /// deterministic and allocation-free beyond storing the parts.
    #[must_use]
    pub fn build(self) -> Application<S> {
        Application {
            routes: self.routes,
            proxy: self.proxy,
            bind_address: self.bind_address,
            port: self.port,
            #[cfg(feature = "inertia")]
            inertia_config: self.inertia_config,
            #[cfg(feature = "inertia")]
            page_contracts: self.page_contracts,
            #[cfg(feature = "pages")]
            pages: self.pages,
            #[cfg(feature = "pages")]
            maintenance_guard: self.maintenance_guard,
            #[cfg(feature = "db")]
            database: self.database,
            #[cfg(feature = "cache")]
            cache_config: self.cache_config,
            #[cfg(feature = "storage")]
            storage_config: self.storage_config,
            #[cfg(feature = "mail")]
            mail_config: self.mail_config,
            #[cfg(feature = "jobs")]
            jobs_registry: self.jobs_registry,
            #[cfg(feature = "jobs")]
            worker_config: self.worker_config,
            #[cfg(feature = "dx")]
            error_mapping: self.error_mapping,
            #[cfg(feature = "dev-proxy")]
            dev_proxy_endpoint: self.dev_proxy_endpoint,
        }
    }
}

impl ApplicationBuilder<()> {
    /// Start a new stateless builder with an empty route table and default
    /// bind address (`127.0.0.1:3000`). Most applications call
    /// [`Application::new`](crate::Application::new) instead.
    #[must_use]
    pub fn new() -> Self {
        Self {
            routes: Routes::new(),
            proxy: None,
            bind_address: DEFAULT_BIND_ADDR.to_owned(),
            port: DEFAULT_PORT,
            #[cfg(feature = "inertia")]
            inertia_config: None,
            #[cfg(feature = "inertia")]
            page_contracts: None,
            #[cfg(feature = "pages")]
            pages: None,
            #[cfg(feature = "pages")]
            maintenance_guard: None,
            #[cfg(feature = "db")]
            database: None,
            #[cfg(feature = "cache")]
            cache_config: None,
            #[cfg(feature = "storage")]
            storage_config: None,
            #[cfg(feature = "mail")]
            mail_config: None,
            #[cfg(feature = "jobs")]
            jobs_registry: None,
            #[cfg(feature = "jobs")]
            worker_config: None,
            #[cfg(feature = "dx")]
            error_mapping: None,
            #[cfg(feature = "dev-proxy")]
            dev_proxy_endpoint: None,
        }
    }
}

impl Default for ApplicationBuilder<()> {
    fn default() -> Self {
        Self::new()
    }
}

// `routes` changes the builder's state type, so it is a free-standing impl
// block (not bound by `S: Clone + Send + Sync + 'static`) so a stateful
// router can be installed from the initial `ApplicationBuilder<()>`.
impl<S> ApplicationBuilder<S> {
    /// Replace the route table. The previous routes are discarded; the
    /// builder's state type becomes the router's state type `S2`.
    #[must_use]
    pub fn routes<S2>(self, routes: Routes<S2>) -> ApplicationBuilder<S2> {
        ApplicationBuilder {
            routes,
            proxy: self.proxy,
            bind_address: self.bind_address,
            port: self.port,
            #[cfg(feature = "inertia")]
            inertia_config: self.inertia_config,
            #[cfg(feature = "inertia")]
            page_contracts: self.page_contracts,
            #[cfg(feature = "pages")]
            pages: self.pages,
            #[cfg(feature = "pages")]
            maintenance_guard: self.maintenance_guard,
            #[cfg(feature = "db")]
            database: self.database,
            #[cfg(feature = "cache")]
            cache_config: self.cache_config,
            #[cfg(feature = "storage")]
            storage_config: self.storage_config,
            #[cfg(feature = "mail")]
            mail_config: self.mail_config,
            #[cfg(feature = "jobs")]
            jobs_registry: self.jobs_registry,
            #[cfg(feature = "jobs")]
            worker_config: self.worker_config,
            #[cfg(feature = "dx")]
            error_mapping: self.error_mapping,
            #[cfg(feature = "dev-proxy")]
            dev_proxy_endpoint: self.dev_proxy_endpoint,
        }
    }
}