laravel-rust 0.1.0

Laravel for Rust: a full-stack Rust web framework, inspired by PHP Laravel
Documentation
//! # Laravel for Rust
//!
//! A full-stack web framework for Rust.
//!
//! Most web applications need the same things: routing, validation, sessions, a database,
//! queues, mail, and tests that exercise them. Laravel provides them in one crate,
//! configured from the environment. This application serves a home page and a form handler
//! that redirects back to it:
//!
//! ```no_run
//! use std::process::ExitCode;
//!
//! use laravel::prelude::*;
//!
//! async fn home() -> &'static str {
//!     "Welcome to Laravel for Rust"
//! }
//!
//! #[derive(serde::Deserialize)]
//! struct Profile {
//!     name: Option<String>,
//! }
//!
//! async fn store(request: Request) -> laravel::Result<Redirect> {
//!     let name = request.parse::<Profile>()?.name.or_abort(422)?;
//!     // ...
//!     Ok(Redirect::route(home, ()))
//! }
//!
//! fn web(route: &mut Router) {
//!     route.get("/", home);
//!     route.post("/users", store);
//! }
//!
//! fn main() -> ExitCode {
//!     Application::configure()
//!         .with_routing(|routing, _| {
//!             routing.web(web);
//!         })
//!         .run()
//! }
//! ```
//!
//! An application starts with [`Application`], and the [`prelude`] imports the types and
//! traits most handlers use. The
//! [documentation](https://github.com/laravel/rust-framework/blob/0.x/docs/installation.md)
//! has a guide for each feature.
//!
//! Laravel is built on [Axum](https://docs.rs/axum). Handlers are Axum handlers, and any
//! Axum extractor or tower layer works. The crate re-exports [`axum`] for applications that need
//! to use Axum directly.
//!
//! # Features
//!
//! | Feature | Enables |
//! | --- | --- |
//! | `inertia` (default) | [Inertia](https://inertiajs.com) pages, in `laravel::inertia` |
//! | `minijinja` (default) | `.html` views in Jinja's syntax, rendered by MiniJinja |
//! | `database-sqlite`, `database-postgres`, `database-mysql` | Database connections for each driver, in `laravel::db`, and models in `laravel::model` |
//! | `redis` | Redis connections, in `laravel::redis`, and the `redis` cache store, session driver, and queue driver |
//! | `s3` | S3-compatible file storage |
//! | `sqs` | The `sqs` and `cloud` queue drivers |
//! | `ses` | The `ses` mail transport |
//! | `opentelemetry` | Trace export over OTLP, configured by the `OTEL_*` variables |
//! | `reverb` | The `reverb:start` command, which runs a Reverb server for local development |
//! | `search` | Full-text search over models, in `laravel::search`. It needs a database driver feature too |
//!
//! Enabling `database` without a driver feature is a compile error, so enable a driver feature
//! instead.

#![warn(missing_docs)]

extern crate self as laravel;

#[cfg(all(
    feature = "database",
    not(any(
        feature = "database-sqlite",
        feature = "database-postgres",
        feature = "database-mysql"
    ))
))]
compile_error!("enable a database driver feature: `database-sqlite`, `database-postgres` or `database-mysql`");

pub mod auth;
pub mod broadcast;
pub mod cache;
pub mod config;
pub mod console;
pub mod container;
pub mod context;
pub mod cookie;
pub mod crypt;
#[cfg(feature = "database")]
pub mod db;
pub mod embed;
pub mod errors;
pub mod event;
pub mod feature;
pub mod foundation;
pub mod hash;
pub mod head;
pub mod http;
#[cfg(feature = "inertia")]
pub mod inertia;
pub mod lottery;
pub mod mail;
#[cfg(feature = "database")]
pub mod model;
pub mod notification;
pub mod numeric;
pub mod pagination;
pub mod prelude;
pub mod process;
pub mod queue;
pub mod rate_limit;
#[cfg(feature = "redis")]
pub mod redis;
pub mod routing;
pub mod schedule;
#[cfg(feature = "search")]
pub mod search;
pub mod session;
pub mod slack;
pub mod sms;
pub mod storage;
pub mod str;
pub mod stream;
pub mod task;
pub mod testing;
pub mod time;
pub mod url;
pub mod validation;
pub mod view;
pub mod workflow;

#[cfg(test)]
mod tests;

pub use axum;
#[doc(hidden)]
pub use laravel_core::__inventory;
pub(crate) use laravel_core::*;

pub use crate::config::config;
#[doc(inline)]
pub use laravel_core::{
    Error, ErrorContext, OrAbort, Result, abort, abort_if, abort_unless, abort_with, now, once, once_for, report,
    resolve,
};
#[cfg(feature = "database")]
#[doc(hidden)]
pub use laravel_database::{__column_names, __db_values, __model_joined};
#[doc(hidden)]
pub use laravel_http::{__invalid, __view_data};
/// Embed a directory's files in the binary as an [`Embedded`](embed::Embedded).
///
/// The path is relative to the crate's `Cargo.toml`, as in `laravel::embed!("resources/views")`.
pub use laravel_rust_macros::embed;

