Open source CapCut alternative.
TypeScript
feat(site): publishing renders the post before it answers
David Le9db7b0e2bd74
diff --git a/site/src/app/api/su/blog/posts/[id]/images/remove/route.ts b/site/src/app/api/su/blog/posts/[id]/images/remove/route.tsindex 5f8f0a04..305f01f7 100644--- a/site/src/app/api/su/blog/posts/[id]/images/remove/route.ts+++ b/site/src/app/api/su/blog/posts/[id]/images/remove/route.ts@@ -2,7 +2,7 @@ import { NextResponse } from "next/server";import { z } from "zod";import { adminPost } from "@/lib/blog/admin";-import { revalidateBlog } from "@/lib/blog/revalidate";+import { revalidateBlogLater } from "@/lib/blog/revalidate";import { invalidResponse } from "@/lib/config/experimentList";import { notFoundResponse, withSuperUser } from "@/lib/donkey-api-auth";import { prisma } from "@/lib/prisma";@@ -24,6 +24,6 @@ export const POST = withSuperUser(async (request, { params }: Params) => {where: { id: existing.id },data: parsed.data.kind === "header" ? { headerKey: null, headerAlt: null, headerFocus: null } : { thumbnailKey: null },});- revalidateBlog([row.slug]);+ revalidateBlogLater([row.slug]);return NextResponse.json({ post: adminPost(row) });});diff --git a/site/src/app/api/su/blog/posts/[id]/images/route.ts b/site/src/app/api/su/blog/posts/[id]/images/route.tsindex 21a8e61d..1169f9c8 100644--- a/site/src/app/api/su/blog/posts/[id]/images/route.ts+++ b/site/src/app/api/su/blog/posts/[id]/images/route.ts@@ -5,7 +5,7 @@ import { del, getObject, putObject } from "@/cut/server/cloud/r2";import { adminPost } from "@/lib/blog/admin";import { encodeBlogImage } from "@/lib/blog/images";import { blogImageKey, blogImageUrl, blogPrefix } from "@/lib/blog/keys";-import { revalidateBlog } from "@/lib/blog/revalidate";+import { revalidateBlogLater } from "@/lib/blog/revalidate";import { invalidResponse } from "@/lib/config/experimentList";import { notFoundResponse, withSuperUser } from "@/lib/donkey-api-auth";import { prisma } from "@/lib/prisma";@@ -51,6 +51,6 @@ export const POST = withSuperUser(async (request, { params }: Params) => {where: { id: existing.id },data: kind === "header" ? { headerKey: key } : { thumbnailKey: key },});- revalidateBlog([row.slug]);+ revalidateBlogLater([row.slug]);return NextResponse.json({ image, post: adminPost(row) });});diff --git a/site/src/app/api/su/blog/posts/[id]/publish/route.ts b/site/src/app/api/su/blog/posts/[id]/publish/route.tsindex 4bda1a0a..d9ccb2a4 100644--- a/site/src/app/api/su/blog/posts/[id]/publish/route.ts+++ b/site/src/app/api/su/blog/posts/[id]/publish/route.ts@@ -3,7 +3,7 @@ import { z } from "zod";import { adminPost } from "@/lib/blog/admin";import { readBody } from "@/lib/blog/read";-import { revalidateBlog } from "@/lib/blog/revalidate";+import { revalidateBlogNow } from "@/lib/blog/revalidate";import { notFoundResponse, withSuperUser } from "@/lib/donkey-api-auth";import { prisma } from "@/lib/prisma";@@ -34,6 +34,6 @@ export const POST = withSuperUser(async (_request, { params }: Params) => {? [prisma.blogPost.updateMany({ where: { featured: true, id: { not: id.data } }, data: { featured: false } })]: []),]);- revalidateBlog([row.slug]);+ await revalidateBlogNow([row.slug]);return NextResponse.json({ post: { ...adminPost(row), body } });});diff --git a/site/src/app/api/su/blog/posts/[id]/route.ts b/site/src/app/api/su/blog/posts/[id]/route.tsindex 1aa11a9d..a222931a 100644--- a/site/src/app/api/su/blog/posts/[id]/route.ts+++ b/site/src/app/api/su/blog/posts/[id]/route.ts@@ -6,7 +6,7 @@ import { Prisma } from "@/generated/prisma/client";import { adminPost } from "@/lib/blog/admin";import { blogBodyKey, blogPrefix } from "@/lib/blog/keys";import { readBody } from "@/lib/blog/read";-import { revalidateBlog } from "@/lib/blog/revalidate";+import { revalidateBlogLater } from "@/lib/blog/revalidate";import { blogPostInputSchema } from "@/lib/blog/schema";import { invalidResponse } from "@/lib/config/experimentList";import { notFoundResponse, withSuperUser } from "@/lib/donkey-api-auth";@@ -69,7 +69,7 @@ export const PUT = withSuperUser(async (request, { params }: Params) => {}throw error;}- revalidateBlog([existing.slug, row.slug]);+ revalidateBlogLater([existing.slug, row.slug]);return NextResponse.json({ post: { ...adminPost(row), body: input.body } });});@@ -81,6 +81,6 @@ export const DELETE = withSuperUser(async (_request, { params }: Params) => {if (!existing) return notFoundResponse();await prisma.blogPost.delete({ where: { id: id.data } });await deletePrefix(blogPrefix(existing.id));- revalidateBlog([existing.slug]);+ revalidateBlogLater([existing.slug]);return NextResponse.json({ ok: true });});diff --git a/site/src/app/api/su/blog/posts/[id]/unpublish/route.ts b/site/src/app/api/su/blog/posts/[id]/unpublish/route.tsindex 8b572f54..2df91d5a 100644--- a/site/src/app/api/su/blog/posts/[id]/unpublish/route.ts+++ b/site/src/app/api/su/blog/posts/[id]/unpublish/route.ts@@ -3,7 +3,7 @@ import { z } from "zod";import { adminPost } from "@/lib/blog/admin";import { readBody } from "@/lib/blog/read";-import { revalidateBlog } from "@/lib/blog/revalidate";+import { revalidateBlogLater } from "@/lib/blog/revalidate";import { notFoundResponse, withSuperUser } from "@/lib/donkey-api-auth";import { prisma } from "@/lib/prisma";@@ -18,6 +18,6 @@ export const POST = withSuperUser(async (_request, { params }: Params) => {const existing = await prisma.blogPost.findUnique({ select: { id: true }, where: { id: id.data } });if (!existing) return notFoundResponse();const row = await prisma.blogPost.update({ where: { id: id.data }, data: { status: "DRAFT" } });- revalidateBlog([row.slug]);+ revalidateBlogLater([row.slug]);return NextResponse.json({ post: { ...adminPost(row), body: await readBody(row.id) } });});diff --git a/site/src/app/cut/blog/[slug]/page.tsx b/site/src/app/cut/blog/[slug]/page.tsxindex f7afcb63..f207e877 100644--- a/site/src/app/cut/blog/[slug]/page.tsx+++ b/site/src/app/cut/blog/[slug]/page.tsx@@ -9,7 +9,7 @@ import { BlogShell } from "@/app/cut/blog/_components/BlogShell";import { formatBlogDate, titleCaseTag } from "@/app/cut/blog/_components/blogDate";import { ScrollToHash, TableOfContents } from "@/app/cut/blog/_components/TableOfContents";import { DONKEYCUT_CANONICAL } from "@/cut/lib/hosts";-import { blogPath } from "@/lib/blog/keys";+import { BLOG_SKELETON_ATTR, blogPath } from "@/lib/blog/keys";import { getPost, listPublishedSlugs, type BlogPostPage } from "@/lib/blog/read";import { PostArticle } from "@/lib/blog/render";@@ -179,7 +179,7 @@ async function Post({ params }: Params) {function PostSkeleton() {return (- <div aria-hidden className="animate-pulse">+ <div aria-hidden className="animate-pulse" {...{ [BLOG_SKELETON_ATTR]: "" }}><div className="mb-8 h-60 rounded-2xl border-2 border-ink/10 bg-cream" /><div className="max-w-[72ch] space-y-4"><div className="h-10 w-3/4 rounded-lg bg-ink/10" />diff --git a/site/src/app/cut/blog/_components/BlogGrid.tsx b/site/src/app/cut/blog/_components/BlogGrid.tsxindex e6e57241..7de2335c 100644--- a/site/src/app/cut/blog/_components/BlogGrid.tsx+++ b/site/src/app/cut/blog/_components/BlogGrid.tsx@@ -2,7 +2,7 @@ import Link from "next/link";import { formatBlogDate, titleCaseTag } from "@/app/cut/blog/_components/blogDate";import type { BlogPostCard } from "@/lib/blog/read";-import { blogPath } from "@/lib/blog/keys";+import { BLOG_SKELETON_ATTR, blogPath } from "@/lib/blog/keys";function TagPills({ tags }: { tags: string[] }) {if (tags.length === 0) return null;@@ -109,7 +109,7 @@ export function BlogGrid({ posts, featured }: { posts: BlogPostCard[]; featured:export function BlogGridSkeleton() {return (- <div className="grid grid-cols-1 gap-6 md:grid-cols-2 md:gap-y-8 lg:grid-cols-3" aria-hidden>+ <div className="grid grid-cols-1 gap-6 md:grid-cols-2 md:gap-y-8 lg:grid-cols-3" aria-hidden {...{ [BLOG_SKELETON_ATTR]: "" }}>{Array.from({ length: 6 }, (_, i) => (<div key={i} className="aspect-[4/5] animate-pulse rounded-2xl border-2 border-ink/10 bg-cream" />))}diff --git a/site/src/lib/blog/keys.ts b/site/src/lib/blog/keys.tsindex c1f391b1..14707014 100644--- a/site/src/lib/blog/keys.ts+++ b/site/src/lib/blog/keys.ts@@ -31,3 +31,7 @@ export const blogPageCount = (total: number) => Math.max(1, Math.ceil(total / BLexport const blogPath = (slug: string) => `/blog/${slug}`;// Page 1 is the canonical /blog; later pages live under /blog/page/N.export const blogPageHref = (page: number) => (page <= 1 ? "/blog" : `/blog/page/${page}`);++// Marks a page's loading state, so a warm-up fetch can tell the shell from+// the finished page.+export const BLOG_SKELETON_ATTR = "data-blog-skeleton";diff --git a/site/src/lib/blog/revalidate.ts b/site/src/lib/blog/revalidate.tsindex 427e3286..ab55e9e2 100644--- a/site/src/lib/blog/revalidate.ts+++ b/site/src/lib/blog/revalidate.ts@@ -3,30 +3,62 @@// updateTag, and the stale-while-revalidate profile would show the first// visitor after a publish the page from before it.//-// Then the pages are fetched once after the response goes out. That visit is-// what makes Next render the index and the post again with everything cached,-// so the next reader gets a finished static page, never the shell with its-// skeleton, including for a post published after the deploy.+// Then the pages are rendered again before anyone asks for them. A fetch of+// the address is the visit that makes Next render the index and the post with+// everything cached and keep the result as a static page, including for a post+// published after the deploy. The fetch repeats until the answer carries no+// skeleton, so the first reader gets the finished page. Publishing waits for+// it; the other writes let it run after their response.import { revalidateTag } from "next/cache";import { after } from "next/server";import { CUT_HOSTED_ORIGIN } from "@/cut/lib/hosts";-import { blogPath } from "@/lib/blog/keys";+import { BLOG_SKELETON_ATTR, blogPath } from "@/lib/blog/keys";import { BLOG_TAG, blogPostTag } from "@/lib/blog/read";+const WARM_TRIES = 12;+const WARM_DELAY_MS = 500;++const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));++// The marker as a rendered attribute. The page's React payload names it too,+// as a prop of the fallback, on the finished page as well as on the shell.+const SKELETON_MARKUP = ` ${BLOG_SKELETON_ATTR}=""`;++// Fetches the page until it comes back rendered. Resolves true when it did.+async function warmPath(path: string): Promise<boolean> {+ for (let attempt = 0; attempt < WARM_TRIES; attempt++) {+ try {+ const response = await fetch(`${CUT_HOSTED_ORIGIN}${path}`, { cache: "no-store" });+ const html = await response.text();+ if (response.ok && !html.includes(SKELETON_MARKUP)) return true;+ if (response.status === 404) return false;+ } catch {+ // The host was not reachable this time; the next try may be.+ }+ await sleep(WARM_DELAY_MS);+ }+ return false;+}++export async function warmBlog(slugs: string[]): Promise<void> {+ await Promise.all(["/blog", ...Array.from(new Set(slugs), blogPath)].map(warmPath));+}+export function revalidateBlog(slugs: string[]): void {- const unique = new Set(slugs);revalidateTag(BLOG_TAG, { expire: 0 });- for (const slug of unique) revalidateTag(blogPostTag(slug), { expire: 0 });- after(async () => {- const paths = ["/blog", ...Array.from(unique, blogPath)];- await Promise.all(- paths.map((path) =>- fetch(`${CUT_HOSTED_ORIGIN}${path}`, { cache: "no-store", headers: { "x-blog-warm": "1" } }).then(- (response) => response.body?.cancel(),- () => undefined,- ),- ),- );- });+ for (const slug of new Set(slugs)) revalidateTag(blogPostTag(slug), { expire: 0 });+}++// Expires and renders again before the response goes out, so the address is+// static the moment the caller hears back.+export async function revalidateBlogNow(slugs: string[]): Promise<void> {+ revalidateBlog(slugs);+ await warmBlog(slugs);+}++// Expires now, renders again once the response has gone out.+export function revalidateBlogLater(slugs: string[]): void {+ revalidateBlog(slugs);+ after(() => warmBlog(slugs));}