feat: initial scaffold for ClickTrack monorepo

Full self-hosted click track generator for cover bands.

Core technical pieces implemented:
- CTP (Click Track Protocol) TypeScript schema, Zod validator, and WAV
  renderer (44.1 kHz, 16-bit PCM, accented downbeats, ramp sections)
- MusicBrainz API client with 1 req/s rate limiting
- PostgreSQL schema (songs, tempo_maps, registry_sync_log) with triggers
- Git registry sync logic (clone/pull → validate CTP → upsert DB)
- Next.js 14 App Router: search page, track page, API routes
  (/api/songs, /api/tracks, /api/generate)
- UI components: SearchBar, SongResult, TempoMapEditor, ClickTrackPlayer
  (Web Audio API in-browser playback + WAV download)
- Docker Compose stack: app + postgres + redis + nginx + registry-sync
- Multi-stage Dockerfile with standalone Next.js output
- .env.example documenting all configuration variables
- README with setup instructions, CTP format spec, and API reference

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
AJ Avezzano
2026-04-01 11:14:46 -04:00
commit 5b772655c6
31 changed files with 2762 additions and 0 deletions

101
app/(web)/page.tsx Normal file
View File

@@ -0,0 +1,101 @@
import { Suspense } from "react";
import SearchBar from "@/components/SearchBar";
import SongResult from "@/components/SongResult";
import { searchSongs as searchSongsDB } from "@/lib/db/client";
import { searchSongs as searchMB } from "@/lib/musicbrainz/client";
import { upsertSong } from "@/lib/db/client";
interface PageProps {
searchParams: { q?: string };
}
async function SearchResults({ q }: { q: string }) {
// Try local DB first
let songs = await searchSongsDB(q, 20);
// If sparse results, hit MusicBrainz and cache locally
if (songs.length < 3) {
try {
const mbResults = await searchMB(q, 20);
for (const s of mbResults) {
await upsertSong({
mbid: s.mbid,
title: s.title,
artist: s.artist,
duration_seconds: s.duration_seconds,
acousticbrainz_bpm: null,
acousticbrainz_time_sig_num: null,
source: "musicbrainz",
});
}
songs = await searchSongsDB(q, 20);
} catch {
// MusicBrainz unavailable — fall through with local results
}
}
if (songs.length === 0) {
return (
<p className="mt-8 text-center text-zinc-500">
No results for <span className="text-zinc-300">&ldquo;{q}&rdquo;</span>.
Try a different search.
</p>
);
}
return (
<ul className="mt-6 space-y-3">
{songs.map((song) => (
<SongResult key={song.mbid} song={song} />
))}
</ul>
);
}
export default function HomePage({ searchParams }: PageProps) {
const q = searchParams.q?.trim() ?? "";
return (
<div>
<div className="mb-10 text-center">
<h1 className="text-4xl font-bold tracking-tight text-green-400">ClickTrack</h1>
<p className="mt-3 text-zinc-400">
Find a song, download a click track. Built for cover bands.
</p>
</div>
<SearchBar initialValue={q} />
{q && (
<Suspense
fallback={
<p className="mt-8 text-center text-zinc-500 animate-pulse">Searching</p>
}
>
{/* @ts-expect-error async server component */}
<SearchResults q={q} />
</Suspense>
)}
{!q && (
<div className="mt-12 grid gap-6 text-sm text-zinc-500 sm:grid-cols-3">
<div className="rounded-lg border border-zinc-800 p-5">
<div className="mb-2 text-lg font-semibold text-zinc-200">Search</div>
Search any song by title or artist. We pull metadata from MusicBrainz
and cache it locally.
</div>
<div className="rounded-lg border border-zinc-800 p-5">
<div className="mb-2 text-lg font-semibold text-zinc-200">Tempo Map</div>
Community-contributed CTP tempo maps define every section, time
signature change, and tempo ramp in a song.
</div>
<div className="rounded-lg border border-zinc-800 p-5">
<div className="mb-2 text-lg font-semibold text-zinc-200">Download</div>
Generate a 44.1 kHz WAV click track with accented downbeats ready
for your in-ear monitor mix.
</div>
</div>
)}
</div>
);
}

View File

