Skip to content

fix: align asset hash, exclusion, and MIME with Cloudflare workers-sdk - #65

Closed
Brooooooklyn wants to merge 0 commit into
mainfrom
fix/align-asset-upload-with-workers-sdk
Closed

Brooooooklyn wants to merge 0 commit into
mainfrom
fix/align-asset-upload-with-workers-sdk

Conversation

@Brooooooklyn

@Brooooooklyn Brooooooklyn commented Apr 1, 2026 •

Copy link
Copy Markdown
Member

fix: align asset hash, exclusion, and MIME with Cloudflare workers-sdk

Switch asset hash from SHA-256(bytes) to BLAKE3(base64+ext) via blake3-jit,
matching Wrangler's hashFile algorithm. This fixes "no completion JWT" errors
caused by hash mismatches with CF's asset upload API.

  • Hash: BLAKE3 of base64(content) + bare extension, first 32 hex chars
  • Exclude .assetsignore, _headers, _redirects from asset collection
  • Support .assetsignore files with gitignore-format patterns
  • Add _worker.js safety guard (prevents exposing server code as assets)
  • Tighten all catch blocks to only swallow ENOENT, not guard errors

Co-Authored-By: Claude Opus 4.6 (1M context) noreply@anthropic.com

fix(test): warm up client module graph to fix kitchen-sink hydration flake

The "serves SSR home page and hydrates" test was flaky because
waitForServer only exercises the SSR path (Node fetch → HTML).
The first browser page load triggers Vite's client-side dep
optimization and module transformation for all dependencies
(Vue, drizzle-orm, better-auth, valibot, etc.), which on CI
easily exceeds the 10s waitForSelector timeout.

Add a warm-up page load in beforeAll that primes the client-side
module cache. Individual tests now start with all modules cached,
making them fast and deterministic.

Co-Authored-By: Claude Opus 4.6 (1M context) noreply@anthropic.com


Note

Medium Risk
Changes the deploy asset collection/hashing algorithm and ignore behavior to match Cloudflare’s upload expectations, which can affect which files get uploaded and whether deploys succeed. Risk is moderate because it touches release-critical deploy packaging, though it also adds safeguards (e.g. _worker.js guard) and narrows error swallowing to ENOENT only.

Overview
Aligns static asset preflight/upload behavior with Cloudflare workers-sdk by switching asset hashes to Wrangler-compatible BLAKE3(base64(content)+ext) (32 hex chars) and by excluding /.assetsignore, /_headers, and /_redirects from the asset set.

Adds .assetsignore support using gitignore-style patterns, introduces a safety check to prevent accidentally uploading _worker.js as a public asset (unless explicitly suppressed via .assetsignore), and tightens asset-collection error handling to only ignore missing-directory (ENOENT) cases.

Updates integration testing to warm up the client module graph before hydration tests to eliminate a CI flake caused by first-load Vite client-side optimization latency.

Written by Cursor Bugbot for commit 980d99d. This will update automatically on new commits. Configure here.

Copy link
Copy Markdown
Member Author

This stack of pull requests is managed by Graphite. Learn more about stacking.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 859b19a047

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

