diff --git a/README.md b/README.md index 5dc65b1a..cefa8c6d 100644 --- a/README.md +++ b/README.md @@ -56,14 +56,14 @@ server build for every other request, as a Cloudflare Worker with static assets import { httpRouter } from "convex/server"; import { routeAll } from "@samebase/convex-hosting"; import { components } from "./_generated/api.js"; -import { versionId } from "../.convex-hosting/version.js"; +import { assets } from "../.convex-hosting/version.js"; // Type only, nothing is bundled: the server build imported below. import type {} from "@samebase/convex-hosting-tanstack-start/server-build"; import server from "../dist/server/server.js"; const http = httpRouter(); -routeAll(http, components.hosting, versionId, server); +routeAll({ http, component: components.hosting, assets, worker: server }); export default http; ``` @@ -106,10 +106,10 @@ wires both. ## Files only -A site without a server leaves the fourth argument out, -`routeAll(http, components.hosting, versionId)`, needs no adapter package, and deploys its build -directory: `--dist dist` after a `vite build`, or `--dist public` with no `--build` at all. A -single-page app adds `--not-found-handling single-page-application`. The +A site without a server leaves `worker` out, +`routeAll({ http, component: components.hosting, assets })`, needs no adapter package, and deploys +its build directory: `--dist dist` after a `vite build`, or `--dist public` with no `--build` at +all. A single-page app adds `--not-found-handling single-page-application`. The [tanstack-spa](https://github.com/samebase/convex-hosting/tree/main/examples/tanstack-spa) and [hello-world-assets-only](https://github.com/samebase/convex-hosting/tree/main/examples/hello-world-assets-only) examples are such sites. @@ -161,7 +161,7 @@ inside a Convex HTTP action, so `_headers`, `_redirects`, `.assetsignore`, `html `not_found_handling` mean what they mean on Cloudflare. This repository's CI runs Cloudflare's own tests against it: its -[196 cases](https://github.com/samebase/convex-hosting/blob/main/packages/convex-hosting/src/component/conformance.test.ts) +[196 cases](https://github.com/samebase/convex-hosting/blob/main/packages/convex-hosting/src/client/answer.test.ts) for `html_handling` and path encoding, and its [integration test](https://github.com/samebase/convex-hosting/tree/main/packages/convex-hosting/src/workers-sdk/fixtures/workers-with-assets-only) for a files-only site, with its imports pointed at this package, on a local Convex deployment. @@ -185,13 +185,15 @@ lists what differs and how to move an app. On Cloudflare, `wrangler deploy` uploads the files and the Worker code as one version, so the switch is atomic. Here two systems hold the two halves: the component's storage holds the files, and `npx convex deploy` pushes the code. `deploy` binds them the same way. It uploads the files as a new -version, writes that version's id to `.convex-hosting/version.js`, and then pushes the code, which -imports the file and asks the component for exactly that version. The push is the switch: no pointer -moves in a second step, so there is no moment when new code serves old files, and no page refers to -a file that is not uploaded yet. The first request the new code serves marks its version live and -deletes the versions that were live before it. A version whose push never came is deleted at a later -switch, once it is a day old; nothing is deleted by the clock alone. The one rule: run one deploy at -a time per deployment. The +version, writes that version's id and its files (each path's stored file, in the layout of +Cloudflare's asset manifest) to `.convex-hosting/version.js`, and then pushes the code, which +imports the file. The push is the switch: no pointer moves in a second step, so there is no moment +when new code serves old files, and no page refers to a file that is not uploaded yet. A request +reads no database: it costs one function call, the HTTP action, and a file adds the download of its +bytes, which Convex counts as a call too. After the push, `deploy` asks the served code to mark its +version live, which deletes the versions that were live before it. A version whose push never came +is deleted at a later switch, once it is a day old; nothing is deleted by the clock alone. The one +rule: run one deploy at a time per deployment. The [design](https://github.com/samebase/convex-hosting/blob/main/docs/design.md#orderings-and-timing) works through every interleaving. diff --git a/docs/deploy.md b/docs/deploy.md index 2277f238..8f24f7c7 100644 --- a/docs/deploy.md +++ b/docs/deploy.md @@ -1,12 +1,14 @@ # Deploy `deploy` runs `npx convex deploy` with your build and the upload of `--dist` as its `--cmd`. The -pushed code names the version it was built with, so the push switches the site. Then the command -prints the site URL, which it asks the deployment for (`CONVEX_SITE_URL`), and ends. The first -request that the new code serves marks its version live, which deletes the versions that were live -before it. A version that never becomes live, from a deploy that failed, is deleted at the first -switch after it is a day old, and the stored files that no version uses go at the switch after that. -Nothing is deleted while a site gets no request. +pushed code carries the version it was built with and that version's files, so the push switches the +site. Then the command reads the site URL from the deployment (`CONVEX_SITE_URL`), sends one request +to it with the version's mark token, which makes the code that answers mark its version live and +delete the versions that were live before it, prints the site URL, and ends. When that request +fails, the deploy still succeeds and says so; the old versions then stay until the next deploy's +mark. A version that never becomes live, from a deploy that failed, is deleted at the first switch +after it is a day old, and the stored files that no version uses go at the switch after that. +Nothing is deleted but at a deploy's mark. `deploy` goes to production. `--preview-name ` sends it to that preview (with a login or a project's preview deploy key; always pass the name with that key), and `--dev` to the development @@ -15,8 +17,8 @@ deployment (see [Development](./development.md)). A deploy key in `CONVEX_DEPLOY plain `deploy`, and so does `CONVEX_SELF_HOSTED_URL` for a self-hosted deployment; `--dev` refuses a key, and `--preview-name` accepts only a preview key, so a production key cannot redirect either. -The first deploy to a deployment pushes the component, then uploads the files. Until that upload -ends, the site answers 404. +The first deploy to a deployment pushes the component, uploads the files, and pushes again. Until +the second push, the site answers 404 naming the version. Run one deploy at a time per deployment; in GitHub Actions, the job's `concurrency` group queues them (see [GitHub Actions](#github-actions)). @@ -51,7 +53,8 @@ The two handling options work as Each file of `--dist` must be 25 MiB or smaller, and the CLI names a file that is larger. This is Cloudflare's limit per asset, and the HTTP action that serves a file cannot answer more than -Convex's 100 MiB response limit anyway. +Convex's 100 MiB response limit anyway. A site has at most 100,000 files, Cloudflare's limit per +Worker version on its Paid plan. ## Deploy tools and CI diff --git a/docs/design.md b/docs/design.md index 8b4d0dd8..7b1091a2 100644 --- a/docs/design.md +++ b/docs/design.md @@ -23,27 +23,30 @@ gone from the production hostname. On Convex, two systems hold the two halves: `npx convex deploy` pushes the app code, and the site files live in a component's storage. The design binds them the way Cloudflare does: the pushed code -carries the id of the asset version it was built with, and asks the component for exactly that -version. The push is the switch. There is no pointer that a second step must move, so there is no -moment when new code serves old files. - -Only the pushed code knows which version a deployment runs, so the serving code reports it: the -first request that new code serves finds its version in state `ready` and marks it `live`. An older -upload never goes live over a newer one: a version is marked only when no live version was created -after it, so a request still running on replaced code cannot take the site back. Marking a version -live deletes the versions that were live before it, because their code is gone by definition. -Nothing is deleted by the clock alone: deletion runs only at a switch, when a new version becomes -live, so a deployment that gets no request deletes nothing and keeps its version intact for its -first request, whenever it comes. At a switch, a version that never became live is dead too, from a -push that failed, with one exception: a slower deploy whose push has not landed yet. So a never-live -version is deleted at a switch only when it is more than a day old; the day bounds how late a push -may follow its upload, and it is the only time constant in the design. - -The precondition: deploys to one deployment do not overlap. When two overlap and the older upload is -pushed last, the component cannot tell its requests from requests still running on replaced code: -its version serves, but it never becomes live, and nothing is deleted until the next deploy. So run -one deploy at a time per deployment; the example workflows queue them, with one `concurrency` group -per deployment. +carries the asset version it was built with, its id and its files, as a Worker carries its asset +manifest: each path's content hash, content type, and stored file. The push is the switch. There is +no pointer that a second step must move, so there is no moment when new code serves old files. A +request reads no database: the HTTP action answers from the files in its own code, and downloads the +bytes of a file from storage. + +Only the pushed code knows which version a deployment runs, so the serving code reports it: after +the push, the CLI sends one request with the version's mark token, which only that version's code +holds, and the code that answers marks its version `live`. An older upload never goes live over a +newer one: a version is marked only when no live version was created after it. And a mark is late +when another version went live after its request arrived: the request carries its arrival time, and +that version's code has served since. So a request still running on replaced code cannot take the +site back. Marking a version live deletes the versions that were live before it, because their code +is gone by definition. Nothing is deleted by the clock alone: deletion runs only at a switch, when a +new version becomes live, so a version stays intact until a newer one has served. At a switch, a +version that never became live is dead too, from a push that failed, with one exception: a slower +deploy whose push has not landed yet. So a never-live version is deleted at a switch only when it is +more than a day old; the day bounds how late a push may follow its upload, and it is the only time +constant in the design. + +The precondition: deploys to one deployment do not overlap. When two overlap, the mark of the +version that serves may be refused: it then serves without being live. Its files stay, within the +two limits in "Stated, not solved". So run one deploy at a time per deployment; the example +workflows queue them, with one `concurrency` group per deployment. ## Deploy @@ -74,7 +77,8 @@ Bristol's production used it while hosting 0.3 and 0.4 ran side by side under tw Wrangler does (a link to nothing, or to a folder that contains it, is skipped with a message; a link to another folder uploads its files under both paths), and computes each file's sha256 and content type; refuses a file above 25 MiB, Cloudflare's limit per asset (the HTTP action - that serves a file could not answer more than Convex's 100 MiB response limit anyway); reads + that serves a file could not answer more than Convex's 100 MiB response limit anyway), and + more than 100,000 files, Cloudflare's limit per Worker version on its Paid plan; reads `_headers` and `_redirects` with Cloudflare's parsers into the version's config; 2. stores the config as one file through an upload URL, because `npx convex run` passes arguments on the command line, which the operating system limits, and a `_redirects` file can be large; @@ -90,26 +94,38 @@ Bristol's production used it while hosting 0.3 and 0.4 ran side by side under tw 5. calls `finishVersion`, which puts the version in state `ready`. The CLI calls it only after every batch succeeded; a crashed upload leaves an `uploading` version, and a retry reuses every file the crashed run recorded, through step 3; - 6. writes `.convex-hosting/version.js` with the id, in the CLI's state folder at the project - root, like Wrangler's `.wrangler/`; the folder carries its own `.gitignore`, so nothing of it - reaches git and no tool writes into `convex/`. The file is a build artifact that `http.ts` - imports, as a server-rendered app's `http.ts` already imports its server build; the package - ships the declaration of that module (an ambient wildcard module in a script `.d.ts` that the - package's types entry references), so a fresh clone typechecks with nothing added. Then, still - inside `npx convex deploy`, Convex bundles `convex/` with the new id and pushes. The push is - the switch, and the command ends. + 6. reads the storage URL of every entry, with the deployment's `CONVEX_CLOUD_URL`, through inline + queries in the component (`npx convex run --component --inline-query`), which run + whatever release of this package the component is, so an upgrade's upload works before its + push installs the new functions; then writes `.convex-hosting/version.js` with the version's + `assets`: the id, a random mark token, and the files (see Serve), in the CLI's state folder at + the project root, like Wrangler's `.wrangler/`. It writes a temporary file and renames it, so + a running `npx convex dev` never reads half of it; the folder carries its own `.gitignore`, so + nothing of it reaches git and no tool writes into `convex/`. The file is a build artifact that + `http.ts` imports, as a server-rendered app's `http.ts` already imports its server build; the + package ships the declaration of that module (an ambient wildcard module in a script `.d.ts` + that the package's types entry references), so a fresh clone typechecks with nothing added. + Then, still inside `npx convex deploy`, Convex bundles `convex/` with the new id and pushes. + The push is the switch, and the command ends. 3. `--dev`: the same steps, in one process: the CLI runs the build itself (Vite reads the deployment's URL from `.env.local`, so no nesting is needed), uploads, writes the version file, and pushes with `npx convex run --push`. -**The site URL.** When the push, and on a first install the upload after it, have ended, the CLI -asks the deployment for its site URL: `npx convex run --inline-query process.env.CONVEX_SITE_URL`, -with the selector of its other calls, which needs only the permission of the first-install probe. It -prints the URL and, when `GITHUB_OUTPUT` is set, appends `url=` to that file, so a -workflow step reads it as a step output. The value is the one the deployment gives its own -functions, so it is right for every kind of deployment (production, a preview, development, local, -self-hosted) and is the custom domain when the dashboard's "Override Environment Variables" sets -one; the CLI never builds it from a deployment name. +**The mark.** When the last push has ended, the CLI reads the site URL (below) and sends +`POST /.convex-hosting/mark` with the header `Convex-Hosting-Mark: `. The code +that answers calls `markLive` for its own version and answers the result. A failure, or an answer +from other code, is reported, and the deploy succeeds: nothing is deleted until a later version is +marked, so the cost is old files kept until the next deploy. + +**The site URL.** When the push, and on a first install the upload and the push after it, have +ended, the CLI asks the deployment for its site URL: +`npx convex run --inline-query process.env.CONVEX_SITE_URL`, with the selector of its other calls, +which needs only the permission of the first-install probe. It prints the URL and, when +`GITHUB_OUTPUT` is set, appends `url=` to that file, so a workflow step reads it as a step +output. The value is the one the deployment gives its own functions, so it is right for every kind +of deployment (production, a preview, development, local, self-hosted) and is the custom domain when +the dashboard's "Override Environment Variables" sets one; the CLI never builds it from a deployment +name. **First install.** The component's functions exist only after a push, and a new preview deployment exists only once `npx convex deploy` has created it, which happens before it runs the command. So @@ -117,11 +133,12 @@ the upload decides. Its first call is a probe, `npx convex run --component " was not found.` when the deployment does not have it (a function run against a missing component answers only a generic server error, which must not count). -On that exact message, the production and preview upload writes the version file and a marker file -in `.convex-hosting/` and exits without uploading, so the push that follows installs the component; -`deploy` sees the marker after `npx convex deploy` returns and runs the upload then. For `--dev`, in -one process, it writes the version file, pushes, and uploads. Until that upload ends, the site -answers 404 (see Serve). Once per deployment. +On that exact message, the production and preview upload writes a version file without files and a +marker file in `.convex-hosting/` and exits without uploading, so the push that follows installs the +component; `deploy` sees the marker after `npx convex deploy` returns, runs the upload then, and +pushes again with `npx convex deploy`. For `--dev`, in one process, it writes the version file, +pushes, uploads, and pushes again. Until the second push, the site answers 404 naming the version +(see Serve). Once per deployment. **The development loop.** Local work uses Vite's dev server, with hot reload, against the development deployment's URL, while `npx convex dev` pushes function changes, as in any Convex app. @@ -168,16 +185,16 @@ chain started, because the sweep runs before the version deletion in each chain. deleted version's unshared files, a file stored but never recorded, and the config files. An upload in progress that took a stored file from `knownFiles` loses it only if two switches happen during that one upload; it then fails with a message that says so, and a retry works. A push that the -command reports as failed may still have landed; the site then serves the new version, which marks -itself live at its first request, and the next deploy is a normal one. No resume logic. Two first -deploys at once are an overlap, which the precondition rules out: both push and upload, and the last -push serves. +command reports as failed may still have landed; the site then serves the new version, which stays +`ready` because the CLI sent no mark, and the next deploy is a normal one: its mark deletes the +versions before it. No resume logic. Two first deploys at once are an overlap, which the +precondition rules out: both push and upload, and the last push serves. **Browsers.** A page opened before a deploy keeps asking for its hashed files, which the new version does not have, exactly as on Cloudflare: they answer 404, or the shell on a files-only single-page app. An app that wants to reload on a new version adds one query that returns the bundled -`versionId` and reloads when its value changes. The README shows it. The component has no part in -it. +`assets.versionId` and reloads when its value changes. The README shows it. The component has no +part in it. ## Serve @@ -191,11 +208,17 @@ picks the longest matching prefix, so only an exact route reaches the app there. ```ts import { routeAll } from "@samebase/convex-hosting"; -import { versionId } from "../.convex-hosting/version.js"; +import { assets } from "../.convex-hosting/version.js"; -routeAll(http, components.hosting, versionId, server); +routeAll({ http, component: components.hosting, assets, worker: server }); ``` +Every input is named, after Cloudflare where Cloudflare has a name: `assets` is the static assets of +Workers Static Assets (its `assets` setting and `ASSETS` binding), and `worker` is the Worker script +(`has_user_worker`, `run_worker_first`). The export is not `site`, the setting of Workers Sites, +which Cloudflare deprecated for Static Assets. The file stays `version.js`, since it holds one +version, Cloudflare's unit of a deploy. + `serveSite` answers with the file when one matches. Otherwise it answers with the page that the optional `worker.fetch()` returns, else 404, both with `Cache-Control: no-store`; the page keeps every other header, several `Set-Cookie` included. Measured on 2026-10-14: the deployment's @@ -207,67 +230,87 @@ upload ends. `worker` is the Worker script, the object with `fetch(request)` tha exports: the code that runs on a miss. Its absence is the files-only Worker, so `serveSite` is the one entry. -`serveSite` calls the component query `route` with the method, the URL, the four request headers -that Cloudflare's handler reads (`If-None-Match`, `Sec-Fetch-Mode`, and the presence of -`Authorization` and `Range`), and `hasUserWorker`. As on Cloudflare, the presence of code decides, -and `hasUserWorker` is Cloudflare's `has_user_worker`: `serveSite` passes `true` with `worker` and -`false` without it; the app sets no option. With code, the app is the Worker, and Cloudflare's -routing with a Worker applies: inside the query, Cloudflare's `canFetch` decides whether an asset +`serveSite` runs Cloudflare's handler in the action, on the request as it came, against the site's +files, so a request calls no function of the component. As on Cloudflare, the presence of code +decides, and `hasUserWorker` is Cloudflare's `has_user_worker`: `serveSite` passes `true` with +`worker` and `false` without it; the app sets no option. With code, the app is the Worker, and +Cloudflare's routing with a Worker applies: Cloudflare's `canFetch` decides whether an asset answers, a request that does not resolve to a file goes to the app, and `not_found_handling` (the 404 page, the single-page fallback) applies to navigation requests only. Without code, the site is a -Worker without a script, whose router sends every request to the asset handler: the query skips +Worker without a script, whose router sends every request to the asset handler: `serveSite` skips `canFetch` and runs `handleRequest`, so `not_found_handling` applies to every request, and a missing hashed file on a single-page app gets the shell with 200. One difference from Cloudflare follows from Convex's router and is stated, not fixed: an exact app route wins over an asset at the same path. -The component runs the handler with a fixed compatibility date at or after 2025-04-01, the date from -which Cloudflare treats `Sec-Fetch-Mode: navigate` requests this way; the date is package code, not -configuration. When an asset answers, Cloudflare's `handleRequest` computes the status and headers: -`Cache-Control: public, max-age=0, must-revalidate` (Cloudflare omits it when the request carries -`Authorization` or `Range`, and so do we), `ETag`, 304 for `If-None-Match`, `_headers` rules, -`_redirects`, `html_handling`, and the custom 404 page with its body. Cloudflare's own cases for -`html_handling` and path encoding (the test-cases files of `fixtures/workers-shared-asset-config` in -workers-sdk, copied by the same sync script as the handler) run through `route` in -`src/component/conformance.test.ts`, with each case's files as a version's entries. Cloudflare's -integration fixtures for static assets (`fixtures/workers-with-assets-only` in workers-sdk, copied -at the same pinned commit with their `public/` folders, their imports pointed at this package) run -against the whole path an app takes: our implementation of the helper they import to start -`wrangler dev` starts an anonymous local Convex deployment, deploys the fixture's assets with -`convex-hosting deploy --dev`, and returns the site's address. -`scripts/fixtures-expected-failures.json` lists each test that fails by a stated difference from -Cloudflare, and the run fails when the list and the outcome disagree. The query drops -`CF-Cache-Status`, which describes a cache we do not run, sets `Cache-Control: no-store` on every -404, because the deployment's Cloudflare front caches 404 answers on static paths, and returns the -status, the headers, and the storage URL of the body when the response has one, whatever the status. -`serveSite` fetches that body and returns the response. When the query finds no storage URL for the -entry, or storage answers 404, because a deletion pass removed the file, the answer is 404 with -`Cache-Control: no-store`; any other fetch failure answers 502 with no caching. An app cannot read a -component's storage, so each asset hit costs that one fetch. - -When the version does not exist, is still `uploading`, or is `deleting`, `serveSite` answers a 404 -response that names the version, with `Cache-Control: no-store`, so a half-installed site answers -404 rather than rendering pages without their files. The deployment's Cloudflare front keeps -`no-store` for a path without an extension and gives a path with one a four-hour browser `max-age` -anyway; the deploy order keeps that moot, because no page refers to a file that is not uploaded yet. -A `null` asset means one thing: no asset matched, and `worker` answers. - -When `route` reports the version in state `ready`, `serveSite` calls `markLive` once, before it -answers. `markLive` marks the version only when no live version was created after it, inside its own -transaction, so a request whose code was replaced, whenever it reaches its lookup or its mark, -cannot make its version newest, and concurrent first requests mark once. That is the only write the -serving path ever makes, once per deploy. - -`route` and `markLive` are the component's only public functions, because `serveSite` runs in the -app and an app can call only a component's public functions; clients cannot call them at all. The -CLI calls the other functions, which are internal, with `npx convex run --component`. - -The two callbacks that Cloudflare's code takes map to the version's entries: `exists(path)` reads -one index entry and returns its ETag, the sha256 followed by a short hash of the content type, so -that identical bytes stored under two content types stay distinct; `getByETag` returns the content -type of the entry that `exists` found and a placeholder stream, which `serveSite` replaces with the -body. Nothing is added to Cloudflare's headers besides `no-store` on a 404. Long caching of hashed -files is a `_headers` rule, as on Cloudflare. +The handler runs with a fixed compatibility date at or after 2025-04-01, the date from which +Cloudflare treats `Sec-Fetch-Mode: navigate` requests this way; the date is package code, which the +CLI writes into each site's config, not configuration. When an asset answers, Cloudflare's +`handleRequest` computes the status and headers: `Cache-Control: public, max-age=0, must-revalidate` +(Cloudflare omits it when the request carries `Authorization` or `Range`, and so do we), `ETag`, 304 +for `If-None-Match`, `_headers` rules, `_redirects`, `html_handling`, and the custom 404 page with +its body. Cloudflare's own cases for `html_handling` and path encoding (the test-cases files of +`fixtures/workers-shared-asset-config` in workers-sdk, copied by the same sync script as the +handler) run through the action's handler in `src/client/answer.test.ts`, with each case's files as +a site's manifest. Cloudflare's integration fixtures for static assets +(`fixtures/workers-with-assets-only` in workers-sdk, copied at the same pinned commit with their +`public/` folders, their imports pointed at this package) run against the whole path an app takes: +our implementation of the helper they import to start `wrangler dev` starts an anonymous local +Convex deployment, deploys the fixture's assets with `convex-hosting deploy --dev`, and returns the +site's address. `scripts/fixtures-expected-failures.json` lists each test that fails by a stated +difference from Cloudflare, and the run fails when the list and the outcome disagree. `serveSite` +drops `CF-Cache-Status`, which describes a cache we do not run, sets `Cache-Control: no-store` on +every 404, because the deployment's Cloudflare front caches 404 answers on static paths, and, when +the response has a body, downloads the file from its storage URL. When storage answers 404, because +a deletion pass removed the file, the answer is 404 with `Cache-Control: no-store`; any other fetch +failure answers 502 with no caching. An app cannot read a component's storage, so each answer with a +body costs that one download, which Convex counts as a function call; a redirect, a 304, a 405, and +a 404 without a page download nothing. + +The site's `files` are `null` in the code that a first install pushes before its upload: `serveSite` +then answers 404 naming the version, with `Cache-Control: no-store`, without calling `worker`, so a +half-installed site answers 404 rather than rendering pages without their files. The storage URLs +name the deployment they came from, so when the site's `cloudUrl` is not the deployment's +`CONVEX_CLOUD_URL` (a version file that a deploy elsewhere wrote, pushed by a running +`npx convex dev`), it answers 404 naming both, without rendering. A site of another format, which +only another release writes, answers 500 and asks for a deploy. The deployment's Cloudflare front +keeps `no-store` for a path without an extension and gives a path with one a four-hour browser +`max-age` anyway; the deploy order keeps that moot, because no page refers to a file that is not +uploaded yet. A `null` asset means one thing: no asset matched, and `worker` answers. + +A request with the header `Convex-Hosting-Mark` set to the site's mark token is the CLI's mark: +before anything else, `serveSite` calls `markLive` for its version and answers the result as JSON, +with `Cache-Control: no-store`. `markLive` marks the version only when no live version was created +after it and none went live after the request arrived, inside its own transaction, so code that was +replaced cannot make its version newest, and a repeated mark changes nothing. It never throws: it +answers `marked`, `live`, `superseded`, `uploading`, `deleting`, or `missing`, and the CLI reports +the last four. That is the only write the serving path ever makes, once per deploy. Any other +request, with another token or none, calls no function. + +`markLive` is the component's only public function, because `serveSite` runs in the app and an app +can call only a component's public functions; clients cannot call it at all. The CLI calls the other +functions, which are internal, with `npx convex run --component`. + +The two callbacks that Cloudflare's code takes map to the site's manifest: `exists(path)` finds the +path's entry and returns its ETag, the content hash, as on Cloudflare; `getByETag` returns the +content type of the entry that `exists` found and a placeholder stream, which `serveSite` replaces +with the body. Nothing is added to Cloudflare's headers besides `no-store` on a 404. Long caching of +hashed files is a `_headers` rule, as on Cloudflare. + +**The site's files.** The manifest is Cloudflare's asset manifest, and Cloudflare's own reader +(`asset-worker/src/assets-manifest.ts`, vendored) searches it: a 20-byte header, then one 40-byte +entry per path, sorted by the path hash, the first 16 bytes of the SHA-256 of the path. The CLI +(`src/cli/manifest.ts`) encodes it as Miniflare does for `wrangler dev`. The content hash covers the +bytes and the content type, as Cloudflare's covers the bytes and the extension, so the same bytes +under two types have two ETags. The tail, which Cloudflare leaves zero, holds the index of the +storage URL (a big-endian u32) and of the content type (a big-endian u16, `0xffff` for none). Convex +modules carry no binary data, so the manifest is a base64 string, decoded once per request with +Convex's native `Uint8Array.fromBase64`. The storage URLs differ only in a key, so the start and the +end that they share are written once, and the keys are one string of fixed width: Convex evaluates +the module for every request, and an array of 100,000 strings cost 5 ms and 9 MB more than that one +string. Measured on a cloud deployment on 2026-11-10, against 3.8 ms for an empty action: 4.2 ms per +request at 10,000 files (a 0.9 MB module), 7.5 ms at 100,000 (8.9 MB), where the assets take about 7 +MB of the 64 MB that an action has, which the app's `worker` shares. Other HTTP routes of the app (auth, APIs) win over the site route when they are exact paths or longer prefixes, by Convex's router rules for the same method. @@ -286,41 +329,46 @@ entries go, so a version half deleted cannot become live. Creation times come fr field per rule and Convex limits an object to 1,024 fields. A document is limited to 1 MiB, so the CLI refuses a config above 900 KiB, leaving room for the other fields and the encoding, and names the file that causes it. An entry keeps its own content type because the type belongs to the path, -not to the bytes: paths with identical bytes share one stored file but keep their own types, and -`route` serves without reading `_storage`. +not to the bytes: paths with identical bytes share one stored file but keep their own types, and the +site's manifest carries each type, so serving reads no `_storage` metadata. Serving does not read +`config` either; it makes a retried upload of the same id refuse another config. -The package sets one limit of its own, 25 MiB per file, for the reason above. Convex's limits apply: -1 MiB per document, and the transaction limits (16,000 writes, 32,000 documents scanned, 16 MiB read -and written, 8,192 array elements, 4,096 index ranges, argument and result sizes) shape the batches. +The package sets two limits of its own, Cloudflare's: 25 MiB per file, for the reason above, and +100,000 files per site, the most that the site's files were measured with in the pushed code. +Convex's limits apply: 1 MiB per document, and the transaction limits (16,000 writes, 32,000 +documents scanned, 16 MiB read and written, 8,192 array elements, 4,096 index ranges, argument and +result sizes) shape the batches. ## Orderings and timing Every interleaving worked through for 0.4, what happens, and what checks it. "Component test" is a convex-test run of the exact order of transactions; "runtime" is a run against a local backend. -| What happens | Outcome | Checked by | -| ------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------- | -| A deploy pushes; the first request arrives | The version is marked live; the versions live before it are deleted | Component test, runtime | -| Two deploys overlap; the pushes land in creation order | Both complete; the last push's version is marked live at its first request; the other was never live and goes at a later switch when a day old | Component test (age rule) | -| Two deploys overlap; the earlier-created one pushes last | Outside the precondition. Its version serves but is never marked, because the other is newer and live; nothing is deleted until the next deploy | Component test (stale request) | -| A request on old code is in flight when a push lands, and reaches `markLive` after the new code's first mark | Its version is older than the live one, so the mark is refused; the new version stays live and keeps its files | Component test (stale request) | -| Two first requests of one version | One mark; the second is a no-op | Component test | -| Two marks in one millisecond | The second is strictly later | Component test | -| A deploy dies before its push | A never-live version; deleted at a later switch when a day old | Component test (age rule) | -| An upload dies midway | An `uploading` version; same fate; a retry reuses its recorded files | Component test, runtime (reuse) | -| The push is reported as failed but landed | The version is `ready` and is marked live at its first request | Inherent; stated | -| No request for days, weeks | Nothing is deleted; the first request marks the version live | Inherent: deletion runs only at a switch | -| Many deploys, no requests in between | The first request marks the newest; older never-live versions go when a day old, younger ones at the next switch | Component test (age rule) | -| A push lands more than a day after its upload, after another switch | Its version is gone; the site answers 404 naming it; redeploy | Stated | -| An upload borrows a stored file; a switch deletes the lending version | The file survives: files go only when unreferenced, a day old, and already unreferenced when the chain started | Component test (sweep order) | -| Two switches during one upload | The borrowed file can go; `recordFiles` says so; a retry works | Stated | -| A first request reaches a version while its entries are being deleted in pages | The version is `deleting`: 404, no mark | Component test | -| Documents share a creation time at a page boundary | The cursor carries the ids seen at that time; none is skipped | Component test (crafted cursor) | -| First install: the component does not exist yet | Push first, then upload; 404 until the upload ends | Runtime (both flows) | -| Two first installs at once | Outside the precondition. Both push and upload; the last push serves | Stated | -| Two commands from one checkout at once | They overwrite each other's build output and version file | Stated, unsupported | -| A production deploy from a checkout where `npx convex dev` runs | Production's id is pushed to development until the next `deploy --dev` | Stated | -| `deploy --dev` against an anonymous local deployment without `npx convex dev` | Each Convex CLI call starts and stops its own backend; the upload fails with `fetch failed` | Runtime; stated in the README | +| What happens | Outcome | Checked by | +| --------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------- | +| A deploy pushes; the CLI's mark reaches the new code | The version is marked live; the versions live before it are deleted | Component test, runtime | +| Two deploys overlap; the pushes land in creation order | Both complete; the last push's version is marked live by its deploy's mark; the other was never live and goes at a later switch when a day old | Component test (age rule) | +| Two deploys overlap; the earlier-created one pushes last | Outside the precondition. Its version serves but is never marked, because the other is newer and live; nothing is deleted until the next deploy | Component test (stale request) | +| Two deploys overlap; the newer one's mark is still running while the older one is pushed and marked | The late mark is refused, because a version went live after its request arrived; the version that serves stays live | Component test, `overlap.test.ts` | +| A mark for an older version reaches its code after the new version was marked, from an overlapping deploy | Its version is older than the live one, so the mark answers `superseded`; the new version stays live and keeps its files | Component test, CLI test | +| Two marks of one version | One mark; the second answers `live` | Component test | +| Two marks in one millisecond | The second is strictly later | Component test | +| A deploy dies before its push | A never-live version; deleted at a later switch when a day old | Component test (age rule) | +| An upload dies midway | An `uploading` version; same fate; a retry reuses its recorded files | Component test, runtime (reuse) | +| The push is reported as failed but landed | The version serves, `ready`, since the CLI sent no mark; the next deploy's mark deletes the versions before it | Inherent; stated | +| No request for days, weeks | Nothing changes: the deploy marked its version, and deletion waits for the next mark | Inherent: deletion runs only at a switch | +| Many deploys in a row | Each deploy marks its version; the one before goes at that mark, never-live versions when a day old | Component test (age rule) | +| A push lands more than a day after its upload, after another switch | Its files are gone: pages render, and its files answer 404 from storage; redeploy | Stated | +| An upload borrows a stored file; a switch deletes the lending version | The file survives: files go only when unreferenced, a day old, and already unreferenced when the chain started | Component test (sweep order) | +| Two switches during one upload | The borrowed file can go; `recordFiles` says so; a retry works | Stated | +| A request on replaced code reaches a version while it is being deleted | Its files answer 404 from storage; a mark answers `deleting` | Component test, client test | +| Documents share a creation time at a page boundary | The cursor carries the ids seen at that time; none is skipped | Component test (crafted cursor) | +| The CLI's mark fails, or other code answers it | Reported; the deploy succeeds; nothing is deleted until the next deploy's mark | CLI test | +| First install: the component does not exist yet | Push a site without files, upload, push the site; 404 naming the version until the second push | CLI test, runtime (both flows) | +| Two first installs at once | Outside the precondition. Both push and upload; the last push serves | Stated | +| Two commands from one checkout at once | They overwrite each other's build output and version file | Stated, unsupported | +| A production deploy from a checkout where `npx convex dev` runs | Production's site is pushed to development, which answers 404 naming production's deployment until the next `deploy --dev` | Client test; stated | +| `deploy --dev` against an anonymous local deployment without `npx convex dev` | Each Convex CLI call starts and stops its own backend; the upload fails with `fetch failed` | Runtime; stated in the README | Not reproducible in the test runtime and not yet run against a cloud deployment: two real pushes in a chosen order, a preview deployment, an old HTTP action kept running across a push. A smoke script @@ -329,10 +377,13 @@ place for those. ## Stated, not solved -- Deploys to one deployment do not overlap. When two overlap and the older upload is pushed last, - the component cannot tell its requests from requests still running on replaced code, so its - version serves but is never marked live, each of its requests calls `markLive` for nothing, and - nothing is deleted until the next deploy. +- Deploys to one deployment do not overlap. When two overlap, the mark of the version that serves + may be refused, so it serves without being live and nothing is deleted until the next deploy. The + version that serves keeps its entries and its files (`src/client/overlap.test.ts`), within two + limits. The arrival time is read in the HTTP action and compared with a time set in the mutation, + so a late mark is refused as far as those two clocks agree. And the day is a bound, not a margin: + an upload pushed just under a day later, after a newer version went live, is deleted as never live + by a `collect` call that runs past the day. - An upload that took a stored file from `knownFiles` loses it only if two switches happen during that one upload; it fails with a message that says so, and a retry works. - No `run_worker_first`, no `base_path`, no selectable compatibility date: an app that needs its @@ -342,11 +393,11 @@ place for those. ## Not here, and why -- No live pointer that a command moves, no `activate`, no `getLiveVersion`: the pushed code names - its version, and the serving code reports it. -- No lock, no heartbeat, no cron, no call after the push besides the read of the site URL: a version - is deleted only after another version has served in its place. A one-day age bounds garbage from - failed deploys; it decides nothing about what is served. +- No live pointer that a command moves, no `activate`, no `getLiveVersion`: the pushed code carries + its version, and the served code marks it when the CLI asks. +- No lock, no heartbeat, no cron, no call after the push besides the read of the site URL and the + mark: a version is deleted only after another version has served in its place. A one-day age + bounds garbage from failed deploys; it decides nothing about what is served. - No marking of hashed files, no one-year `Cache-Control`: Cloudflare has neither. A site that wants them writes one `_headers` rule. - No component HTTP route, no `httpPrefix` mount, no second serving helper: one way for static and @@ -363,6 +414,23 @@ place for those. Approaches that were built or proposed during the 0.4 design and dropped, with the reason, so they are not proposed again. +- **A component query per request (`route`, 0.4 to 0.14).** An HTTP action reads the database only + through a query, so every request cost two function calls, and an answer with a body a third, its + download. On samebase.com in one billing period, `route` ran 109,000 times for 72,000 site + requests and 35,000 session refreshes, which the `/auth` exact routes sent through the site's + action and which never match a file. The pushed code now carries the site's files. +- **Marking live once per isolate, from the serving code.** Convex evaluates the HTTP module for + every request: on a cloud deployment on 2026-11-04, a module-level counter read 1 on every one of + 52 requests, 40 of them concurrent, while the module's own random id stayed the same. A + module-level flag would have called `markLive` on every request. +- **Marking live from the CLI with `npx convex run lib:markLive`.** When deploys overlap, the CLI + can mark a version whose code does not serve, and the mark deletes the files of the code that + does. The mark request reaches the code that serves, and its token makes only that deploy's code + mark. `src/client/overlap.test.ts` runs an order of two deploys in which the CLI's mark deletes + the entries of the version that serves, with no request still running. +- **Marking live on a random share of requests.** It kept the mark in the serving code for about one + call per hundred requests, but a site with little traffic would keep its old versions for days, + and every request would pay the draw. - **Deletion driven by the CLI after the push.** The order in which overlapping deploys report back is not the order in which their pushes landed, so a CLI could delete the version that is live. - **A deploy lock in the component, with a heartbeat and a two-minute expiry, and a kill of the push @@ -379,7 +447,7 @@ are not proposed again. between a request's lookup and its mark, not the gap between the request's start and its lookup: a request on replaced code whose lookup came after the new code's first mark passed it, made its old version newest, and `collect` deleted the new version's files. Creation order decides the mark - instead, and deploys that do not overlap are the precondition. + instead, with the arrival time of the mark's request, which needs no lookup. - **A committed version file in `convex/`.** Its value is set by the deploy that pushes it, so the committed value is never used by a correct deploy; it left stale ids and merge conflicts in git, and a plain `npx convex deploy` from a clean checkout would push a stale id and take the site @@ -495,9 +563,10 @@ or ChessMerge goes; the list is checked at every release. At 0.8.0 and 0.5.0 tha - `packages/convex-hosting` - `src/component`: `schema.ts`, `lib.ts`, `convex.config.ts`, and its generated files. - - `src/client`: `routeAll` and the shipped declaration of the version module. + - `src/client`: `routeAll`, Cloudflare's handler run against the assets (`answer.ts`), the assets' + types and lookup (`manifest.ts`), and the shipped declaration of the version module. - `src/cli`: the `convex-hosting` command: `deploy`, and `upload`, the inner step that - `npx convex deploy --cmd` has to call as a program. + `npx convex deploy --cmd` has to call as a program; `manifest.ts` encodes the manifest. - `src/workers-sdk`: Cloudflare's asset worker, its tests, and its html_handling and encoding cases, copied by `scripts/sync-workers-sdk.ts` from cloudflare/workers-sdk at the commit in `UPSTREAM`, each file at its upstream path, so the folder mirrors that repository. Only the sync diff --git a/docs/development.md b/docs/development.md index c8effe32..a66630c3 100644 --- a/docs/development.md +++ b/docs/development.md @@ -44,7 +44,9 @@ Two cases are transient: ```ts vi.mock("../dist/server/server.js", () => ({ default: { fetch: async () => new Response() } })); - vi.mock("../.convex-hosting/version.js", () => ({ versionId: "test" })); + vi.mock("../.convex-hosting/version.js", () => ({ + assets: { format: 1, versionId: "test", markToken: "test", files: null }, + })); ``` - `npx convex codegen` bundles `convex/http.ts`, so before the first `deploy --dev` it fails with @@ -62,9 +64,9 @@ open tabs on a new version, add a query that returns the bundled version: // convex/siteVersion.ts import { v } from "convex/values"; import { query } from "./_generated/server.js"; -import { versionId } from "../.convex-hosting/version.js"; +import { assets } from "../.convex-hosting/version.js"; -export const get = query({ args: {}, returns: v.string(), handler: () => versionId }); +export const get = query({ args: {}, returns: v.string(), handler: () => assets.versionId }); ``` and reload when its value changes after the first one: diff --git a/docs/from-static-hosting.md b/docs/from-static-hosting.md index 839a6c7e..19ba6aa8 100644 --- a/docs/from-static-hosting.md +++ b/docs/from-static-hosting.md @@ -10,14 +10,14 @@ and source on 2026-10-18, version 0.2.1. ## What differs -| | static-hosting | convex-hosting | -| ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Pages | Files only | What no file answers goes to the app's server entry, an object with `fetch(request)`; TanStack Start has an [adapter](../packages/convex-hosting-tanstack-start) | -| File rules | Its own: a miss without an extension gets `index.html` unless deployed with `--no-spa`, and a miss with one is 404. Hashed file names get a one-year cache | Cloudflare's asset Worker: `_headers`, `_redirects`, `.assetsignore`, `html_handling`, and `not_found_handling` (see [Serving](./serving.md)). Every file revalidates unless `_headers` says otherwise | -| Routes | The component owns `/`, with the app's routes under `/api`, or a sub-path; or `registerStaticRoutes` adds a GET catch-all to `convex/http.ts` | `routeAll` adds a catch-all for every method to `convex/http.ts`, and exact routes win over it. There is no sub-path option | -| Deploy | Build, `npx convex deploy`, then upload. The upload's last mutation switches the files and deletes the previous ones, so code and files switch at different moments | Upload a new version, then push code that names it. The push switches code and files together, and the first request on the new code deletes the versions live before it ([how](../README.md#how-a-deploy-switches-the-site)) | -| CLI | `setup`, `deploy`, and `upload`; `--dist` defaults to `./dist` and `--build-command` to `npm run build` | `deploy`, with `--dist` required and `--build` optional; `--dev` and `--preview-name` pick the deployment ([options](./deploy.md#options)) | -| Reload prompt | `UpdateBanner` and `useDeploymentUpdates` | A query and a hook to copy, in [Development](./development.md#open-tabs-after-a-deploy) | +| | static-hosting | convex-hosting | +| ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Pages | Files only | What no file answers goes to the app's server entry, an object with `fetch(request)`; TanStack Start has an [adapter](../packages/convex-hosting-tanstack-start) | +| File rules | Its own: a miss without an extension gets `index.html` unless deployed with `--no-spa`, and a miss with one is 404. Hashed file names get a one-year cache | Cloudflare's asset Worker: `_headers`, `_redirects`, `.assetsignore`, `html_handling`, and `not_found_handling` (see [Serving](./serving.md)). Every file revalidates unless `_headers` says otherwise | +| Routes | The component owns `/`, with the app's routes under `/api`, or a sub-path; or `registerStaticRoutes` adds a GET catch-all to `convex/http.ts` | `routeAll` adds a catch-all for every method to `convex/http.ts`, and exact routes win over it. There is no sub-path option | +| Deploy | Build, `npx convex deploy`, then upload. The upload's last mutation switches the files and deletes the previous ones, so code and files switch at different moments | Upload a new version, then push code that names it. The push switches code and files together, and the deploy then marks it live, which deletes the versions live before it ([how](../README.md#how-a-deploy-switches-the-site)) | +| CLI | `setup`, `deploy`, and `upload`; `--dist` defaults to `./dist` and `--build-command` to `npm run build` | `deploy`, with `--dist` required and `--build` optional; `--dev` and `--preview-name` pick the deployment ([options](./deploy.md#options)) | +| Reload prompt | `UpdateBanner` and `useDeploymentUpdates` | A query and a hook to copy, in [Development](./development.md#open-tabs-after-a-deploy) | ## How to move @@ -31,9 +31,9 @@ and source on 2026-10-18, version 0.2.1. `httpPrefix: "/api"` from `defineApp`, and add `/api` to the paths of your own routes whose URLs must stay. 3. In `convex/http.ts`, replace `registerStaticRoutes(...)` with - `routeAll(http, components.hosting, versionId)`, and import `versionId` from + `routeAll({ http, component: components.hosting, assets })`, and import `assets` from `../.convex-hosting/version.js`. Your exact routes keep winning. A server-rendered app passes its - server entry as the fourth argument. + server entry as `worker`. 4. In the deploy scripts, replace `@convex-dev/static-hosting deploy`, or the pair `npx convex deploy` and `upload --prod`, with `convex-hosting deploy --build "" --dist `, which builds, uploads, and pushes @@ -57,8 +57,8 @@ Then check three things: without a server entry answers a missing file with an extension, such as `/assets/old.js`, with `index.html`, where static-hosting answered 404. - **Old files.** The push that removes `app.use(staticHosting)` unmounts that component, and its - files stay until you delete it in the Convex dashboard. From then on, each deploy's first request - deletes the version that was live before it. + files stay until you delete it in the Convex dashboard. From then on, each deploy's mark deletes + the version that was live before it. ## From convex-hosting 0.3.x diff --git a/docs/serving.md b/docs/serving.md index 24600806..4a9c51d4 100644 --- a/docs/serving.md +++ b/docs/serving.md @@ -26,7 +26,7 @@ the file when the page reloads. A local deployment, which has no front, sends th ## Routing -`routeAll(http, component, versionId, worker?)` routes the site's HTTP action for every method at +`routeAll({ http, component, assets, worker? })` routes the site's HTTP action for every method at every path, and returns it. The action answers with the file that matches, else with what `worker` answers (see [Server-rendered pages](#server-rendered-pages)), else 404. Another method than GET or HEAD on a path that has a file answers 405, as on Cloudflare; on any other path it goes to `worker`, @@ -35,9 +35,11 @@ miss. Everything it returns gets `Cache-Control: no-store`, and so does a 404, b `*.convex.site` front caches paths with an extension. The front keeps `no-store` for a path without an extension and replaces it with a four-hour browser `max-age` for a path with one, so a browser that asks for a script before its upload ended keeps the 404; the deploy order prevents that case, -because no page refers to a file that is not uploaded yet. When the version does not exist or is -still uploading, it answers 404 naming the version. At the first request for a new version, it marks -the version live. +because no page refers to a file that is not uploaded yet. The `assets` of the version come with the +pushed code, in `.convex-hosting/version.js`, so a request reads no database: it costs one function +call, the HTTP action, and a file adds the download of its bytes, which Convex counts as a call too. +A redirect, a 304, a miss, and a rendered page download nothing. Until a first install's upload +ends, the site answers 404 naming the version. As on Cloudflare, the presence of code decides where `not_found_handling` (the single-page fallback or the 404 page) applies: @@ -62,10 +64,10 @@ over an asset at the same path. The other differences are in ## Server-rendered pages -`routeAll` takes a fourth argument, `worker`, the object with `fetch(request)` that the app's server -entry exports, and calls it when no file matches. `convex/http.ts` imports the server build -directly, such as `../dist/server/server.js` for TanStack Start, so `npx convex dev` bundles it only -after a build: on a fresh clone, the first `deploy --dev` builds before the first push (see +`routeAll` takes a `worker`, the object with `fetch(request)` that the app's server entry exports, +and calls it when no file matches. `convex/http.ts` imports the server build directly, such as +`../dist/server/server.js` for TanStack Start, so `npx convex dev` bundles it only after a build: on +a fresh clone, the first `deploy --dev` builds before the first push (see [Quick start](../README.md#quick-start)). [`@samebase/convex-hosting-tanstack-start`](../packages/convex-hosting-tanstack-start) runs TanStack diff --git a/examples/hello-world-assets-only-workers.patch b/examples/hello-world-assets-only-workers.patch index 24ca5ec4..45c17848 100644 --- a/examples/hello-world-assets-only-workers.patch +++ b/examples/hello-world-assets-only-workers.patch @@ -12,20 +12,20 @@ index 41a6c4afe86dc311eed5da6e75804b73bdc4462f..00000000000000000000000000000000 -export default app; diff --git a/convex/http.ts b/convex/http.ts deleted file mode 100644 -index 68549db0c7867c3c98d3caae46fb994864126d94..0000000000000000000000000000000000000000 +index 51996727a045edbc5b84557709e31b07a62c3bfb..0000000000000000000000000000000000000000 --- a/convex/http.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { httpRouter } from "convex/server"; -import { routeAll } from "@samebase/convex-hosting"; -import { components } from "./_generated/api.js"; --import { versionId } from "../.convex-hosting/version.js"; +-import { assets } from "../.convex-hosting/version.js"; - -const http = httpRouter(); - -// Every method, every path, as a Cloudflare Worker without a script: a file for a path that has -// one, else 404; another method than GET or HEAD on a file answers 405. --routeAll(http, components.hosting, versionId); +-routeAll({ http, component: components.hosting, assets }); - -export default http; diff --git a/convex/tsconfig.json b/convex/tsconfig.json diff --git a/examples/hello-world-assets-only/convex/http.ts b/examples/hello-world-assets-only/convex/http.ts index 68549db0..51996727 100644 --- a/examples/hello-world-assets-only/convex/http.ts +++ b/examples/hello-world-assets-only/convex/http.ts @@ -1,12 +1,12 @@ import { httpRouter } from "convex/server"; import { routeAll } from "@samebase/convex-hosting"; import { components } from "./_generated/api.js"; -import { versionId } from "../.convex-hosting/version.js"; +import { assets } from "../.convex-hosting/version.js"; const http = httpRouter(); // Every method, every path, as a Cloudflare Worker without a script: a file for a path that has // one, else 404; another method than GET or HEAD on a file answers 405. -routeAll(http, components.hosting, versionId); +routeAll({ http, component: components.hosting, assets }); export default http; diff --git a/examples/tanstack-spa/convex/http.ts b/examples/tanstack-spa/convex/http.ts index 02d1725d..229ed7c7 100644 --- a/examples/tanstack-spa/convex/http.ts +++ b/examples/tanstack-spa/convex/http.ts @@ -1,12 +1,12 @@ import { httpRouter } from "convex/server"; import { routeAll } from "@samebase/convex-hosting"; import { components } from "./_generated/api.js"; -import { versionId } from "../.convex-hosting/version.js"; +import { assets } from "../.convex-hosting/version.js"; const http = httpRouter(); // Every method, every path, as a Cloudflare Worker without a script: a file for a path that has // one, else the single-page fallback; another method than GET or HEAD on a file answers 405. -routeAll(http, components.hosting, versionId); +routeAll({ http, component: components.hosting, assets }); export default http; diff --git a/examples/tanstack-ssr-workers.patch b/examples/tanstack-ssr-workers.patch index bcfe2650..43250147 100644 --- a/examples/tanstack-ssr-workers.patch +++ b/examples/tanstack-ssr-workers.patch @@ -18,14 +18,14 @@ index 1831f4b4fa5703fe1332d9cf45fb2308a57be703..dcc4d5f09735722e1164710651a0c69d export default app; diff --git a/convex/http.ts b/convex/http.ts deleted file mode 100644 -index 2bd08d55546dfacc4e31f84614c81a5625beee4e..0000000000000000000000000000000000000000 +index 4ae60e6c413b09f9d22481a9cba1b67b633b2529..0000000000000000000000000000000000000000 --- a/convex/http.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { httpRouter } from "convex/server"; -import { routeAll } from "@samebase/convex-hosting"; -import { components } from "./_generated/api.js"; --import { versionId } from "../.convex-hosting/version.js"; +-import { assets } from "../.convex-hosting/version.js"; -// Type only, nothing is bundled: the server build imported below. -import type {} from "@samebase/convex-hosting-tanstack-start/server-build"; -import server from "../dist/server/server.js"; @@ -35,7 +35,7 @@ index 2bd08d55546dfacc4e31f84614c81a5625beee4e..00000000000000000000000000000000 -// Every method, every path: a file for a path that has one (another method than GET or HEAD on it -// answers 405), the app's server (src/server.ts) for every other path, as a Cloudflare Worker with -// static assets does. --const handler = routeAll(http, components.hosting, versionId, server); +-const handler = routeAll({ http, component: components.hosting, assets, worker: server }); -// Exact routes for the three auth paths: the Convex Auth component holds the /auth prefix, where it -// serves the key set, and the longest prefix wins, so the catch-all above never sees them. -for (const path of ["/auth/signin", "/auth/refresh", "/auth/signout"]) { diff --git a/examples/tanstack-ssr/convex/http.ts b/examples/tanstack-ssr/convex/http.ts index 2bd08d55..4ae60e6c 100644 --- a/examples/tanstack-ssr/convex/http.ts +++ b/examples/tanstack-ssr/convex/http.ts @@ -1,7 +1,7 @@ import { httpRouter } from "convex/server"; import { routeAll } from "@samebase/convex-hosting"; import { components } from "./_generated/api.js"; -import { versionId } from "../.convex-hosting/version.js"; +import { assets } from "../.convex-hosting/version.js"; // Type only, nothing is bundled: the server build imported below. import type {} from "@samebase/convex-hosting-tanstack-start/server-build"; import server from "../dist/server/server.js"; @@ -11,7 +11,7 @@ const http = httpRouter(); // Every method, every path: a file for a path that has one (another method than GET or HEAD on it // answers 405), the app's server (src/server.ts) for every other path, as a Cloudflare Worker with // static assets does. -const handler = routeAll(http, components.hosting, versionId, server); +const handler = routeAll({ http, component: components.hosting, assets, worker: server }); // Exact routes for the three auth paths: the Convex Auth component holds the /auth prefix, where it // serves the key set, and the longest prefix wins, so the catch-all above never sees them. for (const path of ["/auth/signin", "/auth/refresh", "/auth/signout"]) { diff --git a/packages/convex-hosting-tanstack-start/README.md b/packages/convex-hosting-tanstack-start/README.md index 3e9acb65..9999a624 100644 --- a/packages/convex-hosting-tanstack-start/README.md +++ b/packages/convex-hosting-tanstack-start/README.md @@ -29,11 +29,12 @@ other request goes to the server, as it goes to a Cloudflare Worker: ```ts import { routeAll } from "@samebase/convex-hosting"; +import { assets } from "../.convex-hosting/version.js"; // Type only, nothing is bundled: the server build imported below. import type {} from "@samebase/convex-hosting-tanstack-start/server-build"; import server from "../dist/server/server.js"; -routeAll(http, components.hosting, versionId, server); +routeAll({ http, component: components.hosting, assets, worker: server }); ``` Import `@samebase/convex-hosting` before the server build: it defines `queueMicrotask` when it diff --git a/packages/convex-hosting/CHANGELOG.md b/packages/convex-hosting/CHANGELOG.md index c1f722c9..b7631b4e 100644 --- a/packages/convex-hosting/CHANGELOG.md +++ b/packages/convex-hosting/CHANGELOG.md @@ -1,5 +1,37 @@ # Changelog +## 0.15.0 + +- A request reads no database. The deploy writes the version's assets into + `.convex-hosting/version.js` (each path's content hash, content type, and stored file, in the + layout of Cloudflare's asset manifest), and the HTTP action answers from them. A page, a miss, a + redirect, a 304, and a session refresh cost one function call, the HTTP action, where they cost + two; an answer with a body costs two, the action and the download of the file, where it cost + three. The component's `route` query is gone. +- Breaking: `routeAll` takes one object, with every input named, and the assets in place of the + version id: + + ```ts + import { assets } from "../.convex-hosting/version.js"; + + routeAll({ http, component: components.hosting, assets, worker: server }); + ``` + + A files-only site leaves `worker` out. `assets` and `worker` are Cloudflare's names: the static + assets of a Worker, and the Worker script. The file exports only `assets`: the query that reloads + open tabs reads `assets.versionId` in place of `versionId`. A test that mocks the version module + adds `assets: { format: 1, versionId: "test", markToken: "test", files: null }`. + +- After the push, `deploy` sends one request with the version's mark token, and the code that + answers marks its version live; before, the first request did. `markLive` answers what it did and + never throws. It takes the time the request arrived and refuses a mark when another version went + live after it: a mark that was still running when another deploy's push and mark landed deleted + the entries of the version that serves. +- A first install pushes twice: once to install the component, and once after the upload, to serve + the site. +- A version file uploaded to another deployment, such as production's pushed to development by a + running `npx convex dev`, answers 404 naming that deployment. + ## 0.14.0 - The README, which this package ships, starts with what the component is, who it is for, and the diff --git a/packages/convex-hosting/package.json b/packages/convex-hosting/package.json index 47dff2c3..fc076b15 100644 --- a/packages/convex-hosting/package.json +++ b/packages/convex-hosting/package.json @@ -1,6 +1,6 @@ { "name": "@samebase/convex-hosting", - "version": "0.14.0", + "version": "0.15.0", "description": "Serves a web app from its own Convex deployment: the files of a build, and the pages the app renders.", "keywords": [ "component", @@ -59,6 +59,7 @@ "@types/node": "catalog:", "convex": "catalog:", "convex-test": "catalog:", + "fast-check": "catalog:", "typescript": "catalog:", "undici": "catalog:", "vite-plus": "catalog:" diff --git a/packages/convex-hosting/scripts/sync-workers-sdk.ts b/packages/convex-hosting/scripts/sync-workers-sdk.ts index 8b0f976c..02f71b38 100644 --- a/packages/convex-hosting/scripts/sync-workers-sdk.ts +++ b/packages/convex-hosting/scripts/sync-workers-sdk.ts @@ -2,7 +2,7 @@ // from cloudflare/workers-sdk (MIT OR Apache-2.0) into src/workers-sdk, at the commit recorded in // src/workers-sdk/UPSTREAM: the asset Worker and its tests from packages/workers-shared, and // Cloudflare's html_handling and encoding cases from fixtures/workers-shared-asset-config, which -// src/component/conformance.test.ts runs through `route`. +// src/client/answer.test.ts runs through the site's action. // // node scripts/sync-workers-sdk.ts [] // @@ -40,6 +40,7 @@ const UPSTREAM_FILES = [ "fixtures/workers-shared-asset-config/test-cases/encoding-test-cases.ts", "fixtures/workers-shared-asset-config/test-cases/html-handling-test-cases.ts", "packages/workers-shared/asset-worker/src/analytics.ts", + "packages/workers-shared/asset-worker/src/assets-manifest.ts", "packages/workers-shared/asset-worker/src/compatibility-flags.ts", "packages/workers-shared/asset-worker/src/configuration.ts", "packages/workers-shared/asset-worker/src/constants.ts", diff --git a/packages/convex-hosting/src/cli/convex.ts b/packages/convex-hosting/src/cli/convex.ts index 9476fdd0..1163fd54 100644 --- a/packages/convex-hosting/src/cli/convex.ts +++ b/packages/convex-hosting/src/cli/convex.ts @@ -46,7 +46,8 @@ export const nodeCli: Cli = { execFile( process.execPath, [convexBin(process.cwd()), ...args], - { encoding: "utf8" }, + // A page of storage URLs can pass Node's default of 1 MiB. + { encoding: "utf8", maxBuffer: 64 * 1024 * 1024 }, (error, stdout, stderr) => { const exitCode = error === null ? 0 : typeof error.code === "number" ? error.code : 1; resolve({ exitCode, stdout, stderr }); @@ -150,6 +151,33 @@ export async function siteUrl(cli: Cli, flags: string[]): Promise { return z.string().parse(JSON.parse(stdout)); } +/** + * Evaluates `code` as an inline query in the component and validates its result. An inline query + * runs whatever release of this package the component's functions are, so the upload of a new + * release reads with it before the push has installed the new functions. + */ +export async function runComponentQuery( + cli: Cli, + target: Target, + code: string, + result: z.ZodType, +): Promise { + const { exitCode, stdout, stderr } = await cli.convex([ + "run", + "--component", + target.component, + "--inline-query", + code, + ...target.flags, + ]); + if (exitCode !== 0) { + throw new Error( + stderr.trim() || stdout.trim() || `npx convex run --inline-query exited with ${exitCode}.`, + ); + } + return result.parse(JSON.parse(stdout)); +} + /** * Runs a function of the component with `npx convex run` and validates its result. The Convex CLI * prints the result as JSON from another process, so `result` checks it at runtime; its type makes diff --git a/packages/convex-hosting/src/cli/files.ts b/packages/convex-hosting/src/cli/files.ts index 41bcc7bb..e7ff818f 100644 --- a/packages/convex-hosting/src/cli/files.ts +++ b/packages/convex-hosting/src/cli/files.ts @@ -10,6 +10,7 @@ import { parseHeaders } from "../workers-sdk/packages/workers-shared/utils/confi import { parseRedirects } from "../workers-sdk/packages/workers-shared/utils/configuration/parseRedirects.js"; import { HEADERS_FILENAME, + MAX_ASSET_COUNT, MAX_ASSET_SIZE, REDIRECTS_FILENAME, } from "../workers-sdk/packages/workers-shared/utils/constants.js"; @@ -72,6 +73,13 @@ export async function readDist( } walk(file); } else if (stats.isFile() && !assetsIgnoreFunction(ignorePath)) { + // Cloudflare's limit per Worker version on its Paid plan, 100,000 files. + if (entries.length === MAX_ASSET_COUNT) { + throw new Error( + `${dist} has more than ${MAX_ASSET_COUNT.toLocaleString("en-US")} files, Cloudflare's ` + + "limit per Worker version. List the files that are not served in .assetsignore.", + ); + } const bytes = readFileSync(file); // Cloudflare's limit per asset, 25 MiB. The HTTP action that serves a file cannot answer // more than Convex's 100 MiB response limit anyway. diff --git a/packages/convex-hosting/src/cli/main.test.ts b/packages/convex-hosting/src/cli/main.test.ts index a78faa81..5cfccf5c 100644 --- a/packages/convex-hosting/src/cli/main.test.ts +++ b/packages/convex-hosting/src/cli/main.test.ts @@ -12,6 +12,7 @@ import { import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; import { describe, expect, test } from "vite-plus/test"; +import { manifestLookup, MARK_HEADER, MARK_PATH, type Assets } from "../client/manifest.js"; import { deploymentSelector, type Cli } from "./convex.js"; import { main, VERSION_FILE } from "./main.js"; @@ -22,6 +23,12 @@ const missing = (component: string) => /** The site URL that the fake deployment gives its functions in `CONVEX_SITE_URL`. */ const SITE_URL = "https://happy-cat-123.convex.site"; +/** The fake deployment's `CONVEX_CLOUD_URL`, the origin of its storage URLs. */ +const CLOUD_URL = "https://happy-cat-123.convex.cloud"; + +/** The storage URL that the fake deployment gives a stored file. */ +const fileUrl = (storageId: string) => `${CLOUD_URL}/api/storage/${storageId}?component=c1`; + /** An app directory with `convex/` and the given files. */ function app(files: Record) { const cwd = mkdtempSync(join(tmpdir(), "convex-hosting-cli-")); @@ -33,19 +40,25 @@ function app(files: Record) { return cwd; } -/** What a `npx convex run` call is: the probe, the site URL query, or a function's name. */ +/** + * What a `npx convex run` call is: the probe, the site URL query, the storage URL query, or a + * function's name. + */ const callName = (args: string[]) => args.includes("process.env.CONVEX_SITE_URL") ? "site url" - : args.includes("--inline-query") - ? "probe" - : args[3]; + : args.some((arg) => arg.includes("ctx.storage.getUrl")) + ? "urls" + : args.includes("--inline-query") + ? "probe" + : args[3]; /** * A fake `Cli`: `npx convex run` answers like a deployment with the component, the build calls - * `build`, and `npx convex deploy` or `npx convex run --push` calls `push`. No processes, no - * network. `events` lists the builds, the probes, the site URL queries, the function calls, and the - * pushes in order. + * `build`, `npx convex deploy` or `npx convex run --push` calls `push`, and the site answers the + * mark request with `mark`. No processes, no network. `events` lists the builds, the probes, the + * site URL queries, the storage URL queries, the function calls, the pushes, and the marks in + * order. */ function fake( cwd: string, @@ -58,6 +71,8 @@ function fake( failing?: Record; build?: () => Promise; push?: (cli: Cli, args: string[]) => Promise; + /** The site's answer to the mark request; by default it marks the version of the file. */ + mark?: (token: string | null, init: RequestInit | undefined) => Promise; } = {}, ) { const runs: string[][] = []; @@ -65,6 +80,8 @@ function fake( const builds: string[] = []; const events: string[] = []; const stored = new Map(); + /** The entries that `recordFiles` recorded, by version. */ + const recorded = new Map(); const logs: string[] = []; const ok = (value: unknown) => ({ exitCode: 0, @@ -80,6 +97,19 @@ function fake( events.push("site url"); return ok(SITE_URL); } + if (callName(args) === "urls") { + events.push("urls"); + const code = args[args.indexOf("--inline-query") + 1]; + const [, versionId, after] = + /q\.eq\("versionId", ("[^"]*")\)\.gt\("path", ("[^"]*")\)/.exec(code) ?? []; + const take = Number(/\.take\((\d+)\)/.exec(code)?.[1]); + const files = (recorded.get(JSON.parse(versionId)) ?? []) + .filter(({ path }) => path > JSON.parse(after)) + .sort((a, b) => (a.path < b.path ? -1 : 1)) + .slice(0, take) + .map(({ path, storageId }) => [path, fileUrl(storageId)]); + return ok({ cloudUrl: CLOUD_URL, files }); + } if (args.includes("--inline-query")) { events.push("probe"); return (options.installed?.() ?? true) @@ -91,6 +121,12 @@ function fake( if (failure !== undefined) return { exitCode: 1, stdout: "", stderr: failure }; const fnArgs = JSON.parse(args[4]); switch (args[3]) { + case "lib:recordFiles": + recorded.set(fnArgs.versionId, [ + ...(recorded.get(fnArgs.versionId) ?? []), + ...fnArgs.entries, + ]); + return ok(null); case "lib:generateUploadUrls": return ok(Array.from({ length: fnArgs.count }, (_, i) => `https://upload/${i}`)); case "lib:knownFiles": @@ -114,7 +150,16 @@ function fake( events.push("build"); return (await options.build?.()) ?? 0; }, - fetch: async (_url, init) => { + fetch: async (url, init) => { + if (url === SITE_URL + MARK_PATH) { + events.push("mark"); + const token = new Headers(init?.headers).get(MARK_HEADER); + if (options.mark !== undefined) return await options.mark(token, init); + const assets = writtenAssets(cwd); + return token === assets.markToken + ? Response.json({ versionId: assets.versionId, result: "marked" }) + : new Response("

