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