glacier-web 0.1.0

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
Documentation
//! Glacier — a batteries-included web framework for Rust.
//!
//! ```no_run
//! use glacier::prelude::*;
//!
//! async fn home(_ctx: Context) -> &'static str {
//!     "Hello from Glacier"
//! }
//!
//! #[glacier::main]
//! async fn main() -> glacier::Result<()> {
//!     App::new()
//!         .routes(|r| {
//!             r.get("/", home);
//!         })
//!         .serve("127.0.0.1:4000")
//!         .await
//! }
//! ```
//!
//! # Logs and traces
//!
//! `serve` logs to stdout: text in development, JSON lines in production
//! (`GLACIER_LOG_FORMAT=json|text` chooses), filtered by `RUST_LOG`.
//!
//! Glacier also emits [`tracing`] spans with stable names and fields from
//! OpenTelemetry's semantic conventions, for a tracing backend to collect.
//! Logs leave them out. To export them, register a layer with
//! [`App::telemetry`]: the `glacier-otel` crate sends them over OTLP
//! (`.telemetry(glacier_otel::from_env("blog")?)`).
//!
//! | Span | Fields |
//! | --- | --- |
//! | `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) |
//! | `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 |
//!
//! Queries nest in their request's span. A request that fails with a 5xx
//! records an `ERROR` event in its span with `error.message` and
//! `error.causes` (the full cause chain, which the response never shows).

pub mod app;
pub mod attachment;
pub mod auth;
pub mod authorization;
pub mod config;
pub mod context;
pub mod controller;
pub mod cookies;
pub mod cors;
pub mod csrf;
pub mod db;
pub mod error;
pub mod files;
pub mod handler;
pub mod html;
pub mod i18n;
pub mod jobs;
pub mod middleware;
pub mod mime;
pub mod model;
pub mod pagination;
mod random;
pub mod request;
pub mod response;
pub mod router;
pub mod serialize;
pub mod session;
pub mod storage;
pub mod telemetry;
pub mod testing;
pub mod time;
pub mod upload;
pub mod view;

pub use app::{App, Service};
pub use config::{Config, Env};
pub use context::{Context, Params, PathParams};
pub use controller::{Action, Resource};
pub use error::{Error, Result};
pub use handler::Handler;
pub use http::{Method, StatusCode, header};
pub use middleware::{Middleware, Next, Pipeline};
pub use model::{Callbacks, Model};
pub use response::{Html, IntoResponse, Json, Response};
pub use router::{Router, ToPath};
pub use serialize::Serializer;

pub use glacier_macros::{
    Model, config, controller, controllers, enumeration, jobs, main, model, models, scopes,
    serializers, services, static_files, test, tests, views,
};

/// Route pattern constants and path helpers from one definition.
///
/// ```
/// mod paths {
///     glacier::paths! {
///         home = "/";
///         file = "/files/*path";
///         resources posts(post) = "/posts";
///     }
/// }
///
/// assert_eq!(paths::HOME, "/");
/// assert_eq!(paths::home_path(), "/");
/// assert_eq!(paths::POSTS, "/posts");
/// assert_eq!(paths::post_path(7), "/posts/7");
/// assert_eq!(paths::edit_post_path("a b"), "/posts/a%20b/edit");
/// assert_eq!(paths::new_post_path(), "/posts/new");
/// assert_eq!(paths::file_path("docs/a b.pdf"), "/files/docs/a%20b.pdf");
/// ```
///
/// Use the constants when drawing routes (`r.get(paths::HOME, ..)`,
/// `r.resources::<Posts>(paths::POSTS)`) and the helpers in links, so a
/// renamed route or a missing parameter is a compile error.
pub use glacier_macros::paths;

/// The route table: generates `draw()` for `App::routes` and a `*_path()`
/// helper per named route, from one declaration.
///
/// ```ignore
/// glacier::routes! {
///     pipeline browser = Pipeline::browser();
///
///     scope "/" through browser {
///         get "/" => Pages::home, as home;              // home_path()
///         resources "/posts" => Posts;                  // posts_path(), post_path(id), …
///         resources "/people" => People, as person;     // person_path(id) for irregulars
///         resources "/tags" => Tags, only [index, show];
///     }
///
///     scope "/api" {
///         get "/posts" => api::posts, as api_posts;
///     }
/// }
/// ```
///
/// Helpers are generated only for routes that exist, so a link to a route
/// that was removed or renamed fails to compile. Without `only`, a resource
/// gets helpers for all seven actions.
pub use glacier_macros::routes;

