Skip to main content

Crate glacier

Crate glacier 

Source
Expand description

Glacier — a batteries-included web framework for Rust.

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")?)).

SpanFields
glacier.requesthttp.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.querydb.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

| glacier.job | job.name, job.id, job.attempt, otel.name (the job’s name), otel.kind (consumer) | | glacier.mail | mail.to, mail.subject, mail.delivery (smtp, postmark, …) | | glacier.http.client | http.request.method, url.full, http.response.status_code, otel.kind (client) | | glacier.webhook | webhook.provider, webhook.event_id, webhook.event_type, inside its glacier.job |

Queries nest in their request’s (or job’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).

Re-exports§

pub use app::App;
pub use app::Service;
pub use config::Config;
pub use config::Env;
pub use context::Context;
pub use context::Params;
pub use context::PathParams;
pub use controller::Action;
pub use controller::Resource;
pub use error::Error;
pub use error::Result;
pub use handler::Handler;
pub use middleware::Middleware;
pub use middleware::Next;
pub use middleware::Pipeline;
pub use model::Callbacks;
pub use model::Model;
pub use response::Html;
pub use response::IntoResponse;
pub use response::Json;
pub use response::Response;
pub use router::Router;
pub use router::ToPath;
pub use router::url_for;
pub use serialize::Serializer;
pub use authorization::Decision;
pub use authorization::skip_authorization;
pub use tracing;
pub use sqlx;
pub use chrono;

Modules§

