diff --git a/INTEGRATION.md b/INTEGRATION.md index 14d7038..1a5f22e 100644 --- a/INTEGRATION.md +++ b/INTEGRATION.md @@ -286,13 +286,17 @@ npx @convex-dev/static-hosting upload [options] The complete manifest is staged in small, portable command-line chunks after all uploads finish. One final mutation atomically publishes the manifest and -deployment settings. Old component storage is removed immediately afterward in -bounded cleanup transactions. A failed attempt leaves the previous deployment -live and removes only new files that are not referenced by the live manifest. -The supported maximum is 1,800 files and 2 MiB of serialized manifest metadata, -which keeps the atomic switch below Convex transaction limits. Upload URLs are -generated in bounded batches. Later uploads recover component files and staging -records left unreferenced for more than 24 hours after an interrupted CLI. +deployment settings. Replaced files stay in component storage for at least seven +days. A request for a missing file with an extension, except HTML, gets the +newest replaced copy, so pages that are already open can still load their +scripts. Files remain available until a later upload removes expired files in +bounded cleanup transactions. Legacy CDN blobs are not retained. A failed +attempt leaves the previous deployment live and removes only new files that are +not referenced by the live manifest. The supported maximum is 1,800 files and 2 +MiB of serialized manifest metadata, which keeps the atomic switch below Convex +transaction limits. Upload URLs are generated in bounded batches. Later uploads +recover component files and staging records left unreferenced for more than 24 +hours after an interrupted CLI. Convex HTTP routers currently expose GET but not HEAD routes. Uptime monitors must use a lightweight GET request. diff --git a/README.md b/README.md index 4ce1f0d..bc28e70 100644 --- a/README.md +++ b/README.md @@ -18,8 +18,10 @@ alongside your backend. new version is ready. - ๐Ÿ”’ **Authenticated uploads:** uploads go through the Convex CLI's authenticated session; there's no public upload endpoint. -- ๐Ÿงน **Automatic cleanup:** files from previous 0.2.x deployments are garbage - collected on every deploy. The migration guide covers one-time v1 cleanup. +- ๐Ÿงน **Automatic cleanup:** non-HTML files from previous 0.2.x deployments stay + available for at least seven days, so open pages keep working, and are then + garbage collected on a later deploy. The migration guide covers one-time v1 + cleanup. https://github.com/user-attachments/assets/5eaf781f-87da-4292-9f96-38070c86cd39 @@ -242,8 +244,10 @@ npx @convex-dev/static-hosting upload [options] Each upload is published atomically, so visitors never see a page that refers to assets that are not available yet. Failed uploads leave the previous deployment -live, and old files are cleaned up safely. See [INTEGRATION.md](./INTEGRATION.md) -for upload limits and lifecycle details. +live. Replaced non-HTML files stay available for at least seven days, so pages +that are already open can still load their scripts. A later upload removes +expired files. See [INTEGRATION.md](./INTEGRATION.md) for upload limits and +lifecycle details. Convex HTTP routes currently support GET but not HEAD. Configure uptime checks to make a lightweight GET request rather than a HEAD request. diff --git a/src/component/lib.test.ts b/src/component/lib.test.ts index e3334e8..69e83b1 100644 --- a/src/component/lib.test.ts +++ b/src/component/lib.test.ts @@ -299,6 +299,16 @@ describe("component lib", () => { expect(await ctx.storage.get(oldStorageId)).not.toBeNull(); expect(await ctx.storage.get(newStorageId)).not.toBeNull(); }); + // The replaced file is kept for seven days, so open pages can still load it. + expect(await t.mutation(internal.lib.cleanupPendingStorage, {})).toEqual({ + processed: 0, + deleted: 0, + needsAnotherPass: false, + }); + await t.run(async (ctx) => { + expect(await ctx.storage.get(oldStorageId)).not.toBeNull(); + }); + vi.advanceTimersByTime(7 * 24 * 60 * 60 * 1000); expect(await t.mutation(internal.lib.cleanupPendingStorage, {})).toEqual({ processed: 1, deleted: 1, @@ -809,6 +819,92 @@ describe("component lib", () => { ).rejects.toThrow("Duplicate asset path"); }); + describe("replaced files", () => { + const sevenDays = 7 * 24 * 60 * 60 * 1000; + + async function publish( + t: ReturnType, + deploymentId: string, + paths: string[], + ) { + const assets = await t.run(async (ctx) => { + const result = []; + for (const path of ["/index.html", ...paths]) { + result.push({ + path, + storageId: await ctx.storage.store(new Blob([deploymentId + path])), + contentType: path.endsWith(".html") + ? "text/html; charset=utf-8" + : "application/javascript; charset=utf-8", + deploymentId, + }); + } + return result; + }); + await t.mutation(internal.lib.stageAssets, { assets }); + await t.mutation(internal.lib.publishDeployment, { + currentDeploymentId: deploymentId, + expectedAssetCount: assets.length, + }); + return new Map(assets.map((asset) => [asset.path, asset.storageId])); + } + + test("serves a replaced file, but never replaced HTML, for seven days", async () => { + const t = initConvexTest(); + const a = await publish(t, "deploy-a", [ + "/assets/app-A1b2C3d4.js", + "/about.html", + ]); + const b = await publish(t, "deploy-b", ["/assets/app-E5f6G7h8.js"]); + + const resolve = (path: string) => + t.query(api.lib.resolveAssetForHttp, { path }); + expect(await resolve("/assets/app-A1b2C3d4.js")).toMatchObject({ + etag: `"${a.get("/assets/app-A1b2C3d4.js")}"`, + }); + expect(await resolve("/about.html")).toBeNull(); + // Paths without an extension still get the current SPA shell. + expect(await resolve("/dashboard")).toMatchObject({ + etag: `"${b.get("/index.html")}"`, + }); + + vi.advanceTimersByTime(sevenDays); + await t.mutation(internal.lib.cleanupPendingStorage, {}); + expect(await resolve("/assets/app-A1b2C3d4.js")).toBeNull(); + await t.run(async (ctx) => { + expect( + await ctx.storage.get(a.get("/assets/app-A1b2C3d4.js")!), + ).toBeNull(); + }); + }); + + test("no cleanup deletes a replaced file before it expires", async () => { + const t = initConvexTest(); + const a = await publish(t, "deploy-a", ["/assets/app-A1b2C3d4.js"]); + await publish(t, "deploy-b", []); + const retired = a.get("/assets/app-A1b2C3d4.js")!; + // Old enough for every cleanup to consider it, young enough to keep. + vi.advanceTimersByTime(2 * 24 * 60 * 60 * 1000); + + await t.mutation(internal.lib.cleanupPendingStorage, {}); + await t.mutation(internal.lib.cleanupUnreferencedStorage, {}); + expect( + await t.mutation(internal.lib.deleteUploadedFiles, { + storageIds: [retired], + }), + ).toMatchObject({ stillReferenced: 1 }); + + await t.run(async (ctx) => { + expect(await ctx.storage.get(retired)).not.toBeNull(); + }); + expect( + await t.query(api.lib.resolveAssetForHttp, { + path: "/assets/app-A1b2C3d4.js", + }), + ).not.toBeNull(); + }); + }); + describe("resolveAsset", () => { async function seedIndex(t: ReturnType) { await t.mutation(internal.lib.recordAsset, { diff --git a/src/component/lib.ts b/src/component/lib.ts index 6923814..c17332f 100644 --- a/src/component/lib.ts +++ b/src/component/lib.ts @@ -1,4 +1,4 @@ -import { v } from "convex/values"; +import { v, type Infer } from "convex/values"; import { internalMutation, internalQuery, @@ -7,7 +7,7 @@ import { type QueryCtx, } from "./_generated/server.js"; import type { Id } from "./_generated/dataModel.js"; -import { hasFileExtension } from "./serving.js"; +import { hasFileExtension, isHtmlContentType } from "./serving.js"; const staticAssetValidator = v.object({ _id: v.id("staticAssets"), @@ -19,6 +19,15 @@ const staticAssetValidator = v.object({ deploymentId: v.string(), }); +const resolvedAssetValidator = v.union( + staticAssetValidator, + staticAssetValidator.omit("_id").extend({ + _id: v.id("retiredAssets"), + storageId: v.id("_storage"), + expiresAt: v.number(), + }), +); + const deploymentInfoValidator = v.object({ _id: v.id("deploymentInfo"), _creationTime: v.number(), @@ -37,6 +46,7 @@ const MAINTENANCE_PAGE_LIMIT = 256; // staged lookups use an explicit budget below Convex's 4,096 read limit. const STORAGE_SCAN_LIMIT = 2000; const ABANDONED_UPLOAD_AGE_MS = 24 * 60 * 60 * 1000; +const RETIRED_ASSET_AGE_MS = 7 * 24 * 60 * 60 * 1000; const httpAssetValidator = v.object({ storageUrl: v.optional(v.string()), @@ -55,14 +65,25 @@ async function resolveAssetDocument( ctx: QueryCtx, path: string, spaFallbackOverride?: boolean, -) { +): Promise | null> { const exact = await ctx.db .query("staticAssets") .withIndex("by_path", (q) => q.eq("path", path)) .unique(); if (exact) return exact; - if (hasFileExtension(path)) return null; + if (hasFileExtension(path)) { + // A file the current deployment replaced stays reachable for a while, so + // pages that are already open can still load their scripts. Old HTML never + // comes back. + const retired = await ctx.db + .query("retiredAssets") + .withIndex("by_path", (q) => q.eq("path", path)) + .order("desc") + .first(); + if (retired && !isHtmlContentType(retired.contentType)) return retired; + return null; + } const info = await ctx.db.query("deploymentInfo").first(); const spaFallback = spaFallbackOverride ?? info?.spaFallback ?? true; @@ -75,6 +96,11 @@ async function resolveAssetDocument( } async function deleteStorageFile(ctx: MutationCtx, storageId: Id<"_storage">) { + const retiredReference = await ctx.db + .query("retiredAssets") + .withIndex("by_storageId", (q) => q.eq("storageId", storageId)) + .first(); + if (retiredReference) return false; // A v2 component mounted with the old `selfHosting` name can inherit v1 rows // containing app-owned storage IDs. They are deliberately invisible in the // component namespace. Checking metadata avoids relying on backend error text @@ -200,7 +226,7 @@ export const getByPath = internalQuery({ // index.html asset. Doing the fallback here keeps it to a single query. export const resolveAsset = internalQuery({ args: { path: v.string() }, - returns: v.union(staticAssetValidator, v.null()), + returns: v.union(resolvedAssetValidator, v.null()), handler: async (ctx, { path }) => { return await resolveAssetDocument(ctx, path); }, @@ -305,6 +331,16 @@ export const cleanupPendingStorage = internalMutation({ limit ?? MAINTENANCE_PAGE_LIMIT, MAINTENANCE_PAGE_LIMIT, ); + const expired = await ctx.db + .query("retiredAssets") + .withIndex("by_expiresAt", (q) => q.lte("expiresAt", Date.now())) + .take(batchLimit); + for (const asset of expired) { + await ctx.db.insert("pendingStorageCleanup", { + storageId: asset.storageId, + }); + await ctx.db.delete("retiredAssets", asset._id); + } const entries = await ctx.db .query("pendingStorageCleanup") .take(batchLimit); @@ -332,7 +368,8 @@ export const cleanupPendingStorage = internalMutation({ return { processed: entries.length, deleted, - needsAnotherPass: entries.length === batchLimit, + needsAnotherPass: + entries.length === batchLimit || expired.length === batchLimit, }; }, }); @@ -357,7 +394,11 @@ export const deleteUploadedFiles = internalMutation({ let alreadyMissing = 0; let stillReferenced = 0; for (const storageId of storageIds) { - if (referencedStorageIds.has(storageId)) { + const retiredReference = await ctx.db + .query("retiredAssets") + .withIndex("by_storageId", (q) => q.eq("storageId", storageId)) + .first(); + if (referencedStorageIds.has(storageId) || retiredReference) { stillReferenced++; continue; } @@ -570,16 +611,20 @@ export const cleanupUnreferencedStorage = internalMutation({ } scanned++; if (liveStorageIds.has(file._id)) continue; - if (stagedLookups >= stagedLookupBudget) { + if (stagedLookups + 2 > stagedLookupBudget) { stoppedForReadBudget = true; break; } - stagedLookups++; + stagedLookups += 2; const stagedReference = await ctx.db .query("stagedAssets") .withIndex("by_storageId", (q) => q.eq("storageId", file._id)) .first(); - if (!stagedReference) { + const retiredReference = await ctx.db + .query("retiredAssets") + .withIndex("by_storageId", (q) => q.eq("storageId", file._id)) + .first(); + if (!stagedReference && !retiredReference) { await ctx.storage.delete(file._id); deleted++; } @@ -589,8 +634,9 @@ export const cleanupUnreferencedStorage = internalMutation({ deleted, needsAnotherPass: deleted === deleteLimit || - stoppedForReadBudget || - (deleted > 0 && files.length === STORAGE_SCAN_LIMIT), + // Without deletes, another pass would inspect the same protected prefix. + (deleted > 0 && + (stoppedForReadBudget || files.length === STORAGE_SCAN_LIMIT)), }; }, }); @@ -752,9 +798,25 @@ export const publishDeployment = internalMutation({ `The old and new manifests contain more than ${MAX_PUBLISH_MANIFEST_READS} rows combined. Reduce the new build or clean up the legacy manifest before migrating.`, ); } + const retiredAssets = oldAssets.flatMap((asset) => { + if (asset.storageId !== undefined && asset.blobId === undefined) { + return [ + { + _id: asset._id, + path: asset.path, + storageId: asset.storageId, + contentType: asset.contentType, + deploymentId: asset.deploymentId, + }, + ]; + } + return []; + }); + const retiredIds = new Set(retiredAssets.map((asset) => asset._id)); const blobIds: string[] = []; const storageIds = new Set>(); for (const asset of oldAssets) { + if (retiredIds.has(asset._id)) continue; if (asset.blobId) blobIds.push(asset.blobId); if (asset.storageId) storageIds.add(asset.storageId); } @@ -764,6 +826,7 @@ export const publishDeployment = internalMutation({ blobIds.length + assets.length + stagedAssets.length + + retiredAssets.length + 2; if (plannedDocumentWrites > MAX_PUBLISH_DOCUMENT_WRITES) { throw new Error( @@ -775,6 +838,13 @@ export const publishDeployment = internalMutation({ await ctx.db.delete("staticAssets", asset._id); } + for (const { _id, ...asset } of retiredAssets) { + await ctx.db.insert("retiredAssets", { + ...asset, + expiresAt: Date.now() + RETIRED_ASSET_AGE_MS, + }); + } + for (const asset of assets) { await ctx.db.insert("staticAssets", { path: asset.path, diff --git a/src/component/schema.ts b/src/component/schema.ts index f2684f2..ecbe2ff 100644 --- a/src/component/schema.ts +++ b/src/component/schema.ts @@ -13,6 +13,20 @@ export default defineSchema({ .index("by_deploymentId", ["deploymentId"]) .index("by_storageId", ["storageId"]), + // Publication moves replaced storage files here. Missing non-HTML paths with + // an extension can still resolve to these files. A later upload removes them + // after expiresAt, at least seven days after replacement. + retiredAssets: defineTable({ + path: v.string(), + storageId: v.id("_storage"), + contentType: v.string(), + deploymentId: v.string(), + expiresAt: v.number(), + }) + .index("by_path", ["path"]) + .index("by_storageId", ["storageId"]) + .index("by_expiresAt", ["expiresAt"]), + // Uploads stage their manifest in small chunks because the Convex CLI takes // function arguments on the command line. Only publishDeployment copies a // complete staged manifest into staticAssets, so partial uploads are never