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// <<< CUSTOM MODULES
28// The hand-authored write path: receive an inbound provider event idempotently and map it via TargetPort,
29// plus the port + receiver types a composing service needs to wire the seam from one place.
30pub use application::service::IntegrationsWriteService;
31pub use application::service::{TargetPort, MapRequest, MapOutcome, MapRejected, MappedRef};
32pub use application::service::{InboundEvent, ReceiveOutcome, NewConnector, FailedEvent, IntegrationError};
33pub use application::service::{IntegrationEvent, IntegrationEventMapped, IntegrationEventSink, LoggingSink};
34// The OAuth credential port (ADR-0024 amendment: the store is reached through a port, never a
35// Cargo edge) — the types a composing host needs to bind the credential store for the OAuth flow.
36pub use application::service::{OAuthCredentialFailure, OAuthCredentialStore, PURPOSE_OAUTH_TOKEN, TokenBundle, TokenMetadata};
37// The one OAuth generation: the service + config a composing host binds (with the two ports it
38// runs on), and the outbound endpoint-guard surface its transport belongs to.
39pub use application::service::{
40 AccountStatus, AuthorizeRequest, AuthorizeResponse, CompleteOutcome, CompleteRequest,
41 IntegrationsOauthConfig, IntegrationsOauthService, OauthError, RefreshSummary,
42 STATE_TTL_SECONDS,
43};
44pub use infrastructure::http::{OAuthTransport, ReqwestOAuthTransport};
45// END CUSTOM
46
47// Re-exports - Infrastructure
48pub use infrastructure::persistence::*;
49
50// Re-exports - Application services
51pub use application::service::IntegrationConnectorService;
52pub use application::service::IntegrationAccountService;
53pub use application::service::IntegrationEventService;
54
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 BUILDER FIELDS
173 // OAuth generation fields (the one flow's construction inputs)
174 oauth_config: Option<IntegrationsOauthConfig>,
175 oauth_transport: Option<Arc<dyn OAuthTransport>>,
176 oauth_store: Option<Arc<dyn OAuthCredentialStore>>,
177 // END CUSTOM
178}
179
180impl IntegrationsModuleBuilder {
181 /// Create a new builder
182 pub fn new() -> Self {
183 Self {
184 db_pool: None,
185 // <<< CUSTOM BUILDER DEFAULTS
186 oauth_config: None,
187 oauth_transport: None,
188 oauth_store: None,
189 // END CUSTOM
190 }
191 }
192
193 /// Set the database connection pool
194 pub fn with_database(mut self, pool: PgPool) -> Self {
195 self.db_pool = Some(pool);
196 self
197 }
198
199 // <<< CUSTOM - custom builder methods
200 /// Opt the module into the one OAuth generation. The config carries the
201 /// deployment's public base, per-provider clients, and endpoint overrides
202 /// — every override passes the endpoint guard at build time (a bad one
203 /// fails the build), and the state-signing key is read from the
204 /// environment variable the config names (never a file value).
205 pub fn with_oauth(mut self, config: IntegrationsOauthConfig) -> Self {
206 self.oauth_config = Some(config);
207 self
208 }
209
210 /// The outbound OAuth transport (token exchange + server-side identity
211 /// read). Defaults to [`ReqwestOAuthTransport`] when omitted.
212 pub fn with_oauth_transport(mut self, transport: Arc<dyn OAuthTransport>) -> Self {
213 self.oauth_transport = Some(transport);
214 self
215 }
216
217 /// Bind the credential store through the port (ADR-0024 amendment: no
218 /// Cargo edge — the host adapts its store onto these verbs).
219 pub fn with_oauth_store(mut self, store: Arc<dyn OAuthCredentialStore>) -> Self {
220 self.oauth_store = Some(store);
221 self
222 }
223 // END CUSTOM
224
225 /// Build the module with configured dependencies
226 pub fn build(self) -> anyhow::Result<IntegrationsModule> {
227 let db_pool = self.db_pool
228 .ok_or_else(|| anyhow::anyhow!("Database pool not configured"))?;
229
230 // IntegrationConnector service
231 let integration_connector_repository = Arc::new(IntegrationConnectorRepository::new(db_pool.clone()));
232 let integration_connector_service = Arc::new(IntegrationConnectorService::with_repository(integration_connector_repository.clone()));
233
234 // IntegrationAccount service
235 let integration_account_repository = Arc::new(IntegrationAccountRepository::new(db_pool.clone()));
236 let integration_account_service = Arc::new(IntegrationAccountService::with_repository(integration_account_repository.clone()));
237
238 // IntegrationEvent service
239 let integration_event_repository = Arc::new(IntegrationEventRepository::new(db_pool.clone()));
240 let integration_event_service = Arc::new(IntegrationEventService::with_repository(integration_event_repository.clone()));
241
242 // <<< CUSTOM
243 // IntegrationsWrite service — the hand-authored receive/retry/map path; constructed alongside the
244 // generated CRUD services so the module ships its whole public surface from the builder.
245 let integrations_write_service = Arc::new(IntegrationsWriteService::new(db_pool.clone()));
246 // The one OAuth generation. Constructed only when composition opted in; a partial opt-in
247 // (config without both ports) is a build error, and IntegrationsOauthService::build
248 // re-validates everything fail-closed: the named env var must hold the state-signing key,
249 // public_base must be present, and every endpoint override must pass the guard.
250 let integrations_oauth = match (self.oauth_config, self.oauth_transport, self.oauth_store) {
251 (Some(config), transport, Some(store)) => {
252 let transport = match transport {
253 Some(t) => t,
254 None => Arc::new(ReqwestOAuthTransport::new()
255 .map_err(|e| anyhow::anyhow!("building the default OAuth transport: {e}"))?),
256 };
257 Some(Arc::new(IntegrationsOauthService::build(
258 db_pool.clone(),
259 config,
260 transport,
261 store,
262 )?))
263 }
264 (Some(_), _, None) => {
265 return Err(anyhow::anyhow!(
266 "with_oauth needs the credential store bound through the port: with_oauth_store(..)"
267 ))
268 }
269 (None, _, _) => None,
270 };
271 // END CUSTOM
272
273 Ok(IntegrationsModule {
274 integration_connector_service,
275 integration_account_service,
276 integration_event_service,
277 // <<< CUSTOM
278 integrations_write_service,
279 integrations_oauth,
280 // END CUSTOM
281 })
282 }
283}
284
285impl Default for IntegrationsModuleBuilder {
286 fn default() -> Self {
287 Self::new()
288 }
289}