Skip to main content

serenade_framework/
lib.rs

1//! # Serenade
2//!
3//! Serenade is a Symfony-oriented application framework for Rust: a kernel with
4//! bundles, a dependency-injection container, an event dispatcher, layered
5//! configuration, and optional components (HTTP, security, messaging, views,
6//! forms, ...) that applications compose.
7//!
8//! `serenade-framework` is the public entry point for normal Serenade consumers.
9//! It re-exports a curated, stable surface of the `serenade-*` implementation
10//! crates. Those crates stay independently published and usable; the facade
11//! never owns their implementation.
12//!
13//! Website: <https://serenade.rs>. Guides: <https://docs.serenade.rs>.
14//!
15//! ```toml
16//! [dependencies]
17//! serenade = { package = "serenade-framework", version = "1.0.0" }
18//! ```
19//!
20//! The `package` rename imports the crate as `serenade` instead of
21//! `serenade_framework` (`cargo add serenade-framework --rename serenade`).
22//!
23//! The executable named `serenade` is shipped by the separate `serenade-cli`
24//! package. The crates.io package `serenade` is unrelated to this project.
25//!
26//! ## Features
27//!
28//! The default build contains only the framework foundations ([`kernel`],
29//! [`config`], [`di`], [`event`]). It needs no web server, database, Leptos,
30//! or Rangular.
31//!
32//! | Feature | Module | Enables |
33//! | --- | --- | --- |
34//! | *(default)* | [`kernel`], [`config`], [`di`], [`event`] | Foundations |
35//! | `console` | `console` | `serenade-console` |
36//! | `bundle` | `bundle` | `serenade-bundle` |
37//! | `http` | `http`, `http::client` | `serenade-http`, `serenade-http-client` |
38//! | `http-actix` | `http::actix` | `http` + `serenade-http-actix` |
39//! | `http-axum` | `http::axum` | `http` + `serenade-http-axum` |
40//! | `http-client-reqwest` | `http::client::ReqwestHttpClient` | Reqwest outbound client |
41//! | `session` | `session` | `serenade-session` |
42//! | `security` | `security` | `serenade-security` |
43//! | `security-oauth` / `security-ldap` | `security` | OAuth / LDAP helpers |
44//! | `validation` | `validator` | `serenade-validator` |
45//! | `lock` | `lock` | `serenade-lock` |
46//! | `rate-limiter` | `rate_limiter` | `serenade-rate-limiter` |
47//! | `scheduler` | `scheduler` | `serenade-scheduler` |
48//! | `scheduler-messenger` | `scheduler` | Scheduler dispatch through the message bus |
49//! | `messenger` | `messenger` | `serenade-messenger` |
50//! | `mailer` | `mailer` | `serenade-mailer` (no transport backend) |
51//! | `mailer-smtp` / `mailer-esp` | `mailer` | SMTP / ESP transports |
52//! | `notifier` | `notifier` | `serenade-notifier` |
53//! | `view` | `view` | `serenade-view` (engine neutral) |
54//! | `view-leptos-ssr` / `view-leptos-client` | `view` | Leptos SSR / hydrate support |
55//! | `form` | `form` | `view` + `serenade-form` |
56//!
57//! Integration features (`*-reqwest`, `*-smtp`, `*-esp`, `*-oauth`, `*-ldap`,
58//! `view-leptos-*`, `scheduler-messenger`) are never implied by their base
59//! feature.
60//!
61//! Crates outside this surface (for example `serenade-cache`,
62//! `serenade-workflow`, `serenade-translation`, `serenade-testing`) are used
63//! directly by depending on them.
64//!
65//! ## Example
66//!
67//! ```
68//! # extern crate serenade_framework as serenade;
69//! use serenade::prelude::*;
70//!
71//! struct Shop;
72//!
73//! impl BundleInterface for Shop {
74//!     fn name(&self) -> &'static str {
75//!         "shop"
76//!     }
77//! }
78//!
79//! let mut app = App::new(Environment::Test);
80//! app.register_bundle(Shop).expect("register");
81//! app.boot().expect("boot");
82//! assert_eq!(app.kernel().bundle_names(), vec!["shop"]);
83//! app.shutdown().expect("shutdown");
84//! ```
85
86/// Facade crate version (matches every `serenade-*` crate in the same release).
87#[must_use]
88pub const fn version() -> &'static str {
89    env!("CARGO_PKG_VERSION")
90}
91
92/// Application kernel, bundles, environment, and lifecycle.
93pub mod kernel {
94    pub use serenade_kernel::{
95        App, Application, Bundle, BundleInterface, BundleRegistry, Environment, Kernel,
96        KernelError, KernelPhase,
97    };
98}
99
100/// Layered configuration: dotenv, TOML/YAML packages, env overlays.
101pub mod config {
102    pub use serenade_config::{
103        Config, ConfigError, load_dotenv, load_packages, load_packages_for_env,
104    };
105}
106
107/// Dependency injection container.
108pub mod di {
109    pub use serenade_di::{
110        CompilePass, Container, ContainerBuilder, DiError, ParameterBag, Reference, Scope,
111        ServiceDefinition, ServiceFactory,
112    };
113}
114
115/// Synchronous event dispatcher.
116pub mod event {
117    pub use serenade_event::{
118        DISPATCHER_SERVICE, Event, EventDispatcher, EventError, EventSubscriber,
119        RecordingSubscriber, RegisterEventSubscribersPass, SUBSCRIBER_TAG, SubscriberService,
120        assert_dispatched,
121    };
122}
123
124/// Console application (`bin/console` analogue).
125#[cfg(feature = "console")]
126pub mod console {
127    pub use serenade_console::{
128        APPLICATION_SERVICE, AboutCommand, Application, COMMAND_TAG, Command, CommandService,
129        ConsoleError, DebugConfigCommand, DebugContainerCommand, Input, RegisterCommandsPass,
130    };
131}
132
133/// Bundle composition and framework bundle.
134#[cfg(feature = "bundle")]
135pub mod bundle {
136    pub use serenade_bundle::{
137        BundleError, CONFIG_SERVICE, Extension, FRAMEWORK_BUNDLE, FrameworkBundle,
138        FrameworkExtension, ROUTER_SERVICE, build_container,
139    };
140}
141
142/// Framework-agnostic HTTP foundation: request, response, routing, middleware, kernel.
143#[cfg(feature = "http")]
144pub mod http {
145    pub use serenade_http::{
146        AsyncFn, AsyncHealthMiddleware, AsyncHttpKernel, AsyncMiddleware, AsyncNext,
147        AsyncRequestHandler, AsyncRequestIdMiddleware, AttributeBag, BoxFuture,
148        DefaultExceptionHandler, ExceptionHandler, HEALTHZ_PATH, Headers, HealthMiddleware,
149        HttpCacheHeaders, HttpError, HttpKernel, MatchResult, Method, Middleware, READYZ_PATH,
150        REQUEST_ID_ATTRIBUTE, REQUEST_ID_HEADER, ROUTE_ATTRIBUTE, Readiness, Request,
151        RequestHandler, RequestIdMiddleware, Response, Route, RouteCollection, RouteLoader,
152        SyncToAsync, UrlMatcher, box_future, ensure_request_id, etag, healthz, load_routes,
153        maybe_not_modified, readyz, request_id, weak_etag,
154    };
155
156    /// Outbound HTTP client contract.
157    pub mod client {
158        #[cfg(feature = "http-client-reqwest")]
159        pub use serenade_http_client::ReqwestHttpClient;
160        pub use serenade_http_client::{
161            ClientMethod, ClientRequest, ClientResponse, DEFAULT_HTTP_CLIENT_SERVICE,
162            DynHttpClient, HTTP_CLIENT_TAG, HttpClient, HttpClientError, HttpClientService,
163            MockHttpClient, RegisterDefaultHttpClientPass,
164        };
165    }
166
167    /// Actix-web bridge.
168    #[cfg(feature = "http-actix")]
169    pub mod actix {
170        pub use serenade_http_actix::{
171            app, await_bound, bind_server, conversion_error, dispatch, dispatch_async, from_actix,
172            listen, to_actix,
173        };
174    }
175
176    /// Axum bridge.
177    #[cfg(feature = "http-axum")]
178    pub mod axum {
179        pub use serenade_http_axum::{
180            BoundServer, ShutdownHandle, await_bound, bind_server, conversion_error, dispatch,
181            dispatch_async, from_axum, listen, router, to_axum,
182        };
183    }
184}
185
186/// Session bag, stores, flash messages, and middleware.
187#[cfg(feature = "session")]
188pub mod session {
189    pub use serenade_session::{
190        AsyncSessionMiddleware, CookieSession, CookieSessionOptions, DEFAULT_SESSION_COOKIE,
191        FLASH_SESSION_KEY, FlashBag, MemorySessionStore, SESSION_ATTRIBUTE, SameSite, Session,
192        SessionError, SessionMiddleware, SessionStore, generate_session_id, parse_cookie_value,
193        request_session, request_session_mut,
194    };
195}
196
197/// Authentication, authorization, CSRF, and password hashing.
198#[cfg(feature = "security")]
199pub mod security {
200    pub use serenade_security::{
201        AccessDecisionManager, Argon2idPasswordHasher, AsyncSessionTokenMiddleware, Authenticator,
202        CSRF_FIELD_NAME, CsrfToken, CsrfTokenManager, FirewallMiddleware, HmacCsrfTokenManager,
203        InMemoryUser, PasswordHasher, RoleVoter, SECURITY_SESSION_KEY, SecurityError,
204        SessionTokenMiddleware, Subject, TOKEN_ATTRIBUTE, TokenInterface, UserInterface,
205        UsernamePasswordToken, Vote, Voter, login, logout, request_token, token_from_session,
206    };
207    #[cfg(feature = "security-oauth")]
208    pub use serenade_security::{
209        AuthorizationRequest, MockTokenExchanger, OAuthClientConfig, OAuthTokenResponse,
210        TokenExchanger, build_authorization_request, build_authorization_request_with,
211        decode_jwt_payload_json, parse_token_response, subject_from_id_token, token_exchange_form,
212        token_from_oidc_subject,
213    };
214    #[cfg(feature = "security-ldap")]
215    pub use serenade_security::{
216        LDAP_USERNAME_PLACEHOLDER, LdapAuthenticator, LdapBindConfig, LdapBinder, LdapIdentity,
217        MockLdapBinder, authenticate_ldap_password, split_user_password, token_from_ldap_identity,
218    };
219}
220
221/// Constraint validation for DTOs and commands.
222#[cfg(feature = "validation")]
223pub mod validator {
224    pub use serenade_validator::{
225        Constraint, ConstraintViolationList, Length, MessengerValidateHook, NotBlank, Range,
226        RecursiveValidator, Validatable, Validator, ValidatorError, Violation,
227    };
228}
229
230/// Named locks.
231#[cfg(feature = "lock")]
232pub mod lock {
233    pub use serenade_lock::{
234        DEFAULT_LOCK_STORE_SERVICE, DEFAULT_LOCK_TTL, FilesystemLockStore,
235        FilesystemLockStoreConfig, InMemoryLockStore, LOCK_STORE_TAG, Lock, LockError, LockFactory,
236        LockKey, LockStore, LockStoreService, RegisterDefaultLockPass, generate_lock_token,
237        validate_resource,
238    };
239}
240
241/// Rate limiting.
242#[cfg(feature = "rate-limiter")]
243pub mod rate_limiter {
244    pub use serenade_rate_limiter::{
245        ConsumeOrExceedError, DEFAULT_RATE_LIMITER_STORAGE_SERVICE, InMemoryRateLimiterStorage,
246        Policy, RATE_LIMITER_STORAGE_TAG, RateLimit, RateLimitExceeded, RateLimiter,
247        RateLimiterError, RateLimiterFactory, RateLimiterStorage, RateLimiterStorageService,
248        RegisterDefaultRateLimiterPass, WindowState, consume_or_exceed, require_accepted,
249        too_many_requests, validate_key,
250    };
251}
252
253/// Scheduling.
254#[cfg(feature = "scheduler")]
255pub mod scheduler {
256    #[cfg(feature = "scheduler-messenger")]
257    pub use serenade_scheduler::CommandOnDue;
258    pub use serenade_scheduler::{
259        Clock, DEFAULT_SCHEDULER_SERVICE, DueJob, FnScheduleHandler, HandlerMap, ManualClock,
260        RegisterDefaultSchedulerPass, RunSchedulerCommand, SCHEDULER_TAG, Schedule,
261        ScheduleHandler, Scheduler, SchedulerError, SchedulerService, SystemClock, Trigger,
262        validate_id,
263    };
264}
265
266/// Command and event message bus.
267#[cfg(feature = "messenger")]
268pub mod messenger {
269    pub use serenade_messenger::{
270        Command, CommandHandler, DispatchContext, DispatchKind, Envelope, Event, EventHandler,
271        InMemoryTransport, LogSink, LoggingMiddleware, Message, MessageBus, MessengerError,
272        Middleware, Transport, ValidateHook, ValidationMiddleware, WireEnvelope,
273    };
274}
275
276/// Email messages and transports.
277#[cfg(feature = "mailer")]
278pub mod mailer {
279    pub use serenade_mailer::{
280        Address, Attachment, Body, ContentDisposition, DEFAULT_MAILER_SERVICE, Email,
281        FileTransport, MAILER_TRANSPORT_TAG, MailerError, MailerService, MimePart, MimeTree,
282        NullTransport, RegisterDefaultMailerPass, Transport,
283    };
284    #[cfg(feature = "mailer-esp")]
285    pub use serenade_mailer::{
286        EspApiConfig, EspAuthScheme, EspHttpPoster, EspHttpResponse, EspHttpTransport,
287        MockEspHttpPoster, MockEspRequest, build_esp_payload,
288    };
289    #[cfg(feature = "mailer-smtp")]
290    pub use serenade_mailer::{SmtpTransport, SmtpTransportBuilder};
291}
292
293/// SMS and push notifications.
294#[cfg(feature = "notifier")]
295pub mod notifier {
296    pub use serenade_notifier::{
297        Channel, DEFAULT_NOTIFIER_SERVICE, MemoryTransport, NOTIFIER_TRANSPORT_TAG, Notification,
298        NotifierError, NotifierService, NullTransport, PushMessage, RegisterDefaultNotifierPass,
299        SmsMessage, SmsOnlyTransport, Transport,
300    };
301}
302
303/// HTML view helpers and document composition (template-engine neutral).
304#[cfg(feature = "view")]
305pub mod view {
306    pub use serenade_view::{
307        AssetConfig, DefaultDocumentTemplate, Document, DocumentAssets, DocumentParts,
308        DocumentTemplate, RenderedDocument, TRUNK_ASSET_MANIFEST_ENV, TRUNK_ASSET_MANIFEST_FILE,
309        TRUNK_DIST_DIRECTORY_ENV, TrunkAssetManifest, TrunkAssetReference, TrunkDocumentAsset,
310        TrunkPreloadReference, TrunkWasmBundle, ViewError, asset, escape_attr, escape_html,
311        partial, path,
312    };
313    #[cfg(feature = "view-leptos-ssr")]
314    pub use serenade_view::{DocumentSlot, LeptosExecutor, initialize_leptos_ssr};
315    #[cfg(any(feature = "view-leptos-client", feature = "view-leptos-ssr"))]
316    pub use serenade_view::{JsonLd, ManagedHead, ManagedLink, ManagedMeta, ManagedTitle};
317    #[cfg(not(target_arch = "wasm32"))]
318    pub use serenade_view::{STATIC_OUTPUT_DIR_ENV, StaticDocumentWriter};
319}
320
321/// HTML forms: binding, CSRF, rendering, multipart.
322#[cfg(feature = "form")]
323pub mod form {
324    pub use serenade_form::{
325        BoolToStringTransformer, COLLECTION_PROTOTYPE_INDEX, CSRF_FIELD_NAME, CheckboxOptions,
326        ChoiceEntry, ChoiceOptions, ChoiceToValueTransformer, CollectionEntryBuilder,
327        CollectionPrototypeMeta, CompoundBuilder, DEFAULT_MAX_FILE_SIZE,
328        DEFAULT_MAX_MULTIPART_BODY, DataTransformer, Field, FieldConfig, FieldKind, FileOptions,
329        FileStorage, Form, FormBuilder, FormError, FormStatus, HiddenOptions,
330        I64ToStringTransformer, MultipartData, NestedData, NumberOptions, PasswordOptions,
331        RenderedForm, TextOptions, TextareaOptions, UploadedFile, collection_field_name,
332        collection_indices, collection_prototype_field_name, escape_attr, escape_html, form_csrf,
333        form_errors, form_label, form_row, form_widget, is_multipart, join_multi,
334        multipart_boundary, parse_form_body, parse_multipart, parse_urlencoded,
335        parse_urlencoded_multi, split_multi, unflatten_form_data,
336    };
337}
338
339/// Common imports for application code built on the default feature set.
340pub mod prelude {
341    pub use crate::config::Config;
342    pub use crate::di::{Container, ContainerBuilder, ServiceDefinition};
343    pub use crate::event::{Event, EventDispatcher, EventSubscriber};
344    pub use crate::kernel::{App, Application, BundleInterface, Environment, Kernel, KernelPhase};
345}