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")?)).
| 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 |
| 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 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_sizeand_updated_atcolumns describing it. - auth
- The pieces
glacier generate authenticationbuilds on: password hashing, session tokens and bearer tokens. The generated app code (aUserandSessionmodel, a sessions controller and anAuthenticationmiddleware) is yours to read and change, as with Rails’ and Phoenix’s generators. - authorization
- Checking that every action authorized, as Pundit’s
verify_authorized: putVerifyAuthorizedon a pipeline, and an action there that answers without callingauthorize(orskip_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
Contexthanded 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
OPTIONSrequests 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’encryptsdoes. 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
Hostheader names another is refused with403, as Rails’config.hostsdoes. 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
Enumerableand Elixir’sEnumgive: on anyVec, slice or loadedhas_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::lockand Rails’with_advisory_lock: - 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’
Mimeregistry knows them:/posts/1.jsonorAccept: application/jsonasks for JSON. - model
- Database models.
- notify
- One Postgres
NOTIFYchannel 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 openapiwrites it. - pagination
- Pages of records, with the
Link,Per-PageandTotalheaders that Rails’ api-pagination gem sends: - 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:limitattempts perperiodfor each key, counted in fixed windows in the cache (cache::increment). - request
- The current request, available without passing
Contextaround. - response
- HTTP responses and the
IntoResponseconversion trait. - retry
- Running work again when it fails:
retry times: 3, wait: 1.seconds() do … endin.glacier, as Laravel’sretryand Ruby’sretry. - 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(¶ms)?in the action refuses the form with422when 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
Storeon 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.glacierholds them: - telemetry
- Where logs and traces go.
- testing
- In-process testing: drive an
Appwithout 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-datarequest. - values
- Values as
.glacierreads them:a || b, Ruby’s “a, or else b”, and Ruby’s conversions,to_s,to_iandto_f. - view
- Views: compiled templates.
- webhooks
- Receiving webhooks: verify the sender’s signature, store the event
once, answer
200at 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, fromsrc/models/<name>.glacier(compiled into.glacier/models/) or<name>.rs, re-exporting what each defines.glacier::app!(): all of an app’ssrc/lib.rs. Declares every folder and file undersrc/(nomod.rslists: a folder’s files are re-exported from it,src/jobs/getsjobs::all()), the migrations indb/migrations/anddb/<name>/migrations/, andapp(config, repo): the config and database, migrations, seeds and jobs, thensrc/app.glacier’s settings,public/’s static files and the routes.- clients
clients!(stripe): declares an app’s clients for other services, fromsrc/clients/<name>.glacier(client Stripe do … end) or<name>.rs, re-exporting each.- config
- The app’s configuration:
Config::load()(readingconfig/*.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
.glacieror.rsfiles. - folder
folder!()in a folder’smod.rs(src/policies/mod.rs): every.glacierand.rsfile in the folder, declared and re-exported, with no list to keep.- jobs
jobs!(send_report): declares an app’s background job modules (fromsrc/jobs/<name>.rs), re-exports each job, and generatesall(), theJobsregistering every one (SendReportforsend_report), forApp::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, aStatusCodeor a snake_case name. - mailers
mailers!(report_mailer): declares an app’s mailers, fromsrc/mailers/<name>.glacier(mailer ReportMailer do … end) or<name>.rs, re-exporting each.- middleware
middleware!(require_admin): declares an app’s middleware, fromsrc/middleware/<name>.glacier(middleware RequireAdmin do … end) or<name>.rs, re-exporting each.- migrations
migrations!()insrc/lib.rs: the app’s migrations, everym<version>_<name>.glacier(or.rs) indb/migrations/, oldest first, aspub mod migrationswithall()forApp::migrations.migrations!(analytics): a named database’s, fromdb/analytics/migrations/, asanalytics_migrations.- models
- modules
modules!(slack, helpers): declares an app’s modules fromsrc/<name>.glacier(module Slack do … end) orsrc/<name>.rs, re-exporting each, forsrc/lib.rs.- or_else
a || bin.glacier:aunless it’sfalseorNone(anOption’s value when it has one), elseb, which runs only then and is converted toa’s type (Option<String> || "x"is aString).- 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 Otherto a path or a record (viaToPath), optionally setting flash messages, and evaluates to aglacier::Result.status: "found"(in.glacier,status: :found) picks another status, such as the302Rails’redirect_tosends by default: - routes
- The route table: generates
draw()forApp::routesand a*_path()helper per named route, from one declaration. - seeds
seeds!(): declares the app’sseedsmodule, fromsrc/seeds.glacierorsrc/seeds.rs; seeApp::seeds.- serializers
serializers!(country_serializer): declares an app’s serializer modules, fromsrc/serializers/<name>.glacier(compiled into.glacier/serializers/) or<name>.rs, re-exporting each serializer.- serve
glacier::serve!(): all of an app’ssrc/main.rs, servingapp()with the config inconfig/(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), fromsrc/services/<name>.glacieror<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.glaciertest 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/; seeglacier::view.
Structs§
- Method
- The Request Method (VERB)
- Status
Code - An HTTP status code (
status-codein RFC 9110 et al.).
Functions§
- authorize
- Checks a permission:
Err(403 Forbidden)unless allowed.authorize report.editable_by(&user)!in.glacier, as Laravel’sGate::authorizeor CanCan’sauthorize!; the rules themselves are the app’s own methods, returning aboolor aDecision, whose denial keeps its status and message (deny :not_found).
Attribute Macros§
- controller
- Turns an
implblock into a controller; seeglacier::controller. - enumeration
- An enum stored as text in a column (
"draft"), with predicates (is_draft()), parsing and form casting. Seeglacier::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
idand timestamps, makes fieldspub, and derivesDebug,Clone,SerializeandModel. - scopes
- Named, chainable queries on a model: each
fn name(query: Query<M>, …) -> Query<M>becomesM::name(…)and a method onQuery<M>(through anMScopestrait), soPost::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.