Skip to main content

backbone_integrations/
lib.rs

1//! Integrations Module
2//!
3//! Generated by metaphor-schema. Enhanced with runtime implementations.
4//!
5//! This module provides:
6//! - Domain entities and repositories
7//! - Application services
8//! - HTTP and gRPC handlers
9//! - Route configuration
10//! - State machine enforcement
11//! - Validation rules runtime
12//! - RBAC middleware
13//! - Trigger execution system
14//! - Computed fields
15//! - Workflow orchestrator
16
17#![recursion_limit = "1024"]
18#![allow(unused_imports)]
19
20// Generated modules
21pub mod domain;
22pub mod infrastructure;
23pub mod application;
24pub mod presentation;
25pub mod seeders;
26pub mod exports;
27
28// Re-exports - Infrastructure
29pub use infrastructure::persistence::*;
30
31// Re-exports - Application services
32pub use application::service::IntegrationConnectorService;
33pub use application::service::IntegrationAccountService;
34pub use application::service::IntegrationEventService;
35
36// <<< CUSTOM
37// The hand-authored write path: receive an inbound provider event idempotently and map it via TargetPort,
38// plus the port + receiver types a composing service needs to wire the seam from one place.
39pub use application::service::IntegrationsWriteService;
40pub use application::service::{TargetPort, MapRequest, MapOutcome, MapRejected, MappedRef};
41pub use application::service::{InboundEvent, ReceiveOutcome, NewConnector, FailedEvent, IntegrationError};
42pub use application::service::{IntegrationEvent, IntegrationEventMapped, IntegrationEventSink, LoggingSink};
43// The OAuth credential port (ADR-0024 amendment: the store is reached through a port, never a
44// Cargo edge) — the types a composing host needs to bind the credential store for the OAuth flow.
45pub use application::service::{OAuthCredentialFailure, OAuthCredentialStore, PURPOSE_OAUTH_TOKEN, TokenBundle, TokenMetadata};
46// The one OAuth generation: the service + config a composing host binds (with the two ports it
47// runs on), and the outbound endpoint-guard surface its transport belongs to.
48pub use application::service::{
49    AccountStatus, AuthorizeRequest, AuthorizeResponse, CompleteOutcome, CompleteRequest,
50    IntegrationsOauthConfig, IntegrationsOauthService, OauthError, RefreshSummary,
51    STATE_TTL_SECONDS,
52};
53pub use infrastructure::http::{OAuthTransport, ReqwestOAuthTransport};
54// END CUSTOM
55// Re-exports - Workflows
56pub use application::workflows::*;
57
58use std::sync::Arc;
59use axum::Router;
60use sqlx::PgPool;
61
62/// Integrations module configuration
63///
64/// Use the builder pattern to configure and register this module:
65///
66/// ```text
67/// let integrations = IntegrationsModule::builder()
68///     .with_database(pool.clone())
69///     .build()?;
70///
71/// // Unguarded full CRUD (trusted/admin); compose a guarded router for production.
72/// let router = integrations.all_crud_routes();
73/// ```
74pub struct IntegrationsModule {
75    pub(crate) integration_connector_service: Arc<IntegrationConnectorService>,
76    pub(crate) integration_account_service: Arc<IntegrationAccountService>,
77    pub(crate) integration_event_service: Arc<IntegrationEventService>,
78    // <<< CUSTOM FIELDS
79    /// The hand-authored receive/retry/map path. The module's reason for existing — without this field
80    /// it's unreachable through the public API (CLAUDE.md: "MUST register every service in the {Domain}Module builder").
81    pub integrations_write_service: Arc<IntegrationsWriteService>,
82    /// The one OAuth generation service. `Option` because composition opts in
83    /// (`with_oauth` + the two ports); `oauth_routes()` is empty without it.
84    pub integrations_oauth: Option<Arc<IntegrationsOauthService>>,
85    // END CUSTOM
86}
87
88impl IntegrationsModule {
89    /// Create a new module builder
90    pub fn builder() -> IntegrationsModuleBuilder {
91        IntegrationsModuleBuilder::new()
92    }
93
94    /// Mount ALL generated CRUD endpoints (12 per entity) with NO domain
95    /// validation — the fully **unguarded** surface. A well-formed request can
96    /// create invalid rows or soft-delete a referenced master out from under its
97    /// dependents. Prefer a guarded composition (read + validated writes) for any
98    /// real deployment; use this only in trusted/admin/seeding contexts.
99    pub fn all_crud_routes(&self) -> Router {
100        use presentation::http::{
101            create_integration_connector_routes,
102            create_integration_event_routes,
103        };
104
105        Router::new()
106            .merge(create_integration_connector_routes(self.integration_connector_service.clone()))
107            .merge(create_integration_event_routes(self.integration_event_service.clone()))
108    }
109
110    /// Deprecated alias for [`Self::all_crud_routes`]. `routes()` reads like
111    /// "the routes" but mounts UNVALIDATED generic CRUD on every entity — a naive
112    /// mount exposes unguarded writes. Compose a guarded router (read + validated
113    /// writes) for production, or call `all_crud_routes()` to opt into the full
114    /// unguarded surface explicitly.
115    #[deprecated(note = "mounts unvalidated generic CRUD; prefer readonly_routes() + validated writes, or all_crud_routes() for the full/unguarded surface")]
116    pub fn routes(&self) -> Router {
117        self.all_crud_routes()
118    }
119
120    /// Read-only routes for every entity (GET endpoints only) — the safe base.
121    ///
122    /// Generic mutation can't reach here, so this surface cannot bypass a
123    /// validated write service's invariants. Use this as the production base and
124    /// merge validated write routes (or a write service's HTTP layer) onto it.
125    pub fn readonly_routes(&self) -> Router {
126        use presentation::http::{
127            create_integration_connector_read_routes,
128            create_integration_event_read_routes,
129        };
130
131        Router::new()
132            .merge(create_integration_connector_read_routes(self.integration_connector_service.clone()))
133            .merge(create_integration_event_read_routes(self.integration_event_service.clone()))
134    }
135
136    // <<< CUSTOM METHODS
137    /// Production-safe router: connector admin CRUD + event READ-only.
138    ///
139    /// Integration events are produced by the idempotent `receive_event` path, not
140    /// hand-mutated, so the generic event write/bulk endpoints are deliberately
141    /// excluded here — a caller cannot bypass the dedup/map state machine through
142    /// this surface. Mount this (or `readonly_routes()`) for production; reserve
143    /// `all_crud_routes()` for trusted/admin/seeding only.
144    pub fn guarded_routes(&self) -> Router {
145        use presentation::http::{
146            create_integration_connector_routes,
147            create_integration_event_read_routes,
148        };
149
150        Router::new()
151            .merge(create_integration_connector_routes(self.integration_connector_service.clone()))
152            .merge(create_integration_event_read_routes(self.integration_event_service.clone()))
153    }
154
155    /// The verb-shaped OAuth surface (authorize / callback / complete /
156    /// disconnect / status). Empty when the module was built without
157    /// `with_oauth` — mounting it anyway is safe, it contributes no routes.
158    pub fn oauth_routes(&self) -> Router {
159        use presentation::http::create_oauth_routes;
160
161        match &self.integrations_oauth {
162            Some(service) => create_oauth_routes(service.clone()),
163            None => Router::new(),
164        }
165    }
166    // END CUSTOM
167}
168
169/// Builder for IntegrationsModule
170pub struct IntegrationsModuleBuilder {
171    db_pool: Option<PgPool>,
172    // <<< CUSTOM - OAuth generation fields (the one flow's construction inputs)
173    oauth_config: Option<IntegrationsOauthConfig>,
174    oauth_transport: Option<Arc<dyn OAuthTransport>>,
175    oauth_store: Option<Arc<dyn OAuthCredentialStore>>,
176    // END CUSTOM
177}
178
179impl IntegrationsModuleBuilder {
180    /// Create a new builder
181    pub fn new() -> Self {
182        Self {
183            db_pool: None,
184            // <<< CUSTOM
185            oauth_config: None,
186            oauth_transport: None,
187            oauth_store: None,
188            // END CUSTOM
189        }
190    }
191
192    /// Set the database connection pool
193    pub fn with_database(mut self, pool: PgPool) -> Self {
194        self.db_pool = Some(pool);
195        self
196    }
197
198    // <<< CUSTOM - custom builder methods
199    /// Opt the module into the one OAuth generation. The config carries the
200    /// deployment's public base, per-provider clients, and endpoint overrides
201    /// — every override passes the endpoint guard at build time (a bad one
202    /// fails the build), and the state-signing key is read from the
203    /// environment variable the config names (never a file value).
204    pub fn with_oauth(mut self, config: IntegrationsOauthConfig) -> Self {
205        self.oauth_config = Some(config);
206        self
207    }
208
209    /// The outbound OAuth transport (token exchange + server-side identity
210    /// read). Defaults to [`ReqwestOAuthTransport`] when omitted.
211    pub fn with_oauth_transport(mut self, transport: Arc<dyn OAuthTransport>) -> Self {
212        self.oauth_transport = Some(transport);
213        self
214    }
215
216    /// Bind the credential store through the port (ADR-0024 amendment: no
217    /// Cargo edge — the host adapts its store onto these verbs).
218    pub fn with_oauth_store(mut self, store: Arc<dyn OAuthCredentialStore>) -> Self {
219        self.oauth_store = Some(store);
220        self
221    }
222    // END CUSTOM
223
224    /// Build the module with configured dependencies
225    pub fn build(self) -> anyhow::Result<IntegrationsModule> {
226        let db_pool = self.db_pool
227            .ok_or_else(|| anyhow::anyhow!("Database pool not configured"))?;
228
229        // IntegrationConnector service
230        let integration_connector_repository = Arc::new(IntegrationConnectorRepository::new(db_pool.clone()));
231        let integration_connector_service = Arc::new(IntegrationConnectorService::with_repository(integration_connector_repository.clone()));
232
233        // IntegrationAccount service
234        let integration_account_repository = Arc::new(IntegrationAccountRepository::new(db_pool.clone()));
235        let integration_account_service = Arc::new(IntegrationAccountService::with_repository(integration_account_repository.clone()));
236
237        // IntegrationEvent service
238        let integration_event_repository = Arc::new(IntegrationEventRepository::new(db_pool.clone()));
239        let integration_event_service = Arc::new(IntegrationEventService::with_repository(integration_event_repository.clone()));
240
241        // <<< CUSTOM
242        // IntegrationsWrite service — the hand-authored receive/retry/map path; constructed alongside the
243        // generated CRUD services so the module ships its whole public surface from the builder.
244        let integrations_write_service = Arc::new(IntegrationsWriteService::new(db_pool.clone()));
245        // The one OAuth generation. Constructed only when composition opted in; a partial opt-in
246        // (config without both ports) is a build error, and IntegrationsOauthService::build
247        // re-validates everything fail-closed: the named env var must hold the state-signing key,
248        // public_base must be present, and every endpoint override must pass the guard.
249        let integrations_oauth = match (self.oauth_config, self.oauth_transport, self.oauth_store) {
250            (Some(config), transport, Some(store)) => {
251                let transport = match transport {
252                    Some(t) => t,
253                    None => Arc::new(ReqwestOAuthTransport::new()
254                        .map_err(|e| anyhow::anyhow!("building the default OAuth transport: {e}"))?),
255                };
256                Some(Arc::new(IntegrationsOauthService::build(
257                    db_pool.clone(),
258                    config,
259                    transport,
260                    store,
261                )?))
262            }
263            (Some(_), _, None) => {
264                return Err(anyhow::anyhow!(
265                    "with_oauth needs the credential store bound through the port: with_oauth_store(..)"
266                ))
267            }
268            (None, _, _) => None,
269        };
270        // END CUSTOM
271
272        Ok(IntegrationsModule {
273            integration_connector_service,
274            integration_account_service,
275            integration_event_service,
276            // <<< CUSTOM
277            integrations_write_service,
278            integrations_oauth,
279            // END CUSTOM
280        })
281    }
282}
283
284impl Default for IntegrationsModuleBuilder {
285    fn default() -> Self {
286        Self::new()
287    }
288}