@@ -0,0 +1,108 @@
import { notFound } from "next/navigation";
import type { Metadata } from "next";
import { query, getTempoMapsForSong } from "@/lib/db/client";
import type { SongRow } from "@/lib/db/client";
import TempoMapEditor from "@/components/TempoMapEditor";
import ClickTrackPlayer from "@/components/ClickTrackPlayer";
import type { CTPDocument } from "@/lib/ctp/schema";
interface PageProps {
params: { id: string };
}
async function getSong(mbid: string): Promise<SongRow | null> {
const { rows } = await query<SongRow>(
"SELECT * FROM songs WHERE mbid = $1",
[mbid]
);
return rows[0] ?? null;
}
export async function generateMetadata({ params }: PageProps): Promise<Metadata> {
const song = await getSong(params.id);
if (!song) return { title: "Track not found" };
return { title: `${song.title}${song.artist}` };
}
export default async function TrackPage({ params }: PageProps) {
const song = await getSong(params.id);
if (!song) notFound();
const tempoMaps = await getTempoMapsForSong(params.id);
const bestMap = tempoMaps.find((m) => m.verified) ?? tempoMaps[0] ?? null;
return (
<div className="space-y-8">
{/* Song header */}
<div>
<p className="text-sm text-zinc-500 uppercase tracking-widest mb-1">Click Track</p>
<h1 className="text-3xl font-bold">{song.title}</h1>
<p className="mt-1 text-lg text-zinc-400">{song.artist}</p>
{song.duration_seconds && (
<p className="mt-1 text-sm text-zinc-600">
{Math.floor(song.duration_seconds / 60)}m{" "}
{Math.round(song.duration_seconds % 60)}s
</p>
)}
</div>
{/* Player / Download */}
{bestMap ? (
<ClickTrackPlayer
tempoMapId={bestMap.id}
ctpDoc={bestMap.ctp_data as unknown as CTPDocument}
verified={bestMap.verified}
upvotes={bestMap.upvotes}
/>
) : (
<div className="rounded-lg border border-dashed border-zinc-700 p-10 text-center text-zinc-500">
<p className="text-lg font-medium text-zinc-300 mb-2">No tempo map yet</p>
<p className="text-sm">
Be the first to contribute a tempo map for this song via the community
registry.
</p>
</div>
)}
{/* Tempo map editor / viewer */}
{bestMap && (
<div>
<h2 className="text-lg font-semibold mb-4">Tempo Map</h2>
<TempoMapEditor ctpDoc={bestMap.ctp_data as unknown as CTPDocument} readOnly />
</div>
)}
{/* All maps */}
{tempoMaps.length > 1 && (
<div>
<h2 className="text-lg font-semibold mb-3">
All community maps ({tempoMaps.length})
</h2>
<ul className="space-y-2">
{tempoMaps.map((m) => (
<li
key={m.id}
className="flex items-center justify-between rounded-lg border border-zinc-800 px-4 py-3 text-sm"
>
<span className="text-zinc-300">
By{" "}
<span className="font-medium">
{(m.ctp_data as { metadata?: { contributed_by?: string } }).metadata?.contributed_by ?? "unknown"}
</span>
</span>
<div className="flex items-center gap-3 text-zinc-500">
{m.verified && (
<span className="rounded-full bg-green-900/40 px-2 py-0.5 text-xs text-green-400">
verified
</span>
)}
<span>{m.upvotes} upvotes</span>
</div>
</li>
))}
</ul>
</div>
)}
</div>
);
}

86
app/api/generate/route.ts Normal file
View File

@@ -0,0 +1,86 @@
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { query } from "@/lib/db/client";
import { validateCTP } from "@/lib/ctp/validate";
import { renderCTP } from "@/lib/ctp/render";
import type { TempoMapRow } from "@/lib/db/client";
const ParamsSchema = z.object({
id: z.string().uuid("tempo map id must be a UUID"),
count_in: z
.enum(["true", "false"])
.transform((v) => v === "true")
.optional(),
});
/**
* GET /api/generate?id=<tempo-map-uuid>[&count_in=true]
*
* Renders the requested tempo map to a WAV file and streams it back.
* The response is cached for 1 hour since tempo maps are immutable once created.
*/
export async function GET(req: NextRequest) {
const raw = Object.fromEntries(req.nextUrl.searchParams);
const parsed = ParamsSchema.safeParse(raw);
if (!parsed.success) {
return NextResponse.json(
{ error: "Invalid parameters", details: parsed.error.flatten() },
{ status: 400 }
);
}
const { id, count_in } = parsed.data;
// Load tempo map from DB
const { rows } = await query<TempoMapRow>(
"SELECT * FROM tempo_maps WHERE id = $1",
[id]
);
if (rows.length === 0) {
return NextResponse.json({ error: "Tempo map not found" }, { status: 404 });
}
const map = rows[0];
const validation = validateCTP(map.ctp_data);
if (!validation.success) {
return NextResponse.json(
{ error: "Stored CTP document is invalid", details: validation.errors.flatten() },
{ status: 500 }
);
}
const doc = validation.data;
// Render WAV
let wav: Buffer;
try {
wav = renderCTP(doc, { countIn: count_in });
} catch (err) {
console.error("[generate] Render error:", err);
return NextResponse.json(
{ error: "Failed to render click track", detail: String(err) },
{ status: 500 }
);
}
// Build a clean filename
const safeName = `${doc.metadata.artist} - ${doc.metadata.title}`
.replace(/[^\w\s\-]/g, "")
.replace(/\s+/g, "_")
.slice(0, 80);
const filename = `${safeName}_click.wav`;
return new NextResponse(wav, {
status: 200,
headers: {
"Content-Type": "audio/wav",
"Content-Disposition": `attachment; filename="${filename}"`,
"Content-Length": String(wav.byteLength),
"Cache-Control": "public, max-age=3600, immutable",
},
});
}

49
app/api/songs/route.ts Normal file
View File

