glacier-web-cli 0.4.0

Command-line tool for creating and running Glacier applications.
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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
# 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
<!-- src/views/posts/index.html -->
{% props posts: Array<Post> %}
<h1>Posts</h1>
{% for post in posts %}
  {{ link_to(&post.title, post) }}
{% end %}
```

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

  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.changed("title")                         # dirty tracking; post.was("title")
post.destroy()!                               # with before_destroy/after_destroy
```

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`), 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])`.
`glacier::pagination::Page` reads `page`/`per_page` 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(&params, ["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]`, as Rails apps often do, and `locale()` reads it:

```elixir
faqs = FaqSection.where(locale: locale())!
```

`glacier::i18n::load("config/locales")` reads a Rails app's locale YAML,
and `t("versions.ios.warning")` translates in the current locale.
`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, 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.
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(…)`.
- **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&#39;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.
  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; controllers with convention-based
rendering and compiled templates (with the app's own helpers, called by
name); 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); 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; 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

| Path | What |
| --- | --- |
| `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.