Skip to main content

backbone_core/
lib.rs

1//! Backbone Framework Core
2//!
3//! Foundation for generic CRUD system with 11 standard endpoints.
4//! This is the core package that can be published and reused across projects.
5//!
6//! # Key Components
7//!
8//! - **`CrudService` trait**: Core async trait for entity CRUD operations
9//! - **`BackboneCrudHandler`**: Generic Axum router builder for all 11 endpoints
10//! - **`extractors::JsonOrForm`**: Body extractor that accepts JSON or
11//!   url-encoded form payloads; `BackboneCrudHandler` uses it so every generated
12//!   endpoint accepts both content types.
13//! - **Response types**: `ApiResponse`, `PaginatedResponse`, `BulkResponse`
14//! - **Utilities**: Timestamp, ID generation, pagination, validation
15//! - **Persistence**: Generic repositories for PostgreSQL and in-memory storage
16//!
17//! # Quick Start
18//!
19//! ## Option 1: Using BackboneCrudHandler (recommended)
20//!
21//! ```ignore
22//! use backbone_core::{CrudService, BackboneCrudHandler, ApiResponse};
23//!
24//! // 1. Implement CrudService for your entity
25//! impl CrudService<User, CreateUserDto, UpdateUserDto> for UserCrudService {
26//!     // ... implement all 11 methods
27//! }
28//!
29//! // 2. Create router with all 11 endpoints
30//! let routes = BackboneCrudHandler::<_, User, CreateUserDto, UpdateUserDto, UserResponse>
31//!     ::routes(Arc::new(user_crud), "/api/v1/users");
32//! ```
33//!
34//! ## Option 2: Using Generic Repositories
35//!
36//! ```ignore
37//! use backbone_core::persistence::{InMemoryRepository, PostgresRepository, CrudRepository};
38//!
39//! // For testing/prototyping
40//! let repo = InMemoryRepository::<User>::new();
41//!
42//! // For production (requires "postgres" feature)
43//! let repo = PostgresRepository::<User>::new(pool);
44//! ```
45
46// Macros must be declared before any items that use them.
47// `#[macro_export]` makes them available as `backbone_core::impl_crud_repository!`.
48pub mod macros;
49pub use macros::log_include_hydration_failure;
50
51/// Number of standard CRUD endpoints generated per entity
52pub const STANDARD_ENDPOINT_COUNT: usize = 12;
53
54pub mod config;
55pub mod crud;
56pub mod entity;
57pub mod repository;
58pub mod extractors;
59pub mod http;
60pub mod grpc;
61pub mod builder;
62pub mod utils;
63pub mod persistence;
64pub mod specification;
65pub mod registry;
66
67// Module system - Laravel-style service provider pattern
68pub mod module;
69pub mod module_registry;
70
71// DDD Pattern modules
72pub mod domain_service;
73pub mod command;
74pub mod query;
75pub mod value_object;
76pub mod aggregate;
77pub mod error;
78
79// Generic base layer — Phase 0 composition foundation
80pub mod service;
81pub mod usecase;
82pub mod validation;
83pub mod policy;
84pub mod bulk;
85pub mod integration;
86pub mod cqrs;
87pub mod graphql;
88
89// Category C generic base traits — Phase 0 extension for trigger/flow/projection
90pub mod trigger;
91pub mod flow;
92pub mod projection;
93pub mod state_machine;
94
95/// OpenAPI/Swagger schema generation (feature `openapi`).
96#[cfg(feature = "openapi")]
97pub mod openapi;
98
99pub use trigger::{
100    TriggerHandler, TriggerEvent, TriggerContext, TriggerContextMut,
101    ActionExecutor, TriggerRegistry,
102};
103
104// Re-export core types for convenience
105pub use entity::*;
106pub use repository::*;
107pub use grpc::*;
108pub use builder::*;
109
110// Configuration exports
111pub use config::{
112    BackboneConfig, ConfigError, ConfigResult, ConfigLoader,
113    // App config
114    AppConfig, Environment,
115    // Server config
116    ServerConfig,
117    // Database config
118    DatabaseConfig, CacheConfig,
119    // Module configs
120    ModulesConfig, SapiensConfig, PostmanConfig, BucketConfig,
121    SapiensAuthConfig, PasswordHasherConfig, SapiensLockoutConfig,
122    SmtpConfig, TemplatesConfig, StorageConfig,
123    // Logging config
124    LoggingConfig, LoggingFileConfig,
125    // Monitoring config
126    MonitoringConfig,
127    // Context config
128    ContextsConfig, RedisEventBusConfig,
129    // Features config
130    FeaturesConfig, RateLimitingConfig,
131    // Security config
132    SecurityConfig, CsrfConfig, SecurityHeadersConfig,
133    // Configuration Bus for cross-module config sharing
134    ConfigurationBus, ConfigValue, ConfigChangeEvent,
135};
136
137// HTTP module exports - primary API for generic CRUD
138pub use http::{
139    // Core generic CRUD components
140    CrudService,
141    BackboneCrudHandler,
142    BackboneHttpHandler,
143    // Field-level security scope (injected by the app's auth middleware)
144    AccessScope,
145    // Response types
146    ApiResponse,
147    PaginatedResponse,
148    PaginatedApiResponse,
149    PaginationResponse,
150    BulkResponse,
151    BulkCreateRequest,
152    // Request types
153    ListQueryParams,
154    ListRequest,
155    UpsertRequest,
156    FilterOptions,
157    SortOrder,
158    BatchIdsRequest,
159    BulkUpdateItem,
160    BulkPatchItem,
161    BulkPatchRequest,
162    // Legacy
163    PaginationRequest,
164};
165
166// OpenAPI component template (feature `openapi`)
167#[cfg(feature = "openapi")]
168pub use openapi::BackboneComponents;
169
170// Utility exports
171pub use utils::{
172    BackboneError, PaginationParams, PaginationMeta as BackbonePaginationMeta,
173    now, days_ago, days_from_now, hours_ago, hours_from_now, minutes_from_now,
174    new_id, new_id_string, parse_id, is_valid_uuid,
175    is_valid_email, is_valid_username, normalize_string,
176};
177
178// Persistence layer exports - Generic repositories
179pub use persistence::{
180    // Core traits
181    CrudRepository, PersistentEntity, RepositoryError, PartialUpdatable, SearchableRepository, Versioned,
182    // In-memory repository (always available)
183    InMemoryRepository,
184    // Adapters for bridging Repository to CrudService
185    CrudServiceAdapter, SimpleCrudServiceAdapter, AdapterError,
186};
187
188// Specification pattern exports - DDD business rules
189pub use specification::{
190    // Core trait
191    Specification,
192    // Composite specifications
193    AndSpecification, OrSpecification, NotSpecification,
194    // Result and evaluator
195    SpecificationResult, SpecificationEvaluator,
196    // Common specifications
197    AlwaysTrue, AlwaysFalse, PredicateSpecification,
198    // Helper function
199    predicate,
200};
201
202// PostgreSQL exports (requires "postgres" feature)
203#[cfg(feature = "postgres")]
204pub use persistence::{PostgresRepository, PostgresRepositoryBuilder, PostgresEntity};
205
206// Service Registry exports - Module service discovery
207pub use registry::{
208    // Core trait
209    ModuleService,
210    // Registry
211    ServiceRegistry,
212    // Health types
213    ServiceHealth, HealthStatus, RegistryHealth, RegistryStatistics,
214    // Metadata
215    ServiceDescriptor,
216};
217
218// Module System exports - Laravel-style service provider pattern
219pub use module::{
220    BackboneModule,
221    MigrationInfo,
222    SeedInfo,
223};
224
225pub use module_registry::{
226    ModuleRegistry,
227    ModuleRegistryError,
228    ModuleRegistryResult,
229};
230
231// DDD Pattern exports - Domain-Driven Design traits
232pub use domain_service::{DomainService, TransactionalDomainService};
233
234pub use command::{Command, CommandHandler, CommandDispatcher, ValidatableCommand, ValidatingCommandHandler};
235
236pub use query::{
237    Query, QueryHandler, QueryDispatcher,
238    CacheableQuery, PaginatedQuery, PaginatedQueryResult,
239};
240
241pub use value_object::{ValueObject, OptionalValueObject, ValueObjectError};
242
243pub use aggregate::{AggregateRoot, EventSourcedAggregate, InvariantAggregate, AggregateMetadata};
244
245pub use error::{ModuleError, ErrorCategory, ErrorResponse, CommonError};
246
247// Generic base layer re-exports
248pub use service::{
249    GenericCrudService, ServiceError, ServiceResult,
250    FromCreateDto, ApplyUpdateDto, ServiceLifecycle, NoOpLifecycle,
251};
252
253pub use usecase::{
254    UseCaseError, UseCaseResult,
255    UseCaseHooks, DefaultHooks,
256    UseCaseService, EntityFactory, EntityUpdater,
257    CreateUseCase, UpdateUseCase, GetUseCase, DeleteUseCase,
258    ListUseCase, ListParams, ListResult, ListService,
259};
260
261pub use validation::{
262    ValidationError, ValidationErrors, FieldRule, EntityValidator,
263    RequiredString, MaxLength, NonNegative, OptionalNotBlank, Regex, RequiredUuid,
264};
265
266pub use policy::{
267    PolicyContext, PolicyOutcome, PolicyDecision, DomainPolicy,
268    PermitAllPolicy, DenyAllPolicy,
269    AllOfPolicy, AnyOfPolicy, NotPolicy,
270};
271
272pub use bulk::{
273    BulkFailureMode, BulkOperationConfig, BulkItemResult, BulkOperationResult,
274    BulkOperationProgress, BulkCapableService, GenericBulkService,
275};
276
277pub use integration::{
278    ModuleAdapter, ProjectionAdapter, IntegrationError,
279    EventBridge, IdentityAdapter, identity_adapter,
280};
281
282pub use cqrs::{
283    // Commands
284    GenericCreateCommand, GenericUpdateCommand, GenericDeleteCommand, GenericRestoreCommand,
285    // Queries
286    GenericGetQuery, GenericListQuery, GenericListDeletedQuery,
287    // Handlers
288    GenericCommandHandler, GenericQueryHandler,
289    // Service contracts
290    CqrsService, CqrsReadService,
291};
292
293pub use graphql::{
294    GenericGraphQLResolver, GraphQLCapableService,
295    GraphQLListResult, GraphQLPaginationInput,
296};
297
298// grpc module already fully re-exported via `pub use grpc::*` above.
299// GenericGrpcService, GrpcCapableService and all gRPC types are available at crate root.
300
301/// Core version
302pub const VERSION: &str = env!("CARGO_PKG_VERSION");
303
304/// The 11 standard Backbone endpoints that are auto-generated for each entity:
305/// 1. GET /api/v1/{collection} - List (paginated, filtered, sorted)
306/// 2. POST /api/v1/{collection} - Create
307/// 3. GET /api/v1/{collection}/:id - Get by ID
308/// 4. PUT /api/v1/{collection}/:id - Full update
309/// 5. PATCH /api/v1/{collection}/:id - Partial update
310/// 6. DELETE /api/v1/{collection}/:id - Soft delete
311/// 7. POST /api/v1/{collection}/bulk - Bulk create
312/// 8. POST /api/v1/{collection}/upsert - Upsert
313/// 9. GET /api/v1/{collection}/trash - List deleted
314/// 10. POST /api/v1/{collection}/:id/restore - Restore
315/// 11. DELETE /api/v1/{collection}/empty - Empty trash
316pub const STANDARD_ENDPOINTS: [&str; 11] = [
317    "GET /api/v1/{collection}",
318    "POST /api/v1/{collection}",
319    "GET /api/v1/{collection}/:id",
320    "PUT /api/v1/{collection}/:id",
321    "PATCH /api/v1/{collection}/:id",
322    "DELETE /api/v1/{collection}/:id",
323    "POST /api/v1/{collection}/bulk",
324    "POST /api/v1/{collection}/upsert",
325    "GET /api/v1/{collection}/trash",
326    "POST /api/v1/{collection}/:id/restore",
327    "DELETE /api/v1/{collection}/empty",
328];