Architecture
Overview
Sleeve is one Bun process (API, and in production also the static frontend) plus a Vite-built React SPA. SQLite is the local source of truth for the user’s collection and wishlist; remote MusicBrainz data is cached separately.
React SPA
│ JSON over /api
▼
Elysia (Bun)
├── Prisma → SQLite (Release, Track, WishlistItem, MetadataCache)
├── MusicBrainz service → MetadataCache + rate limiter + single-flight
└── Cover proxy → disk cache (data/covers)
├── Uploaded covers → data/uploads/coversRuntime modes
Development
bun run devstarts:- API on
PORT(3001, from.env) - Vite on
5173, proxying/apito3001
- API on
- Vite serves the SPA; the API does not serve
dist/. - Service worker is not registered.
Production
bun run buildwritesdist/.bun run startsetsNODE_ENV=production.server/index.tsstartsBun.serve:/api/*→ Elysia- existing files under
dist/→ static response - everything else →
dist/index.html(SPA fallback)
- Production port is
PORT(3001in the local.env). - Service worker registration happens in
src/main.tsxonly underimport.meta.env.PROD.
Backend modules
server/index.ts
Creates the Elysia app and mounts route plugins. In production it also serves the built SPA and implements a normalized path check to prevent static path traversal.
server/musicbrainz.ts
The only module allowed to call MusicBrainz or Cover Art Archive APIs.
Responsibilities:
- Fixed the MusicBrainz contact header.
- Global serialized request chain with at least 1.2s between requests.
- Retries for transient
503, then a 30s global cooldown. - Persistent cache in SQLite
MetadataCache. - Single-flight for identical in-flight requests.
- AbortSignal propagation so cancelled client requests are dropped before consuming rate-limit slots.
- Mapping raw MusicBrainz payloads to internal
SearchResult,ReleaseDetail, artist and release-group shapes. refreshReleasebypasses the normal cache read and stores fresh detail.
TTLs:
| Tier | TTL |
|---|---|
| Search / artist search / genre release-group search | 30 min |
| Release detail / artist detail / artist group pages | 7 days |
| Empty search result | 10 min |
Search results include score; artist results include score, type, area, country, life span and disambiguation. Artist detail includes genres/tags, selected external links and the first 100 release groups plus a total count.
server/release-metadata.ts
Metadata application and matching:
applyReleaseDetail(releaseId, detail)- Deletes/recreates tracks in one transaction.
- Updates MB-derived fields and
musicbrainzId. - Preserves user fields:
format,condition,rating,notes, purchase fields.
enrichReleaseById(releaseId)- Existing MBID → fetch/apply detail.
- Manual release → barcode search, then
artist + title, then title fallback. - Ranks candidates by title, artist, format, year, barcode, catalog number and MB relevance.
- Requires confidence ≥ 75; rejects duplicate MBIDs.
applyReleaseMatch(releaseId, mbid)- Applies a user-selected edition.
- Rejects MBIDs already used by another release.
server/routes/
| Module | Responsibility |
|---|---|
releases.ts | CRUD, list filters, owned lookup, refresh/enrich/manual match, clear library |
search.ts | Global header search across releases, artists and wishlist, with scopes and operators |
search-query.ts | Converts parsed operators into Prisma filters |
search-index.ts | SQLite FTS5 lookup with contains fallback |
musicbrainz.ts | Release search, barcode search, artist search/detail, group pages, release detail |
wishlist.ts | Wishlist CRUD |
follows.ts | Followed artists list, follow/unfollow |
settings.ts | Library defaults read/update |
discover.ts | Discover picks from library affinity and ListenBrainz |
import.ts | Merge-safe import, JSON or multipart with uploaded covers |
export.ts | Backup: JSON, or zip with library.json and uploaded covers |
stats.ts | Collection stats, spending stats, missing-metadata count |
meta.ts | Format/genre/decade filter options |
maintenance.ts | Metadata cache stats + clear |
covers.ts | Allowlisted Cover Art Archive proxy, disk cache, uploaded cover storage |
Request flows
Add a release
- Add dialog searches releases through
/api/musicbrainz/search. - Artist suggestions are derived from the release search results; no separate artist call by default.
- User can explicitly request an artist search, or click an artist to open the artist page.
- Clicking a result fetches full release detail unless the MBID is already owned.
- On save,
/api/releasesstores release and tracks in SQLite. - After save, the app navigates to
/releases/:id, which reads from SQLite.
Library and release pages
Library list, filters, stats and release details read Prisma/SQLite only. No MusicBrainz call is made to render an owned release.
Refresh and enrichment
- Per-release Refresh (existing MBID): fetch fresh detail and apply.
- Fetch metadata (manual): auto-match and apply.
- Search match (always available): search MusicBrainz, user selects the exact edition,
/apply-matchapplies it. - Library batch Download metadata: client processes missing releases sequentially via
/enrich, showing progress. Running against many records can take time because of MusicBrainz rate limits.
“Missing metadata” means no MBID, no cover URL, or no track count. A cover URL may exist while CAA still returns 404; the release page also detects image failure and offers Search match.
Metadata cache and cancellation
- Every MB endpoint builds a cache key and calls
withCache. - Cache reads/writes are best-effort; a cache failure never breaks the reply.
- Identical requests share a flight.
- Client query functions pass
AbortSignal; routes passrequest.signal; the MB service drops aborted queued tasks. - Expired cache rows are pruned opportunistically.
Cover proxy
Frontend CoverArt rewrites https://coverartarchive.org/... URLs to /api/cover?url=….
The proxy:
- allows only HTTPS
coverartarchive.orgURLs; - uses single-flight;
- stores image + content-type metadata in
data/covers; - caps images at 5MB;
- returns immutable browser cache headers;
- responds with
x-cover-cache: HIT|MISS.
Non-CAA URLs already stored render directly, but the UI no longer offers URL entry. Uploaded covers use coverUrl = upload:<sha256>.<ext> and are served from data/uploads/covers; they are user-owned and survive metadata refresh. The edit form and manual add dialog offer upload, replacement and removal. An editor that closes without saving deletes the uploads it created after a server reference check. Release updates, deletes and replace imports delete the exact files they orphan. Startup and an hourly sweep remove any remaining stale files, with a one-hour age guard.
Imports
JSON import/restore
- Settings sends a parsed JSON file to
POST /api/import/previewfirst; no data is written. - Preview returns incoming, importable, duplicate, invalid and current counts plus warnings.
POST /api/import?mode=mergeis the default.mode=replacerequires a fullapp: "sleeve"JSON object.- Replace clears the collection, saved/follows, library defaults and discovery state in one transaction, then restores the backup.
- Dedupe:
- releases with MBID → MBID
- manual releases → normalized title + artist + format
- wishlist uses the same rules
- saved by release-group ID, follows by artist ID
- Duplicate/invalid rows are counted and skipped.
createdAtis preserved for releases, wishlist, saved and follows.- Creates release tracks in one transaction with the release rows.
- Every import creates a
pre-import-*.dbsnapshot before writing. Snapshot failure aborts the import. - When the backup is a zip, the client extracts
library.jsonand the cover files, previews the JSON, then posts the payload plus files toPOST /api/import/upload. Cover files are written before the transaction and referencedupload:values must all be present. - Exact
.dbrestore remains CLI-only; live SQLite file swapping is intentionally avoided.
Discogs CSV import
/import/csvis lazy-loaded.- Papa Parse reads the CSV client-side.
src/lib/discogs.tsauto-maps columns by normalized header synonyms.- Mapping changes update a live preview immediately.
- Transform normalizes format, condition, rating, dates, year, comma/dot prices and currency.
- Rows without title or artist are skipped.
- The mapped array is sent to the generic
/api/import, so the same dedupe and validation apply.
Wishlist
Wishlist is a separate table, not a release status. It represents buy intent only. Items can be added from MusicBrainz search results without fetching full release detail. Target price/currency and notes are editable per item. Wishlist state is not part of collection stats.
Saved suggestions
Discover bookmarks live in SavedSuggestion, not Wishlist. Saving stores only release-group metadata. The Saved tab in Discover can promote a suggestion into Wishlist, which creates a WishlistItem and removes the saved row. Saved items are excluded from future Discover feeds. Following an artist is separate: ArtistFollow is a taste signal, never an album bookmark or buy intent.
Discovery
See Discovery for the full algorithm. Short version: server/discovery.ts composes a cached feed from four album-oriented sources:
- From your artists — top owned/wishlist/followed artists by weighted affinity. One MusicBrainz query batched across their artist IDs, last 30 days plus upcoming.
- New this week — top 3 genres and similar artists, albums/EPs released in the last 7 days.
- New this month — albums/EPs released 8–30 days ago.
- Lost in the Stacks — all-time older albums/EPs from top genres and similar artists, rotated deterministically by month key.
Feed rules:
- Mixes only studio albums/EPs; no secondary types.
- Removes owned releases, wishlist/saved items, duplicates, Various Artists and repeated artists.
- Caps: 8 per section, with artist, genre and era diversity limits.
- Candidates are expanded with ListenBrainz similar artists seeded from top owned/wishlist artists.
- Ranking combines library affinity (purchases, ratings, wishlist, saves, weak opens) with ListenBrainz artist and release-group listen/user counts.
releaseCountis not used as a popularity proxy. - First available item becomes the lead pick and is removed from its section; similar-artist picks are preferred when the From your artists section has no items.
- Feed snapshots live in
DiscoveryFeedfor 7 days. Expired feeds are served stale while a background rebuild runs; there is no user-facing refresh button. ?refresh=1is a dev/internal override. Wishlist/saved changes shape the next weekly refresh; owning a record prunes only that item from the current feed.- Returned release-group IDs are stored in
DiscoverySeenfor 30 days and deprioritised on later generations. - Opening a suggestion and removing saved/wishlist items are recorded in
DiscoveryEvent; no extra user action or prompt is introduced. - Card opens a suggestion dialog with Listen on ListenBrainz under the recommendation reason, then Add to wishlist, Save for later and I already own it — Add to library. Listening opens the release-group page in a new tab; playback depends on the user's ListenBrainz music service. Adding to the library opens the edition picker; Discover never creates a release directly. Artist link opens
/artists/:mbid.
PWA/offline
public/sw.js:
- Pre-caches the shell, built JS/CSS assets parsed from
index.html, core icons and key API GETs. - Navigation: network-first, fallback to cached
index.html. - Static assets and
/api/cover: cache-first. - Selected API GETs: network-first, fallback to cache.
- Cache groups: shell, runtime assets, API, covers.
- Registered only in production.
- An offline banner appears when the browser goes offline.
Frontend structure
Routes
| Path | Page |
|---|---|
/ | Library |
/releases/:id | Release detail, edit, refresh, enrich, manual match |
/artists/:mbid | Artist detail + paginated discography |
/wishlist | Wishlist |
/discover | Discover picks |
/stats | Collection + spending insights |
/settings | Appearance, defaults, data, metadata cache, about |
/import/csv | Lazy-loaded Discogs CSV mapping |
State
- TanStack Query owns server state and abort signals.
AppProviderowns Add dialog state and its optional preset (rgid:/ artist query).- UI settings (theme, accent, view, sort) use
localStoragekeysleeve:settings:v1. - Library defaults (format, condition, currency) live in SQLite
AppSettingsand are cached by TanStack Query. - Wishlist add/edit dialogs and metadata dialogs are local component state.
- Toasts have a small custom provider.
Visual language and component patterns are documented in Design system.
Static demo
src/demo/ mounts the same React app with HashRouter for static hosting. api.ts replaces window.fetch for /api/*, serving deterministic fixtures and read-only responses; data.ts generates the records, wishlist, Discover feed, stats and artist pages. vite.demo.config.ts builds it into docs/public/demo, and bun run docs:build includes that folder in the docs site at /demo/. No database, API server or service worker is involved.
Filtering and defaults
- Library filters live in URL search params (
q,format,genre,decade,sort,view). - The global header search debounces input, previews library/artist/wishlist hits and only writes
qto the URL on the Library page. Submitting or choosing “View all” opens/withq. - Global search supports scopes (
all,library,wishlist,artists), recent searches inlocalStorage, match highlighting andkey:valueoperators. Free text matches title and artist only; label, catalog, genre, year, format and track are operator-only. Operator queries also work on the Library page. - Release search uses the
ReleaseSearchFTS5 index when present, restricted to title and artist columns. The route falls back to Prismacontainsif the index or migration is missing. - Default view/sort come from browser settings; format/condition/currency come from
AppSettings. - Settings accent changes CSS variables at runtime.
Source of truth
| Data | Source |
|---|---|
| Owned releases/tracks | SQLite Release/Track |
| Wishlist | SQLite WishlistItem |
| Followed artists | SQLite ArtistFollow |
| Library defaults | SQLite AppSettings |
| UI preferences | Browser localStorage |
| MusicBrainz payload cache | SQLite MetadataCache |
| Cover images | data/covers disk cache |
| Filter state | URL params |
Key extension points
- Add a new MB endpoint only in
server/musicbrainz.tsand wrap it withwithCache. - Add a new page under
src/pages/and register insrc/App.tsx; lazy-load heavy tools. - Add a new DB field: update Prisma schema, add a migration, run
db:deploy, update server schemas, response types, export/import mapping, UI and docs. - For destructive operations, require explicit confirmation and never run them automatically.