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>
);
}