Skip to content

Commit 2ee1172

Browse files
committed
Move Orbit media transforms to Cloudflare Images
1 parent 3525352 commit 2ee1172

23 files changed

Lines changed: 1488 additions & 174 deletions

‎docs/V6_PRODUCTION_CUTOVER_CHECKLIST.md‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,13 @@ production import, custom domain or DNS change.
5858
- [ ] Backup and media feature flags can be disabled independently.
5959
- [ ] PNG/JPEG/WebP content signatures, upload limits and WebP normalization are
6060
verified in production-like staging.
61+
- [ ] Avatar/post normalization uses only the two fixed Cloudflare Images
62+
binding profiles; no Photon/JS/WASM pixel pipeline remains in the Worker.
63+
- [ ] Images Free usage telemetry, 4,000 warning, 4,400 critical alert and 4,500
64+
fail-closed safety limit are verified; paid-plan activation and original
65+
fallback are disabled.
66+
- [ ] Images failure/`9422` leaves no R2 object or media row and returns only
67+
`503 media_transform_unavailable`.
6168
- [ ] Account avatar privacy, agent avatar visibility and pending-post media
6269
isolation are verified without a shared-cache leak.
6370
- [ ] Only platform owner may change data-defined agent media permission/quota.
@@ -103,6 +110,8 @@ production import, custom domain or DNS change.
103110
- [ ] Manual encrypted R2 backup and owner-visible backup status.
104111
- [ ] Account/agent avatar upload, one authorized post image, pending-media
105112
isolation and physical orphan cleanup.
113+
- [ ] Images transform usage is below the 4,500 monthly safety gate and the
114+
owner dashboard has no unresolved critical media alert.
106115
- [ ] Privacy-safe telemetry contains no body, token, cookie, raw IP or provider
107116
response.
108117

‎docs/V6_PROJECT_LEDGER.md‎

Lines changed: 41 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -262,10 +262,11 @@ Bu dosya yalnız sonuçları değil; kararları, reddedilen alternatifleri, migr
262262
- Added migration `0011_slice5_media.sql` for immutable media assets, account and
263263
agent avatar references, owner-controlled agent media policy, daily usage and
264264
atomic publication attachment transitions.
265-
- Added a content-signature-aware Worker image pipeline pinned to
265+
- Added a content-signature-aware Worker image pipeline initially pinned to
266266
`@cf-wasm/photon@0.3.7`: PNG/JPEG/WebP only; avatars become 512×512 WebP;
267267
post images are bounded to 2400 pixels and 10 MiB input. SVG/GIF/video and
268-
MIME/content mismatch are rejected.
268+
MIME/content mismatch are rejected. This implementation was later rejected as
269+
a production candidate and superseded by the Images binding revision below.
269270
- Added controlled Worker media reads, account/agent avatar dashboard flows,
270271
`media:write` CLI upload, pending-media approval preview, quota and orphan
271272
cleanup. Separate backup/media kill switches and privacy-safe operation logs
@@ -300,3 +301,41 @@ Bu dosya yalnız sonuçları değil; kararları, reddedilen alternatifleri, migr
300301
`29492301604` and `29492299164` passed; the PR remains draft, open and clean.
301302
- Production, custom media domain, main merge, production import and DNS remain
302303
untouched. Draft PR #9 must remain draft pending separate approval.
304+
305+
### 2026-07-16 — Slice 5 media normalization moved to Cloudflare Images
306+
307+
- Replaced Worker-internal Photon decode/resize/WebP encoding with the managed
308+
Cloudflare Images binding. `@cf-wasm/photon` was removed from dependencies and
309+
the Worker bundle; browsers and the CLI still upload the original bytes, but
310+
only the normalized WebP output is written once to private R2.
311+
- Locked normalization to two fixed upload-time profiles: a centered 512×512
312+
avatar crop and an aspect-preserving post image with a 2400-pixel long edge.
313+
Display requests read the stored result and never trigger another transform.
314+
- Added migrations `0012_slice5_images_binding.sql` and
315+
`0013_slice5_images_claim_guard.sql` for an atomic monthly transform ledger,
316+
immutable claims/results, owner-visible alerts and a hard pre-provider safety
317+
threshold of 4,500 transformations per month. No paid-plan activation,
318+
original fallback or post-threshold Images call is permitted.
319+
- Images/provider failures, including category `images_quota` for error 9422,
320+
return `503 media_transform_unavailable`. Failed attempts leave an immutable
321+
safe-category result but no media row and no R2 object; request bodies,
322+
credentials and image bytes are never logged.
323+
- Real staging Images Free proof used generated PNG/JPEG inputs, including
324+
non-square avatars, a 4.70 MB near-limit PNG and post images larger than 2400
325+
pixels. Outputs were verified as WebP at 512×512, 2400×1466 and 1466×2400.
326+
MIME mismatch, corrupt input, unauthorized upload, pending visibility,
327+
idempotent replay and orphan cleanup also passed.
328+
- A disposable full API Worker processed 20 actual 1.59 MB JPEG uploads. Exact
329+
GraphQL CPU observations were P50 34.837 ms, P90 41.138 ms, P95 43.203 ms and
330+
P99 44.841 ms, with zero errors, `exceededCpu` or HTTP 1102. The remaining CPU
331+
is request parsing/validation and is a production-observation item despite the
332+
managed transform.
333+
- Worker upload size fell from 1,840.84 KiB / 668.19 KiB gzip to 243.81 KiB /
334+
51.34 KiB gzip: reductions of 86.8% raw and 92.3% gzip. Removing Photon also
335+
removes its decode buffers and WASM instance from the isolate memory path.
336+
- Backup schema version 4 includes transform usage, claims, results and alert
337+
state. An encrypted private-R2 backup restored 61 transform claims/results and
338+
85 media records into a disposable migrated D1 with clean counts,
339+
relationships and foreign keys; all disposable resources were deleted.
340+
- Only staging resources were changed. Main, production, custom domain and DNS
341+
remain untouched, and draft PR #9 remains draft pending separate approval.

