Files
gerbeur/api/test/migrations.test.ts
khannurien de5abeceb2
All checks were successful
Build and Publish Docker Image / build-and-push (push) Successful in 49s
v3: a performance pass over both halves — indexed queries, streamed files, cached previews, and feeds that stop re-rendering on every tick — a review turned up whole-file reads, unindexed scans and render storms; each fix comes with a test. Database: migration 0016 adds the indexes the hot queries lacked — dumps by created_at, (user_id, created_at) and slug, votes by (user_id, created_at), playlists by slug, users by lower(username) for @mentions, and the child side of every cascading foreign key (comment replies, a user's comments, follows both ways, chat messages, invites, reset tokens); the feeds, dump and playlist pages, upvotes and follower fan-out all plan as index searches now, with no temp-table sort. SQLite runs in WAL with synchronous=NORMAL and a busy timeout, and a transaction() helper wraps the multi-row writes (a dump and its categories, category sets, backlinks, attachment links, playlist reorders, follower notifications) so they commit once instead of once a row. Lists no longer run a COUNT(*) per page: they fetch limit + 1 rows and hasMore comes from the extra one; total stays only on search, the one place it's shown. Files: /api/files read the whole upload (up to 50 MB) for every range request a player makes while seeking; api/lib/serve-file.ts streams the requested bytes from disk, with an ETag and 304s, and serves avatars, attachments, covers and thumbnails too. File and thumbnail URLs carry the file's version (size and last change), so the current one is cached for a year and anything else revalidates — a same-size replacement used to stay stale, and a video's still was cached immutable forever under a URL that never changed. Feeds showed image dumps at full size: /api/thumbnails now makes a 960px preview with ffmpeg (GIFs and unreadable images go out as they are), one run per output however many cards ask at once, and ffmpeg is probed once per process instead of spawned per request. Uploads stream to disk; replacing a file writes beside it and renames over, a hard link keeping the old one for rollback instead of holding both in memory; generated stills and previews go when the file is replaced or the dump deleted, and a custom thumbnail with its dump. Outbound: fetchWithTimeout's deadline now covers the body — a server that answered at once and then dripped could hold a create open indefinitely — and pages are read to 4 MB at most; metadata is cached five minutes so the create form's preview and the post that follows share one fetch (refresh-metadata still goes to the page); proxied images sit in a 32 MB LRU. Broadcasts serialize once rather than per socket, and index.html is kept in memory until the file changes. Frontend: currentTime lived in PlayerContext, so every card re-rendered — and re-parsed its Markdown — four times a second while anything played; the playhead has its own PlayerTimeContext now. The socket context is split three ways (feed, chat via useWSChat, presence via useWSPresence), so typing, presence and chat messages leave the feeds alone. DumpCard, JournalCard and Markdown are memoized; card images use the server preview and load lazily; the feed cache is written when the page is left rather than after every pause in scrolling; the theme context value is memoized.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-27 16:35:51 +00:00

183 lines
5.6 KiB
TypeScript

// Migrations run against fresh databases (built from schema.sql) and old ones;
// each must be idempotent, and the data rewrites must touch only what they
// mean to.
import "./setup.ts";
import { assertEquals } from "@std/assert";
import { DatabaseSync } from "node:sqlite";
import { runMigrations } from "../db/migrate.ts";
import { up as up0004 } from "../db/migrations/0004_user_roles.ts";
import { up as up0005 } from "../db/migrations/0005_drop_is_admin.ts";
import { up as up0010 } from "../db/migrations/0010_youtube_embed_start.ts";
import { up as up0011 } from "../db/migrations/0011_split_favicon_thumbnail.ts";
import { up as up0012 } from "../db/migrations/0012_fix_favicon_reclassification.ts";
const SCHEMA = Deno.readTextFileSync(
new URL("../db/schema.sql", import.meta.url),
);
function freshDb(): DatabaseSync {
const db = new DatabaseSync(":memory:");
db.exec(SCHEMA);
return db;
}
function schemaOf(db: DatabaseSync): string[] {
return (db.prepare(
`SELECT sql FROM sqlite_master WHERE sql IS NOT NULL AND name != 'schema_migrations' ORDER BY name;`,
).all() as { sql: string }[]).map((r) => r.sql);
}
Deno.test("runMigrations: a fresh database is left as schema.sql made it", () => {
const db = freshDb();
const before = schemaOf(db);
runMigrations(db);
assertEquals(schemaOf(db), before);
const applied = db.prepare(`SELECT COUNT(*) as n FROM schema_migrations;`)
.get() as {
n: number;
};
assertEquals(applied.n, 16);
// Running again applies nothing.
runMigrations(db);
assertEquals(
(db.prepare(`SELECT COUNT(*) as n FROM schema_migrations;`).get() as {
n: number;
}).n,
16,
);
db.close();
});
Deno.test("0004/0005: is_admin becomes role, then goes", () => {
const db = new DatabaseSync(":memory:");
db.exec(
`CREATE TABLE users (id TEXT PRIMARY KEY, is_admin INTEGER NOT NULL DEFAULT 0);`,
);
db.exec(`INSERT INTO users (id, is_admin) VALUES ('a', 1), ('b', 0);`);
up0004(db);
up0004(db);
up0005(db);
up0005(db);
assertEquals(
db.prepare(`SELECT id, role FROM users ORDER BY id;`).all().map((r) => ({
...r,
})),
[{ id: "a", role: "admin" }, { id: "b", role: "user" }],
);
const cols =
(db.prepare(`PRAGMA table_info(users);`).all() as { name: string }[])
.map((c) => c.name);
assertEquals(cols, ["id", "role"]);
db.close();
});
function insertRich(db: DatabaseSync, id: string, url: string, rich: unknown) {
db.prepare(
`INSERT INTO users (id, username, password_hash, created_at, email)
VALUES ('u', 'u', 'x', 'now', 'u@x') ON CONFLICT DO NOTHING;`,
).run();
db.prepare(
`INSERT INTO dumps (id, kind, title, user_id, created_at, url, rich_content)
VALUES (?, 'url', 't', 'u', 'now', ?, ?);`,
).run(id, url, typeof rich === "string" ? rich : JSON.stringify(rich));
}
function richOf(db: DatabaseSync, id: string): Record<string, unknown> {
return JSON.parse(
(db.prepare(`SELECT rich_content FROM dumps WHERE id = ?;`).get(id) as {
rich_content: string;
}).rich_content,
);
}
Deno.test("0010: adds the start offset to YouTube embeds that lost it", () => {
const db = freshDb();
const embed = "https://www.youtube.com/embed/abc?rel=0";
insertRich(db, "hms", "https://youtu.be/abc?t=1h2m3s", {
type: "youtube",
embedUrl: embed,
});
insertRich(db, "plain", "https://youtu.be/abc?start=42", {
type: "youtube",
embedUrl: embed,
});
insertRich(db, "none", "https://youtu.be/abc", {
type: "youtube",
embedUrl: embed,
});
insertRich(db, "has", "https://youtu.be/abc?t=5", {
type: "youtube",
embedUrl: `${embed}&start=9`,
});
insertRich(db, "other", "https://example.com/?t=5", {
type: "generic",
embedUrl: embed,
});
insertRich(db, "bad", "https://youtu.be/abc?t=5", "{not json");
up0010(db);
up0010(db);
assertEquals(richOf(db, "hms").embedUrl, `${embed}&start=3723`);
assertEquals(richOf(db, "plain").embedUrl, `${embed}&start=42`);
assertEquals(richOf(db, "none").embedUrl, embed);
assertEquals(richOf(db, "has").embedUrl, `${embed}&start=9`);
assertEquals(richOf(db, "other").embedUrl, embed);
db.close();
});
Deno.test("0011 then 0012: icons move to faviconUrl, artwork stays or comes back", () => {
const db = freshDb();
const cases: Record<
string,
[string, string | undefined, string | undefined]
> = {
// id: [thumbnailUrl before, thumbnailUrl after, faviconUrl after]
ico: [
"https://a.test/favicon.ico",
undefined,
"https://a.test/favicon.ico",
],
touch: [
"https://a.test/apple-touch-icon.png",
undefined,
"https://a.test/apple-touch-icon.png",
],
art: ["https://a.test/cover.jpg", "https://a.test/cover.jpg", undefined],
// 0011 mistook these for icons; 0012 puts them back.
logoFavicon: [
"https://a.test/uploads/mir-logo-favicon.png",
"https://a.test/uploads/mir-logo-favicon.png",
undefined,
],
svgArt: [
"https://a.test/art/poster.svg",
"https://a.test/art/poster.svg",
undefined,
],
// 0011 missed this one; 0012 catches it.
iconName: [
"https://a.test/img/icon_SEARCH.png",
undefined,
"https://a.test/img/icon_SEARCH.png",
],
};
for (const [id, [thumbnailUrl]] of Object.entries(cases)) {
insertRich(db, id, "https://a.test/", {
type: "generic",
url: "u",
thumbnailUrl,
});
}
up0011(db);
up0011(db);
up0012(db);
up0012(db);
for (const [id, [, thumbnailUrl, faviconUrl]] of Object.entries(cases)) {
const rich = richOf(db, id);
assertEquals([rich.thumbnailUrl, rich.faviconUrl], [
thumbnailUrl,
faviconUrl,
], id);
}
db.close();
});