laravel-rust 0.1.3

Laravel for Rust: a full-stack Rust web framework.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
//! # 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"
//! }
//!
//! #[laravel::input]
//! 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;

/// Derive support for a fieldless enum as a model column, a form field, and a query value.
///
/// The enum must implement Serde's `Serialize` and `Deserialize`. Each variant reads and writes as
/// its Serde name, so `rename`, `rename_all`, and `alias` apply. Validation rules such as `one_of`
/// and `distinct` compare a variant by its Serde name, whichever alias the request sent. With the
/// `database` feature, the enum also binds in queries and decodes from a text column.
///
/// ```no_run
/// # async fn example() -> laravel::Result<()> {
/// use laravel::db;
///
/// #[derive(serde::Serialize, serde::Deserialize, laravel::Enum)]
/// #[serde(rename_all = "snake_case")]
/// enum Status { Pending, Active }
///
/// let status = Status::Active;
/// db::query!("INSERT INTO users (status) VALUES ({status})").insert().await?;
///
/// let user = db::query!("SELECT status FROM users LIMIT 1").select_one().await?;
/// if let Some(user) = user {
///     let status: Status = user.try_get("status")?;
/// }
/// # Ok(()) }
/// ```
///
/// A variant with fields is a compile error. To store an enum with data in a JSON column, derive
/// `db::Json` instead:
///
/// ```compile_fail
/// #[derive(serde::Serialize, serde::Deserialize, laravel::Enum)]
/// enum Status { Active { id: i64 } }
/// ```
pub use laravel_rust_database_macros::Enum;

/// Derive support for a struct with one field, such as `struct Email(String)`, as the value of its
/// field.
///
/// A form field of the struct accepts and validates the same input as its field. A route parameter
/// reads the same way. With the `database` feature, the database stores the struct as the value of
/// its field, so the struct reads and writes the same column type that its field would. Wrap the
/// struct in `Option` for a nullable column.
///
/// The derived struct works in more places, depending on its field and the traits it implements:
///
/// - A struct over a `String` works with the `like`, `starts_with`, `ends_with`, and `contains`
///   filters of a model's typed column.
/// - A struct that implements `Add` and `Sub` takes `+=` and `-=` in `update!`.
/// - A struct over a key type, such as `i64` or `Uuid`, that implements `Eq`, `Hash`, `Display`,
///   and `Deserialize` can be a model's key. The model gets its values as it would for a key of the
///   field's type.
///
/// ```no_run
/// # async fn example() -> laravel::Result<()> {
/// use laravel::db;
///
/// #[derive(laravel::Newtype)]
/// struct Email(String);
///
/// let email = Email("taylor@laravel.com".into());
/// db::query!("INSERT INTO users (email) VALUES ({email})").insert().await?;
///
/// let user = db::query!("SELECT email FROM users LIMIT 1").select_one().await?;
/// if let Some(user) = user {
///     let email: Email = user.try_get("email")?;
/// }
/// # Ok(()) }
/// ```
///
/// Decoding builds the struct from the stored value directly, so checks in the struct's own
/// constructors don't run on a value the database already holds.
///
/// A struct with more than one field is a compile error. Derive `db::Json` to store one as JSON:
///
/// ```compile_fail
/// #[derive(laravel::Newtype)]
/// struct Money { cents: i64, currency: String }
/// ```
pub use laravel_rust_database_macros::Newtype;

/// Expands to its input when the `database` feature is on, and to nothing otherwise, so derives
/// such as [`Enum`] emit their database impls only in applications that have a database.
#[cfg(feature = "database")]
#[doc(hidden)]
#[macro_export]
macro_rules! __database {
    ($($item:tt)*) => { $($item)* };
}

#[cfg(not(feature = "database"))]
#[doc(hidden)]
#[macro_export]
macro_rules! __database {
    ($($item:tt)*) => {};
}

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");