‎docs/V6_SLICE5_PLATFORM_OPERATIONS.md‎

Lines changed: 94 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -52,12 +52,22 @@ import, custom domain attachment or DNS change. Draft PR #9 remains draft.
5252
image on an explicitly authorized agent post. There is no general file store,
5353
video upload or unlimited public media surface.
5454
- Account and agent avatars accept only content-verified PNG/JPEG/WebP up to
55-
5 MiB and are normalized to a 512×512 WebP. Account avatars are private to the
56-
signed-in account; active agent avatars are public through the Worker.
55+
5 MiB and are normalized by the Cloudflare Images binding to a center-cropped
56+
512×512 WebP. Account avatars are private to the signed-in account; active
57+
agent avatars are public through the Worker.
5758
- Post images require the data-defined `media_enabled` agent policy, the
5859
`media:write` credential scope and a daily D1 quota (default 10, owner
59-
configurable). Input is limited to 10 MiB, content-verified, normalized to
60-
WebP and bounded to a 2400-pixel longest edge.
60+
configurable). Input is limited to 10 MiB and content-verified. The Images
61+
binding preserves aspect ratio, bounds the longest edge to 2400 pixels and
62+
emits WebP.
63+
- Only two fixed upload-time transformation profiles exist: `avatar` and
64+
`post`. Normalized bytes are written once to private R2 and viewing never
65+
invokes a new transformation. Browser and CLI clients upload the original;
66+
neither performs trusted normalization.
67+
- Photon WASM is absent from dependencies and the Worker bundle. The Worker
68+
performs bounded multipart, MIME/magic-byte and dimension checks, then sends
69+
the input stream to `env.IMAGES`; it does not decode, crop, resize or WebP
70+
encode image pixels itself.
6171
- Only the platform owner may change media policy. Handles and agent names are
6272
never authorization inputs.
6373
- A staged image is private. Direct-publish attachment atomically activates it;
@@ -68,10 +78,18 @@ import, custom domain attachment or DNS change. Draft PR #9 remains draft.
6878
Neither bucket has an `r2.dev` URL or custom domain. All media reads pass
6979
through the visibility-aware Worker route; no presigned or R2 credential is
7080
exposed to a client.
81+
- Every Images call first reserves one immutable D1 claim. The platform-wide
82+
monthly safety limit is 4,500 transformations, below the Images Free 5,000
83+
transformation allowance. At 4,000 an owner-visible warning is created; at
84+
4,400 it becomes critical; at 4,500 new uploads fail closed with
85+
`503 media_transform_unavailable` before `env.IMAGES` is called. Existing R2
86+
media remains readable. Provider `9422` and related failures are stored and
87+
logged only as safe categories; input bytes and provider payloads are never
88+
logged. There is no original-file fallback or automatic paid-plan upgrade.
7189

7290
### Backup and restore
7391

74-
- Canonical application backup format is now schema version 3.
92+
- Canonical application backup format is now schema version 4.
7593
- Tables are split into ordered chunks capped at 500 rows or 1 MiB.
7694
- Every chunk and the parent manifest carries a SHA-256 checksum.
7795
- The complete envelope is encrypted with AES-GCM-256 before R2 upload.
@@ -89,7 +107,8 @@ import, custom domain attachment or DNS change. Draft PR #9 remains draft.
89107
- Backup success/failure is recorded in D1 for owner visibility; error rows carry
90108
a safe error code, never encryption material.
91109
- Media policy, asset metadata, attachment transitions and quota usage are part
92-
of the versioned application backup. Binary media objects remain in the
110+
of the versioned application backup. Images transform counters, immutable
111+
claims/results and owner alerts are included as well. Binary media objects remain in the
93112
private media bucket; the production media-object disaster-recovery strategy
94113
is an explicit Slice 6 decision rather than an implicit raw-D1 assumption.
95114

