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