Home

"); + } const storageId = `storage-${stored.size}`; stored.set(storageId, await new Response(init?.body).text()); return Response.json({ storageId }); @@ -138,7 +183,14 @@ function innerUpload(cli: Cli, args: string[]) { } const versionFile = (cwd: string) => readFileSync(join(cwd, VERSION_FILE), "utf8"); -const writtenVersionId = (cwd: string) => /"([^"]+)"/.exec(versionFile(cwd))?.[1]; +const writtenVersionId = (cwd: string) => writtenAssets(cwd).versionId; +/** The assets of the version file, as `convex/http.ts` imports them. */ +function writtenAssets(cwd: string): Assets { + const line = versionFile(cwd) + .split("\n") + .find((text) => text.startsWith("export const assets = ")); + return JSON.parse(line?.slice("export const assets = ".length, -1) ?? "null"); +} const site = { "dist/index.html": "

Home

", @@ -171,7 +223,7 @@ describe("help", () => { }); describe("deploy --dev", () => { - test("builds, uploads, writes the version file, pushes with npx convex run --push, and reports the site URL", async () => { + test("builds, uploads, writes the version file, pushes with npx convex run --push, marks, and reports the site URL", async () => { const cwd = app(site); let pushedVersionId: string | undefined; const { cli, events, builds, pushes, runs, logs } = fake(cwd, { @@ -193,8 +245,10 @@ describe("deploy --dev", () => { "lib:generateUploadUrls", "lib:recordFiles", "lib:finishVersion", + "urls", "push: run", "site url", + "mark", ]); // An inline query at the app's root, which exists before a first install. expect(pushes).toEqual([["run", "--push", "--inline-query", "null"]]); @@ -205,13 +259,14 @@ describe("deploy --dev", () => { expect(logs[logs.length - 1]).toBe(`Deployed version ${versionId} to ${SITE_URL}.`); }); - test("on a first install, writes the version file, pushes, then uploads", async () => { + test("on a first install, pushes a site without files, uploads, then pushes the site", async () => { const cwd = app(site); let pushed = false; + const pushedFiles: boolean[] = []; const { cli, events, callArgs } = fake(cwd, { installed: () => pushed, push: async () => { - expect(existsSync(join(cwd, VERSION_FILE))).toBe(true); + pushedFiles.push(writtenAssets(cwd).files !== null); pushed = true; return 0; }, @@ -224,7 +279,14 @@ describe("deploy --dev", () => { "probe", "lib:generateUploadUrls", ]); - expect(events.slice(-2)).toEqual(["lib:finishVersion", "site url"]); + expect(events.slice(-5)).toEqual([ + "lib:finishVersion", + "urls", + "push: run", + "site url", + "mark", + ]); + expect(pushedFiles).toEqual([false, true]); expect(existsSync(join(cwd, ".convex-hosting", "first-install"))).toBe(false); expect(callArgs("lib:createVersion")[0].versionId).toBe(writtenVersionId(cwd)); }); @@ -330,6 +392,80 @@ describe("deploy reports", () => { ); }); + test("the mark carries the site's token, so only the code of this deploy marks", async () => { + const tokens: (string | null)[] = []; + const cwd = app(site); + const { cli, logs } = fake(cwd, { + push: innerUpload, + mark: async (token) => { + tokens.push(token); + return Response.json({ versionId: writtenAssets(cwd).versionId, result: "marked" }); + }, + }); + expect(await main(DEPLOY, cli)).toBe(0); + expect(tokens).toEqual([writtenAssets(cwd).markToken]); + expect(logs[logs.length - 1]).toMatch(/^Deployed version /); + }); + + test("a mark that fails or reaches other code is reported, and the deploy succeeds", async () => { + const answers: Record Promise> = { + "failed: fetch failed": async () => { + throw new TypeError("fetch failed"); + }, + "did not answer as version": async () => new Response("

Home

"), + }; + for (const [message, answer] of Object.entries(answers)) { + const { cli, logs } = fake(app(site), { push: innerUpload, mark: answer }); + expect(await main(DEPLOY, cli)).toBe(0); + expect(logs.some((line) => line.includes(message))).toBe(true); + expect(logs[logs.length - 1]).toMatch(/^Deployed version /); + } + }); + + test("the mark follows no redirect, which would carry the token to another origin", async () => { + const redirects: (RequestRedirect | undefined)[] = []; + const { cli, logs } = fake(app(site), { + push: innerUpload, + mark: async (_token, init) => { + redirects.push(init?.redirect); + return new Response(null, { status: 307, headers: { Location: "https://other.example/" } }); + }, + }); + expect(await main(DEPLOY, cli)).toBe(0); + expect(redirects).toEqual(["manual"]); + expect(logs.some((line) => line.includes("did not answer as version"))).toBe(true); + }); + + test("a mark refused because a newer version is live says that deploys overlapped", async () => { + const cwd = app(site); + const { cli, logs } = fake(cwd, { + push: innerUpload, + mark: async () => + Response.json({ versionId: writtenAssets(cwd).versionId, result: "superseded" }), + }); + expect(await main(DEPLOY, cli)).toBe(0); + expect(logs.some((line) => line.includes("a deploy overlapped this one"))).toBe(true); + }); + + test("a stored file that is gone before the version file is written fails the upload", async () => { + const cwd = app(site); + const { cli, logs } = fake(cwd); + const convex = cli.convex; + cli.convex = async (args) => + callName(args) === "urls" + ? { + exitCode: 0, + stdout: JSON.stringify({ cloudUrl: CLOUD_URL, files: [["/index.html", null]] }), + stderr: "", + } + : convex(args); + expect(await main(["upload", "--dist", "dist", "--version-id", "v1"], cli)).toBe(1); + expect(logs[logs.length - 1]).toBe( + "The stored file of /index.html is gone, deleted by the age rule; run the deploy again.", + ); + expect(existsSync(join(cwd, VERSION_FILE))).toBe(false); + }); + test("a failed upload names the file", async () => { const { cli, logs } = fake(app(site)); // The config, a string, stores; the files, bytes, do not. @@ -350,7 +486,7 @@ describe("deploy without --build", () => { expect(await main(["deploy", "--dev", "--dist", "dist"], cli)).toBe(0); expect(builds).toEqual([]); expect(events[0]).toBe("probe"); - expect(events.slice(-2)).toEqual(["push: run", "site url"]); + expect(events.slice(-3)).toEqual(["push: run", "site url", "mark"]); }); test("production runs only the upload inside npx convex deploy --cmd", async () => { @@ -358,7 +494,7 @@ describe("deploy without --build", () => { expect(await main(["deploy", "--dist", "dist"], cli)).toBe(0); expect(pushes[0][2]).toMatch(/^'.+' '.+' 'upload' '--dist' 'dist' '--version-id' '/); expect(events[0]).toBe("push: deploy"); - expect(events.slice(-2)).toEqual(["lib:finishVersion", "site url"]); + expect(events.slice(-4)).toEqual(["lib:finishVersion", "urls", "site url", "mark"]); }); }); @@ -377,29 +513,37 @@ describe("deploy", () => { // `npx convex deploy` goes to production by default and has no --prod flag; every run gets it. expect(pushes[0]).not.toContain("--prod"); expect(runs.every((args) => args.includes("--prod"))).toBe(true); - // The upload runs inside the push, and only the site URL query runs after it. + // The upload runs inside the push; after it, the site URL query and the mark. expect(events[0]).toBe("push: deploy"); - expect(events.slice(-2)).toEqual(["lib:finishVersion", "site url"]); + expect(events.slice(-4)).toEqual(["lib:finishVersion", "urls", "site url", "mark"]); expect(callArgs("lib:createVersion")[0].versionId).toBe(writtenVersionId(cwd)); }); - test("on a first install, uploads after the push", async () => { + test("on a first install, uploads after the push, then pushes again", async () => { const cwd = app(site); let pushed = false; - const { cli, calls } = fake(cwd, { + const pushedFiles: boolean[] = []; + const { cli, calls, pushes } = fake(cwd, { installed: () => pushed, push: async (cli, args) => { - const exitCode = await innerUpload(cli, args); - expect(existsSync(join(cwd, ".convex-hosting", "first-install"))).toBe(true); - expect(existsSync(join(cwd, VERSION_FILE))).toBe(true); - pushed = true; - return exitCode; + if (args.includes("--cmd")) { + const exitCode = await innerUpload(cli, args); + expect(existsSync(join(cwd, ".convex-hosting", "first-install"))).toBe(true); + pushedFiles.push(writtenAssets(cwd).files !== null); + pushed = true; + return exitCode; + } + pushedFiles.push(writtenAssets(cwd).files !== null); + return 0; }, }); expect(await main(DEPLOY, cli)).toBe(0); expect(calls().slice(0, 3)).toEqual(["probe", "probe", "lib:generateUploadUrls"]); - expect(calls().slice(-2)).toEqual(["lib:finishVersion", "site url"]); + expect(calls().slice(-3)).toEqual(["lib:finishVersion", "urls", "site url"]); + expect(pushes.map((args) => args[0])).toEqual(["deploy", "deploy"]); + expect(pushes[1]).toEqual(["deploy"]); + expect(pushedFiles).toEqual([false, true]); expect(existsSync(join(cwd, ".convex-hosting", "first-install"))).toBe(false); }); @@ -411,7 +555,7 @@ describe("deploy", () => { }, }); expect(await main(DEPLOY, cli)).toBe(1); - expect(events[events.length - 1]).toBe("lib:finishVersion"); + expect(events[events.length - 1]).toBe("urls"); expect(logs[logs.length - 1]).toBe("npx convex deploy failed with exit code 1."); }); @@ -484,6 +628,7 @@ describe("upload", () => { "lib:generateUploadUrls", "lib:recordFiles", "lib:finishVersion", + "urls", ]); // Inside `npx convex deploy` to production, every run gets --prod. expect(runs.every((args) => args.includes("--prod"))).toBe(true); @@ -521,10 +666,57 @@ describe("upload", () => { home.storageId, ); - expect(versionFile(cwd)).toBe('export const versionId = "v1";\n'); + // tsc reads the file itself in an app whose convex/tsconfig.json sets allowJs. + expect(versionFile(cwd).split("\n")[0]).toBe( + '/** @type {import("@samebase/convex-hosting").Assets} */', + ); + const written = writtenAssets(cwd); + expect(written).toMatchObject({ format: 1, versionId: "v1", markToken: expect.any(String) }); + const files = written.files; + if (files === null) throw new Error("The version file has no files."); + expect(files.cloudUrl).toBe(CLOUD_URL); + expect(files.config).toMatchObject({ + compatibility_date: "2025-04-01", + html_handling: "auto-trailing-slash", + not_found_handling: "single-page-application", + }); + expect(files.contentTypes).toEqual([ + "text/html; charset=utf-8", + "text/javascript; charset=utf-8", + ]); + // Every path finds its stored file and its type; the two copies share one stored file and ETag. + const contentType = "text/html; charset=utf-8"; + const lookup = manifestLookup(files); + const found = await lookup("/copy.html"); + expect(found).toEqual({ + eTag: createHash("sha256") + .update(`${home.sha256}\n${contentType}`) + .digest("hex") + .slice(0, 32), + url: fileUrl(home.storageId), + contentType, + }); + expect(await lookup("/index.html")).toEqual(found); + expect(await lookup("/private/notes.txt")).toBeNull(); expect(readFileSync(join(cwd, ".convex-hosting", ".gitignore"), "utf8")).toBe("*\n"); }); + test("reads the storage URLs a page at a time, and every path finds its stored file", async () => { + const files = Object.fromEntries( + Array.from({ length: 2500 }, (_, i) => [`dist/assets/${i}.js`, `console.log(${i})`]), + ); + const cwd = app(files); + const { cli, calls } = fake(cwd); + expect(await main(upload(), cli)).toBe(0); + expect(calls().filter((name) => name === "urls")).toHaveLength(2); + const written = writtenAssets(cwd).files; + if (written === null) throw new Error("The version file has no files."); + const lookup = manifestLookup(written); + for (const i of [0, 1999, 2000, 2499]) { + expect(await lookup(`/assets/${i}.js`)).not.toBeNull(); + } + }); + test("does not upload the files that knownFiles knows, and records them with their stored file", async () => { const home = createHash("sha256").update("

Home

").digest("hex"); const { cli, calls, callArgs } = fake(app(site), { known: { [home]: "known-home" } }); diff --git a/packages/convex-hosting/src/cli/main.ts b/packages/convex-hosting/src/cli/main.ts index d407cb01..b78cff83 100644 --- a/packages/convex-hosting/src/cli/main.ts +++ b/packages/convex-hosting/src/cli/main.ts @@ -4,6 +4,7 @@ import { existsSync, mkdirSync, readFileSync, + renameSync, rmSync, writeFileSync, } from "node:fs"; @@ -11,7 +12,15 @@ import { join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; import { parseArgs } from "node:util"; import { z } from "zod"; +import { + ASSETS_FORMAT, + MARK_HEADER, + MARK_PATH, + type AssetFiles, + type Assets, +} from "../client/manifest.js"; import { internal } from "../component/_generated/api.js"; +import type { Config } from "../component/lib.js"; import type { Id } from "../component/_generated/dataModel.js"; import { AssetConfigSchema } from "../workers-sdk/packages/workers-shared/utils/types.js"; import { @@ -19,12 +28,15 @@ import { probeComponent, readConvexEnv, runComponent, + runComponentQuery, siteUrl, type Cli, type Destination, type Target, } from "./convex.js"; import { readDist, type DistEntry, type HandlingOptions } from "./files.js"; +import { buildAssetFiles } from "./manifest.js"; +import { siteConfig } from "./site-config.js"; const USAGE = `Usage: convex-hosting deploy --dist [options] @@ -57,6 +69,12 @@ export const VERSION_FILE = join(STATE_DIR, "version.js"); */ const FIRST_INSTALL_MARKER = join(STATE_DIR, "first-install"); +/** + * Entries per inline query that reads the storage URLs: 2,000 entries and their `_storage` + * documents are 4,000 of the 32,000 documents a query may read, and about 300 KB of result. + */ +const URL_PAGE = 2000; + /** Files that the upload sends to storage at once. */ const UPLOAD_CONCURRENCY = 4; @@ -167,9 +185,9 @@ function quote(arg: string): string { } /** - * Builds, uploads, writes the version file, and pushes. The push is the switch: the first request - * that the new code serves marks its version live. Then it reports the site URL, for a person and, - * through `$GITHUB_OUTPUT`, for the next step of a GitHub Actions job. + * Builds, uploads, writes the version file, and pushes. The push is the switch. Then it asks the + * served code to mark its version live, and reports the site URL, for a person and, through + * `$GITHUB_OUTPUT`, for the next step of a GitHub Actions job. */ async function deploy(cli: Cli, options: Options, build: string | undefined) { // A deploy key wins over every selector in the Convex CLI, so a production key in the environment @@ -226,6 +244,7 @@ async function deploy(cli: Cli, options: Options, build: string | undefined) { const message = error instanceof Error ? error.message : String(error); throw new Error(`Deployed version ${versionId}, but reading the site URL failed: ${message}`); } + await markServedVersion(cli, url, readVersionFile(cli)); cli.log(`Deployed version ${versionId} to ${url}.`); if (cli.env.GITHUB_OUTPUT) appendFileSync(cli.env.GITHUB_OUTPUT, `url=${url}\n`); } @@ -236,7 +255,7 @@ async function deploy(cli: Cli, options: Options, build: string | undefined) { * reads `VITE_CONVEX_URL`). Then the upload runs here, and `npx convex run --push` pushes, with an inline * query at the app's root, which exists before the push installs the component. It works whether * or not `npx convex dev` runs; `npx convex dev --once` refuses while it runs a local deployment's - * backend. + * backend. A first install pushes, uploads, and pushes again. */ async function deployDev( cli: Cli, @@ -251,12 +270,22 @@ async function deployDev( } const missing = await upload(cli, options, target, versionId); if (missing !== undefined) cli.log(notInstalledYet(options.component)); + await pushDev(cli); + if (missing !== undefined) { + await uploadAfterPush(cli, options, target, versionId); + await pushDev(cli); + } +} + +async function pushDev(cli: Cli) { const exitCode = await cli.convexInherited(["run", "--push", "--inline-query", "null"]); if (exitCode !== 0) throw new Error(`npx convex run --push failed with exit code ${exitCode}.`); - if (missing !== undefined) await uploadAfterPush(cli, options, target, versionId); } -/** Production or a preview: the build, if any, and the upload run inside `npx convex deploy --cmd`. */ +/** + * Production or a preview: the build, if any, and the upload run inside `npx convex deploy --cmd`. + * A first install uploads after that push and pushes again with `npx convex deploy`. + */ async function deployWithConvexDeploy( cli: Cli, options: Options, @@ -299,7 +328,11 @@ async function deployWithConvexDeploy( const firstInstall = existsSync(marker); rmSync(marker, { force: true }); if (exitCode !== 0) throw new Error(`npx convex deploy failed with exit code ${exitCode}.`); - if (firstInstall) await uploadAfterPush(cli, options, target, versionId); + if (firstInstall) { + await uploadAfterPush(cli, options, target, versionId); + const again = await cli.convexInherited(["deploy", ...deployFlags]); + if (again !== 0) throw new Error(`npx convex deploy failed with exit code ${again}.`); + } } /** The upload inside `npx convex deploy --cmd`. On a first install, `deploy` uploads after the push. */ @@ -315,7 +348,7 @@ async function uploadInsideDeploy(cli: Cli, options: Options, versionId: string) } function notInstalledYet(component: string) { - return `The component "${component}" is not installed yet. The push installs it, and the upload runs after the push.`; + return `The component "${component}" is not installed yet. The push installs it, the upload runs after the push, and a second push serves the site.`; } /** The upload of a first install, after the push. The probe's output shows a mistyped `--component`. */ @@ -330,9 +363,9 @@ async function uploadAfterPush(cli: Cli, options: Options, target: Target, versi } /** - * Uploads `--dist` as version `versionId` and writes the version file. When the component is not - * installed yet, it writes only the version file, so that the push that follows installs the - * component, and returns the probe's output. + * Uploads `--dist` as version `versionId` and writes the version file with the site's files. When + * the component is not installed yet, it writes a version file without files, which serves + * nothing, so that the push that follows installs the component, and returns the probe's output. */ async function upload( cli: Cli, @@ -351,9 +384,11 @@ async function upload( z.array(z.string()).length(count), ); + // The CLI sends it after the push; see `MARK_HEADER`. + const markToken = randomUUID(); const missing = await probeComponent(cli, target); if (missing !== undefined) { - writeVersionFile(cli, versionId); + writeVersionFile(cli, { format: ASSETS_FORMAT, versionId, markToken, files: null }); return missing; } @@ -442,23 +477,146 @@ async function upload( await record(uploaded); } await runComponent(cli, target, internal.lib.finishVersion, { versionId }, z.null()); - writeVersionFile(cli, versionId); + const files = await assetFiles(cli, target, versionId, config, entries); + writeVersionFile(cli, { format: ASSETS_FORMAT, versionId, markToken, files }); cli.log(`Uploaded version ${versionId} and wrote ${VERSION_FILE}.`); return undefined; } -function writeVersionFile(cli: Cli, versionId: string) { - writeStateFile(cli, VERSION_FILE, `export const versionId = ${JSON.stringify(versionId)};\n`); +/** + * The files of the site that serving reads: the storage URL of each entry, which only the + * component can make, read with inline queries in the component, which work whatever release of + * this package its functions are, and the deployment's `CONVEX_CLOUD_URL`, their origin. + */ +async function assetFiles( + cli: Cli, + target: Target, + versionId: string, + config: Config, + entries: DistEntry[], +): Promise { + const urls = new Map(); + let cloudUrl = ""; + let after = ""; + for (;;) { + const page = await runComponentQuery( + cli, + target, + `const rows = await ctx.db.query("entries").withIndex("by_version_path", (q) => ` + + `q.eq("versionId", ${JSON.stringify(versionId)}).gt("path", ${JSON.stringify(after)}))` + + `.take(${URL_PAGE}); return { cloudUrl: process.env.CONVEX_CLOUD_URL, files: await ` + + `Promise.all(rows.map(async (row) => [row.path, await ctx.storage.getUrl(row.storageId)])) };`, + z.object({ + cloudUrl: z.string(), + files: z.array(z.tuple([z.string(), z.string().nullable()])), + }), + ); + cloudUrl = page.cloudUrl; + for (const [path, url] of page.files) { + if (url === null) { + throw new Error( + `The stored file of ${path} is gone, deleted by the age rule; run the deploy again.`, + ); + } + urls.set(path, url); + } + if (page.files.length < URL_PAGE) break; + after = page.files[page.files.length - 1][0]; + } + return buildAssetFiles( + cloudUrl, + siteConfig(config), + entries.map(({ path, sha256, contentType }) => { + const url = urls.get(path); + if (url === undefined) throw new Error(`Version ${versionId} has no entry for ${path}.`); + return { path, sha256, contentType, url }; + }), + ); } -/** Writes a file of the state folder, and the folder's `.gitignore` when it is absent. */ +/** The line of the version file that holds the assets. */ +const ASSETS_LINE = "export const assets = "; + +/** + * Writes the version file. The assets carry their type as JSDoc: Convex's default + * `convex/tsconfig.json` sets `allowJs`, so tsc reads this file instead of the package's + * declaration, and would infer `string` where `Assets` has a union of literals. + */ +function writeVersionFile(cli: Cli, assets: Assets) { + writeStateFile( + cli, + VERSION_FILE, + `/** @type {import("@samebase/convex-hosting").Assets} */\n` + + `${ASSETS_LINE}${JSON.stringify(assets)};\n`, + ); +} + +/** The id and the mark token of the assets in the version file that the upload wrote. */ +function readVersionFile(cli: Cli): Pick { + const line = readFileSync(join(cli.cwd, VERSION_FILE), "utf8") + .split("\n") + .find((text) => text.startsWith(ASSETS_LINE)); + if (line === undefined) throw new Error(`${VERSION_FILE} has no assets.`); + return z + .object({ versionId: z.string(), markToken: z.string() }) + .parse(JSON.parse(line.slice(ASSETS_LINE.length, -1))); +} + +/** + * Asks the code that the deployment serves to mark its version live, with the site's mark token, + * which only the code of this deploy has. A failure deletes nothing: the versions live before stay + * until a later deploy marks its own, so it is reported, and the deploy succeeds. + */ +async function markServedVersion( + cli: Cli, + url: string, + site: Pick, +) { + const later = `Version ${site.versionId} serves, and the next deploy deletes the files of the versions before it.`; + let answer: unknown; + try { + // A redirect would carry the token to another origin, so it counts as other code answering. + const response = await cli.fetch(url + MARK_PATH, { + method: "POST", + headers: { [MARK_HEADER]: site.markToken }, + redirect: "manual", + }); + // Other code answers the path with a page or a 404, which is no mark. + answer = response.ok ? await response.json().catch(() => null) : null; + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + cli.log(`Asking the site to mark version ${site.versionId} live failed: ${message}. ${later}`); + return; + } + const parsed = z.object({ versionId: z.string(), result: z.string() }).safeParse(answer); + if (!parsed.success || parsed.data.versionId !== site.versionId) { + cli.log( + `The site did not answer as version ${site.versionId}, so its code is not this deploy's.`, + ); + return; + } + const { result } = parsed.data; + if (result === "superseded") { + cli.log( + `Another version went live over ${site.versionId}, so a deploy overlapped this one; ${later}`, + ); + } else if (result !== "marked" && result !== "live") { + cli.log(`Version ${site.versionId} could not be marked live: it is ${result}.`); + } +} + +/** + * Writes a file of the state folder, and the folder's `.gitignore` when it is absent. It writes a + * temporary file and renames it, so a running `npx convex dev` never reads half a file. + */ function writeStateFile(cli: Cli, path: string, body: string) { const gitignore = join(cli.cwd, STATE_DIR, ".gitignore"); if (!existsSync(gitignore)) { mkdirSync(join(cli.cwd, STATE_DIR), { recursive: true }); writeFileSync(gitignore, "*\n"); } - writeFileSync(join(cli.cwd, path), body); + writeFileSync(join(cli.cwd, `${path}.tmp`), body); + renameSync(join(cli.cwd, `${path}.tmp`), join(cli.cwd, path)); } /** Stores one file through an upload URL and returns its storage id; `what` names it in errors. */ diff --git a/packages/convex-hosting/src/cli/manifest.test.ts b/packages/convex-hosting/src/cli/manifest.test.ts new file mode 100644 index 00000000..aec782aa --- /dev/null +++ b/packages/convex-hosting/src/cli/manifest.test.ts @@ -0,0 +1,83 @@ +import { createHash } from "node:crypto"; +import fc from "fast-check"; +import { describe, expect, test } from "vite-plus/test"; +import { manifestLookup } from "../client/manifest.js"; +import { buildAssetFiles, type AssetEntry } from "./manifest.js"; +import { siteConfig } from "./site-config.js"; + +const CLOUD_URL = "https://happy-cat-123.convex.cloud"; +const config = siteConfig({}); +const sha256Hex = (text: string) => createHash("sha256").update(text).digest("hex"); +const url = (key: string) => + `${CLOUD_URL}/api/storage/${key}?component=m026ambq8g7g5yxf42tb4d4tfx8hg303`; + +/** What the lookup finds for an entry. */ +const hit = (entry: AssetEntry) => ({ + eTag: sha256Hex(`${entry.sha256}\n${entry.contentType ?? ""}`).slice(0, 32), + url: entry.url, + contentType: entry.contentType, +}); + +/** A file of any path, Unicode included, whose storage key has any length. */ +const anyEntry = fc.record({ + path: fc.string({ unit: "grapheme" }).map((path) => `/${path}`), + sha256: fc.uint8Array({ minLength: 32, maxLength: 32 }).map((bytes) => { + return Buffer.from(bytes).toString("hex"); + }), + contentType: fc.option(fc.constantFrom("text/html; charset=utf-8", "text/css", "image/png"), { + nil: undefined, + }), + url: fc.stringMatching(/^[0-9a-z-]{1,40}$/).map(url), +}); + +describe("buildAssetFiles, read with Cloudflare's lookup", () => { + test("every path of any site finds its own entry, and any other path finds none", async () => { + await fc.assert( + fc.asyncProperty( + fc.uniqueArray(anyEntry, { selector: ({ path }) => path, maxLength: 40 }), + fc.string({ unit: "grapheme" }).map((path) => `/${path}`), + async (entries, other) => { + const lookup = manifestLookup(buildAssetFiles(CLOUD_URL, config, entries)); + for (const entry of entries) expect(await lookup(entry.path)).toEqual(hit(entry)); + if (entries.every(({ path }) => path !== other)) expect(await lookup(other)).toBeNull(); + }, + ), + ); + }); + + test("5,000 entries: every path finds its entry", async () => { + // Every third entry shares the bytes of the one before, and every fifth has no type. + const entries = Array.from({ length: 5000 }, (_, i) => { + const sha256 = sha256Hex(`body ${i - (i % 3 === 2 ? 1 : 0)}`); + const contentType = i % 5 === 4 ? undefined : i % 2 === 0 ? "text/javascript" : "text/html"; + return { path: `/assets/chunk-${i}.js`, sha256, contentType, url: url(sha256.slice(0, 36)) }; + }); + const lookup = manifestLookup(buildAssetFiles(CLOUD_URL, config, entries)); + for (const entry of entries) expect(await lookup(entry.path)).toEqual(hit(entry)); + expect(await lookup("/assets/missing.js")).toBeNull(); + }); + + test("a path is found as the handler decodes it, not percent-encoded", async () => { + const entry = { path: "/café/menu.html", sha256: sha256Hex("menu"), contentType: undefined }; + const lookup = manifestLookup( + buildAssetFiles(CLOUD_URL, config, [{ ...entry, url: url("k") }]), + ); + expect(await lookup("/café/menu.html")).not.toBeNull(); + expect(await lookup("/caf%C3%A9/menu.html")).toBeNull(); + }); + + test("the storage URLs are written as what they share and one string of keys", () => { + const entries = ["0c1f6a52", "5b7d2e11", "9e4a7c30"].map((key, i) => ({ + path: `/${i}.js`, + sha256: sha256Hex(key), + contentType: undefined, + url: url(key), + })); + expect(buildAssetFiles(CLOUD_URL, config, entries)).toMatchObject({ + urlPrefix: `${CLOUD_URL}/api/storage/`, + urlSuffix: "?component=m026ambq8g7g5yxf42tb4d4tfx8hg303", + urlKeys: "0c1f6a525b7d2e119e4a7c30", + urlKeyWidth: 8, + }); + }); +}); diff --git a/packages/convex-hosting/src/cli/manifest.ts b/packages/convex-hosting/src/cli/manifest.ts new file mode 100644 index 00000000..fb6a2866 --- /dev/null +++ b/packages/convex-hosting/src/cli/manifest.ts @@ -0,0 +1,113 @@ +import { createHash } from "node:crypto"; +import type { NormalizedAssetConfig } from "../workers-sdk/packages/workers-shared/asset-worker/src/types.js"; +import { + CONTENT_HASH_OFFSET, + CONTENT_HASH_SIZE, + ENTRY_SIZE, + HEADER_SIZE, + PATH_HASH_OFFSET, + PATH_HASH_SIZE, +} from "../workers-sdk/packages/workers-shared/utils/constants.js"; +import { + NO_CONTENT_TYPE, + TAIL_CONTENT_TYPE, + TAIL_URL, + type AssetFiles, +} from "../client/manifest.js"; + +/** One file of a version, as the upload knows it. */ +export type AssetEntry = { + /** The URL path, such as `/assets/index-a1b2.js`. */ + path: string; + /** The hex SHA-256 of the bytes. */ + sha256: string; + contentType: string | undefined; + url: string; +}; + +const sha256 = (text: string) => createHash("sha256").update(text).digest(); + +/** + * Builds the files that serving reads. The manifest is encoded as Miniflare encodes it for + * `wrangler dev`: a 20-byte header, then one 40-byte entry per path, sorted by the path hash. The + * content hash covers the bytes and the content type, as Cloudflare's covers the bytes and the + * extension, so the same bytes under two types are two entries with two ETags. The storage URLs + * differ only in a key, so what they share is written once. + */ +export function buildAssetFiles( + cloudUrl: string, + config: NormalizedAssetConfig, + entries: AssetEntry[], +): AssetFiles { + // Sorted, so the same files write the same version file. + const urls = [...new Set(entries.map(({ url }) => url))].sort(); + const contentTypes = [ + ...new Set( + entries.flatMap(({ contentType }) => (contentType === undefined ? [] : [contentType])), + ), + ].sort(); + const urlIndex = new Map(urls.map((url, index) => [url, index])); + const urlPrefix = sharedStart(urls); + const urlSuffix = sharedEnd(urls.map((url) => url.slice(urlPrefix.length))); + const keys = urls.map((url) => url.slice(urlPrefix.length, url.length - urlSuffix.length)); + const urlKeyWidth = keys.reduce((width, key) => Math.max(width, key.length), 0); + const contentTypeIndex = new Map(contentTypes.map((type, index) => [type, index])); + + const sorted = entries + .map((entry) => ({ entry, pathHash: sha256(entry.path).subarray(0, PATH_HASH_SIZE) })) + .sort((a, b) => Buffer.compare(a.pathHash, b.pathHash)); + const manifest = Buffer.alloc(HEADER_SIZE + sorted.length * ENTRY_SIZE); + sorted.forEach(({ entry, pathHash }, i) => { + const offset = HEADER_SIZE + i * ENTRY_SIZE; + pathHash.copy(manifest, offset + PATH_HASH_OFFSET); + sha256(`${entry.sha256}\n${entry.contentType ?? ""}`).copy( + manifest, + offset + CONTENT_HASH_OFFSET, + 0, + CONTENT_HASH_SIZE, + ); + const tail = offset + CONTENT_HASH_OFFSET + CONTENT_HASH_SIZE; + manifest.writeUInt32BE(urlIndex.get(entry.url) ?? 0, tail + TAIL_URL); + manifest.writeUInt16BE( + entry.contentType === undefined + ? NO_CONTENT_TYPE + : (contentTypeIndex.get(entry.contentType) ?? 0), + tail + TAIL_CONTENT_TYPE, + ); + }); + return { + cloudUrl, + config, + manifest: manifest.toString("base64"), + contentTypes, + urlPrefix, + urlSuffix, + urlKeys: keys.map((key) => key.padEnd(urlKeyWidth)).join(""), + urlKeyWidth, + }; +} + +function sharedStart(texts: string[]): string { + let start = texts[0] ?? ""; + for (const text of texts) { + let length = 0; + while (length < start.length && start[length] === text[length]) length++; + start = start.slice(0, length); + } + return start; +} + +function sharedEnd(texts: string[]): string { + let end = texts[0] ?? ""; + for (const text of texts) { + let length = 0; + while ( + length < Math.min(end.length, text.length) && + end[end.length - 1 - length] === text[text.length - 1 - length] + ) { + length++; + } + end = end.slice(end.length - length); + } + return end; +} diff --git a/packages/convex-hosting/src/cli/site-config.ts b/packages/convex-hosting/src/cli/site-config.ts new file mode 100644 index 00000000..aa69a0ce --- /dev/null +++ b/packages/convex-hosting/src/cli/site-config.ts @@ -0,0 +1,17 @@ +import type { Config } from "../component/lib.js"; +import { normalizeConfiguration } from "../workers-sdk/packages/workers-shared/asset-worker/src/configuration.js"; +import { AssetConfigSchema } from "../workers-sdk/packages/workers-shared/utils/types.js"; + +/** + * The compatibility date of Cloudflare's handler. From 2025-04-01 on, Cloudflare applies + * `not_found_handling` to a request with `Sec-Fetch-Mode: navigate` when a Worker exists. + */ +const COMPATIBILITY_DATE = "2025-04-01"; + +/** A version's config as Cloudflare's handler takes it, which the site carries. */ +export function siteConfig(config: Config) { + return normalizeConfiguration({ + ...AssetConfigSchema.parse(config), + compatibility_date: COMPATIBILITY_DATE, + }); +} diff --git a/packages/convex-hosting/src/client/answer.test.ts b/packages/convex-hosting/src/client/answer.test.ts new file mode 100644 index 00000000..c9b843a5 --- /dev/null +++ b/packages/convex-hosting/src/client/answer.test.ts @@ -0,0 +1,237 @@ +import { describe, expect, test } from "vite-plus/test"; +import { siteConfig } from "../cli/site-config.js"; +import type { Config } from "../component/lib.js"; +import { encodingTestCases } from "../workers-sdk/fixtures/workers-shared-asset-config/test-cases/encoding-test-cases.js"; +import { htmlHandlingTestCases } from "../workers-sdk/fixtures/workers-shared-asset-config/test-cases/html-handling-test-cases.js"; +import { answer } from "./answer.js"; +import { buildAssetFiles } from "../cli/manifest.js"; +import type { AssetFiles } from "./manifest.js"; + +type Files = Record; + +const CLOUD_URL = "https://example.convex.cloud"; +const ORIGIN = "https://example.convex.site"; + +async function sha256Hex(body: string) { + const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(body)); + return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join(""); +} + +/** The ETag of `body` under `contentType`: the content hash, which covers both. */ +async function eTagOf(body: string, contentType?: string) { + return (await sha256Hex(`${await sha256Hex(body)}\n${contentType ?? ""}`)).slice(0, 32); +} + +/** The stored file's URL of `body`: it names the bytes, so a test can tell which file answered. */ +async function bodyUrl(body: string) { + return `${CLOUD_URL}/api/storage/${await sha256Hex(body)}`; +} + +/** The site's files for `files` and `config`, as the upload builds them. */ +async function siteFiles(files: Files, config: Config = {}) { + const entries = await Promise.all( + Object.entries(files).map(async ([path, { body, contentType }]) => ({ + path, + sha256: await sha256Hex(body), + contentType, + url: await bodyUrl(body), + })), + ); + return buildAssetFiles(CLOUD_URL, siteConfig(config), entries); +} + +/** Cloudflare's answer to one request, with the storage URL of its body, or `null` for a miss. */ +async function route( + files: AssetFiles, + path: string, + headers: Record = {}, + hasUserWorker = true, + method = "GET", +) { + const asset = await answer(files, new Request(ORIGIN + path, { method, headers }), hasUserWorker); + if (asset === null) return null; + return { + status: asset.status, + headers: Object.fromEntries(asset.headers), + bodyUrl: asset.url, + }; +} + +const site: Files = { + "/index.html": { body: "

Home

", contentType: "text/html; charset=utf-8" }, + "/404.html": { body: "

Missing

", contentType: "text/html; charset=utf-8" }, + "/assets/app-a1.js": { body: "console.log(1)", contentType: "text/javascript; charset=utf-8" }, +}; + +describe("answer", () => { + test("a hit has Cloudflare's headers and an ETag; If-None-Match answers 304", async () => { + const files = await siteFiles(site); + const hit = await route(files, "/assets/app-a1.js"); + expect(hit?.status).toBe(200); + expect(hit?.headers["content-type"]).toBe("text/javascript; charset=utf-8"); + expect(hit?.headers["cache-control"]).toBe("public, max-age=0, must-revalidate"); + expect(hit?.headers["cf-cache-status"]).toBeUndefined(); + const eTag = hit?.headers.etag; + expect(eTag).toBe(`"${await eTagOf("console.log(1)", "text/javascript; charset=utf-8")}"`); + expect(hit?.bodyUrl).toBe(await bodyUrl("console.log(1)")); + + const revalidated = await route(files, "/assets/app-a1.js", { "if-none-match": eTag ?? "" }); + expect(revalidated?.status).toBe(304); + expect(revalidated?.bodyUrl).toBeNull(); + }); + + test("the same bytes under two content types have two ETags", async () => { + const files = await siteFiles({ + "/a.txt": { body: "same", contentType: "text/plain" }, + "/a.js": { body: "same", contentType: "text/javascript" }, + }); + const txt = await route(files, "/a.txt"); + const js = await route(files, "/a.js"); + expect(txt?.headers.etag).not.toBe(js?.headers.etag); + expect(js?.headers["content-type"]).toBe("text/javascript"); + expect(txt?.bodyUrl).toBe(js?.bodyUrl); + }); + + test("with code, single-page-application answers navigations only", async () => { + const files = await siteFiles(site, { not_found_handling: "single-page-application" }); + const navigation = await route(files, "/settings/profile", { "sec-fetch-mode": "navigate" }); + const index = await route(files, "/"); + expect(navigation?.status).toBe(200); + expect(navigation?.headers.etag).toBe(index?.headers.etag); + expect(await route(files, "/settings/profile")).toBeNull(); + }); + + test("without code, single-page-application answers every request, as a files-only Worker", async () => { + const files = await siteFiles(site, { not_found_handling: "single-page-application" }); + const index = await route(files, "/"); + // No `Sec-Fetch-Mode`, as from curl, a monitor, or a link-preview bot. + const filesOnly = await route(files, "/about", {}, false); + expect(filesOnly?.status).toBe(200); + expect(filesOnly?.headers["content-type"]).toBe("text/html; charset=utf-8"); + expect(filesOnly?.headers.etag).toBe(index?.headers.etag); + // With code, the same request is a miss, which the app answers. + expect(await route(files, "/about", {}, true)).toBeNull(); + }); + + test("without code and with html_handling none, / answers index.html through the fallback", async () => { + const files = await siteFiles(site, { + html_handling: "none", + not_found_handling: "single-page-application", + }); + const root = await route(files, "/", {}, false); + const index = await route(files, "/index.html", {}, false); + expect(root?.status).toBe(200); + expect(root?.headers.etag).toBe(index?.headers.etag); + }); + + test("another method than GET or HEAD on a file answers 405; on a miss, the code or 404", async () => { + const files = await siteFiles(site); + for (const hasUserWorker of [true, false]) { + const post = await route(files, "/index.html", {}, hasUserWorker, "POST"); + expect(post?.status).toBe(405); + expect(post?.bodyUrl).toBeNull(); + } + expect(await route(files, "/missing", {}, true, "POST")).toBeNull(); + expect((await route(files, "/missing", {}, false, "POST"))?.status).toBe(404); + }); + + test("HEAD answers the file's headers without its body", async () => { + const files = await siteFiles(site); + const head = await route(files, "/", {}, true, "HEAD"); + expect(head?.status).toBe(200); + expect(head?.headers["content-type"]).toBe("text/html; charset=utf-8"); + expect(head?.bodyUrl).toBeNull(); + }); + + test("without code, a miss with not_found_handling none answers 404 with no-store", async () => { + const files = await siteFiles(site); + expect(await route(files, "/missing", {}, false)).toEqual({ + status: 404, + headers: { "cache-control": "no-store" }, + bodyUrl: null, + }); + }); + + test("the custom 404 page answers with its body and no-store", async () => { + const files = await siteFiles(site, { not_found_handling: "404-page" }); + const page = await route(files, "/missing", { "sec-fetch-mode": "navigate" }); + expect(page?.status).toBe(404); + expect(page?.bodyUrl).toBe(await bodyUrl("

Missing

")); + expect(page?.headers["cache-control"]).toBe("no-store"); + const filesOnly = await route(files, "/missing", {}, false); + expect(filesOnly?.status).toBe(404); + expect(filesOnly?.headers.etag).toBe(page?.headers.etag); + }); + + test("a _headers rule applies", async () => { + const files = await siteFiles(site, { + headers: { + version: 2, + rules: { "/assets/*": { set: { "Cache-Control": "public, max-age=31536000, immutable" } } }, + }, + }); + const hit = await route(files, "/assets/app-a1.js"); + expect(hit?.headers["cache-control"]).toBe("public, max-age=31536000, immutable"); + }); + + test("a _redirects rule applies", async () => { + const files = await siteFiles(site, { + redirects: { + version: 1, + staticRules: { "/old": { status: 301, to: "/", lineNumber: 1 } }, + rules: {}, + }, + }); + const redirect = await route(files, "/old?x=1"); + expect(redirect?.status).toBe(301); + expect(redirect?.headers.location).toBe("/?x=1"); + expect(redirect?.bodyUrl).toBeNull(); + }); +}); + +// Cloudflare's own cases for `html_handling` and path encoding, from +// fixtures/workers-shared-asset-config in cloudflare/workers-sdk. Upstream runs them against its +// asset Worker with `exists` mocked; here the files are a site's manifest. +describe("Cloudflare's conformance cases", () => { + /** Requests `path` and follows redirects, as the upstream test's `fetch` does. */ + async function follow(files: AssetFiles, path: string) { + let url = ORIGIN + path; + for (let hop = 0; hop < 8; hop++) { + const asset = await answer(files, new Request(url), false); + if (asset === null) throw new Error(`No asset for ${url}`); + const location = asset.headers.get("location"); + if (location !== null && asset.status >= 300 && asset.status < 400) { + url = new URL(location, url).href; + continue; + } + return { status: asset.status, url, eTag: asset.headers.get("etag"), redirected: hop > 0 }; + } + throw new Error(`Too many redirects from ${path}`); + } + + const suites = [ + { title: "html_handling", suite: htmlHandlingTestCases }, + { title: "encoding", suite: encodingTestCases }, + ]; + + describe.each(suites)("$title", ({ suite }) => { + describe.each(suite)("$html_handling", ({ html_handling, cases }) => { + test.each(cases)("$title", async ({ files, requestPath, matchedFile, finalPath }) => { + // Each file's body is its own path, so the ETag names it. + const site = await siteFiles( + Object.fromEntries(files.map((path) => [path, { body: path }])), + { html_handling, not_found_handling: "none" }, + ); + const response = await follow(site, requestPath); + if (matchedFile && finalPath) { + expect(response.status).toBe(200); + expect(response.url).toBe(ORIGIN + finalPath); + expect(response.redirected).toBe(requestPath !== finalPath); + expect(response.eTag).toBe(`"${await eTagOf(matchedFile)}"`); + } else { + expect(response.status).toBe(404); + } + }); + }); + }); +}); diff --git a/packages/convex-hosting/src/client/answer.ts b/packages/convex-hosting/src/client/answer.ts new file mode 100644 index 00000000..e69223be --- /dev/null +++ b/packages/convex-hosting/src/client/answer.ts @@ -0,0 +1,65 @@ +import { Analytics } from "../workers-sdk/packages/workers-shared/asset-worker/src/analytics.js"; +import { + canFetch, + handleRequest, +} from "../workers-sdk/packages/workers-shared/asset-worker/src/handler.js"; +import { mockJaegerBinding } from "../workers-sdk/packages/workers-shared/utils/tracing.js"; +import { manifestLookup, type AssetFiles, type ManifestHit } from "./manifest.js"; + +/** An answer of Cloudflare's handler, and the storage URL of its body, if it has one. */ +export type Answer = { status: number; headers: Headers; url: string | null }; + +/** + * Runs Cloudflare's asset handler for `request` against the version's files, or returns `null` when + * no asset answers. `hasUserWorker` is Cloudflare's `has_user_worker`: whether the app has code that + * answers a miss. With it, Cloudflare's router asks `canFetch` first, which keeps + * `not_found_handling` for navigations only, and the app answers the other misses. Without it, + * every request goes to `handleRequest`, so `not_found_handling` applies to all of them, and an + * asset always answers. + */ +export async function answer( + files: AssetFiles, + request: Request, + hasUserWorker: boolean, +): Promise { + const env = { JAEGER: mockJaegerBinding() }; + // `exists` returns the entry's ETag; `getByETag` gets the entry back for that ETag. + const lookup = manifestLookup(files); + const found = new Map(); + const exists = async (pathname: string) => { + const hit = await lookup(pathname); + if (hit === null) return null; + found.set(hit.eTag, hit); + return hit.eTag; + }; + let body: ManifestHit | undefined; + const getByETag = async (eTag: string) => { + body = found.get(eTag); + if (body === undefined) throw new Error(`No entry has the ETag ${eTag}.`); + return { + // `withBody` replaces this placeholder with the stored file. + readableStream: new ReadableStream(), + contentType: body.contentType, + cacheStatus: "MISS" as const, + }; + }; + + if (hasUserWorker && !(await canFetch(request, env, files.config, exists))) return null; + const response = await handleRequest( + request, + env, + files.config, + exists, + getByETag, + new Analytics(), + ); + // It describes Cloudflare's cache, which does not exist here. + response.headers.delete("CF-Cache-Status"); + // The deployment's Cloudflare front caches 404 answers on static paths. + if (response.status === 404) response.headers.set("Cache-Control", "no-store"); + return { + status: response.status, + headers: response.headers, + url: response.body !== null && body !== undefined ? body.url : null, + }; +} diff --git a/packages/convex-hosting/src/client/index.test.ts b/packages/convex-hosting/src/client/index.test.ts index 1069107a..bf086c70 100644 --- a/packages/convex-hosting/src/client/index.test.ts +++ b/packages/convex-hosting/src/client/index.test.ts @@ -2,50 +2,80 @@ import { convexTest } from "convex-test"; import { anyApi, httpRouter, ROUTABLE_HTTP_METHODS } from "convex/server"; import { afterEach, describe, expect, test, vi } from "vite-plus/test"; +import { siteConfig } from "../cli/site-config.js"; +import type { Config } from "../component/lib.js"; import { internal } from "../component/_generated/api.js"; import schema from "../component/schema.js"; import { routeAll } from "./index.js"; +import { buildAssetFiles } from "../cli/manifest.js"; +import { MARK_HEADER, type Assets } from "./manifest.js"; const modules = import.meta.glob(["../component/**/*.ts", "!../component/**/*.test.ts"]); /** The component's public functions, as an app reaches them through `components.hosting`. */ -const component = { lib: { route: anyApi.lib.route, markLive: anyApi.lib.markLive } }; +const component = { lib: { markLive: anyApi.lib.markLive } }; -/** Version `v1` with `/index.html` and `config`, and version `v2`, still uploading. */ -async function setup(config = "{}") { +const CLOUD_URL = "https://example.convex.cloud"; + +/** + * Version `v1` with `/index.html` and `config`, ready, and its assets as the upload writes them. The + * site's action runs in an HTTP action, an action context where `fetch` is allowed; convex-test + * refuses `fetch` in `t.run`, which is a mutation. The response comes back as its parts, with the + * number of functions that the action called. + */ +async function setup(config: Config = {}) { // `markLive` schedules `collect`; the tests run it with `finish`. vi.useFakeTimers(); + vi.stubEnv("CONVEX_CLOUD_URL", CLOUD_URL); const t = convexTest(schema, modules); - const entry = { path: "/index.html", body: "

Home

" }; - const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(entry.body)); + const body = "

Home

"; + const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(body)); const sha256 = Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join( "", ); - const createVersion = async (versionId: string) => { - const configId = await t.run((ctx) => ctx.storage.store(new Blob([config]))); - await t.action(internal.lib.createVersion, { versionId, configId }); - }; - await createVersion("v1"); - const storageId = await t.run((ctx) => ctx.storage.store(new Blob([entry.body]))); + const configId = await t.run((ctx) => ctx.storage.store(new Blob([JSON.stringify(config)]))); + await t.action(internal.lib.createVersion, { versionId: "v1", configId }); + const storageId = await t.run((ctx) => ctx.storage.store(new Blob([body]))); + const entry = { path: "/index.html", sha256, contentType: "text/html" }; await t.mutation(internal.lib.recordFiles, { versionId: "v1", - entries: [{ path: entry.path, sha256, contentType: "text/html", storageId }], + entries: [{ ...entry, storageId }], }); await t.mutation(internal.lib.finishVersion, { versionId: "v1" }); - await createVersion("v2"); - // The site's action runs in an HTTP action, an action context where `fetch` is allowed; - // convex-test refuses `fetch` in `t.run`, which is a mutation. The response comes back as its - // parts, with the number of mutations that the action called. - const serve = (path: string, versionId = "v1", render?: () => Promise) => + const assets: Assets = { + format: 1, + versionId: "v1", + markToken: "token-1", + files: buildAssetFiles(CLOUD_URL, siteConfig(config), [ + { ...entry, url: `${CLOUD_URL}/api/storage/${storageId}` }, + ]), + }; + + const serve = ( + path: string, + options: { + assets?: Assets; + render?: () => Promise; + headers?: Record; + method?: string; + } = {}, + ) => t.action(async (ctx) => { const runMutation = vi.spyOn(ctx, "runMutation"); + const runQuery = vi.spyOn(ctx, "runQuery"); const url = `https://example.convex.site${path}`; - const worker = render === undefined ? undefined : { fetch: render }; - const site = routeAll(httpRouter(), component, versionId, worker); + const worker = options.render === undefined ? undefined : { fetch: options.render }; + const action = routeAll({ + http: httpRouter(), + component, + assets: options.assets ?? assets, + worker, + }); + const request = new Request(url, { method: options.method, headers: options.headers }); // @ts-expect-error httpActionGeneric keeps the function as _handler; PublicHttpAction does not declare it. - const response: Response = await site._handler(ctx, new Request(url)); + const response: Response = await action._handler(ctx, request); return { - mutations: runMutation.mock.calls.length, + calls: runMutation.mock.calls.length + runQuery.mock.calls.length, status: response.status, contentType: response.headers.get("content-type"), cacheControl: response.headers.get("cache-control"), @@ -53,37 +83,39 @@ async function setup(config = "{}") { body: await response.text(), }; }); - const state = (versionId: string) => + const state = () => t.run( async (ctx) => ( await ctx.db .query("versions") - .withIndex("by_versionId", (q) => q.eq("versionId", versionId)) + .withIndex("by_versionId", (q) => q.eq("versionId", "v1")) .unique() )?.state.kind, ); const finish = () => t.finishAllScheduledFunctions(vi.runAllTimers); - return { t, serve, state, finish }; + return { assets, serve, state, finish }; } afterEach(() => { vi.unstubAllGlobals(); + vi.unstubAllEnvs(); vi.useRealTimers(); }); describe("routeAll", () => { - test("routes the action for every method Convex routes, at every path, and returns it", () => { + test("routes the action for every method Convex routes, at every path, and returns it", async () => { + const { assets } = await setup(); const http = httpRouter(); - const site = routeAll(http, component, "v1"); + const action = routeAll({ http, component, assets }); for (const method of ROUTABLE_HTTP_METHODS) { - expect(http.lookup("/any/path", method)).toEqual([site, method, "/*"]); + expect(http.lookup("/any/path", method)).toEqual([action, method, "/*"]); } }); }); describe("the site's action", () => { - test("answers a hit with the stored body and the handler's headers", async () => { + test("answers a hit with the stored body and the handler's headers, and calls no function", async () => { const fetchStorage = vi.fn(async () => new Response("

Home

")); vi.stubGlobal("fetch", fetchStorage); const hit = await (await setup()).serve("/"); @@ -91,64 +123,66 @@ describe("the site's action", () => { expect(hit.contentType).toBe("text/html"); expect(hit.body).toBe("

Home

"); expect(fetchStorage).toHaveBeenCalledOnce(); + expect(hit.calls).toBe(0); }); - test("the first request marks the version live; a later request makes no mutation call", async () => { - vi.stubGlobal("fetch", async () => new Response("

Home

")); - const { serve, state, finish } = await setup(); - expect(await state("v1")).toBe("ready"); - const first = await serve("/"); - expect(first.mutations).toBe(1); - expect(first.status).toBe(200); - expect(await state("v1")).toBe("live"); - const later = await serve("/"); - expect(later.mutations).toBe(0); - expect(later.status).toBe(200); + test("the request with the site's mark token marks the version live and answers the result", async () => { + const { assets, serve, state, finish } = await setup(); + const render = vi.fn(async () => new Response("page")); + const marked = await serve("/.convex-hosting/mark", { + render, + method: "POST", + headers: { [MARK_HEADER]: assets.markToken }, + }); + expect(marked.calls).toBe(1); + expect(JSON.parse(marked.body)).toEqual({ versionId: "v1", result: "marked" }); + expect(marked.cacheControl).toBe("no-store"); + expect(render).not.toHaveBeenCalled(); + expect(await state()).toBe("live"); + const again = await serve("/", { headers: { [MARK_HEADER]: assets.markToken } }); + expect(JSON.parse(again.body)).toEqual({ versionId: "v1", result: "live" }); await finish(); - expect(await state("v1")).toBe("live"); + expect(await state()).toBe("live"); }); - test("concurrent first requests all mark the version live, and all answer", async () => { + test("a request with another mark token is an ordinary request, which calls no function", async () => { vi.stubGlobal("fetch", async () => new Response("

Home

")); - const { serve, state, finish } = await setup(); - const answers = await Promise.all([serve("/"), serve("/"), serve("/missing")]); - expect(answers.map(({ status }) => status)).toEqual([200, 200, 404]); - await finish(); - expect(await state("v1")).toBe("live"); + const { serve, state } = await setup(); + const other = await serve("/", { headers: { [MARK_HEADER]: "guess" } }); + expect(other.status).toBe(200); + expect(other.body).toBe("

Home

"); + expect(other.calls).toBe(0); + expect(await state()).toBe("ready"); }); - test("answers 404 for a version that is being deleted, and does not mark it", async () => { - const { t, serve } = await setup(); - await t.run(async (ctx) => { - const version = await ctx.db - .query("versions") - .withIndex("by_versionId", (q) => q.eq("versionId", "v1")) - .unique(); - if (version !== null) - await ctx.db.patch("versions", version._id, { state: { kind: "deleting" } }); - }); - const deleting = await serve("/"); - expect(deleting.status).toBe(404); - expect(deleting.body).toBe("Version v1 of the site is being deleted."); - expect(deleting.cacheControl).toBe("no-store"); - expect(deleting.mutations).toBe(0); + test("a first install's assets, before its upload, answer 404 naming the version, without rendering", async () => { + const { assets, serve } = await setup(); + const render = vi.fn(async () => new Response("page")); + const early = await serve("/", { assets: { ...assets, files: null }, render }); + expect(early.status).toBe(404); + expect(early.body).toBe("Version v1 of the site is not uploaded yet."); + expect(early.cacheControl).toBe("no-store"); + expect(render).not.toHaveBeenCalled(); }); - test("answers 404 naming a version that does not exist or is uploading, without rendering", async () => { - const { serve } = await setup(); + test("assets uploaded to another deployment answer 404 naming it, without rendering", async () => { + const { assets, serve } = await setup(); + vi.stubEnv("CONVEX_CLOUD_URL", "https://other-dog-456.convex.cloud"); const render = vi.fn(async () => new Response("page")); - const missing = await serve("/", "v3", render); - expect(missing.status).toBe(404); - expect(missing.body).toContain("v3"); - expect(missing.cacheControl).toBe("no-store"); - const uploading = await serve("/", "v2", render); - expect(uploading.status).toBe(404); - expect(uploading.body).toContain("v2"); - expect(uploading.cacheControl).toBe("no-store"); - expect(missing.mutations + uploading.mutations).toBe(0); + const elsewhere = await serve("/", { assets, render }); + expect(elsewhere.status).toBe(404); + expect(elsewhere.body).toContain(`was uploaded to ${CLOUD_URL}, not to this deployment`); expect(render).not.toHaveBeenCalled(); }); + test("assets of another format answer 500 and ask for a deploy", async () => { + const { assets, serve } = await setup(); + // A version file that another release wrote. + const answer = await serve("/", { assets: { ...assets, format: 0 } }); + expect(answer.status).toBe(500); + expect(answer.body).toContain("Deploy again."); + }); + test("answers 404 when storage no longer has the file, and 502 for other failures", async () => { const { serve } = await setup(); vi.stubGlobal("fetch", async () => new Response(null, { status: 404 })); @@ -170,19 +204,26 @@ describe("the site's action", () => { test("answers a file without rendering", async () => { vi.stubGlobal("fetch", async () => new Response("

Home

")); const render = vi.fn(async () => new Response("page")); - const file = await (await setup()).serve("/", "v1", render); + const file = await (await setup()).serve("/", { render }); expect(file.status).toBe(200); expect(file.cacheControl).toBe("public, max-age=0, must-revalidate"); expect(file.body).toBe("

Home

"); expect(render).not.toHaveBeenCalled(); }); + test("a redirect downloads nothing", async () => { + const fetchStorage = vi.fn(async () => new Response("

Home

")); + vi.stubGlobal("fetch", fetchStorage); + const { serve } = await setup(); + const redirect = await serve("/index.html"); + expect(redirect.status).toBe(307); + expect(fetchStorage).not.toHaveBeenCalled(); + }); + test("answers a rendered page with no-store and keeps its other headers", async () => { const { serve } = await setup(); - const page = await serve( - "/todos", - "v1", - async () => + const page = await serve("/todos", { + render: async () => new Response("

Todos

", { status: 200, headers: [ @@ -191,11 +232,12 @@ describe("the site's action", () => { ["Set-Cookie", "b=2"], ], }), - ); + }); expect(page.status).toBe(200); expect(page.cacheControl).toBe("no-store"); expect(page.setCookie).toEqual(["a=1", "b=2"]); expect(page.body).toBe("

Todos

"); + expect(page.calls).toBe(0); }); test("answers a miss without render with 404 and no-store", async () => { @@ -206,16 +248,18 @@ describe("the site's action", () => { test("without render, the single-page fallback answers a request that is not a navigation", async () => { vi.stubGlobal("fetch", async () => new Response("

Home

")); - const spa = JSON.stringify({ not_found_handling: "single-page-application" }); - const page = await (await setup(spa)).serve("/about"); + const page = await ( + await setup({ not_found_handling: "single-page-application" }) + ).serve("/about"); expect(page.status).toBe(200); expect(page.body).toBe("

Home

"); }); test("with render, a request that is not a navigation and matches no file is rendered", async () => { - const spa = JSON.stringify({ not_found_handling: "single-page-application" }); const render = vi.fn(async () => new Response("

About

")); - const page = await (await setup(spa)).serve("/about", "v1", render); + const page = await ( + await setup({ not_found_handling: "single-page-application" }) + ).serve("/about", { render }); expect(render).toHaveBeenCalledOnce(); expect(page.status).toBe(200); expect(page.body).toBe("

About

"); diff --git a/packages/convex-hosting/src/client/index.ts b/packages/convex-hosting/src/client/index.ts index ee496493..0cdb10e0 100644 --- a/packages/convex-hosting/src/client/index.ts +++ b/packages/convex-hosting/src/client/index.ts @@ -2,36 +2,80 @@ import "./runtime.js"; import { httpActionGeneric, ROUTABLE_HTTP_METHODS, - type GenericActionCtx, - type GenericDataModel, type HttpRouter, type PublicHttpAction, } from "convex/server"; import type { ComponentApi } from "../component/_generated/component.js"; +import { answer, type Answer } from "./answer.js"; +import { ASSETS_FORMAT, MARK_HEADER, type Assets } from "./manifest.js"; + +export type { Assets } from "./manifest.js"; + +/** What `routeAll` routes, each named as Cloudflare and Convex name it. */ +export type RouteAllOptions = { + /** The app's router, from `httpRouter()`. */ + http: HttpRouter; + /** The installed component: `components.hosting`. */ + component: ComponentApi; + /** `assets` from `.convex-hosting/version.js`, which `convex-hosting deploy` writes. */ + assets: Assets; + /** + * The Worker script: the object with `fetch(request)` that the app's server entry exports, the + * code that runs on a miss. Without it, the site is assets only. + */ + worker?: { fetch(request: Request): Promise }; +}; /** - * The HTTP action that serves the site, for `routeAll`: it answers a request with the file of - * version `versionId` (another method than GET or HEAD on a file answers 405), else with what - * `worker` answers, else 404. `worker` is the Worker script, the object with `fetch(request)` - * that the app's server entry exports: the code that runs on a miss. As on Cloudflare, the presence - * of code decides how `not_found_handling` applies: with `worker`, it applies to navigations only - * and `worker` answers the other misses; without it, the site is files only, so it applies to every - * request. + * The HTTP action that serves the site, for `routeAll`: it answers a request with an asset (another + * method than GET or HEAD on an asset answers 405), else with what `worker` answers, else 404. As on + * Cloudflare, the presence of a Worker script decides how `not_found_handling` applies: with + * `worker`, it applies to navigations only and `worker` answers the other misses; without it, it + * applies to every request. + * + * The assets are in the pushed code, so a request calls no function of the component: a file costs + * this action and the download of its bytes, any other answer this action alone. * * A page and a 404 answer `Cache-Control: no-store`. The deployment's Cloudflare front keeps that * for a path without an extension and replaces it with a four-hour browser `max-age` for a path * with one, so a browser that asks for a script before its upload ended keeps the 404; the deploy * order prevents that case, because no page refers to a file that is not uploaded yet. */ -function serveSite( - component: ComponentApi, - versionId: string, - worker?: { fetch(request: Request): Promise }, -): PublicHttpAction { +function serveSite({ component, assets, worker }: RouteAllOptions): PublicHttpAction { return httpActionGeneric(async (ctx, request) => { - const asset = await answer(ctx, component, request, versionId, worker !== undefined); - if (asset !== null) return asset; - // `route` answers every files-only request itself, so this 404 only fails closed. + // Read first: a mark says when its request reached this code. + const arrivedAt = Date.now(); + if (assets.format !== ASSETS_FORMAT) { + return notServed( + 500, + `.convex-hosting/version.js has format ${assets.format}, and this release of ` + + `@samebase/convex-hosting reads format ${ASSETS_FORMAT}. Deploy again.`, + ); + } + if (request.headers.get(MARK_HEADER) === assets.markToken) { + const result = await ctx.runMutation(component.lib.markLive, { + versionId: assets.versionId, + arrivedAt, + }); + return Response.json({ versionId: assets.versionId, result }, { headers: NO_STORE }); + } + const { files } = assets; + // A first install pushes before its upload; the deploy pushes again when the upload ends. + if (files === null) { + return notServed(404, `Version ${assets.versionId} of the site is not uploaded yet.`); + } + // The storage URLs name the deployment they were taken from. + if (files.cloudUrl !== process.env.CONVEX_CLOUD_URL) { + return notServed( + 404, + `Version ${assets.versionId} of the site was uploaded to ${files.cloudUrl}, not to this ` + + `deployment. Deploy to this deployment with convex-hosting deploy.`, + ); + } + + const asset = await answer(files, request, worker !== undefined); + if (asset !== null) return await withBody(asset); + // `answer` answers every assets-only request itself, so this 404 only fails closed. if (worker === undefined) return new Response(null, { status: 404, headers: NO_STORE }); const page = await worker.fetch(request); const headers = new Headers(page.headers); @@ -45,95 +89,37 @@ function serveSite( * every path, as every request reaches a Cloudflare Worker with static assets. Convex answers HEAD * through GET. * + * ```ts + * routeAll({ http, component: components.hosting, assets, worker: server }); + * ``` + * * Returns the action, for the paths that a component's HTTP prefix would otherwise take: Convex * picks an exact route first, then the longest prefix, so an app whose session routes sit under a * component's prefix registers them with `http.route({ path, method, handler })`. */ -export function routeAll( - http: HttpRouter, - component: ComponentApi, - versionId: string, - worker?: { fetch(request: Request): Promise }, -): PublicHttpAction { - const site = serveSite(component, versionId, worker); +export function routeAll(options: RouteAllOptions): PublicHttpAction { + const action = serveSite(options); for (const method of ROUTABLE_HTTP_METHODS) { - http.route({ pathPrefix: "/", method, handler: site }); + options.http.route({ pathPrefix: "/", method, handler: action }); } - return site; + return action; } -/** - * Answers `request` with the asset of version `versionId` that Cloudflare's asset handler picks, - * or returns `null` when no asset matches. `hasUserWorker` is Cloudflare's `has_user_worker`. - * - * A version that does not exist, is still uploading, or is being deleted answers 404, so a - * half-installed site does not render pages without their files. The first request for a `ready` - * version marks it live, which deletes the versions that were live before it; a version older than - * the live one is never marked. - */ -async function answer( - ctx: Pick, "runQuery" | "runMutation">, - component: ComponentApi, - request: Request, - versionId: string, - hasUserWorker: boolean, -): Promise { - const { state, asset } = await ctx.runQuery(component.lib.route, { - versionId, - method: request.method, - url: request.url, - headers: handlerHeaders(request.headers), - hasUserWorker, - }); - if (state === null || state === "uploading" || state === "deleting") { - const problem = - state === null - ? "does not exist" - : state === "uploading" - ? "is still uploading" - : "is being deleted"; - return new Response(`Version ${versionId} of the site ${problem}.`, { - status: 404, - headers: NO_STORE, - }); - } - // Only the pushed code knows which version the deployment runs, so its first request reports it. - if (state === "ready") { - await ctx.runMutation(component.lib.markLive, { versionId }); - } - if (asset === null) return null; - - const headers = new Headers(); - for (const { name, value } of asset.headers) headers.append(name, value); - if (asset.bodyUrl === null) return new Response(null, { status: asset.status, headers }); - +/** The response of `asset`, with the stored file as its body when it has one. */ +async function withBody(asset: Answer): Promise { + if (asset.url === null) + return new Response(null, { status: asset.status, headers: asset.headers }); // An app cannot read a component's storage, so the body comes from the storage URL. let stored: Response; try { - stored = await fetch(asset.bodyUrl); + stored = await fetch(asset.url); } catch { - return badGateway(); + return new Response(null, { status: 502, headers: NO_STORE }); } - // A deploy deleted the file between the query and the fetch. + // A deploy deleted the file: this code was replaced, and a later version's mark deleted it. if (stored.status === 404) return new Response(null, { status: 404, headers: NO_STORE }); - if (!stored.ok) return badGateway(); - return new Response(stored.body, { status: asset.status, headers }); -} - -/** - * The request headers that Cloudflare's handler reads. It reads only the presence of - * `Authorization` and `Range`, so their values (a credential, for one) stay out of the query. - */ -function handlerHeaders(headers: Headers): Record { - const picked: Record = {}; - for (const name of ["if-none-match", "sec-fetch-mode"]) { - const value = headers.get(name); - if (value !== null) picked[name] = value; - } - for (const name of ["authorization", "range"]) { - if (headers.has(name)) picked[name] = ""; - } - return picked; + if (!stored.ok) return new Response(null, { status: 502, headers: NO_STORE }); + return new Response(stored.body, { status: asset.status, headers: asset.headers }); } /** @@ -143,6 +129,7 @@ function handlerHeaders(headers: Headers): Record { */ const NO_STORE = { "Cache-Control": "no-store" }; -function badGateway() { - return new Response(null, { status: 502, headers: NO_STORE }); +/** A site that cannot serve this request, named in the body. */ +function notServed(status: number, message: string) { + return new Response(message, { status, headers: NO_STORE }); } diff --git a/packages/convex-hosting/src/client/manifest.ts b/packages/convex-hosting/src/client/manifest.ts new file mode 100644 index 00000000..3acb0659 --- /dev/null +++ b/packages/convex-hosting/src/client/manifest.ts @@ -0,0 +1,104 @@ +import { + binarySearch, + hashPath, +} from "../workers-sdk/packages/workers-shared/asset-worker/src/assets-manifest.js"; +import type { NormalizedAssetConfig } from "../workers-sdk/packages/workers-shared/asset-worker/src/types.js"; +import { CONTENT_HASH_SIZE } from "../workers-sdk/packages/workers-shared/utils/constants.js"; + +/** + * The format of `Assets`. `serveSite` refuses assets of another format, which only a deploy with + * another release of this package writes. + */ +export const ASSETS_FORMAT = 1; + +/** + * The header with which the CLI, after the push, asks the served code to mark its version live. Its + * value is the site's `markToken`; a request without it is an ordinary request. + */ +export const MARK_HEADER = "Convex-Hosting-Mark"; + +/** The path of that request, which names it in logs; the header alone decides. */ +export const MARK_PATH = "/.convex-hosting/mark"; + +/** + * The static assets of one version, as `.convex-hosting/version.js` exports them under `assets`, + * Cloudflare's name for them: the version's id, and everything that serving reads, so that a + * request reads no database. `files` is `null` in the code that a first install pushes before its + * upload, which serves nothing. + */ +export type Assets = { + /** `ASSETS_FORMAT` of the release that wrote it. */ + format: number; + versionId: string; + /** + * The CLI sends it after the push, so that only the CLI makes the served code mark its version + * live; another request with the header pays nothing more than any other request. + */ + markToken: string; + files: AssetFiles | null; +}; + +export type AssetFiles = { + /** The deployment's `CONVEX_CLOUD_URL` at the upload: the origin of every storage URL. */ + cloudUrl: string; + /** Cloudflare's normalized `AssetConfig` for the version, as its handler takes it. */ + config: NormalizedAssetConfig; + /** + * Cloudflare's asset manifest, in base64, which Cloudflare's own reader searches. The tail of an + * entry, which Cloudflare leaves zero, holds the indexes of its URL and its content type. + */ + manifest: string; + contentTypes: string[]; + /** + * The storage URL of each stored file is `urlPrefix`, its key, and `urlSuffix`. The keys are one + * string, `urlKeyWidth` characters each, padded with spaces: Convex evaluates the module for + * every request, and one string costs less than an array of 100,000. + */ + urlPrefix: string; + urlSuffix: string; + urlKeys: string; + urlKeyWidth: number; +}; + +/** Where an entry's tail, after the content hash, keeps the index of its URL (a big-endian u32). */ +export const TAIL_URL = 0; +/** Where the tail keeps the index of the content type (a big-endian u16). */ +export const TAIL_CONTENT_TYPE = 4; +/** The content type index of an entry without a content type. */ +export const NO_CONTENT_TYPE = 0xffff; + +export type ManifestHit = { + /** The hex of the content hash, which is the ETag, as on Cloudflare. */ + eTag: string; + url: string; + contentType: string | undefined; +}; + +/** + * Decodes the manifest once, like Cloudflare's `AssetsManifest`, and returns its lookup: it finds the + * entry of a path with Cloudflare's binary search, or returns `null`. + */ +export function manifestLookup(files: AssetFiles) { + const manifest = fromBase64(files.manifest); + return async (path: string): Promise => { + const contentHash = binarySearch(manifest, await hashPath(path)); + if (contentHash === false) return null; + const tail = new DataView(contentHash.buffer, contentHash.byteOffset + CONTENT_HASH_SIZE); + const key = tail.getUint32(TAIL_URL) * files.urlKeyWidth; + const contentType = tail.getUint16(TAIL_CONTENT_TYPE); + return { + eTag: Array.from(contentHash, (byte) => byte.toString(16).padStart(2, "0")).join(""), + url: + files.urlPrefix + + files.urlKeys.slice(key, key + files.urlKeyWidth).trimEnd() + + files.urlSuffix, + contentType: contentType === NO_CONTENT_TYPE ? undefined : files.contentTypes[contentType], + }; + }; +} + +/** Convex's runtime decodes base64 natively; Node before 25, where tests run, does not. */ +function fromBase64(text: string): Uint8Array { + const decoded = (Uint8Array as { fromBase64?: (text: string) => Uint8Array }).fromBase64?.(text); + return decoded ?? Uint8Array.from(atob(text), (char) => char.charCodeAt(0)); +} diff --git a/packages/convex-hosting/src/client/overlap.test.ts b/packages/convex-hosting/src/client/overlap.test.ts new file mode 100644 index 00000000..d3e83f55 --- /dev/null +++ b/packages/convex-hosting/src/client/overlap.test.ts @@ -0,0 +1,290 @@ +/// +import { convexTest } from "convex-test"; +import { anyApi, httpRouter, type FunctionReference } from "convex/server"; +import fc from "fast-check"; +import { afterEach, describe, expect, test, vi } from "vite-plus/test"; +import { api, internal } from "../component/_generated/api.js"; +import type { Id } from "../component/_generated/dataModel.js"; +import schema from "../component/schema.js"; +import { routeAll } from "./index.js"; +import { ASSETS_FORMAT, MARK_HEADER, MARK_PATH, type Assets } from "./manifest.js"; + +const modules = import.meta.glob(["../component/**/*.ts", "!../component/**/*.test.ts"]); +const component = { lib: { markLive: anyApi.lib.markLive } }; +const DAY = 24 * 60 * 60 * 1000; + +/** + * The steps of a deploy that other deploys can come between. The mark is two: the request arrives + * at the code that serves at that moment, and the `markLive` that this code calls runs later, when + * other code may serve. + */ +const STEPS = ["upload", "push", "mark arrives", "mark runs"] as const; + +/** A call of `markLive` that is on its way. */ +type Call = { versionId: string; arrivedAt: number }; + +/** What an upload leaves: the version file that the deploy pushes, and its stored files. */ +type Uploaded = { assets: Assets; storageIds: Id<"_storage">[] }; + +type Run = { + /** + * Picks what happens next among what can happen now, or nothing to end the run: a deploy's name + * for its next step, `cleanup N` for the next call of the Nth `collect` chain that waits, or `a + * day passes`. A day can pass when no deploy is between its upload and its push, no mark is on + * its way, and no `collect` waits: the day bounds how late a push may follow its upload, and the + * rest takes seconds. + */ + pick: (events: string[]) => string | undefined; + /** The deploys that build the commit that serves, so their script is `p`'s, a day old. */ + rebuilds: string[]; + /** + * Who marks a version live. `request` is the design: the deploy's request with its mark token, + * answered by the code that serves. `cli` is the rejected one: the deploy's own call of + * `markLive`. + */ + markBy: "request" | "cli"; +}; + +/** + * Runs deploys a, b and c on the real component and the real serving code, over a version `p` that + * was deployed a day before, and returns the first event after which the version that serves lacks + * an entry or a stored file, or `null`. A stored file goes only after its entries, so the entries + * are checked too. + */ +async function firstLoss({ pick, rebuilds, markBy }: Run) { + vi.useFakeTimers(); + const t = convexTest(schema, modules); + + /** The upload of a page that every commit has, stored once, and the commit's script. */ + const upload = async (versionId: string): Promise => { + const configId = await t.run((ctx) => ctx.storage.store(new Blob(["{}"]))); + await t.action(internal.lib.createVersion, { versionId, configId }); + const commit = rebuilds.includes(versionId) ? "p" : versionId; + const entries = []; + for (const [path, body] of [ + ["/index.html", "

Home

"], + ["/assets/app.js", commit], + ] as const) { + const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(body)); + const sha256 = Array.from(new Uint8Array(digest), (byte) => + byte.toString(16).padStart(2, "0"), + ).join(""); + const [known] = await t.query(internal.lib.knownFiles, { sha256s: [sha256] }); + const storageId = + known?.storageId ?? (await t.run((ctx) => ctx.storage.store(new Blob([body])))); + entries.push({ path, sha256, storageId }); + } + await t.mutation(internal.lib.recordFiles, { versionId, entries }); + await t.mutation(internal.lib.finishVersion, { versionId }); + return { + // The mark reads the id and the token alone. + assets: { format: ASSETS_FORMAT, versionId, markToken: `token of ${versionId}`, files: null }, + storageIds: entries.map(({ storageId }) => storageId), + }; + }; + + /** The call of `markLive` that the mark of `deploy` makes when `serving` is the code that serves. */ + const markArrives = async (deploy: Assets, serving: Assets): Promise => { + if (markBy === "cli") return { versionId: deploy.versionId, arrivedAt: Date.now() }; + let call: Call | undefined; + const runMutation = async (_: FunctionReference<"mutation">, args: Call) => { + call = args; + return "marked"; + }; + const action = routeAll({ http: httpRouter(), component, assets: serving }); + const request = new Request(`https://example.convex.site${MARK_PATH}`, { + method: "POST", + headers: { [MARK_HEADER]: deploy.markToken }, + }); + // @ts-expect-error httpActionGeneric keeps the function as _handler; PublicHttpAction does not declare it. + await action._handler({ runMutation }, request); + return call; + }; + + /** + * The `collect` calls that wait, oldest first. The clock moves without running the timers, so + * the scheduled calls never start by themselves: the run picks when each one does. + */ + const waiting: { step: (typeof internal.lib.collect)["_args"]["step"] }[] = []; + const seen = new Set(); + const readScheduled = async () => { + const jobs = await t.run((ctx) => ctx.db.system.query("_scheduled_functions").collect()); + for (const job of jobs) { + if (!seen.has(job._id)) waiting.push({ step: job.args[0].step }); + seen.add(job._id); + } + }; + + let serving = await upload("p"); + await t.mutation(api.lib.markLive, { versionId: "p", arrivedAt: Date.now() }); + for (await readScheduled(); waiting.length > 0; await readScheduled()) { + await t.mutation(internal.lib.collect, waiting.shift()!); + } + vi.setSystemTime(Date.now() + DAY + 1); + + const deploys = new Map(); + const done = (name: string) => deploys.get(name)?.done ?? 0; + const happened: string[] = []; + for (;;) { + const underway = [...deploys.values()].some((deploy) => deploy.done === 1 || deploy.done === 3); + const event = pick([ + ...["a", "b", "c"].filter((name) => done(name) < STEPS.length), + ...waiting.map((_, i) => `cleanup ${i + 1}`), + ...(underway || waiting.length > 0 ? [] : ["a day passes"]), + ]); + if (event === undefined) return null; + + if (event === "a day passes") { + vi.setSystemTime(Date.now() + DAY); + happened.push(event); + } else if (event.startsWith("cleanup ")) { + const [call] = waiting.splice(Number(event.slice("cleanup ".length)) - 1, 1); + await t.mutation(internal.lib.collect, call!); + happened.push(`cleanup of ${call!.step.kind}`); + } else { + const deploy = deploys.get(event) ?? { ...(await upload(event)), done: 0 }; + deploys.set(event, deploy); + const step = STEPS[deploy.done++]!; + happened.push(`${step} ${event}`); + if (step === "push") serving = deploy; + if (step === "mark arrives") deploy.call = await markArrives(deploy.assets, serving.assets); + if (step === "mark runs" && deploy.call !== undefined) { + await t.mutation(api.lib.markLive, deploy.call); + } + } + await readScheduled(); + vi.setSystemTime(Date.now() + 1000); + + const { assets, storageIds } = serving; + const kept = await t.run(async (ctx) => { + const entries = await ctx.db + .query("entries") + .withIndex("by_version_path", (q) => q.eq("versionId", assets.versionId)) + .collect(); + const files = await Promise.all(storageIds.map((id) => ctx.db.system.get("_storage", id))); + return { entries: entries.length, files: files.filter((file) => file !== null).length }; + }); + if (kept.entries < 2 || kept.files < 2) { + return ( + `${assets.versionId} serves with ${kept.entries} of its 2 entries and ${kept.files} of ` + + `its 2 stored files: ${happened.join(", ")}` + ); + } + } +} + +type Orders = { + /** The deploys that run, named in the order of their uploads. */ + deploys: string; + /** A day passes after every event that allows one, so everything is old enough to delete. */ + days: boolean; + /** + * Every mark runs as it arrives and every `collect` chain runs to its end before the next step, + * which leaves few enough orders for three deploys. + */ + atOnce: boolean; + markBy: Run["markBy"]; +}; + +/** + * Runs every order in which the deploys' steps and the calls of `collect` can happen, and returns + * the runs that lost something, with the number of runs. It walks the tree of choices: each run + * repeats the choices of the one before up to the deepest choice that has another option, and + * takes that one. + */ +async function everyOrder({ deploys, days, atOnce, markBy }: Orders) { + const losses: string[] = []; + const path: number[] = []; + let runs = 0; + do { + const sizes: number[] = []; + const steps = new Map(); + let rested = true; + let last: string | undefined; + const pick: Run["pick"] = (events) => { + if (days && !rested && events.includes("a day passes")) { + rested = true; + return "a day passes"; + } + rested = false; + const taken = (name: string) => steps.get(name) ?? 0; + const step = (name: string) => { + steps.set(name, taken(name) + 1); + last = name; + return name; + }; + if (atOnce && events.includes("cleanup 1")) return "cleanup 1"; + if (atOnce && last !== undefined && taken(last) === 3) return step(last); + // The uploads start in the order of `deploys`, which only names them by creation time. + const choices = events.filter((event) => { + const i = deploys.indexOf(event); + return event.startsWith("cleanup") || i === 0 || (i > 0 && taken(deploys[i - 1]!) > 0); + }); + if (choices.length === 0) return undefined; + const depth = sizes.push(choices.length) - 1; + const choice = choices[(path[depth] ??= 0)]!; + return choice.startsWith("cleanup") ? choice : step(choice); + }; + const loss = await firstLoss({ pick, rebuilds: [], markBy }); + if (loss !== null) losses.push(loss); + runs++; + path.length = sizes.length; + while (path.length > 0 && path[path.length - 1]! + 1 >= sizes[path.length - 1]!) path.pop(); + if (path.length > 0) path[path.length - 1]!++; + } while (path.length > 0); + return { runs, losses }; +} + +afterEach(() => { + vi.useRealTimers(); +}); + +describe("deploys that overlap: the version that serves keeps its entries and its files", () => { + test.each([false, true])( + "two deploys, their steps and every call of collect in every order (a day between them: %s)", + async (days) => { + const orders = { deploys: "ab", days, atOnce: false, markBy: "request" } as const; + expect(await everyOrder(orders)).toEqual({ runs: 221, losses: [] }); + }, + 60_000, + ); + + test.each([false, true])( + "three deploys, their steps in every order, each mark and collect run at once (a day between them: %s)", + async (days) => { + const orders = { deploys: "abc", days, atOnce: true, markBy: "request" } as const; + expect(await everyOrder(orders)).toEqual({ runs: 280, losses: [] }); + }, + 60_000, + ); + + test("three deploys, their steps and every call of collect in any order, days between them or not", async () => { + await fc.assert( + fc.asyncProperty( + // Always 40 events: enough for the three deploys and their collect calls. + fc.array(fc.nat(), { minLength: 40, maxLength: 40 }), + fc.subarray(["a", "b", "c"]), + async (picks, rebuilds) => { + let taken = 0; + const pick: Run["pick"] = (events) => + taken < picks.length ? events[picks[taken++]! % events.length] : undefined; + expect(await firstLoss({ pick, rebuilds, markBy: "request" })).toBeNull(); + }, + ), + { numRuns: 300 }, + ); + }, 60_000); + + test("marked from the CLI instead, a version that serves loses its entries with no mark on its way", async () => { + const orders = { deploys: "ab", days: false, atOnce: true } as const; + const { losses } = await everyOrder({ ...orders, markBy: "cli" }); + // The older upload is pushed last, so a serves. Each deploy's own call marks its version, and + // b's mark deletes a as the version that was live before it. + expect(losses).toEqual([ + "a serves with 0 of its 2 entries and 2 of its 2 stored files: upload a, upload b, " + + "push b, push a, mark arrives a, mark runs a, cleanup of files, cleanup of versions, " + + "mark arrives b, mark runs b, cleanup of files, cleanup of versions", + ]); + expect((await everyOrder({ ...orders, markBy: "request" })).losses).toEqual([]); + }); +}); diff --git a/packages/convex-hosting/src/client/version-module.d.ts b/packages/convex-hosting/src/client/version-module.d.ts index 696a4ec9..6b549ecc 100644 --- a/packages/convex-hosting/src/client/version-module.d.ts +++ b/packages/convex-hosting/src/client/version-module.d.ts @@ -2,5 +2,5 @@ // fresh clone, before its first deploy. Script file on purpose: a wildcard module name is only allowed // in an ambient context. declare module "*/.convex-hosting/version.js" { - export const versionId: string; + export const assets: import("./manifest.js").Assets; } diff --git a/packages/convex-hosting/src/component/_generated/component.ts b/packages/convex-hosting/src/component/_generated/component.ts index d9bfea95..d925e227 100644 --- a/packages/convex-hosting/src/component/_generated/component.ts +++ b/packages/convex-hosting/src/component/_generated/component.ts @@ -27,28 +27,8 @@ export type ComponentApi = markLive: FunctionReference< "mutation", "internal", - { versionId: string }, - null, - Name - >; - route: FunctionReference< - "query", - "internal", - { - hasUserWorker: boolean; - headers: Record; - method: string; - url: string; - versionId: string; - }, - { - asset: null | { - bodyUrl: string | null; - headers: Array<{ name: string; value: string }>; - status: number; - }; - state: "uploading" | "ready" | "live" | "deleting" | null; - }, + { arrivedAt: number; versionId: string }, + "marked" | "live" | "superseded" | "uploading" | "deleting" | "missing", Name >; }; diff --git a/packages/convex-hosting/src/component/conformance.test.ts b/packages/convex-hosting/src/component/conformance.test.ts deleted file mode 100644 index aafe1029..00000000 --- a/packages/convex-hosting/src/component/conformance.test.ts +++ /dev/null @@ -1,84 +0,0 @@ -/// -// Cloudflare's own cases for `html_handling` and path encoding, from -// fixtures/workers-shared-asset-config in cloudflare/workers-sdk, run through `route`. Upstream -// runs them against its asset Worker with `exists` mocked; here the files are a version's entries. -import { convexTest } from "convex-test"; -import { describe, expect, test } from "vite-plus/test"; -import type { Config } from "./lib.js"; -import { api, internal } from "./_generated/api.js"; -import schema from "./schema.js"; -import { encodingTestCases } from "../workers-sdk/fixtures/workers-shared-asset-config/test-cases/encoding-test-cases.js"; -import { htmlHandlingTestCases } from "../workers-sdk/fixtures/workers-shared-asset-config/test-cases/html-handling-test-cases.js"; - -const modules = import.meta.glob(["./**/*.ts", "!./**/*.test.ts"]); - -const ORIGIN = "https://example.convex.site"; - -async function sha256Hex(body: string) { - const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(body)); - return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join(""); -} - -/** Uploads `files` as version `versionId`. Each file's body is its own path, so the ETag names it. */ -async function uploadVersion( - t: ReturnType, - versionId: string, - files: string[], - config: Config, -) { - const configId = await t.run((ctx) => ctx.storage.store(new Blob([JSON.stringify(config)]))); - await t.action(internal.lib.createVersion, { versionId, configId }); - const entries = []; - for (const path of files) { - const storageId = await t.run((ctx) => ctx.storage.store(new Blob([path]))); - entries.push({ path, sha256: await sha256Hex(path), storageId }); - } - await t.mutation(internal.lib.recordFiles, { versionId, entries }); - await t.mutation(internal.lib.finishVersion, { versionId }); -} - -/** Requests `path` and follows redirects, as the upstream test's `fetch` does. */ -async function follow(t: ReturnType, versionId: string, path: string) { - let url = ORIGIN + path; - for (let hop = 0; hop < 8; hop++) { - const { asset } = await t.query(api.lib.route, { - versionId, - method: "GET", - url, - headers: {}, - hasUserWorker: false, - }); - if (asset === null) throw new Error(`No asset for ${url}`); - const header = (name: string) => asset.headers.find((h) => h.name === name)?.value; - const location = header("location"); - if (location !== undefined && asset.status >= 300 && asset.status < 400) { - url = new URL(location, url).href; - continue; - } - return { status: asset.status, url, eTag: header("etag"), redirected: hop > 0 }; - } - throw new Error(`Too many redirects from ${path}`); -} - -const suites = [ - { title: "html_handling", suite: htmlHandlingTestCases }, - { title: "encoding", suite: encodingTestCases }, -]; - -describe.each(suites)("$title", ({ suite }) => { - describe.each(suite)("$html_handling", ({ html_handling, cases }) => { - test.each(cases)("$title", async ({ files, requestPath, matchedFile, finalPath }) => { - const t = convexTest(schema, modules); - await uploadVersion(t, "v1", files, { html_handling, not_found_handling: "none" }); - const response = await follow(t, "v1", requestPath); - if (matchedFile && finalPath) { - expect(response.status).toBe(200); - expect(response.url).toBe(ORIGIN + finalPath); - expect(response.redirected).toBe(requestPath !== finalPath); - expect(response.eTag).toMatch(new RegExp(`^"${await sha256Hex(matchedFile)}`)); - } else { - expect(response.status).toBe(404); - } - }); - }); -}); diff --git a/packages/convex-hosting/src/component/lib.test.ts b/packages/convex-hosting/src/component/lib.test.ts index c67b1262..d2a858e4 100644 --- a/packages/convex-hosting/src/component/lib.test.ts +++ b/packages/convex-hosting/src/component/lib.test.ts @@ -71,25 +71,8 @@ const site: Files = { "/assets/app-a1.js": { body: "console.log(1)", contentType: "text/javascript; charset=utf-8" }, }; -function route( - t: ReturnType, - versionId: string, - path: string, - headers: Record = {}, - hasUserWorker = true, - method = "GET", -) { - return t.query(api.lib.route, { - versionId, - method, - url: `https://example.convex.site${path}`, - headers, - hasUserWorker, - }); -} - async function markLive(t: ReturnType, versionId: string) { - await t.mutation(api.lib.markLive, { versionId }); + return await t.mutation(api.lib.markLive, { versionId, arrivedAt: Date.now() }); } /** The kind of each version's state, and the number of `collect` chains that `markLive` started. */ @@ -104,10 +87,6 @@ async function liveness(t: ReturnType) { })); } -function header(asset: { headers: { name: string; value: string }[] } | null, name: string) { - return asset?.headers.find((h) => h.name === name)?.value; -} - afterEach(() => { vi.useRealTimers(); }); @@ -201,7 +180,7 @@ describe("markLive", () => { vi.useFakeTimers(); const t = convexTest(schema, modules); await uploadVersion(t, "v1", site); - await markLive(t, "v1"); + expect(await markLive(t, "v1")).toBe("marked"); const state = async () => await t.run( async (ctx) => @@ -215,35 +194,52 @@ describe("markLive", () => { const live = await state(); expect(live).toEqual({ kind: "live", at: Date.now() }); vi.advanceTimersByTime(1000); - await markLive(t, "v1"); + expect(await markLive(t, "v1")).toBe("live"); expect(await state()).toEqual(live); - expect((await route(t, "v1", "/")).state).toBe("live"); }); - test("refuses a version that is uploading or does not exist", async () => { + test("does not mark a version that is uploading or does not exist, and says so", async () => { const t = convexTest(schema, modules); await createVersion(t, "v1"); - await expect(markLive(t, "v1")).rejects.toThrow("Version v1 is still uploading."); - await expect(markLive(t, "v2")).rejects.toThrow("Version v2 does not exist."); + expect(await markLive(t, "v1")).toBe("uploading"); + expect(await markLive(t, "v2")).toBe("missing"); + expect((await liveness(t)).versions).toEqual({ v1: "uploading" }); }); - test("an older upload never goes live over a newer one: a stale request's mark is refused", async () => { + test("an older upload never goes live over a newer one: a mark of replaced code is refused", async () => { vi.useFakeTimers(); const t = convexTest(schema, modules); await uploadVersion(t, "a", site); await uploadVersion(t, "b", site); - // B's code replaces A's and its first request marks B live. - await markLive(t, "b"); + // B's code replaces A's, and B's deploy marks B live. + expect(await markLive(t, "b")).toBe("marked"); await t.finishAllScheduledFunctions(vi.runAllTimers); - // A request that started on A's code reaches its mark after that. + // A's mark arrives after that, from an overlapping deploy of A. vi.advanceTimersByTime(1000); - await markLive(t, "a"); + expect(await markLive(t, "a")).toBe("superseded"); expect(await liveness(t)).toEqual({ versions: { a: "ready", b: "live" }, collects: 1 }); await t.finishAllScheduledFunctions(vi.runAllTimers); - expect((await route(t, "b", "/assets/app-a1.js")).asset?.status).toBe(200); expect((await tables(t)).entries).toContain("b/assets/app-a1.js"); }); + test("a mark whose request arrived before another version went live is late, and refused", async () => { + vi.useFakeTimers(); + const t = convexTest(schema, modules); + await uploadVersion(t, "a", site); + vi.advanceTimersByTime(1000); + await uploadVersion(t, "b", site); + // B's code serves when B's mark request arrives. Then A is pushed and marked, and B's mark + // runs last, on replaced code. + const arrivedAt = Date.now(); + vi.advanceTimersByTime(1000); + expect(await markLive(t, "a")).toBe("marked"); + vi.advanceTimersByTime(1000); + expect(await t.mutation(api.lib.markLive, { versionId: "b", arrivedAt })).toBe("superseded"); + await t.finishAllScheduledFunctions(vi.runAllTimers); + expect((await liveness(t)).versions).toEqual({ a: "live", b: "ready" }); + expect((await tables(t)).entries).toContain("a/assets/app-a1.js"); + }); + test("a mark in the same millisecond as the newest is still strictly newer", async () => { vi.useFakeTimers(); const t = convexTest(schema, modules); @@ -265,7 +261,7 @@ describe("markLive", () => { expect((await liveness(t)).versions).toEqual({ b: "live" }); }); - test("two first requests of one version mark it live once", async () => { + test("two marks of one version mark it live once", async () => { vi.useFakeTimers(); const t = convexTest(schema, modules); await uploadVersion(t, "a", site); @@ -373,9 +369,8 @@ describe("collect", () => { const after = await tables(t); expect(after.versions).toEqual([["large", "deleting"]]); expect(after.entries).toHaveLength(1); - // A request between the pages answers 404 and cannot mark the version live. - expect(await route(t, "large", "/0.txt")).toEqual({ state: "deleting", asset: null }); - await expect(markLive(t, "large")).rejects.toThrow("Version large is being deleted."); + // A mark between the pages cannot make the version live. + expect(await markLive(t, "large")).toBe("deleting"); // The next call reads the same version again and ends it. expect(await pendingSteps(t)).toEqual([{ kind: "versions" }]); await runNext(t); @@ -450,164 +445,3 @@ describe("collect", () => { ]); }); }); - -describe("route", () => { - test("a hit has Cloudflare's headers and an ETag; If-None-Match answers 304", async () => { - const t = convexTest(schema, modules); - await uploadVersion(t, "v1", site); - const { state, asset } = await route(t, "v1", "/assets/app-a1.js"); - expect(state).toBe("ready"); - expect(asset?.status).toBe(200); - expect(header(asset, "content-type")).toBe("text/javascript; charset=utf-8"); - expect(header(asset, "cache-control")).toBe("public, max-age=0, must-revalidate"); - expect(header(asset, "cf-cache-status")).toBeUndefined(); - const eTag = header(asset, "etag"); - expect(eTag).toMatch(new RegExp(`^"${await sha256Hex("console.log(1)")}[0-9a-f]{8}"$`)); - expect(asset?.bodyUrl).toEqual(expect.any(String)); - - const revalidated = await route(t, "v1", "/assets/app-a1.js", { "if-none-match": eTag ?? "" }); - expect(revalidated.asset?.status).toBe(304); - expect(revalidated.asset?.bodyUrl).toBeNull(); - }); - - test("the same bytes under two content types have two ETags", async () => { - const t = convexTest(schema, modules); - await uploadVersion(t, "v1", { - "/a.txt": { body: "same", contentType: "text/plain" }, - "/a.js": { body: "same", contentType: "text/javascript" }, - }); - const txt = await route(t, "v1", "/a.txt"); - const js = await route(t, "v1", "/a.js"); - expect(header(txt.asset, "etag")).not.toBe(header(js.asset, "etag")); - expect(header(js.asset, "content-type")).toBe("text/javascript"); - }); - - test("with code, single-page-application answers navigations only", async () => { - const t = convexTest(schema, modules); - await uploadVersion(t, "v1", site, { not_found_handling: "single-page-application" }); - const navigation = await route(t, "v1", "/settings/profile", { "sec-fetch-mode": "navigate" }); - const index = await route(t, "v1", "/"); - expect(navigation.asset?.status).toBe(200); - expect(header(navigation.asset, "etag")).toBe(header(index.asset, "etag")); - - expect(await route(t, "v1", "/settings/profile")).toEqual({ state: "ready", asset: null }); - }); - - test("without code, single-page-application answers every request, as a files-only Worker", async () => { - const t = convexTest(schema, modules); - await uploadVersion(t, "v1", site, { not_found_handling: "single-page-application" }); - const index = await route(t, "v1", "/"); - // No `Sec-Fetch-Mode`, as from curl, a monitor, or a link-preview bot. - const filesOnly = await route(t, "v1", "/about", {}, false); - expect(filesOnly.asset?.status).toBe(200); - expect(header(filesOnly.asset, "content-type")).toBe("text/html; charset=utf-8"); - expect(header(filesOnly.asset, "etag")).toBe(header(index.asset, "etag")); - // With code, the same request is a miss, which the app answers. - expect(await route(t, "v1", "/about", {}, true)).toEqual({ state: "ready", asset: null }); - }); - - test("without code and with html_handling none, / answers index.html through the fallback", async () => { - const t = convexTest(schema, modules); - await uploadVersion(t, "v1", site, { - html_handling: "none", - not_found_handling: "single-page-application", - }); - const { asset } = await route(t, "v1", "/", {}, false); - const index = await route(t, "v1", "/index.html", {}, false); - expect(asset?.status).toBe(200); - expect(header(asset, "etag")).toBe(header(index.asset, "etag")); - }); - - test("another method than GET or HEAD on a file answers 405; on a miss, the code or 404", async () => { - const t = convexTest(schema, modules); - await uploadVersion(t, "v1", site); - for (const hasUserWorker of [true, false]) { - const post = await route(t, "v1", "/index.html", {}, hasUserWorker, "POST"); - expect(post.asset?.status).toBe(405); - expect(post.asset?.bodyUrl).toBeNull(); - } - expect(await route(t, "v1", "/missing", {}, true, "POST")).toEqual({ - state: "ready", - asset: null, - }); - const miss = await route(t, "v1", "/missing", {}, false, "POST"); - expect(miss.asset?.status).toBe(404); - }); - - test("without code, a miss with not_found_handling none answers 404 with no-store", async () => { - const t = convexTest(schema, modules); - await uploadVersion(t, "v1", site); - const miss = await route(t, "v1", "/missing", {}, false); - expect(miss.asset).toEqual({ - status: 404, - headers: [{ name: "cache-control", value: "no-store" }], - bodyUrl: null, - }); - }); - - test("the custom 404 page answers with its body and no-store", async () => { - const t = convexTest(schema, modules); - await uploadVersion(t, "v1", site, { not_found_handling: "404-page" }); - const { asset } = await route(t, "v1", "/missing", { "sec-fetch-mode": "navigate" }); - expect(asset?.status).toBe(404); - expect(asset?.bodyUrl).toEqual(expect.any(String)); - expect(header(asset, "cache-control")).toBe("no-store"); - const filesOnly = await route(t, "v1", "/missing", {}, false); - expect(filesOnly.asset?.status).toBe(404); - expect(header(filesOnly.asset, "etag")).toBe(header(asset, "etag")); - }); - - test("a file that is gone from storage answers 404 with no-store", async () => { - const t = convexTest(schema, modules); - await uploadVersion(t, "v1", site); - await t.run(async (ctx) => { - const entry = await ctx.db - .query("entries") - .withIndex("by_version_path", (q) => q.eq("versionId", "v1").eq("path", "/index.html")) - .unique(); - if (entry !== null) await ctx.storage.delete(entry.storageId); - }); - expect(await route(t, "v1", "/")).toEqual({ - state: "ready", - asset: { - status: 404, - headers: [{ name: "cache-control", value: "no-store" }], - bodyUrl: null, - }, - }); - }); - - test("a _headers rule applies", async () => { - const t = convexTest(schema, modules); - await uploadVersion(t, "v1", site, { - headers: { - version: 2, - rules: { "/assets/*": { set: { "Cache-Control": "public, max-age=31536000, immutable" } } }, - }, - }); - const { asset } = await route(t, "v1", "/assets/app-a1.js"); - expect(header(asset, "cache-control")).toBe("public, max-age=31536000, immutable"); - }); - - test("a _redirects rule applies", async () => { - const t = convexTest(schema, modules); - await uploadVersion(t, "v1", site, { - redirects: { - version: 1, - staticRules: { "/old": { status: 301, to: "/", lineNumber: 1 } }, - rules: {}, - }, - }); - const { asset } = await route(t, "v1", "/old?x=1"); - expect(asset?.status).toBe(301); - expect(header(asset, "location")).toBe("/?x=1"); - expect(asset?.bodyUrl).toBeNull(); - }); - - test("a version that is uploading or does not exist reports its state", async () => { - const t = convexTest(schema, modules); - await createVersion(t, "v1"); - expect(await route(t, "v1", "/")).toEqual({ state: "uploading", asset: null }); - expect(await route(t, "v2", "/")).toEqual({ state: null, asset: null }); - }); -}); diff --git a/packages/convex-hosting/src/component/lib.ts b/packages/convex-hosting/src/component/lib.ts index f4013592..0bb960a2 100644 --- a/packages/convex-hosting/src/component/lib.ts +++ b/packages/convex-hosting/src/component/lib.ts @@ -1,30 +1,16 @@ import { ConvexError, v } from "convex/values"; import { z } from "zod"; -import { Analytics } from "../workers-sdk/packages/workers-shared/asset-worker/src/analytics.js"; -import { normalizeConfiguration } from "../workers-sdk/packages/workers-shared/asset-worker/src/configuration.js"; -import { - canFetch, - handleRequest, -} from "../workers-sdk/packages/workers-shared/asset-worker/src/handler.js"; -import { mockJaegerBinding } from "../workers-sdk/packages/workers-shared/utils/tracing.js"; import { AssetConfigSchema } from "../workers-sdk/packages/workers-shared/utils/types.js"; import { internal } from "./_generated/api.js"; -import type { Doc, Id } from "./_generated/dataModel.js"; +import type { Id } from "./_generated/dataModel.js"; import { internalAction, internalMutation, internalQuery, mutation, - query, type QueryCtx, } from "./_generated/server.js"; -/** - * The compatibility date of Cloudflare's handler. From 2025-04-01 on, Cloudflare applies - * `not_found_handling` to a request with `Sec-Fetch-Mode: navigate` when a Worker exists. - */ -const COMPATIBILITY_DATE = "2025-04-01"; - /** * A version that never became live, and a stored file that no entry references, are garbage once * they are a day old: a failed deploy leaves them, and an upload in progress is younger. This age @@ -247,37 +233,50 @@ export const finishVersion = internalMutation({ }); /** - * Marks a `ready` version `live` and schedules `collect`. `serveSite` calls it at each request that - * finds the version `ready`. An older upload never goes live over a newer one: the mark does nothing - * when a live version was created after this one. So a request that started on replaced code, and - * reaches its lookup or its mark after the new code's first request marked the new version, cannot - * make the old version newest, and `collect` cannot delete the new version's files. A version that - * is already live stays as it is, so concurrent first requests are fine. + * Marks a `ready` version `live` and schedules `collect`, and says what it did. `serveSite` calls + * it for the request that the CLI sends after the push, with the site's mark token, so only the + * code that serves marks its own version. A version that is already live stays as it is, so a + * repeated mark is fine. It never throws, so the CLI reads every outcome from the answer. + * + * The request may still run when its code is replaced, so two rules refuse a mark of replaced code. + * An older upload never goes live over a newer one: the mark does nothing when a live version was + * created after this one. And a mark is late when another version went live after its request + * arrived, at `arrivedAt`: that version's code has served since. `arrivedAt` is the HTTP action's + * clock and the live time is this mutation's, so the rule holds as far as the two agree. * - * Precondition: deploys to one deployment do not overlap. When two overlap and the older upload is - * pushed last, its requests look like requests of replaced code: its version serves but stays - * `ready`, and nothing is deleted until the next deploy. + * Precondition: deploys to one deployment do not overlap. When two overlap, the mark of the + * version that serves may be refused: it then stays `ready`, and nothing is deleted until the next + * deploy. The limits are in `docs/design.md`, "Stated, not solved". */ export const markLive = mutation({ - args: { versionId: v.string() }, - returns: v.null(), - handler: async (ctx, { versionId }) => { - const version = await getVersionOrThrow(ctx, versionId); - if (version.state.kind === "live") return null; - if (version.state.kind === "uploading") { - throw new ConvexError(`Version ${versionId} is still uploading.`); - } - if (version.state.kind === "deleting") { - throw new ConvexError(`Version ${versionId} is being deleted.`); - } + args: { + versionId: v.string(), + /** `Date.now()` when the mark's request reached the code that serves. */ + arrivedAt: v.number(), + }, + returns: v.union( + /** It was `ready` and is now the newest live version. */ + v.literal("marked"), + v.literal("live"), + /** A live version was created after it, or went live after `arrivedAt`: it stays as it is. */ + v.literal("superseded"), + v.literal("uploading"), + v.literal("deleting"), + v.literal("missing"), + ), + handler: async (ctx, { versionId, arrivedAt }) => { + const version = await getVersion(ctx, versionId); + if (version === null) return "missing"; + if (version.state.kind !== "ready") return version.state.kind; const newest = await getNewestLive(ctx); - if (newest !== null && newest.createdAt > version._creationTime) return null; + if (newest !== null && newest.createdAt > version._creationTime) return "superseded"; + if (newest !== null && newest.at > arrivedAt) return "superseded"; // Later than every live `at`, also within one millisecond or when the clock moves back, so that // `at` follows creation order and `collect` deletes the versions live before this one. const at = newest === null ? Date.now() : Math.max(Date.now(), newest.at + 1); await ctx.db.patch("versions", version._id, { state: { kind: "live", at } }); await ctx.scheduler.runAfter(0, internal.lib.collect, { step: { kind: "files" } }); - return null; + return "marked"; }, }); @@ -380,7 +379,7 @@ export const collect = internalMutation({ for (const entry of entries) await ctx.db.delete("entries", entry._id); if (entries.length === budget) { // The version may have more entries: the next call reads it again. Until its row goes, - // it is `deleting`, so that no request serves it or marks it live between the pages. + // it is `deleting`, so that no mark makes it live between the pages. if (state.kind !== "deleting") { await ctx.db.patch("versions", version._id, { state: { kind: "deleting" } }); } @@ -413,130 +412,9 @@ function advance( : { at: document._creationTime, seen: [document._id] }; } -const routeHeaders = v.record(v.string(), v.string()); - -/** - * Runs Cloudflare's asset handler for one request against one version. `state` is the kind of the - * version's state, or `null` when the version does not exist. `asset` is `null` when the version is - * uploading, being deleted, or does not exist, or when no asset answers. - * - * `hasUserWorker` is Cloudflare's `has_user_worker`: whether the app has code that answers a miss. - * With it, Cloudflare's router asks `canFetch` first, which keeps `not_found_handling` for - * navigations only, and the app answers the other misses. Without it, every request goes to - * `handleRequest`, so `not_found_handling` applies to all of them, and an asset always answers. - */ -export const route = query({ - args: { - versionId: v.string(), - method: v.string(), - url: v.string(), - headers: routeHeaders, - hasUserWorker: v.boolean(), - }, - returns: v.object({ - state: v.union( - v.literal("uploading"), - v.literal("ready"), - v.literal("live"), - v.literal("deleting"), - v.null(), - ), - asset: v.union( - v.null(), - v.object({ - status: v.number(), - headers: v.array(v.object({ name: v.string(), value: v.string() })), - /** The storage URL of the body, when the response has one. */ - bodyUrl: v.union(v.string(), v.null()), - }), - ), - }), - handler: async (ctx, { versionId, method, url, headers, hasUserWorker }) => { - const version = await getVersion(ctx, versionId); - if (version === null) return { state: null, asset: null }; - const state = version.state.kind; - if (state === "uploading" || state === "deleting") { - return { state, asset: null }; - } - - const configuration = normalizeConfiguration({ - ...AssetConfigSchema.parse(JSON.parse(version.config)), - compatibility_date: COMPATIBILITY_DATE, - }); - const request = new Request(url, { method, headers }); - const env = { JAEGER: mockJaegerBinding() }; - - // `exists` returns an ETag; `getByETag` gets the entry back for that ETag. - const found = new Map>(); - const exists = async (pathname: string) => { - const entry = await getEntry(ctx, versionId, pathname); - if (entry === null) return null; - const eTag = entry.sha256 + (await shortHash(entry.contentType ?? "")); - found.set(eTag, entry); - return eTag; - }; - let bodyEntry: Doc<"entries"> | undefined; - const getByETag = async (eTag: string) => { - bodyEntry = found.get(eTag); - if (bodyEntry === undefined) throw new Error(`No entry has the ETag ${eTag}.`); - return { - // `serveSite` replaces this placeholder with the stored file. - readableStream: new ReadableStream(), - contentType: bodyEntry.contentType, - cacheStatus: "MISS" as const, - }; - }; - - if (hasUserWorker && !(await canFetch(request, env, configuration, exists))) { - return { state, asset: null }; - } - const response = await handleRequest( - request, - env, - configuration, - exists, - getByETag, - new Analytics(), - ); - // It describes Cloudflare's cache, which does not exist here. - response.headers.delete("CF-Cache-Status"); - // The deployment's Cloudflare front caches 404 answers on static paths. - if (response.status === 404) response.headers.set("Cache-Control", "no-store"); - - let bodyUrl: string | null = null; - if (response.body !== null && bodyEntry !== undefined) { - bodyUrl = await ctx.storage.getUrl(bodyEntry.storageId); - // The file is gone from storage. As in `serveSite` when storage answers 404, the answer must - // not stay in a cache. - if (bodyUrl === null) { - return { - state, - asset: { status: 404, headers: [{ name: "cache-control", value: "no-store" }], bodyUrl }, - }; - } - } - return { - state, - asset: { - status: response.status, - headers: [...response.headers].map(([name, value]) => ({ name, value })), - bodyUrl, - }, - }; - }, -}); - /** Convex's `_storage` table holds the sha256 in base64; entries hold it in hex. */ function base64ToHex(base64: string) { return Array.from(atob(base64), (char) => char.charCodeAt(0).toString(16).padStart(2, "0")).join( "", ); } - -/** The first 8 hex digits of the SHA-256 of `text`. */ -async function shortHash(text: string) { - const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text)); - return Array.from(new Uint8Array(digest, 0, 4), (byte) => - byte.toString(16).padStart(2, "0"), - ).join(""); -} diff --git a/packages/convex-hosting/src/component/schema.ts b/packages/convex-hosting/src/component/schema.ts index 723b0dae..5415e30e 100644 --- a/packages/convex-hosting/src/component/schema.ts +++ b/packages/convex-hosting/src/component/schema.ts @@ -6,7 +6,7 @@ export default defineSchema({ versions: defineTable({ versionId: v.string(), /** - * `live` carries the time the first request of the version's pushed code marked it live, so a + * `live` carries the time the version's pushed code marked it live, at its deploy's mark, so a * version cannot have a live time without being live. */ state: v.union( @@ -38,7 +38,7 @@ export default defineSchema({ sha256: v.string(), /** * The type belongs to the path, not to the bytes: paths with identical bytes share one stored - * file but keep their own types, and `route` serves without reading `_storage`. Absent when + * file but keep their own types, and the site's manifest carries each type. Absent when * the `mime` package has no type for the file name. */ contentType: v.optional(v.string()), diff --git a/packages/convex-hosting/src/workers-sdk/UPSTREAM b/packages/convex-hosting/src/workers-sdk/UPSTREAM index 7b51b863..51eff88b 100644 --- a/packages/convex-hosting/src/workers-sdk/UPSTREAM +++ b/packages/convex-hosting/src/workers-sdk/UPSTREAM @@ -2,7 +2,7 @@ Copied from https://github.com/cloudflare/workers-sdk, at the paths the files ha packages/workers-shared, and the test cases of fixtures/workers-shared-asset-config. License: MIT OR Apache-2.0 (LICENSE-MIT, LICENSE-APACHE). commit: 855812b79fcb8ee77cac5ab0b01ebc167741951d -synced: 2026-10-16 +synced: 2026-11-10 Run `node scripts/sync-workers-sdk.ts []` from packages/convex-hosting to update. Relative import and export specifiers without an extension get .js, for Node's ESM loader. diff --git a/packages/convex-hosting/src/workers-sdk/fixtures/shared/src/run-wrangler-long-lived.ts b/packages/convex-hosting/src/workers-sdk/fixtures/shared/src/run-wrangler-long-lived.ts index 64d5f8b9..978d2962 100644 --- a/packages/convex-hosting/src/workers-sdk/fixtures/shared/src/run-wrangler-long-lived.ts +++ b/packages/convex-hosting/src/workers-sdk/fixtures/shared/src/run-wrangler-long-lived.ts @@ -96,11 +96,11 @@ export default app; `import { httpRouter } from "convex/server"; import { routeAll } from "@samebase/convex-hosting"; import { components } from "./_generated/api.js"; -import { versionId } from "../.convex-hosting/version.js"; +import { assets } from "../.convex-hosting/version.js"; const http = httpRouter(); -routeAll(http, components.hosting, versionId); +routeAll({ http, component: components.hosting, assets }); export default http; `, diff --git a/packages/convex-hosting/src/workers-sdk/packages/workers-shared/asset-worker/src/assets-manifest.ts b/packages/convex-hosting/src/workers-sdk/packages/workers-shared/asset-worker/src/assets-manifest.ts new file mode 100644 index 00000000..6499707d --- /dev/null +++ b/packages/convex-hosting/src/workers-sdk/packages/workers-shared/asset-worker/src/assets-manifest.ts @@ -0,0 +1,125 @@ +import { + CONTENT_HASH_OFFSET, + CONTENT_HASH_SIZE, + ENTRY_SIZE, + HEADER_SIZE, + PATH_HASH_OFFSET, + PATH_HASH_SIZE, +} from "../../utils/constants.js"; + +export class AssetsManifest { + private data: Uint8Array; + + constructor(data: ArrayBuffer) { + this.data = new Uint8Array(data); + } + + async get(pathname: string) { + const pathHash = await hashPath(pathname); + const entry = binarySearch(this.data, pathHash); + return entry ? Uint8ToHexString(entry) : null; + } +} + +export const hashPath = async (path: string) => { + const encoder = new TextEncoder(); + const data = encoder.encode(path); + const hashBuffer = await crypto.subtle.digest( + "SHA-256", + data.buffer as ArrayBuffer + ); + return new Uint8Array(hashBuffer, 0, PATH_HASH_SIZE); +}; + +/** + * Search for an entry with the given hash path. + * + * @param manifest the manifest bytes + * @param pathHash the path hash to find in the manifest + * @returns The content hash when the entry is found and `false` otherwise + */ +export const binarySearch = ( + manifest: Uint8Array, + pathHash: Uint8Array +): Uint8Array | false => { + if (pathHash.byteLength !== PATH_HASH_SIZE) { + throw new TypeError( + `Search value should have a length of ${PATH_HASH_SIZE}` + ); + } + + const numberOfEntries = (manifest.byteLength - HEADER_SIZE) / ENTRY_SIZE; + + if (numberOfEntries === 0) { + return false; + } + + let lowIndex = 0; + let highIndex = numberOfEntries - 1; + + while (lowIndex <= highIndex) { + const middleIndex = (lowIndex + highIndex) >> 1; + + const cmp = comparePathHashWithEntry(pathHash, manifest, middleIndex); + + if (cmp < 0) { + highIndex = middleIndex - 1; + continue; + } + + if (cmp > 0) { + lowIndex = middleIndex + 1; + continue; + } + + return new Uint8Array( + manifest.buffer, + HEADER_SIZE + middleIndex * ENTRY_SIZE + CONTENT_HASH_OFFSET, + CONTENT_HASH_SIZE + ); + } + + return false; +}; + +/** + * Compares a search value with a path hash in the manifest + * + * @param searchValue a `Uint8Array` of size `PATH_HASH_SIZE` + * @param manifest the manifest bytes + * @param entryIndex the index in the manifest of the entry to compare + */ +function comparePathHashWithEntry( + searchValue: Uint8Array, + manifest: Uint8Array, + entryIndex: number +) { + let pathHashOffset = HEADER_SIZE + entryIndex * ENTRY_SIZE + PATH_HASH_OFFSET; + for (let offset = 0; offset < PATH_HASH_SIZE; offset++, pathHashOffset++) { + const s = searchValue[offset]; + const e = manifest[pathHashOffset]; + if (s === undefined || e === undefined) { + throw new TypeError( + `Unexpected undefined value at offset ${offset} during path hash comparison` + ); + } + if (s < e) { + return -1; + } + if (s > e) { + return 1; + } + } + + return 0; +} + +/** + * Converts an Uint8Array to an hex string + * + * @param array The content hash + * @returns padded hex string + */ +const Uint8ToHexString = (array: Uint8Array) => { + return [...array].map((b) => b.toString(16).padStart(2, "0")).join(""); +}; diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index f489e2a0..b56d40d5 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -200,6 +200,9 @@ catalogs: convex-test: specifier: 0.0.61 version: 0.0.61 + fast-check: + specifier: 4.10.2 + version: 4.10.2 ignore: specifier: 7.0.12 version: 7.0.12 @@ -482,6 +485,9 @@ importers: convex-test: specifier: 'catalog:' version: 0.0.61(convex@1.46.0(react@19.3.0)) + fast-check: + specifier: 'catalog:' + version: 4.10.2 typescript: specifier: 'catalog:' version: 7.0.2 @@ -2623,6 +2629,10 @@ packages: exsolve@1.1.3: resolution: {integrity: sha512-kuzL9zherLQoqDeQaS55AiiIg1kb4KYXaSusTtgZTPlvKP2gGCI82LNmBNh5RjDVUXIcmgx+/Mx7vPwRzBbhJA==} + fast-check@4.10.2: + resolution: {integrity: sha512-iK2f+YrcmoeGqk6fA0ea2bptcu/itMIm4NfEozq6N25+aG6h7s5HZbB/k1aV7b5w5sFLMCbbtRUsTVR+BgC3xw==} + engines: {node: '>=12.17.0'} + fast-deep-equal@3.1.3: resolution: {integrity: sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==} @@ -3008,6 +3018,9 @@ packages: resolution: {integrity: sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==} engines: {node: '>=6'} + pure-rand@8.4.2: + resolution: {integrity: sha512-vvuOGgcuPJAirlHvuQw1TrOiw7ptaIXXmIbNuiNOY6lNGJJH49PQ1Kj4nd783nPdQhQdicgOjVI2yI/9BD6/Ng==} + pvtsutils@1.3.6: resolution: {integrity: sha512-PLgQXQ6H2FWCaeRak8vvk1GW462lMxB5s3Jm673N82zI4vqtVUPuZdffdZbPDFRoU8kAhItWFtPCWiPpp4/EDg==} @@ -5211,6 +5224,10 @@ snapshots: exsolve@1.1.3: {} + fast-check@4.10.2: + dependencies: + pure-rand: 8.4.2 + fast-deep-equal@3.1.3: {} fast-json-stable-stringify@2.1.0: {} @@ -5544,6 +5561,8 @@ snapshots: punycode@2.3.1: {} + pure-rand@8.4.2: {} + pvtsutils@1.3.6: dependencies: tslib: 2.8.1 diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index b1dc42f5..0703b77f 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -17,6 +17,7 @@ catalog: ignore: 7.0.12 mime: 4.1.1 convex-test: 0.0.61 + fast-check: 4.10.2 react: 19.3.0 react-dom: 19.3.0 typescript: 7.0.2