toolkit/lib.rs
1#![cfg_attr(coverage_nightly, feature(coverage_attribute))]
2//! # `ToolKit` - Declarative Gear System
3//!
4//! A unified crate for building modular applications with declarative gear definitions.
5//!
6//! ## Features
7//!
8//! - **Declarative**: Use `#[gear(...)]` attribute to declare gears
9//! - **Auto-discovery**: Gears are automatically discovered via inventory
10//! - **Type-safe**: Compile-time validation of capabilities
11//! - **Phase-based lifecycle**: executed by `HostRuntime` (see `runtime/host_runtime.rs` docs)
12//!
13//! ## Golden Path: Stateless Handlers
14//!
15//! For optimal performance and readability, prefer stateless handlers that receive
16//! `Extension<T>` and other extractors rather than closures that capture environment.
17//!
18//! ### Recommended Pattern
19//!
20//! ```rust,ignore
21//! use axum::{Extension, Json};
22//! use toolkit::api::{OperationBuilder, Problem};
23//! use std::sync::Arc;
24//!
25//! async fn list_users(
26//! Extension(svc): Extension<Arc<UserService>>,
27//! ) -> Result<Json<Vec<UserDto>>, Problem> {
28//! let users = svc.list_users().await.map_err(Problem::from)?;
29//! Ok(Json(users))
30//! }
31//!
32//! pub fn router(service: Arc<UserService>) -> axum::Router {
33//! let op = OperationBuilder::get("/users-info/v1/users")
34//! .summary("List users")
35//! .handler(list_users)
36//! .json_response(200, "List of users")
37//! .standard_errors(®istry);
38//!
39//! axum::Router::new()
40//! .route("/users-info/v1/users", axum::routing::get(list_users))
41//! .layer(Extension(service))
42//! .layer(op.to_layer())
43//! }
44//! ```
45//!
46//! ### Benefits
47//!
48//! - **Performance**: No closure captures or cloning on each request
49//! - **Readability**: Clear function signatures show exactly what data is needed
50//! - **Testability**: Easy to unit test handlers with mock state
51//! - **Type Safety**: Compile-time verification of dependencies
52//! - **Flexibility**: Individual service injection without coupling
53//!
54//! ## Basic Gear Example
55//!
56//! ```rust,ignore
57//! use toolkit::{gear, Gear, DbGear, RestfulGear, StatefulGear};
58//!
59//! #[derive(Default)]
60//! #[gear(name = "user", deps = ["database"], capabilities = [db, rest, stateful])]
61//! pub struct UserGear;
62//!
63//! // Implement the declared capabilities...
64//! ```
65
66// When running tests, make ::toolkit resolve to this crate so macros work
67#[cfg(test)]
68extern crate self as toolkit;
69
70pub use anyhow::Result;
71pub use async_trait::async_trait;
72
73// Re-export inventory for user convenience
74pub use inventory;
75
76// Gear system exports
77pub use crate::contracts::*;
78pub use crate::contracts::{GrpcServiceCapability, RegisterGrpcServiceFn};
79
80// Configuration gear
81pub mod config;
82pub use config::{ConfigError, ConfigProvider, gear_config_or_default, gear_config_required};
83
84// Context gear
85pub mod context;
86pub use context::{GearContextBuilder, GearCtx};
87
88// Gear system implementations for macro code
89pub mod client_hub;
90pub mod registry;
91
92// Re-export main types
93pub use client_hub::ClientHub;
94pub use registry::GearRegistry;
95
96// Re-export the macros from the proc-macro crate
97pub use toolkit_macros::{ExpandVars, gear, lifecycle};
98
99// Re-export var_expand gear so derive-generated impls resolve via ::toolkit::var_expand
100pub use toolkit_utils::var_expand;
101
102// Core gear contracts and traits
103pub mod contracts;
104// Type-safe API operation builder
105pub mod api;
106pub use api::{
107 IntoCanonical, OpenApiInfo, OpenApiRegistry, OpenApiRegistryImpl, OperationBuilder,
108 error_mapping_middleware,
109};
110pub use toolkit_odata::{Page, PageInfo};
111
112// HTTP utilities
113pub mod http;
114pub use http::sse::SseBroadcaster;
115
116// Telemetry utilities
117pub mod telemetry;
118
119pub mod backends;
120pub mod lifecycle;
121pub mod plugins;
122pub mod runtime;
123
124// Domain layer marker traits for DDD enforcement
125pub mod domain;
126pub use domain::{DomainErrorMarker, DomainModel};
127
128// Directory API for service discovery
129pub mod directory;
130pub use directory::{
131 DirectoryClient, LocalDirectoryClient, RegisterInstanceInfo, ServiceEndpoint,
132 ServiceInstanceInfo,
133};
134
135// GTS schema support
136pub mod gts;
137
138// Security context scoping wrapper (re-exported from toolkit-sdk)
139pub use toolkit_sdk::{Secured, WithSecurityContext};
140
141pub use backends::{
142 BackendKind, GearRuntimeBackend, InstanceHandle, LocalProcessBackend, OopBackend,
143 OopGearConfig, OopSpawnConfig,
144};
145pub use lifecycle::{Lifecycle, Runnable, Status, StopReason, WithLifecycle};
146pub use plugins::GtsPluginSelector;
147pub use runtime::{
148 DEFAULT_SHUTDOWN_DEADLINE, DbOptions, Endpoint, GearInstance, GearManager, OopGearSpawnConfig,
149 OopSpawnOptions, RunOptions, ShutdownOptions, run,
150};
151
152#[cfg(feature = "bootstrap")]
153pub mod bootstrap;