access
Who a piece of work acts for: a signed-in user, an organisation, or the system itself. Glacier’s name for what Phoenix calls a scope.
app
The application builder and the HTTP server.
attachment
Files attached to records, as Paperclip keeps them: the original and a resized copy per style, under a path built from a pattern, with the record’s <name>_file_name, _content_type, _file_size and _updated_at columns describing it.
auth
The pieces glacier generate authentication builds on: password hashing, session tokens and bearer tokens. The generated app code (a User and Session model, a sessions controller and an Authentication middleware) is yours to read and change, as with Rails’ and Phoenix’s generators.
authorization
Checking that every action authorized, as Pundit’s verify_authorized: put VerifyAuthorized on a pipeline, and an action there that answers without calling authorize (or skip_authorization, for public actions) is a bug the response reports, instead of an endpoint silently open to everyone.
billing
Taking payments with Stripe: customers, Checkout for one-off payments and subscriptions, and keeping the app’s copy of charges and subscriptions in step with Stripe, from the return URL and from webhooks alike (“sync from the source”: both fetch the object from Stripe and upsert it, so repeats and reordering do no harm).
cache
Caching computed values: in the process (fast, per server) and, optionally, in the database, so every server shares them (as Rails’ Solid Cache).
client
Calling other services over HTTP, as Jumpstart’s API clients do: a client per service with its base URL and credentials, JSON in and out, timeouts, retries, and errors for answers that aren’t a success.
config
Configuration and environments.
context
The per-request Context handed to every handler and middleware.
controller
Rails-style resource controllers.
cookies
Request cookies, with signed and encrypted variants.
cors
Cross-origin requests, as rack-cors answers them: preflight OPTIONS requests get the allowed methods and headers, and responses to allowed origins say who may read them.
csrf
Cross-site request forgery protection.
current
Values for the rest of a request, as Rails’ Current: set one in middleware or an action, and read it wherever the request’s work runs, templates and layouts included, without passing it down.
db
The database layer: connections, the ambient repo, transactions and raw SQL. Models and queries build on this (see glacier::Model).
encryption
Encrypted columns: a model field declared encrypted (#[glacier(encrypted)] in Rust) is stored encrypted with AES-256-GCM and read back as plain text, as Rails’ encrypts does. A leaked database, backup or log of SQL shows only ciphertext.
error
The error type shared across Glacier.
files
Serving static files.
handler
Request handlers.
header
HTTP header types
hosts
The hosts an app answers for: a request whose Host header names another is refused with 403, as Rails’ config.hosts does. That stops DNS rebinding, and a forged host reaching anything that trusts it.
html
HTML helpers.
i18n
The request’s locale, as Rails’ I18n.locale.
jobs
Background jobs, kept in the database as Rails’ Solid Queue keeps them: enqueued in the same transaction as the work that asks for them, run by workers the app starts, retried with backoff, and left marked failed after their last attempt.
list
Everything an application typically needs, in one import. List methods, as Ruby’s Enumerable and Elixir’s Enum give: on any Vec, slice or loaded has_many, without .iter() or .collect().
lock
Locks, so one thing happens at a time for a key, across every process that shares the cache, as Laravel’s Cache::lock and Rails’ with_advisory_lock:
mail
Sending mail, as Action Mailer does: a message built from templates, delivered now or (by default) from a job, through whichever service the environment configures.
middleware
Middleware: code that wraps every request.
mime
Request formats and their media types, as Rails’ Mime registry knows them: /posts/1.json or Accept: application/json asks for JSON.
model
Database models.
notify
One Postgres NOTIFY channel for everything Glacier tells other processes, each message a small JSON envelope: {"topic": "jobs", "event": "queued", "id": 42}. Job wake-ups use it now; PubSub (0.6) will send its topics through it too.
openapi
OpenAPI: a description of the app’s API, from its routes, what its controllers’ actions respond with and its serializers’ schemas. glacier openapi writes it.
pagination
Pages of records, with the Link, Per-Page and Total headers that Rails’ api-pagination gem sends:
pdf
PDFs from HTML, printed by headless Chrome, as Rails apps do with Grover or a Puppeteer service: render a template to HTML, then print it.
prelude
process
Running other programs, as Laravel’s Process: a command, its arguments, a timeout, and what it printed.
rate_limit
A rate limiter shared by every process that shares the cache, as Laravel’s RateLimiter: limit attempts per period for each key, counted in fixed windows in the cache (cache::increment).
request
The current request, available without passing Context around.
response
HTTP responses and the IntoResponse conversion trait.
retry
Running work again when it fails: retry times: 3, wait: 1.seconds() do … end in .glacier, as Laravel’s retry and Ruby’s retry.
router
The router: maps a method and path to a handler.
serialize
Serializers: the JSON shape of a model, as active_model_serializers gives Rails apps.
session
Cookie-backed sessions and flash messages.
spam
Keeping bots off public forms, such as signing up, without a puzzle for people: {{ spam_trap() }} in the form adds a field people never see (bots fill in every field) and the time the form was shown, signed; glacier::spam::check(&params)? in the action refuses the form with 422 when the hidden field has text, the time is missing or forged, or the form came back sooner than a person could fill it in.
storage
Files kept elsewhere: a Store on disk or in S3 (or anything that speaks its API, such as MinIO), and presigned S3 URLs, as Active Storage, Paperclip and the aws-sdk hand to clients, so a client can fetch a private object directly for a while.
task
App tasks: code run from the command line, as Rails’ rake tasks and Laravel’s commands. In .glacier, src/tasks.glacier holds them:
telemetry
Where logs and traces go.
testing
In-process testing: drive an App without opening a socket.
text
Text and number helpers, for views and code alike: post.body.truncated(140), "Annual Report 2026".parameterize(), "author_id".humanize(), "book".pluralize(n), 1234567.delimited(), price.to_currency("GBP"), size.human_size(), 3.ordinal().
time
Times in a place: a UTC timestamp shown on a hospital’s (or a user’s) wall clock, as Rails’ in_time_zone.
upload
Files uploaded in a multipart/form-data request.
values
Values as .glacier reads them: a || b, Ruby’s “a, or else b”, and Ruby’s conversions, to_s, to_i and to_f.
view
Views: compiled templates.
webhooks
Receiving webhooks: verify the sender’s signature, store the event once, answer 200 at once, and handle it in a job, as pay does, but with every event kept for replay and deduplicated on its provider’s id.

Macros§

app
models!(post, comment): declares an app’s model modules, from src/models/<name>.glacier (compiled into .glacier/models/) or <name>.rs, re-exporting what each defines. glacier::app!(): all of an app’s src/lib.rs. Declares every folder and file under src/ (no mod.rs lists: a folder’s files are re-exported from it, src/jobs/ gets jobs::all()), the migrations in db/migrations/ and db/<name>/migrations/, and app(config, repo): the config and database, migrations, seeds and jobs, then src/app.glacier’s settings, public/’s static files and the routes.
clients
clients!(stripe): declares an app’s clients for other services, from src/clients/<name>.glacier (client Stripe do … end) or <name>.rs, re-exporting each.
config
The app’s configuration: Config::load() (reading config/*.toml) in debug builds, and the same files compiled into the binary in release builds. Environment variables override either.
controllers
Declares the app’s controller modules, from .glacier or .rs files.
folder
folder!() in a folder’s mod.rs (src/policies/mod.rs): every .glacier and .rs file in the folder, declared and re-exported, with no list to keep.
jobs
jobs!(send_report): declares an app’s background job modules (from src/jobs/<name>.rs), re-exports each job, and generates all(), the Jobs registering every one (SendReport for send_report), for App::jobs(jobs::all()).
json
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.
mailers
mailers!(report_mailer): declares an app’s mailers, from src/mailers/<name>.glacier (mailer ReportMailer do … end) or <name>.rs, re-exporting each.
middleware
middleware!(require_admin): declares an app’s middleware, from src/middleware/<name>.glacier (middleware RequireAdmin do … end) or <name>.rs, re-exporting each.
migrations
migrations!() in src/lib.rs: the app’s migrations, every m<version>_<name>.glacier (or .rs) in db/migrations/, oldest first, as pub mod migrations with all() for App::migrations. migrations!(analytics): a named database’s, from db/analytics/migrations/, as analytics_migrations.
models
modules
modules!(slack, helpers): declares an app’s modules from src/<name>.glacier (module Slack do … end) or src/<name>.rs, re-exporting each, for src/lib.rs.
or_else
a || b in .glacier: a unless it’s false or None (an Option’s value when it has one), else b, which runs only then and is converted to a’s type (Option<String> || "x" is a String).
parallel
Runs several fallible futures at once and gives their values together, or the first error: parallel(Catalogue.prices(s), Rates.latest())! in .glacier, glacier::parallel!(a, b).await? in Rust. They run in this task, side by side, so the request’s database connection and access come along.
paths
Route pattern constants and path helpers from one definition.
redirect
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:
routes
The route table: generates draw() for App::routes and a *_path() helper per named route, from one declaration.
seeds
seeds!(): declares the app’s seeds module, from src/seeds.glacier or src/seeds.rs; see App::seeds.
serializers
serializers!(country_serializer): declares an app’s serializer modules, from src/serializers/<name>.glacier (compiled into .glacier/serializers/) or <name>.rs, re-exporting each serializer.
serve
glacier::serve!(): all of an app’s src/main.rs, serving app() with the config in config/ (or running a command, app migrate).
services
services!(report_detail): declares an app’s service modules (plain objects for code that belongs to no one model), from src/services/<name>.glacier or <name>.rs.
static_files
Middleware serving a folder of static files: from disk in debug builds, and from copies compiled into the binary in release builds, with ETags from their contents.
tests
tests!(controllers::posts, factories::post): declares an app’s .glacier test files (tests/controllers/posts.test.glacier, tests/factories/post.glacier) as modules of the test crate, nested like their folders, and the app they test.
validate
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.
views
Generates a struct per template in src/views/; see glacier::view.

Structs§

Method
The Request Method (VERB)
StatusCode
An HTTP status code (status-code in RFC 9110 et al.).

Functions§

authorize
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, returning a bool or a Decision, whose denial keeps its status and message (deny :not_found).

Attribute Macros§

controller
Turns an impl block into a controller; see glacier::controller.
enumeration
An enum stored as text in a column ("draft"), with predicates (is_draft()), parsing and form casting. See glacier::db.
main
Marks the async entry point of a Glacier application, starting a multi-threaded Tokio runtime. Apps don’t need to depend on Tokio directly.
model
Makes a struct a model: adds id and timestamps, makes fields pub, and derives Debug, Clone, Serialize and Model.
scopes
Named, chainable queries on a model: each fn name(query: Query<M>, …) -> Query<M> becomes M::name(…) and a method on Query<M> (through an MScopes trait), so Post::published().recent() chains.
test
An async test, run on a single-threaded Tokio runtime, so apps don’t need Tokio as a dependency.

Derive Macros§

Model
Derives glacier::Model. See the trait docs for details.