fix(news): preserve recoverable reads and verify publication against real services
CI / check (push) Failing after 29s
CI / deploy (push) Skipped
CI / publish-container (push) Skipped

This commit is contained in:
Simo committed 2026-09-13 19:31:32 +02:00
1 parent 8abfe352ef
commit f7b9b55700
33 files changed
+1377 -220

No files matched your search

+138
View File
@@ -0,0 +1,138 @@
import { renderToStaticMarkup } from "react-dom/server";
import { beforeEach, expect, it, vi } from "vitest";
const state = vi.hoisted(() => ({
missing: false,
fail: false,
sectionsFail: false,
}));
vi.mock("@/lib/auth", () => ({ auth: async () => ({ user: { id: "7" } }) }));
vi.mock("@/actions/article-comments", () => ({ postComment: async () => {} }));
vi.mock("@/actions/article-reactions", () => ({
toggleReaction: async () => {},
}));
vi.mock("@/lib/logger", () => ({ logger: { error: vi.fn() } }));
vi.mock("@/lib/public-page-performance", () => ({
withPublicPagePerformance: (_route: string, render: unknown) => render,
}));
vi.mock("next/navigation", () => ({
notFound: () => {
throw Error("ARTICLE_NOT_FOUND");
},
}));
vi.mock("next-intl/server", () => ({
getTranslations:
async () => (key: string, values?: Record<string, unknown>) =>
values ? `${key} ${Object.values(values).join(" ")}` : key,
}));
vi.mock("@/lib/services/news-cache", () => ({
cacheNews: async (_key: string, _ttl: number, load: () => Promise<unknown>) =>
load(),
}));
vi.mock("@/lib/db", async () => {
const schema = await import("@/db/schema");
const { drizzle } = await import("drizzle-orm/mysql-proxy");
return {
...schema,
db: drizzle(async () => {
throw Error("database offline");
}),
};
});
vi.mock("@/lib/services/news-detail", () => ({
getPublishedArticle: async () => {
if (state.fail) throw Error("database offline private connection details");
if (state.missing) return null;
return {
id: 12n,
slug: "community-update",
title: "Community update",
shortStory: "Summary",
fullStory: "<p>Readable article body</p>",
image: "",
createdAt: new Date("2030-01-01T00:00:00Z"),
updatedAt: null,
publishAt: new Date("2030-02-01T00:00:00Z"),
publishedAt: null,
};
},
getArticleComments: async (_id: bigint, page: number | "last") => {
if (state.sectionsFail) throw Error("comments offline");
return {
rows: [
{
id: 225n,
userId: 7,
comment: page === "last" ? "Newly posted comment" : "Earlier comment",
username: "Member",
createdAt: null,
},
],
total: 225,
page: page === "last" ? 9 : 1,
perPage: 25,
lastPage: 9,
};
},
getArticleReactions: async () => {
if (state.sectionsFail) throw Error("reactions offline");
return { counts: new Map([["love", 2]]), myReaction: "love" };
},
}));
import ArticlePage, { generateMetadata } from "./page";
beforeEach(() => {
state.missing = false;
state.fail = false;
state.sectionsFail = false;
});
const renderPage = async (search: Record<string, string> = {}) =>
renderToStaticMarkup(
await ArticlePage({
params: Promise.resolve({ slug: ["community-update"] }),
searchParams: Promise.resolve(search),
}),
);
it("keeps the article readable with explicit failures for comments and reactions", async () => {
state.sectionsFail = true;
const html = await renderPage();
expect(html).toContain("Readable article body");
expect(html).toContain("commentsUnavailable");
expect(html).toContain("reactionsUnavailable");
expect(html).not.toContain("noComments");
expect(html).not.toContain("noReactions");
expect(html).not.toContain("aria-pressed");
});
it("shows recoverable article failures without producing a false 404 or exposing diagnostics", async () => {
state.fail = true;
const html = await renderPage();
expect(html).toContain("loadError");
expect(html).toContain("retry");
expect(html).not.toContain("private connection details");
});
it("returns not found only when a successful lookup found no public article", async () => {
state.missing = true;
await expect(renderPage()).rejects.toThrow("ARTICLE_NOT_FOUND");
});
it("shows the newest comment after posting and preserves existing reaction controls", async () => {
const html = await renderPage({ comment: "posted" });
expect(html).toContain("Newly posted comment");
expect(html).toContain("commentsPage=8#comments");
expect(html).toContain("success.posted");
expect(html).toContain('aria-pressed="true"');
expect(html).toContain("2030-02-01");
expect(html).not.toContain("2030-01-01");
});
it("loads metadata from the same public article service", async () => {
expect(
await generateMetadata({
params: Promise.resolve({ slug: ["community-update"] }),
}),
).toMatchObject({ title: "Community update" });
});
+193 -184
View File
@@ -1,4 +1,3 @@
import { and, asc, eq, inArray, or, sql } from "drizzle-orm";
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { getTranslations } from "next-intl/server";
@@ -10,23 +9,22 @@ import { ContentCard, EmptyState } from "@/components/public/ui";
import { SanitizedHtml } from "@/components/shared/sanitized-html";
import { articleSlug } from "@/lib/article-input";
import { auth } from "@/lib/auth";
import {
db,
User,
WebsiteArticleComments,
WebsiteArticleReactions,
WebsiteArticles,
} from "@/lib/db";
import { excerpt } from "@/lib/format";
import { formatDate } from "@/lib/format-date";
import { logger } from "@/lib/logger";
import { withPublicPagePerformance } from "@/lib/public-page-performance";
import { sanitize } from "@/lib/sanitize";
import { cacheNews } from "@/lib/services/news-cache";
import {
getArticleComments,
getArticleReactions,
getPublishedArticle,
} from "@/lib/services/news-detail";
type SearchParams = Promise<{
comment?: string;
reaction?: string;
error?: string;
commentsPage?: string;
}>;
function feedbackStyle(tone: "success" | "error"): CSSProperties {
@@ -52,24 +50,10 @@ export async function generateMetadata({
}): Promise<Metadata> {
const appUrl = process.env.APP_URL ?? "http://localhost:3000";
const slug = articleSlug((await params).slug);
const [article] = await db
.select({
title: WebsiteArticles.title,
shortStory: WebsiteArticles.shortStory,
})
.from(WebsiteArticles)
.where(
and(
eq(WebsiteArticles.slug, slug),
eq(WebsiteArticles.status, "published"),
or(
sql`${WebsiteArticles.publishAt} IS NULL`,
sql`${WebsiteArticles.publishAt} <= NOW()`,
),
),
)
.limit(1)
.catch(() => []);
const article = await getPublishedArticle(slug).catch(() => {
logger.error("Public article metadata failed", { module: "news" });
return null;
});
if (!article) return { title: "Article" };
return {
title: article.title,
@@ -101,36 +85,28 @@ async function ArticlePage({
searchParams: SearchParams;
}) {
const slug = articleSlug((await params).slug);
const { comment, reaction, error } = await searchParams;
const { comment, reaction, error, commentsPage } = await searchParams;
const t = await getTranslations("pages.article");
const article = await cacheNews(`article:slug:${slug}`, 60_000, async () => {
const [row] = await db
.select({
id: WebsiteArticles.id,
slug: WebsiteArticles.slug,
title: WebsiteArticles.title,
shortStory: WebsiteArticles.shortStory,
fullStory: WebsiteArticles.fullStory,
image: WebsiteArticles.image,
createdAt: WebsiteArticles.createdAt,
updatedAt: WebsiteArticles.updatedAt,
})
.from(WebsiteArticles)
.where(
and(
eq(WebsiteArticles.slug, slug),
eq(WebsiteArticles.status, "published"),
or(
sql`${WebsiteArticles.publishAt} IS NULL`,
sql`${WebsiteArticles.publishAt} <= NOW()`,
),
),
)
.limit(1)
.catch(() => []);
return row ?? null;
});
let article: Awaited<ReturnType<typeof getPublishedArticle>>;
try {
article = await getPublishedArticle(slug);
} catch {
logger.error("Public article lookup failed", { module: "news" });
return (
<main className="page-grid">
<ContentCard icon="📰" title={t("loadError")}>
<p role="alert">{t("loadError")}</p>
<a
className="btn btn-outline"
href={`/news/${encodeURIComponent(slug)}`}
>
{t("retry")}
</a>
</ContentCard>
</main>
);
}
if (!article) notFound();
const articleId = article.id;
@@ -139,60 +115,33 @@ async function ArticlePage({
const loggedIn = Boolean(session?.user?.id);
const sessionUserId = session?.user?.id ? Number(session.user.id) : null;
// Reaction counts grouped by reaction type for this article, plus the
// signed-in user's currently-active reaction (so its button reads as pressed).
let reactionCounts = new Map<string, number>();
let myReaction: string | null = null;
try {
const rows = await db
.select({
reaction: WebsiteArticleReactions.reaction,
userId: WebsiteArticleReactions.userId,
})
.from(WebsiteArticleReactions)
.where(
and(
eq(WebsiteArticleReactions.articleId, articleId),
eq(WebsiteArticleReactions.active, true),
),
);
for (const r of rows) {
reactionCounts.set(r.reaction, (reactionCounts.get(r.reaction) ?? 0) + 1);
if (sessionUserId !== null && r.userId === sessionUserId)
myReaction = r.reaction;
}
} catch {
reactionCounts = new Map();
myReaction = null;
}
// Comments for this article (oldest first).
let comments: (typeof WebsiteArticleComments.$inferSelect)[] = [];
try {
comments = await db
.select()
.from(WebsiteArticleComments)
.where(eq(WebsiteArticleComments.articleId, articleId))
.orderBy(asc(WebsiteArticleComments.createdAt))
.limit(200);
} catch {
comments = [];
}
// Resolve usernames for the commenters (userId is the emulator users.id, Int).
const commenterIds = Array.from(new Set(comments.map((c) => c.userId)));
let usernameById = new Map<number, string>();
if (commenterIds.length > 0) {
try {
const users = await db
.select({ id: User.id, username: User.username })
.from(User)
.where(inArray(User.id, commenterIds));
usernameById = new Map(users.map((u) => [u.id, u.username]));
} catch {
usernameById = new Map();
}
}
const requestedPage =
comment === "posted" && !commentsPage ? "last" : Number(commentsPage ?? 1);
const [reactions, commentsResult] = await Promise.all([
getArticleReactions(articleId, sessionUserId).catch(() => {
logger.error("Public article reactions failed", {
module: "news",
articleId: String(articleId),
});
return null;
}),
getArticleComments(articleId, requestedPage).catch(() => {
logger.error("Public article comments failed", {
module: "news",
articleId: String(articleId),
});
return null;
}),
]);
const reactionCounts = reactions?.counts ?? new Map<string, number>();
const myReaction = reactions?.myReaction ?? null;
const comments = commentsResult?.rows ?? [];
const articleHref = `/news/${encodeURIComponent(slug)}`;
const commentsHref = (page: number) =>
`${articleHref}?commentsPage=${page}#comments`;
const retryHref = commentsPage
? `${articleHref}?${new URLSearchParams({ commentsPage })}`
: articleHref;
const errorMessage =
error === "empty"
@@ -231,7 +180,9 @@ async function ArticlePage({
icon="📰"
title={article.title}
subtitle={
article.createdAt ? formatDate(article.createdAt, "date") : undefined
(article.publishAt ?? article.createdAt)
? formatDate(article.publishAt ?? article.createdAt, "date")
: undefined
}
action={
<Link className="btn btn-outline" href="/news">
@@ -261,7 +212,14 @@ async function ArticlePage({
title={t("reactionsTitle")}
subtitle={t("reactionsSubtitle")}
>
{loggedIn ? (
{!reactions ? (
<div role="alert">
<p>{t("reactionsUnavailable")}</p>
<a className="btn btn-outline" href={retryHref}>
{t("retry")}
</a>
</div>
) : loggedIn ? (
<div style={{ display: "flex", gap: "0.5rem", flexWrap: "wrap" }}>
{REACTIONS.map((r) => {
const active = myReaction === r.key;
@@ -331,80 +289,131 @@ async function ArticlePage({
</ContentCard>
{/* ── Comments ──────────────────────────────────────────── */}
<ContentCard
icon="🗨️"
title={t("commentsTitle")}
subtitle={
comments.length > 0
? t("commentsCount", { count: comments.length })
: t("commentsSubtitle")
}
>
{comments.length === 0 ? (
<EmptyState icon="🗨️">{t("noComments")}</EmptyState>
) : (
<div className="grid" style={{ marginBottom: "1.5rem" }}>
{comments.map((c) => {
const name = usernameById.get(c.userId);
return (
<article key={String(c.id)} className="card">
<p
className="muted"
style={{ marginTop: 0, marginBottom: "0.35rem" }}
>
{name ? (
<Link href={`/u/${name}`}>{name}</Link>
) : (
<span>{t("userNumber", { id: c.userId })}</span>
)}
{c.createdAt ? (
<span> · {formatDate(c.createdAt, "date", "")}</span>
) : null}
</p>
<p style={{ margin: 0, whiteSpace: "pre-wrap" }}>
{c.comment}
</p>
</article>
);
})}
</div>
)}
{loggedIn ? (
<form action={postComment} className="card">
<input type="hidden" name="articleId" value={String(articleId)} />
<input type="hidden" name="slug" value={slug} />
<label
htmlFor="comment"
style={{
display: "block",
fontWeight: 700,
marginBottom: "0.5rem",
}}
>
{t("addComment")}
</label>
<textarea
id="comment"
name="comment"
required
maxLength={255}
rows={3}
placeholder={t("commentPlaceholder")}
style={{ width: "100%", resize: "vertical" }}
/>
<div style={{ marginTop: "0.75rem" }}>
<button type="submit" className="btn btn-primary">
{t("postComment")}
</button>
<section id="comments" aria-label={t("commentsTitle")}>
<ContentCard
icon="🗨️"
title={t("commentsTitle")}
subtitle={
commentsResult && commentsResult.total > 0
? t("commentsCount", { count: commentsResult.total })
: t("commentsSubtitle")
}
>
{!commentsResult ? (
<div role="alert">
<p>{t("commentsUnavailable")}</p>
<a className="btn btn-outline" href={`${retryHref}#comments`}>
{t("retry")}
</a>
</div>
</form>
) : (
<p className="muted">
<Link href="/login">{t("logIn")}</Link> {t("toComment")}
</p>
)}
</ContentCard>
) : comments.length === 0 ? (
<EmptyState icon="🗨️">{t("noComments")}</EmptyState>
) : (
<div className="grid" style={{ marginBottom: "1.5rem" }}>
{comments.map((c) => {
const name = c.username;
return (
<article key={String(c.id)} className="card">
<p
className="muted"
style={{ marginTop: 0, marginBottom: "0.35rem" }}
>
{name ? (
<Link href={`/u/${name}`}>{name}</Link>
) : (
<span>{t("userNumber", { id: c.userId })}</span>
)}
{c.createdAt ? (
<span> · {formatDate(c.createdAt, "date", "")}</span>
) : null}
</p>
<p
style={{
margin: 0,
whiteSpace: "pre-wrap",
overflowWrap: "anywhere",
}}
>
{c.comment}
</p>
</article>
);
})}
</div>
)}
{commentsResult && commentsResult.lastPage > 1 ? (
<nav
aria-label={t("commentsPagination")}
className="flex flex-wrap items-center justify-between gap-3"
style={{ marginBottom: "1rem" }}
>
{commentsResult.page > 1 ? (
<Link
className="btn btn-outline"
href={commentsHref(commentsResult.page - 1)}
>
{t("previous")}
</Link>
) : (
<span />
)}
<span>
{t("commentsPageSummary", {
page: commentsResult.page,
pages: commentsResult.lastPage,
total: commentsResult.total,
})}
</span>
{commentsResult.page < commentsResult.lastPage ? (
<Link
className="btn btn-outline"
href={commentsHref(commentsResult.page + 1)}
>
{t("next")}
</Link>
) : (
<span />
)}
</nav>
) : null}
{loggedIn ? (
<form action={postComment} className="card">
<input type="hidden" name="articleId" value={String(articleId)} />
<input type="hidden" name="slug" value={slug} />
<label
htmlFor="comment"
style={{
display: "block",
fontWeight: 700,
marginBottom: "0.5rem",
}}
>
{t("addComment")}
</label>
<textarea
id="comment"
name="comment"
required
maxLength={255}
rows={3}
placeholder={t("commentPlaceholder")}
style={{ width: "100%", resize: "vertical" }}
/>
<div style={{ marginTop: "0.75rem" }}>
<button type="submit" className="btn btn-primary">
{t("postComment")}
</button>
</div>
</form>
) : (
<p className="muted">
<Link href="/login">{t("logIn")}</Link> {t("toComment")}
</p>
)}
</ContentCard>
</section>
</main>
);
}
+198
View File
@@ -0,0 +1,198 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const state = vi.hoisted(() => ({
fail: false,
articleRows: [] as unknown[][],
commentRows: [] as unknown[][],
reactionRows: [] as unknown[][],
total: 225,
queries: [] as { sql: string; params: unknown[] }[],
values: new Map<string, string>(),
}));
vi.mock("@/lib/services/news-cache", () => ({
cacheNews: async (
key: string,
_ttl: number,
query: () => Promise<unknown>,
) => {
const existing = state.values.get(key);
if (existing !== undefined) return JSON.parse(existing);
const result = await query();
const serialized = JSON.stringify(result);
state.values.set(key, serialized);
return JSON.parse(serialized);
},
}));
vi.mock("@/lib/db", async () => {
const schema = await import("@/db/schema");
const { drizzle } = await import("drizzle-orm/mysql-proxy");
return {
...schema,
db: drizzle(async (sql, params) => {
state.queries.push({ sql, params });
if (state.fail) throw new Error("database unavailable");
if (sql.includes("count(*)") && !sql.includes("group by"))
return { rows: [[state.total]] };
if (sql.includes("website_article_comments"))
return { rows: state.commentRows };
if (sql.includes("website_article_reactions"))
return { rows: state.reactionRows };
return { rows: state.articleRows };
}),
};
});
import {
getArticleComments,
getArticleReactions,
getPublishedArticle,
} from "./news-detail";
beforeEach(() => {
state.fail = false;
state.values.clear();
state.queries = [];
state.articleRows = [];
state.commentRows = [];
state.reactionRows = [];
state.total = 225;
});
describe("public article loading", () => {
it("keeps database failures retryable instead of caching a missing article", async () => {
state.fail = true;
await expect(getPublishedArticle("community-update")).rejects.toThrow();
state.fail = false;
expect(await getPublishedArticle("community-update")).toBeNull();
expect(state.queries).toHaveLength(2);
});
it("round-trips large IDs and publication dates through a JSON cache", async () => {
state.articleRows = [
[
"9007199254740993",
"community-update",
"Title",
"Summary",
"<p>Body</p>",
"",
"2030-01-01 10:00:00",
"2030-02-01 10:00:00",
"2030-02-01 10:00:00",
"2030-02-01 10:01:00",
],
];
const article = await getPublishedArticle("community-update");
expect(article?.id).toBe(9007199254740993n);
expect(article?.publishAt).toEqual(new Date("2030-02-01T10:00:00Z"));
expect(article?.createdAt).toEqual(new Date("2030-01-01T10:00:00Z"));
expect(await getPublishedArticle("community-update")).toEqual(article);
expect(state.queries).toHaveLength(1);
});
it("only selects articles that are published and already due", async () => {
expect(await getPublishedArticle("quote'")).toBeNull();
expect(state.queries[0].sql).toContain("`status` = ?");
expect(state.queries[0].sql).toContain("<= NOW()");
expect(state.queries[0].params).toEqual(["quote'", "published", 1]);
});
});
describe("public article comments", () => {
it("makes comments beyond the former 200 item ceiling reachable", async () => {
state.commentRows = [
["225", 7, "Comment beyond 200", "2030-01-01 12:00:00", "Member"],
];
const result = await getArticleComments(12n, 9);
expect(result).toMatchObject({
total: 225,
page: 9,
perPage: 25,
lastPage: 9,
rows: [{ id: 225n, comment: "Comment beyond 200", username: "Member" }],
});
expect(state.queries[1].params.slice(-2)).toEqual([25, 200]);
expect(state.queries[1].sql).toMatch(
/order by .*`created_at` asc, .*`id` asc/,
);
expect(state.queries.every((query) => query.params[0] === 12n)).toBe(true);
});
it.each([
[-5, 1, 0],
[NaN, 1, 0],
[Infinity, 1, 0],
[1e99, 9, 200],
["last", 9, 200],
])("bounds requested page %s", async (requested, page, offset) => {
expect(
await getArticleComments(12n, requested as number | "last"),
).toMatchObject({ page });
expect(state.queries[1].params).toEqual(
offset === 0 ? [12n, 25] : [12n, 25, offset],
);
});
it("preserves a successful empty page", async () => {
state.total = 0;
expect(await getArticleComments(12n, "last")).toMatchObject({
rows: [],
total: 0,
page: 1,
lastPage: 1,
});
});
it("propagates a failed comment read instead of claiming there are no comments", async () => {
state.fail = true;
await expect(getArticleComments(12n)).rejects.toThrow();
});
});
describe("public article reactions", () => {
it("aggregates counts and the current user's reaction without loading every vote", async () => {
state.reactionRows = [
["love", 1200, 1],
["like", 30, 0],
];
const result = await getArticleReactions(12n, 7);
expect(result.counts.get("love")).toBe(1200);
expect(result.myReaction).toBe("love");
expect(state.queries[0].sql).toContain("group by");
expect(state.queries[0].params).toContain(7);
});
it("does not hide a failed reaction read behind zero counts", async () => {
state.fail = true;
await expect(getArticleReactions(12n, null)).rejects.toThrow();
});
});
it("ignores legacy cached absence and loads the current public article", async () => {
state.values.set("article:slug:community-update", "null");
state.articleRows = [
[
"12",
"community-update",
"Current article",
"Summary",
"<p>Current body</p>",
"",
null,
null,
null,
null,
],
];
expect(await getPublishedArticle("community-update")).toMatchObject({
id: 12n,
title: "Current article",
fullStory: "<p>Current body</p>",
});
state.fail = true;
expect(await getPublishedArticle("community-update")).toMatchObject({
id: 12n,
title: "Current article",
});
expect(state.queries).toHaveLength(1);
});
+140
View File
@@ -0,0 +1,140 @@
import "server-only";
import { and, asc, count, eq, or, sql } from "drizzle-orm";
import {
db,
User,
WebsiteArticleComments,
WebsiteArticleReactions,
WebsiteArticles,
} from "@/lib/db";
import { cacheNews } from "@/lib/services/news-cache";
/** Null means a successful lookup found no public article. Failed reads must reject. */
export async function getPublishedArticle(slug: string) {
const cached = await cacheNews(
`article:v2:slug:${slug}`,
60_000,
async () => {
const [article] = await db
.select({
id: WebsiteArticles.id,
slug: WebsiteArticles.slug,
title: WebsiteArticles.title,
shortStory: WebsiteArticles.shortStory,
fullStory: WebsiteArticles.fullStory,
image: WebsiteArticles.image,
createdAt: WebsiteArticles.createdAt,
updatedAt: WebsiteArticles.updatedAt,
publishAt: WebsiteArticles.publishAt,
publishedAt: WebsiteArticles.publishedAt,
})
.from(WebsiteArticles)
.where(
and(
eq(WebsiteArticles.slug, slug),
eq(WebsiteArticles.status, "published"),
or(
sql`${WebsiteArticles.publishAt} IS NULL`,
sql`${WebsiteArticles.publishAt} <= NOW()`,
),
),
)
.limit(1);
if (!article) return null;
// Redis uses JSON: preserve full bigint precision and restore dates on reads.
return {
...article,
id: String(article.id),
createdAt: article.createdAt?.toISOString() ?? null,
updatedAt: article.updatedAt?.toISOString() ?? null,
publishAt: article.publishAt?.toISOString() ?? null,
publishedAt: article.publishedAt?.toISOString() ?? null,
};
},
);
if (!cached) return null;
return {
...cached,
id: BigInt(cached.id),
createdAt: cached.createdAt ? new Date(cached.createdAt) : null,
updatedAt: cached.updatedAt ? new Date(cached.updatedAt) : null,
publishAt: cached.publishAt ? new Date(cached.publishAt) : null,
publishedAt: cached.publishedAt ? new Date(cached.publishedAt) : null,
};
}
export type PublishedArticle = NonNullable<
Awaited<ReturnType<typeof getPublishedArticle>>
>;
export async function getArticleComments(
articleId: bigint,
requestedPage: number | "last" = 1,
) {
const where = eq(WebsiteArticleComments.articleId, articleId);
const [totals] = await db
.select({ value: count() })
.from(WebsiteArticleComments)
.where(where);
const total = Number(totals?.value ?? 0);
const perPage = 25;
const lastPage = Math.max(1, Math.ceil(total / perPage));
const page =
requestedPage === "last"
? lastPage
: Math.min(
lastPage,
Number.isFinite(requestedPage)
? Math.max(1, Math.trunc(requestedPage))
: 1,
);
const rows = await db
.select({
id: WebsiteArticleComments.id,
userId: WebsiteArticleComments.userId,
comment: WebsiteArticleComments.comment,
createdAt: WebsiteArticleComments.createdAt,
username: User.username,
})
.from(WebsiteArticleComments)
.leftJoin(User, eq(User.id, WebsiteArticleComments.userId))
.where(where)
.orderBy(
asc(WebsiteArticleComments.createdAt),
asc(WebsiteArticleComments.id),
)
.limit(perPage)
.offset((page - 1) * perPage);
return { rows, total, page, perPage, lastPage };
}
export type ArticleComments = Awaited<ReturnType<typeof getArticleComments>>;
export async function getArticleReactions(
articleId: bigint,
userId: number | null,
) {
const rows = await db
.select({
reaction: WebsiteArticleReactions.reaction,
count: count(),
mine:
userId === null
? sql<number>`0`
: sql<number>`MAX(CASE WHEN ${WebsiteArticleReactions.userId} = ${userId} THEN 1 ELSE 0 END)`,
})
.from(WebsiteArticleReactions)
.where(
and(
eq(WebsiteArticleReactions.articleId, articleId),
eq(WebsiteArticleReactions.active, true),
),
)
.groupBy(WebsiteArticleReactions.reaction);
return {
counts: new Map(rows.map((row) => [row.reaction, Number(row.count)])),
myReaction: rows.find((row) => Number(row.mine) > 0)?.reaction ?? null,
};
}
export type ArticleReactions = Awaited<ReturnType<typeof getArticleReactions>>;
+32 -2
View File
@@ -1,5 +1,6 @@
import type { SQL } from "drizzle-orm";
import { MySqlDialect } from "drizzle-orm/mysql-core";
import { format } from "mysql2";
import { beforeEach, expect, it, vi } from "vitest";
const state = vi.hoisted(() => ({
@@ -9,6 +10,7 @@ const state = vi.hoisted(() => ({
status: string;
publishAt: Date;
}>,
queries: [] as Array<{ sql: string; params: unknown[] }>,
operations: [] as unknown[][],
effects: [] as unknown[][],
failOutbox: false,
@@ -19,15 +21,20 @@ vi.mock("@/lib/logger", () => ({ logger: { error: vi.fn() } }));
vi.mock("./news-cache", () => ({ invalidateNewsCache: state.refresh }));
vi.mock("@/lib/db", () => {
const dialect = new MySqlDialect();
const timestamp = (value: unknown) =>
value instanceof Date
? value
: new Date(`${String(value).replace(" ", "T")}Z`);
const tx = {
execute: async (query: SQL) => {
const { sql, params } = dialect.sqlToQuery(query);
state.queries.push({ sql, params });
if (sql.startsWith("SELECT"))
return [
state.articles
.filter(
(a) =>
a.status === "scheduled" && a.publishAt <= (params[0] as Date),
a.status === "scheduled" && a.publishAt <= timestamp(params[0]),
)
.slice(0, 100),
];
@@ -37,7 +44,7 @@ vi.mock("@/lib/db", () => {
state.loseRace ||
!article ||
article.status !== "scheduled" ||
article.publishAt > (params[3] as Date)
article.publishAt > timestamp(params[3])
)
return [{ affectedRows: 0 }];
article.status = "published";
@@ -83,6 +90,7 @@ beforeEach(() => {
publishAt: new Date("2030-01-01T00:00:00Z"),
},
];
state.queries = [];
state.operations = [];
state.effects = [];
state.failOutbox = false;
@@ -128,3 +136,25 @@ it("reports committed publication even when immediate cache refresh fails", asyn
expect(state.effects).toHaveLength(1);
expect(state.refresh).toHaveBeenCalledOnce();
});
it("uses the same UTC cutoff and publication timestamps regardless of the MySQL client timezone", async () => {
const instant = new Date("2030-06-01T08:09:10.123Z");
expect(await publishDueArticles(instant)).toBe(1);
const statements = state.queries.filter(
({ sql }) =>
sql.startsWith("SELECT") || sql.startsWith("UPDATE website_articles"),
);
expect(statements).toHaveLength(2);
for (const statement of statements) {
expect(format(statement.sql, statement.params, false, "+02:00")).toBe(
format(statement.sql, statement.params, false, "-07:00"),
);
}
expect(statements[0].params).toEqual(["2030-06-01 08:09:10.123"]);
expect(statements[1].params).toEqual([
"2030-06-01 08:09:10.123",
"2030-06-01 08:09:10.123",
"1",
"2030-06-01 08:09:10.123",
]);
});
+4 -2
View File
@@ -9,9 +9,11 @@ import { invalidateNewsCache } from "./news-cache";
/** Publish a bounded batch and persist its refresh work before committing. */
export async function publishDueArticles(now = new Date()): Promise<number> {
// Match Drizzle's TIMESTAMP writes; raw Date parameters use the host timezone.
const utcNow = now.toISOString().slice(0, -1).replace("T", " ");
const published = await db.transaction(async (tx) => {
const [rows] = await tx.execute(
sql`SELECT CAST(id AS CHAR) AS id,user_id AS userId,publish_at AS publishAt FROM website_articles WHERE status='scheduled' AND publish_at<=${now} ORDER BY publish_at,id LIMIT 100 FOR UPDATE`,
sql`SELECT CAST(id AS CHAR) AS id,user_id AS userId,publish_at AS publishAt FROM website_articles WHERE status='scheduled' AND publish_at<=${utcNow} ORDER BY publish_at,id LIMIT 100 FOR UPDATE`,
);
let published = 0;
for (const article of rows as unknown as Array<{
@@ -20,7 +22,7 @@ export async function publishDueArticles(now = new Date()): Promise<number> {
publishAt: Date | string;
}>) {
const [result] = await tx.execute(
sql`UPDATE website_articles SET status='published',published_at=${now},updated_at=${now} WHERE id=${article.id} AND status='scheduled' AND publish_at<=${now}`,
sql`UPDATE website_articles SET status='published',published_at=${utcNow},updated_at=${utcNow} WHERE id=${article.id} AND status='scheduled' AND publish_at<=${utcNow}`,
);
if ((result as unknown as { affectedRows: number }).affectedRows !== 1)
continue;
+9 -1
View File
@@ -3919,7 +3919,15 @@
"invalid": "Invalid comment.",
"notFound": "That article was not found.",
"error": "Something went wrong. Please try again."
}
},
"loadError": "This article is temporarily unavailable.",
"retry": "Try again",
"commentsUnavailable": "Comments are temporarily unavailable.",
"reactionsUnavailable": "Reactions are temporarily unavailable.",
"commentsPagination": "Comment pages",
"previous": "Previous",
"next": "Next",
"commentsPageSummary": "Page {page} of {pages} · {total} comments"
},
"photos": {
"title": "Photos",
+9 -1
View File
@@ -297,7 +297,15 @@
"invalid": "Invalid comment.",
"notFound": "That article was not found.",
"error": "Something went wrong. Please try again."
}
},
"loadError": "This article is temporarily unavailable.",
"retry": "Try again",
"commentsUnavailable": "Comments are temporarily unavailable.",
"reactionsUnavailable": "Reactions are temporarily unavailable.",
"commentsPagination": "Comment pages",
"previous": "Previous",
"next": "Next",
"commentsPageSummary": "Page {page} of {pages} · {total} comments"
},
"photos": {
"title": "Снимки",
+9 -1
View File
@@ -297,7 +297,15 @@
"invalid": "Invalid comment.",
"notFound": "That article was not found.",
"error": "Something went wrong. Please try again."
}
},
"loadError": "This article is temporarily unavailable.",
"retry": "Try again",
"commentsUnavailable": "Comments are temporarily unavailable.",
"reactionsUnavailable": "Reactions are temporarily unavailable.",
"commentsPagination": "Comment pages",
"previous": "Previous",
"next": "Next",
"commentsPageSummary": "Page {page} of {pages} · {total} comments"
},
"photos": {
"title": "Fotografie",
+9 -1
View File
@@ -297,7 +297,15 @@
"invalid": "Invalid comment.",
"notFound": "That article was not found.",
"error": "Something went wrong. Please try again."
}
},
"loadError": "This article is temporarily unavailable.",
"retry": "Try again",
"commentsUnavailable": "Comments are temporarily unavailable.",
"reactionsUnavailable": "Reactions are temporarily unavailable.",
"commentsPagination": "Comment pages",
"previous": "Previous",
"next": "Next",
"commentsPageSummary": "Page {page} of {pages} · {total} comments"
},
"photos": {
"title": "Fotos",
+9 -1
View File
@@ -297,7 +297,15 @@
"invalid": "Invalid comment.",
"notFound": "That article was not found.",
"error": "Something went wrong. Please try again."
}
},
"loadError": "This article is temporarily unavailable.",
"retry": "Try again",
"commentsUnavailable": "Comments are temporarily unavailable.",
"reactionsUnavailable": "Reactions are temporarily unavailable.",
"commentsPagination": "Comment pages",
"previous": "Previous",
"next": "Next",
"commentsPageSummary": "Page {page} of {pages} · {total} comments"
},
"photos": {
"title": "Fotos",
+9 -1
View File
@@ -297,7 +297,15 @@
"invalid": "Invalid comment.",
"notFound": "That article was not found.",
"error": "Something went wrong. Please try again."
}
},
"loadError": "This article is temporarily unavailable.",
"retry": "Try again",
"commentsUnavailable": "Comments are temporarily unavailable.",
"reactionsUnavailable": "Reactions are temporarily unavailable.",
"commentsPagination": "Comment pages",
"previous": "Previous",
"next": "Next",
"commentsPageSummary": "Page {page} of {pages} · {total} comments"
},
"photos": {
"title": "Φωτογραφίες",
+9 -1
View File
@@ -339,7 +339,15 @@
"invalid": "Invalid comment.",
"notFound": "That article was not found.",
"error": "Something went wrong. Please try again."
}
},
"loadError": "This article is temporarily unavailable.",
"retry": "Try again",
"commentsUnavailable": "Comments are temporarily unavailable.",
"reactionsUnavailable": "Reactions are temporarily unavailable.",
"commentsPagination": "Comment pages",
"previous": "Previous",
"next": "Next",
"commentsPageSummary": "Page {page} of {pages} · {total} comments"
},
"photos": {
"title": "Photos",
+9 -1
View File
@@ -297,7 +297,15 @@
"invalid": "Invalid comment.",
"notFound": "That article was not found.",
"error": "Something went wrong. Please try again."
}
},
"loadError": "This article is temporarily unavailable.",
"retry": "Try again",
"commentsUnavailable": "Comments are temporarily unavailable.",
"reactionsUnavailable": "Reactions are temporarily unavailable.",
"commentsPagination": "Comment pages",
"previous": "Previous",
"next": "Next",
"commentsPageSummary": "Page {page} of {pages} · {total} comments"
},
"photos": {
"title": "Fotos",
+9 -1
View File
@@ -3919,7 +3919,15 @@
"invalid": "Invalid comment.",
"notFound": "That article was not found.",
"error": "Something went wrong. Please try again."
}
},
"loadError": "This article is temporarily unavailable.",
"retry": "Try again",
"commentsUnavailable": "Comments are temporarily unavailable.",
"reactionsUnavailable": "Reactions are temporarily unavailable.",
"commentsPagination": "Comment pages",
"previous": "Previous",
"next": "Next",
"commentsPageSummary": "Page {page} of {pages} · {total} comments"
},
"photos": {
"title": "Photos",
+9 -1
View File
@@ -297,7 +297,15 @@
"invalid": "Invalid comment.",
"notFound": "That article was not found.",
"error": "Something went wrong. Please try again."
}
},
"loadError": "This article is temporarily unavailable.",
"retry": "Try again",
"commentsUnavailable": "Comments are temporarily unavailable.",
"reactionsUnavailable": "Reactions are temporarily unavailable.",
"commentsPagination": "Comment pages",
"previous": "Previous",
"next": "Next",
"commentsPageSummary": "Page {page} of {pages} · {total} comments"
},
"photos": {
"title": "Photos",
+9 -1
View File
@@ -297,7 +297,15 @@
"invalid": "Invalid comment.",
"notFound": "That article was not found.",
"error": "Something went wrong. Please try again."
}
},
"loadError": "This article is temporarily unavailable.",
"retry": "Try again",
"commentsUnavailable": "Comments are temporarily unavailable.",
"reactionsUnavailable": "Reactions are temporarily unavailable.",
"commentsPagination": "Comment pages",
"previous": "Previous",
"next": "Next",
"commentsPageSummary": "Page {page} of {pages} · {total} comments"
},
"photos": {
"title": "Fotografije",
+9 -1
View File
@@ -297,7 +297,15 @@
"invalid": "Invalid comment.",
"notFound": "That article was not found.",
"error": "Something went wrong. Please try again."
}
},
"loadError": "This article is temporarily unavailable.",
"retry": "Try again",
"commentsUnavailable": "Comments are temporarily unavailable.",
"reactionsUnavailable": "Reactions are temporarily unavailable.",
"commentsPagination": "Comment pages",
"previous": "Previous",
"next": "Next",
"commentsPageSummary": "Page {page} of {pages} · {total} comments"
},
"photos": {
"title": "Fényképek",
+9 -1
View File
@@ -339,7 +339,15 @@
"invalid": "Commento non valido.",
"notFound": "Articolo non trovato.",
"error": "Qualcosa è andato storto. Riprova."
}
},
"loadError": "Questo articolo è temporaneamente non disponibile.",
"retry": "Riprova",
"commentsUnavailable": "I commenti sono temporaneamente non disponibili.",
"reactionsUnavailable": "Le reazioni sono temporaneamente non disponibili.",
"commentsPagination": "Pagine dei commenti",
"previous": "Precedente",
"next": "Successiva",
"commentsPageSummary": "Pagina {page} di {pages} · {total} commenti"
},
"photos": {
"title": "Foto",
+9 -1
View File
@@ -3919,7 +3919,15 @@
"invalid": "Invalid comment.",
"notFound": "That article was not found.",
"error": "Something went wrong. Please try again."
}
},
"loadError": "This article is temporarily unavailable.",
"retry": "Try again",
"commentsUnavailable": "Comments are temporarily unavailable.",
"reactionsUnavailable": "Reactions are temporarily unavailable.",
"commentsPagination": "Comment pages",
"previous": "Previous",
"next": "Next",
"commentsPageSummary": "Page {page} of {pages} · {total} comments"
},
"photos": {
"title": "Photos",
+9 -1
View File
@@ -339,7 +339,15 @@
"invalid": "Ongeldige reactie.",
"notFound": "Dat artikel is niet gevonden.",
"error": "Er ging iets mis. Probeer het opnieuw."
}
},
"loadError": "Dit artikel is tijdelijk niet beschikbaar.",
"retry": "Opnieuw proberen",
"commentsUnavailable": "Reacties zijn tijdelijk niet beschikbaar.",
"reactionsUnavailable": "Waarderingen zijn tijdelijk niet beschikbaar.",
"commentsPagination": "Reactiepagina’s",
"previous": "Vorige",
"next": "Volgende",
"commentsPageSummary": "Pagina {page} van {pages} · {total} reacties"
},
"photos": {
"title": "Foto's",
+9 -1
View File
@@ -297,7 +297,15 @@
"invalid": "Invalid comment.",
"notFound": "That article was not found.",
"error": "Something went wrong. Please try again."
}
},
"loadError": "This article is temporarily unavailable.",
"retry": "Try again",
"commentsUnavailable": "Comments are temporarily unavailable.",
"reactionsUnavailable": "Reactions are temporarily unavailable.",
"commentsPagination": "Comment pages",
"previous": "Previous",
"next": "Next",
"commentsPageSummary": "Page {page} of {pages} · {total} comments"
},
"photos": {
"title": "Bilder",
+9 -1
View File
@@ -297,7 +297,15 @@
"invalid": "Invalid comment.",
"notFound": "That article was not found.",
"error": "Something went wrong. Please try again."
}
},
"loadError": "This article is temporarily unavailable.",
"retry": "Try again",
"commentsUnavailable": "Comments are temporarily unavailable.",
"reactionsUnavailable": "Reactions are temporarily unavailable.",
"commentsPagination": "Comment pages",
"previous": "Previous",
"next": "Next",
"commentsPageSummary": "Page {page} of {pages} · {total} comments"
},
"photos": {
"title": "Zdjęcia",
+9 -1
View File
@@ -297,7 +297,15 @@
"invalid": "Invalid comment.",
"notFound": "That article was not found.",
"error": "Something went wrong. Please try again."
}
},
"loadError": "This article is temporarily unavailable.",
"retry": "Try again",
"commentsUnavailable": "Comments are temporarily unavailable.",
"reactionsUnavailable": "Reactions are temporarily unavailable.",
"commentsPagination": "Comment pages",
"previous": "Previous",
"next": "Next",
"commentsPageSummary": "Page {page} of {pages} · {total} comments"
},
"photos": {
"title": "Fotos",
+9 -1
View File
@@ -297,7 +297,15 @@
"invalid": "Invalid comment.",
"notFound": "That article was not found.",
"error": "Something went wrong. Please try again."
}
},
"loadError": "This article is temporarily unavailable.",
"retry": "Try again",
"commentsUnavailable": "Comments are temporarily unavailable.",
"reactionsUnavailable": "Reactions are temporarily unavailable.",
"commentsPagination": "Comment pages",
"previous": "Previous",
"next": "Next",
"commentsPageSummary": "Page {page} of {pages} · {total} comments"
},
"photos": {
"title": "Fotografii",
+9 -1
View File
@@ -297,7 +297,15 @@
"invalid": "Invalid comment.",
"notFound": "That article was not found.",
"error": "Something went wrong. Please try again."
}
},
"loadError": "This article is temporarily unavailable.",
"retry": "Try again",
"commentsUnavailable": "Comments are temporarily unavailable.",
"reactionsUnavailable": "Reactions are temporarily unavailable.",
"commentsPagination": "Comment pages",
"previous": "Previous",
"next": "Next",
"commentsPageSummary": "Page {page} of {pages} · {total} comments"
},
"photos": {
"title": "Фото",
+9 -1
View File
@@ -297,7 +297,15 @@
"invalid": "Invalid comment.",
"notFound": "That article was not found.",
"error": "Something went wrong. Please try again."
}
},
"loadError": "This article is temporarily unavailable.",
"retry": "Try again",
"commentsUnavailable": "Comments are temporarily unavailable.",
"reactionsUnavailable": "Reactions are temporarily unavailable.",
"commentsPagination": "Comment pages",
"previous": "Previous",
"next": "Next",
"commentsPageSummary": "Page {page} of {pages} · {total} comments"
},
"photos": {
"title": "Fotografie",
+9 -1
View File
@@ -297,7 +297,15 @@
"invalid": "Invalid comment.",
"notFound": "That article was not found.",
"error": "Something went wrong. Please try again."
}
},
"loadError": "This article is temporarily unavailable.",
"retry": "Try again",
"commentsUnavailable": "Comments are temporarily unavailable.",
"reactionsUnavailable": "Reactions are temporarily unavailable.",
"commentsPagination": "Comment pages",
"previous": "Previous",
"next": "Next",
"commentsPageSummary": "Page {page} of {pages} · {total} comments"
},
"photos": {
"title": "Фотографије",
+9 -1
View File
@@ -297,7 +297,15 @@
"invalid": "Invalid comment.",
"notFound": "That article was not found.",
"error": "Something went wrong. Please try again."
}
},
"loadError": "This article is temporarily unavailable.",
"retry": "Try again",
"commentsUnavailable": "Comments are temporarily unavailable.",
"reactionsUnavailable": "Reactions are temporarily unavailable.",
"commentsPagination": "Comment pages",
"previous": "Previous",
"next": "Next",
"commentsPageSummary": "Page {page} of {pages} · {total} comments"
},
"photos": {
"title": "Foton",
+9 -1
View File
@@ -297,7 +297,15 @@
"invalid": "Invalid comment.",
"notFound": "That article was not found.",
"error": "Something went wrong. Please try again."
}
},
"loadError": "This article is temporarily unavailable.",
"retry": "Try again",
"commentsUnavailable": "Comments are temporarily unavailable.",
"reactionsUnavailable": "Reactions are temporarily unavailable.",
"commentsPagination": "Comment pages",
"previous": "Previous",
"next": "Next",
"commentsPageSummary": "Page {page} of {pages} · {total} comments"
},
"photos": {
"title": "Fotoğraflar",
+9 -1
View File
@@ -297,7 +297,15 @@
"invalid": "Invalid comment.",
"notFound": "That article was not found.",
"error": "Something went wrong. Please try again."
}
},
"loadError": "This article is temporarily unavailable.",
"retry": "Try again",
"commentsUnavailable": "Comments are temporarily unavailable.",
"reactionsUnavailable": "Reactions are temporarily unavailable.",
"commentsPagination": "Comment pages",
"previous": "Previous",
"next": "Next",
"commentsPageSummary": "Page {page} of {pages} · {total} comments"
},
"photos": {
"title": "Фотографії",