for (const filePath of files) {
const relativePath = "/" + toSlash(relative(dir, filePath));
if (isIgnored(relativePath)) continue;
checkWorkerJsAsset(relativePath, assetsIgnoreFilePresent);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Exempt framework worker entry from _worker.js guard

Calling checkWorkerJsAsset() during collectAndHashAssets() makes framework preflight fail for SvelteKit-style outputs where the generated worker entry is _worker.js inside the assets directory. runFrameworkDeploy() hashes assetsDir before packaging, and SvelteKit’s preset uses .svelte-kit/cloudflare (which includes _worker.js by default), so deploy now throws unless a generated .assetsignore is present. This is a release-blocking regression for framework deploys, because the CLI aborts before upload even when _worker.js is expected worker output rather than a user-exposed static asset.

Useful? React with 👍 / 👎.

@Brooooooklyn
Brooooooklyn force-pushed the fix/align-asset-upload-with-workers-sdk branch from 859b19a to 980d99d Compare April 1, 2026 13:02
@Brooooooklyn
Brooooooklyn deleted the fix/align-asset-upload-with-workers-sdk branch April 13, 2026 06:25
cpojer pushed a commit that referenced this pull request Sep 11, 2026
* fix(api): align asset upload resilience with workers-sdk (#62)

Asset uploads were failing randomly because our retry logic lacked the
gateway error protection that Cloudflare's workers-sdk has battle-tested.

Changes:
- Add gateway error (524) special handling: 5 "free" retries before
  counting against the attempt limit, with separate exponential backoff
  (5s base vs 1s) and automatic concurrency throttle from 3 to 1
- Switch from sequential to parallel bucket uploads (concurrency=3)
  using a lightweight semaphore (no npm deps, CF Worker compatible)
- Add JWT expiration detection with actionable error messaging when
  upload sessions time out
- Throw AssetUploadError with HTTP status for structured error handling
- Increase effective retries from 5 to 6 total attempts per bucket,
  matching workers-sdk MAX_UPLOAD_ATTEMPTS=5

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* refactor(api): simplify asset upload code after review

- Pre-compute base64 entries once per bucket instead of re-encoding on
  every retry attempt
- Fix isJwtExpired to handle base64url encoding (CF JWTs use url-safe chars)
- Replace buckets.flat().length with buckets.some() to avoid temp array
- Trim narrating comments that restate the code, keep only non-obvious
  constraints

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(api): close remaining alignment gaps with workers-sdk

- Retry malformed 2xx responses instead of silently accepting them.
  Wrangler's fetchResult throws on non-JSON bodies; we now validate
  the response has a result key and throw AssetUploadError if not.
- Remove 4xx fail-fast escape hatch — all errors are now retried
  (matching Wrangler), which handles transient 429/401 from CF edge.
- Rethrow original error when retries are exhausted instead of a
  generic message, preserving status and CF response details for
  debugging (matching Wrangler's throw e).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(api): correct off-by-one in gateway retry comments

The increment-before-check pattern (matching Wrangler exactly) yields
4 truly free gateway retries, not 5. The code was correct but comments
were misleading. Fix all comments to accurately describe the retry math.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(api): remove isFinalBucket check broken under concurrency

With parallel bucket uploads, the highest-index bucket may arrive at CF
before slower earlier buckets. CF returns { result: {} } (no JWT yet)
because not all hashes have been received — this is normal, not an error.
The isFinalBucket check was treating it as a failure and burning retry
budget on valid responses.

CF returns the completion JWT to whichever bucket chronologically
completes the full upload set, not the highest-index one. Wrangler has
no isFinalBucket concept — it just collects res.jwt from any bucket.
Malformed 2xx responses (CF edge-node bug) are already caught by the
postAssetUpload validation added earlier.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* refactor(api): convert recursive doUpload to iterative while loop

Replace recursive return doUpload() with a while(true) loop. Max depth
was only 9 frames (not dangerous), but the loop is easier to follow
given the interplay between attempts, bucketGatewayErrors, and
MAX_GATEWAY_ERRORS.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(api): tolerate late bucket failures once completion JWT is obtained

With parallel uploads, one bucket may return the completion JWT (CF
confirmed all hashes received) while another in-flight bucket later
errors due to transient edge/auth issues. Promise.all would reject
the entire deploy even though the upload succeeded.

Switch to Promise.allSettled and only throw if no completion JWT was
captured. Once CF returns the JWT, the upload is definitively complete
regardless of client-side bucket errors.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* refactor(api): rename MAX_UPLOAD_ATTEMPTS to MAX_UPLOAD_RETRIES

The constant is used as a max-retries ceiling (attempts >= N), not a
total attempts count. The old name implied 5 total attempts but the
code produces 6 total tries. MAX_UPLOAD_RETRIES matches the codebase
convention (retryWithBackoff's maxRetries parameter).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(api): reacquire semaphore slot per retry attempt

Previously each bucket held its slot for the entire lifetime including
all retries, so 3 concurrent buckets continued retrying in parallel
after a 524 throttle — defeating the concurrency reduction.

Now the slot is released before backoff and reacquired before each
retry attempt. After concurrency drops to 1, retries across all
buckets are properly serialized, reducing pressure on CF.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(api): defer base64 encoding until slot is acquired

Base64 encoding happened before acquireSlot(), so all buckets encoded
concurrently regardless of the concurrency limit. This could spike
memory with all base64 strings held at once.

Move encoding inside the concurrency-limited section via lazy init:
entries are computed once on first slot acquisition and reused for
retries. Memory is now bounded by concurrency * bucket_size.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(api): release slot via try/finally and short-circuit on JWT

Two fixes:
- Wrap the entire attempt body (encoding + upload) in try/finally to
  guarantee releaseSlot() runs even if base64 encoding or arrayBuffer
  throws. Previously a throw during encoding would leak the slot and
  deadlock queued buckets.
- Check completionJwt at the top of the retry loop so remaining bucket
  retries short-circuit immediately once any bucket receives the JWT,
  instead of waiting through full backoff cycles.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(api): prevent partial entries cache on encoding failure

Build base64 entries into a temporary array and only assign to the
cached entries variable after the loop completes. Previously, if
arrayBuffer() threw mid-loop, entries would be a partially-filled
array that retries would reuse (arrays are truthy), silently uploading
incomplete data.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Brooooooklyn added a commit that referenced this pull request Nov 24, 2026
…, show the last bypass

- waiting_scan copy (API and CLI) says when it waits for a deploy going live
  or for the project's Zero Trust row, not only for a scan (#75, #86).
- The CLI bypass sends the request it saw; the route takes `requestId`, so a
  bypass that loses to a protect gets 409 `public request closed` with its
  state instead of "no public request ... run public" (#72).
- Bypass refusals keep the API code, status and blockers in `--json` (#93).
- GET /projects/:id/zero-trust returns `lastBypass` (reason for deploy and
  up) and `zero-trust status` prints a "Last bypass" line (§13.3).
- `protect` that cancels an open request prints "Public request canceled.
  <slug> stays protected."; a held `public` prints the CLI request lines and
  "Check it: void project zero-trust status" (§11.4, §13.3, #80).
- A public-only Zero Trust switch with the gate on is refused with 409
  `security public gate on` before the existing-projects check (#64).
- Copy nits: "finishes" for one going-public project, the requester in the
  cancel preview, "failing since" from a stored start of the probe failure,
  bypass during a Zero Trust change says "Try again after it ends", and a
  passed request drops its held reason (#65, #87, #89, §5.2).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant