Skip to main content

ocre/runtime/
mod.rs

1//! Code that calls the Workers JavaScript runtime. It only runs inside
2//! workerd, so it is exercised by the end-to-end tests
3//! (`crates/ocre-cli/tests/system/e2e.rs`) rather than by native unit tests.
4
5pub(crate) mod alerts;
6pub(crate) mod cache;
7#[cfg(target_arch = "wasm32")]
8mod crypto;
9mod ctx;
10mod d1;
11pub(crate) mod errors;
12#[cfg(feature = "graphql")]
13mod graphql;
14pub(crate) mod http;
15pub(crate) mod jobs;
16pub(crate) mod jwt;
17pub(crate) mod mail;
18pub(crate) mod oauth;
19#[cfg(feature = "push")]
20pub(crate) mod push;
21mod query;
22#[cfg(feature = "realtime")]
23pub(crate) mod realtime;
24pub(crate) mod resumable;
25pub(crate) mod s3;
26pub(crate) mod secrets;
27pub(crate) mod security;
28pub(crate) mod seo;
29pub(crate) mod storage;
30pub(crate) mod webhooks;
31
32#[cfg(target_arch = "wasm32")]
33pub(crate) use crypto::{pbkdf2_sha256, unix_millis};
34pub use ctx::Ctx;
35pub use d1::Db;
36#[cfg(feature = "graphql")]
37pub use graphql::routes as graphql_routes;
38
39use axum::Router;
40use tower_service::Service;
41use worker::{Env, HttpRequest, web_sys};
42
43use crate::{protect, session};
44
45/// Runs one request through the application router: the Worker `fetch` entry point.
46///
47/// Builds a [`Ctx`] from `env`, gives it to `routes` as axum state, and wraps
48/// the router with the middleware every Ocre app runs (outermost first):
49///
50/// 1. Security headers on every response (`X-Content-Type-Options: nosniff`,
51///    `X-Frame-Options: SAMEORIGIN`, `Referrer-Policy`, HSTS on HTTPS...); a
52///    handler's own value wins.
53/// 2. Host authorization: when the [`ALLOWED_HOSTS`](crate::ALLOWED_HOSTS)
54///    Worker variable is set, other hosts get `403 Forbidden`.
55/// 3. CORS for the origins listed in the [`ALLOWED_ORIGINS`](crate::ALLOWED_ORIGINS)
56///    Worker variable (no CORS layer when it is empty).
57/// 4. Cross-origin request protection (CSRF) without tokens: unsafe requests a
58///    browser sends from another site (`Sec-Fetch-Site`, or `Origin` against
59///    `Host`) get `403 Forbidden`.
60/// 5. The encrypted cookie [`Session`](crate::Session), keyed from the
61///    [`SECRET_KEY_BASE`](crate::SECRET_KEY_BASE) secret (and, during a
62///    rotation, [`SECRET_KEY_BASE_PREVIOUS`](crate::SECRET_KEY_BASE_PREVIOUS)).
63///
64/// A missing or short `SECRET_KEY_BASE` does not fail every request: only
65/// handlers that touch the session get [`Error::Internal`](crate::Error::Internal),
66/// naming the fix (`ocre secret`, `.dev.vars`).
67///
68/// The request also carries the [`Ctx`] as an extension, so the app's own
69/// middleware (`axum::middleware::from_fn`) can reach the bindings with an
70/// `Extension(ctx): Extension<Ctx>` argument, as handlers do with `State`.
71///
72/// Files from [`storage::serve`](crate::storage::serve) go out as R2's own
73/// stream, so the Worker spends no CPU copying them and `Content-Length` is
74/// kept.
75///
76/// Around the router, `serve` picks the request id ([`RequestId`](crate::RequestId))
77/// and tags [`Ctx::log`] with it, the method and the path; answers with an
78/// `X-Request-Id` header; reports an [`Error::Internal`](crate::Error::Internal)
79/// response through [`Ctx::errors`] (logged as `[ocre] <message>`, then
80/// sent to the [`errors`](crate::errors) subscribers); and logs
81/// `GET /posts 200 in 40 ms (db: 3 queries, 12 ms)` at `debug`. Debug
82/// builds (`ocre dev`) also add a `Server-Timing` header (D1 time and
83/// total, in the browser's Network panel) and show the development error
84/// page: a 500 page with the internal message, the request's details
85/// (secrets filtered) and the D1 statements it ran, or `error.detail` in a
86/// JSON error; and they mount [`DEV_STORAGE_PATH`](crate::storage::DEV_STORAGE_PATH),
87/// the route presigned storage URLs point to in development. Release
88/// builds (`ocre deploy`) never show internal details.
89///
90/// # Errors
91///
92/// Returns a [`worker::Error`] only when the response cannot be converted to a
93/// JavaScript `Response`. Handler errors are responses (an HTML page or JSON),
94/// not `Err`.
95///
96/// # Free plan
97///
98/// One call per Worker request (100,000 a day); the middleware itself reads no
99/// D1 rows and no KV keys: sessions live in the cookie.
100///
101/// # Examples
102///
103/// `src/lib.rs` of a generated app:
104///
105/// ```no_run
106/// use axum::{Router, routing::get};
107/// use ocre::Ctx;
108///
109/// fn routes() -> Router<Ctx> {
110///     Router::new().route("/up", get(|| async { "OK" }))
111/// }
112///
113/// #[worker::event(fetch)]
114/// async fn fetch(
115///     req: worker::HttpRequest,
116///     env: worker::Env,
117///     _ctx: worker::Context,
118/// ) -> worker::Result<worker::web_sys::Response> {
119///     ocre::serve(routes(), req, env).await
120/// }
121/// # fn main() {}
122/// ```
123pub async fn serve(routes: Router<Ctx>, req: HttpRequest, env: Env) -> worker::Result<web_sys::Response> {
124    let var = |name: &str| env.var(name).ok().map(|var| var.to_string());
125    let secret = |name: &str| env.secret(name).ok().map(|secret| secret.to_string());
126    let config = protect::Config {
127        keys: session::keys_from_secrets(secret(session::SECRET_KEY_BASE), secret(session::SECRET_KEY_BASE_PREVIOUS)),
128        allowed_origins: protect::parse_origins(var(protect::ALLOWED_ORIGINS)),
129        allowed_hosts: protect::parse_hosts(var(protect::ALLOWED_HOSTS)),
130    };
131    let replicas = crate::replicas::enabled(var(crate::replicas::REPLICAS_VAR).as_deref());
132    let started = crate::clock::now_millis();
133    let dev = cfg!(debug_assertions);
134    let request_id = crate::request::request_id(req.headers());
135    let details = crate::errors::RequestDetails::new(&request_id, req.method().as_str(), req.uri(), req.headers(), dev);
136    let ctx = Ctx::new(env).with_log(details.logger());
137    if replicas {
138        ctx.memo().start_replicas(req.method(), req.headers());
139    }
140    let mut req = req;
141    req.extensions_mut().insert(ctx.clone());
142    req.extensions_mut().insert(crate::RequestId(request_id));
143    // Debug builds: presigned storage URLs point to this route on the local bucket.
144    let routes = if dev { routes.merge(s3::dev_routes()) } else { routes };
145    let mut app = protect::wrap(routes.with_state(ctx.clone()), config);
146    let response = app.call(req).await?;
147    let total_ms = crate::clock::now_millis() - started;
148    let mut response = crate::errors::finish(response, &details, ctx.errors(), ctx.timings(), total_ms, dev).await;
149    errors::flush(&ctx).await;
150    // After a write, the visitor's next requests resume from its bookmark.
151    for (binding, bookmark) in ctx.memo().bookmarks() {
152        if let Some(cookie) = crate::replicas::bookmark_cookie(&binding, &bookmark) {
153            response.headers_mut().append(axum::http::header::SET_COOKIE, cookie);
154        }
155    }
156    match response.extensions_mut().remove::<storage::R2Stream>() {
157        Some(stream) => storage::into_js_response(response, stream),
158        None => worker::response_to_wasm(response),
159    }
160}
161
162/// Waits `duration` without using CPU (JavaScript's `setTimeout`): pacing for [`sse`](crate::sse) streams and polling.
163///
164/// On Workers, time spent waiting is not CPU time: the free plan's 10 ms
165/// per request only counts the work between waits. An HTTP request may wait
166/// as long as its client stays connected; a queue or scheduled invocation
167/// is limited to 15 minutes of wall time. The returned future is `Send`, so
168/// it can be awaited in handlers and in [`sse::stream`](crate::sse::stream)
169/// steps. Only runs on Workers (natively it panics, like every binding).
170///
171/// # Examples
172///
173/// ```no_run
174/// use std::time::Duration;
175///
176/// async fn slow() -> &'static str {
177///     ocre::sleep(Duration::from_millis(500)).await;
178///     "done"
179/// }
180/// # let _ = slow;
181/// ```
182pub fn sleep(duration: std::time::Duration) -> impl Future<Output = ()> + Send {
183    worker::send::SendFuture::new(worker::Delay::from(duration))
184}