Skip to main content

toolkit/
contracts.rs

1use async_trait::async_trait;
2use axum::Router;
3use tokio_util::sync::CancellationToken;
4
5pub use crate::api::openapi_registry::OpenApiRegistry;
6pub use crate::grpc_registration::RegisterGrpcServiceFn;
7
8/// Infrastructure that starts before application preparation: types registry,
9/// service discovery, cluster and gRPC hub.
10///
11/// The system group completes startup before application preparation and serves
12/// during GTS admission. System gears cannot publish via `gts_publication(...)`
13/// or depend on/consume local application gears. Early `OoP` HTTP routes allow
14/// only platform-plane and anonymous calls; tenant auth is not wired yet.
15///
16/// Embedded hosts serve probes and system platform routes before application startup.
17/// Lifecycle hooks live on [`Gear`]; this trait receives runtime internals.
18#[async_trait]
19pub trait SystemCapability: Send + Sync {
20    /// Receive runtime internals, once, before the gear's `pre_init`.
21    ///
22    /// Service discovery takes the gear manager; the gRPC hub takes the
23    /// installer store and the process instance id. Default: nothing.
24    ///
25    /// # Errors
26    /// Returns an error if the gear cannot take the runtime internals.
27    fn wire_runtime(&self, _sys: &crate::runtime::SystemContext) -> anyhow::Result<()> {
28        Ok(())
29    }
30
31    /// Temporary hook for the legacy registry's in-memory ready mode only.
32    /// Validates all legacy registrations once, after application `init` and proxy
33    /// wiring, before application `post_init`. Removed with that ready mode.
34    async fn legacy_finalize_after_application_init(
35        &self,
36        _sys: &crate::runtime::SystemContext,
37    ) -> anyhow::Result<()> {
38        Ok(())
39    }
40}
41
42/// Core lifecycle and dependency wiring, once per gear within its startup group.
43/// The system group completes before the application group begins.
44///
45/// 1. [`pre_init`](Self::pre_init), before the group's DB migrations;
46/// 2. [`init`](Self::init), after migrations and, for applications, GTS admission;
47/// 3. [`post_init`](Self::post_init), after all group `init`s and consumed-client
48///    wiring, before routes and `start`.
49///
50/// `init` can use its configured, migrated database and register local clients.
51/// Ordinary `#[toolkit::consumes]` clients may be absent until proxy wiring;
52/// resolve them in `post_init` or lazily. System-provider and publication registry
53/// clients are wired earlier; `deps` can order local client registration.
54#[async_trait]
55pub trait Gear: Send + Sync + 'static {
56    /// Optional hook before this group's migrations; also runs in migration-only mode.
57    /// The context has no DB handle or admitted manifest. No gear in this group has
58    /// initialized yet, so do not rely on its providers. Default: no-op.
59    ///
60    /// # Errors
61    /// Returns an error to fail startup.
62    async fn pre_init(&self, _ctx: &crate::context::GearCtx) -> anyhow::Result<()> {
63        Ok(())
64    }
65
66    async fn init(&self, ctx: &crate::context::GearCtx) -> anyhow::Result<()>;
67
68    /// Optional hook after the group's `init`s and proxy wiring, before routes and
69    /// `start`. Application hooks also follow legacy registry finalization.
70    /// Do not wait for remote services: this group's routes are not served yet.
71    /// Default: no-op.
72    ///
73    /// # Errors
74    /// Returns an error to fail startup.
75    async fn post_init(&self, _ctx: &crate::context::GearCtx) -> anyhow::Result<()> {
76        Ok(())
77    }
78}
79
80/// Database capability: gears provide migrations, runtime executes them.
81///
82/// # Security
83///
84/// Gears MUST NOT receive raw database connections. They only return migration definitions.
85#[cfg(feature = "db")]
86pub trait DatabaseCapability: Send + Sync {
87    fn migrations(&self) -> Vec<Box<dyn sea_orm_migration::MigrationTrait>>;
88}
89
90/// REST API capability: Pure wiring; must be sync. Runs AFTER DB migrations.
91pub trait RestApiCapability: Send + Sync {
92    /// Register REST routes for this gear.
93    ///
94    /// # Errors
95    /// Returns an error if route registration fails.
96    fn register_rest(
97        &self,
98        ctx: &crate::context::GearCtx,
99        router: Router,
100        openapi: &dyn OpenApiRegistry,
101    ) -> anyhow::Result<Router>;
102
103    /// Readiness healthcheck for this gear, run on every `/readyz` and `/health`.
104    /// `None` (default) opts out.
105    ///
106    /// Return **one composite check per gear** that aggregates the gear's critical
107    /// dependencies, rather than many fine-grained probes — the aggregate is what decides
108    /// whether the pod stays in traffic. External SaaS/LLM dependencies should usually **not**
109    /// gate readiness: a provider outage would evict every pod from rotation and take the
110    /// whole service down. Report such dependencies as `degraded` (kept in rotation), reserving
111    /// `unhealthy` for failures the gear itself cannot serve through.
112    fn healthcheck(
113        &self,
114        _ctx: &crate::context::GearCtx,
115    ) -> Option<std::sync::Arc<dyn crate::healthcheck::Healthcheck>> {
116        None
117    }
118
119    /// Whether the in-process host advertises this gear as a REST provider in the
120    /// service directory, under its gear name. Asked after `init`. `false` keeps a gear
121    /// that serves only part of its contracts here from being discovered as their
122    /// provider; its routes are still served. Defaults to `true`.
123    fn advertised_in_directory(&self) -> bool {
124        true
125    }
126}
127
128/// REST hosting with optional early probes and system routes during preparation.
129#[allow(dead_code)]
130#[async_trait]
131pub trait ApiGatewayCapability: Send + Sync + 'static {
132    /// Bind probes without application clients; return a prepared router for staged hosting.
133    /// System routes attach first, then application routes. Stop on `cancel`, even if init fails.
134    async fn rest_bootstrap(
135        &self,
136        _ctx: &crate::context::GearCtx,
137        _hc_registry: std::sync::Arc<crate::healthcheck::RestHealthcheckRegistry>,
138        _cancel: CancellationToken,
139    ) -> anyhow::Result<Option<Router>> {
140        Ok(None)
141    }
142
143    /// Serve system routes during admission; reject tenant calls until `AuthN` is ready.
144    ///
145    /// # Errors
146    /// Staged serving is unsupported or composition fails.
147    fn rest_finalize_bootstrap(
148        &self,
149        _ctx: &crate::context::GearCtx,
150        _router: Router,
151        _hc_registry: std::sync::Arc<crate::healthcheck::RestHealthcheckRegistry>,
152    ) -> anyhow::Result<()> {
153        anyhow::bail!("this REST host does not support staged serving")
154    }
155
156    /// Join a bootstrap listener whose application lifecycle never started.
157    async fn rest_shutdown_bootstrap(&self) -> anyhow::Result<()> {
158        Ok(())
159    }
160
161    /// Prepare a base Router (e.g., global middlewares) and optionally touch `OpenAPI` meta.
162    /// Do NOT start the server here. `hc_registry` is the runtime's shared healthcheck
163    /// registry, passed explicitly (not via `ClientHub`, which is for inter-gear clients).
164    ///
165    /// # Errors
166    /// Returns an error if router preparation fails.
167    fn rest_prepare(
168        &self,
169        ctx: &crate::context::GearCtx,
170        router: Router,
171        hc_registry: std::sync::Arc<crate::healthcheck::RestHealthcheckRegistry>,
172    ) -> anyhow::Result<Router>;
173
174    /// Finalize before start: attach /openapi.json, /docs, health endpoints, persist the
175    /// Router internally if needed. Do NOT start the server here.
176    ///
177    /// `hc_registry` is the same registry instance passed to [`rest_prepare`](Self::rest_prepare).
178    ///
179    /// # Errors
180    /// Returns an error if router finalization fails.
181    fn rest_finalize(
182        &self,
183        ctx: &crate::context::GearCtx,
184        router: Router,
185        hc_registry: std::sync::Arc<crate::healthcheck::RestHealthcheckRegistry>,
186    ) -> anyhow::Result<Router>;
187
188    // Return OpenAPI registry of the gear, e.g., to register endpoints
189    fn as_registry(&self) -> &dyn OpenApiRegistry;
190
191    /// The bound REST base URL (e.g. `http://127.0.0.1:8080`) once the gateway's
192    /// server is listening, or `None` before the listener binds.
193    ///
194    /// Mirrors [`GrpcHubCapability::bound_endpoint`]. The runtime polls this in
195    /// its directory-register phase to advertise REST providers in the service
196    /// directory. Defaults to `None` for hosts that don't expose an address.
197    fn bound_endpoint(&self) -> Option<String> {
198        None
199    }
200}
201
202/// Capability for gears that have a long-running background task.
203///
204/// # Shutdown Contract
205///
206/// The `stop` method receives a **deadline token** that implements two-phase shutdown:
207///
208/// 1. **Graceful stop request**: When `stop(deadline_token)` is called, the `deadline_token`
209///    is *not* cancelled. This is the signal to begin graceful shutdown.
210///
211/// 2. **Hard-stop deadline**: After the runtime's `shutdown_deadline` expires (default 35s),
212///    the `deadline_token` is cancelled. This signals that graceful shutdown time is over
213///    and the gear should abort immediately.
214///
215/// ## Recommended Implementation Pattern
216///
217/// ```ignore
218/// async fn stop(&self, deadline_token: CancellationToken) -> anyhow::Result<()> {
219///     // 1. Request cooperative shutdown of child tasks
220///     self.request_graceful_shutdown();
221///
222///     // 2. Wait for graceful completion OR hard-stop deadline
223///     tokio::select! {
224///         _ = self.wait_for_graceful_completion() => {
225///             // Graceful shutdown succeeded
226///         }
227///         _ = deadline_token.cancelled() => {
228///             // Deadline reached, force abort
229///             self.force_abort();
230///         }
231///     }
232///     Ok(())
233/// }
234/// ```
235///
236/// ## Important Notes
237///
238/// - The `deadline_token` passed to `stop()` is a **fresh token**, not the root cancellation
239///   token that triggered the shutdown. This allows gears to implement real graceful shutdown.
240/// - Gears should NOT assume the token is already cancelled when `stop()` is called.
241/// - The `WithLifecycle` wrapper handles this contract automatically via its `stop_timeout`.
242#[async_trait]
243pub trait RunnableCapability: Send + Sync {
244    /// Start the gear's background task.
245    ///
246    /// The `cancel` token is a child of the runtime's root cancellation token.
247    /// When cancelled, the gear should stop its background work.
248    async fn start(&self, cancel: CancellationToken) -> anyhow::Result<()>;
249
250    /// Stop the gear's background task.
251    ///
252    /// The `deadline_token` implements two-phase shutdown:
253    /// - Initially not cancelled: begin graceful shutdown
254    /// - When cancelled: graceful period expired, abort immediately
255    ///
256    /// See trait-level documentation for the full shutdown contract.
257    async fn stop(&self, deadline_token: CancellationToken) -> anyhow::Result<()>;
258}
259
260/// gRPC Service capability: gears that export gRPC services.
261///
262/// The runtime will call this during the gRPC registration phase to collect
263/// all services that should be exposed on the shared gRPC server.
264#[async_trait]
265pub trait GrpcServiceCapability: Send + Sync {
266    /// Returns all gRPC services this gear wants to expose.
267    ///
268    /// Each installer adds one service to the `tonic::Server` builder.
269    async fn get_grpc_services(
270        &self,
271        ctx: &crate::context::GearCtx,
272    ) -> anyhow::Result<Vec<RegisterGrpcServiceFn>>;
273}
274
275/// gRPC Hub capability: hosts the gRPC server.
276///
277/// This trait is implemented by the single gear responsible for hosting
278/// the `tonic::Server` instance. Only one gear per process should implement this.
279pub trait GrpcHubCapability: Send + Sync {
280    /// Returns the bound endpoint after the server starts listening.
281    ///
282    /// Examples:
283    /// - TCP: `http://127.0.0.1:50652`
284    /// - Unix socket: `unix:///path/to/socket`
285    /// - Named pipe: `pipe://\\.\pipe\name`
286    ///
287    /// Returns `None` if the server hasn't started listening yet.
288    fn bound_endpoint(&self) -> Option<String>;
289
290    /// Whether the hub has settled on binding nothing (`listen_addr: none`, or
291    /// no services to serve), so [`bound_endpoint`](Self::bound_endpoint)
292    /// stays `None` for good.
293    fn serves_no_endpoint(&self) -> bool {
294        false
295    }
296}