Repository navigation
feat(songs): store a song's audio duration, extracted on upload - #1202
Conversation
A Song stored no duration, so every playlist row in the music library on wemeditate.com rendered `0:00` (sydevs/WeMeditateWeb#252 reads the field and waits on this). Meditations already extracted one from the uploaded buffer; the machinery was one collection away from reuse. `extractAudioDuration` moves out of `src/collections/Meditations/hooks/` into `src/lib/audio/duration.ts` and becomes a factory taking the cap as an option — Meditations passes 50 minutes, Songs passes none, because that cap is a meditation rule. Importing it from Songs where it sat would have been the cross-owner import `src/AGENTS.md` rule 4 prohibits, and two consumers is what `lib-boundary` requires of a module under `src/lib/`. `readAudioDuration` splits out of it so the backfill parses the same way the hook does, with each caller deciding what an unparseable file means: the hook warns and leaves the save alone, the backfill reports the row and carries on. The hook fires on an upload, so songs stored before it carry no duration. `backfillSongDurations` reads each one's stored audio and writes the length it states, behind `scripts/backfill-song-durations.ts` — dry run by default, `--force` writes, and a song that already holds a duration is never fetched. Two fixture audio files land with it: all five fixture songs shared one file, so identical durations would have proved nothing, and one song now carries a real MPEG header with no duration in it, which is what a corrupt upload looks like to a reviewer. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjWAgPrgD8ZLRKq8E68
… cap Review pass over the branch. The backfill downloaded each whole track to read a header. `readAudioDuration` now takes a stream as well as a buffer, so `parseWebStream` stops at the format block and the rest of the body is never pulled; the response's own content-type goes with it, and a stalled transfer is bounded rather than hanging an operator's run for ever. Its result drops `scanned`, which was always `written.length + skipped.length`, and splits the two row shapes so a row carries either a duration or a reason, never both. A missing `CLOUDFLARE_R2_DELIVERY_URL` is one failure before the loop rather than the same skip reason repeated per song, and the script exits through `exitAfterFlush`, which is what keeps a few hundred lines of report from being truncated on a pipe. Meditations' 50 minutes becomes `MAX_MEDITATION_MINUTES`, so the Lemonfox timeout comment points at a name that can be grepped rather than at a literal inside a 600-line config. The int spec's two hand-mocked hook cases went: the unit spec covers them without a schema bootstrap. Its own upload helper went with them, in favour of `testData.createSong` and a copy of the corrupt sample under `tests/files/`, which is where test audio lives. The backfill spec reads its audio from there too; `audio-duration.spec.ts` keeps reading `src/fixture/files/`, because what a reviewer sees on each fixture song is exactly what it asserts. The corrupt fixture song now says so in its title, so a reviewer opening the preview can tell a deliberate blank duration from the defect this fixes. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjWAgPrgD8ZLRKq8E68
|
🚅 Deployed to the SahajCloud-pr-1202 environment in sahajcloud
1 service not affected by this PR
|
|
🤖 no session running recent dispatchesWritten by the sydevs dispatcher. Sessions never edit this comment. |
sydevs-bot
left a comment
There was a problem hiding this comment.
🧐 Adversarial review
The diff is the ticket and no larger: one moved extractor, one column, one hook, one migration, one backfill. It also removes two hook cases from the int lane into tests/unit/audio-duration.spec.ts, where they belong. The ladder found nothing to fold away — readAudioDuration has two callers taking different inputs, and backfillSongDurations is the thin-wrapper shape lib-boundary.spec.ts exempts by name.
The contract holds. Song.duration is additive, and WeMeditateWeb composes its own select for songs (server/content-index.ts:68), so the consumer gains the field by adding one key. "No endpoint changed" is correct.
All three findings are claims the diff's own evidence contradicts. None is a design problem.
Findings
- should-fix
src/fixture/songs.ts:8— "unreadable" is wrong in four places. The file parses; it states no duration. - should-fix
src/collections/Songs/Songs.ts:109— the editor-facing description says "every save". The hook reads only on an upload. - consider
src/collections/Meditations/Meditations.ts:116—MAX_MEDITATION_MINUTESis exported, and nothing imports it.
What was checked
Read whole on the branch: duration.ts, backfillSongDurations.ts, the script, Songs.ts, both new specs, fixture/songs.ts, albums.ts, content-ids.ts. Ladder walked on readAudioDuration, the backfill routine, the new constant, both fixture audio files. Consumer side followed into WeMeditateWeb server/content-index.ts and sahajcloud-client.ts. getR2Url's unset branch checked against urlFields.ts:101. Migration read: one ADD COLUMN, down drops it. All three preview links answer ON_HOST, and ids 1017001, 1017003 and 1015001 each exist under src/fixture/, showing what each line claims. This checkout has no node_modules, so nothing needing one was asserted.
🤖 Written by the sydevs autonomous loop — see what this is
Generated by Claude Code
The file starts `ff fb 90 00`, a valid MPEG frame header, and
`readAudioDuration` resolves `undefined` for it rather than throwing. Only
`Buffer.from('not audio')` is unparseable anywhere in this branch, so
"unreadable" named a branch these bytes never take.
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjYNtutVUAzXq8hd6qB
The hook returns early when `req.file` is absent, so a save uploading no file reads nothing and keeps the stored value. The description claimed every save, and it reaches both the admin panel and the generated type's JSDoc. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjYNtutVUAzXq8hd6qB
Nothing imports `MAX_MEDITATION_MINUTES`, and the cap is Meditations' own. The Lemonfox timeout comment names its file beside the symbol, so the breadcrumb survives the constant being private. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjYNtutVUAzXq8hd6qB
|
Addressed all three review findings. Each is its own commit, and each thread carries the detail.
The branch was already on the current 🤖 Written by the sydevs autonomous loop — see what this is Generated by Claude Code |
Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjWD6khx11V4rCcXh7D
A one-time backfill left in src/lib/ is app code nothing in the app calls, and retiring it would need a PR of its own. Beside its CLI it is one deletion, and the unit spec still covers it there — the shape challenge-mounts.ts and preview-domain-plan.ts already use. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjWD6khx11V4rCcXh7D
|
Four threads answered — two adopted, two answered with the code.
Merged current 🤖 Written by the sydevs autonomous loop — see what this is Generated by Claude Code |
Both sides added a migration, so `src/migrations/index.ts` conflicted. Both are kept, in timestamp order — they are independent. The data-only migration main added re-stamps the previous migration's snapshot, and after this merge the previous migration is this branch's. Its `.json` is re-copied from `20261118_181435_add_songs_duration.json` for that reason. Left as main wrote it, it is the newest snapshot by timestamp and states no `songs.duration`, so the next `migrate:create` on main re-emits `ALTER TABLE "songs" ADD COLUMN "duration"` — the replay that aborts a boot migration (#566). Watched it emit exactly that, then verified a probe writes nothing against the re-stamped snapshot. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjXaZcpX2oGt8egpGWS
|
Merged One change the diff does not explain. The data-only migration main added ( Left as main wrote it, that file is the newest snapshot by timestamp and states no Lean gate green (3813 unit tests). 🤖 Written by the sydevs autonomous loop — see what this is Generated by Claude Code |
Summary
src/lib/audio/, with its 50-minute cap as a caller's option.Change outline
Contract — what
songsstores and servessongs src/collections/Songs/Songs.ts hooks.beforeChange restrictUploadToAdmin + extractAudioDuration() # no cap: a song is an album track autoSetIncludeForMeditationsOnCreate fields title, album, tags + duration: number, read-only, seconds # ALTER TABLE songs ADD COLUMN duration numeric includeForMeditations, fileMetadataA client that asks for it gets it —
GET /api/songs?select[duration]=true— which is howsydevs/WeMeditateWeb#252 reads it. No endpoint changed.
Files — where the extractor lives now
Songs importing the hook where it sat would be the cross-owner import
src/AGENTS.mdrule 4prohibits, and two consumers is what
tests/unit/lib-boundary.spec.tsrequires of a module undersrc/lib/. The backfill has one caller and is not app code, so it sits beside its CLI instead.Behaviour — what each caller does with audio it cannot measure
extractAudioDuration({ maxMinutes }) src/lib/audio/duration.ts no req.file → return data unchanged readAudioDuration(buffer, req.file.mimetype) throws → warn, return data unchanged # a save must not fail over metadata no duration → return data unchanged over the cap → throw # only where a caller passes one data.duration = whole seconds backfillSongDurations(payload, { dryRun }) scripts/song-durations.ts find songs where duration does not exist, trashed rows included no filename → skipped, "no audio file" fetch(getR2Url(filename)), 60 s bound not ok / no body / unparseable → skipped, with the reason no duration stated → skipped, "audio states no duration" update the row, unless dryRunThe hook holds the uploaded bytes already; the backfill holds a response, so
readAudioDurationtakes either andparseWebStreamstops at the format block rather thanpulling a whole track across the network.
Preview
Songs set
admin.hidden: true, which unregisters their own routes —/admin/collections/songs/<id>404s. The join on an album is the way in: open the album, then each song from its Songs list.
Fixture Opening Breathreads 42 s,Fixture Held Note9 s. They shared one audio file before this branch, so matching durations would have proved nothing.Fixture Damaged Interlude (no duration)carries a real MPEG header with no duration behind it, so its Duration field is blank and the save still succeeded. That blankness is the fixture's point, not a defect.Contract impact
src/payload-types.tsgainsSong.duration. sydevs/WeMeditateWeb#252 is the consumer andcarries the matching
Blocked by:line; the dispatcher re-syncs the copied types after thismerges.
Migration
src/migrations/20261118_181435_add_songs_duration.tsADD COLUMN "duration" numericonsongs. No rename, no data touched.Songsconfigures no
versions, so there is no version table to carry it.downdrops the column, and nothing but this branch reads it.Test results
.claude/skills/pr-prep/check.sh— lint, format, typecheck, typecheck:tests, 3796 unit testssong-duration,meditation-duration,fixture-load,albums,meditation-songs(43 cases)Every new assertion was watched failing first: unmounting the Songs hook reddens three cases in
song-duration.int.spec.ts, moving the cap to 100 minutes reddens the Meditations case, anddropping the backfill's
response.okcheck reddens its skip case.Manual verification
GET /api/songs?select[title]=true&select[duration]=true&depth=0&limit=5on the preview, with a client key — each row carries a number.pnpm tsx scripts/backfill-song-durations.tsis a dry run that writes nothing;--forcewrites.Notes for reviewer
Three design calls worth your eye, each raised by the review pass and kept deliberately:
fileMetadatais not where this went. The ticket settles it — only the storage adapters andseed importers write that column, and a stored, typed number is what a client can
select.Video duration does arrive through
fileMetadata(the Stream adapter writes it), so audio andvideo now answer "how long is this" two ways. Moving audio into the R2 adapter's
handleUploadwould unify them for all eight upload collections; it is a bigger change than this ticket, and
files,user-choicesandsong-tagsget no duration until someone makes it.audioDurationField()factory. A field-level
beforeChangeruns after every collection hook (feat(events): enforce one lifecycle table for events and submissions #1121), which would putthe write after
cacheMeditationNodeWeights— and that hook computes weights against theduration the save is about to store. A factory declaring only the column would be a middle
layer, so neither form was taken.
refusal Meditations owns. It is now
MAX_MEDITATION_MINUTESinMeditations.ts, unexported,and the Lemonfox timeout comment points at that name and file rather than at a literal.
Dismissed with reasons: a concurrent backfill loop (sequential is fine at this catalogue size,
and it keeps the dry-run report in id order); folding
tests/unit/music-metadata.spec.tsinto thenew spec (it is pre-existing and pins the library itself, WAV included); and generalising the
backfill to any collection (nothing asks for it yet).
Security review ran — the diff touches
src/collections/*/hooks/— and found nothing. The onlynew outbound call composes its host from
CLOUDFLARE_R2_DELIVERY_URLand its path from aslugified R2 key, and the routine is reachable only from the operator script.
Detail
Why a second fixture audio file. All five fixture songs shared
fixture-audio.mp3, so everysong would have shown 42 s whether extraction worked or not.
fixture-audio-short.mp3is 9 s,18 KB, generated silence.
Why
tests/files/audio-51m.mp3is 4 KB.music-metadatareads an MP3's length from the Xingheader in the first frame, so a 51-minute file truncated to 4 KB still states 51 minutes. The case
it supports pins
maxMinutes: 50on Meditations, which the unit lane cannot see.Fixture pre-mortem. The new entries assume
songsacceptsaudio/mpegand that Payload sniffsthe bytes rather than trusting the declared type. Checked against
src/collections/Songs/Songs.ts(
upload.mimeTypes) andnode_modules/payload/dist/uploads/checkFileRestrictions.js— a file thatsniffs as text is refused whatever its extension, which is why
fixture-audio-no-duration.mp3carries a real MPEG frame header — it parses, and states no duration.
Closes #1195
Generated by Claude Code