# Glacier
A batteries-included web framework for Rust, inspired by Rails, Phoenix and
Laravel. Controllers, models and tests are written in `.glacier`, an
Elixir-flavoured syntax that compiles to Rust at build time. Routes and
anything else are Rust, and Rust works everywhere `.glacier` does.
```elixir
# src/controllers/posts_controller.glacier
module PostsController do
implements Controller
def index do
posts = Post.order(inserted_at: :desc)!
render posts, title: "Posts"
end
def create(ctx) do
post = Post.build(ctx.params())
if post.save()! do
redirect post, notice: "Post created."
else
render :new, post, title: "New post", status: 422
end
end
end
```
```elixir
# src/models/post.glacier
module Post do
implements Model
field title: String, required
field body: Option<String>
field published: bool
# Deleting a post deletes its comments, with their callbacks.
has_many :comments, dependent: :destroy
# A writer's form: the title and body, never `published`.
changeset draft do
cast :title, :body
validate :title, length(max: 80)
end
# Written in the last day.
def fresh(self) -> bool do
self.inserted_at > 1.days().ago()
end
end
```
```elixir
# src/routes.glacier
routes do
pipeline browser = Pipeline.browser()
scope "/", through: :browser do
get "/", PagesController.home, as: :home
resources "/posts", PostsController do
# /posts/:post_id/comments, with post_comments_path(post_id)
resources "/comments", CommentsController, only: [:index, :create]
end
end
end
```
```html
{% props posts: Array<Post> %}
<h1>Posts</h1>
{% for post in posts %}
{{ link_to(&post.title, post) }}
{% end %}
```
Components, as Phoenix's HEEx calls them, are templates in
`src/components/` whose props are their attributes and slots, each call
checked when the app builds:
```html
{% props title: String, inner_block: Slot %}
<section class="card"><h2>{{ title }}</h2>{{ inner_block }}</section>
<.card title={post.title.clone()}>{{ post.body }}</.card>
```
New apps are styled with Tailwind CSS, with no Node: every build turns
`assets/app.css` into `public/assets/app.css` with Tailwind's standalone
program, downloaded once and checked, so `cargo build` and `glacier
server` keep it current and release builds embed it; `glacier new
--no-tailwind` keeps a plain stylesheet. Under `glacier server`, a
template edit that leaves its code alone (markup, classes, wording) shows
without a rebuild, and the page reloads itself. `glacier new --vite`
bundles JavaScript with Vite: `glacier server` runs its dev server, a
release build runs `vite build` and embeds the output, and `{{
vite("assets/js/app.js") }}` links either.
Every new app also gets a component library of about 140 components in
`src/components/` (buttons, forms wired to their fields, tables, dialogs,
tabs, charts drawn on the server, and more), with design tokens for light
and dark themes and the Geist fonts served by the app. They work without
JavaScript; a small `public/ui/ui.js` opens dialogs in browsers that lack
invoker commands. `/dev/components` shows each one's examples in the
app's own layout.
These are taken from `examples/hello`, a small blog made with `glacier new`
and `glacier generate scaffold`, then grown to show more:
- Comments on posts, deleted with their post, and the seeds a new
database starts with (`src/seeds.glacier`).
- `db/schema.sql`, the whole schema, rewritten by each migration.
- A JSON feed at `/api/posts` with a serializer, cursor pagination and
sorting from an allowlist (`src/controllers/feed_controller.glacier`).
- A job that publishes a post an hour later (`src/jobs/publish_post.glacier`),
unique per post, so scheduling it twice queues it once.
- Mail: a comment emails the post's author (`src/mailers/comment_mailer.glacier`,
with HTML and text templates), queued with `deliver_later` in the
comment's transaction; previews at `/dev/mail` in development.
- A weekly digest of each author's comments, sent on Monday mornings with
`cron "0 9 * * mon"` in the job, and drafts untouched for a year pruned
by the model's `prune do`.
- The feed's pages cached with `cache::fetch`, under a key from
`cache::key(&post, …)` that changes when a post is saved or commented
on, and an `ETag` on every response, so an unchanged feed is a `304`.
- Tests for all of it, which move the clock with `travel` and `travel_to`,
check the queue with `enqueued_jobs()`, run the schedule with
`enqueue_recurring()`, and read the mail sent with `delivered_mail()`.
## Why
- **Rust is fast.** Compiled ahead of time, no garbage collector, async on
hyper and Tokio, so an app gets a lot out of a small server.
- **Code should be written for humans to read.** AI writes more code than
ever (it wrote much of this repository), and someone still has to review
it. Rust is powerful but not the easiest language to read. Rails has
always put readability for people first; Glacier brings that to Rust.
`.glacier` reads like Elixir or Ruby, and compiles to Rust, so you can
drop to Rust syntax whenever you need it.
- **The compiler is the first reviewer.** Templates, routes, path helpers
and query columns are all compiled, so a typo is a build error rather
than a 500 in production. Errors point at your `.glacier` line, which
keeps the fix loop short for people and for AI agents alike.
- **Conventions mean less to read.** Every app has the same layout, and the
generators write controllers, models, views and their tests the same
way, so code is where you expect it and a review starts from what's
different.
- **One binary to deploy.** A release build is a single executable with
its templates, migrations, config and static files built in: copy it to
a server, point it at a database, and run it. No interpreter or runtime
to install, quick to start, and small enough to run many apps on one
server.
- **Rust's ecosystem, not a new one.** Everything compiles to ordinary
Rust, so cargo, crates.io, rust-analyzer and clippy all keep working.
`.glacier` is a layer you can step out of, not a separate language.
## Models, Active Record style
Models declare their fields, validations, associations, scopes, methods and
callbacks in one place:
```elixir
# src/models/post.glacier
module Post do
implements Model
field title: String, required, length(max: 200)
field slug: String, unique, format: "^[a-z0-9-]+$"
field views: i32, numericality(greater_than_or_equal_to: 0)
field status: enum(draft, published), default: :draft
belongs_to :author
has_many :comments
has_one :latest_comment, Comment, latest: :inserted_at
scope published, where(status: :published)
scope by(author_id: i64), where(author_id: author_id)
def excerpt(self) -> String do
self.title.chars().take(140).collect()
end
def publish(self) do
self.update(status: :published)!
end
before_save do
self.slug = self.title.to_lowercase().replace(" ", "-")
end
end
```
and records work like Rails' Active Record:
```elixir
post = Post.new(title: "Hello")
post.title = "Hello, world"
post.save()! # true, or false with post.errors_on("title")
post.update(status: :published)! # in place; only changed columns are written
Post.where(status: :published, author_id: id).order(inserted_at: :desc)!
Post.published().by(id).limit(5)! # scopes chain
Post.find_by(slug: "hello")!
Post.exists(title: "Hello")!
Post.order(:title).pluck(:title)!
Post.where(published: true).sum(:views)! # also average, minimum, maximum
Post.group(:status).count()! # [("draft", 3), ("published", 5)]
Post.join(:author, name: "Ada").joins(:comments).distinct()!
Post.where(status: :draft).update_all(status: :published)!
Post.order(:inserted_at).limit(100).delete_all()! # only those 100, as Rails
post.changed("title") # dirty tracking; post.was("title")
post.destroy()! # with before_destroy/after_destroy
```
A comment on a post or a photo is a polymorphic association, as in
Rails: `belongs_to :commentable, polymorphic: [Post, Photo]`, with
`has_many :comments, as: :commentable` on each, and
`comment.commentable()!` giving `Commentable.Post(post)` or
`Commentable.Photo(photo)`.
The keyword forms compile to typed column closures, so `where(titel: …)` is
a build error, not a runtime one. Every model also has the Ecto-style
changeset API (`Post.create(params)` returning `Saved`/`Invalid`, with
the model's callbacks, as Rails' `create`), and
models can be plain Rust (`#[glacier::model]`, `#[glacier::scopes]`,
`#[glacier::enumeration]`, `impl Callbacks`). To share the database with
other libraries, `repo.postgres_pool()` and `glacier::sqlx` hand over the
sqlx pool, e.g. to SeaORM.
Migrations say what changes, and roll back by undoing it:
```elixir
# db/migrations/m20261005120000_create_posts.glacier
migration do
create_table :posts do
string :title, null: false
string :status, null: false, default: :draft
references :author, null: false
timestamps
end
add_index :posts, [:status, :inserted_at]
end
```
## Forms, transactions and more than one database
A model can have named changesets, as Ecto's, when forms take different
fields and rules:
```elixir
module Member do
implements Model
field name: String, required
field email: String, required, unique
field admin: bool, protected
changeset signup do
cast :name, :email
validate :name, length(max: 50)
end
changeset staff_edit do
cast :name, :admin # naming a protected field permits it here
end
end
```
```elixir
member = Member.create(Member.signup(ctx.params()))!
```
`transaction do … end` commits a block's writes together; `db::Multi`, as
Ecto's, runs named steps in one transaction and says which failed and why.
For bigger apps:
- **Read replicas:** set `database.replica_url` and GET requests read from
the replica, while writes, and reads after a write, use the primary.
- **More databases:** `[databases.analytics]` in the config and
`implements Model, database: :analytics` put a model in another
database, with its own migrations.
- **N+1 queries:** associations load only through `preload`, and in
development a query repeated in one request logs a warning naming it.
- **Seeds and the schema:** `glacier db setup` migrates and loads
`src/seeds.glacier`; each migration rewrites `db/schema.sql`.
## JSON APIs and serializers
Serializers give a model its JSON shape, as active_model_serializers does
for Rails:
```elixir
# src/serializers/country_serializer.glacier
serializer CountrySerializer do
attributes :id, :iso_code, :name
attribute :label, format!("{} ({})", object.name, object.iso_code)
has_many :installations # every column, or serializer: InstallationSerializer
end
```
```elixir
# src/controllers/countries_controller.glacier
def index(_ctx) do
countries = Country.preload(:installations)!
json countries, each_serializer: CountrySerializer # {"countries": [...]}
end
```
`json` also takes `serializer:` for one record, `root:` (a key, or `false`),
and `status:`. Keys come out in the order written. Models can map an
existing Rails schema: `implements Model, timestamps: false`, `field id: i32`,
and `has_many :installations, through: :countries_installations`.
Settings kept in a JSON column read like fields, as Rails'
`store_accessor`: `store :cache do field timezone: String, default:
"Europe/London" end` gives `info.timezone()`.
Preloads nest, as Rails' `includes`, one query per level:
`Post.preload(:author, comments: [:author, likes: :user])`, and a
query in place of a list loads only what it matches:
`Author.preload(books: Book.where(published: true))`.
`glacier::pagination::Page` reads `page`/`per_page` (capped at 100) and `json posts,
paginate: (page, total)` adds api-pagination's `Link`, `Per-Page` and
`Total` headers. Cursor pagination pages any depth quickly and never skips
a row: `Author.order(:name).sort(¶ms, ["name", "inserted_at"])?
.cursor(page)!` reads `?sort=-inserted_at` from an allowlist and signed
cursors from the client, and `json authors.records, cursor: authors` adds
the `Link` header (`authors.links()` gives JSON:API's `links`). `Decimal` fields hold `numeric` columns exactly and
render as Rails renders a `BigDecimal` (`"50.0"`), and
`glacier::serialize::set_time_format` switches timestamps to Unix seconds
for apps that render them that way.
Associations take `order: :position`, and a model's
`default_scope order(:position).preload(:faq_items)` applies to every
query of it (`FaqSection.unscoped()` skips it).
The `glacier::i18n::Locales` middleware takes the locale from
`params[:locale]` (remembered in a cookie), as Rails apps often do, or
else from the browser's `Accept-Language`, and `locale()` reads it:
```elixir
faqs = FaqSection.where(locale: locale())!
```
A Rails app's locale YAML in `config/locales/` is compiled in, and
`t("versions.ios.warning")` translates in the current locale;
`t("inbox", count: n)` picks the plural form by the locale's rules.
`JsonErrors::body(|status| …)` gives a pipeline's error responses the
app's own JSON shape, as a Rails `rescue_from` does. `unique` checks with a
query before writing, as Rails' `uniqueness` does, so it works without an
index, and takes a scope: `unique(scope: :platform)`.
Tests against an existing schema can use a Postgres test database loaded
from the Rails app's `structure.sql`; each test then runs in a
transaction that is rolled back. Factories skip the fields a test sets,
as FactoryBot does, so `insert(FaqItem, faq_section_id: id)` inserts no
extra section.
`glacier openapi` prints an OpenAPI 3.1 document built from the routes,
what each action responds with and the serializers' schemas, so it can't
drift from the code. APIs can be versioned by path (`scope "/v1"`) or by
header: `scope "/" version "2" { … }` answers `Api-Version: 2`.
## Authentication
`glacier generate authentication` writes sign up, sign in and sign out into
the app, as Rails' `generate authentication` and Phoenix's `phx.gen.auth`
do: `User` and `Session` models with migrations, sessions and registrations
controllers, password resets, sign-in links, email confirmation and
confirmed email changes by mailed links, a `sudo` pipeline that asks for the password again,
two-factor sign-in with an authenticator app, throttles on sign-in
attempts, mailed links and codes, their pages and tests,
`Auth` (`Auth.current_user(ctx)`,
signing in and out) and two middleware, `Authentication` and
`RequireAuthentication` (the `authenticated` pipeline), all in `.glacier`. It's ordinary
app code to read and change, not a library to configure:
```elixir
# src/models/user.glacier (generated)
module User do
implements Model
field email_address: String, required, unique
field password_digest: String, protected
field password: Option<String>, virtual
has_many :sessions
def authenticate_by(email_address: &str, password: &str) -> Option<User> do
user = User.find_by(email_address: User.normalize_email(email_address))!
digest = user.as_ref().map(fn u -> u.password_digest.as_str() end)
if glacier::auth::verify_password(password, digest) do
user
else
None
end
end
...
end
```
```elixir
# Routes for signed-in users only:
scope "/", through: [:browser, :authenticated] do
get "/account", AccountsController.show, as: :account
end
```
Passwords are hashed with Argon2id, and session tokens are random, with
only their SHA-256 digest stored. `--api` writes JSON endpoints that return
a token for `Authorization: Bearer …` instead of using the session cookie.
`glacier::storage::S3Signer` makes presigned S3 URLs (AWS Signature V4, as
Active Storage and Paperclip hand out), and
`glacier::response::escape_html_entities_in_json(true)` writes `<`, `>` and
`&` in JSON as Rails does by default.
Who a request is for is its *Access* (Phoenix's scope): the generator
writes `UserAccess`, and `glacier generate access org` adds orgs whose
members share rows. A model says whose it is, and actions read through
the access, so another user's or org's rows are a `404`, never a leak:
```elixir
module Note do
implements Model
field title: String, required
owned_by :user # or :org
end
notes = Note.for(access).order(inserted_at: :desc)!
note = Note.for(access).build(params) # user_id from the access, never params
```
`owned_by :org, global: true` adds rows every tenant shares (no owner),
which change only in `unscoped "why" do … end`; `glacier generate access
org` writes orgs with roles, invitations by email and an `OrgPolicy`.
Once an app has an Access, `glacier generate scaffold` writes owned
resources by default (`--no-access` for shared ones), with a test that
another tenant gets `404` for every read and write. In tests,
`insert_for(access, Note)` inserts a record that's the access's.
Fields can be stored encrypted and kept out of JSON:
```elixir
field otp_secret: Option<String>, encrypted # AES-256-GCM
field email: String, encrypted(deterministic), unique # still findable
field api_key: String, hidden # never in JSON
```
The key is `encryption.key` (or `secret_key_base`), with
`encryption.previous_keys` to rotate; values Rails' `encrypts` or
Laravel's `Crypt` wrote read too, given their keys. `*_digest` columns are
hidden without saying so. `previous_secret_key_bases` keeps old cookies,
sessions and signed links working when `secret_key_base` changes; `hosts`
(and `url`) refuse requests for other hosts; `trusted_proxies` adds load
balancers to those `remote_ip()` believes. `glacier generate
authentication --impersonation --api-tokens` adds impersonation by staff
and API tokens with scopes (`glacier::auth::require_scope`), as the
`accounts` example has them.
Authorisation rules are the app's own methods, as Laravel's gates are:
`authorize report.editable_by(&user)!` answers `403 Forbidden` unless the
rule allows it.
An existing app's users can sign in too: `glacier::auth::verify_password`
checks the bcrypt hashes Devise and `has_secure_password` store, as well as
Argon2. `glacier::middleware::Throttle` limits requests per key (an email,
an IP) as Rack::Attack and Rails 8's `rate_limit` do, shared by every
server with the database cache store (and `RateLimit.attempt(key, 5,
1.minutes())!` limits anything in code, as Laravel's `RateLimiter`), and
`ctx.remote_ip()` finds the client behind trusted proxies as Rails does.
An existing app's tokens work too: `glacier::auth::jwt` signs and checks
HS256 JSON Web Tokens exactly as Ruby's `jwt` gem does, so a Glacier app
can accept the tokens a Rails app issues (and the other way round) while
endpoints move across.
## Authorization
Rules are the app's own functions; by convention a policy per model, as
Laravel's:
```sh
glacier generate policy Post # src/policies/post_policy.glacier
```
```elixir
module PostPolicy do
def update(user: &User, post: &Post) -> bool do
post.user_id == user.id
end
end
```
`authorize PostPolicy.update(user, post)` in an action answers `403` when
the rule says no. A rule can return a `Decision` instead, `allow` or `deny
:not_found` (or `deny "message"`), and `authorize` answers with that. Put `VerifyAuthorized` on a pipeline and an action there
that answers without `authorize` (or `skip_authorization`, for a public
one) is an error outside production, as Pundit's `verify_authorized`.
Middleware wraps the requests of a pipeline's routes (or every request).
It answers by itself, or passes the request on with `next(ctx)` and
returns the response, changed or not:
```sh
glacier generate middleware RequireAdmin # src/middleware/require_admin.glacier
```
```elixir
module RequireAdmin do
implements Middleware
def call(ctx, next) do
if session.get::<bool>("admin") == Some(true) do
return next(ctx)
end
redirect home_path(), alert: "Admins only."
end
end
```
## Background jobs
Jobs live in the database, as Rails' Solid Queue keeps them: queued in the
same transaction as the work that asks for them, run by workers that
`glacier server` starts, retried with backoff, and left marked failed after
their last attempt.
```sh
glacier generate job SendReport report_id:bigint # src/jobs/send_report.glacier
```
```elixir
# src/jobs/send_report.glacier
module SendReport do
implements Job
queue: :mailers
arg report_id: i64
unique_by report_id
def perform do
report = Report.find(report_id)!
ReportMailer.ready(&report).deliver_now()!
end
end
```
Queue one with `SendReport { report_id: id }.enqueue()!`, or later with
`enqueue_in(30.days())` or `enqueue_at(time)`. Jobs can have priorities,
queues with workers of their own, a unique key (one waiting at a time)
and an expiry, each a line in the `job` block. A recurring job says when
in its own block, and is queued once however many servers are running:
```glacier
module NightlyDigest do
implements Job
cron "0 3 * * *"
def perform do … end
end
```
Settings for every job, such as a queue's workers, go in the app's
`jobs do` block (`queue :mailers, workers: 3`).
On Postgres, workers wake the moment a job is queued. `glacier jobs`
shows the queue and its failures; `glacier jobs retry ID` runs one again.
A job can have a `timeout` and `discard_on :not_found`; `app work` runs
the jobs in a process of their own (`app web` the server alone), and on
SIGTERM running jobs finish before the process exits. In tests, `enqueued_jobs()!` lists what's queued and `perform_jobs()!`
runs it.
## Mail
A mailer builds each mail from an HTML and a text template;
`deliver_later` sends it from a job, only if the transaction that asked
for it commits:
```sh
glacier generate mailer ReportMailer ready # src/mailers/report_mailer.glacier, src/views/report_mailer/ready.{html,txt}
```
```elixir
module ReportMailer do
implements Mailer
layout: :mailer
def ready(report: &Report) do
mail to: &report.requested_by, subject: "#{report.title} is ready"
end
end
```
and send it with `ReportMailer.ready(&report).deliver_later()!`.
SMTP, SendGrid or Postmark in production (`[mail]` in the config); in
development, sent mail and previews are at `/dev/mail`; in tests,
`delivered_mail()` lists what was sent, and nothing leaves the process.
## File uploads
An attachment on a model, kept on disk or in S3 (`[storage]` in the
config) with a resized copy per style, as Paperclip keeps them:
```elixir
module Photo do
implements Model
field title: String, required
has_attached :image, styles: [medium: "640x480", thumb: "100x100"]
end
```
`photo.image = file("image")` and `photo.save()!` store it,
`photo.image_url("thumb")` links to it, and `destroy` removes it.
## Other services: HTTP clients and webhooks
A client per service, with its base URL and credentials; failures are
typed errors, and tests answer requests from stubs instead of the
network:
```elixir
module ConvertKit do
implements Client
base: "https://api.convertkit.com/v3"
query_auth: ["api_key", secret("convert_kit.api_key", "CONVERTKIT_API_KEY")]
def subscribe(form_id: i64, email: &str) -> JsonValue do
post("forms/#{form_id}/subscribe").json(&json!({"email": email})).fetch()!
end
end
```
Webhooks are verified, stored once, answered at once, and handled in a
job; `glacier generate webhook stripe` sets one up, and
`glacier webhooks replay ID` handles an event again.
## How `.glacier` works
The app's `build.rs` compiles each `.glacier` file into ordinary Rust, line
for line, in a hidden, git-ignored `.glacier/` folder. `create` above
becomes:
```rust
// .glacier/controllers/posts_controller.rs (generated)
async fn create(ctx: Context) { let mut params = ctx.params();
let mut post = Post::build(params);
if post.save().await? {
redirect!(post, notice: "Post created.")
} else {
render!(post; template = new, title = "New post", status = 422)
}
}
```
`src/` holds only what you write, with no lists of files: every file
under `src/` is found when the app builds. The app itself is
`src/app.glacier`, an `app do` block of its own settings
(`middleware Logger`); its config, database, migrations, jobs and routes
are added for you, and `src/lib.rs` and `src/main.rs` are one line each,
`glacier::app!()` and `glacier::serve!()`. As in Rails, models need no import: controllers,
models, serializers and tests all see every model. `alias Serializers.X`
(or any `alias Module.Name`) brings in anything else.
- **Plain tools work.** `cargo build`, `cargo test` and clippy work
unchanged, and any crate from crates.io can be used.
- **Errors point at your file.** Compiler errors land on the `.glacier`
line, which is the same line number as the generated Rust.
- **Editor support.** `glacier lsp` proxies rust-analyzer, so hover,
go-to-definition and errors work in `.glacier` files, and formats them.
The [VS Code extension](https://github.com/glacierlabsltd/glacier-vscode)
adds highlighting and starts it; any editor with an LSP client can point
at `glacier lsp`.
- **One format.** `glacier fmt` (or `--check` in CI) lays out `.glacier`
files canonically.
- **Variables work as in Ruby.** `total = 0` binds a name; assigning to it
inside an `if` or loop updates it, rather than making a new one that ends
with the block. `(posts, total) = load()!` destructures.
- **Lists and errors as in Ruby.** `books.map(:title)`, `books.sum(:pages)`
and `books.filter(fn b -> b.published end)` need no `.iter()` or
`.collect()`; `raise Error.not_found()` ends an action with an error,
and an action's last value is its response, with no `Ok(…)`.
- **Text and numbers for people.** `title.parameterize()`,
`body.truncated(140)`, `"book".pluralize(n)`, `price.to_currency("GBP")`,
`1234567.delimited()`, `3.ordinal()`, `size.human_size()`, with the
request's locale's separators (`1.234,50 €` in German).
- **Rust when you want it.** `.rs` and `.glacier` controllers mix in one
app, and `--dialect rust` makes the generators write plain Rust.
The dialect is an experiment.
## Tests in `.glacier`
Tests read the same way, ExUnit-style. Every generator writes them: the
scaffold writes `tests/controllers/posts_controller.test.glacier`,
`tests/models/post.test.glacier` and a factory in
`tests/factories/post.glacier`. The controller tests start:
```elixir
# Load a form first, as a browser would, for its CSRF token.
setup do
get "/posts/new"
end
test "rejects a post without title" do
res = post "/posts", params_for(Post), title: ""
assert res.status == :unprocessable_entity
assert res.body =~ "can't be blank"
end
test "deletes a post" do
post = insert(Post)
res = delete post
assert res.status == :see_other
assert get(post).status == :not_found
end
```
- **Every test gets a fresh, migrated database** and its own client, which
keeps cookies and the CSRF token like a browser, so there's no setup
code to repeat.
- **Factories** in `tests/factories/` give `insert(Post)` and
`params_for(Post)` valid fields to start from; override any per call,
or name a trait for a variant: `insert(Loan, :overdue)` (a trait is a
block, or one line: `trait :long, due_at: 28.days().from_now()`);
`insert_list(Loan, 3)` makes several.
Model tests check validations with
`assert errors_on(saved) =~ "title can't be blank"`.
- **Failures explain themselves** and point at the `.glacier` line:
```text
panicked at tests/controllers/pages_controller.test.glacier:4:3:
assertion failed: res.body =~ "is running on Rails"
expected to contain: "is running on Rails"
but was: "<!doctype html>…"
```
- **Time can move.** `travel(15.days())`, `travel_to("2026-10-19T09:00:00Z")`
and `freeze_time()` move the clock that timestamps, due jobs and
`Timestamp.now()` read, per test.
- `describe "…" do` groups tests, `test "…", skip: "why" do` skips one,
and `def` defines helpers (calls to them are awaited for you).
`tests/glacier.rs` declares them all with
`glacier::tests!(controllers::posts_controller, factories::post, models::post, …)`, so
they build into one test binary, named by folder
(`controllers::posts_controller::lists_posts`). Run them with `cargo test`, or
`glacier test` to see `.glacier` paths in failures.
Templates, routes and queries are all compiled, so a typo in a template
expression, a link to a missing route or a misspelled column is a build error,
not a 500.
## Before a commit
`glacier audit` looks for security problems in the source, and `glacier
precommit` runs formatting, clippy, the tests and the audit before a
commit.
## For AI agents
Agents are first-class users. `glacier mcp` is a
[Model Context Protocol](https://modelcontextprotocol.io) server that teaches
an agent the language and checks what it writes: it searches the guides,
gives the `.glacier` syntax and the app's conventions, lists routes,
models, symbols and the database schema, shows what a model's save runs in
order, finds definitions and references (and renames), returns compile
errors as data located in `.glacier` source (with the syntax expected and
rustc's suggested fixes), shows the generated Rust, gives the app's
OpenAPI document, runs read-only queries, and runs the formatter, tests,
generators and migrations. The guides are built in, with their code
examples. Before 0.2's release, an agent that knew Glacier only through
the MCP ported two endpoints of the Rails app below, and they answered as
Rails does.
New apps come with an `AGENTS.md` (the conventions, for agents without the
MCP) and a `.mcp.json`, so Claude Code and other clients that read it start
the server in the app. Elsewhere: `claude mcp add glacier -- glacier mcp`.
`glacier check --json` prints the same errors for any other tool. The
guide [Working with AI Agents](guides/source/ai_agents.md) lists every tool.
## Status
Early, but proven on real apps: a production Rails 6.1 JSON API was
ported endpoint by endpoint, and every route answers as Rails does
(checked by sweeps of its reads, writes, uploads and errors), or differs
for a written-down reason such as a Rails crash; it and a Rails store are
written in `.glacier` end to end.
Glacier has a route table with Phoenix-style pipelines, nested resources,
constraints and generated path helpers (with query params by name);
controllers with convention-based
rendering and compiled templates (with the app's own helpers, called by
name, and layout values middleware `assign`s); JSON APIs with serializers
(`glacier new --api`); an Active Record-style ORM for Postgres and SQLite
(validations, callbacks, associations with `through`, `dependent`, `touch`
and nested attributes, joins and aggregates, named changesets,
migrations, multi-step transactions, read replicas and more than one
database, with exact decimal sums on SQLite too); cursor pagination and OpenAPI; file uploads to disk or
S3; an authentication generator (resets, sign-in links, two-factor, sudo
mode, throttles); multi-tenant scoping with Access; encrypted and hidden
fields; sessions, flash, CSRF and CORS; config
per environment; an MCP server for AI agents; and the basics for
production: a `/up` health check, JSON logs, and traces of every request
and query, which the optional `glacier-otel` crate exports to any
OpenTelemetry backend; and background jobs in the database, with
priorities, queues, unique and recurring jobs; command-line tasks
(`glacier run reports:requeue 7`, or by name: `--days 10`); mail by SMTP, SendGrid
or Postmark, with previews; an HTTP client; verified webhooks;
caching in memory or the database, with a per-request query cache;
Stripe billing; PDFs from templates through headless Chrome; and safe
HTML from users with `sanitize`. 0.4 makes `.glacier` the way to write
all of it, with Rust as the escape hatch. See
[CHANGELOG.md](CHANGELOG.md).
## Layout
| `crates/glacier` | The framework (`glacier-web` on crates.io, used as `glacier`): server (on hyper), router, controllers, middleware, views, sessions, the `db` ORM, testing |
| `crates/glacier-macros` | `routes!`, `controllers!`, `models!`, `serializers!`, `tests!`, `#[controller]`, `#[model]`, `#[scopes]`, `#[enumeration]`, `render!`, `views!`, `html!`, `config!`, `static_files!`, `#[derive(Template)]`, `#[derive(Model)]`, `#[glacier::main]` |
| `crates/glacier-dialect` | The `.glacier` transpiler and the build-script compiler |
| `crates/glacier-otel` | Optional OpenTelemetry (OTLP) export of Glacier's traces |
| `crates/glacier-inflect` | Pluralizing and case conversion, shared by the crates |
| `crates/glacier-cli` | The `glacier` command (`glacier-web-cli` on crates.io): `new`, `server`, `build`, `test`, `check`, `fmt`, `compile`, `lsp`, `mcp`, `routes`, `openapi`, `db`, `generate`, `secret` |
| `examples/hello` | A small blog: what `glacier new` + `glacier generate scaffold Post …` produce, grown with comments, seeds, a cached JSON feed, mail to authors, and unique, recurring and pruning jobs, all tested |
## Getting started
Glacier needs Rust 1.94 or later. Install the `glacier` command from
crates.io, then make an app:
```sh
cargo install glacier-web-cli
glacier new blog && cd blog
glacier generate scaffold Post title:string body:text:optional published:boolean
glacier generate model Tag name:string:unique # or just a model, with its tests
glacier generate controller Reports summary # or just a controller, with its tests
glacier db setup # migrate, then load src/seeds.glacier
glacier server # rebuilds on every change; visit /posts
glacier test # the generated tests (or cargo test)
glacier new shop-api --api # a JSON API: no views or CSRF, errors as
# JSON; scaffolds there are JSON controllers
```
New apps depend on `glacier-web` from crates.io (used in code as
`glacier`). Their release builds use `lto = "fat"`, `codegen-units = 1`
and `panic = "abort"`: slower to build, faster to run, and a panic ends
the process (run it under a supervisor that restarts it, as most hosts
do), where with unwinding Glacier would answer that one request with a
500. `config/default.toml` names the app (`name = "My Shop"`), which
two-factor sign-in shows in authenticator apps.
## Working on Glacier
From a checkout, `glacier new` makes apps that use the checkout's crates:
```sh
cargo install --path crates/glacier-cli
cargo build -p glacier-web-cli # or just build: target/debug/glacier
cd examples/hello && ../../target/debug/glacier db migrate && ../../target/debug/glacier server
# http://127.0.0.1:4000/posts
cargo test --workspace
GLACIER_TEST_POSTGRES_URL=postgres://$USER@localhost/glacier_framework_test cargo test --workspace
```
See [CONTRIBUTING.md](CONTRIBUTING.md) before sending changes.
## Licence
Glacier is released under the [MIT licence](LICENSE), copyright Glacier
Labs Ltd. See [CONTRIBUTING.md](CONTRIBUTING.md) to get involved.