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