Skip to main content

modkit/
contracts.rs

1use async_trait::async_trait;
2use axum::Router;
3use tokio_util::sync::CancellationToken;
4
5pub use crate::api::openapi_registry::OpenApiRegistry;
6
7/// System capability: receives runtime internals before init.
8///
9/// This trait is internal to modkit and only used by modules with the "system" capability.
10/// Normal user modules don't implement this.
11#[async_trait]
12pub trait SystemCapability: Send + Sync {
13    /// Optional pre-init hook for system modules.
14    ///
15    /// This runs BEFORE `init()` has completed for ALL modules, and only for system modules.
16    ///
17    /// Default implementation is a no-op so most modules don't need to implement it.
18    ///
19    /// # Errors
20    /// Returns an error if system wiring fails.
21    fn pre_init(&self, _sys: &crate::runtime::SystemContext) -> anyhow::Result<()> {
22        Ok(())
23    }
24
25    /// Optional post-init hook for system modules.
26    ///
27    /// This runs AFTER `init()` has completed for ALL modules, and only for system modules.
28    ///
29    /// Default implementation is a no-op so most modules don't need to implement it.
30    async fn post_init(&self, _sys: &crate::runtime::SystemContext) -> anyhow::Result<()> {
31        Ok(())
32    }
33}
34
35/// Core module: DI/wiring; do not rely on migrated schema here.
36#[async_trait]
37pub trait Module: Send + Sync + 'static {
38    async fn init(&self, ctx: &crate::context::ModuleCtx) -> anyhow::Result<()>;
39}
40
41/// Database capability: modules provide migrations, runtime executes them.
42///
43/// # Security
44///
45/// Modules MUST NOT receive raw database connections. They only return migration definitions.
46#[cfg(feature = "db")]
47pub trait DatabaseCapability: Send + Sync {
48    fn migrations(&self) -> Vec<Box<dyn sea_orm_migration::MigrationTrait>>;
49}
50
51/// REST API capability: Pure wiring; must be sync. Runs AFTER DB migrations.
52pub trait RestApiCapability: Send + Sync {
53    /// Register REST routes for this module.
54    ///
55    /// # Errors
56    /// Returns an error if route registration fails.
57    fn register_rest(
58        &self,
59        ctx: &crate::context::ModuleCtx,
60        router: Router,
61        openapi: &dyn OpenApiRegistry,
62    ) -> anyhow::Result<Router>;
63}
64
65/// API Gateway capability: handles gateway hosting with prepare/finalize phases.
66/// Must be sync. Runs during REST phase, but doesn't start the server.
67#[allow(dead_code)]
68pub trait ApiGatewayCapability: Send + Sync + 'static {
69    /// Prepare a base Router (e.g., global middlewares, /healthz) and optionally touch `OpenAPI` meta.
70    /// Do NOT start the server here.
71    ///
72    /// # Errors
73    /// Returns an error if router preparation fails.
74    fn rest_prepare(
75        &self,
76        ctx: &crate::context::ModuleCtx,
77        router: Router,
78    ) -> anyhow::Result<Router>;
79
80    /// Finalize before start: attach /openapi.json, /docs, persist the Router internally if needed.
81    /// Do NOT start the server here.
82    ///
83    /// # Errors
84    /// Returns an error if router finalization fails.
85    fn rest_finalize(
86        &self,
87        ctx: &crate::context::ModuleCtx,
88        router: Router,
89    ) -> anyhow::Result<Router>;
90
91    // Return OpenAPI registry of the module, e.g., to register endpoints
92    fn as_registry(&self) -> &dyn OpenApiRegistry;
93}
94
95#[async_trait]
96pub trait RunnableCapability: Send + Sync {
97    async fn start(&self, cancel: CancellationToken) -> anyhow::Result<()>;
98    async fn stop(&self, cancel: CancellationToken) -> anyhow::Result<()>;
99}
100
101/// Represents a gRPC service registration callback used by the gRPC hub.
102///
103/// Each module that exposes gRPC services provides one or more of these.
104/// The `register` closure adds the service into the provided `RoutesBuilder`.
105#[cfg(feature = "otel")]
106pub struct RegisterGrpcServiceFn {
107    pub service_name: &'static str,
108    pub register: Box<dyn Fn(&mut tonic::service::RoutesBuilder) + Send + Sync>,
109}
110
111#[cfg(not(feature = "otel"))]
112pub struct RegisterGrpcServiceFn {
113    pub service_name: &'static str,
114}
115
116/// gRPC Service capability: modules that export gRPC services.
117///
118/// The runtime will call this during the gRPC registration phase to collect
119/// all services that should be exposed on the shared gRPC server.
120#[async_trait]
121pub trait GrpcServiceCapability: Send + Sync {
122    /// Returns all gRPC services this module wants to expose.
123    ///
124    /// Each installer adds one service to the `tonic::Server` builder.
125    async fn get_grpc_services(
126        &self,
127        ctx: &crate::context::ModuleCtx,
128    ) -> anyhow::Result<Vec<RegisterGrpcServiceFn>>;
129}
130
131/// gRPC Hub capability: hosts the gRPC server.
132///
133/// This trait is implemented by the single module responsible for hosting
134/// the `tonic::Server` instance. Only one module per process should implement this.
135pub trait GrpcHubCapability: Send + Sync {
136    /// Returns the bound endpoint after the server starts listening.
137    ///
138    /// Examples:
139    /// - TCP: `http://127.0.0.1:50652`
140    /// - Unix socket: `unix:///path/to/socket`
141    /// - Named pipe: `pipe://\\.\pipe\name`
142    ///
143    /// Returns `None` if the server hasn't started listening yet.
144    fn bound_endpoint(&self) -> Option<String>;
145}