Skip to main content

ocre/
lib.rs

1//! Ocre: a Rails-like Rust web framework for Cloudflare Workers, built to run
2//! on the Workers free plan and to be written by AI agents.
3//!
4//! An Ocre app is one Worker compiled to WebAssembly. Requests go through
5//! [`serve`], which runs a plain [axum](https://docs.rs/axum) router with
6//! sessions, CSRF protection, CORS and security headers. Handlers reach the
7//! Worker's bindings (D1, KV, R2, Queues, Durable Objects, email) through the
8//! per-request [`Ctx`]. The `ocre` command-line tool (crate `ocre-cli`)
9//! generates the app, its models, scaffolds and migrations, and deploys it.
10//!
11//! Guides, references and the generated app's conventions are on the
12//! documentation site, <https://ocre.rs>; a one-page list of every public
13//! item is its [API index](https://ocre.rs/api-index.html).
14//!
15//! # Design rules
16//!
17//! - **Plain axum handlers.** Every Ocre type is `Send`, so handlers never
18//!   need `#[worker::send]`. Extractors ([`Session`], [`Flash`], [`Json`],
19//!   [`Page`], [`storage::Multipart`], [`i18n::I18n`], [`cache::Conditional`])
20//!   and responses ([`Created`], [`cache::CacheControl`], [`cache::ETag`])
21//!   are ordinary axum types.
22//! - **One way to do each thing.** SQL with `?N` placeholders and
23//!   [`params!`], askama templates compiled at build time, htmx for
24//!   interactivity, a single [`Error`] type that knows its HTTP status.
25//! - **Errors name the fix.** A missing binding answers 500 and logs which
26//!   `cloudflare.config.ts` entry to add; internal details are logged, never shown
27//!   to users.
28//! - **Free plan first.** Nothing costs a request, a KV write or a database
29//!   row unless the app asks for it: sessions live in an encrypted cookie
30//!   (no storage), static files are served by Workers Static Assets before
31//!   the Worker runs, R2 downloads stream without passing through
32//!   WebAssembly, and features that add binary size or startup CPU
33//!   (GraphQL, realtime) are opt-in cargo features. The free plan allows
34//!   10 ms of CPU per request; functions note their cost in D1 rows, KV
35//!   operations, Queue operations, R2 operations or CPU where it matters.
36//!
37//! # Modules
38//!
39//! | Module | Contents |
40//! |---|---|
41//! | crate root | [`serve`], [`Ctx`], [`Db`], [`params!`] and [`Query`] / [`Paginated`] (D1), [`Error`] / [`Result`], [`Json`] / [`ApiError`] / [`Page`] (JSON APIs), [`Session`] / [`Flash`] / [`Cookies`], [`Validator`], [`NestedForm`] (bracketed form names), request helpers ([`Format`], [`RemoteIp`], [`RequestId`], [`redirect_back`], [`percent_encode`]), `render` / `error_page` / `Htmx` / `HxRedirect` (feature `html`), serde helpers ([`optional`], [`patch`], [`bool_from_sql`], ...) |
42//! | [`alerts`] | Owner alerts by email (`ALERT_EMAIL`): deduplicated per reason and key, an hourly cap, a digest of what was held back |
43//! | [`bulk`] | Many rows in one D1 statement: `bulk::insert`, `upsert` and `update` (one JSON parameter, `json_each`) |
44//! | [`cache`] | Read-through values in Workers KV, `Cache-Control`, `ETag` and `304 Not Modified` |
45//! | [`config`] | Typed app settings from Worker variables and secrets (`ctx.config::<Settings>()`), the environment (development or production) |
46//! | [`encryption`] | Encrypted model columns (AES-256-GCM keyed from `SECRET_KEY_BASE`), deterministic for lookups |
47//! | [`errors`] | Error reporting (Rails' `Rails.error`): `ctx.errors().report / handle / record`, subscribers such as Sentry |
48//! | [`events`] | Structured events (Rails' `Rails.event`): `ctx.events().notify(name, payload)`, tags, context, subscribers |
49#![cfg_attr(
50    feature = "html",
51    doc = "| [`filters`] | Ocre's view helpers as askama filters: `{{ price\\|number_to_currency(\"$\") }}` (feature `html`) |"
52)]
53#![cfg_attr(
54    not(feature = "html"),
55    doc = "| `filters` | View helpers as askama filters (feature `html`, off in this build) |"
56)]
57#![cfg_attr(
58    feature = "graphql",
59    doc = "| [`graphql`] | `/graphql` endpoint and GraphiQL for an async-graphql schema (feature `graphql`) |"
60)]
61#![cfg_attr(
62    not(feature = "graphql"),
63    doc = "| `graphql` | `/graphql` endpoint and GraphiQL (feature `graphql`, off in this build) |"
64)]
65//! | [`helpers`] | Rails' view helpers: numbers (`number_to_currency`...), times (`time_ago_in_words`, `strftime`), text (`excerpt`, `highlight`) |
66//! | [`http`] | Outgoing HTTP requests to other services: JSON, timeouts, `Send` futures for handlers |
67//! | [`i18n`] | Translations from `locales/*.yml`, plurals, the request's locale |
68//! | [`jobs`] | Background jobs on Cloudflare Queues, scheduled tasks on Cron Triggers |
69//! | [`jwt`] | HS256 JSON Web Tokens for API clients |
70//! | [`log`] | Structured logging to Workers Logs: levels, request-scoped fields (`ctx.log()`), JSON lines |
71//! | [`mail`] | Sending email (log, Resend, Cloudflare adapters) and receiving it from Email Routing |
72//! | [`oauth`] | "Sign in with GitHub / Google": OAuth 2.0 code flow with PKCE |
73//! | [`password`] | PBKDF2-HMAC-SHA256 password digests |
74#![cfg_attr(
75    feature = "push",
76    doc = "| [`push`] | Web push notifications: VAPID keys, RFC 8291 encryption, sending (feature `push`) |"
77)]
78#![cfg_attr(not(feature = "push"), doc = "| `push` | Web push notifications (feature `push`, off in this build) |")]
79#![cfg_attr(
80    feature = "realtime",
81    doc = "| [`realtime`] | WebSocket channels on a Durable Object, htmx broadcasts (feature `realtime`) |"
82)]
83#![cfg_attr(
84    not(feature = "realtime"),
85    doc = "| `realtime` | WebSocket channels on a Durable Object (feature `realtime`, off in this build) |"
86)]
87//! | [`replicas`] | D1 read replicas: reads from a nearby copy, each visitor still reading their own writes (`D1_REPLICAS=on`) |
88//! | [`security`] | Content-Security-Policy (nonces), Permissions-Policy, rate limits, safe redirects, `sanitize` / `strip_tags`, log filtering, HTTP Basic auth |
89//! | [`seo`] | JSON-LD (`seo::json_ld`), `/sitemap.xml` (`Sitemap`, with `hreflang` alternates) and `/llms.txt` (`LlmsTxt`) |
90//! | [`sse`] | Server-Sent Events: stream events to the browser as they happen |
91//! | [`storage`] | Files in Cloudflare R2: multipart uploads, attachments, streamed downloads |
92//! | [`token`] | Random tokens for emailed links and API keys, stored as SHA-256 digests |
93//! | [`webhooks`] | Signed webhooks: HMAC-SHA256 and Standard Webhooks verification, signing outgoing calls, each event processed once |
94//!
95//! # A complete app
96//!
97//! A generated app's `src/lib.rs` (crate type `cdylib`) is the Worker entry
98//! point plus an axum router whose state is [`Ctx`]:
99//!
100//! ```no_run
101//! use axum::{Router, extract::{Path, State}, routing::get};
102//! use ocre::{ApiResult, Ctx, Json, OptionExt, params};
103//! use serde::{Deserialize, Serialize};
104//! use worker::{Context, Env, HttpRequest, event};
105//!
106//! #[event(fetch)]
107//! async fn fetch(req: HttpRequest, env: Env, _ctx: Context) -> worker::Result<worker::web_sys::Response> {
108//!     ocre::serve(routes(), req, env).await
109//! }
110//!
111//! fn routes() -> Router<Ctx> {
112//!     Router::new().route("/up", get(up)).route("/posts/{id}", get(show))
113//! }
114//!
115//! async fn up() -> &'static str {
116//!     "OK"
117//! }
118//!
119//! #[derive(Serialize, Deserialize)]
120//! struct Post {
121//!     id: i64,
122//!     title: String,
123//! }
124//!
125//! // GET /posts/1: the row as JSON, or a JSON 404 when there is none. `ApiResult`
126//! // answers errors as JSON; HTML pages return `ocre::Result` (feature `html`).
127//! async fn show(State(ctx): State<Ctx>, Path(id): Path<i64>) -> ApiResult<Json<Post>> {
128//!     let post = ctx.db()?.first::<Post>("SELECT id, title FROM posts WHERE id = ?1", params![id]).await?;
129//!     Ok(Json(post.or_404()?))
130//! }
131//! # fn main() {}
132//! ```
133//!
134//! `cloudflare.config.ts` binds the D1 database as `DB`; `ocre new` writes it, and
135//! `ocre dev` / `ocre deploy` run it.
136//!
137//! # Cargo features
138//!
139//! | Feature | Default | Enables |
140//! |---|---|---|
141//! | `html` | yes | askama templates (`render`), HTML error pages, the `Htmx` extractor. API-only apps (`ocre new --api`) turn it off |
142//! | `graphql` | no | The `graphql` module (async-graphql). About 1.1 MB more WebAssembly and 20-60 ms of CPU when a Worker instance starts |
143//! | `realtime` | no | The `realtime` module and the exported `OcreChannel` Durable Object class (WebSocket Hibernation) |
144#![cfg_attr(docsrs, feature(doc_cfg))]
145#![warn(missing_docs)]
146#![warn(rustdoc::broken_intra_doc_links)]
147
148pub mod alerts;
149mod api;
150pub mod bulk;
151pub mod cache;
152mod clock;
153pub mod config;
154mod cookies;
155pub mod encryption;
156mod error;
157pub mod errors;
158pub mod events;
159mod fields;
160#[cfg(feature = "html")]
161#[cfg_attr(docsrs, doc(cfg(feature = "html")))]
162pub mod filters;
163mod form;
164#[cfg(feature = "graphql")]
165#[cfg_attr(docsrs, doc(cfg(feature = "graphql")))]
166pub mod graphql;
167pub mod helpers;
168#[cfg(feature = "html")]
169mod htmx;
170pub mod http;
171pub mod i18n;
172mod instrument;
173pub mod jobs;
174pub mod jwt;
175pub mod log;
176pub mod mail;
177mod names;
178pub mod oauth;
179pub mod password;
180mod protect;
181#[cfg(feature = "push")]
182#[cfg_attr(docsrs, doc(cfg(feature = "push")))]
183pub mod push;
184mod query;
185#[cfg(feature = "realtime")]
186#[cfg_attr(docsrs, doc(cfg(feature = "realtime")))]
187pub mod realtime;
188pub mod replicas;
189mod request;
190mod runtime;
191pub mod security;
192pub mod seo;
193mod session;
194mod sql;
195pub mod sse;
196pub mod storage;
197#[cfg(test)]
198#[path = "../tests/support.rs"]
199mod support;
200#[cfg(all(feature = "testing", not(target_arch = "wasm32")))]
201#[cfg_attr(docsrs, doc(cfg(feature = "testing")))]
202pub mod testing;
203pub mod token;
204mod validate;
205#[cfg(feature = "html")]
206mod view;
207pub mod webhooks;
208
209pub use api::{ApiError, ApiResult, Created, Json, Page, PageLinks};
210pub use clock::now;
211pub use cookies::Cookies;
212pub use error::{Error, OptionExt, Result};
213pub use fields::{optional, patch, patch_json};
214pub use form::NestedForm;
215#[cfg(feature = "html")]
216#[cfg_attr(docsrs, doc(cfg(feature = "html")))]
217pub use htmx::{Htmx, HxRedirect};
218pub use protect::{ALLOWED_HOSTS, ALLOWED_ORIGINS};
219pub use query::{Batches, Direction, Paginated, Query, escape_like};
220pub use request::{Format, Markdown, RemoteIp, RequestId, encode_path, percent_encode, redirect_back, remote_ip};
221pub use runtime::{Ctx, Db, serve, sleep};
222/// JSON values (`serde_json::Value`, the `json!` macro) for `json` fields,
223/// without adding `serde_json` to the app.
224pub use serde_json;
225pub use session::{Flash, SECRET_KEY_BASE, SECRET_KEY_BASE_PREVIOUS, SESSION_COOKIE, Session};
226pub use sql::{IntoParam, MAX_SAFE_INTEGER, Param, Statement, bool_from_sql, json_from_sql, optional_json_from_sql};
227pub use validate::{FieldError, Validator};
228#[cfg(feature = "html")]
229#[cfg_attr(docsrs, doc(cfg(feature = "html")))]
230pub use view::{ErrorPage, error_page, render};
231
232/// Builds the parameter list of a [`Db`] query: `params![title, id]`.
233///
234/// Each value goes through [`IntoParam`], so strings, integers, floats,
235/// booleans, `Option`s of those (`None` binds `NULL`) and JSON values can be
236/// mixed. Values bind to the `?1`, `?2`, ... placeholders in order. The result
237/// is a `Vec<Param>`, the type every [`Db`] method and [`Statement::new`]
238/// take; `params![]` binds nothing.
239///
240/// # Examples
241///
242/// ```
243/// use ocre::{Param, params};
244///
245/// let title = "Hello";
246/// let published: Option<bool> = None;
247/// let params: Vec<Param> = params![title, 42, published];
248/// assert_eq!(params.len(), 3);
249/// let none: Vec<Param> = params![];
250/// assert!(none.is_empty());
251/// ```
252#[macro_export]
253macro_rules! params {
254    ($($value:expr),* $(,)?) => {
255        ::std::vec![$($crate::IntoParam::into_param($value)),*]
256    };
257}