Skip to main content

webx/
lib.rs

1//! Umbrella crate for the rust-webx framework (package `rust-webx`, imported as
2//! `webx`).
3//!
4//! Re-exports the whole framework so applications need a single dependency:
5//!
6//! ```toml
7//! [dependencies]
8//! rust-webx = "0.7"
9//! ```
10//!
11//! ```ignore
12//! use webx::*;
13//! ```
14//!
15//! The dependency name is `rust-webx`; the import name is `webx`. The same
16//! applies to the sub-crates (`rust-webx-core` → `webx_core`,
17//! `rust-webx-host` → `webx_host`, `rust-webx-macros` → `webx_macros`,
18//! `rust-webx-spa` → `webx_spa`, `rust-webx-openapi` → `webx_openapi`).
19
20// --- Core traits ---
21pub use webx_core::app::IHost;
22pub use webx_core::auth::{
23    CurrentUser, IAuthenticationHandler, IAuthorizationPolicy, IClaims, IDynamicAuthorizer,
24    RequestUser,
25};
26pub use webx_core::cache::{
27    cache_ext::DistributedCacheExtensions,
28    options::DistributedCacheEntryOptions,
29    trait_def::{CacheError, IDistributedCache},
30};
31pub use webx_core::config::{
32    bind_config, bind_root, load_appsettings, AppOptions, AppSection, CorsSection, CultureSection,
33    IAppOptions, JwtSection, MetricsSection, RateLimitSection, TlsSection,
34};
35pub use webx_core::dispatch_runtime::{dispatch_provider, DispatchRuntime};
36pub use webx_core::error::{Error, Result};
37pub use webx_core::form::{
38    sanitize_file_name, set_spool_root, spool_root, FormField, FormFile, FormFileBuilder,
39    MultipartForm, SPOOL_FILE_PREFIX,
40};
41pub use webx_core::handler::{IClaimsCarrier, IEventHandler, IHostedService, IRequestHandler};
42pub use webx_core::http::{
43    content_disposition_value, read_json_body, write_json_response, ByteRange, Disposition,
44    FileBody, FileSource, HttpStatus, IClaimsExt, IHttpContext, IHttpRequest, IHttpResponse, Json,
45    ResponseBody, SeekableReader, STREAM_BUF_SIZE,
46};
47pub use webx_core::localization::{
48    IStringLocalizer, LocalizationOptions, LocalizedString, StringLocalizer, TextRef,
49};
50pub use webx_core::mediator::build_pipeline_chain;
51pub use webx_core::mediator::{IEventRequest, IMediator, IRequest};
52pub use webx_core::middleware::IMiddleware;
53pub use webx_core::mode::AppMode;
54pub use webx_core::pagination::{PagedRequest, PagedResponse};
55pub use webx_core::paths::{
56    app_base, framework_root, looks_like_app_base, looks_like_framework_root,
57};
58pub use webx_core::pipeline::{BoxedNextFn, BoxedPipelineFuture, IPipelineBehavior};
59pub use webx_core::problem::{FieldError, ProblemDetails};
60pub use webx_core::request_context::RequestContext;
61pub use webx_core::route::catalog::{
62    EndpointCatalog, EndpointDescriptor, EndpointInfo, IEndpointCatalog,
63};
64pub use webx_core::route::diagnostics::{
65    duplicate_handlers, format_route_diagnostics, orphan_handlers, orphan_route_details,
66    orphan_routes, route_snapshots,
67};
68pub use webx_core::routing::{HttpMethod, IEndpoint, IRouter, RouteMeta};
69
70// --- DI extensions ---
71pub use webx_core::route::binding;
72pub use webx_core::route::binding::RequestModel;
73pub use webx_core::route::ext::{is_mediator_active, should_scan_endpoints, IServiceCollectionExt};
74#[allow(deprecated)]
75pub use webx_core::route::scan::{
76    global_provider, set_global_provider, AuthorizeRule, HandlerCache, HandlerEntry,
77    HandlerRegistration, HandlerRegistry, ParamMeta, RequestParamEntry, ResponseData,
78    RouteDispatch, RouteDispatchFn, RouteEntry,
79};
80
81// --- HTTP layer ---
82pub use webx_host::auth_jwt::{init_jwt_secret, jwt_middleware, jwt_secret, JwtAuth, JwtClaims};
83#[allow(deprecated)]
84pub use webx_host::authz::{
85    build_resource_policy_from_routes, collect_authorizers, resource_auth_middleware,
86    AuthorizerSet, ResourceAuthorization,
87};
88pub use webx_host::compression::{compress_gzip, CompressionConfig, CompressionMiddleware};
89pub use webx_host::context::{HttpContext, HttpRequest, HttpResponse};
90pub use webx_host::cors::{CorsConfig, CorsMiddleware};
91pub use webx_host::diagnostics::log_startup_diagnostics;
92pub use webx_host::endpoint::{
93    ControllerEndpoint, RequestEndpoint, StaticHtmlEndpoint, StaticJsonEndpoint,
94};
95pub use webx_host::health::{HealthCheckEntry, HealthCheckFn, HealthCheckRegistry, HealthStatus};
96pub use webx_host::memory_cache::MemoryCache;
97pub use webx_host::pipeline::{HandlerFn, MiddlewarePipeline};
98pub use webx_host::rate_limit::{RateLimitMiddleware, RateLimiter};
99pub use webx_host::request_id::RequestIdMiddleware;
100pub use webx_host::request_tracing::RequestTracing;
101pub use webx_host::router::Router;
102pub use webx_host::security_headers::SecurityHeadersMiddleware;
103pub use webx_host::server::{Host, HostAppBuilder, HostBuilder, Server, ServerHandle};
104#[cfg(feature = "testing")]
105pub use webx_host::testing::{free_port, spawn, spawn_with_health, wait_until_ready, TestServer};
106pub use webx_host::timing::TimingMiddleware;
107
108// --- Mediator ---
109pub use webx_core::mediator::Mediator;
110
111// --- Web (SPA) ---
112pub use webx_spa::SpaMiddleware;
113
114/// Static file hosting, including files compiled into the executable.
115///
116/// ```ignore
117/// // build.rs: webx::builder().web_root("wwwroot").build()
118/// #[webx::main(embed)]
119/// async fn main() {
120///     Host::builder().use_spa("wwwroot").build()
121/// }
122/// ```
123pub mod spa {
124    pub use webx_spa::{
125        embed_assets, inventory, ContentEncoding, EmbeddedAsset, EmbeddedAssets, SpaMiddleware,
126        SpaSource, EMBED_ENV,
127    };
128}
129
130/// Files compiled into the executable by `#[webx::main(embed)]`, read by path.
131///
132/// ```ignore
133/// let config = webx::assets::read_str("config/default.json");
134/// ```
135pub mod assets {
136    pub use webx_spa::assets::{read, read_str};
137}
138
139// --- OpenAPI ---
140pub use webx_openapi::{generate_openapi_spec, APIUI_HTML};
141
142// --- Macros ---
143#[doc(hidden)]
144pub use webx_macros::{__webx_category, __webx_description, __webx_display};
145pub use webx_macros::{
146    authorize, category, claims, delete, description, display, embed_assets, endpoint, get,
147    handler, main, post, put, WebxRequestMeta,
148};
149
150// --- Re-export rust_dix (for manual registration, #[inject] auto-registration, and module blocks) ---
151pub use rust_dix;
152pub use rust_dix::inject;
153pub use rust_dix::ScopeFactory;
154pub use rust_dix_macros;
155pub use rust_dix_macros::{module, Inject};
156
157// --- Re-export common dependencies ---
158pub use async_trait::async_trait;
159pub use hyper;
160/// Compile-time registration used by the derive macros.
161pub use inventory;
162pub use serde;
163pub use serde_json;
164pub use tokio;
165
166// =========================================================================
167// Convenience macro: register_handlers!
168//
169// **Deprecated for HTTP handlers.** HTTP dispatch uses inventory +
170// `HandlerCache` exclusively (`#[handler]` / `#[handler(inject)]`).
171// Keep this macro only for non-HTTP Mediator use or manual DI registration.
172//
173// Generates chained .singleton() calls for handlers that implement Default.
174//
175// Usage inside register():
176//   .register(|svc| {
177//       register_handlers!(svc,
178//           HelloRequest => String => HelloHandler,
179//           DeleteUserRequest => () => DeleteUserHandler,
180//       )
181//   })
182// =========================================================================
183#[deprecated(
184    since = "0.2.0",
185    note = "HTTP handlers should use `#[handler]` / `#[handler(inject)]` (inventory). \
186            register_handlers! remains for non-HTTP Mediator scenarios only."
187)]
188#[macro_export]
189macro_rules! register_handlers {
190    ($svc:ident, $($req:ty => $rsp:ty => $handler:ty),+ $(,)?) => {
191        $svc
192        $(
193            .singleton::<dyn $crate::IRequestHandler<$req, $rsp>>(
194                |_| ::std::sync::Arc::new(<$handler>::default())
195            )
196        )+
197    };
198}