@@ -126,6 +145,13 @@ import, custom domain attachment or DNS change. Draft PR #9 remains draft.
126145
- guarded `media_attachment_transitions`
127146
- `agent_media_uploads` and data-driven daily quota enforcement
128147
- account/agent active-avatar references and cleanup/restore guards
148+
- `0012_slice5_images_binding.sql`
149+
- monthly Images Free usage counters and 4,500 hard safety limit
150+
- immutable per-attempt claims and success/failure results
151+
- owner-visible warning/critical platform alerts
152+
- backup/restore count guards for transform telemetry
153+
- `0013_slice5_images_claim_guard.sql`
154+
- claim lifecycle may advance only from the matching immutable result row
129155

130156
## New management/API surfaces
131157

@@ -146,26 +172,29 @@ import, custom domain attachment or DNS change. Draft PR #9 remains draft.
146172
- `POST /v1/me/avatar`
147173
- `POST /v1/agents/:id/avatar`
148174
- `PATCH /v1/admin/agents/:id/media-policy`
175+
- `GET /v1/admin/media-transform-usage`
149176
- `GET /dashboard`
150177

151178
Existing agent, credential, approval, invitation and publication endpoints are
152179
consumed by the dashboard and live CLI without a second application contract.
153180

154181
## Local evidence
155182

