Skip to main content

glacier/
lib.rs

1//! Glacier — a batteries-included web framework for Rust.
2//!
3//! ```no_run
4//! use glacier::prelude::*;
5//!
6//! async fn home(_ctx: Context) -> &'static str {
7//!     "Hello from Glacier"
8//! }
9//!
10//! #[glacier::main]
11//! async fn main() -> glacier::Result<()> {
12//!     App::new()
13//!         .routes(|r| {
14//!             r.get("/", home);
15//!         })
16//!         .serve("127.0.0.1:4000")
17//!         .await
18//! }
19//! ```
20//!
21//! # Logs and traces
22//!
23//! `serve` logs to stdout: text in development, JSON lines in production
24//! (`GLACIER_LOG_FORMAT=json|text` chooses), filtered by `RUST_LOG`.
25//!
26//! Glacier also emits [`tracing`] spans with stable names and fields from
27//! OpenTelemetry's semantic conventions, for a tracing backend to collect.
28//! Logs leave them out. To export them, register a layer with
29//! [`App::telemetry`]: the `glacier-otel` crate sends them over OTLP
30//! (`.telemetry(glacier_otel::from_env("blog")?)`).
31//!
32//! | Span | Fields |
33//! | --- | --- |
34//! | `glacier.request` | `http.request.method`, `url.path`, `http.route` (`/posts/:id`), `http.response.status_code`, `otel.name` (`GET /posts/:id`), `otel.status_code` (`ERROR` on 5xx) |
35//! | `glacier.db.query` | `db.system.name` (`postgresql`, `sqlite`), `db.operation.name` (`SELECT`…), `db.query.text` (with placeholders, never bound values), `db.response.returned_rows`, `error.message` and `otel.status_code` on failure |
36//!
37//! | `glacier.job` | `job.name`, `job.id`, `job.attempt`, `otel.name` (the job's name), `otel.kind` (`consumer`) |
38//! | `glacier.mail` | `mail.to`, `mail.subject`, `mail.delivery` (`smtp`, `postmark`, …) |
39//! | `glacier.http.client` | `http.request.method`, `url.full`, `http.response.status_code`, `otel.kind` (`client`) |
40//! | `glacier.webhook` | `webhook.provider`, `webhook.event_id`, `webhook.event_type`, inside its `glacier.job` |
41//!
42//! Queries nest in their request's (or job's) span. A request that fails with a 5xx
43//! records an `ERROR` event in its span with `error.message` and
44//! `error.causes` (the full cause chain, which the response never shows).
45
46pub mod access;
47pub mod billing;
48/// `glacier::tracing::info!(…)` for an app's own logs, without a
49/// dependency of its own.
50pub use tracing;
51pub mod app;
52pub mod attachment;
53pub mod auth;
54pub mod authorization;
55mod basic_auth;
56pub mod cache;
57pub mod client;
58pub mod config;
59pub mod context;
60pub mod controller;
61pub mod cookies;
62pub mod cors;
63pub mod csrf;
64pub mod current;
65pub mod db;
66pub mod encryption;
67pub mod error;
68pub mod files;
69pub mod handler;
70pub mod hosts;
71pub mod html;
72pub mod i18n;
73pub mod jobs;
74pub mod lock;
75pub mod mail;
76pub mod middleware;
77pub mod mime;
78pub mod model;
79pub mod notify;
80pub mod openapi;
81pub mod pagination;
82pub mod pdf;
83pub mod process;
84mod random;
85pub mod rate_limit;
86pub mod request;
87pub mod response;
88pub mod retry;
89pub mod router;
90pub mod serialize;
91pub mod session;
92pub mod spam;
93pub mod storage;
94pub mod task;
95mod tasks;
96pub mod telemetry;
97pub mod testing;
98pub mod text;
99pub mod time;
100pub mod upload;
101pub mod view;
102pub mod webhooks;
103
104pub use app::{App, Service};
105pub use config::{Config, Env};
106pub use context::{Context, Params, PathParams};
107pub use controller::{Action, Resource};
108pub use error::{Error, Result};
109pub use handler::Handler;
110pub use http::{Method, StatusCode, header};
111pub use middleware::{Middleware, Next, Pipeline};
112pub use model::{Callbacks, Model};
113pub use response::{Html, IntoResponse, Json, Response};
114pub use router::{Router, ToPath, url_for};
115pub use serialize::Serializer;
116
117pub use glacier_macros::{
118    Model, app, clients, config, controller, controllers, enumeration, folder, jobs, mailers, main,
119    middleware, migrations, model, models, modules, scopes, seeds, serializers, serve, services,
120    static_files, test, tests, views,
121};
122
123/// Adds field validations to a changeset, in the syntax of the model's
124/// `#[validate(…)]` attributes: for named changesets, whose rules differ
125/// from one form to another.
126///
127/// ```ignore
128/// pub fn signup(params: &Params) -> Changeset<User> {
129///     let changeset = User::changeset()
130///         .cast(|u| u.email, params)
131///         .cast(|u| u.password, params);
132///     glacier::validate!(changeset, password, required, length = 8..)
133/// }
134/// ```
135pub use glacier_macros::validate;
136
137/// Route pattern constants and path helpers from one definition.
138///
139/// ```
140/// mod paths {
141///     glacier::paths! {
142///         home = "/";
143///         file = "/files/*path";
144///         resources posts(post) = "/posts";
145///     }
146/// }
147///
148/// assert_eq!(paths::HOME, "/");
149/// assert_eq!(paths::home_path(), "/");
150/// assert_eq!(paths::POSTS, "/posts");
151/// assert_eq!(paths::post_path(7), "/posts/7");
152/// assert_eq!(paths::edit_post_path("a b"), "/posts/a%20b/edit");
153/// assert_eq!(paths::new_post_path(), "/posts/new");
154/// assert_eq!(paths::file_path("docs/a b.pdf"), "/files/docs/a%20b.pdf");
155/// ```
156///
157/// Use the constants when drawing routes (`r.get(paths::HOME, ..)`,
158/// `r.resources::<Posts>(paths::POSTS)`) and the helpers in links, so a
159/// renamed route or a missing parameter is a compile error.
160pub use glacier_macros::paths;
161
162/// The route table: generates `draw()` for `App::routes` and a `*_path()`
163/// helper per named route, from one declaration.
164///
165/// ```ignore
166/// glacier::routes! {
167///     pipeline browser = Pipeline::browser();
168///
169///     scope "/" through browser {
170///         get "/" => Pages::home, as home;              // home_path()
171///         resources "/posts" => Posts;                  // posts_path(), post_path(id), …
172///         resources "/people" => People, as person;     // person_path(id) for irregulars
173///         resources "/tags" => Tags, only [index, show];
174///     }
175///
176///     scope "/api" {
177///         get "/posts" => api::posts, as api_posts;
178///     }
179/// }
180/// ```
181///
182/// Helpers are generated only for routes that exist, so a link to a route
183/// that was removed or renamed fails to compile. Without `only`, a resource
184/// gets helpers for all seven actions.
185pub use glacier_macros::routes;
186
187/// Everything an application typically needs, in one import.
188pub mod list;
189pub mod values;
190
191pub mod prelude {
192    pub use crate::db::Save::{self, Invalid, Saved};
193    pub use crate::db::{Changeset, Date, Decimal, JsonValue, NaiveTimestamp, Timestamp, Uuid};
194    pub use crate::i18n::{locale, set_locale, t, t_count, t_with};
195    pub use crate::jobs::{Job, Jobs};
196    pub use crate::request::{after_response, assign};
197    pub use crate::storage::current as storage;
198    pub use crate::task::puts;
199    // `books.map(…)`, `books.sum(…)`: list methods on any `Vec` or slice.
200    pub use crate::db::{LoadedRecords as _, Records as _};
201    pub use crate::list::{Compact as _, List as _};
202    pub use crate::mail::Mail;
203    pub use crate::router::ToPath;
204    pub use crate::serialize::Serializer;
205    pub use crate::view::{Field, Rendered, Slot, Template, html, render};
206    pub use crate::{
207        App, Callbacks, Config, Context, Env, Error, Html, IntoResponse, Json, Method, Middleware,
208        Model, Next, Params, Pipeline, Resource, Response, Result, Router, StatusCode,
209    };
210    pub use crate::{json, redirect, url_for};
211    // `date.year()`, `at.hour()`: the methods, without the trait names.
212    pub use chrono::{Datelike as _, Timelike as _};
213    // `Timestamp.now()`, `Date.today()`, `30.days().ago()`.
214    pub use crate::time::{Durations as _, Now as _, Relative as _, Today as _};
215    // What `30.days()` gives, to name in a signature.
216    pub use chrono::TimeDelta;
217    // `Array<String>`, `Array.new()`: Ruby's and Elixir's name for a list.
218    pub use crate::values::Array;
219    // `Db.sql("…")`, `Db.Expr.raw(…)`: the database module by a short name.
220    pub use crate::Decision;
221    pub use crate::db as Db;
222    // `x.to_s()`, `"12".to_i()`, `"3.5".to_f()`, as Ruby's.
223    pub use crate::lock::Lock;
224    pub use crate::rate_limit::RateLimit;
225    pub use crate::text::{Moment as _, Number as _, Text as _, Whole as _};
226    pub use crate::values::{ToF as _, ToI as _, ToS as _};
227}
228
229pub use authorization::{Decision, skip_authorization};
230
231/// Checks a permission: `Err(403 Forbidden)` unless allowed. `authorize
232/// report.editable_by(&user)!` in `.glacier`, as Laravel's
233/// `Gate::authorize` or CanCan's `authorize!`; the rules themselves are the
234/// app's own methods, returning a `bool` or a [`Decision`], whose denial
235/// keeps its status and message (`deny :not_found`).
236///
237/// # Errors
238///
239/// The denial's status (`403 Forbidden` for `false`) when not allowed.
240pub fn authorize(decision: impl Into<Decision>) -> Result<()> {
241    // Allowed or not, the action checked (`VerifyAuthorized`).
242    authorization::mark();
243    match decision.into() {
244        Decision::Allow => Ok(()),
245        Decision::Deny { status, message } => Err(match message {
246            Some(message) => Error::new(status, message),
247            None if status == http::StatusCode::FORBIDDEN => Error::forbidden(),
248            None => Error::new(status, status.canonical_reason().unwrap_or("denied")),
249        }),
250    }
251}
252
253/// Redirects with `303 See Other` to a path or a record (via `ToPath`),
254/// optionally setting flash messages, and evaluates to a `glacier::Result`.
255/// `status: "found"` (in `.glacier`, `status: :found`) picks another
256/// status, such as the `302` Rails' `redirect_to` sends by default:
257///
258/// ```
259/// # use glacier::prelude::*;
260/// async fn create(_ctx: Context) -> Result {
261///     let id = 7;
262///     glacier::redirect!(format!("/posts/{id}"), notice: "Post created.")
263/// }
264/// ```
265///
266/// Flash requires a request; see `glacier::request`.
267#[macro_export]
268macro_rules! redirect {
269    ($to:expr $(, $kind:ident : $message:expr)* $(,)?) => {{
270        #[allow(unused_mut)]
271        let mut status = $crate::StatusCode::SEE_OTHER;
272        $( $crate::response::RedirectOption::apply($message, ::core::stringify!($kind), &mut status); )*
273        let path = {
274            use $crate::router::ToPath as _;
275            ($to).to_path()
276        };
277        $crate::Result::<$crate::Response>::Ok(
278            $crate::Response::redirect(&path).with_status(status),
279        )
280    }};
281}
282
283/// A JSON response, for API actions: `json!(post)`, `json!(posts, status =
284/// 201)`, `json!(post.errors_json(), status = "unprocessable_entity")`. The
285/// status is a number, a `StatusCode` or a snake_case name.
286///
287/// With a [`Serializer`](serialize::Serializer), as active_model_serializers
288/// renders: `json!(countries, each_serializer = CountrySerializer)` writes
289/// `{"countries": [...]}`, `json!(country, serializer = CountrySerializer)`
290/// writes `{"country": {...}}`, and `root = "name"` or `root = false`
291/// changes the root key.
292#[macro_export]
293macro_rules! json {
294    ($value:expr $(, $option:ident = $setting:expr)* $(,)?) => {
295        $crate::serialize::Render::new(&$value) $( .$option($setting) )* .respond()
296    };
297}
298
299/// The JSON Schema of an expression's type, without evaluating it: its
300/// `Schema`, or `{}` for a type that has none.
301#[doc(hidden)]
302#[macro_export]
303macro_rules! schema_of {
304    ($value:expr) => {{
305        #[allow(unused_imports)]
306        use $crate::serialize::{ProbeAny as _, ProbeSchema as _};
307        #[allow(unreachable_code, clippy::diverging_sub_expression)]
308        let probe = $crate::serialize::Probe::of(|| $value);
309        (&&probe).schema()
310    }};
311}
312
313/// A serializer's `attributes :id` field: written as Rails writes columns.
314#[doc(hidden)]
315#[macro_export]
316macro_rules! __serializer_attr {
317    ($json:ident, $object:ident, $name:expr, $value:expr) => {
318        $json.field(
319            $name,
320            || {
321                let $object = $object.expect("a record");
322                $crate::serialize::attr_json(&$value)
323            },
324            || {
325                let $object = $object;
326                $crate::schema_of!({
327                    let $object = $object.expect("a record");
328                    &$value
329                })
330            },
331        )
332    };
333}
334
335/// Runs several fallible futures at once and gives their values
336/// together, or the first error: `parallel(Catalogue.prices(s),
337/// Rates.latest())!` in `.glacier`, `glacier::parallel!(a, b).await?` in
338/// Rust. They run in this task, side by side, so the request's database
339/// connection and access come along.
340#[macro_export]
341macro_rules! parallel {
342    ($($future:expr),+ $(,)?) => {
343        async { $crate::__private::tokio::try_join!($($future),+) }
344    };
345}
346
347/// A serializer's computed `attribute :label, value` field.
348#[doc(hidden)]
349#[macro_export]
350macro_rules! __serializer_value {
351    ($json:ident, $object:ident, $name:expr, $value:expr) => {
352        $json.field(
353            $name,
354            || {
355                let $object = $object.expect("a record");
356                $crate::serialize::value_to_json(&($value))
357            },
358            || {
359                let $object = $object;
360                $crate::schema_of!({
361                    let $object = $object.expect("a record");
362                    $value
363                })
364            },
365        )
366    };
367}
368
369/// A serializer's association: `one` or `many`, through a serializer or
370/// every column.
371#[doc(hidden)]
372#[macro_export]
373macro_rules! __serializer_assoc {
374    ($json:ident, $object:ident, one, $name:expr, $value:expr) => {
375        $json.field(
376            $name,
377            || {
378                let $object = $object.expect("a record");
379                $crate::serialize::one_json($value.get(), $crate::serialize::attributes)
380            },
381            || {
382                let $object = $object;
383                $crate::schema_of!({
384                    let $object = $object.expect("a record");
385                    $value.get()
386                })
387            },
388        )
389    };
390    ($json:ident, $object:ident, many, $name:expr, $value:expr) => {
391        $json.field(
392            $name,
393            || {
394                let $object = $object.expect("a record");
395                $crate::serialize::many_json($value.get(), $crate::serialize::attributes)
396            },
397            || {
398                let $object = $object;
399                $crate::schema_of!({
400                    let $object = $object.expect("a record");
401                    $value.get()
402                })
403            },
404        )
405    };
406    ($json:ident, $object:ident, one, $name:expr, $value:expr, $serializer:ty) => {
407        $json.field(
408            $name,
409            || {
410                let $object = $object.expect("a record");
411                $crate::serialize::one_json(
412                    $value.get(),
413                    <$serializer as $crate::Serializer>::serialize,
414                )
415            },
416            || $crate::serialize::nullable(<$serializer as $crate::Serializer>::schema()),
417        )
418    };
419    ($json:ident, $object:ident, many, $name:expr, $value:expr, $serializer:ty) => {
420        $json.field(
421            $name,
422            || {
423                let $object = $object.expect("a record");
424                $crate::serialize::many_json(
425                    $value.get(),
426                    <$serializer as $crate::Serializer>::serialize,
427                )
428            },
429            || {
430                $crate::serialize::nullable($crate::__private::serde_json::json!({
431                    "type": "array",
432                    "items": <$serializer as $crate::Serializer>::schema(),
433                }))
434            },
435        )
436    };
437}
438
439/// Expands its input only when Glacier is built with Postgres support; for
440/// macros generating database-specific code.
441#[cfg(feature = "postgres")]
442#[doc(hidden)]
443#[macro_export]
444macro_rules! __with_postgres {
445    ($($code:tt)*) => { $($code)* };
446}
447
448#[cfg(not(feature = "postgres"))]
449#[doc(hidden)]
450#[macro_export]
451macro_rules! __with_postgres {
452    ($($code:tt)*) => {};
453}
454
455/// Like `__with_postgres`, for SQLite.
456#[cfg(feature = "sqlite")]
457#[doc(hidden)]
458#[macro_export]
459macro_rules! __with_sqlite {
460    ($($code:tt)*) => { $($code)* };
461}
462
463#[cfg(not(feature = "sqlite"))]
464#[doc(hidden)]
465#[macro_export]
466macro_rules! __with_sqlite {
467    ($($code:tt)*) => {};
468}
469
470/// The sqlx version Glacier uses, for code that shares its connection pool
471/// (`Repo::postgres_pool`, `Repo::sqlite_pool`) with sqlx or SeaORM.
472pub use sqlx;
473
474/// The chrono version Glacier's timestamps use.
475pub use chrono;
476
477#[doc(hidden)]
478pub mod __private {
479    pub use serde;
480    pub use serde_json;
481    pub use tokio;
482
483    /// `Default::default()` for a type that has one, else `None`, decided
484    /// at compile time where the type is known (autoref specialisation):
485    /// `(&Probe::<T>::new()).blank()`, as the model derive writes it.
486    pub struct Probe<T>(::core::marker::PhantomData<T>);
487
488    impl<T> Probe<T> {
489        #[allow(clippy::new_without_default)]
490        pub fn new() -> Self {
491            Probe(::core::marker::PhantomData)
492        }
493    }
494
495    pub trait BlankByDefault<T> {
496        fn blank(&self) -> Option<T>;
497    }
498
499    impl<T: Default> BlankByDefault<T> for Probe<T> {
500        fn blank(&self) -> Option<T> {
501            Some(T::default())
502        }
503    }
504
505    pub trait NoBlank<T> {
506        fn blank(&self) -> Option<T>;
507    }
508
509    impl<T> NoBlank<T> for &Probe<T> {
510        fn blank(&self) -> Option<T> {
511            None
512        }
513    }
514}