Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 11 additions & 7 deletions INTEGRATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
12 changes: 8 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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.
Expand Down
96 changes: 96 additions & 0 deletions src/component/lib.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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<typeof initConvexTest>,
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<typeof initConvexTest>) {
await t.mutation(internal.lib.recordAsset, {
Expand Down
94 changes: 82 additions & 12 deletions src/component/lib.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { v } from "convex/values";
import { v, type Infer } from "convex/values";
import {
internalMutation,
internalQuery,
Expand All @@ -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"),
Expand All @@ -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(),
Expand All @@ -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()),
Expand All @@ -55,14 +65,25 @@ async function resolveAssetDocument(
ctx: QueryCtx,
path: string,
spaFallbackOverride?: boolean,
) {
): Promise<Infer<typeof resolvedAssetValidator> | 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;
Expand All @@ -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
Expand Down Expand Up @@ -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);
},
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -332,7 +368,8 @@ export const cleanupPendingStorage = internalMutation({
return {
processed: entries.length,
deleted,
needsAnotherPass: entries.length === batchLimit,
needsAnotherPass:
entries.length === batchLimit || expired.length === batchLimit,
};
},
});
Expand All @@ -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;
}
Expand Down Expand Up @@ -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++;
}
Expand All @@ -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)),
};
},
});
Expand Down Expand Up @@ -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<Id<"_storage">>();
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);
}
Expand All @@ -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(
Expand All @@ -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,
Expand Down
14 changes: 14 additions & 0 deletions src/component/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading