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