mirror of
https://github.com/Hackdex-App/hackdex-website.git
synced 2026-12-05 07:47:52 -06:00
Stop Supabase outages from caching hack page 404s (#112)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
28
src/app/api/refresh/route.ts
Normal file
28
src/app/api/refresh/route.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { revalidatePath, revalidateTag } from "next/cache";
|
||||
import { checkUserRoles } from "@/utils/user";
|
||||
import { createClient } from "@/utils/supabase/server";
|
||||
import { revalidateDiscoverCatalog } from "@/app/discover/revalidate";
|
||||
|
||||
/**
|
||||
* Admin-only: drops the cached data and rendered pages for every hack, plus
|
||||
* the discover catalog. Use after a Supabase outage left bad pages cached.
|
||||
* For a single hack, use /api/refresh/[slug].
|
||||
*/
|
||||
export async function GET(req: NextRequest) {
|
||||
const supa = await createClient();
|
||||
const { data: user } = await supa.auth.getUser();
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
}
|
||||
const { isAdmin } = await checkUserRoles(supa);
|
||||
if (!isAdmin) {
|
||||
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
|
||||
}
|
||||
|
||||
// Every hack cache entry (metadata, downloads, redirect) carries the "hack" tag.
|
||||
revalidateTag("hack");
|
||||
revalidatePath("/hack/[slug]", "layout");
|
||||
revalidateDiscoverCatalog();
|
||||
return NextResponse.redirect(new URL("/discover", req.url));
|
||||
}
|
||||
41
src/app/hack/[slug]/error.tsx
Normal file
41
src/app/hack/[slug]/error.tsx
Normal file
@@ -0,0 +1,41 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { startTransition } from "react";
|
||||
|
||||
/** Shown when hack data fails to load (usually a Supabase outage), so it doesn't read as a missing hack. */
|
||||
export default function HackErrorPage({ reset }: { reset: () => void }) {
|
||||
const router = useRouter();
|
||||
|
||||
function retry() {
|
||||
startTransition(() => {
|
||||
router.refresh();
|
||||
reset();
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="mx-auto my-auto max-w-screen-2xl px-6 py-8 h-[calc(100vh-64px)] flex items-center justify-center">
|
||||
<div className="flex flex-col items-center justify-center gap-4">
|
||||
<h1 className="font-display text-[28px] leading-[1.1] md:text-[32px]">Couldn't load this hack</h1>
|
||||
<p className="text-lg text-text-3 text-center">Something went wrong loading the hack data. Try again in a moment.</p>
|
||||
<div className="mt-4 flex w-full flex-col gap-3 sm:w-auto sm:flex-row">
|
||||
<button
|
||||
type="button"
|
||||
onClick={retry}
|
||||
className="inline-flex h-14 w-full sm:h-12 sm:w-auto cursor-pointer items-center justify-center rounded-control bg-accent-deep px-5 text-base font-semibold sm:font-medium text-white transition-colors hover:bg-accent-hover focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-accent elevate"
|
||||
>
|
||||
Try again
|
||||
</button>
|
||||
<Link
|
||||
href="/discover"
|
||||
className="inline-flex h-14 w-full sm:h-12 sm:w-auto items-center justify-center rounded-control px-5 text-base font-semibold sm:font-medium text-text-2 transition-colors hover:text-text focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-accent"
|
||||
>
|
||||
View all hacks
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -12,6 +12,12 @@ import type { SelectablePatch } from "@/types/patcher";
|
||||
// stay out of "use server" files: every export there is a public endpoint that
|
||||
// anyone can call directly, which leaked private drafts and creator emails.
|
||||
// Callers gate what they render (drafts, admin-only email and contact).
|
||||
//
|
||||
// Every Supabase error throws instead of falling back to null or empty data.
|
||||
// unstable_cache doesn't store rejections, so an outage can't get cached as a
|
||||
// missing hack (404) or a page with no covers; the next request after Supabase
|
||||
// recovers loads fresh data, and hack-page renders that throw keep serving the
|
||||
// last good ISR page (or the error boundary if there isn't one yet).
|
||||
|
||||
export interface HackMetadata {
|
||||
hack: {
|
||||
@@ -67,7 +73,7 @@ export interface HackMetadata {
|
||||
};
|
||||
}
|
||||
|
||||
/** null for deleted hacks too; pages that get null should call `hackNotFound`. */
|
||||
/** null for missing and deleted hacks; pages that get null should call `hackNotFound`. Throws on Supabase errors. */
|
||||
export async function getHackMetadata(slug: string): Promise<HackMetadata | null> {
|
||||
const runner = cache(
|
||||
async () => {
|
||||
@@ -80,7 +86,8 @@ export async function getHackMetadata(slug: string): Promise<HackMetadata | null
|
||||
.is("deleted_at", null)
|
||||
.maybeSingle();
|
||||
|
||||
if (error || !hack) return null;
|
||||
if (error) throw error;
|
||||
if (!hack) return null;
|
||||
|
||||
// Security: Don't return verification_contact_info if hack is approved
|
||||
if (hack.approved) {
|
||||
@@ -89,20 +96,22 @@ export async function getHackMetadata(slug: string): Promise<HackMetadata | null
|
||||
|
||||
// Fetch covers
|
||||
let images: string[] = [];
|
||||
const { data: covers } = await supabase
|
||||
const { data: covers, error: coversError } = await supabase
|
||||
.from("hack_covers")
|
||||
.select("url, position")
|
||||
.eq("hack_slug", slug)
|
||||
.order("position", { ascending: true });
|
||||
if (coversError) throw coversError;
|
||||
if (covers && covers.length > 0) {
|
||||
images = getCoverUrls(covers.map(c => c.url));
|
||||
}
|
||||
|
||||
// Fetch tags
|
||||
const { data: tagRows } = await supabase
|
||||
const { data: tagRows, error: tagsError } = await supabase
|
||||
.from("hack_tags")
|
||||
.select("order,tags(name)")
|
||||
.eq("hack_slug", slug);
|
||||
if (tagsError) throw tagsError;
|
||||
|
||||
const tags = sortOrderedTags(
|
||||
(tagRows || [])
|
||||
@@ -113,16 +122,18 @@ export async function getHackMetadata(slug: string): Promise<HackMetadata | null
|
||||
).map((t) => t.name);
|
||||
|
||||
// Fetch profile
|
||||
const { data: profile } = await supabase
|
||||
const { data: profile, error: profileError } = await supabase
|
||||
.from("profiles")
|
||||
.select("id,username,avatar_url,verified")
|
||||
.eq("id", hack.created_by as string)
|
||||
.maybeSingle();
|
||||
if (profileError) throw profileError;
|
||||
|
||||
// Meant to only be available to admins (gated in server-side page rendering)
|
||||
let userEmail: string | null = null;
|
||||
if (profile) {
|
||||
const { data: userData } = await supabase.auth.admin.getUserById(profile.id);
|
||||
const { data: userData, error: userError } = await supabase.auth.admin.getUserById(profile.id);
|
||||
if (userError) throw userError;
|
||||
userEmail = userData?.user?.email || null;
|
||||
}
|
||||
|
||||
@@ -133,7 +144,7 @@ export async function getHackMetadata(slug: string): Promise<HackMetadata | null
|
||||
summary: string;
|
||||
}[] = [];
|
||||
if (!hack.is_archive && !hack.original_author) {
|
||||
const { data: otherHacksData } = await supabase
|
||||
const { data: otherHacksData, error: otherHacksError } = await supabase
|
||||
.from("hacks")
|
||||
.select("slug,title,summary")
|
||||
.eq("created_by", hack.created_by)
|
||||
@@ -143,6 +154,7 @@ export async function getHackMetadata(slug: string): Promise<HackMetadata | null
|
||||
.neq("slug", hack.slug)
|
||||
.order("downloads", { ascending: false })
|
||||
.limit(10);
|
||||
if (otherHacksError) throw otherHacksError;
|
||||
otherHacks = otherHacksData ?? [];
|
||||
}
|
||||
|
||||
@@ -155,11 +167,12 @@ export async function getHackMetadata(slug: string): Promise<HackMetadata | null
|
||||
changelog: string | null;
|
||||
} | null = null;
|
||||
if (hack.current_patch != null) {
|
||||
const { data: patchData } = await supabase
|
||||
const { data: patchData, error: patchError } = await supabase
|
||||
.from("patches")
|
||||
.select("id,bucket,filename,version,created_at,changelog")
|
||||
.eq("id", hack.current_patch)
|
||||
.maybeSingle();
|
||||
if (patchError) throw patchError;
|
||||
if (patchData) {
|
||||
patch = {
|
||||
id: patchData.id,
|
||||
@@ -219,8 +232,9 @@ export async function getHackDownloads(slug: string): Promise<number | null> {
|
||||
.select("downloads")
|
||||
.eq("slug", slug)
|
||||
.maybeSingle();
|
||||
|
||||
if (error || !hack) return null;
|
||||
|
||||
if (error) throw error;
|
||||
if (!hack) return null;
|
||||
return hack.downloads || 0;
|
||||
},
|
||||
[`hack:${slug}:downloads`],
|
||||
@@ -241,12 +255,13 @@ export async function hackNotFound(slug: string): Promise<never> {
|
||||
const runner = cache(
|
||||
async () => {
|
||||
const supabase = await createServiceClient();
|
||||
const { data } = await supabase
|
||||
const { data, error } = await supabase
|
||||
.from("hacks")
|
||||
.select("redirect_url")
|
||||
.eq("slug", slug)
|
||||
.not("deleted_at", "is", null)
|
||||
.maybeSingle();
|
||||
if (error) throw error;
|
||||
return data?.redirect_url ?? null;
|
||||
},
|
||||
[`hack:${slug}:redirect`],
|
||||
|
||||
@@ -2,6 +2,10 @@ import type { Database } from "@/types/db";
|
||||
import type { PatcherPatchSelection, SelectablePatch } from "@/types/patcher";
|
||||
import type { SupabaseClient } from "@supabase/supabase-js";
|
||||
|
||||
/**
|
||||
* Patches the patcher offers for a hack, plus the default pick. Throws on
|
||||
* Supabase errors so callers never mistake an outage for "no patches".
|
||||
*/
|
||||
export async function getPatcherSelectablePatches(
|
||||
supabase: SupabaseClient<Database>,
|
||||
slug: string,
|
||||
@@ -14,14 +18,7 @@ export async function getPatcherSelectablePatches(
|
||||
.eq("patches.published", true)
|
||||
.eq("patches.archived", false)
|
||||
.order("sort_order", { ascending: true });
|
||||
if (error) {
|
||||
console.error(error);
|
||||
return {
|
||||
savedPatchIds: [],
|
||||
selectablePatches: [],
|
||||
defaultPatchId: null,
|
||||
};
|
||||
}
|
||||
if (error) throw error;
|
||||
const savedPatchIds = rows.map((row) => row.patch_id);
|
||||
let selectablePatches: SelectablePatch[] = rows.map((row) => row.patches).flat().map((patch) => ({
|
||||
id: patch.id,
|
||||
@@ -36,14 +33,7 @@ export async function getPatcherSelectablePatches(
|
||||
.select("id, version, created_at, published, archived, filename")
|
||||
.eq("id", currentPatchId)
|
||||
.maybeSingle();
|
||||
if (currentPatchError) {
|
||||
console.error(currentPatchError);
|
||||
return {
|
||||
savedPatchIds: [],
|
||||
selectablePatches: [],
|
||||
defaultPatchId: null,
|
||||
};
|
||||
}
|
||||
if (currentPatchError) throw currentPatchError;
|
||||
if (currentPatch?.published && !currentPatch?.archived) {
|
||||
selectablePatches = [currentPatch];
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user