Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions apps/api/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,14 @@ const idParam = t.Object({
/** Upload-session token path param (bounded; storage layer also guards traversal). */
const tokenParam = t.Object({ token: t.String({ maxLength: 100 }) });

/** Opaque visitor-id shape: hex + dashes (UUID-like), length-bounded vs abuse. */
const VISITOR_ID_RE = /^[0-9a-fA-F-]{8,64}$/;

/** A valid client-supplied `x-visitor-id`, or null if absent/malformed. */
function readVisitorId(header: string | null): string | null {
return header !== null && VISITOR_ID_RE.test(header) ? header : null;
}

/** Project a domain {@link Asset} onto its JSON wire form. */
function serializeAsset(asset: Asset): AssetDto {
return {
Expand Down Expand Up @@ -145,6 +153,15 @@ export function createApp({ core, maxUploadBytes }: AppDependencies) {
.get("/health", () => ({ status: "ok" as const }))
.group("/api/v1", (api) =>
api
// Opaque visitor id for the traffic counters — never an IP. The client
// owns a stable id (localStorage) and sends it as `x-visitor-id`, so we
// read+validate it (no server-minted cookie → no first-load mint race).
// Left null when absent/invalid: the counter routes reject rather than
// synthesize a throwaway id, which would defeat dedup (every header-less
// request would count as a brand-new visitor/view).
.derive(({ request }) => ({
visitorId: readVisitorId(request.headers.get("x-visitor-id")),
}))
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
.get("/health", () => ({ status: "ok" as const }))
// Newest-first page of assets. `page`/`per_page` are coerced and
// range-checked here; the service clamps defensively as well.
Expand Down Expand Up @@ -306,6 +323,30 @@ export function createApp({ core, maxUploadBytes }: AppDependencies) {
// NOT exposed yet — it's an admin operation, so it lands with the auth /
// superadmin milestone rather than as an open, unauthenticated write.
// `tagService.setCategory` is ready for that route.
// --- Traffic counters ----------------------------------------------
// Record a view of a post (throttled to at most once per window per
// visitor, so refreshes don't inflate it). The web fires this once per
// detail view.
.post(
"/assets/:id/view",
async ({ params, visitorId }) => {
if (visitorId === null) throw new HttpError(400, "Missing or invalid x-visitor-id");
const asset = await core.assetService.getById(params.id);
if (!asset) throw new HttpError(404, "Asset not found");
const counted = await core.statsService.recordView(visitorId, params.id);
return { counted };
},
{ params: idParam },
)
// Record that this visitor was here today (idempotent per day). The web
// fires it once on app load.
.post("/stats/visit", async ({ visitorId }) => {
if (visitorId === null) throw new HttpError(400, "Missing or invalid x-visitor-id");
await core.statsService.recordVisit(visitorId);
return { ok: true as const };
})
// Site-wide counters for the UI (total posts + today's unique visitors).
.get("/stats", () => core.statsService.getStats())
// --- Resumable chunked uploads -------------------------------------
// Open a session for a file; the client PATCHes chunks until complete.
// The one-shot POST /assets above remains for small/non-browser uploads.
Expand Down
72 changes: 72 additions & 0 deletions apps/api/test/server.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import type {
AssetUpdate,
Core,
ListAssetsOptions,
StatsService,
Tag,
TagService,
UploadService,
Expand All @@ -27,6 +28,7 @@ const sampleAsset: Asset = {
md5: "a1b2c3d4".repeat(4), // 32-char lowercase hex
rating: "safe",
source: null,
viewCount: 0,
uploaderId: null,
createdAt: new Date("2026-01-01T00:00:00.000Z"),
updatedAt: new Date("2026-01-02T00:00:00.000Z"),
Expand All @@ -51,6 +53,7 @@ function stubCore(
overrides: Partial<AssetService> = {},
uploadOverrides: Partial<UploadService> = {},
tagOverrides: Partial<TagService> = {},
statsOverrides: Partial<StatsService> = {},
): Core {
return {
assetService: {
Expand Down Expand Up @@ -78,6 +81,12 @@ function stubCore(
setCategory: async () => sampleTag,
...tagOverrides,
},
statsService: {
recordView: async () => true,
recordVisit: async () => undefined,
getStats: async () => ({ posts: 0, visitorsToday: 0 }),
...statsOverrides,
},
events: createCoreEvents(),
};
}
Expand Down Expand Up @@ -595,3 +604,66 @@ describe("tags", () => {
expect(await res.json()).toEqual([tagJson]);
});
});

describe("traffic counters", () => {
it("POST /assets/:id/view records a view (404 absent asset, 400 absent visitor id)", async () => {
const headers = { "x-visitor-id": "abcdef12-3456-7890-abcd-ef1234567890" };

const ok = await buildApp(stubCore({ getById: async () => sampleAsset })).handle(
new Request("http://localhost/api/v1/assets/1/view", { method: "POST", headers }),
);
expect(ok.status).toBe(200);
expect(await ok.json()).toEqual({ counted: true });

const missing = await buildApp(stubCore({ getById: async () => null })).handle(
new Request("http://localhost/api/v1/assets/999/view", { method: "POST", headers }),
);
expect(missing.status).toBe(404);

// No visitor id → 400 (before any asset lookup).
const noVisitor = await buildApp(stubCore({ getById: async () => sampleAsset })).handle(
new Request("http://localhost/api/v1/assets/1/view", { method: "POST" }),
);
expect(noVisitor.status).toBe(400);
});

it("GET /stats returns site counters", async () => {
const res = await buildApp(
stubCore({}, {}, {}, { getStats: async () => ({ posts: 12, visitorsToday: 3 }) }),
).handle(new Request("http://localhost/api/v1/stats"));
expect(res.status).toBe(200);
expect(await res.json()).toEqual({ posts: 12, visitorsToday: 3 });
});

it("attributes a visit to a valid x-visitor-id header and 400s when it's absent", async () => {
const seen: string[] = [];
const core = stubCore(
{},
{},
{},
{
recordVisit: async (visitorId) => {
seen.push(visitorId);
},
},
);

// A valid header is used as the visitor id, as-is.
const withHeader = await buildApp(core).handle(
new Request("http://localhost/api/v1/stats/visit", {
method: "POST",
headers: { "x-visitor-id": "abcdef12-3456-7890-abcd-ef1234567890" },
}),
);
expect(await withHeader.json()).toEqual({ ok: true });
expect(seen).toEqual(["abcdef12-3456-7890-abcd-ef1234567890"]);

// No header → 400 and nothing recorded (we never synthesize a throwaway id,
// which would count every header-less request as a fresh visitor).
const noHeader = await buildApp(core).handle(
new Request("http://localhost/api/v1/stats/visit", { method: "POST" }),
);
expect(noHeader.status).toBe(400);
expect(seen).toEqual(["abcdef12-3456-7890-abcd-ef1234567890"]);
});
});
40 changes: 9 additions & 31 deletions apps/web/src/components/visitor-counter.tsx
Original file line number Diff line number Diff line change
@@ -1,45 +1,23 @@
import { useEffect, useState } from "react";
import { useSiteStats } from "../lib/stats";

const STORAGE_KEY = "bunbooru:visits";

/** Once-per-app-boot guard so StrictMode's double-invoked effect counts once. */
let counted = false;
/** Demo starting point so the odometer looks established. */
const SEED = 13370;
/** Zero-pad width for the classic odometer look. */
const WIDTH = 7;

/**
* Retro visitor counter. Increments once per app load (per browser, via
* localStorage) and renders the total as a zero-padded text odometer.
* Purely client-side until a real analytics endpoint exists.
* Retro visitor counter — renders today's unique-visitor total (from `GET
* /stats`) as a zero-padded text odometer. Visits are recorded server-side once
* per app load (see `useRecordVisit` in the root layout) and deduped per day, so
* this just reflects the real count.
*/
export function VisitorCounter() {
const [count, setCount] = useState<number | null>(null);

useEffect(() => {
const stored = Number(localStorage.getItem(STORAGE_KEY));
const valid = Number.isFinite(stored) && stored > 0;

// Already counted this boot (e.g. StrictMode's second effect run): just show.
if (counted) {
setCount(valid ? stored : SEED + 1);
return;
}
counted = true;

const next = (valid ? stored : SEED) + 1;
localStorage.setItem(STORAGE_KEY, String(next));
setCount(next);
}, []);

if (count === null) return null;
const { data } = useSiteStats();
if (!data) return null;

return (
<span className="inline-flex items-center gap-1.5">
<span>Visitors:</span>
<span>Visitors today:</span>
<span className="font-mono font-semibold tracking-wider tabular-nums text-ink">
{String(count).padStart(WIDTH, "0")}
{String(data.visitorsToday).padStart(WIDTH, "0")}
</span>
</span>
);
Expand Down
30 changes: 30 additions & 0 deletions apps/web/src/lib/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,38 @@ import type { App } from "@bunbooru/api";
* on one origin; in dev the web server proxies `/api/*` to the API. Either way
* there's no CORS. The SSR fallback origin is never actually used in this SPA.
*/
/** localStorage key for the client-owned anonymous visitor id. */
const VISITOR_KEY = "bunbooru:visitor";

/**
* A stable, client-owned anonymous visitor id (a random uuid in localStorage).
* Sent on every request as `x-visitor-id` so the server attributes views/visits
* to one browser without minting a cookie per request — which would race across
* a first-load request burst and count one human several times. Opaque, not an
* IP; clearing site data resets it, exactly like a cookie.
*/
let volatileVisitorId: string | null = null;

function visitorId(): string {
// localStorage can throw (private mode, disabled, quota). A header callback
// that rejects would fail EVERY request, so fall back to an in-memory id —
// the server treats a missing/changed id as a new visitor, no worse than that.
try {
let id = localStorage.getItem(VISITOR_KEY);
if (id === null || !/^[0-9a-f-]{8,64}$/i.test(id)) {
id = crypto.randomUUID();
localStorage.setItem(VISITOR_KEY, id);
}
return id;
} catch {
volatileVisitorId ??= crypto.randomUUID();
return volatileVisitorId;
}
}

export const api = treaty<App>(
typeof window !== "undefined" ? window.location.origin : "http://localhost:3000",
typeof window !== "undefined" ? { headers: () => ({ "x-visitor-id": visitorId() }) } : undefined,
);

/** Public URL for an asset's stored bytes (used as an `<img src>`, not a data call). */
Expand Down
73 changes: 73 additions & 0 deletions apps/web/src/lib/stats.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import { useEffect, useRef } from "react";

import { useQuery, useQueryClient } from "@tanstack/react-query";

import { api, unwrap } from "./api";

/** Site-wide traffic counters returned by `GET /stats`. */
export interface SiteStats {
posts: number;
visitorsToday: number;
}

/** Total posts + today's unique visitors. Polled lazily; safe to call anywhere. */
export function useSiteStats() {
return useQuery({
queryKey: ["site-stats"],
queryFn: async (): Promise<SiteStats> => unwrap(await api.api.v1.stats.get()),
staleTime: 60_000,
});
}

/**
* Record a daily visit once per app load. The server dedupes per (day, visitor),
* so a StrictMode double-invoke or a re-render is harmless; the ref just avoids
* the redundant request.
*/
export function useRecordVisit(): void {
const queryClient = useQueryClient();
const fired = useRef(false);
useEffect(() => {
if (fired.current) return;
fired.current = true;
api.api.v1.stats.visit
.post()
.then(() => {
// Refresh the footer/home counters so they include this visit.
void queryClient.invalidateQueries({ queryKey: ["site-stats"] });
})
.catch(() => {
// A transient failure shouldn't permanently drop the visit — allow a
// retry on the next mount (the endpoint is deduped per day).
fired.current = false;
});
}, [queryClient]);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}

/**
* Record a view of `assetId` once it's known. The server debounces per
* visitor-session, so refreshes don't inflate the count; the ref avoids a
* duplicate request when the same asset id re-renders.
*/
export function useRecordView(assetId: number | undefined): void {
const queryClient = useQueryClient();
const fired = useRef<number | null>(null);
useEffect(() => {
if (assetId === undefined || fired.current === assetId) return;
fired.current = assetId;
api.api.v1
.assets({ id: String(assetId) })
.view.post()
.then((res) => {
// Only refetch the asset when the view actually counted (not a throttled
// repeat), so the detail page shows the incremented viewCount.
if (res.data && "counted" in res.data && res.data.counted) {
void queryClient.invalidateQueries({ queryKey: ["asset", assetId] });
}
})
.catch(() => {
// Allow a retry on a later mount rather than dropping the view.
fired.current = null;
});
}, [assetId, queryClient]);
}
2 changes: 2 additions & 0 deletions apps/web/src/routes/__root.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { Link, Outlet, useRouterState } from "@tanstack/react-router";
import pkg from "../../package.json";
import { ThemeSwitcher } from "../components/theme-switcher";
import { VisitorCounter } from "../components/visitor-counter";
import { useRecordVisit } from "../lib/stats";
import { useApplyTheme } from "../stores/theme";

const VERSION = pkg.version;
Expand Down Expand Up @@ -40,6 +41,7 @@ function AccountLinks({ className }: { className?: string }) {
*/
export function RootLayout() {
useApplyTheme();
useRecordVisit(); // count this visitor once per app load (server dedupes per day)
const isHome = useRouterState({ select: (s) => s.location.pathname === "/" });

return (
Expand Down
11 changes: 6 additions & 5 deletions apps/web/src/routes/home.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,7 @@ import { Link, useNavigate } from "@tanstack/react-router";

import { Counter } from "../components/counter";
import { ThemeSwitcher } from "../components/theme-switcher";

/** Dummy site stats — wired to the API once endpoints exist. */
const POST_COUNT = "1234567890";
import { useSiteStats } from "../lib/stats";

/** Centered landing menu (safebooru-style front page). */
const HOME_MENU = [
Expand All @@ -22,6 +20,9 @@ const HOME_MENU = [
export function HomePage() {
const navigate = useNavigate();
const [query, setQuery] = useState("");
const { data: stats } = useSiteStats();
// Render the live post total once loaded; the odometer needs a numeric string.
const postCount = stats ? String(stats.posts) : null;

return (
<div className="flex min-h-[82vh] flex-col justify-center space-y-8">
Expand All @@ -36,9 +37,9 @@ export function HomePage() {
Bun<span className="text-link">booru</span>
</h1>
<p className="text-lg text-muted">
Serving <strong>{POST_COUNT}</strong> posts and counting.
Serving <strong>{postCount ?? "…"}</strong> posts and counting.
</p>
<Counter value={POST_COUNT} digitClass="h-16 sm:h-20" />
{postCount !== null && <Counter value={postCount} digitClass="h-16 sm:h-20" />}

<form
onSubmit={(e) => {
Expand Down
Loading
Loading