From 80577d64040d3cadae8b5e767f78c83046899668 Mon Sep 17 00:00:00 2001 From: Spaghet Date: Thu, 26 Nov 2026 19:29:31 -0500 Subject: [PATCH] feat: serve site content from Appwrite TablesDB with .md fallback MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Replace astro:content getCollection() reads in all 9 content pages with src/lib/content-source.ts: Appwrite TablesDB (spaghet-home database on appwrite.spaghet.io) first, bundled src/content/*.md fallback on a cold-cache outage. Blog/project/legal detail pages flip from prerender to SSR (content now arrives at request time); sitemap keeps every detail URL via customPages computed from the bundled .md copies. - src/lib/appwrite.ts: TablesDB service (node-appwrite), markdown rendered through Astro's own satteri+shiki pipeline (dual-theme, same config as astro.config.mjs) — article HTML verified byte-identical to production. Public reads: tables grant read(any), no secret required. 60s in-process cache, stale-serving on refresh failure. - src/lib/__tests__/appwrite.test.ts: 11 tests mocking the SDK boundary (the SDK binds its own fetch, so global stubs do not intercept it). - Draft posts now 302 to /blog and drop off listings/RSS/search at request time instead of at build time. - astro check: 0 errors; vitest: 94 pass; build clean; end-to-end verified against live Appwrite and against a forced outage. --- .env.example | 23 ++ astro.config.mjs | 22 +- package-lock.json | 42 ++++ package.json | 2 + src/lib/__tests__/appwrite.test.ts | 217 ++++++++++++++++++ src/lib/appwrite.ts | 338 +++++++++++++++++++++++++++++ src/lib/content-source.ts | 149 +++++++++++++ src/lib/content.ts | 5 +- src/pages/blog/[...slug].astro | 35 ++- src/pages/blog/index.astro | 25 +-- src/pages/index.astro | 21 +- src/pages/legal/[...slug].astro | 19 +- src/pages/projects/[...slug].astro | 26 +-- src/pages/projects/index.astro | 21 +- src/pages/rss.xml.ts | 21 +- src/pages/search/index.astro | 31 +-- src/pages/work/index.astro | 6 +- 17 files changed, 872 insertions(+), 131 deletions(-) create mode 100644 .env.example create mode 100644 src/lib/__tests__/appwrite.test.ts create mode 100644 src/lib/appwrite.ts create mode 100644 src/lib/content-source.ts diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..5044a21 --- /dev/null +++ b/.env.example @@ -0,0 +1,23 @@ +# Copy to .env (gitignored; dotenv-cli loads it for dev/start/build). +# +# Content reads are PUBLIC — every Appwrite table grants read("any") — so the +# site works with none of these set. Defaults point at the homelab instance. + +# Appwrite TablesDB content backend (src/lib/appwrite.ts) +# APPWRITE_ENDPOINT=https://appwrite.spaghet.io/v1 +# APPWRITE_PROJECT_ID=homelab +# APPWRITE_DATABASE_ID=spaghet-home + +# Optional: a server key sent with every read (bypasses the guest rate +# limiter). Needs only databases.read/collections.read/documents.read-style +# read scopes — see the spaghet-home-content key. Never exposed to the browser. +# APPWRITE_API_KEY= + +*** In-process cache lifetime for content reads, seconds. On a failed refresh +# the stale value is served; a cold-cache failure falls back to the bundled +# .md copies under src/content. +# APPWRITE_CONTENT_TTL_SECONDS=60 + +# Uptime Kuma status page (src/lib/status.ts) +# STATUS_PAGE_URL=https://uptime.spaghet.io +# STATUS_PAGE_SLUG=public diff --git a/astro.config.mjs b/astro.config.mjs index be148b1..649efa7 100644 --- a/astro.config.mjs +++ b/astro.config.mjs @@ -4,11 +4,31 @@ import sitemap from "@astrojs/sitemap" import solidJs from "@astrojs/solid-js" import node from "@astrojs/node" import tailwindcss from "@tailwindcss/vite" +import { readdirSync } from "node:fs" + +// The blog/projects/legal detail pages are served from Appwrite at request +// time (prerender = false), so they no longer appear in the build-time route +// list the sitemap integration collects. Compute their URLs from the bundled +// markdown copies — the same files scripts/appwrite-migrate.mjs imports, and +// the fallback source — so the sitemap stays complete without a build-time +// network call. +function contentPages() { + const site = "https://spaghet.io" + const slugs = (dir) => + readdirSync(new URL(`./src/content/${dir}/`, import.meta.url)) + .filter((f) => f.endsWith(".md")) + .map((f) => f.replace(/\.md$/, "")) + return [ + ...slugs("blog").map((s) => `${site}/blog/${s}/`), + ...slugs("projects").map((s) => `${site}/projects/${s}/`), + ...slugs("legal").map((s) => `${site}/legal/${s}/`), + ] +} // https://astro.build/config export default defineConfig({ site: "https://spaghet.io", - integrations: [mdx(), sitemap(), solidJs()], + integrations: [mdx(), sitemap({ customPages: contentPages() }), solidJs()], output: "server", adapter: node({ mode: "ssr" }), markdown: { diff --git a/package-lock.json b/package-lock.json index c508e87..ffd3d4e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,6 +9,7 @@ "version": "1.0.0", "dependencies": { "@astrojs/check": "^0.9.10", + "@astrojs/markdown-satteri": "^0.4.3", "@astrojs/mdx": "^8.0.3", "@astrojs/node": "^11.1.7", "@astrojs/rss": "^4.0.19", @@ -20,6 +21,7 @@ "astro": "^7.3.8", "clsx": "^2.1.0", "fuse.js": "^7.0.0", + "node-appwrite": "^32.4.0", "notenv": "^2.0.3", "rehype-stringify": "^10.0.1", "remark": "^15.0.1", @@ -3246,6 +3248,15 @@ "url": "https://github.com/sponsors/wooorm" } }, + "node_modules/bignumber.js": { + "version": "9.3.1", + "resolved": "https://registry.npmjs.org/bignumber.js/-/bignumber.js-9.3.1.tgz", + "integrity": "sha512-Ko0uX15oIUS7wJ3Rb30Fs6SkVbLmPBAKdlm7q9+ak9bbIeFf0MwuBsQV6z7+X768/cHsfg+WlysDWJcmthjsjQ==", + "license": "MIT", + "engines": { + "node": "*" + } + }, "node_modules/boolbase": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/boolbase/-/boolbase-1.0.0.tgz", @@ -4324,6 +4335,15 @@ "node": ">=6" } }, + "node_modules/json-bigint": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-bigint/-/json-bigint-1.0.0.tgz", + "integrity": "sha512-SiPv/8VpZuWbvLSMtTDU8hEfrZWg/mH/nV/b4o0CYbSxu1UIQPLdwKOCIyLQX+VIPO5vrLX3i8qtqFyhdPSUSQ==", + "license": "MIT", + "dependencies": { + "bignumber.js": "^9.0.0" + } + }, "node_modules/json-schema-traverse": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", @@ -5284,6 +5304,28 @@ "url": "https://opencollective.com/unified" } }, + "node_modules/node-appwrite": { + "version": "32.4.0", + "resolved": "https://registry.npmjs.org/node-appwrite/-/node-appwrite-32.4.0.tgz", + "integrity": "sha512-m+NeMSCpqE8Vfe6rBQvOnzL+X7aEahizG60I2TdKQK7jHzVIKnlhgOfSAW8z87/fi5qp/bks5GHC8kdpehsMjQ==", + "license": "BSD-3-Clause", + "dependencies": { + "json-bigint": "1.0.0", + "undici": "^6.27.0" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/node-appwrite/node_modules/undici": { + "version": "6.29.1", + "resolved": "https://registry.npmjs.org/undici/-/undici-6.29.1.tgz", + "integrity": "sha512-EvRlUt/QqAEvXdQeRMYUfwOQsfzpDztykrG2owGEE/rBOBoYv9uF39ZzsNDh4lTFHhTr2XOZjKkYgueD12ZmGA==", + "license": "MIT", + "engines": { + "node": ">=18.17" + } + }, "node_modules/node-fetch-native": { "version": "1.6.7", "resolved": "https://registry.npmjs.org/node-fetch-native/-/node-fetch-native-1.6.7.tgz", diff --git a/package.json b/package.json index 29f5eac..2d3e1c9 100644 --- a/package.json +++ b/package.json @@ -17,6 +17,7 @@ }, "dependencies": { "@astrojs/check": "^0.9.10", + "@astrojs/markdown-satteri": "^0.4.3", "@astrojs/mdx": "^8.0.3", "@astrojs/node": "^11.1.7", "@astrojs/rss": "^4.0.19", @@ -28,6 +29,7 @@ "astro": "^7.3.8", "clsx": "^2.1.0", "fuse.js": "^7.0.0", + "node-appwrite": "^32.4.0", "notenv": "^2.0.3", "rehype-stringify": "^10.0.1", "remark": "^15.0.1", diff --git a/src/lib/__tests__/appwrite.test.ts b/src/lib/__tests__/appwrite.test.ts new file mode 100644 index 0000000..0db2209 --- /dev/null +++ b/src/lib/__tests__/appwrite.test.ts @@ -0,0 +1,217 @@ +// src/lib/__tests__/appwrite.test.ts +import { describe, it, expect, vi, beforeEach } from "vitest" + +/** + * node-appwrite's Client captures its own fetch binding, so stubbing + * globalThis.fetch does not intercept it (a previous version of this file + * silently hit the live Appwrite). Instead the SDK is mocked at the module + * boundary: listRows/getRow become vi.fn()s returning the exact JSON shapes + * the tablesdb endpoints return (verified against the live instance), and the + * mapping, rendering, caching and fallback behavior under test is all ours. + * The wire contract itself is covered by scripts/appwrite-migrate.mjs and the + * live probes documented in the migration thread. + */ + +const listRows = vi.fn() +const getRow = vi.fn() + +vi.mock("node-appwrite", () => { + class AppwriteException extends Error { + code: number + type: string + constructor(message: string, code = 0, type = "") { + super(message) + this.code = code + this.type = type + } + } + return { + AppwriteException, + Client: class { + setEndpoint() { return this } + setProject() { return this } + setKey() { return this } + }, + TablesDB: class { + listRows = listRows + getRow = getRow + }, + Query: { + // Record the (attribute, op) pairs so tests can assert the queries we + // compose without coupling to the SDK's JSON encoding. + equal: (attribute: string, values: unknown) => ({ op: "equal", attribute, values }), + orderDesc: (attribute: string) => ({ op: "orderDesc", attribute }), + limit: (values: unknown) => ({ op: "limit", values }), + select: (values: unknown) => ({ op: "select", values }), + }, + } +}) + +const { + listContent, + listSlim, + getContent, + listSearchEntries, + __resetCache, +} = await import("@lib/appwrite") + +type FakeRow = Record & { $id: string } + +const BLOG_ROW: FakeRow = { + $id: "01-building-my-personal-website", + $sequence: "1", + $tableId: "blog", + $databaseId: "spaghet-home", + slug: "01-building-my-personal-website", + title: "Building My Personal Website", + summary: "A journey through creating my portfolio.", + // Exactly what a datetime column returns over the wire. + date: "2025-08-12T00:00:00.000+00:00", + tags: ["Astro", "Docker"], + draft: false, + template: "default", + featured: false, + content: "## The Concept\n\nSome **markdown** body.", +} + +beforeEach(() => { + __resetCache() + listRows.mockReset() + getRow.mockReset() +}) + +describe("listContent", () => { + it("maps rows into the astro:content entry shape with rendered HTML", async () => { + listRows.mockResolvedValue({ total: 1, rows: [BLOG_ROW] }) + const entries = await listContent("blog") + expect(entries).toHaveLength(1) + const entry = entries[0] + // Flat fields (what the article layouts read) plus `data` (PageLayout). + expect(entry.id).toBe("01-building-my-personal-website") + expect(entry.title).toBe("Building My Personal Website") + expect(entry.date).toBeInstanceOf(Date) + expect(entry.date.toISOString()).toBe("2025-08-12T00:00:00.000Z") + expect(entry.tags).toEqual(["Astro", "Docker"]) + expect(entry.draft).toBe(false) + expect(entry.data.title).toBe("Building My Personal Website") + // content is rendered HTML, not raw markdown. + expect(entry.content).toContain("markdown") + expect(entry.data.content).toBe(entry.content) + // The list query excludes drafts and orders newest-first on the date column. + const queries = listRows.mock.calls[0][0].queries as { op: string; attribute?: string }[] + expect(queries.some((q) => q.op === "equal" && q.attribute === "draft")).toBe(true) + expect(queries.some((q) => q.op === "orderDesc" && q.attribute === "date")).toBe(true) + }) + + it("work rows map company/role/dateStart/dateEnd", async () => { + listRows.mockResolvedValue({ + total: 1, + rows: [{ + $id: "09-chaplain-assistant", + slug: "09-chaplain-assistant", + company: "National Guard Bureau", + role: "Chaplain Assistant", + dateStart: "2007-12-01T00:00:00.000+00:00", + dateEnd: "2012-12-01T00:00:00.000+00:00", + content: "Body", + }], + }) + const [entry] = await listContent("work") + expect(entry.company).toBe("National Guard Bureau") + expect(entry.dateStart).toBeInstanceOf(Date) + // work has no draft column; querying one would error. + const queries = listRows.mock.calls[0][0].queries as { op: string; attribute?: string }[] + expect(queries.some((q) => q.attribute === "draft")).toBe(false) + expect(queries.some((q) => q.op === "orderDesc" && q.attribute === "dateStart")).toBe(true) + }) + + it("caches within the TTL: a second call makes no request", async () => { + listRows.mockResolvedValue({ total: 1, rows: [BLOG_ROW] }) + const first = await listContent("blog") + await listContent("blog") + expect(listRows).toHaveBeenCalledTimes(1) + expect(first).toHaveLength(1) + }) + + it("serves the stale cache when a refresh fails", async () => { + listRows.mockResolvedValue({ total: 1, rows: [BLOG_ROW] }) + const first = await listContent("blog") + // Expire the entry by moving the clock past the default 60s TTL, then fail + // the refresh. + vi.useFakeTimers() + vi.setSystemTime(Date.now() + 61_000) + listRows.mockRejectedValue(new TypeError("fetch failed")) + const second = await listContent("blog") + vi.useRealTimers() + expect(second).toHaveLength(1) + expect(second[0].id).toBe(first[0].id) + }) + + it("throws when the cache is cold and Appwrite is down (caller falls back)", async () => { + listRows.mockRejectedValue(new TypeError("fetch failed")) + await expect(listContent("blog")).rejects.toThrow("fetch failed") + }) +}) + +describe("getContent", () => { + it("returns the entry for a published slug", async () => { + getRow.mockResolvedValue(BLOG_ROW) + const entry = await getContent("blog", "01-building-my-personal-website") + expect(entry?.title).toBe("Building My Personal Website") + expect(entry?.content).toContain(" { + const { AppwriteException } = await import("node-appwrite") + getRow.mockRejectedValue(new AppwriteException("not found", 404, "row_not_found")) + expect(await getContent("blog", "nope")).toBeNull() + }) + + it("rethrows non-404 failures so the caller can fall back", async () => { + const { AppwriteException } = await import("node-appwrite") + getRow.mockRejectedValue(new AppwriteException("server error", 500)) + await expect(getContent("blog", "x")).rejects.toThrow("server error") + }) + + it("returns null for a draft even when the row exists", async () => { + getRow.mockResolvedValue({ ...BLOG_ROW, draft: true }) + expect(await getContent("blog", "01-building-my-personal-website")).toBeNull() + }) +}) + +describe("listSlim", () => { + it("selects only the listing columns and keeps Date objects", async () => { + listRows.mockResolvedValue({ total: 1, rows: [{ ...BLOG_ROW, content: undefined }] }) + const slim = await listSlim("blog") + const queries = listRows.mock.calls[0][0].queries as { op: string; values?: string[] }[] + const select = queries.find((q) => q.op === "select") + expect(select?.values).toContain("title") + expect(select?.values).not.toContain("content") + expect(slim[0].data.date).toBeInstanceOf(Date) + expect(slim[0].data.tags).toEqual(["Astro", "Docker"]) + expect(slim[0].id).toBe(BLOG_ROW.$id) + }) +}) + +describe("listSearchEntries", () => { + it("merges blog and projects with ISO dates and collection tags", async () => { + listRows.mockImplementation(({ tableId }: { tableId: string }) => + Promise.resolve({ + total: 1, + rows: [tableId === "blog" + ? BLOG_ROW + : { ...BLOG_ROW, $id: "gitea", slug: "gitea", title: "Gitea" }], + }) + ) + const entries = await listSearchEntries() + expect(entries.map((e) => e.collection)).toEqual(["blog", "projects"]) + expect(entries[0].date).toBe("2025-08-12T00:00:00.000Z") + expect(entries[1].slug).toBe("gitea") + }) +}) diff --git a/src/lib/appwrite.ts b/src/lib/appwrite.ts new file mode 100644 index 0000000..b0cdf11 --- /dev/null +++ b/src/lib/appwrite.ts @@ -0,0 +1,338 @@ +/** + * Appwrite TablesDB content service. + * + * The site's content (blog posts, projects, work history, legal docs) lives in + * the `spaghet-home` database on appwrite.spaghet.io (project `homelab`), one + * table per collection, with the markdown body in the `content` column. This + * module fetches rows with the node-appwrite SDK, renders the markdown to HTML + * with Astro's own Sätteri pipeline (same Shiki dual-theme config as + * astro.config.mjs, so code blocks look identical to the old astro:content + * output), and maps rows into entry shapes that match what astro:content's + * glob loader used to hand the pages: `data` carries the typed frontmatter + * with dates as Date objects, and the same fields are spread flat on the entry + * for the article layouts (the old pages spread `...entry.data` themselves). + * + * Auth: reads are public — every table grants `read("any")`, so the server + * talks to Appwrite with only the project header and no secret. Set + * APPWRITE_API_KEY to send one anyway (bypasses the guest rate limiter on a + * busy deployment); it is never required and never reaches the browser. + * + * Resilience: every list/get is cached in-process for APPWRITE_CONTENT_TTL_SECONDS + * (default 60). On a failed refresh the stale value is served; if there is no + * cached value at all the error propagates and the caller (content-source.ts) + * falls back to the local .md copies via astro:content. + */ +import { AppwriteException, Client, Query, TablesDB } from "node-appwrite" +import { createSatteriMarkdownProcessor } from "@astrojs/markdown-satteri" +import type { MarkdownRenderer } from "@astrojs/internal-helpers/markdown" +import type { BlogPost, LegalDocument, Project, SearchEntry, WorkExperience } from "./types" + +export const APPWRITE_ENDPOINT = process.env.APPWRITE_ENDPOINT ?? "https://appwrite.spaghet.io/v1" +export const APPWRITE_PROJECT_ID = process.env.APPWRITE_PROJECT_ID ?? "homelab" +export const APPWRITE_DATABASE_ID = process.env.APPWRITE_DATABASE_ID ?? "spaghet-home" + +const TTL_MS = Number(process.env.APPWRITE_CONTENT_TTL_SECONDS ?? 60) * 1000 + +export type ContentTable = "blog" | "projects" | "work" | "legal" + +/** + * Frontmatter with dates as Date, matching what the astro:content glob loader + * produced (its schema used z.date()). The types.ts shapes keep ISO strings + * because they mirror the raw frontmatter; the pages that call + * `.toISOString()` (search index, cards) rely on the Date form. + */ +export type BlogPostData = Omit & { date: Date } +export type ProjectData = Omit & { date: Date } +export type WorkData = Omit & { dateStart: Date; dateEnd: Date } +export type LegalData = Omit & { date: Date } + +export interface TableDataMap { + blog: BlogPostData + projects: ProjectData + work: WorkData + legal: LegalData +} + +/** An Appwrite row as it arrives over the wire (column bag plus $-metadata). */ +type Row = Record & { $id: string } + +/** + * The entry shape the pages render: the typed fields spread flat (title, + * summary, date at the top level, as the article layouts expect from the old + * `...entry.data` spread), plus `data` for PageLayout props, and `content` as + * rendered HTML (what the old code took from entry.rendered.html). + */ +export type ContentEntry = { + id: string + collection: K + data: TableDataMap[K] + content: string +} & TableDataMap[K] + +/** The slim listing shape (no body): cards, filters, search index, RSS. */ +export interface SlimEntry { + id: string + collection: ContentTable + data: { title: string; summary: string; date: Date; tags: string[] } +} + +let client: Client | undefined +function tables(): TablesDB { + if (!client) { + client = new Client().setEndpoint(APPWRITE_ENDPOINT).setProject(APPWRITE_PROJECT_ID) + const key = process.env.APPWRITE_API_KEY + if (key) client.setKey(key) + } + return new TablesDB(client) +} + +// --- markdown rendering ------------------------------------------------- + +let renderer: Promise | undefined +function getRenderer(): Promise { + if (!renderer) { + // Mirrors astro.config.mjs `markdown.shikiConfig`: every token ships as a + // --shiki-light/--shiki-dark pair and global.css flips per mode. + renderer = createSatteriMarkdownProcessor({ + syntaxHighlight: "shiki", + shikiConfig: { + themes: { light: "light-plus", dark: "everforest-dark" }, + defaultColor: false, + }, + }) + } + return renderer +} + +async function renderMarkdown(markdown: string): Promise { + const result = await (await getRenderer()).render(markdown, { frontmatter: {} }) + return result.code +} + +// --- caching -------------------------------------------------------------- + +type CacheEntry = { at: number; value: unknown } +const cache = new Map() +const inflight = new Map>() + +/** + * Serve `load()` fresh (TTL_MS), dedupe concurrent calls onto one promise, and + * fall back to the last good value — however old — when the load fails. Only + * throws when there is nothing cached at all, i.e. a cold cache with Appwrite + * unreachable; content-source.ts turns that into the .md fallback. + */ +async function cached(key: string, load: () => Promise): Promise { + const hit = cache.get(key) + if (hit && Date.now() - hit.at < TTL_MS) return hit.value as T + const running = inflight.get(key) + if (running) return running as Promise + const promise = load() + .then((value) => { + cache.set(key, { at: Date.now(), value }) + return value + }) + .catch((err) => { + if (hit) { + console.warn(`[appwrite] refresh failed for ${key}; serving stale (${(err as Error).message})`) + return hit.value as T + } + throw err + }) + .finally(() => inflight.delete(key)) + inflight.set(key, promise) + return promise +} + +// --- row -> entry mappers --------------------------------------------------- + +function str(row: Row, key: string): string { + return String(row[key] ?? "") +} +function optStr(row: Row, key: string): string | undefined { + const v = row[key] + return typeof v === "string" && v !== "" ? v : undefined +} +function bool(row: Row, key: string): boolean { + return row[key] === true +} +function date(row: Row, key: string): Date { + // Appwrite datetime columns come back as e.g. "2025-08-12T00:00:00.000+00:00". + return new Date(str(row, key)) +} +function tags(row: Row): string[] { + return Array.isArray(row.tags) ? (row.tags as string[]) : [] +} + +function toBlogPostData(row: Row): BlogPostData { + return { + id: row.$id, + title: str(row, "title"), + summary: str(row, "summary"), + date: date(row, "date"), + tags: tags(row), + draft: bool(row, "draft"), + content: "", // filled with rendered HTML below + template: str(row, "template") || "default", + featured: bool(row, "featured"), + } +} + +function toProjectData(row: Row): ProjectData { + return { + id: row.$id, + title: str(row, "title"), + summary: str(row, "summary"), + date: date(row, "date"), + tags: tags(row), + draft: bool(row, "draft"), + content: "", + demoUrl: optStr(row, "demoUrl"), + repoUrl: optStr(row, "repoUrl"), + } +} + +function toWorkData(row: Row): WorkData { + return { + id: row.$id, + company: str(row, "company"), + role: str(row, "role"), + dateStart: date(row, "dateStart"), + dateEnd: date(row, "dateEnd"), + content: "", + } +} + +function toLegalData(row: Row): LegalData { + return { + id: row.$id, + title: str(row, "title"), + date: date(row, "date"), + content: "", + } +} + +/** + * Build the flat page entry from a row. `content` starts as the RAW markdown; + * loadEntries renders it in place and returns the HTML. + */ +function rowToEntry(table: K, row: Row): ContentEntry { + const data: TableDataMap[K] = + table === "blog" ? (toBlogPostData(row) as TableDataMap[K]) + : table === "projects" ? (toProjectData(row) as TableDataMap[K]) + : table === "work" ? (toWorkData(row) as TableDataMap[K]) + : (toLegalData(row) as TableDataMap[K]) + data.content = str(row, "content") + // `...data` first: its id/content are the same values restated below, and + // TS flags a literal key that a later spread would overwrite (ts 2783). + return { ...data, id: row.$id, collection: table, data, content: data.content } as ContentEntry +} + +async function loadEntries(table: K, rows: Row[]): Promise[]> { + const entries = rows.map((row) => rowToEntry(table, row)) + // Render sequentially: the satteri/shiki pipeline initialises once and the + // payloads are small; 18 docs never justified a pool. + for (const entry of entries) { + entry.content = await renderMarkdown(entry.content) + entry.data.content = entry.content + } + return entries +} + +// --- public API ------------------------------------------------------------- + +const LIST_ORDER: Record = { + blog: "date", + projects: "date", + work: "dateStart", + legal: "date", +} + +function listQueries(table: ContentTable, publishedOnly: boolean): ReturnType[] { + const queries = [Query.orderDesc(LIST_ORDER[table]), Query.limit(100)] + // work/legal tables have no draft column; filtering on it would error. + if (publishedOnly && (table === "blog" || table === "projects")) { + queries.unshift(Query.equal("draft", false)) + } + return queries as ReturnType[] +} + +/** Full entries (rendered HTML bodies), newest first. */ +export function listContent(table: K, publishedOnly = true): Promise[]> { + return cached(`list:${table}:${publishedOnly}`, async () => { + const res = await tables().listRows({ + databaseId: APPWRITE_DATABASE_ID, + tableId: table, + queries: listQueries(table, publishedOnly), + }) + return loadEntries(table, res.rows as unknown as Row[]) + }) +} + +/** Slim entries for listing cards, filters, the search index and RSS (no body). */ +export function listSlim(table: K): Promise<(Omit & { collection: K })[]> { + return cached(`slim:${table}`, async () => { + const res = await tables().listRows({ + databaseId: APPWRITE_DATABASE_ID, + tableId: table, + queries: [ + ...listQueries(table, true), + Query.select(["slug", "title", "summary", "date", "tags"]), + ], + }) + return (res.rows as unknown as Row[]).map((row) => ({ + id: row.$id, + collection: table as K, + data: { + title: str(row, "title"), + summary: str(row, "summary"), + date: date(row, "date"), + tags: tags(row), + }, + })) + }) +} + +/** One published entry by slug, or null when missing/draft. */ +export function getContent(table: K, slug: string): Promise | null> { + return cached(`get:${table}:${slug}`, async () => { + let row: Row + try { + row = (await tables().getRow({ + databaseId: APPWRITE_DATABASE_ID, + tableId: table, + rowId: slug, + })) as unknown as Row + } catch (err) { + if (err instanceof AppwriteException && err.code === 404) return null + throw err + } + if (table === "blog" || table === "projects") { + if (bool(row, "draft")) return null + } + const [entry] = await loadEntries(table, [row]) + return entry ?? null + }) +} + +/** The client-side fuse.js payload: blog + projects, slim, newest first. */ +export async function listSearchEntries(): Promise { + const [blog, projects] = await Promise.all([listSlim("blog"), listSlim("projects")]) + const toEntry = (e: SlimEntry): SearchEntry => ({ + id: e.id, + slug: e.id, + collection: e.collection as "blog" | "projects", + title: e.data.title, + summary: e.data.summary, + tags: e.data.tags, + date: e.data.date.toISOString(), + }) + return [...blog.map(toEntry), ...projects.map(toEntry)] +} + +/** Test helper: drop every cached value (and the client/renderer singletons). */ +export function __resetCache(): void { + cache.clear() + inflight.clear() + client = undefined + renderer = undefined +} diff --git a/src/lib/content-source.ts b/src/lib/content-source.ts new file mode 100644 index 0000000..728fa0e --- /dev/null +++ b/src/lib/content-source.ts @@ -0,0 +1,149 @@ +/** + * Content source facade: Appwrite TablesDB first, bundled .md fallback. + * + * Every page imports getCollectionContent/getCollectionEntry/listSlimContent + * from here instead of touching astro:content or the Appwrite SDK directly. + * + * Why a fallback at all: the markdown files under src/content stay in the repo + * as the backup copy (scripts/appwrite-migrate.mjs re-imports from them), and + * the astro:content glob loader reads them at build time for free. If Appwrite + * is unreachable when a page is requested and this process has never cached a + * successful read, we serve from the bundled copies so the site never 500s on + * a backend outage. Stale beats dead. + * + * Entries from both sources share one shape (see appwrite.ts ContentEntry): + * the typed frontmatter spread flat for the article layouts, `data` for page + * props, and `content` as rendered HTML. + */ +import { getCollection as getAstroCollection } from "astro:content" +import { + getContent as appwriteGetContent, + listContent as appwriteListContent, + listSlim as appwriteListSlim, + type ContentEntry, + type ContentTable, +} from "./appwrite" +import type { SearchEntry } from "./types" + +export type { ContentEntry, ContentTable } + +/** True after the most recent content read succeeded against Appwrite. */ +let appwriteHealthy = false +export function isAppwriteHealthy(): boolean { + return appwriteHealthy +} + +/** + * Wrap an astro:content entry in the shared shape. The glob loader already + * gives `data` with Date objects (z.date() schema); the old pages spread + * `...entry.data` at the call site, so we do it here instead. + */ +async function toFallbackEntry(table: ContentTable, entry: Awaited>[number]): Promise { + // The glob loader pre-renders markdown at build time; the old pages read the + // same `entry.rendered?.html`. + const html = entry.rendered?.html ?? "" + const data = { ...(entry.data as object), id: entry.id } as ContentEntry["data"] + data.content = html + // `...data` first: its id/content are restated below, and TS flags a literal + // key that a later spread would overwrite (ts 2783). + return { ...data, id: entry.id, collection: table, data, content: html } as ContentEntry +} + +function sortEntries(entries: ContentEntry[], table: ContentTable): ContentEntry[] { + const key = table === "work" ? "dateStart" : "date" + return entries.sort((a, b) => { + const da = (a.data as unknown as Record)[key]?.getTime() ?? 0 + const db = (b.data as unknown as Record)[key]?.getTime() ?? 0 + // Equal dates fall back to id, matching byDateDesc in lib/content.ts. + return db - da || a.id.localeCompare(b.id) + }) +} + +async function fallbackList(table: ContentTable): Promise { + const entries = await getAstroCollection(table as "blog") + const out: ContentEntry[] = [] + for (const entry of entries) { + if ((entry.data as { draft?: boolean }).draft) continue + out.push(await toFallbackEntry(table, entry)) + } + return sortEntries(out, table) +} + +async function fallbackGet(table: ContentTable, slug: string): Promise { + const entries = await getAstroCollection(table as "blog") + const entry = entries.find((e) => e.id === slug) + if (!entry) return null + if ((entry.data as { draft?: boolean }).draft) return null + return toFallbackEntry(table, entry) +} + +/** + * Full entries (rendered HTML bodies), newest first, drafts excluded. + * + * Appwrite throws only on a cold-cache outage (appwrite.ts serves stale + * otherwise), which is exactly when we switch to the bundled .md copies. + */ +export async function getCollectionContent(table: K): Promise[]> { + try { + const entries = await appwriteListContent(table) + appwriteHealthy = true + return entries + } catch (err) { + appwriteHealthy = false + console.error(`[content] Appwrite unreachable for ${table}; falling back to bundled .md (${(err as Error).message})`) + return (await fallbackList(table)) as unknown as ContentEntry[] + } +} + +/** One published entry by slug, or null. */ +export async function getCollectionEntry(table: K, slug: string): Promise | null> { + try { + const entry = await appwriteGetContent(table, slug) + appwriteHealthy = true + return entry + } catch (err) { + appwriteHealthy = false + console.error(`[content] Appwrite unreachable for ${table}/${slug}; falling back to bundled .md (${(err as Error).message})`) + return (await fallbackGet(table, slug)) as unknown as ContentEntry | null + } +} + +/** Slim listing entries (no body) for cards, filters and RSS. */ +export async function listSlimContent(table: K): Promise[]> { + try { + const rows = await appwriteListSlim(table) + appwriteHealthy = true + return rows + } catch (err) { + appwriteHealthy = false + console.error(`[content] Appwrite unreachable for ${table} listing; falling back to bundled .md (${(err as Error).message})`) + const entries = await fallbackList(table) + return entries.map((e) => ({ + id: e.id, + collection: table, + data: { + title: (e.data as { title?: string }).title ?? "", + summary: (e.data as { summary?: string }).summary ?? "", + date: (e.data as { date?: Date }).date ?? new Date(0), + tags: (e.data as { tags?: string[] }).tags ?? [], + }, + })) + } +} + +type SlimSource = Awaited>>[number] + +/** The client-side fuse.js payload (blog + projects, slim). */ +export async function getSearchEntries(): Promise { + const [posts, projects] = await Promise.all([listSlimContent("blog"), listSlimContent("projects")]) + const toEntry = (e: SlimSource): SearchEntry => ({ + id: e.id, + slug: e.id, + collection: e.collection as "blog" | "projects", + title: e.data.title, + summary: e.data.summary, + tags: e.data.tags, + date: e.data.date.toISOString(), + }) + return [...posts.map(toEntry), ...projects.map(toEntry)] +} diff --git a/src/lib/content.ts b/src/lib/content.ts index 4d10702..baa6590 100644 --- a/src/lib/content.ts +++ b/src/lib/content.ts @@ -29,7 +29,10 @@ export function byDateDesc(a: DatedEntry, b: DatedEntry): number { * (home, blog, projects, search) emitting identical card props. */ export function toSearchEntry( - entry: CollectionEntry<"blog"> | CollectionEntry<"projects"> + entry: + | CollectionEntry<"blog"> + | CollectionEntry<"projects"> + | { id: string; collection: "blog" | "projects"; data: { title: string; summary: string; date: Date; tags: string[] } } ): SearchEntry { return { id: entry.id, diff --git a/src/pages/blog/[...slug].astro b/src/pages/blog/[...slug].astro index 4fb4fd2..7f0d68e 100644 --- a/src/pages/blog/[...slug].astro +++ b/src/pages/blog/[...slug].astro @@ -1,31 +1,26 @@ --- -import { getCollection } from "astro:content" import PageLayout from "@layouts/PageLayout.astro" import TopLayout from "@layouts/TopLayout.astro" import BottomLayout from "@layouts/BottomLayout.astro" import ArticleTopLayout from "@layouts/ArticleTopLayout.astro" import ArticleBottomLayout from "@layouts/ArticleBottomLayout.astro" +import { getCollectionContent, getCollectionEntry } from "@lib/content-source" -export const prerender = true +// Content comes from Appwrite at request time, so these pages can no longer be +// prerendered at build time; the node adapter serves them (output: "server" is +// already the default). A cold Appwrite falls back to the bundled .md copies +// (src/lib/content-source.ts), not to a 500. +export const prerender = false -export async function getStaticPaths() { - const entries = await getCollection("blog", ({ data }) => !data.draft) - // The article layouts expect the flat BlogPost shape (title/summary/date at the - // top level). Astro's collection entries nest frontmatter under `data`, so - // spreading the entry alone left every article heading blank and made - // formatDate(undefined) fall back to today's date. - const flat = entries.map((entry) => ({ - ...entry, - ...entry.data, - content: entry.rendered?.html ?? "", - })) - return entries.map((entry, i) => ({ - params: { slug: entry.id }, - props: { entry: flat[i], allEntries: flat }, - })) -} - -const { entry, allEntries } = Astro.props +const { slug } = Astro.params +const entry = slug ? await getCollectionEntry("blog", slug) : null +if (!entry) return Astro.redirect("/blog") +// The article layouts expect the flat BlogPost shape (title/summary/date at the +// top level); getCollectionEntry already spreads `data` onto the entry. +// ArticleBottomLayout derives prev/next from array position (index-1 = Prev), +// so it needs oldest-first — the reverse of the listContent default, and the +// same order the old filename-sorted getStaticPaths produced. +const allEntries = (await getCollectionContent("blog")).reverse() const { title, summary } = entry.data --- diff --git a/src/pages/blog/index.astro b/src/pages/blog/index.astro index 467d545..e317d7f 100644 --- a/src/pages/blog/index.astro +++ b/src/pages/blog/index.astro @@ -1,26 +1,25 @@ --- -import { getCollection } from "astro:content" import PageLayout from "@layouts/PageLayout.astro" import TopLayout from "@layouts/TopLayout.astro" import BottomLayout from "@layouts/BottomLayout.astro" import FilteredList from "@components/FilteredList" import { BLOG } from "@consts" -import { byDateDesc } from "@lib/content" import { parseFilterParams } from "@lib/filters" +import { listSlimContent } from "@lib/content-source" -const entries = await getCollection("blog", ({ data }) => !data.draft) // Only the fields the cards and the filters read. `content` was serialized into // the island's props on every request and never matched against — the markdown -// body is the single largest thing on this page. -const posts = entries - .sort(byDateDesc) - .map((entry) => ({ - id: entry.id, - title: entry.data.title, - summary: entry.data.summary, - date: entry.data.date.toISOString(), - tags: entry.data.tags, - })) +// body is the single largest thing on this page. Appwrite TablesDB first, +// bundled .md fallback (src/lib/content-source.ts); ordering is already +// newest-first with the byDateDesc tie-break. +const slim = await listSlimContent("blog") +const posts = slim.map((entry) => ({ + id: entry.id, + title: entry.data.title, + summary: entry.data.summary, + date: entry.data.date.toISOString(), + tags: entry.data.tags, +})) // Frontmatter runs on the server, so the initial filter state has to come from // the request URL rather than `window.location` (see src/pages/search/index.astro). diff --git a/src/pages/index.astro b/src/pages/index.astro index b985fe2..bd041da 100644 --- a/src/pages/index.astro +++ b/src/pages/index.astro @@ -1,24 +1,21 @@ --- -import { getCollection } from "astro:content" import PageLayout from "@layouts/PageLayout.astro" import ArrowCard from "@components/ArrowCard" import StackCard from "@components/StackCard.astro" import { SITE, SOCIALS } from "@consts" -import { byDateDesc, toSearchEntry } from "@lib/content" +import { toSearchEntry } from "@lib/content" +import { listSlimContent } from "@lib/content-source" import ParmesanFlecks from "@components/ParmesanFlecks.astro" import MeatballShower from "@components/MeatballShower.astro" -const allBlogEntries = await getCollection("blog", ({ data }) => !data.draft) -const posts = allBlogEntries - .sort(byDateDesc) - .slice(0, 3) - .map(toSearchEntry) +// Appwrite TablesDB first, bundled .md fallback (src/lib/content-source.ts). +// listSlimContent already returns published entries newest-first with the +// byDateDesc tie-break, so no local sort is needed here. +const blogSlim = await listSlimContent("blog") +const posts = blogSlim.slice(0, 3).map(toSearchEntry) -const allProjectEntries = await getCollection("projects", ({ data }) => !data.draft) -const projects = allProjectEntries - .sort(byDateDesc) - .slice(0, 3) - .map(toSearchEntry) +const projectSlim = await listSlimContent("projects") +const projects = projectSlim.slice(0, 3).map(toSearchEntry) const stack = [ { diff --git a/src/pages/legal/[...slug].astro b/src/pages/legal/[...slug].astro index 790c471..ce17c3b 100644 --- a/src/pages/legal/[...slug].astro +++ b/src/pages/legal/[...slug].astro @@ -1,22 +1,15 @@ --- -export const prerender = true; -import { getCollection } from "astro:content" +export const prerender = false; import PageLayout from "@layouts/PageLayout.astro" import TopLayout from "@layouts/TopLayout.astro" import BottomLayout from "@layouts/BottomLayout.astro" import { formatDate } from "@lib/utils" import { SITE } from "@consts" +import { getCollectionEntry } from "@lib/content-source" -export async function getStaticPaths() { - const entries = await getCollection("legal") - return entries.map((entry) => ({ - params: { slug: entry.id }, - props: { entry }, - })) -} - -const { entry } = Astro.props -const doc = entry +const { slug } = Astro.params +const doc = slug ? await getCollectionEntry("legal", slug) : null +if (!doc) return Astro.redirect("/") --- @@ -31,6 +24,6 @@ const doc = entry -
+
diff --git a/src/pages/projects/[...slug].astro b/src/pages/projects/[...slug].astro index 61d5b9b..fd98d8e 100644 --- a/src/pages/projects/[...slug].astro +++ b/src/pages/projects/[...slug].astro @@ -1,29 +1,19 @@ --- -import { getCollection } from "astro:content" import PageLayout from "@layouts/PageLayout.astro" import TopLayout from "@layouts/TopLayout.astro" import BottomLayout from "@layouts/BottomLayout.astro" import ArticleTopLayout from "@layouts/ArticleTopLayout.astro" import ArticleBottomLayout from "@layouts/ArticleBottomLayout.astro" +import { getCollectionContent, getCollectionEntry } from "@lib/content-source" -export const prerender = true +// Content comes from Appwrite at request time; see the note in +// src/pages/blog/[...slug].astro. +export const prerender = false -export async function getStaticPaths() { - const entries = await getCollection("projects", ({ data }) => !data.draft) - // Flatten frontmatter to the shape ArticleTopLayout/ArticleBottomLayout expect; - // see the note in src/pages/blog/[...slug].astro. - const flat = entries.map((entry) => ({ - ...entry, - ...entry.data, - content: entry.rendered?.html ?? "", - })) - return entries.map((entry, i) => ({ - params: { slug: entry.id }, - props: { entry: flat[i], allEntries: flat }, - })) -} - -const { entry, allEntries } = Astro.props +const { slug } = Astro.params +const entry = slug ? await getCollectionEntry("projects", slug) : null +if (!entry) return Astro.redirect("/projects") +const allEntries = (await getCollectionContent("projects")).reverse() const { title, summary } = entry.data --- diff --git a/src/pages/projects/index.astro b/src/pages/projects/index.astro index a5a3dcf..03adb60 100644 --- a/src/pages/projects/index.astro +++ b/src/pages/projects/index.astro @@ -1,24 +1,21 @@ --- -import { getCollection } from "astro:content" import PageLayout from "@layouts/PageLayout.astro" import TopLayout from "@layouts/TopLayout.astro" import BottomLayout from "@layouts/BottomLayout.astro" import FilteredList from "@components/FilteredList" import { PROJECTS } from "@consts" -import { byDateDesc } from "@lib/content" import { parseFilterParams } from "@lib/filters" +import { listSlimContent } from "@lib/content-source" -const entries = await getCollection("projects", ({ data }) => !data.draft) // Only the fields the cards and the filters read; see src/pages/blog/index.astro. -const projects = entries - .sort(byDateDesc) - .map((entry) => ({ - id: entry.id, - title: entry.data.title, - summary: entry.data.summary, - date: entry.data.date.toISOString(), - tags: entry.data.tags, - })) +const slim = await listSlimContent("projects") +const projects = slim.map((entry) => ({ + id: entry.id, + title: entry.data.title, + summary: entry.data.summary, + date: entry.data.date.toISOString(), + tags: entry.data.tags, +})) // Frontmatter runs on the server, so the initial filter state has to come from // the request URL rather than `window.location` (see src/pages/search/index.astro). diff --git a/src/pages/rss.xml.ts b/src/pages/rss.xml.ts index 3aa94a1..912e396 100644 --- a/src/pages/rss.xml.ts +++ b/src/pages/rss.xml.ts @@ -1,22 +1,21 @@ import rss from "@astrojs/rss" -import { getCollection } from "astro:content" import { SITE } from "@consts" +import { listSlimContent } from "@lib/content-source" type Context = { site: string } export async function GET(context: Context) { - const entries = await getCollection("blog", ({ data }) => !data.draft) - - const items = entries - .sort((a, b) => b.data.date.getTime() - a.data.date.getTime()) - .map((entry) => ({ - title: entry.data.title, - description: entry.data.summary, - pubDate: entry.data.date, - link: `/blog/${entry.id}/`, - })) + // Published posts, newest first (listSlimContent ordering). + const entries = await listSlimContent("blog") + + const items = entries.map((entry) => ({ + title: entry.data.title, + description: entry.data.summary, + pubDate: entry.data.date, + link: `/blog/${entry.id}/`, + })) return rss({ title: SITE.TITLE, diff --git a/src/pages/search/index.astro b/src/pages/search/index.astro index 81f95d5..2173e1d 100644 --- a/src/pages/search/index.astro +++ b/src/pages/search/index.astro @@ -1,38 +1,15 @@ --- -import { getCollection } from "astro:content" import PageLayout from "@layouts/PageLayout.astro" import TopLayout from "@layouts/TopLayout.astro" import BottomLayout from "@layouts/BottomLayout.astro" import Search from "@components/Search" import { SEARCH } from "@consts" import type { SearchEntry } from "@lib/search" +import { getSearchEntries } from "@lib/content-source" -// Blog posts -> slim searchable entries. -// `body` is intentionally NOT serialized to the client; see src/lib/search.ts. -const blogEntries = await getCollection("blog", ({ data }) => !data.draft) -const posts: SearchEntry[] = blogEntries.map((entry) => ({ - id: entry.id, - slug: entry.id, - collection: "blog", - title: entry.data.title, - summary: entry.data.summary, - date: entry.data.date.toISOString(), - tags: entry.data.tags, -})) - -// Projects -> slim searchable entries. -const projectEntries = await getCollection("projects", ({ data }) => !data.draft) -const projects: SearchEntry[] = projectEntries.map((entry) => ({ - id: entry.id, - slug: entry.id, - collection: "projects", - title: entry.data.title, - summary: entry.data.summary, - date: entry.data.date.toISOString(), - tags: entry.data.tags, -})) - -const entries: SearchEntry[] = [...posts, ...projects] +// Blog + projects -> slim searchable entries (fuse.js runs in the browser; +// `body` is intentionally NOT serialized to the client, see src/lib/search.ts). +const entries: SearchEntry[] = await getSearchEntries() // Read the `?search=` param from the incoming SSR request. // NOTE: this frontmatter runs on the server, so `window` is never available diff --git a/src/pages/work/index.astro b/src/pages/work/index.astro index 19b527a..0a64744 100644 --- a/src/pages/work/index.astro +++ b/src/pages/work/index.astro @@ -1,11 +1,11 @@ --- -import { getCollection } from "astro:content" import PageLayout from "@layouts/PageLayout.astro" import TopLayout from "@layouts/TopLayout.astro" import BottomLayout from "@layouts/BottomLayout.astro" import { WORK } from "@consts" +import { getCollectionContent } from "@lib/content-source" -const work = await getCollection("work") +const work = await getCollectionContent("work") function formatWorkDate(input: Date | string) { if (typeof input === "string") input = new Date(input) @@ -39,7 +39,7 @@ function formatWorkDate(input: Date | string) {
{entry.data.role}
-
+
)) }