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