glacier-web 0.3.0

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
//! 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 access;
pub mod billing;
/// `glacier::tracing::info!(…)` for an app's own logs, without a
/// dependency of its own.
pub use tracing;
pub mod app;
pub mod attachment;
pub mod auth;
pub mod authorization;
pub mod cache;
pub mod client;
pub mod config;
pub mod context;
pub mod controller;
pub mod cookies;
pub mod cors;
pub mod csrf;
pub mod current;
pub mod db;
pub mod error;
pub mod files;
pub mod handler;
pub mod html;
pub mod i18n;
pub mod jobs;
pub mod mail;
pub mod middleware;
pub mod mime;
pub mod model;
pub mod openapi;
pub mod pagination;
pub mod pdf;
mod random;
pub mod request;
pub mod response;
pub mod router;
pub mod serialize;
pub mod session;
pub mod storage;
mod tasks;
pub mod telemetry;
pub mod testing;
pub mod time;
pub mod upload;
pub mod view;
pub mod webhooks;

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, seeds,
    serializers, services, static_files, test, tests, views,
};

/// Adds field validations to a changeset, in the syntax of the model's
/// `#[validate(…)]` attributes: for named changesets, whose rules differ
/// from one form to another.
///
/// ```ignore
/// pub fn signup(params: &Params) -> Changeset<User> {
///     let changeset = User::changeset()
///         .cast(|u| u.email, params)
///         .cast(|u| u.password, params);
///     glacier::validate!(changeset, password, required, length = 8..)
/// }
/// ```
pub use glacier_macros::validate;

/// 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::mail::Mail;
    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 _};
    // `Timestamp.now()`, `Date.today()`, `30.days().ago()`.
    pub use crate::time::{Durations as _, Now as _, Relative as _, Today 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`.
/// `status: "found"` (in `.glacier`, `status: :found`) picks another
/// status, such as the `302` Rails' `redirect_to` sends by default:
///
/// ```
/// # 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)* $(,)?) => {{
        #[allow(unused_mut)]
        let mut status = $crate::StatusCode::SEE_OTHER;
        $( $crate::response::RedirectOption::apply($message, ::core::stringify!($kind), &mut status); )*
        let path = {
            use $crate::router::ToPath as _;
            ($to).to_path()
        };
        $crate::Result::<$crate::Response>::Ok(
            $crate::Response::redirect(&path).with_status(status),
        )
    }};
}

/// 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()
    };
}

/// The JSON Schema of an expression's type, without evaluating it: its
/// `Schema`, or `{}` for a type that has none.
#[doc(hidden)]
#[macro_export]
macro_rules! schema_of {
    ($value:expr) => {{
        #[allow(unused_imports)]
        use $crate::serialize::{ProbeAny as _, ProbeSchema as _};
        #[allow(unreachable_code, clippy::diverging_sub_expression)]
        let probe = $crate::serialize::Probe::of(|| $value);
        (&&probe).schema()
    }};
}

/// A serializer's `attributes :id` field: written as Rails writes columns.
#[doc(hidden)]
#[macro_export]
macro_rules! __serializer_attr {
    ($json:ident, $object:ident, $name:expr, $value:expr) => {
        $json.field(
            $name,
            || {
                let $object = $object.expect("a record");
                $crate::serialize::attr_json(&$value)
            },
            || {
                let $object = $object;
                $crate::schema_of!({
                    let $object = $object.expect("a record");
                    &$value
                })
            },
        )
    };
}

/// A serializer's computed `attribute :label, value` field.
#[doc(hidden)]
#[macro_export]
macro_rules! __serializer_value {
    ($json:ident, $object:ident, $name:expr, $value:expr) => {
        $json.field(
            $name,
            || {
                let $object = $object.expect("a record");
                $crate::serialize::value_to_json(&($value))
            },
            || {
                let $object = $object;
                $crate::schema_of!({
                    let $object = $object.expect("a record");
                    $value
                })
            },
        )
    };
}

/// A serializer's association: `one` or `many`, through a serializer or
/// every column.
#[doc(hidden)]
#[macro_export]
macro_rules! __serializer_assoc {
    ($json:ident, $object:ident, one, $name:expr, $value:expr) => {
        $json.field(
            $name,
            || {
                let $object = $object.expect("a record");
                $crate::serialize::one_json($value.get(), $crate::serialize::attributes)
            },
            || {
                let $object = $object;
                $crate::schema_of!({
                    let $object = $object.expect("a record");
                    $value.get()
                })
            },
        )
    };
    ($json:ident, $object:ident, many, $name:expr, $value:expr) => {
        $json.field(
            $name,
            || {
                let $object = $object.expect("a record");
                $crate::serialize::many_json($value.get(), $crate::serialize::attributes)
            },
            || {
                let $object = $object;
                $crate::schema_of!({
                    let $object = $object.expect("a record");
                    $value.get()
                })
            },
        )
    };
    ($json:ident, $object:ident, one, $name:expr, $value:expr, $serializer:ty) => {
        $json.field(
            $name,
            || {
                let $object = $object.expect("a record");
                $crate::serialize::one_json(
                    $value.get(),
                    <$serializer as $crate::Serializer>::serialize,
                )
            },
            || $crate::serialize::nullable(<$serializer as $crate::Serializer>::schema()),
        )
    };
    ($json:ident, $object:ident, many, $name:expr, $value:expr, $serializer:ty) => {
        $json.field(
            $name,
            || {
                let $object = $object.expect("a record");
                $crate::serialize::many_json(
                    $value.get(),
                    <$serializer as $crate::Serializer>::serialize,
                )
            },
            || {
                $crate::serialize::nullable($crate::__private::serde_json::json!({
                    "type": "array",
                    "items": <$serializer as $crate::Serializer>::schema(),
                }))
            },
        )
    };
}

/// 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;
}