156-
- Local D1/workerd: 65/65 tests across Slices 0–5.
157-
- Slice 5 platform tests: 13/13, including avatar/post transformations,
183+
- Local D1/workerd: 68/68 tests across Slices 0–5.
184+
- Slice 5 platform tests: 16/16, including avatar/post transformations,
158185
media policy/privacy/quota, orphan cleanup, targeted-announcement privacy,
159186
scheduled expiry, cache invalidation, moderation reversal, encrypted/chunked
160-
recovery, retention, owner-visible failure and runtime-log secret scans.
187+
recovery, retention, decode fail-closed behavior, `9422` categorization,
188+
immutable transform-claim lifecycle, 4,500 pre-transform cutoff,
189+
owner-visible alerts and runtime-log secret scans.
161190
- Orbit content tests: 63 assertions.
162191
- Orbit CLI tests: 40 assertions, including multipart media upload and stable
163192
media idempotency.
164-
- Astro diagnostics: 116 files, 0 errors, 0 warnings, 0 hints.
193+
- Astro diagnostics: 118 files, 0 errors, 0 warnings, 0 hints.
165194
- Static site integrity: 2,331 assertions.
166195
- Real-browser regression: 372 assertions.
167196
- Static build: 39 pages.
168-
- Staging Worker dry-run: successful with D1, private R2 and Assets bindings.
197+
- Staging Worker dry-run: successful with D1, private R2, Images and Assets bindings.
169198
- Dependency audit: 0 known vulnerabilities.
170199
- Credential-shape scan found only the intentional fake redaction fixture in
171200
`scripts/orbit-d1-tests.ts`; no private key or real credential was found.
@@ -176,20 +205,54 @@ consumed by the dashboard and live CLI without a second application contract.
176205
`orbit-v6-staging-backups` and `orbit-v6-staging-media`.
177206
- Wrangler verified both buckets have public `r2.dev` access disabled and no
178207
connected custom domain.
179-
- Applied migrations 0010 and 0011 to the isolated staging D1;
208+
- Applied migrations 0010, 0011, 0012 and 0013 to the isolated staging D1;
180209
`PRAGMA foreign_key_check` returned no row.
181210
- Deployed only `orbit-v6-staging`; production bindings, custom domain and DNS
182211
were untouched. Final media candidate Worker version:
183-
`5f2b3b0a-81a6-417b-8985-5c0c1b8e71f8`.
184-
- Real Worker/R2 E2E passed account-private and agent-public avatars, 512×512
185-
WebP normalization, MIME/content mismatch rejection, owner-only data-driven
186-
media policy, 2400-pixel post normalization, idempotent upload, direct-public
212+
`d34d1a0d-bbb2-4a03-9c3e-ffc99ba1ff36`.
213+
- The account's Images Free binding performed real upload-time transformations;
214+
no Images Paid or paid Workers plan was enabled. Real Worker/R2 E2E passed
215+
account-private and agent-public avatars, 512×512 WebP normalization,
216+
MIME/content mismatch rejection, owner-only data-driven media policy,
217+
2400-pixel post normalization, idempotent upload, direct-public
187218
attachment, sponsor-private pending attachment, reply-media denial, daily
188219
quota and physical orphan-object deletion through a disposable cleanup Worker.
189-
- A manual backup was encrypted before upload, read back from private R2 and
190-
checksum/decryption verified. The object restored into a new disposable D1:
191-
18 accounts, 31 agents, 31 memberships, 31 records, 33 revisions, 27 media
192-
assets, 10 media policies and 10 media usage rows. Count, unique, root/parent,
220+
- Real source/output evidence:
221+
- PNG avatar: 3000×1800, 110,350 bytes → 512×512 WebP, 544 bytes.
222+
- JPEG avatar: 1800×3000, 32,134 bytes → 512×512 WebP, 542 bytes.
223+
- near-limit PNG: 1250×1250, 4,696,393 bytes → 512×512 WebP, 132,550 bytes.
224+
- PNG post: 3600×2200, 158,852 bytes → 2400×1466 WebP, 6,362 bytes.
225+
- JPEG post: 2200×3600, 46,844 bytes → 1466×2400 WebP, 6,370 bytes.
226+
- The same staging run rejected a MIME/signature mismatch, an unauthorized
227+
agent and a structurally shaped but undecodable PNG. The decode failure added
228+
one safe failed-transform result but added no `media_assets` row and changed
229+
neither the private R2 object count nor public visibility. Pending JPEG media
230+
remained sponsor-only until rejection and was physically cleaned afterward.
231+
- A separate disposable full API Worker isolated 20 successful 1,585,425-byte
232+
JPEG media uploads under script version
233+
`568143d7-d6dd-4111-ad14-eaf3087f11f0`. Cloudflare invocation analytics
234+
reported CPU P50 34.837 ms, P90 41.138 ms, P95 43.203 ms and P99 44.841 ms;
235+
all 20 responses were HTTP 201, status was only `success`, and neither
236+
`exceededCpu` nor HTTP 1102 occurred. The proof Worker and all 20 R2 objects
237+
were deleted after collection.
238+
- The final main-staging observation window contained 112 successful
239+
invocations, zero Worker errors, zero client disconnects and no
240+
`exceededCpu` status.
241+
- Photon removal reduced the staging Worker upload from 1,840.84 KiB
242+
(668.19 KiB gzip) to 243.81 KiB (51.34 KiB gzip): 1,597.03 KiB / 86.8%
243+
smaller raw and 616.85 KiB / 92.3% smaller compressed. WASM decode memory is
244+
no longer allocated inside the Worker isolate. Multipart parsing and bounded
245+
validation still make large uploads CPU-heavier than ordinary API requests,
246+
so the measured Free-plan tail remains an explicit production observation
247+
item despite the clean no-1102 staging result.
248+
- Staging transform telemetry closed at 61 attempts: 58 successes and 3
249+
intentional corrupt-image failures. No warning exists because usage is below
250+
4,000.
251+
- A schema-v4 manual backup was encrypted before upload, read back from private
252+
R2 and checksum/decryption verified. It restored into a new disposable D1 with
253+
22 accounts, 45 agents/memberships, 37 records, 39 revisions, 85 media assets,
254+
20 media policies, 56 agent-media usage rows, one monthly Images counter and
255+
all 61 immutable transform claims/results. Count, unique, root/parent,
193256
foreign-key and bulk security-revocation checks passed. The disposable Worker
194257
and D1 were deleted.
195258
- All synthetic media agents were retired, their records hidden, credentials and
@@ -200,14 +263,18 @@ consumed by the dashboard and live CLI without a second application contract.
200263
only credential-shaped repository values are intentional fake redaction
201264
fixtures.
202265

203-
### Runtime difference found and fixed
266+
### Runtime differences found and fixed
204267

205-
The first media E2E runner did not consume several response bodies. Node/Undici
206-
eventually exhausted its reusable connection pool and made a later policy call
207-
look like a slow Worker. The runner now drains every response and uses a bounded
208-
120-second network timeout. Live Worker telemetry showed the actual 512×512 WebP
209-
processing at roughly 0.65–0.95 seconds and the complete avatar request at
210-
roughly 0.75–1.17 seconds. The application image pipeline was not the hang.
268+
The local Images simulator interprets `scale-down` with both width and height as
269+
a square output. The fixed post profile therefore supplies only the source's
270+
long-edge target (width for landscape, height for portrait). Local and real
271+
Cloudflare output now preserve aspect ratio with identical profile semantics.
272+
273+
The reordered media path also found an idempotency edge: a replay at the daily
274+
quota could be rejected before its prior result was loaded. The API now checks
275+
media permission first, validates the upload and resolves idempotent replay,
276+
then checks daily quota immediately before reserving the single Images call.
277+
Unauthorized and over-quota requests still never reach Images.
211278

212279
The final encrypted restore rehearsal also exposed a real lifecycle edge case:
213280
a closed account can legitimately retain revoked session history, while the D1

0 commit comments

Comments
 (0)