/// Everything an application typically needs, in one import.
pub mod prelude {
    pub use crate::db::Save::{self, Invalid, Saved};
    pub use crate::db::{Changeset, Date, Decimal, JsonValue, NaiveTimestamp, Timestamp, Uuid};
    pub use crate::i18n::{locale, t, t_with};
    pub use crate::jobs::{Job, Jobs};
    pub use crate::router::ToPath;
    pub use crate::serialize::Serializer;
    pub use crate::view::{Rendered, Template, html, render};
    pub use crate::{
        App, Callbacks, Config, Context, Env, Error, Html, IntoResponse, Json, Method, Middleware,
        Model, Next, Params, Pipeline, Resource, Response, Result, Router, StatusCode,
    };
    pub use crate::{json, redirect};
    // `date.year()`, `at.hour()`: the methods, without the trait names.
    pub use chrono::{Datelike as _, Timelike as _};
}

pub use authorization::skip_authorization;

/// Checks a permission: `Err(403 Forbidden)` unless `allowed`. `authorize
/// report.editable_by(&user)!` in `.glacier`, as Laravel's
/// `Gate::authorize` or CanCan's `authorize!`; the rules themselves are the
/// app's own methods.
///
/// # Errors
///
/// `403 Forbidden` when not allowed.
pub fn authorize(allowed: bool) -> Result<()> {
    // Allowed or not, the action checked (`VerifyAuthorized`).
    authorization::mark();
    if allowed {
        Ok(())
    } else {
        Err(Error::forbidden())
    }
}

/// Redirects with `303 See Other` to a path or a record (via `ToPath`),
/// optionally setting flash messages, and evaluates to a `glacier::Result`:
///
/// ```
/// # use glacier::prelude::*;
/// async fn create(_ctx: Context) -> Result {
///     let id = 7;
///     glacier::redirect!(format!("/posts/{id}"), notice: "Post created.")
/// }
/// ```
///
/// Flash requires a request; see `glacier::request`.
#[macro_export]
macro_rules! redirect {
    ($to:expr $(, $kind:ident : $message:expr)* $(,)?) => {{
        $( $crate::request::put_flash(::core::stringify!($kind), $message); )*
        let path = {
            use $crate::router::ToPath as _;
            ($to).to_path()
        };
        $crate::Result::<$crate::Response>::Ok($crate::Response::redirect(&path))
    }};
}

/// A JSON response, for API actions: `json!(post)`, `json!(posts, status =
/// 201)`, `json!(post.errors_json(), status = "unprocessable_entity")`. The
/// status is a number, a `StatusCode` or a snake_case name.
///
/// With a [`Serializer`](serialize::Serializer), as active_model_serializers
/// renders: `json!(countries, each_serializer = CountrySerializer)` writes
/// `{"countries": [...]}`, `json!(country, serializer = CountrySerializer)`
/// writes `{"country": {...}}`, and `root = "name"` or `root = false`
/// changes the root key.
#[macro_export]
macro_rules! json {
    ($value:expr $(, $option:ident = $setting:expr)* $(,)?) => {
        $crate::serialize::Render::new(&$value) $( .$option($setting) )* .respond()
    };
}

/// Lists an app's migrations, declaring each as a module (one file per
/// migration in the same directory) and generating `all()`. Maintained by
/// `glacier generate migration`:
///
/// ```ignore
/// // src/migrations/mod.rs
/// glacier::migrations! {
///     m20261003120000_create_posts,
/// }
/// ```
#[macro_export]
macro_rules! migrations {
    ($($name:ident),* $(,)?) => {
        $( mod $name; )*

        /// Every migration, for `App::migrations` and `Migrator`.
        pub fn all() -> ::std::vec::Vec<$crate::db::migration::Migration> {
            ::std::vec![$(
                $crate::db::migration::Migration::new(::core::stringify!($name), $name::up, $name::down)
            ),*]
        }
    };
}

/// Expands its input only when Glacier is built with Postgres support; for
/// macros generating database-specific code.
#[cfg(feature = "postgres")]
#[doc(hidden)]
#[macro_export]
macro_rules! __with_postgres {
    ($($code:tt)*) => { $($code)* };
}

#[cfg(not(feature = "postgres"))]
#[doc(hidden)]
#[macro_export]
macro_rules! __with_postgres {
    ($($code:tt)*) => {};
}

/// Like `__with_postgres`, for SQLite.
#[cfg(feature = "sqlite")]
#[doc(hidden)]
#[macro_export]
macro_rules! __with_sqlite {
    ($($code:tt)*) => { $($code)* };
}

#[cfg(not(feature = "sqlite"))]
#[doc(hidden)]
#[macro_export]
macro_rules! __with_sqlite {
    ($($code:tt)*) => {};
}

/// The sqlx version Glacier uses, for code that shares its connection pool
/// (`Repo::postgres_pool`, `Repo::sqlite_pool`) with sqlx or SeaORM.
pub use sqlx;

/// The chrono version Glacier's timestamps use.
pub use chrono;

#[doc(hidden)]
pub mod __private {
    pub use serde;
    pub use serde_json;
    pub use tokio;
}