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
6 changes: 6 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -41,3 +41,9 @@ TODOS.md

# CodeRabbit CLI review output (bin/cr.ts)
.cr/

# Local asset storage (filesystem provider). STORAGE_ROOT resolves from the cwd,
# so cover both repo-root runs and starting the API from apps/api/. Anchored on
# purpose — a bare `storage/` would also ignore the `packages/storage` source.
/storage/
/apps/api/storage/
4 changes: 4 additions & 0 deletions apps/api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@
"private": true,
"type": "module",
"module": "src/index.ts",
"exports": {
".": "./src/index.ts"
},
"types": "./src/index.ts",
"scripts": {
"dev": "bun run --watch src/index.ts",
"start": "bun run src/index.ts"
Expand Down
7 changes: 4 additions & 3 deletions apps/api/src/env-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,16 +56,17 @@ class EnvConfig {

/**
* Filesystem root for stored asset binaries. Required in production; in dev it
* defaults to an **absolute** `<cwd>/data/storage` so the location is
* deterministic and doesn't silently move with the process working directory.
* defaults to an **absolute** `<cwd>/storage` — deterministic, and kept out of
* `data/` (which holds the root-owned Docker bind mounts the app-user can't
* write into).
*/
get STORAGE_ROOT(): string {
const raw = Bun.env.STORAGE_ROOT?.trim();
if (raw) return raw;
if (this.NODE_ENV === "production") {
throw new Error("STORAGE_ROOT is required outside development");
}
return resolve(process.cwd(), "data/storage");
return resolve(process.cwd(), "storage");
}

/**
Expand Down
2 changes: 1 addition & 1 deletion apps/api/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,4 +44,4 @@ const shutdown = async (): Promise<void> => {
process.once("SIGTERM", () => void shutdown());
process.once("SIGINT", () => void shutdown());

export type { App } from "./server";
export type { App, AssetDto } from "./server";
21 changes: 20 additions & 1 deletion apps/api/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,21 @@ export function createApp({ core, maxUploadBytes }: AppDependencies) {
}),
},
)
// Single asset's metadata (JSON). The detail page fetches this directly
// so deep links work without a prior list query.
.get(
"/assets/:id",
async ({ params }) => {
const asset = await core.assetService.getById(params.id);
if (!asset) throw new HttpError(404, "Asset not found");
return serializeAsset(asset);
},
{
params: t.Object({
id: t.Numeric({ minimum: 1, maximum: Number.MAX_SAFE_INTEGER, multipleOf: 1 }),
}),
},
)
// Stream an asset's stored bytes. Kept separate from the JSON metadata so
// the binary never has to be base64'd into a JSON payload.
.get(
Expand All @@ -185,7 +200,11 @@ export function createApp({ core, maxUploadBytes }: AppDependencies) {
if (!file) throw new HttpError(404, "Asset not found");
return new Response(file.stream, { headers: { "content-type": file.mimeType } });
},
{ params: t.Object({ id: t.Numeric({ minimum: 1, multipleOf: 1 }) }) },
{
params: t.Object({
id: t.Numeric({ minimum: 1, maximum: Number.MAX_SAFE_INTEGER, multipleOf: 1 }),
}),
},
),
);
}
Expand Down
2 changes: 1 addition & 1 deletion apps/api/test/env-config.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ describe("STORAGE_ROOT", () => {
Bun.env.NODE_ENV = "development";
const root = envConfig.STORAGE_ROOT;
expect(root.startsWith("/")).toBe(true);
expect(root.endsWith("/data/storage")).toBe(true);
expect(root.endsWith("/storage")).toBe(true);
});

it("is required in production", () => {
Expand Down
24 changes: 24 additions & 0 deletions apps/api/test/server.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,30 @@ describe("POST /api/v1/assets", () => {
});
});

describe("GET /api/v1/assets/:id", () => {
it("returns the asset metadata (ISO timestamps)", async () => {
const res = await buildApp(stubCore({ getById: async () => sampleAsset })).handle(
new Request("http://localhost/api/v1/assets/1"),
);
expect(res.status).toBe(200);
const body = (await res.json()) as { id: number; createdAt: unknown };
expect(body.id).toBe(1);
expect(body.createdAt).toBe("2026-01-01T00:00:00.000Z");
});

it("returns 404 when absent", async () => {
const res = await buildApp(stubCore({ getById: async () => null })).handle(
new Request("http://localhost/api/v1/assets/999"),
);
expect(res.status).toBe(404);
});

it("rejects a non-numeric id with 422", async () => {
const res = await request("/api/v1/assets/abc");
expect(res.status).toBe(422);
});
});

describe("GET /api/v1/assets/:id/file", () => {
it("streams the stored bytes with the asset's content type", async () => {
const body = new Response("IMGBYTES").body;
Expand Down
3 changes: 3 additions & 0 deletions apps/web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,10 @@
"start": "bun run src/index.ts"
},
"dependencies": {
"@bunbooru/api": "workspace:*",
"@elysiajs/eden": "^1.4.9",
"@floating-ui/react": "^0.27.19",
"@tanstack/react-query": "^5.101.2",
"@tanstack/react-router": "^1.170.16",
"lucide-react": "^1.21.0",
"react": "^19.2.7",
Expand Down
51 changes: 51 additions & 0 deletions apps/web/src/components/asset-image.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { useEffect, useState, type CSSProperties } from "react";

/**
* An asset image that degrades gracefully. A metadata row can outlive its stored
* bytes (the API answers `404` from `/assets/:id/file`), so on a load error we
* render an "unavailable" placeholder in the same box instead of the browser's
* broken-image glyph. Shared by the gallery grid and the detail view so both
* gate on actual file availability, not just the presence of a metadata row.
*/
export function AssetImage({
src,
alt,
className,
style,
loading,
}: {
src: string;
alt: string;
className?: string;
style?: CSSProperties;
loading?: "lazy" | "eager";
}) {
const [failed, setFailed] = useState(false);

// Reset on src change so a reused instance retries the new asset instead of
// staying stuck on the placeholder from a previous failure.
useEffect(() => {
setFailed(false);
}, [src]);

if (failed) {
return (
<div className={className} style={style} role="img" aria-label={`${alt} (image unavailable)`}>
<span className="flex h-full w-full items-center justify-center text-[11px] text-muted">
Image unavailable
</span>
</div>
);
}

return (
<img
src={src}
alt={alt}
loading={loading}
className={className}
style={style}
onError={() => setFailed(true)}
/>
);
}
54 changes: 50 additions & 4 deletions apps/web/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,19 +8,65 @@ const port = Number(Bun.env.WEB_PORT ?? "3001") || 3001;
const hostname = Bun.env.WEB_HOST ?? "0.0.0.0";
/** Enable Bun's dev bundling/HMR unless explicitly in production. */
const development = Bun.env.NODE_ENV !== "production";
/**
* Where to proxy `/api/*` in dev (the API listens on 3000 by default). Strip any
* trailing slash so concatenating the request path can't yield `//api/...`,
* which some upstreams route differently.
*/
const apiTarget = (Bun.env.API_TARGET ?? "http://localhost:3000").replace(/\/+$/, "");
/**
* Per-proxied-request timeout. Bun's default fetch timeout is ~5 min, long
* enough that a stalled/silent upstream would hold a dev request open for ages.
* Cap it so `/api/*` fails fast with a 504 instead — generous enough not to
* abort legitimate dev uploads (this dev-only proxy isn't on the prod path,
* where the API serves the SPA directly).
*/
const PROXY_TIMEOUT_MS = 120_000;

/**
* Serve the single-page app. Every route returns `index.html`; the client
* router takes over, and Bun bundles `index.tsx` + assets (Tailwind via
* bun-plugin-tailwind from bunfig.toml).
* Serve the single-page app. `/api/*` is reverse-proxied to the API so the
* browser talks to a single origin (Model A topology) — the Eden client uses
* `window.location.origin`, so there's no CORS in dev or prod. Every other route
* returns `index.html`; the client router takes over, and Bun bundles
* `index.tsx` + assets (Tailwind via bun-plugin-tailwind from bunfig.toml).
*/
const server = serve({
port,
hostname,
development,
routes: {
// Re-target at the API, preserving method/headers/body (streams multipart
// uploads through unchanged). A failed upstream becomes a deterministic 502
// rather than an opaque server error.
"/api/*": async (req) => {
const { pathname, search } = new URL(req.url);
try {
return await fetch(new Request(`${apiTarget}${pathname}${search}`, req), {
signal: AbortSignal.timeout(PROXY_TIMEOUT_MS),
});
} catch (error) {
// A timeout means the upstream stalled (504); anything else is a
// connect/transport failure (502). Both are deterministic, not opaque.
const timedOut = error instanceof DOMException && error.name === "TimeoutError";
return new Response(timedOut ? "Upstream API timed out" : "Upstream API unavailable", {
status: timedOut ? 504 : 502,
});
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
},
"/*": index,
},
});

console.log(`🐇 Bunbooru web on ${server.url}`);
/** Log the target without any basic-auth credentials it might carry. */
const apiTargetForLog = (() => {
try {
const url = new URL(apiTarget);
url.username = "";
url.password = "";
return url.toString();
} catch {
return "<invalid API_TARGET>";
}
})();

console.log(`🐇 Bunbooru web on ${server.url} (api → ${apiTargetForLog})`);
6 changes: 5 additions & 1 deletion apps/web/src/index.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { QueryClientProvider } from "@tanstack/react-query";
import { RouterProvider } from "@tanstack/react-router";

import { queryClient } from "./lib/query";
import { router } from "./router";

const rootEl = document.getElementById("root");
if (!rootEl) throw new Error("#root element not found");

createRoot(rootEl).render(
<StrictMode>
<RouterProvider router={router} />
<QueryClientProvider client={queryClient}>
<RouterProvider router={router} />
</QueryClientProvider>
</StrictMode>,
);
37 changes: 37 additions & 0 deletions apps/web/src/lib/api.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { treaty } from "@elysiajs/eden";

import type { App } from "@bunbooru/api";

/**
* Type-safe API client (Eden Treaty) — the ONLY way the frontend talks to the
* API. Never call `fetch` directly: Eden derives request/response types from the
* server's {@link App} type, so a route rename or payload change is a compile
* error here, not a runtime 404.
*
* Base = `window.location.origin` (same-origin): in prod the API serves this SPA
* 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.
*/
export const api = treaty<App>(
typeof window !== "undefined" ? window.location.origin : "http://localhost:3000",
);

/** Public URL for an asset's stored bytes (used as an `<img src>`, not a data call). */
export function assetFileUrl(id: number): string {
return `/api/v1/assets/${id}/file`;
}

/**
* Unwrap an Eden Treaty response: throw on transport/HTTP error, then narrow out
* the API's `{ error }` envelope. The global `onError` handler's return type is
* merged by Elysia into every route's response type, so `data` is typed as
* `Success | envelope` even though non-2xx bodies actually arrive on `error`.
*/
export function unwrap<T>(res: { data: T | null; error: unknown }): Exclude<T, { error: unknown }> {
if (res.error) throw res.error;
if (res.data == null) throw new Error("Unexpected API response");
// Eden routes non-2xx bodies to `res.error`, so a non-null `data` is a success
// payload; the envelope is removed at the type level only (never at runtime, so
// a payload that legitimately carries an `error` field isn't misread as failed).
return res.data as Exclude<T, { error: unknown }>;
}
40 changes: 40 additions & 0 deletions apps/web/src/lib/assets.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { useQuery } from "@tanstack/react-query";

import type { AssetDto } from "@bunbooru/api";

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

/** Grid page size. */
export const ASSETS_PER_PAGE = 42;

export type { AssetDto };

/**
* Newest-first page of assets. Eden Treaty is the transport; TanStack Query owns
* caching + loading/error state. The `error` discriminant narrows `data` to
* non-null, so the hook resolves a fully-typed page.
*/
export function useAssetsPage(page: number) {
return useQuery({
queryKey: ["assets", page],
enabled: Number.isInteger(page) && page > 0,
queryFn: async () =>
unwrap(await api.api.v1.assets.get({ query: { page, per_page: ASSETS_PER_PAGE } })),
});
}

/** A single asset's metadata (for the detail page / deep links). */
export function useAsset(id: number) {
return useQuery({
queryKey: ["asset", id],
enabled: Number.isInteger(id) && id > 0,
queryFn: async () => {
const res = await api.api.v1.assets({ id: String(id) }).get();
// A 404 is "this asset doesn't exist" — a normal not-found state, not a
// query failure. Return null so the detail page renders NotFound instead
// of the generic error/retry UI; other errors still throw via unwrap.
if (res.status === 404) return null;
return unwrap(res);
},
});
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
Loading
Loading