@@ -0,0 +1,49 @@
import { NextRequest, NextResponse } from "next/server";
import { searchSongs as searchSongsDB, upsertSong } from "@/lib/db/client";
import { searchSongs as searchMB } from "@/lib/musicbrainz/client";
import { z } from "zod";
const QuerySchema = z.object({
q: z.string().min(1).max(200),
limit: z.coerce.number().int().min(1).max(50).default(20),
});
export async function GET(req: NextRequest) {
const params = Object.fromEntries(req.nextUrl.searchParams);
const parsed = QuerySchema.safeParse(params);
if (!parsed.success) {
return NextResponse.json(
{ error: "Invalid query parameters", details: parsed.error.flatten() },
{ status: 400 }
);
}
const { q, limit } = parsed.data;
// Try local DB first
let songs = await searchSongsDB(q, limit);
// Augment from MusicBrainz when local results are thin
if (songs.length < 3) {
try {
const mbResults = await searchMB(q, limit);
for (const s of mbResults) {
await upsertSong({
mbid: s.mbid,
title: s.title,
artist: s.artist,
duration_seconds: s.duration_seconds,
acousticbrainz_bpm: null,
acousticbrainz_time_sig_num: null,
source: "musicbrainz",
});
}
songs = await searchSongsDB(q, limit);
} catch (err) {
console.error("[songs] MusicBrainz search failed:", err);
}
}
return NextResponse.json({ songs, total: songs.length });
}

80
app/api/tracks/route.ts Normal file
View File

@@ -0,0 +1,80 @@
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { getTempoMapsForSong, insertTempoMap, query } from "@/lib/db/client";
import { validateCTP } from "@/lib/ctp/validate";
// ─── GET /api/tracks?mbid=<uuid> ─────────────────────────────────────────────
const GetSchema = z.object({
mbid: z.string().uuid(),
});
export async function GET(req: NextRequest) {
const params = Object.fromEntries(req.nextUrl.searchParams);
const parsed = GetSchema.safeParse(params);
if (!parsed.success) {
return NextResponse.json(
{ error: "mbid (UUID) is required" },
{ status: 400 }
);
}
const maps = await getTempoMapsForSong(parsed.data.mbid);
return NextResponse.json({ maps });
}
// ─── POST /api/tracks ─────────────────────────────────────────────────────────
// Body: a raw CTP document JSON
export async function POST(req: NextRequest) {
let body: unknown;
try {
body = await req.json();
} catch {
return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 });
}
const validation = validateCTP(body);
if (!validation.success) {
return NextResponse.json(
{
error: "CTP document validation failed",
details: validation.errors.flatten(),
},
{ status: 422 }
);
}
const doc = validation.data;
if (!doc.metadata.mbid) {
return NextResponse.json(
{ error: "CTP document must include a metadata.mbid to be stored" },
{ status: 422 }
);
}
// Ensure the song exists
const { rowCount } = await query("SELECT 1 FROM songs WHERE mbid = $1", [
doc.metadata.mbid,
]);
if (!rowCount || rowCount === 0) {
return NextResponse.json(
{
error: "Song not found. Search for the song first to register it.",
mbid: doc.metadata.mbid,
},
{ status: 404 }
);
}
const map = await insertTempoMap({
song_mbid: doc.metadata.mbid,
ctp_data: body as Record<string, unknown>,
contributed_by: doc.metadata.contributed_by,
});
return NextResponse.json({ map }, { status: 201 });
}

3
app/globals.css Normal file
View File

@@ -0,0 +1,3 @@
@tailwind base;
@tailwind components;
@tailwind utilities;

48
app/layout.tsx Normal file
View File

@@ -0,0 +1,48 @@
import type { Metadata } from "next";
import "./globals.css";
export const metadata: Metadata = {
title: {
default: process.env.NEXT_PUBLIC_APP_NAME ?? "ClickTrack",
template: `%s | ${process.env.NEXT_PUBLIC_APP_NAME ?? "ClickTrack"}`,
},
description:
"Self-hosted click track generator for cover bands. Search songs, view community tempo maps, and download metronomic WAV files.",
};
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en">
<body className="min-h-screen bg-zinc-950 text-zinc-100 antialiased">
<header className="border-b border-zinc-800 px-6 py-4">
<div className="mx-auto flex max-w-4xl items-center justify-between">
<a href="/" className="text-xl font-bold tracking-tight text-green-400">
{process.env.NEXT_PUBLIC_APP_NAME ?? "ClickTrack"}
</a>
<nav className="flex gap-6 text-sm text-zinc-400">
<a href="/" className="hover:text-zinc-100 transition-colors">
Search
</a>
<a
href="https://github.com/your-org/clicktrack"
target="_blank"
rel="noopener noreferrer"
className="hover:text-zinc-100 transition-colors"
>
GitHub
</a>
</nav>
</div>
</header>
<main className="mx-auto max-w-4xl px-6 py-10">{children}</main>
<footer className="border-t border-zinc-800 px-6 py-6 text-center text-xs text-zinc-600">
ClickTrack open source, self-hosted. Tempo data from the community registry.
</footer>
</body>
</html>
);
}