Skip to content

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.

text
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/covers

Runtime modes ​

Development ​

  • bun run dev starts:
    • API on PORT (3001, from .env)
    • Vite on 5173, proxying /api to 3001
  • Vite serves the SPA; the API does not serve dist/.
  • Service worker is not registered.

Production ​

  • bun run build writes dist/.
  • bun run start sets NODE_ENV=production.
  • server/index.ts starts Bun.serve:
    • /api/* → Elysia
    • existing files under dist/ → static response
    • everything else → dist/index.html (SPA fallback)
  • Production port is PORT (3001 in the local .env).
  • Service worker registration happens in src/main.tsx only under import.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.
  • refreshRelease bypasses the normal cache read and stores fresh detail.

TTLs:

TierTTL
Search / artist search / genre release-group search30 min
Release detail / artist detail / artist group pages7 days
Empty search result10 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/ ​

ModuleResponsibility
releases.tsCRUD, list filters, owned lookup, refresh/enrich/manual match, clear library
search.tsGlobal header search across releases, artists and wishlist, with scopes and operators
search-query.tsConverts parsed operators into Prisma filters
search-index.tsSQLite FTS5 lookup with contains fallback
musicbrainz.tsRelease search, barcode search, artist search/detail, group pages, release detail
wishlist.tsWishlist CRUD
follows.tsFollowed artists list, follow/unfollow
settings.tsLibrary defaults read/update
discover.tsDiscover picks from library affinity and ListenBrainz
import.tsMerge-safe import, JSON or multipart with uploaded covers
export.tsBackup: JSON, or zip with library.json and uploaded covers
stats.tsCollection stats, spending stats, missing-metadata count
meta.tsFormat/genre/decade filter options
maintenance.tsMetadata cache stats + clear
covers.tsAllowlisted Cover Art Archive proxy, disk cache, uploaded cover storage

Request flows ​

Add a release ​

  1. Add dialog searches releases through /api/musicbrainz/search.
  2. Artist suggestions are derived from the release search results; no separate artist call by default.
  3. User can explicitly request an artist search, or click an artist to open the artist page.
  4. Clicking a result fetches full release detail unless the MBID is already owned.
  5. On save, /api/releases stores release and tracks in SQLite.
  6. 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-match applies 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 pass request.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.org URLs;
  • 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/preview first; no data is written.
  • Preview returns incoming, importable, duplicate, invalid and current counts plus warnings.
  • POST /api/import?mode=merge is the default. mode=replace requires a full app: "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.
  • createdAt is preserved for releases, wishlist, saved and follows.
  • Creates release tracks in one transaction with the release rows.
  • Every import creates a pre-import-*.db snapshot before writing. Snapshot failure aborts the import.
  • When the backup is a zip, the client extracts library.json and the cover files, previews the JSON, then posts the payload plus files to POST /api/import/upload. Cover files are written before the transaction and referenced upload: values must all be present.
  • Exact .db restore remains CLI-only; live SQLite file swapping is intentionally avoided.

Discogs CSV import ​

  • /import/csv is lazy-loaded.
  • Papa Parse reads the CSV client-side.
  • src/lib/discogs.ts auto-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. releaseCount is 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 DiscoveryFeed for 7 days. Expired feeds are served stale while a background rebuild runs; there is no user-facing refresh button.
  • ?refresh=1 is 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 DiscoverySeen for 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 ​

PathPage
/Library
/releases/:idRelease detail, edit, refresh, enrich, manual match
/artists/:mbidArtist detail + paginated discography
/wishlistWishlist
/discoverDiscover picks
/statsCollection + spending insights
/settingsAppearance, defaults, data, metadata cache, about
/import/csvLazy-loaded Discogs CSV mapping

State ​

  • TanStack Query owns server state and abort signals.
  • AppProvider owns Add dialog state and its optional preset (rgid: / artist query).
  • UI settings (theme, accent, view, sort) use localStorage key sleeve:settings:v1.
  • Library defaults (format, condition, currency) live in SQLite AppSettings and 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 q to the URL on the Library page. Submitting or choosing “View all” opens / with q.
  • Global search supports scopes (all, library, wishlist, artists), recent searches in localStorage, match highlighting and key:value operators. 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 ReleaseSearch FTS5 index when present, restricted to title and artist columns. The route falls back to Prisma contains if 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 ​

DataSource
Owned releases/tracksSQLite Release/Track
WishlistSQLite WishlistItem
Followed artistsSQLite ArtistFollow
Library defaultsSQLite AppSettings
UI preferencesBrowser localStorage
MusicBrainz payload cacheSQLite MetadataCache
Cover imagesdata/covers disk cache
Filter stateURL params

Key extension points ​

  • Add a new MB endpoint only in server/musicbrainz.ts and wrap it with withCache.
  • Add a new page under src/pages/ and register in src/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.