feat(bindings): media binding for Media Transformations
Jason Schwarzenberger authored 1 parent 71285b4commit 2477acd6e62de8d021968a5bc802819b92ba3e54Browse files
11 files changed+205−1
Files (11)
- HOMEFLARE.md+1−0
- crates/celld/deploy.rs+32−1
- crates/celld/fleet.rs+8−0
- crates/celld/generation.rs+2−0
- crates/celld/js.rs+10−0
- crates/celld/js/bootstrap.rs+14−0
- crates/celld/js/harness.js+97−0
- crates/celld/main.rs+1−0
- docs/cloudflare-compat.md+1−0
- homeflare/smoke/media-binding/index.js+33−0
- homeflare/smoke/media-binding/wrangler.jsonc+6−0
modifiedHOMEFLARE.md+1−0View file
| @@ -23,6 +23,7 @@ | ||
| 23 | 23 | | `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()`. | |
| 24 | 24 | | `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. | |
| 25 | 25 | | `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. | | |
| 26 | 27 | |
| 27 | 28 | ## Building |
| 28 | 29 |
modifiedcrates/celld/deploy.rs+32−1View file
| @@ -57,6 +57,7 @@ | ||
| 57 | 57 | "workflows", |
| 58 | 58 | "r2_buckets", |
| 59 | 59 | "worker_loaders", |
| 60 | + "media", | |
| 60 | 61 | "containers", |
| 61 | 62 | "no_bundle", |
| 62 | 63 | "define", |
| @@ -547,6 +548,10 @@ | ||
| 547 | 548 | format!("env.{name} (Worker Loader)"), |
| 548 | 549 | "Dynamic Workers".to_string(), |
| 549 | 550 | )), |
| 551 | + Some("media") => Some(( | |
| 552 | + format!("env.{name} (Media)"), | |
| 553 | + "Media Transformations".to_string(), | |
| 554 | + )), | |
| 550 | 555 | Some("plain_text") => Some(( |
| 551 | 556 | format!("env.{name} (Text)"), |
| 552 | 557 | "Environment Variable".to_string(), |
| @@ -1875,6 +1880,31 @@ | ||
| 1875 | 1880 | "name": binding, |
| 1876 | 1881 | })); |
| 1877 | 1882 | } |
| 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 | + }; | |
| 1878 | 1908 | let mut vars = BTreeMap::new(); |
| 1879 | 1909 | match object.get("vars") { |
| 1880 | 1910 | None => {} |
| @@ -1940,7 +1970,8 @@ | ||
| 1940 | 1970 | || service_count > 0 |
| 1941 | 1971 | || declared_vars |
| 1942 | 1972 | || !r2_binding_names.is_empty() |
| 1943 | - || !worker_loaders.is_empty()) | |
| 1973 | + || !worker_loaders.is_empty() | |
| 1974 | + || media_binding.is_some()) | |
| 1944 | 1975 | { |
| 1945 | 1976 | bail!("an asset-only project cannot declare Worker bindings"); |
| 1946 | 1977 | } |
modifiedcrates/celld/fleet.rs+8−0View file
| @@ -896,6 +896,10 @@ | ||
| 896 | 896 | let loader_bindings = bindings(&manifest, "worker_loader") |
| 897 | 897 | .filter_map(|binding| binding.get("name")?.as_str().map(str::to_string)) |
| 898 | 898 | .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(); | |
| 899 | 903 | let services = service_bindings(&manifest); |
| 900 | 904 | let vars = worker_vars(&manifest); |
| 901 | 905 | let compat = crate::worker_compat(&manifest.raw_metadata); |
| @@ -952,6 +956,7 @@ | ||
| 952 | 956 | prefix, |
| 953 | 957 | asset_binding, |
| 954 | 958 | loader_bindings, |
| 959 | + media_bindings, | |
| 955 | 960 | assets, |
| 956 | 961 | services, |
| 957 | 962 | crons, |
| @@ -970,6 +975,9 @@ | ||
| 970 | 975 | /// `worker_loaders` config. A script reaches no loader that it does not |
| 971 | 976 | /// declare, and each loader keeps a cache of its own loaded Workers. |
| 972 | 977 | pub loader_bindings: Vec<String>, |
| 978 | + /// `env` names of this script's Media Transformations bindings (Homeflare | |
| 979 | + /// patch). | |
| 980 | + pub media_bindings: Vec<String>, | |
| 973 | 981 | pub assets: Option<crate::assets::AssetResolver>, |
| 974 | 982 | pub services: Vec<(String, String, Option<String>)>, |
| 975 | 983 | /// `triggers.crons` from the manifest, driving the reserved cron cell. |
modifiedcrates/celld/generation.rs+2−0View file
| @@ -554,6 +554,7 @@ | ||
| 554 | 554 | script_name: script, |
| 555 | 555 | asset_binding, |
| 556 | 556 | loader_bindings, |
| 557 | + media_bindings, | |
| 557 | 558 | assets: resolver, |
| 558 | 559 | services, |
| 559 | 560 | crons, |
| @@ -572,6 +573,7 @@ | ||
| 572 | 573 | .with_services(services) |
| 573 | 574 | .with_asset_binding(asset_binding) |
| 574 | 575 | .with_loaders(loader_bindings) |
| 576 | + .with_media(media_bindings) | |
| 575 | 577 | .with_queue_consumers(queue_catalog.clone()) |
| 576 | 578 | .with_crons(if is_primary { crons } else { Vec::new() }) |
| 577 | 579 | .with_containers(containers) |
modifiedcrates/celld/js.rs+10−0View file
| @@ -1918,6 +1918,8 @@ | ||
| 1918 | 1918 | /// binding gets a cache of its own, so a name loaded through one loader |
| 1919 | 1919 | /// is a different Worker from the same name loaded through another. |
| 1920 | 1920 | loader_bindings: Vec<String>, |
| 1921 | + /// `env` names of Media Transformations bindings (Homeflare patch). | |
| 1922 | + media_bindings: Vec<String>, | |
| 1921 | 1923 | /// Ambient outbound authority. Loaded workers may be denied. |
| 1922 | 1924 | egress: EgressPolicy, |
| 1923 | 1925 | /// Structured-clone values and host-minted service routes that a loaded |
| @@ -2064,6 +2066,7 @@ | ||
| 2064 | 2066 | services: Vec::new(), |
| 2065 | 2067 | asset_binding: None, |
| 2066 | 2068 | loader_bindings: Vec::new(), |
| 2069 | + media_bindings: Vec::new(), | |
| 2067 | 2070 | egress: EgressPolicy::Allow, |
| 2068 | 2071 | loader_env: None, |
| 2069 | 2072 | resource_limits: None, |
| @@ -2141,6 +2144,13 @@ | ||
| 2141 | 2144 | self |
| 2142 | 2145 | } |
| 2143 | 2146 | |
| 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 | + | |
| 2144 | 2154 | /// Set this Worker's ambient outbound authority (loaded workers only). |
| 2145 | 2155 | fn with_egress(mut self, egress: EgressPolicy) -> Self { |
| 2146 | 2156 | self.egress = egress; |
modifiedcrates/celld/js/bootstrap.rs+14−0View file
| @@ -683,6 +683,20 @@ | ||
| 683 | 683 | for name in &config.loader_bindings { |
| 684 | 684 | lines.push_str(&format!("e[{:?}] = __celld.__makeLoader();\n", name)); |
| 685 | 685 | } |
| 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 | + } | |
| 686 | 700 | lines |
| 687 | 701 | }; |
| 688 | 702 | run_internal_snippet(scope, &src).ok_or_else(|| anyhow!("env install failed"))?; |
modifiedcrates/celld/js/harness.js+97−0View file
| @@ -1132,6 +1132,103 @@ | ||
| 1132 | 1132 | await __r2_mp_abort(await id.host); |
| 1133 | 1133 | }, |
| 1134 | 1134 | }); |
| 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 | +}); | |
| 1135 | 1232 | __celld.__makeR2Bucket = (binding, bucketName) => ({ |
| 1136 | 1233 | async head(key) { |
| 1137 | 1234 | const name = __r2Key(binding, "head", key); |
modifiedcrates/celld/main.rs+1−0View file
| @@ -4053,6 +4053,7 @@ | ||
| 4053 | 4053 | .filter(|name| !name.is_empty()) |
| 4054 | 4054 | .map(str::to_string) |
| 4055 | 4055 | .collect(), |
| 4056 | + media_bindings: Vec::new(), | |
| 4056 | 4057 | assets: None, |
| 4057 | 4058 | services: Vec::new(), |
| 4058 | 4059 | crons, |
modifieddocs/cloudflare-compat.md+1−0View file
| @@ -27,6 +27,7 @@ | ||
| 27 | 27 | | [D1](services/d1.md) | **Yes** | |
| 28 | 28 | | [Workflows](services/workflows.md) | **Yes** | |
| 29 | 29 | | [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) | | |
| 30 | 31 | | Workers AI | **No** | |
| 31 | 32 | | Vectorize | **No** | |
| 32 | 33 | | 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 | +} |