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 violation;
82pub mod write_guard;
83pub mod row_rule;
84pub mod actor_roles;
85pub mod usecase;
86pub mod validation;
87pub mod policy;
88pub mod bulk;
89pub mod integration;
90pub mod cqrs;
91pub mod graphql;
92
93// Category C generic base traits — Phase 0 extension for trigger/flow/projection
94pub mod trigger;
95pub mod flow;
96pub mod projection;
97pub mod state_machine;
98
99/// OpenAPI/Swagger schema generation (feature `openapi`).
100#[cfg(feature = "openapi")]
101pub mod openapi;
102
103pub use trigger::{
104    TriggerHandler, TriggerEvent, TriggerContext, TriggerContextMut,
105    ActionExecutor, TriggerRegistry,
106};
107
108// Re-export core types for convenience
109pub use entity::*;
110pub use repository::*;
111pub use grpc::*;
112pub use builder::*;
113
114// Configuration exports
115pub use config::{
116    BackboneConfig, ConfigError, ConfigResult, ConfigLoader,
117    // App config
118    AppConfig, Environment,
119    // Server config
120    ServerConfig,
121    // Database config
122    DatabaseConfig, CacheConfig,
123    // Module configs
124    ModulesConfig, SapiensConfig, PostmanConfig, BucketConfig,
125    SapiensAuthConfig, PasswordHasherConfig, SapiensLockoutConfig,
126    SmtpConfig, TemplatesConfig, StorageConfig,
127    // Logging config
128    LoggingConfig, LoggingFileConfig,
129    // Monitoring config
130    MonitoringConfig,
131    // Context config
132    ContextsConfig, RedisEventBusConfig,
133    // Features config
134    FeaturesConfig, RateLimitingConfig,
135    // Security config
136    SecurityConfig, CsrfConfig, SecurityHeadersConfig,
137    // Configuration Bus for cross-module config sharing
138    ConfigurationBus, ConfigValue, ConfigChangeEvent,
139};
140
141// HTTP module exports - primary API for generic CRUD
142pub use http::{
143    // Core generic CRUD components
144    CrudService,
145    BackboneCrudHandler,
146    BackboneHttpHandler,
147    // Field-level security scope (injected by the app's auth middleware)
148    AccessScope,
149    // Response types
150    ApiResponse,
151    PaginatedResponse,
152    PaginatedApiResponse,
153    PaginationResponse,
154    BulkResponse,
155    BulkCreateRequest,
156    // Request types
157    ListQueryParams,
158    ListRequest,
159    UpsertRequest,
160    FilterOptions,
161    SortOrder,
162    BatchIdsRequest,
163    BulkUpdateItem,
164    BulkPatchItem,
165    BulkPatchRequest,
166    // Legacy
167    PaginationRequest,
168};
169
170// OpenAPI component template (feature `openapi`)
171#[cfg(feature = "openapi")]
172pub use openapi::BackboneComponents;
173
174// Utility exports
175pub use utils::{
176    BackboneError, PaginationParams, PaginationMeta as BackbonePaginationMeta,
177    now, days_ago, days_from_now, hours_ago, hours_from_now, minutes_from_now,
178    new_id, new_id_string, parse_id, is_valid_uuid,
179    is_valid_email, is_valid_username, normalize_string,
180};
181
182// Persistence layer exports - Generic repositories
183pub use persistence::{
184    // Core traits
185    CrudRepository, PersistentEntity, RepositoryError, PartialUpdatable, SearchableRepository, Versioned,
186    // In-memory repository (always available)
187    InMemoryRepository,
188    // Adapters for bridging Repository to CrudService
189    CrudServiceAdapter, SimpleCrudServiceAdapter, AdapterError,
190};
191
192// Specification pattern exports - DDD business rules
193pub use specification::{
194    // Core trait
195    Specification,
196    // Composite specifications
197    AndSpecification, OrSpecification, NotSpecification,
198    // Result and evaluator
199    SpecificationResult, SpecificationEvaluator,
200    // Common specifications
201    AlwaysTrue, AlwaysFalse, PredicateSpecification,
202    // Helper function
203    predicate,
204};
205
206// PostgreSQL exports (requires "postgres" feature)
207#[cfg(feature = "postgres")]
208pub use persistence::{PostgresRepository, PostgresRepositoryBuilder, PostgresEntity};
209
210// Service Registry exports - Module service discovery
211pub use registry::{
212    // Core trait
213    ModuleService,
214    // Registry
215    ServiceRegistry,
216    // Health types
217    ServiceHealth, HealthStatus, RegistryHealth, RegistryStatistics,
218    // Metadata
219    ServiceDescriptor,
220};
221
222// Module System exports - Laravel-style service provider pattern
223pub use module::{
224    BackboneModule,
225    MigrationInfo,
226    SeedInfo,
227};
228
229pub use module_registry::{
230    ModuleRegistry,
231    ModuleRegistryError,
232    ModuleRegistryResult,
233};
234
235// DDD Pattern exports - Domain-Driven Design traits
236pub use domain_service::{DomainService, TransactionalDomainService};
237
238pub use command::{Command, CommandHandler, CommandDispatcher, ValidatableCommand, ValidatingCommandHandler};
239
240pub use query::{
241    Query, QueryHandler, QueryDispatcher,
242    CacheableQuery, PaginatedQuery, PaginatedQueryResult,
243};
244
245pub use value_object::{ValueObject, OptionalValueObject, ValueObjectError};
246
247pub use aggregate::{AggregateRoot, EventSourcedAggregate, InvariantAggregate, AggregateMetadata};
248
249pub use error::{ModuleError, ErrorCategory, ErrorResponse, CommonError};
250
251// Generic base layer re-exports
252pub use violation::{code_from_constraint, Violation};
253pub use write_guard::{AllowAll, GuardOutcome, WriteCtx, WriteGuard, WriteKind};
254pub use service::{
255    GenericCrudService, ServiceError, ServiceResult,
256    FromCreateDto, ApplyUpdateDto, ServiceLifecycle, NoOpLifecycle,
257};
258
259pub use usecase::{
260    UseCaseError, UseCaseResult,
261    UseCaseHooks, DefaultHooks,
262    UseCaseService, EntityFactory, EntityUpdater,
263    CreateUseCase, UpdateUseCase, GetUseCase, DeleteUseCase,
264    ListUseCase, ListParams, ListResult, ListService,
265};
266
267pub use validation::{
268    ValidationError, ValidationErrors, FieldRule, EntityValidator,
269    RequiredString, MaxLength, NonNegative, OptionalNotBlank, Regex, RequiredUuid,
270};
271
272pub use policy::{
273    PolicyContext, PolicyOutcome, PolicyDecision, DomainPolicy,
274    PermitAllPolicy, DenyAllPolicy,
275    AllOfPolicy, AnyOfPolicy, NotPolicy,
276};
277
278pub use bulk::{
279    BulkFailureMode, BulkOperationConfig, BulkItemResult, BulkOperationResult,
280    BulkOperationProgress, BulkCapableService, GenericBulkService,
281};
282
283pub use integration::{
284    ModuleAdapter, ProjectionAdapter, IntegrationError,
285    EventBridge, IdentityAdapter, identity_adapter,
286};
287
288pub use cqrs::{
289    // Commands
290    GenericCreateCommand, GenericUpdateCommand, GenericDeleteCommand, GenericRestoreCommand,
291    // Queries
292    GenericGetQuery, GenericListQuery, GenericListDeletedQuery,
293    // Handlers
294    GenericCommandHandler, GenericQueryHandler,
295    // Service contracts
296    CqrsService, CqrsReadService,
297};
298
299pub use graphql::{
300    GenericGraphQLResolver, GraphQLCapableService,
301    GraphQLListResult, GraphQLPaginationInput,
302};
303
304// grpc module already fully re-exported via `pub use grpc::*` above.
305// GenericGrpcService, GrpcCapableService and all gRPC types are available at crate root.
306
307/// Core version
308pub const VERSION: &str = env!("CARGO_PKG_VERSION");
309
310/// The 11 standard Backbone endpoints that are auto-generated for each entity:
311/// 1. GET /api/v1/{collection} - List (paginated, filtered, sorted)
312/// 2. POST /api/v1/{collection} - Create
313/// 3. GET /api/v1/{collection}/:id - Get by ID
314/// 4. PUT /api/v1/{collection}/:id - Full update
315/// 5. PATCH /api/v1/{collection}/:id - Partial update
316/// 6. DELETE /api/v1/{collection}/:id - Soft delete
317/// 7. POST /api/v1/{collection}/bulk - Bulk create
318/// 8. POST /api/v1/{collection}/upsert - Upsert
319/// 9. GET /api/v1/{collection}/trash - List deleted
320/// 10. POST /api/v1/{collection}/:id/restore - Restore
321/// 11. DELETE /api/v1/{collection}/empty - Empty trash
322pub const STANDARD_ENDPOINTS: [&str; 11] = [
323    "GET /api/v1/{collection}",
324    "POST /api/v1/{collection}",
325    "GET /api/v1/{collection}/:id",
326    "PUT /api/v1/{collection}/:id",
327    "PATCH /api/v1/{collection}/:id",
328    "DELETE /api/v1/{collection}/:id",
329    "POST /api/v1/{collection}/bulk",
330    "POST /api/v1/{collection}/upsert",
331    "GET /api/v1/{collection}/trash",
332    "POST /api/v1/{collection}/:id/restore",
333    "DELETE /api/v1/{collection}/empty",
334];