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