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