Diffinery

homeflare/celldpublic

feat(bindings): ratelimits binding for Rate Limiting

Jason Schwarzenberger authored 1 parent 5234aa9commit 588fd42fa972b76bbdbacf3ae074cec45aba61b8Browse files
13 files changed+228−1
Files (13)
modifiedHOMEFLARE.md+1−0View file
@@ -25,6 +25,7 @@
2525 | `node:process` as the global `process` | The module was the throwing stub while `globalThis.process` existed, so Fedify's User-Agent (`Node.js/${process.versions.node}`, taken when the global has a Node version) threw on every outgoing request. Found by listing palm's bundle imports. |
2626 | `media` binding (Media Transformations) | palm makes video thumbnails with `env.MEDIA_TRANSFORMS.input(stream).transform(...).output({ mode: "frame" })`. The Wrangler `media` key becomes a binding (config → manifest → `WorkerConfig::with_media` → `__makeMediaBinding`) that reads the input and posts it, with both option objects in the `x-media-transform` header, to `CELLD_MEDIA_URL/transform`: Homeflare's `homeflare-media` (ffmpeg). Its answers and `{code, message}` errors (as `MediaError`) are the binding's. Without `CELLD_MEDIA_URL` a result rejects with code 9500. |
2727 | `version_metadata` binding | Upstream celld had none, so Homeflare passed the version ID as a plain string. The binding is now Cloudflare's frozen `{ id, tag, timestamp }`. The config may set all three (Homeflare passes its own version ID, tag and time, so they match its Dashboard and `wrangler versions`); otherwise the id is the deployment's version, the tag is empty and the timestamp is the deploy time. |
28+| `ratelimits` binding | Diffinery limits sign-ins and API calls with `env.RL_*.limit({ key })`. Each entry becomes a binding counted on the node by a `__ratelimit` op: fixed windows of the period (10 or 60 s), keyed by namespace id and key and shared by the node's isolates, as each Cloudflare location counts on its own. |
2829 | `homeflare:` line in `celld --version` | Lists what this build adds (`HOMEFLARE_FEATURES` in `lib.rs`), so Homeflare sends a config key only to a celld that accepts it. Add a feature there with each patch. |
2930
3031 ## Building
modifiedcrates/celld/deploy.rs+65−1View file
@@ -59,6 +59,7 @@
5959 "worker_loaders",
6060 "media",
6161 "version_metadata",
62+ "ratelimits",
6263 "containers",
6364 "no_bundle",
6465 "define",
@@ -561,6 +562,14 @@
561562 .unwrap_or("this deployment's version")
562563 .to_string(),
563564 )),
565+ Some("ratelimit") => Some((
566+ format!("env.{name} (Rate limit)"),
567+ format!(
568+ "{} requests / {} s per key, per node",
569+ binding.get("limit").and_then(Value::as_u64).unwrap_or(0),
570+ binding.get("period").and_then(Value::as_u64).unwrap_or(0)
571+ ),
572+ )),
564573 Some("plain_text") => Some((
565574 format!("env.{name} (Text)"),
566575 "Environment Variable".to_string(),
@@ -1967,6 +1976,60 @@
19671976 }
19681977 Some(_) => bail!("config `version_metadata` must be an object with a `binding` name"),
19691978 };
1979+ // `ratelimits` (Homeflare patch): Cloudflare's Rate Limiting binding,
1980+ // `env.NAME.limit({ key })`. Each node counts in fixed windows, as each
1981+ // Cloudflare location counts on its own; a namespace_id shares counts
1982+ // between bindings with the same id.
1983+ let mut ratelimits = Vec::new();
1984+ match object.get("ratelimits") {
1985+ None => {}
1986+ Some(Value::Array(list)) => {
1987+ for entry in list {
1988+ let Value::Object(entry) = entry else {
1989+ bail!("each `ratelimits` entry must be an object");
1990+ };
1991+ let name = match entry.get("name") {
1992+ Some(Value::String(name)) if valid_binding(name) => name.clone(),
1993+ _ => bail!("a `ratelimits` entry needs a valid `name`"),
1994+ };
1995+ let namespace = match entry.get("namespace_id") {
1996+ Some(Value::String(id)) if !id.is_empty() => id.clone(),
1997+ Some(Value::Number(id)) => id.to_string(),
1998+ _ => bail!("ratelimit {name} needs a `namespace_id`"),
1999+ };
2000+ let Some(Value::Object(simple)) = entry.get("simple") else {
2001+ bail!("ratelimit {name} needs `simple: {{ limit, period }}`");
2002+ };
2003+ let limit = simple
2004+ .get("limit")
2005+ .and_then(Value::as_u64)
2006+ .filter(|limit| *limit > 0)
2007+ .ok_or_else(|| anyhow!("ratelimit {name}: `simple.limit` must be a positive integer"))?;
2008+ let period = simple.get("period").and_then(Value::as_u64);
2009+ if !matches!(period, Some(10 | 60)) {
2010+ bail!("ratelimit {name}: `simple.period` must be 10 or 60 (seconds), as on Cloudflare");
2011+ }
2012+ if let Some(key) = simple.keys().find(|key| !matches!(key.as_str(), "limit" | "period")) {
2013+ bail!("ratelimit {name} sets `simple.{key}`, which celld does not support");
2014+ }
2015+ if let Some(key) = entry
2016+ .keys()
2017+ .find(|key| !matches!(key.as_str(), "name" | "namespace_id" | "simple"))
2018+ {
2019+ bail!("ratelimit {name} sets `{key}`, which celld does not support");
2020+ }
2021+ bindings.push(json!({
2022+ "type": "ratelimit",
2023+ "name": name,
2024+ "namespace_id": namespace,
2025+ "limit": limit,
2026+ "period": period,
2027+ }));
2028+ ratelimits.push(name);
2029+ }
2030+ }
2031+ Some(_) => bail!("config `ratelimits` must be an array"),
2032+ }
19702033 let mut vars = BTreeMap::new();
19712034 match object.get("vars") {
19722035 None => {}
@@ -2034,7 +2097,8 @@
20342097 || !r2_binding_names.is_empty()
20352098 || !worker_loaders.is_empty()
20362099 || media_binding.is_some()
2037- || version_metadata.is_some())
2100+ || version_metadata.is_some()
2101+ || !ratelimits.is_empty())
20382102 {
20392103 bail!("an asset-only project cannot declare Worker bindings");
20402104 }
modifiedcrates/celld/fleet.rs+9−0View file
@@ -920,6 +920,11 @@
920920 }),
921921 ))
922922 });
923+ // Bindings the Homeflare patches install from their manifest entry as is
924+ // (`ratelimit`).
925+ let homeflare_bindings = bindings(&manifest, "ratelimit")
926+ .cloned()
927+ .collect();
923928 let services = service_bindings(&manifest);
924929 let vars = worker_vars(&manifest);
925930 let compat = crate::worker_compat(&manifest.raw_metadata);
@@ -978,6 +983,7 @@
978983 loader_bindings,
979984 media_bindings,
980985 version_metadata,
986+ homeflare_bindings,
981987 assets,
982988 services,
983989 crons,
@@ -1002,6 +1008,9 @@
10021008 /// The `version_metadata` binding's `env` name and its {id, tag,
10031009 /// timestamp} (Homeflare patch).
10041010 pub version_metadata: Option<(String, serde_json::Value)>,
1011+ /// Manifest entries of the `ratelimit` and `send_email` bindings
1012+ /// (Homeflare patches).
1013+ pub homeflare_bindings: Vec<serde_json::Value>,
10051014 pub assets: Option<crate::assets::AssetResolver>,
10061015 pub services: Vec<(String, String, Option<String>)>,
10071016 /// `triggers.crons` from the manifest, driving the reserved cron cell.
modifiedcrates/celld/generation.rs+2−0View file
@@ -556,6 +556,7 @@
556556 loader_bindings,
557557 media_bindings,
558558 version_metadata,
559+ homeflare_bindings,
559560 assets: resolver,
560561 services,
561562 crons,
@@ -576,6 +577,7 @@
576577 .with_loaders(loader_bindings)
577578 .with_media(media_bindings)
578579 .with_version_metadata(version_metadata)
580+ .with_homeflare_bindings(homeflare_bindings)
579581 .with_queue_consumers(queue_catalog.clone())
580582 .with_crons(if is_primary { crons } else { Vec::new() })
581583 .with_containers(containers)
modifiedcrates/celld/js.rs+13−0View file
@@ -1922,6 +1922,9 @@
19221922 media_bindings: Vec<String>,
19231923 /// The `version_metadata` binding and its value (Homeflare patch).
19241924 version_metadata: Option<(String, serde_json::Value)>,
1925+ /// Manifest entries of `ratelimit` and `send_email` bindings (Homeflare
1926+ /// patches).
1927+ homeflare_bindings: Vec<serde_json::Value>,
19251928 /// Ambient outbound authority. Loaded workers may be denied.
19261929 egress: EgressPolicy,
19271930 /// Structured-clone values and host-minted service routes that a loaded
@@ -2070,6 +2073,7 @@
20702073 loader_bindings: Vec::new(),
20712074 media_bindings: Vec::new(),
20722075 version_metadata: None,
2076+ homeflare_bindings: Vec::new(),
20732077 egress: EgressPolicy::Allow,
20742078 loader_env: None,
20752079 resource_limits: None,
@@ -2161,6 +2165,13 @@
21612165 self
21622166 }
21632167
2168+ /// Give this Worker the `ratelimit` and `send_email` bindings in these
2169+ /// manifest entries (Homeflare patches).
2170+ pub fn with_homeflare_bindings(mut self, bindings: Vec<serde_json::Value>) -> Self {
2171+ self.homeflare_bindings = bindings;
2172+ self
2173+ }
2174+
21642175 /// Set this Worker's ambient outbound authority (loaded workers only).
21652176 fn with_egress(mut self, egress: EgressPolicy) -> Self {
21662177 self.egress = egress;
@@ -6763,6 +6774,7 @@
67636774 "__tcp_close" => tcp::op_tcp_close,
67646775 "__tcp_starttls" => tcp::op_tcp_starttls,
67656776 "__dns_lookup" => dns::op_dns_lookup,
6777+ "__ratelimit" => ratelimit::op_ratelimit,
67666778 "__domain_to_ascii" => node_url::op_domain_to_ascii,
67676779 "__domain_to_unicode" => node_url::op_domain_to_unicode,
67686780 "__container_running" => container::op_container_running,
@@ -9979,6 +9991,7 @@
99799991 mod container;
99809992 mod crypto;
99819993 mod dns;
9994+mod ratelimit;
99829995 mod html_rewriter;
99839996 mod node_url;
99849997 mod tcp;
modifiedcrates/celld/js/bootstrap.rs+15−0View file
@@ -688,6 +688,21 @@
688688 if let Some((name, value)) = &config.version_metadata {
689689 lines.push_str(&format!("e[{:?}] = Object.freeze({});\n", name, value));
690690 }
691+ // Rate limiting (Homeflare patch): counted on this node by the
692+ // __ratelimit op.
693+ for binding in &config.homeflare_bindings {
694+ let field = |key: &str| binding.get(key).cloned().unwrap_or(serde_json::Value::Null);
695+ if binding.get("type").and_then(serde_json::Value::as_str) == Some("ratelimit") {
696+ lines.push_str(&format!(
697+ "e[{}] = __celld.__makeRateLimit({}, {}, {}, {});\n",
698+ field("name"),
699+ field("name"),
700+ field("namespace_id"),
701+ field("limit"),
702+ field("period")
703+ ));
704+ }
705+ }
691706 // Media Transformations (Homeflare patch): the binding posts to the
692707 // node's media service, or says it has none.
693708 if !config.media_bindings.is_empty() {
modifiedcrates/celld/js/harness.js+12−0View file
@@ -1229,6 +1229,18 @@
12291229 };
12301230 },
12311231 });
1232+// A `ratelimit` binding (Homeflare patch): Cloudflare's Rate Limiting API,
1233+// `await env.LIMITER.limit({ key })` -> `{ success }`. The node counts each
1234+// namespace id and key in fixed windows of the binding's period.
1235+__celld.__makeRateLimit = (binding, namespace, limit, period) => ({
1236+ async limit(options) {
1237+ const key = options?.key;
1238+ if (typeof key !== "string" || key === "") {
1239+ throw new TypeError(`${binding}.limit() needs { key: string }`);
1240+ }
1241+ return { success: __ratelimit(`${namespace}\u0000${key}`, limit, period) };
1242+ },
1243+});
12321244 __celld.__makeR2Bucket = (binding, bucketName) => ({
12331245 async head(key) {
12341246 const name = __r2Key(binding, "head", key);
addedcrates/celld/js/ratelimit.rs+76−0View file
@@ -1,0 +1,76 @@
1+//! Host op for the `ratelimit` binding (Homeflare patch).
2+//!
3+//! Cloudflare's Rate Limiting binding counts in each location on its own and
4+//! is "permissive, eventually consistent"; this counts on each node, in
5+//! fixed windows of the binding's period, which a homelab's single node
6+//! makes exact. Counters are shared by every isolate on the node, keyed by
7+//! the binding's namespace id and the caller's key, so two bindings with
8+//! the same namespace id share counts as they do on Cloudflare.
9+
10+use std::collections::HashMap;
11+use std::sync::{Mutex, OnceLock};
12+
13+
14+/// Past this many keys, windows that have ended are dropped.
15+const PRUNE_AT: usize = 100_000;
16+
17+struct Window {
18+ index: u64,
19+ count: u64,
20+}
21+
22+fn counters() -> &'static Mutex<HashMap<String, Window>> {
23+ static COUNTERS: OnceLock<Mutex<HashMap<String, Window>>> = OnceLock::new();
24+ COUNTERS.get_or_init(|| Mutex::new(HashMap::new()))
25+}
26+
27+/// Count one request for `key` and say whether it's within `limit` requests
28+/// per `period` seconds.
29+pub(crate) fn allow(key: &str, limit: u64, period: u64, now_ms: u64) -> bool {
30+ let index = now_ms / (period.max(1) * 1000);
31+ let mut map = counters().lock().unwrap_or_else(|poisoned| poisoned.into_inner());
32+ if map.len() >= PRUNE_AT {
33+ map.retain(|_, window| window.index >= index);
34+ }
35+ let window = map.entry(key.to_string()).or_insert(Window { index, count: 0 });
36+ if window.index != index {
37+ window.index = index;
38+ window.count = 0;
39+ }
40+ if window.count >= limit {
41+ return false;
42+ }
43+ window.count += 1;
44+ true
45+}
46+
47+/// `__ratelimit(key, limit, period)` → whether the request may go ahead.
48+pub(super) fn op_ratelimit(
49+ scope: &mut v8::PinScope,
50+ args: v8::FunctionCallbackArguments,
51+ mut rv: v8::ReturnValue<v8::Value>,
52+) {
53+ let key = args.get(0).to_rust_string_lossy(scope);
54+ let limit = args.get(1).number_value(scope).unwrap_or(0.0).max(0.0) as u64;
55+ let period = args.get(2).number_value(scope).unwrap_or(60.0).max(1.0) as u64;
56+ let now_ms = std::time::SystemTime::now()
57+ .duration_since(std::time::UNIX_EPOCH)
58+ .map(|elapsed| elapsed.as_millis() as u64)
59+ .unwrap_or_default();
60+ rv.set(v8::Boolean::new(scope, allow(&key, limit, period, now_ms)).into());
61+}
62+
63+#[cfg(test)]
64+mod tests {
65+ use super::allow;
66+
67+ #[test]
68+ fn counts_per_key_and_window() {
69+ let t = 1_700_000_000_000;
70+ assert!(allow("t1\0a", 2, 10, t));
71+ assert!(allow("t1\0a", 2, 10, t + 1));
72+ assert!(!allow("t1\0a", 2, 10, t + 2));
73+ assert!(allow("t1\0b", 2, 10, t + 2), "another key has its own count");
74+ assert!(allow("t1\0a", 2, 10, t + 10_000), "a new window starts over");
75+ }
76+}
modifiedcrates/celld/lib.rs+1−0View file
@@ -323,4 +323,5 @@
323323 "response-clone-stream",
324324 "media",
325325 "version-metadata",
326+ "ratelimits",
326327 ];
modifiedcrates/celld/main.rs+1−0View file
@@ -4061,6 +4061,7 @@
40614061 .collect(),
40624062 media_bindings: Vec::new(),
40634063 version_metadata: None,
4064+ homeflare_bindings: Vec::new(),
40644065 assets: None,
40654066 services: Vec::new(),
40664067 crons,
modifieddocs/cloudflare-compat.md+1−0View file
@@ -28,6 +28,7 @@
2828 | [Workflows](services/workflows.md) | **Yes** |
2929 | [R2](services/r2.md) | **Yes** |
3030 | Version metadata (`version_metadata` binding) | **Yes** — `{ id, tag, timestamp }`; a platform can set all three in the config (Homeflare patch) |
31+| Rate Limiting (`ratelimits`) | **Yes** — `limit({ key })`, counted per node in fixed windows of the period (Homeflare patch) |
3132 | Media Transformations (`media` binding) | **Partial** — needs a media service at `CELLD_MEDIA_URL`, such as Homeflare's `homeflare-media` (Homeflare patch) |
3233 | Workers AI | **No** |
3334 | Vectorize | **No** |
addedhomeflare/smoke/ratelimit/index.js+21−0View file
@@ -1,0 +1,21 @@
1+// Smoke test for the ratelimit binding: limit({ key }) → { success }, counted
2+// per namespace id and key.
3+const expectEqual = (name, got, want) => ({ name, ok: JSON.stringify(got) === JSON.stringify(want), got });
4+
5+export default {
6+ async fetch(request, env) {
7+ const key = crypto.randomUUID();
8+ const checks = [
9+ expectEqual("first", await env.TWO.limit({ key }), { success: true }),
10+ expectEqual("second, through the shared namespace", await env.TWO_AGAIN.limit({ key }), { success: true }),
11+ expectEqual("third is limited", await env.TWO.limit({ key }), { success: false }),
12+ expectEqual("another key", await env.TWO.limit({ key: key + "-b" }), { success: true }),
13+ expectEqual("another namespace", await env.OTHER.limit({ key }), { success: true }),
14+ ];
15+ let threw = null;
16+ try { await env.TWO.limit({}); } catch (e) { threw = e.constructor.name; }
17+ checks.push(expectEqual("no key throws", threw, "TypeError"));
18+ const failed = checks.filter((c) => !c.ok);
19+ return Response.json({ ok: failed.length === 0, failed, checks }, { status: failed.length ? 500 : 200 });
20+ },
21+};
addedhomeflare/smoke/ratelimit/wrangler.jsonc+11−0View file
@@ -1,0 +1,11 @@
1+{
2+ "name": "ratelimit",
3+ "main": "index.js",
4+ "compatibility_date": "2026-01-01",
5+ "ratelimits": [
6+ { "name": "TWO", "namespace_id": "1001", "simple": { "limit": 2, "period": 60 } },
7+ // Same namespace id: shares TWO's counts, as on Cloudflare.
8+ { "name": "TWO_AGAIN", "namespace_id": "1001", "simple": { "limit": 2, "period": 60 } },
9+ { "name": "OTHER", "namespace_id": 1002, "simple": { "limit": 1, "period": 10 } }
10+ ]
11+}