Diffinery

homeflare/celldpublic

feat(bindings): media binding for Media Transformations

Jason Schwarzenberger authored 1 parent 71285b4commit 2477acd6e62de8d021968a5bc802819b92ba3e54Browse files
11 files changed+205−1
Files (11)
modifiedHOMEFLARE.md+1−0View file
@@ -23,6 +23,7 @@
2323 | `Response.clone()` on a streaming body | celld threw `Cannot clone a streaming response before consumption`; workerd tees the body, as celld's `Request.clone()` already did. palm's media proxy returns a fetched image and caches `response.clone()`. |
2424 | `node:url` (all but the legacy `parse` / `resolve`) | celld had no `node:url`; Fedify's WebFinger handler calls `domainToASCII` and `domainToUnicode`. Both run Node's own steps (the input set as a `ws://x` hostname) through new host ops on the `url` crate. |
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. |
26+| `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. |
2627
2728 ## Building
2829
modifiedcrates/celld/deploy.rs+32−1View file
@@ -57,6 +57,7 @@
5757 "workflows",
5858 "r2_buckets",
5959 "worker_loaders",
60+ "media",
6061 "containers",
6162 "no_bundle",
6263 "define",
@@ -547,6 +548,10 @@
547548 format!("env.{name} (Worker Loader)"),
548549 "Dynamic Workers".to_string(),
549550 )),
551+ Some("media") => Some((
552+ format!("env.{name} (Media)"),
553+ "Media Transformations".to_string(),
554+ )),
550555 Some("plain_text") => Some((
551556 format!("env.{name} (Text)"),
552557 "Environment Variable".to_string(),
@@ -1875,6 +1880,31 @@
18751880 "name": binding,
18761881 }));
18771882 }
1883+ // `media` (Homeflare patch): a Media Transformations binding, served by
1884+ // the media service at CELLD_MEDIA_URL. Wrangler takes one, as an object
1885+ // with a `binding` name.
1886+ let media_binding = match object.get("media") {
1887+ None => None,
1888+ Some(Value::Object(media)) => {
1889+ let binding = match media.get("binding") {
1890+ Some(Value::String(binding)) => binding.as_str(),
1891+ Some(_) => bail!("media `binding` must be a string"),
1892+ None => bail!("media has no `binding` name"),
1893+ };
1894+ if !valid_binding(binding) {
1895+ bail!("invalid media binding name: {binding:?}");
1896+ }
1897+ if let Some(key) = media.keys().find(|key| key.as_str() != "binding") {
1898+ bail!("media sets `{key}`, which celld does not support");
1899+ }
1900+ bindings.push(json!({
1901+ "type": "media",
1902+ "name": binding,
1903+ }));
1904+ Some(binding)
1905+ }
1906+ Some(_) => bail!("config `media` must be an object with a `binding` name"),
1907+ };
18781908 let mut vars = BTreeMap::new();
18791909 match object.get("vars") {
18801910 None => {}
@@ -1940,7 +1970,8 @@
19401970 || service_count > 0
19411971 || declared_vars
19421972 || !r2_binding_names.is_empty()
1943- || !worker_loaders.is_empty())
1973+ || !worker_loaders.is_empty()
1974+ || media_binding.is_some())
19441975 {
19451976 bail!("an asset-only project cannot declare Worker bindings");
19461977 }
modifiedcrates/celld/fleet.rs+8−0View file
@@ -896,6 +896,10 @@
896896 let loader_bindings = bindings(&manifest, "worker_loader")
897897 .filter_map(|binding| binding.get("name")?.as_str().map(str::to_string))
898898 .collect();
899+ // `media` (Homeflare patch): its `env` name, served by CELLD_MEDIA_URL.
900+ let media_bindings = bindings(&manifest, "media")
901+ .filter_map(|binding| binding.get("name")?.as_str().map(str::to_string))
902+ .collect();
899903 let services = service_bindings(&manifest);
900904 let vars = worker_vars(&manifest);
901905 let compat = crate::worker_compat(&manifest.raw_metadata);
@@ -952,6 +956,7 @@
952956 prefix,
953957 asset_binding,
954958 loader_bindings,
959+ media_bindings,
955960 assets,
956961 services,
957962 crons,
@@ -970,6 +975,9 @@
970975 /// `worker_loaders` config. A script reaches no loader that it does not
971976 /// declare, and each loader keeps a cache of its own loaded Workers.
972977 pub loader_bindings: Vec<String>,
978+ /// `env` names of this script's Media Transformations bindings (Homeflare
979+ /// patch).
980+ pub media_bindings: Vec<String>,
973981 pub assets: Option<crate::assets::AssetResolver>,
974982 pub services: Vec<(String, String, Option<String>)>,
975983 /// `triggers.crons` from the manifest, driving the reserved cron cell.
modifiedcrates/celld/generation.rs+2−0View file
@@ -554,6 +554,7 @@
554554 script_name: script,
555555 asset_binding,
556556 loader_bindings,
557+ media_bindings,
557558 assets: resolver,
558559 services,
559560 crons,
@@ -572,6 +573,7 @@
572573 .with_services(services)
573574 .with_asset_binding(asset_binding)
574575 .with_loaders(loader_bindings)
576+ .with_media(media_bindings)
575577 .with_queue_consumers(queue_catalog.clone())
576578 .with_crons(if is_primary { crons } else { Vec::new() })
577579 .with_containers(containers)
modifiedcrates/celld/js.rs+10−0View file
@@ -1918,6 +1918,8 @@
19181918 /// binding gets a cache of its own, so a name loaded through one loader
19191919 /// is a different Worker from the same name loaded through another.
19201920 loader_bindings: Vec<String>,
1921+ /// `env` names of Media Transformations bindings (Homeflare patch).
1922+ media_bindings: Vec<String>,
19211923 /// Ambient outbound authority. Loaded workers may be denied.
19221924 egress: EgressPolicy,
19231925 /// Structured-clone values and host-minted service routes that a loaded
@@ -2064,6 +2066,7 @@
20642066 services: Vec::new(),
20652067 asset_binding: None,
20662068 loader_bindings: Vec::new(),
2069+ media_bindings: Vec::new(),
20672070 egress: EgressPolicy::Allow,
20682071 loader_env: None,
20692072 resource_limits: None,
@@ -2141,6 +2144,13 @@
21412144 self
21422145 }
21432146
2147+ /// Grant this Worker a Media Transformations binding at each `env` name
2148+ /// (Homeflare patch).
2149+ pub fn with_media(mut self, bindings: Vec<String>) -> Self {
2150+ self.media_bindings = bindings;
2151+ self
2152+ }
2153+
21442154 /// Set this Worker's ambient outbound authority (loaded workers only).
21452155 fn with_egress(mut self, egress: EgressPolicy) -> Self {
21462156 self.egress = egress;
modifiedcrates/celld/js/bootstrap.rs+14−0View file
@@ -683,6 +683,20 @@
683683 for name in &config.loader_bindings {
684684 lines.push_str(&format!("e[{:?}] = __celld.__makeLoader();\n", name));
685685 }
686+ // Media Transformations (Homeflare patch): the binding posts to the
687+ // node's media service, or says it has none.
688+ if !config.media_bindings.is_empty() {
689+ let service = std::env::var("CELLD_MEDIA_URL")
690+ .ok()
691+ .filter(|url| !url.trim().is_empty());
692+ let service = serde_json::to_string(&service).unwrap_or_else(|_| "null".into());
693+ for name in &config.media_bindings {
694+ lines.push_str(&format!(
695+ "e[{:?}] = __celld.__makeMediaBinding({:?}, {});\n",
696+ name, name, service
697+ ));
698+ }
699+ }
686700 lines
687701 };
688702 run_internal_snippet(scope, &src).ok_or_else(|| anyhow!("env install failed"))?;
modifiedcrates/celld/js/harness.js+97−0View file
@@ -1132,6 +1132,103 @@
11321132 await __r2_mp_abort(await id.host);
11331133 },
11341134 });
1135+// A `media` binding (Homeflare patch): Cloudflare's Media Transformations
1136+// API, `env.MEDIA.input(stream).transform(t).output(o)`, with the work done
1137+// by the node's media service (CELLD_MEDIA_URL, an ffmpeg service such as
1138+// Homeflare's homeflare-media). The binding sends the input and both option
1139+// objects in one POST to `<service>/transform`; the service validates them,
1140+// so its answers and error codes are the one source of truth. A result makes
1141+// its request once, when first read, and media(), contentType() and
1142+// response() share it.
1143+class MediaError extends Error {
1144+ constructor(code, message) {
1145+ super(message);
1146+ this.name = "MediaError";
1147+ this.code = code;
1148+ }
1149+}
1150+const __mediaBody = (binding, media) => {
1151+ if (media instanceof ReadableStream) return media;
1152+ if (media instanceof ArrayBuffer || ArrayBuffer.isView(media) || media instanceof Blob) return media;
1153+ throw new TypeError(
1154+ `${binding}.input() takes a ReadableStream of the media's bytes`);
1155+};
1156+const __mediaResult = (binding, service, body, transform, output) => {
1157+ let answer = null;
1158+ const request = () => answer ??= (async () => {
1159+ if (!service) {
1160+ throw new MediaError(9500,
1161+ `${binding}: this celld node has no media service (set CELLD_MEDIA_URL)`);
1162+ }
1163+ // Read into bytes first: fetch() takes a stream only from its owner, and
1164+ // an R2 object's body (palm's case) belongs to the binding that made it.
1165+ // Inputs are at most Cloudflare's 100 MB.
1166+ const bytes = body instanceof ReadableStream
1167+ ? await new Response(body).arrayBuffer()
1168+ : body;
1169+ let response;
1170+ try {
1171+ response = await fetch(`${service.replace(/\/+$/, "")}/transform`, {
1172+ method: "POST",
1173+ headers: {
1174+ "content-type": "application/octet-stream",
1175+ "x-media-transform": JSON.stringify({ transform, output }),
1176+ },
1177+ body: bytes,
1178+ });
1179+ } catch (error) {
1180+ throw new MediaError(9502,
1181+ `${binding}: the media service at ${service} can't be reached (${error?.message ?? error})`);
1182+ }
1183+ if (!response.ok) {
1184+ let code = 9500;
1185+ let message = `media service answered ${response.status}`;
1186+ try {
1187+ const error = await response.json();
1188+ if (Number.isInteger(error.code)) code = error.code;
1189+ if (typeof error.message === "string") message = error.message;
1190+ } catch { /* not JSON: keep the status */ }
1191+ throw new MediaError(code, `${binding}: ${message}`);
1192+ }
1193+ return response;
1194+ })();
1195+ return {
1196+ async media() { return (await request()).body; },
1197+ async contentType() {
1198+ return (await request()).headers.get("content-type") ?? "application/octet-stream";
1199+ },
1200+ async response() {
1201+ const response = await request();
1202+ return new Response(response.body, {
1203+ headers: { "content-type": response.headers.get("content-type") ?? "application/octet-stream" },
1204+ });
1205+ },
1206+ };
1207+};
1208+__celld.__makeMediaBinding = (binding, service) => ({
1209+ input(media) {
1210+ const body = __mediaBody(binding, media);
1211+ let used = false;
1212+ const once = () => {
1213+ if (used) throw new TypeError(`${binding}: an input can be transformed once`);
1214+ used = true;
1215+ };
1216+ return {
1217+ transform(transform = {}) {
1218+ return {
1219+ output(output = {}) {
1220+ once();
1221+ return __mediaResult(binding, service, body, transform, output);
1222+ },
1223+ };
1224+ },
1225+ output(output = {}) {
1226+ once();
1227+ return __mediaResult(binding, service, body, {}, output);
1228+ },
1229+ };
1230+ },
1231+});
11351232 __celld.__makeR2Bucket = (binding, bucketName) => ({
11361233 async head(key) {
11371234 const name = __r2Key(binding, "head", key);
modifiedcrates/celld/main.rs+1−0View file
@@ -4053,6 +4053,7 @@
40534053 .filter(|name| !name.is_empty())
40544054 .map(str::to_string)
40554055 .collect(),
4056+ media_bindings: Vec::new(),
40564057 assets: None,
40574058 services: Vec::new(),
40584059 crons,
modifieddocs/cloudflare-compat.md+1−0View file
@@ -27,6 +27,7 @@
2727 | [D1](services/d1.md) | **Yes** |
2828 | [Workflows](services/workflows.md) | **Yes** |
2929 | [R2](services/r2.md) | **Yes** |
30+| Media Transformations (`media` binding) | **Partial** — needs a media service at `CELLD_MEDIA_URL`, such as Homeflare's `homeflare-media` (Homeflare patch) |
3031 | Workers AI | **No** |
3132 | Vectorize | **No** |
3233 | Hyperdrive | **No** |
addedhomeflare/smoke/media-binding/index.js+33−0View file
@@ -1,0 +1,33 @@
1+// Smoke test for the media binding without a media service (CELLD_MEDIA_URL
2+// unset, as under run.sh): the API's shape, its argument checks, and the
3+// error a result gives. The transforms themselves are tested with
4+// Homeflare's homeflare-media.
5+const expectEqual = (name, got, want) => ({ name, ok: JSON.stringify(got) === JSON.stringify(want), got });
6+const stream = () => new Response("not really media").body;
7+
8+export default {
9+ async fetch(request, env) {
10+ const checks = [
11+ expectEqual("binding has input()", typeof env.MEDIA?.input, "function"),
12+ expectEqual("chain has output()", typeof env.MEDIA.input(stream()).transform({ width: 100 }).output, "function"),
13+ ];
14+ const result = env.MEDIA.input(stream()).transform({ width: 100 }).output({ mode: "frame" });
15+ checks.push(expectEqual("result methods", [typeof result.response, typeof result.media, typeof result.contentType], ["function", "function", "function"]));
16+ try {
17+ await result.response();
18+ checks.push({ name: "no service rejects", ok: false, got: "resolved" });
19+ } catch (error) {
20+ checks.push(expectEqual("no service rejects with MediaError", [error.name, error.code, /CELLD_MEDIA_URL/.test(error.message)], ["MediaError", 9500, true]));
21+ }
22+ const input = env.MEDIA.input(stream());
23+ input.output({ mode: "frame" });
24+ let second = "";
25+ try { input.output({ mode: "frame" }); } catch (error) { second = error.constructor.name; }
26+ checks.push(expectEqual("an input is used once", second, "TypeError"));
27+ let bad = "";
28+ try { env.MEDIA.input("a string"); } catch (error) { bad = error.constructor.name; }
29+ checks.push(expectEqual("input takes a stream", bad, "TypeError"));
30+ const failed = checks.filter((c) => !c.ok);
31+ return Response.json({ ok: failed.length === 0, failed, checks }, { status: failed.length ? 500 : 200 });
32+ },
33+};
addedhomeflare/smoke/media-binding/wrangler.jsonc+6−0View file
@@ -1,0 +1,6 @@
1+{
2+ "name": "media-binding",
3+ "main": "index.js",
4+ "compatibility_date": "2026-01-01",
5+ "media": { "binding": "MEDIA" }
6+}