/// Run a synchronous or asynchronous unit test, or an application test.
///
/// A test with no arguments runs without an application. A test that takes an
/// `Application` argument gets a new application, booted, and its helpers run in
/// that application's scope. The application comes from `app::testing::create`
/// by default. To use another factory, write `#[laravel::test(app = path::to::factory)]`. A test
/// that names a factory runs in its application's scope even without the argument, so it may leave
/// the argument out when it only calls functions such as `laravel::config()`.
///
/// Async tests run on a current-thread Tokio runtime. Return values and attributes
/// such as `#[should_panic]` and `#[ignore]` work as they do in ordinary Rust tests.
///
/// ```
/// #[laravel::test]
/// fn arithmetic() {
///     assert_eq!(2 + 2, 4);
/// }
///
/// #[laravel::test]
/// async fn asynchronous_work() -> laravel::Result<()> {
///     Ok(())
/// }
/// ```
///
/// ```no_run
/// use laravel::Application;
/// use laravel::testing::MakesHttpRequests;
/// # fn create() -> Application { Application::configure().create() }
///
/// #[laravel::test(app = create)]
/// async fn health_check(app: Application) {
///     app.get("/up").await.assert_ok();
/// }
/// ```
///
/// ```compile_fail
/// #[laravel::test]
/// async fn too_many_arguments(a: laravel::Application, b: laravel::Application) {}
/// ```
pub use laravel_rust_macros::test;

/// Declare a struct that a request fills.
///
/// The struct derives `Deserialize` and [`Validate`](crate::validation::Validate). With
/// `fills = Model`, it also derives [`Fill`](crate::model::Fill) with `#[fills(Model)]`. Each
/// [`Sometimes`](crate::validation::Sometimes) field gets `#[serde(default)]`, so deserializers
/// outside the framework, such as `serde_json`, also decode a missing field as `Missing`. The
/// struct's other attributes stay as written.
///
/// ```
/// use laravel::validation::{Sometimes, Valid};
///
/// #[laravel::input]
/// #[validate(anyone)]
/// pub struct EditProfile {
///     #[validate(required, max_length = 255)]
///     pub name: Sometimes<String>,
///     #[validate(max_length = 1000)]
///     pub bio: Sometimes<Option<String>>,
/// }
///
/// async fn update(Valid(input): Valid<EditProfile>) -> &'static str {
///     if input.bio.is_null() { "Removed the bio" } else { "Saved" }
/// }
///
/// let input: EditProfile = serde_json::from_str(r#"{"bio": null}"#).unwrap();
/// assert!(input.name.is_missing());
/// assert!(input.bio.is_null());
/// ```
pub use laravel_rust_http_macros::input;

/// Declare a struct that a request's query string fills.
///
/// The struct derives `Deserialize`, [`Validate`](crate::validation::Validate), and
/// [`QueryInput`](crate::http::QueryInput), so handlers may extract it with
/// [`Query<T>`](crate::http::Query) or read it with [`Request::query`](crate::http::Request::query).
///
/// Fields with a fallback (`Option<T>`, [`Sometimes<T>`](crate::validation::Sometimes),
/// `#[default]`, `#[default = expr]`, or `#[serde(default)]`) are lenient: missing, blank
/// (`?q=`), wrong-type (`?page=abc`), or rule-failing (`?page=0`) values fall back to `None`,
/// `Missing`, or their default. Fields without a fallback are required and fail with `400 Bad
/// Request` when missing or invalid.
///
/// ```
/// use laravel::prelude::*;
///
/// #[laravel::query]
/// pub struct Search {
///     #[default]
///     pub q: String,
///     #[default = 1]
///     #[validate(min_value = 1)]
///     pub page: u32,
///     pub tag: Option<String>,
/// }
///
/// async fn index(Query(search): Query<Search>) -> String {
///     format!("{} (page {})", search.q, search.page)
/// }
/// ```
pub use laravel_rust_http_macros::query;

/// Make a notification from the `impl` block that holds its `mail` and `sms` methods.
///
/// Importing `laravel::notification` brings in both this attribute and the module. The
/// [`notification`](mod@notification) module documents the methods a notification may define.
pub use laravel_rust_queue_macros::notification;

pub use crate::foundation::Application;
pub use crate::view::view;
/// Remember an async function's result for the rest of the [context](crate::context::Context),
/// keyed by its arguments.
///
/// A request is one context, and so are a command and each
/// [`Application::scope`](crate::Application::scope). The attribute applies
/// [`once`](fn@crate::once) to the whole function and keys it by its arguments, as
/// [`once_for`] does. Later calls with equal arguments get a clone of the first call's result.
/// Calls that run at the same time share one computation, even when one of them stops waiting.
/// An error result is remembered too.
///
/// ```no_run
/// # #[derive(Clone)] pub struct Team;
/// # #[derive(Clone)] pub struct User;
/// # pub struct Teams;
/// # impl Teams { async fn current(&self) -> Option<Team> { None } }
/// # pub struct Users;
/// # impl Users { async fn find(&self, id: u64) -> Option<User> { None } }
/// /// The signed-in user's team, looked up at most once per request.
/// #[laravel::once]
/// pub async fn current_team() -> laravel::Result<Option<Team>> {
///     Ok(laravel::resolve::<Teams>().await?.current().await)
/// }
///
/// /// A user by ID, looked up at most once per request for each ID.
/// #[laravel::once]
/// pub async fn find_user(id: u64) -> laravel::Result<Option<User>> {
///     Ok(laravel::resolve::<Users>().await?.find(id).await)
/// }
/// ```
///
/// The function's arguments are its key, so they must be owned values that implement
/// [`Hash`](std::hash::Hash), such as a `u64` or a `String`, and its result must be `Clone`.
/// Return an `Arc` to avoid cloning large values. The function's future must be `Send`. The
/// attribute doesn't support generic functions or methods that take `self`.
///
/// ```compile_fail
/// #[laravel::once]
/// async fn slug(title: &str) -> String {
///     title.to_lowercase()
/// }
/// ```
pub use laravel_rust_macros::once;

/// The framework version.
pub const VERSION: &str = env!("CARGO_PKG_VERSION");