Compare commits
13
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
237380b122 | ||
|
|
4f077736b6 | ||
|
|
727f68950e | ||
|
|
aa9f534f3c | ||
|
|
011b4d9a9c | ||
|
|
d5aa081157 | ||
|
|
a99f855e98 | ||
|
|
7e4727fc49 | ||
|
|
1b7fa635d8 | ||
|
|
57d2299180 | ||
|
|
fa7ea41ccf | ||
|
|
324059b2bd | ||
|
|
1138d75a45 |
+5
-19
@@ -6,20 +6,9 @@
|
|||||||
**/build
|
**/build
|
||||||
web/build
|
web/build
|
||||||
|
|
||||||
# The Android client — built by its own job, never from this context. The APK
|
# Flutter mobile client — built separately on developer machines / Flutter CI.
|
||||||
# reaches the image through client/, downloaded as a CI artifact, so nothing
|
# Including it in the Go build context wastes ~70 files and invalidates the
|
||||||
# here reads android/ sources.
|
# `COPY . .` layer cache on every Flutter-only change.
|
||||||
#
|
|
||||||
# This block named `flutter_client/` until 2026-09-10 and lost its PATTERN when
|
|
||||||
# that tree was deleted, leaving a comment describing an exclusion that was no
|
|
||||||
# longer happening. android/ never took its place, so 4.1 MB of Gradle project
|
|
||||||
# has been entering the context and busting the `COPY . .` layer on every
|
|
||||||
# Android-only change.
|
|
||||||
android/
|
|
||||||
|
|
||||||
# Local `make build` output — an 18 MB binary the image never uses, since the
|
|
||||||
# builder stage compiles its own.
|
|
||||||
bin/
|
|
||||||
|
|
||||||
# Docs and IDE noise
|
# Docs and IDE noise
|
||||||
docs/
|
docs/
|
||||||
@@ -37,8 +26,5 @@ docs/
|
|||||||
!.env.example
|
!.env.example
|
||||||
|
|
||||||
# CI workflow files don't need to ship in the image.
|
# CI workflow files don't need to ship in the image.
|
||||||
#
|
.forgejo/
|
||||||
# This said `.forgejo/` and `.github/` — neither of which this repo has. Gitea
|
.github/
|
||||||
# Actions reads `.gitea/`, so the one directory that actually exists was the
|
|
||||||
# one not excluded, and every workflow edit invalidated the context.
|
|
||||||
.gitea/
|
|
||||||
|
|||||||
@@ -0,0 +1,95 @@
|
|||||||
|
name: android
|
||||||
|
|
||||||
|
# Native Android (Kotlin/Compose/Media3) — M8 rewrite, now the only client.
|
||||||
|
# This workflow is testing only — lint + detekt + unit tests on every push
|
||||||
|
# to dev/main, plus a debug APK artifact for main. The signed-release
|
||||||
|
# build + asset attach + image-bundling lives in release.yml under a
|
||||||
|
# `needs:` chain so the docker image cannot ship without the APK.
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [main, dev]
|
||||||
|
paths:
|
||||||
|
- 'android/**'
|
||||||
|
- '.gitea/workflows/android.yml'
|
||||||
|
|
||||||
|
# pull_request trigger intentionally omitted — see test-web.yml for
|
||||||
|
# the rationale (single-author repo, push covers PR-merge equivalent).
|
||||||
|
concurrency:
|
||||||
|
group: ${{ github.workflow }}-${{ github.ref }}
|
||||||
|
cancel-in-progress: true
|
||||||
|
|
||||||
|
env:
|
||||||
|
# Silences the JDK 22+ "restricted method in java.lang.System has been
|
||||||
|
# called" warning that Gradle 9.1's bundled native-platform jar trips
|
||||||
|
# at launch (System.load for native primitives). Affects the LAUNCHER
|
||||||
|
# JVM, not the daemon — that's why org.gradle.jvmargs in
|
||||||
|
# gradle.properties isn't enough. Future-compat: required opt-in once
|
||||||
|
# JDK 25 promotes the warning to an error.
|
||||||
|
JAVA_TOOL_OPTIONS: "--enable-native-access=ALL-UNNAMED"
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
name: Build + lint + test
|
||||||
|
# Using flutter-ci runner label because it's the only proven-working
|
||||||
|
# label with docker that can pull our container.image. Switch to
|
||||||
|
# android-ci once the operator registers that runner label.
|
||||||
|
runs-on: flutter-ci
|
||||||
|
container:
|
||||||
|
image: git.fabledsword.com/bvandeusen/ci-android:36
|
||||||
|
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
working-directory: android
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Cache Gradle dirs
|
||||||
|
# Resolved deps + Gradle distribution + Kotlin daemon caches.
|
||||||
|
# Saves ~3 min per CI run after the first warm-up.
|
||||||
|
uses: actions/cache@v4
|
||||||
|
with:
|
||||||
|
path: |
|
||||||
|
~/.gradle/caches
|
||||||
|
~/.gradle/wrapper
|
||||||
|
~/.kotlin
|
||||||
|
key: gradle-${{ runner.os }}-${{ hashFiles('android/gradle/wrapper/gradle-wrapper.properties', 'android/gradle/libs.versions.toml', 'android/**/*.gradle.kts') }}
|
||||||
|
restore-keys: |
|
||||||
|
gradle-${{ runner.os }}-
|
||||||
|
|
||||||
|
- name: Make gradlew executable
|
||||||
|
run: chmod +x ./gradlew
|
||||||
|
|
||||||
|
- name: Gradle wrapper validation
|
||||||
|
run: ./gradlew --version
|
||||||
|
|
||||||
|
- name: ktlint
|
||||||
|
run: ./gradlew ktlintCheck
|
||||||
|
|
||||||
|
- name: detekt
|
||||||
|
run: ./gradlew detekt
|
||||||
|
|
||||||
|
- name: Unit tests
|
||||||
|
run: ./gradlew testDebugUnitTest
|
||||||
|
|
||||||
|
- name: Assemble debug
|
||||||
|
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
|
||||||
|
run: ./gradlew assembleDebug
|
||||||
|
|
||||||
|
- name: Upload debug APK
|
||||||
|
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
|
||||||
|
# Mirrored action, never actions/upload-artifact. @v4+ throws
|
||||||
|
# GHESNotSupportedError client-side on the hostname (no server setting
|
||||||
|
# reaches that check), and @v3 is worse — it reports success while Gitea
|
||||||
|
# serves artifacts back only through the v4 API, so the upload is stored
|
||||||
|
# and invisible to every retrieval path. @v3 is what left 72 unreachable
|
||||||
|
# artifacts on this repo. Pinned by SHA because the mirror auto-syncs;
|
||||||
|
# full URL because DEFAULT_ACTIONS_URL sends bare owner/repo to github.com.
|
||||||
|
# See Scribe issues 2255 / 2270.
|
||||||
|
uses: https://git.fabledsword.com/bvandeusen/upload-artifact@cb8afe72b42edc798abfb8fcb556cf660d894245
|
||||||
|
with:
|
||||||
|
name: minstrel-android-debug-${{ github.sha }}
|
||||||
|
path: android/app/build/outputs/apk/debug/app-debug.apk
|
||||||
|
if-no-files-found: error
|
||||||
+106
-631
@@ -2,403 +2,55 @@ name: release
|
|||||||
|
|
||||||
# Builds and pushes the minstrel container image to the Gitea registry.
|
# Builds and pushes the minstrel container image to the Gitea registry.
|
||||||
#
|
#
|
||||||
# push to dev → :dev (freshly-built dev APK bundled)
|
# push to main → :main and :latest (latest-release APK bundled)
|
||||||
# push to main → :latest + :<sha> (latest-release APK bundled)
|
# push tag vYYYY.MM.DD → :vYYYY.MM.DD and :latest (freshly-built APK bundled)
|
||||||
# push tag vYYYY.MM.DD.HHMM → :latest (fresh APK bundled)
|
# workflow_dispatch → manual trigger (same rules based on the ref)
|
||||||
# workflow_dispatch → manual trigger (same rules based on the ref)
|
|
||||||
#
|
#
|
||||||
# That is the whole tag map, and it is family rule 145 + 147 as written.
|
# Release model: per-day CalVer tags (no trailing patch digit). The day's
|
||||||
#
|
# tag is intentionally mutable — if a second release happens the same day,
|
||||||
# :<sha> on main is the ROLLBACK UNIT — every production commit addressable
|
# move the tag with `git push -f origin vYYYY.MM.DD` and the image tag of
|
||||||
# without a release ceremony. It is minted only on main, where rollback is
|
# the same name gets overwritten. :latest is updated by every main push
|
||||||
# actually worth having: merges are gated (rule 2) so they number in the dozens
|
# AND every tag push, so it always reflects the newest blessed image.
|
||||||
# per year, while on dev they would be one per push, forever, for a channel
|
|
||||||
# whose entire contract is that it moves.
|
|
||||||
#
|
|
||||||
# There are NO :<version> image tags. This repo published :vYYYY.MM.DD.HHMM
|
|
||||||
# until 2026-09-10 and it was the inverse of the rule on both counts — minting
|
|
||||||
# a version tag nobody pinned while the rollback unit the rule names did not
|
|
||||||
# exist here at all. Git and the build's own self-reported version answer
|
|
||||||
# "which build is this"; a third name for the same thing is upkeep for a model
|
|
||||||
# we do not run. Operator, 2026-09-10: "only things like the APK need that kind
|
|
||||||
# of versioning for their update process."
|
|
||||||
#
|
|
||||||
# There is no :main either. :latest tracks main's tip with no gate between them
|
|
||||||
# (rule 147), so a second name for the same image sends readers looking for a
|
|
||||||
# distinction that does not exist.
|
|
||||||
#
|
|
||||||
# The dev channel exists so testing a build does not require shipping one.
|
|
||||||
# Before it, the only way to get an APK onto a phone was to cut a release,
|
|
||||||
# which made `main` the staging area by default. `:dev` carries its own
|
|
||||||
# freshly-built APK, signed with the SAME key as release builds — a different
|
|
||||||
# key cannot install over the stable app, so anyone crossing channels would
|
|
||||||
# have to uninstall and lose their data.
|
|
||||||
#
|
|
||||||
# :dev is published ALONE, with no per-commit tag. A rolling channel is
|
|
||||||
# rolling by definition; a commit-addressable image for it would be a
|
|
||||||
# rollback target nobody ever pulls, kept forever. Recovery on dev is to fix
|
|
||||||
# forward.
|
|
||||||
#
|
|
||||||
# Note what this repo does NOT need: a cross-repo dispatch to refresh the
|
|
||||||
# channel when its bundled APK is rebuilt. That mechanism exists elsewhere in
|
|
||||||
# the family because the app and the server live in separate repos. Minstrel
|
|
||||||
# is a monorepo — one push builds the APK and the image in the same run from
|
|
||||||
# the same commit, so the channel cannot go stale against its own artifact.
|
|
||||||
# The requirement is satisfied structurally; copying the mechanism would add
|
|
||||||
# a moving part to fix a problem that does not exist here.
|
|
||||||
#
|
|
||||||
# Release model: the tag IS the artifact's version name with a `v` in front.
|
|
||||||
# `v2026.09.10.1432` and `2026.09.10.1432` are the same string, derived from
|
|
||||||
# the tagged commit's UTC timestamp — so there is no mismatch to reconcile
|
|
||||||
# between what the tag says and what the APK reports, and nothing to look up
|
|
||||||
# when minting one.
|
|
||||||
#
|
|
||||||
# TAGS ARE IMMUTABLE. Never move, retarget or delete a published tag. A
|
|
||||||
# same-day second release is not a collision — HHMM makes every tag unique
|
|
||||||
# by construction, so the answer is simply another tag.
|
|
||||||
#
|
|
||||||
# This block used to say the opposite: that the per-day tag was
|
|
||||||
# "intentionally mutable" and that a same-day re-cut should
|
|
||||||
# `git push -f origin vYYYY.MM.DD`. That instruction is what the family
|
|
||||||
# rulebook now forbids outright, and it has incidents behind it — moving a
|
|
||||||
# same-day tag forward once took a published release down with it. Anyone
|
|
||||||
# installing from a tag is holding something the tag no longer points at,
|
|
||||||
# which is a worse failure than an extra row in the tag list.
|
|
||||||
#
|
|
||||||
# :latest is updated by every main push AND every tag push, so it always
|
|
||||||
# reflects the newest blessed image.
|
|
||||||
#
|
#
|
||||||
# APK pipeline: on tag pushes the android-release job builds + signs the
|
# APK pipeline: on tag pushes the android-release job builds + signs the
|
||||||
# Android APK and uploads it as a workflow artifact. The image-release
|
# Android APK and uploads it as a workflow artifact. The image-release
|
||||||
# job declares `needs: android-release`, so the docker image cannot
|
# job declares `needs: android-release`, so the docker image cannot
|
||||||
# start building until the APK is guaranteed-ready — no polling, no
|
# start building until the APK is guaranteed-ready — no polling, no
|
||||||
# race, no silent-failure mode. Attaching the APK to the gitea Release is
|
# race, no silent-failure mode. Asset attachment to the gitea Release
|
||||||
# its own job (release-assets), behind the test gate below.
|
# happens in the same android-release job, so the Release-page download
|
||||||
|
# link and the in-image bundled APK are both populated atomically.
|
||||||
#
|
#
|
||||||
# :latest always carries an APK. Because every main push also moves
|
# :latest always carries an APK. Because every main push also moves
|
||||||
# :latest (not just tags), a main build with no APK would silently strip
|
# :latest (not just tags), a main build with no APK would silently strip
|
||||||
# the in-app update channel off :latest until the next release. So on
|
# the in-app update channel off :latest until the next release. So on
|
||||||
# non-tag builds image-release pulls the MOST RECENT release's signed APK
|
# non-tag builds image-release pulls the MOST RECENT release's signed APK
|
||||||
# AND the version sidecar published beside it — the recorded values, not
|
# and reconstructs its exact versionName (tag + commit-count, the same
|
||||||
# recomputed ones — so no rebuild is needed, just a rebundle. Tag builds
|
# formula android-release bakes in) for the version sidecar — no rebuild,
|
||||||
# keep bundling their own freshly-built APK.
|
# just rebundle. Tag builds keep bundling their own freshly-built APK.
|
||||||
#
|
#
|
||||||
# THE GATE (rule 177, M462 #4984). Every verifying lane lives in this file —
|
# Android testing (lint + detekt + unit tests, debug APK upload on main)
|
||||||
# Go (vet, lint, short tests), the Postgres integration suite, the web app
|
# lives in android.yml and runs independently on every push.
|
||||||
# (npm audit, svelte-check, vitest), Android (ktlint, detekt, unit tests) and
|
|
||||||
# govulncheck — and every job that publishes something names each of them in
|
|
||||||
# `needs:` and requires `success` from each, by name. Nothing publishes on red.
|
|
||||||
#
|
|
||||||
# They used to be three separate workflows (test-go, test-web, android) on the
|
|
||||||
# same push trigger as this one. Separate workflows cannot see each other's
|
|
||||||
# verdict, so :dev meant "it built", never "it passed": a red test run and a
|
|
||||||
# fresh :dev could carry the same timestamp. One graph is the only place the
|
|
||||||
# edge can be written.
|
|
||||||
#
|
|
||||||
# A skipped lane is NOT a pass. The publishing conditions check
|
|
||||||
# `result == 'success'` per lane rather than `!failure()`, so a lane that
|
|
||||||
# never started blocks the publish exactly as a red one does. Lanes carry no
|
|
||||||
# path filters for the same reason: a web-only push still runs the Go suite,
|
|
||||||
# because "not run" must never read as "passed".
|
|
||||||
#
|
|
||||||
# What publishes, and is therefore gated: the image tags (image-release) and
|
|
||||||
# the APK + version sidecar attached to a tag's Release (release-assets).
|
|
||||||
# android-release only BUILDS the signed APK into a workflow artifact, which
|
|
||||||
# nobody outside this run can pull, so it runs in parallel with the lanes
|
|
||||||
# instead of after them; attaching it to the Release is the publishing half,
|
|
||||||
# and that half waits for the gate.
|
|
||||||
#
|
|
||||||
# To watch the gate refuse: dispatch this workflow with force_red=true. The go
|
|
||||||
# lane fails on purpose, and both publishing jobs must report skipped.
|
|
||||||
|
|
||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
branches: [main, dev]
|
branches: [main]
|
||||||
tags: ['v*']
|
tags: ['v*']
|
||||||
paths-ignore:
|
paths-ignore:
|
||||||
- 'docs/**'
|
- 'docs/**'
|
||||||
- '**/*.md'
|
- '**/*.md'
|
||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
inputs:
|
|
||||||
force_red:
|
|
||||||
description: Fail the go lane on purpose, to check that nothing publishes on red
|
|
||||||
type: boolean
|
|
||||||
default: false
|
|
||||||
|
|
||||||
# A rapid re-push to main should supersede the in-flight build — the
|
# Force-moving the per-day tag (or rapidly re-pushing to main) should
|
||||||
# operator explicitly wants the later commit to win. Tags no longer enter
|
# supersede the in-flight build — the operator explicitly wants the
|
||||||
# into this: they are immutable and unique, so no tag build can ever be
|
# later commit to win.
|
||||||
# superseded by another run on the same ref.
|
|
||||||
concurrency:
|
concurrency:
|
||||||
group: ${{ github.workflow }}-${{ github.ref }}
|
group: ${{ github.workflow }}-${{ github.ref }}
|
||||||
cancel-in-progress: true
|
cancel-in-progress: true
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
# ---------------------------------------------------------------- lanes --
|
|
||||||
# Verifying jobs. Each one is named in the `needs:` of every publishing job
|
|
||||||
# below; add a lane here and it must be added there in the same commit.
|
|
||||||
|
|
||||||
go:
|
|
||||||
runs-on: go-ci
|
|
||||||
container:
|
|
||||||
image: git.fabledsword.com/bvandeusen/ci-go:1.26
|
|
||||||
|
|
||||||
steps:
|
|
||||||
- name: Checkout
|
|
||||||
uses: actions/checkout@v4
|
|
||||||
|
|
||||||
- name: Forced failure (gate check)
|
|
||||||
if: github.event.inputs.force_red == 'true'
|
|
||||||
run: |
|
|
||||||
echo "::error::force_red dispatch: failing on purpose so the publishing jobs must skip"
|
|
||||||
exit 1
|
|
||||||
|
|
||||||
- name: Toolchain versions
|
|
||||||
run: |
|
|
||||||
go version
|
|
||||||
golangci-lint --version
|
|
||||||
|
|
||||||
- name: Generated code matches queries (sqlc)
|
|
||||||
run: make verify-generate
|
|
||||||
|
|
||||||
- name: go vet
|
|
||||||
run: go vet ./...
|
|
||||||
|
|
||||||
- name: golangci-lint
|
|
||||||
run: golangci-lint run ./...
|
|
||||||
|
|
||||||
- name: go test (short, race)
|
|
||||||
run: go test -short -race ./...
|
|
||||||
|
|
||||||
# Full `go test -race` against an ephemeral Postgres.
|
|
||||||
#
|
|
||||||
# DB wiring follows the act_runner shared-daemon pattern: the runner's Docker
|
|
||||||
# daemon also runs the operator's dev compose stack, so service containers
|
|
||||||
# get NO published ports (collision) and no service-name DNS. We discover the
|
|
||||||
# service container through the mounted docker socket and reach it by bridge
|
|
||||||
# IP. The exactly-one assertion is a hard guard — pointing tests at the dev
|
|
||||||
# Postgres would truncate it (the disaster Fable #339 exists to prevent).
|
|
||||||
#
|
|
||||||
# The key stays `integration` with no `name:` (rule 80): act_runner derives
|
|
||||||
# the service container's name from the job's display name.
|
|
||||||
#
|
|
||||||
# `web/build/` has a committed placeholder index.html so go:embed succeeds
|
|
||||||
# without the SPA being built first.
|
|
||||||
integration:
|
|
||||||
runs-on: go-ci
|
|
||||||
container:
|
|
||||||
image: git.fabledsword.com/bvandeusen/ci-go:1.26
|
|
||||||
services:
|
|
||||||
postgres:
|
|
||||||
image: postgres:16-alpine
|
|
||||||
env:
|
|
||||||
POSTGRES_USER: minstrel
|
|
||||||
POSTGRES_PASSWORD: minstrel
|
|
||||||
POSTGRES_DB: minstrel_test
|
|
||||||
# No `ports:` — the runner shares the operator's dev compose
|
|
||||||
# Docker daemon; publishing a fixed host port collides.
|
|
||||||
|
|
||||||
steps:
|
|
||||||
- name: Checkout
|
|
||||||
uses: actions/checkout@v4
|
|
||||||
|
|
||||||
- name: Integration suite (discover service by bridge IP, migrate, test)
|
|
||||||
run: |
|
|
||||||
set -eux
|
|
||||||
# Discover THIS job's Postgres service container via the
|
|
||||||
# mounted docker socket. act_runner attaches the job
|
|
||||||
# container and its service container(s) to a shared per-job
|
|
||||||
# network, so scope discovery to a postgres that sits on a
|
|
||||||
# network THIS job container is also on. The old
|
|
||||||
# `--filter name=integration` matched EVERY concurrent
|
|
||||||
# integration run's postgres (a dev push + the main-merge run
|
|
||||||
# overlap → 2 candidates → false "expected exactly 1" abort).
|
|
||||||
# The operator's dev compose `minstrel-postgres-*` is never on
|
|
||||||
# this job's network; skip it explicitly as belt-and-suspenders
|
|
||||||
# (a wrong target would truncate real data).
|
|
||||||
SELF=$(cat /etc/hostname)
|
|
||||||
SELF_NETS=$(docker inspect -f '{{range $k,$v := .NetworkSettings.Networks}}{{$k}} {{end}}' "$SELF")
|
|
||||||
test -n "$SELF_NETS"
|
|
||||||
echo "self ($SELF) networks: $SELF_NETS"
|
|
||||||
PG_ID=""
|
|
||||||
PG_NAME=""
|
|
||||||
for cid in $(docker ps --filter "ancestor=postgres:16-alpine" -q); do
|
|
||||||
nm=$(docker inspect -f '{{.Name}}' "$cid" | sed 's#^/##')
|
|
||||||
case "$nm" in *minstrel-postgres*|*_postgres_*) continue ;; esac
|
|
||||||
for net in $(docker inspect -f '{{range $k,$v := .NetworkSettings.Networks}}{{$k}} {{end}}' "$cid"); do
|
|
||||||
case " $SELF_NETS " in *" $net "*) PG_ID="$cid"; PG_NAME="$nm"; break 2 ;; esac
|
|
||||||
done
|
|
||||||
done
|
|
||||||
test -n "$PG_ID" || { echo "FATAL: no postgres service container on this job's network (self nets: $SELF_NETS)"; exit 1; }
|
|
||||||
echo "selected postgres: $PG_ID $PG_NAME"
|
|
||||||
PG_IP=$(docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' "$PG_ID")
|
|
||||||
test -n "$PG_IP"
|
|
||||||
export MINSTREL_TEST_DATABASE_URL="postgres://minstrel:minstrel@${PG_IP}:5432/minstrel_test?sslmode=disable"
|
|
||||||
|
|
||||||
# Wait for Postgres to accept connections. Asked of the service
|
|
||||||
# container itself: the run: shell is dash (rule 81), where the
|
|
||||||
# old `/dev/tcp` probe never connects and the loop silently
|
|
||||||
# burned its full two minutes on every run.
|
|
||||||
ready=""
|
|
||||||
for i in $(seq 1 60); do
|
|
||||||
if docker exec "$PG_ID" pg_isready -U minstrel -d minstrel_test -q; then ready=1; break; fi
|
|
||||||
sleep 2
|
|
||||||
done
|
|
||||||
test -n "$ready" || { echo "FATAL: postgres never became ready"; exit 1; }
|
|
||||||
|
|
||||||
# Relax durability on the throwaway CI Postgres. Our test pattern
|
|
||||||
# is dbtest.ResetDB → TRUNCATE … RESTART IDENTITY CASCADE before
|
|
||||||
# every test, and the per-TRUNCATE commit fsync is the dominant
|
|
||||||
# cost of the integration suite. The CI DB is rebuilt every run so
|
|
||||||
# fsync / full_page_writes / synchronous_commit buy nothing. Apply
|
|
||||||
# via docker exec because:
|
|
||||||
# - The act_runner `services:` block can't override the container
|
|
||||||
# command, so `postgres -c fsync=off` at boot isn't an option.
|
|
||||||
# - ALTER SYSTEM cannot run inside a transaction; psql -c
|
|
||||||
# auto-commits each statement, which is what we need.
|
|
||||||
# - fsync / full_page_writes are sighup GUCs and
|
|
||||||
# synchronous_commit is user-context, so pg_reload_conf() picks
|
|
||||||
# all three up with no restart.
|
|
||||||
# Non-fatal: a perms surprise degrades to "slower", never red CI.
|
|
||||||
docker exec "$PG_ID" psql -U minstrel -d minstrel_test \
|
|
||||||
-c "ALTER SYSTEM SET fsync = off" \
|
|
||||||
-c "ALTER SYSTEM SET synchronous_commit = off" \
|
|
||||||
-c "ALTER SYSTEM SET full_page_writes = off" \
|
|
||||||
-c "SELECT pg_reload_conf()" \
|
|
||||||
|| echo "WARN: durability relax failed; continuing"
|
|
||||||
|
|
||||||
# Apply embedded migrations to the fresh test DB, then run the
|
|
||||||
# full suite (no -short → integration tests execute). -p 1:
|
|
||||||
# every integration package TRUNCATEs the one shared test DB;
|
|
||||||
# concurrent package binaries → TRUNCATE deadlocks. Serialize
|
|
||||||
# package execution (the documented local invocation too).
|
|
||||||
MINSTREL_DATABASE_URL="$MINSTREL_TEST_DATABASE_URL" go run ./cmd/minstrel migrate
|
|
||||||
go test -p 1 -race ./...
|
|
||||||
|
|
||||||
web:
|
|
||||||
runs-on: go-ci
|
|
||||||
container:
|
|
||||||
image: git.fabledsword.com/bvandeusen/ci-go:1.26
|
|
||||||
|
|
||||||
defaults:
|
|
||||||
run:
|
|
||||||
working-directory: web
|
|
||||||
|
|
||||||
steps:
|
|
||||||
- name: Checkout
|
|
||||||
uses: actions/checkout@v4
|
|
||||||
|
|
||||||
- name: Install deps
|
|
||||||
run: npm ci
|
|
||||||
|
|
||||||
# What ships to browsers: `dependencies` and the runtime they pull in
|
|
||||||
# (svelte, devalue). Build and test tooling (vite, vitest, tailwind,
|
|
||||||
# kit's dev server) is left out because none of it reaches a user, and
|
|
||||||
# its open advisories need major-version upgrades tracked separately.
|
|
||||||
- name: npm audit (shipped dependencies)
|
|
||||||
run: npm audit --omit=dev --audit-level=moderate
|
|
||||||
|
|
||||||
- name: Type-check + svelte-check
|
|
||||||
run: npm run check
|
|
||||||
|
|
||||||
- name: Vitest
|
|
||||||
run: npm test
|
|
||||||
|
|
||||||
android:
|
|
||||||
# Using flutter-ci runner label because it's the only proven-working
|
|
||||||
# label with docker that can pull our container.image.
|
|
||||||
runs-on: flutter-ci
|
|
||||||
container:
|
|
||||||
image: git.fabledsword.com/bvandeusen/ci-android:36
|
|
||||||
|
|
||||||
defaults:
|
|
||||||
run:
|
|
||||||
working-directory: android
|
|
||||||
|
|
||||||
env:
|
|
||||||
# Silences the JDK 22+ "restricted method in java.lang.System has been
|
|
||||||
# called" warning that Gradle's bundled native-platform jar trips at
|
|
||||||
# launch. Affects the LAUNCHER JVM, not the daemon — that's why
|
|
||||||
# org.gradle.jvmargs in gradle.properties isn't enough.
|
|
||||||
JAVA_TOOL_OPTIONS: "--enable-native-access=ALL-UNNAMED"
|
|
||||||
|
|
||||||
steps:
|
|
||||||
- name: Checkout
|
|
||||||
uses: actions/checkout@v4
|
|
||||||
|
|
||||||
- name: Cache Gradle dirs
|
|
||||||
uses: actions/cache@v4
|
|
||||||
with:
|
|
||||||
path: |
|
|
||||||
~/.gradle/caches
|
|
||||||
~/.gradle/wrapper
|
|
||||||
~/.kotlin
|
|
||||||
key: gradle-${{ runner.os }}-${{ hashFiles('android/gradle/wrapper/gradle-wrapper.properties', 'android/gradle/libs.versions.toml', 'android/**/*.gradle.kts') }}
|
|
||||||
restore-keys: |
|
|
||||||
gradle-${{ runner.os }}-
|
|
||||||
|
|
||||||
- name: Make gradlew executable
|
|
||||||
run: chmod +x ./gradlew
|
|
||||||
|
|
||||||
- name: Gradle wrapper validation
|
|
||||||
run: ./gradlew --version
|
|
||||||
|
|
||||||
- name: ktlint
|
|
||||||
run: ./gradlew ktlintCheck
|
|
||||||
|
|
||||||
- name: detekt
|
|
||||||
run: ./gradlew detekt
|
|
||||||
|
|
||||||
- name: Unit tests
|
|
||||||
run: ./gradlew testDebugUnitTest
|
|
||||||
|
|
||||||
- name: Assemble debug
|
|
||||||
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
|
|
||||||
run: ./gradlew assembleDebug
|
|
||||||
|
|
||||||
- name: Upload debug APK
|
|
||||||
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
|
|
||||||
# Stock action: it works on this forge since the runner moved to
|
|
||||||
# gitea/runner 3.x, which edits upload-artifact's client-side GHES refusal
|
|
||||||
# out of the action bundle (Scribe snippet #2271). Never @v3 — it reports
|
|
||||||
# success while Gitea serves artifacts back only through the v4 API, and
|
|
||||||
# it is what left 72 unreachable artifacts on this repo (Scribe 2270).
|
|
||||||
uses: actions/upload-artifact@v7
|
|
||||||
with:
|
|
||||||
name: minstrel-android-debug-${{ github.sha }}
|
|
||||||
path: android/app/build/outputs/apk/debug/app-debug.apk
|
|
||||||
if-no-files-found: error
|
|
||||||
|
|
||||||
# Known vulnerabilities in the Go code and the standard library it is built
|
|
||||||
# with. Runs in the SAME image the Dockerfile's builder stage uses, so the
|
|
||||||
# standard library it checks is the one that ends up in the shipped binary;
|
|
||||||
# the ci-go image carries its own Go and would be checking a different
|
|
||||||
# toolchain. Keep this image and the Dockerfile's builder in step.
|
|
||||||
#
|
|
||||||
# govulncheck is fetched at CI time, unpinned (rule 154): the vulnerability
|
|
||||||
# database and the tool that reads it should both be current.
|
|
||||||
govulncheck:
|
|
||||||
runs-on: go-ci
|
|
||||||
container:
|
|
||||||
image: golang:1.26-bookworm
|
|
||||||
|
|
||||||
steps:
|
|
||||||
- name: Checkout
|
|
||||||
uses: actions/checkout@v4
|
|
||||||
|
|
||||||
- name: govulncheck
|
|
||||||
run: |
|
|
||||||
go version
|
|
||||||
go run golang.org/x/vuln/cmd/govulncheck@latest ./...
|
|
||||||
|
|
||||||
# ------------------------------------------------------------ artifacts --
|
|
||||||
|
|
||||||
android-release:
|
android-release:
|
||||||
name: Build signed APK (releases and dev)
|
name: Build signed APK (tag releases only)
|
||||||
# Also builds on `dev`, which is what makes a test channel possible at
|
if: startsWith(github.ref, 'refs/tags/v')
|
||||||
# all. Without it the only way to get a build onto a phone was to cut a
|
|
||||||
# release, which quietly turns `main` into the staging area.
|
|
||||||
if: startsWith(github.ref, 'refs/tags/v') || github.ref == 'refs/heads/dev'
|
|
||||||
runs-on: flutter-ci
|
runs-on: flutter-ci
|
||||||
container:
|
container:
|
||||||
image: git.fabledsword.com/bvandeusen/ci-android:36
|
image: git.fabledsword.com/bvandeusen/ci-android:36
|
||||||
@@ -423,18 +75,14 @@ jobs:
|
|||||||
outputs:
|
outputs:
|
||||||
version_name: ${{ steps.ver.outputs.name }}
|
version_name: ${{ steps.ver.outputs.name }}
|
||||||
version_code: ${{ steps.ver.outputs.code }}
|
version_code: ${{ steps.ver.outputs.code }}
|
||||||
channel: ${{ steps.ver.outputs.channel }}
|
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
with:
|
with:
|
||||||
# Full history. The version name now reads only the tip commit's
|
# fetch-depth: 0 retrieves full history; default shallow clone
|
||||||
# timestamp, so a shallow clone would technically serve — but this
|
# would return 1 for `git rev-list --count HEAD`, breaking the
|
||||||
# job derives a value that ships to devices, and a shallow checkout
|
# iteration suffix.
|
||||||
# changes what git-derived values resolve to WITHOUT failing. The
|
|
||||||
# whole failure class here is a green build carrying a wrong
|
|
||||||
# version, so the cheap guarantee is worth keeping.
|
|
||||||
fetch-depth: 0
|
fetch-depth: 0
|
||||||
|
|
||||||
- name: Compute release version
|
- name: Compute release version
|
||||||
@@ -443,23 +91,12 @@ jobs:
|
|||||||
working-directory: ${{ github.workspace }}
|
working-directory: ${{ github.workspace }}
|
||||||
run: |
|
run: |
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
# The derivation lives in ci/version.sh, not here, so it can be
|
TAG="${GITHUB_REF#refs/tags/v}"
|
||||||
# executed by a test on every push. Anything inline in this file is
|
COMMIT_COUNT=$(git rev-list --count HEAD)
|
||||||
# unverifiable until a release is already running.
|
VERSION_NAME="${TAG}.${COMMIT_COUNT}"
|
||||||
out="$(ci/version.sh HEAD)"
|
echo "name=${VERSION_NAME}" >> "$GITHUB_OUTPUT"
|
||||||
printf '%s\n' "${out}" >> "$GITHUB_OUTPUT"
|
echo "code=${COMMIT_COUNT}" >> "$GITHUB_OUTPUT"
|
||||||
|
echo "::notice::APK version: ${VERSION_NAME} (code=${COMMIT_COUNT})"
|
||||||
# The channel is a property of the LANE, not of the commit, which is
|
|
||||||
# why it is derived here rather than in version.sh. Same commit built
|
|
||||||
# on dev and on main reports the same NAME and differs only here —
|
|
||||||
# that is the whole point of separating the two values.
|
|
||||||
if [ "${GITHUB_REF}" = "refs/heads/dev" ]; then
|
|
||||||
channel=dev
|
|
||||||
else
|
|
||||||
channel=stable
|
|
||||||
fi
|
|
||||||
echo "channel=${channel}" >> "$GITHUB_OUTPUT"
|
|
||||||
echo "::notice::APK $(printf '%s' "${out}" | tr '\n' ' ') channel=${channel}"
|
|
||||||
|
|
||||||
# Checked BEFORE the expensive work, not after it. "Attach APK to gitea
|
# Checked BEFORE the expensive work, not after it. "Attach APK to gitea
|
||||||
# Release" below resolves the release by tag and fails if it is absent —
|
# Release" below resolves the release by tag and fails if it is absent —
|
||||||
@@ -471,7 +108,6 @@ jobs:
|
|||||||
# the release together, so this passes). A bare `git push origin vX` is the
|
# the release together, so this passes). A bare `git push origin vX` is the
|
||||||
# case this catches.
|
# case this catches.
|
||||||
- name: Release must exist for this tag
|
- name: Release must exist for this tag
|
||||||
if: startsWith(github.ref, 'refs/tags/v')
|
|
||||||
shell: bash
|
shell: bash
|
||||||
working-directory: ${{ github.workspace }}
|
working-directory: ${{ github.workspace }}
|
||||||
env:
|
env:
|
||||||
@@ -520,12 +156,13 @@ jobs:
|
|||||||
-PMINSTREL_VERSION_CODE=${{ steps.ver.outputs.code }}
|
-PMINSTREL_VERSION_CODE=${{ steps.ver.outputs.code }}
|
||||||
|
|
||||||
- name: Upload APK as workflow artifact
|
- name: Upload APK as workflow artifact
|
||||||
# Stock action (snippet #2271) — never @v3, which uploads something Gitea
|
# Mirrored action, never actions/upload-artifact — @v4+ refuses on the
|
||||||
# will never serve back. This is the producing half of a pair:
|
# hostname, @v3 uploads something Gitea will never serve back. This is
|
||||||
# image-release downloads `minstrel-apk` below. Any upload v4+ pairs with
|
# the producing half of a pair: image-release downloads `minstrel-apk`
|
||||||
# any download v4+ on this forge (every combination tested 2026-09-10,
|
# below with the matching download-artifact mirror. Both must stay on
|
||||||
# Scribe spike #3843), so the two pins need not move together.
|
# the v4 protocol — mixing a v3 upload with a v4 download (or the
|
||||||
uses: actions/upload-artifact@v7
|
# reverse) yields an empty listing, not an error. See Scribe 2255 / 2270.
|
||||||
|
uses: https://git.fabledsword.com/bvandeusen/upload-artifact@cb8afe72b42edc798abfb8fcb556cf660d894245
|
||||||
with:
|
with:
|
||||||
name: minstrel-apk
|
name: minstrel-apk
|
||||||
path: android/app/build/outputs/apk/release/app-release.apk
|
path: android/app/build/outputs/apk/release/app-release.apk
|
||||||
@@ -533,63 +170,17 @@ jobs:
|
|||||||
# artifact existing, so an empty upload must fail here, not there.
|
# artifact existing, so an empty upload must fail here, not there.
|
||||||
if-no-files-found: error
|
if-no-files-found: error
|
||||||
|
|
||||||
# Publishes the signed APK and its version sidecar on the tag's Release.
|
|
||||||
# Split out of android-release so the APK can be BUILT in parallel with the
|
|
||||||
# lanes while being PUBLISHED only once they have all passed.
|
|
||||||
release-assets:
|
|
||||||
name: Attach APK to the Release (tag releases only)
|
|
||||||
needs: [go, integration, web, android, govulncheck, android-release]
|
|
||||||
if: >-
|
|
||||||
${{
|
|
||||||
!cancelled()
|
|
||||||
&& needs.go.result == 'success'
|
|
||||||
&& needs.integration.result == 'success'
|
|
||||||
&& needs.web.result == 'success'
|
|
||||||
&& needs.android.result == 'success'
|
|
||||||
&& needs.govulncheck.result == 'success'
|
|
||||||
&& needs.android-release.result == 'success'
|
|
||||||
&& startsWith(github.ref, 'refs/tags/v') }}
|
|
||||||
runs-on: go-ci
|
|
||||||
container:
|
|
||||||
image: git.fabledsword.com/bvandeusen/ci-go:1.26
|
|
||||||
|
|
||||||
steps:
|
|
||||||
- name: Download signed APK artifact
|
|
||||||
uses: actions/download-artifact@v8
|
|
||||||
with:
|
|
||||||
name: minstrel-apk
|
|
||||||
path: release-apk/
|
|
||||||
|
|
||||||
- name: Attach APK to gitea Release
|
- name: Attach APK to gitea Release
|
||||||
# Tag releases only. A dev build has no Release to hang assets on and
|
|
||||||
# does not need one — the :dev image bundles the APK, and the server
|
|
||||||
# serves it from /api/client/apk like any other.
|
|
||||||
shell: bash
|
shell: bash
|
||||||
env:
|
env:
|
||||||
CI_TOKEN: ${{ secrets.CI_TOKEN }}
|
CI_TOKEN: ${{ secrets.CI_TOKEN }}
|
||||||
VERSION_NAME: ${{ needs.android-release.outputs.version_name }}
|
|
||||||
VERSION_CODE: ${{ needs.android-release.outputs.version_code }}
|
|
||||||
run: |
|
run: |
|
||||||
set -euxo pipefail
|
set -euxo pipefail
|
||||||
TAG="${GITHUB_REF#refs/tags/}"
|
TAG="${GITHUB_REF#refs/tags/}"
|
||||||
REPO="${GITHUB_REPOSITORY}"
|
REPO="${GITHUB_REPOSITORY}"
|
||||||
APK_PATH="release-apk/app-release.apk"
|
APK_PATH="app/build/outputs/apk/release/app-release.apk"
|
||||||
ls -lh "${APK_PATH}"
|
ls -lh "${APK_PATH}"
|
||||||
|
|
||||||
# Publish the version sidecar as a release asset next to the APK.
|
|
||||||
#
|
|
||||||
# This is what lets a later :latest build stop RECONSTRUCTING the
|
|
||||||
# bundled APK's version and simply read what was recorded. The
|
|
||||||
# ordering key in particular cannot be re-derived after the fact —
|
|
||||||
# it is build-time minutes, so once this job ends the value exists
|
|
||||||
# nowhere else. Reconstruction could only ever recover the name,
|
|
||||||
# and only by duplicating a formula that then has to be kept in
|
|
||||||
# step across two files.
|
|
||||||
SIDECAR_PATH="/tmp/minstrel.apk.version"
|
|
||||||
printf '{"name":"%s","code":%s,"channel":"stable"}\n' \
|
|
||||||
"${VERSION_NAME}" "${VERSION_CODE}" > "${SIDECAR_PATH}"
|
|
||||||
cat "${SIDECAR_PATH}"
|
|
||||||
|
|
||||||
RELEASE_JSON="$(curl -fsSL \
|
RELEASE_JSON="$(curl -fsSL \
|
||||||
-H "Authorization: token ${CI_TOKEN}" \
|
-H "Authorization: token ${CI_TOKEN}" \
|
||||||
"https://git.fabledsword.com/api/v1/repos/${REPO}/releases/tags/${TAG}")"
|
"https://git.fabledsword.com/api/v1/repos/${REPO}/releases/tags/${TAG}")"
|
||||||
@@ -611,37 +202,15 @@ jobs:
|
|||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# Same treatment for the sidecar. Named `.apk.version` so the
|
|
||||||
# downloader's `\.apk$` match cannot pick it up by mistake.
|
|
||||||
SIDECAR_HTTP=$(curl -sS -L -o /tmp/upload-sidecar.out -w '%{http_code}' \
|
|
||||||
-H "Authorization: token ${CI_TOKEN}" \
|
|
||||||
-F "attachment=@${SIDECAR_PATH}" \
|
|
||||||
"https://git.fabledsword.com/api/v1/repos/${REPO}/releases/${RELEASE_ID}/assets?name=minstrel-${TAG}.apk.version")
|
|
||||||
echo "sidecar_upload_http=${SIDECAR_HTTP}"
|
|
||||||
cat /tmp/upload-sidecar.out || true
|
|
||||||
echo
|
|
||||||
if [ "${SIDECAR_HTTP}" -lt 200 ] || [ "${SIDECAR_HTTP}" -ge 300 ]; then
|
|
||||||
echo "::error::version sidecar upload returned HTTP ${SIDECAR_HTTP}"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
image-release:
|
image-release:
|
||||||
name: Build + push container image
|
name: Build + push container image
|
||||||
# Every lane must have SUCCEEDED, each named here (rule 177). Then the
|
# `needs:` waits for android-release. For tag pushes android-release
|
||||||
# APK: tag and dev pushes build one and it must have succeeded; main
|
# runs and must succeed before this job starts — guaranteeing the
|
||||||
# pushes skip android-release and bundle the latest release's APK
|
# APK artifact is present. For main pushes android-release is
|
||||||
# instead, so for main alone a skipped android-release is expected.
|
# skipped; the `if: ...` below lets this job run anyway and the
|
||||||
needs: [go, integration, web, android, govulncheck, android-release]
|
# download/copy steps gate themselves on the tag context.
|
||||||
if: >-
|
needs: [android-release]
|
||||||
${{
|
if: ${{ !failure() && !cancelled() }}
|
||||||
!cancelled()
|
|
||||||
&& needs.go.result == 'success'
|
|
||||||
&& needs.integration.result == 'success'
|
|
||||||
&& needs.web.result == 'success'
|
|
||||||
&& needs.android.result == 'success'
|
|
||||||
&& needs.govulncheck.result == 'success'
|
|
||||||
&& (needs.android-release.result == 'success'
|
|
||||||
|| (needs.android-release.result == 'skipped' && github.ref == 'refs/heads/main')) }}
|
|
||||||
runs-on: go-ci
|
runs-on: go-ci
|
||||||
container:
|
container:
|
||||||
image: git.fabledsword.com/bvandeusen/ci-go:1.26
|
image: git.fabledsword.com/bvandeusen/ci-go:1.26
|
||||||
@@ -653,16 +222,11 @@ jobs:
|
|||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
with:
|
with:
|
||||||
# Full history, and rule 149 names this specifically: any job that
|
# Full history + tags so non-tag :latest builds can resolve the
|
||||||
# DERIVES the version name needs it, because a shallow clone changes
|
# latest release tag's commit count and reconstruct the bundled
|
||||||
# what git-derived values resolve to WITHOUT failing — a too-low
|
# APK's exact versionName (see "Bundle latest release APK" below).
|
||||||
# value, silently, with every lane green.
|
|
||||||
#
|
|
||||||
# This job was depth-1 while it took the version from GITHUB_REF. It
|
|
||||||
# now runs ci/version.sh itself, because with :<version> image tags
|
|
||||||
# gone the server's self-reported version is the only thing that says
|
|
||||||
# which build an image is.
|
|
||||||
fetch-depth: 0
|
fetch-depth: 0
|
||||||
|
fetch-tags: true
|
||||||
|
|
||||||
- name: Detect buildable project
|
- name: Detect buildable project
|
||||||
id: guard
|
id: guard
|
||||||
@@ -680,68 +244,21 @@ jobs:
|
|||||||
if: steps.guard.outputs.ready == 'true'
|
if: steps.guard.outputs.ready == 'true'
|
||||||
shell: bash
|
shell: bash
|
||||||
run: |
|
run: |
|
||||||
set -euo pipefail
|
|
||||||
|
|
||||||
# THE VERSION, and it is derived the same way on every ref — the
|
|
||||||
# branch decides the CHANNEL, never the version (family rule 149).
|
|
||||||
#
|
|
||||||
# This used to be three different things: the literal string "main"
|
|
||||||
# on main, "dev" on dev, and the tag name on a tag. None of them
|
|
||||||
# ordered, and the first two were the same string forever — two dev
|
|
||||||
# images eight weeks apart were indistinguishable in the UI. That
|
|
||||||
# mattered little while :vYYYY.MM.DD.HHMM existed to identify a
|
|
||||||
# build; with version image tags gone, this IS how an operator tells
|
|
||||||
# which build a container is running.
|
|
||||||
#
|
|
||||||
# `sed -n s///p` rather than `grep`: it exits 0 when nothing matches,
|
|
||||||
# so the empty check below is actually reachable. A grep here would
|
|
||||||
# kill the step at the assignment under the runner's pipefail — the
|
|
||||||
# exact bug that took down the first main build after the version
|
|
||||||
# rework.
|
|
||||||
VERSION="$(ci/version.sh HEAD | sed -n 's/^name=//p')"
|
|
||||||
if [ -z "${VERSION}" ]; then
|
|
||||||
echo "::error::could not derive a build version from ci/version.sh"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
if [[ "${GITHUB_REF}" == refs/tags/v* ]]; then
|
if [[ "${GITHUB_REF}" == refs/tags/v* ]]; then
|
||||||
# A release refreshes the CHANNEL and mints nothing else.
|
VERSION="${GITHUB_REF#refs/tags/}"
|
||||||
#
|
echo "args=-t ${IMAGE}:${VERSION} -t ${IMAGE}:latest" >> "$GITHUB_OUTPUT"
|
||||||
# The tag build exists to produce the signed APK and attach it to
|
echo "version=${VERSION}" >> "$GITHUB_OUTPUT"
|
||||||
# the release; the image it rebuilds is the SAME SOURCE as the main
|
echo "::notice::Release build: ${VERSION} + latest"
|
||||||
# build minutes earlier, differing only in which APK is baked in.
|
|
||||||
# Rule 145 is explicit about that case: when the same source is
|
|
||||||
# rebuilt with different contents, publish the moving channel tag
|
|
||||||
# and never a commit-addressable one.
|
|
||||||
#
|
|
||||||
# :latest must move here rather than waiting for the next main
|
|
||||||
# push, or the channel would carry the PREVIOUS release's APK
|
|
||||||
# indefinitely — a channel that cannot refresh itself (rule 146).
|
|
||||||
CHANNEL=stable
|
|
||||||
echo "args=-t ${IMAGE}:latest" >> "$GITHUB_OUTPUT"
|
|
||||||
echo "::notice::Release build ${VERSION}: refreshing :latest around the new APK"
|
|
||||||
elif [[ "${GITHUB_REF}" == "refs/heads/dev" ]]; then
|
|
||||||
# The rolling test channel, and :dev ALONE — deliberately no
|
|
||||||
# per-commit tag. A rolling channel is rolling by definition, so a
|
|
||||||
# commit-addressable image here would be a rollback target nobody
|
|
||||||
# has ever pulled, accumulating in the registry forever. Recovery
|
|
||||||
# on dev is to fix forward.
|
|
||||||
CHANNEL=dev
|
|
||||||
echo "args=-t ${IMAGE}:dev" >> "$GITHUB_OUTPUT"
|
|
||||||
echo "::notice::Dev-branch build ${VERSION}: :dev"
|
|
||||||
else
|
else
|
||||||
# The production line: :latest tracks main's tip (rule 147) and
|
# Main is the protected, post-PR-merge branch. Treat it as the
|
||||||
# :<sha> is the rollback unit (rule 145). Full 40-char SHA, matching
|
# rolling stable channel — every main push moves :latest.
|
||||||
# the family's other repos, so a rollback target is addressable
|
# Pinned consumers can target :vYYYY.MM.DD; everyone else
|
||||||
# straight from the commit anyone is reading.
|
# gets the newest main.
|
||||||
CHANNEL=stable
|
echo "args=-t ${IMAGE}:main -t ${IMAGE}:latest" >> "$GITHUB_OUTPUT"
|
||||||
echo "args=-t ${IMAGE}:latest -t ${IMAGE}:${GITHUB_SHA}" >> "$GITHUB_OUTPUT"
|
echo "version=main" >> "$GITHUB_OUTPUT"
|
||||||
echo "::notice::Main-branch build ${VERSION}: :latest + :${GITHUB_SHA}"
|
echo "::notice::Main-branch build: :main + :latest"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
echo "version=${VERSION}" >> "$GITHUB_OUTPUT"
|
|
||||||
echo "channel=${CHANNEL}" >> "$GITHUB_OUTPUT"
|
|
||||||
|
|
||||||
- name: Registry login
|
- name: Registry login
|
||||||
if: steps.guard.outputs.ready == 'true'
|
if: steps.guard.outputs.ready == 'true'
|
||||||
shell: bash
|
shell: bash
|
||||||
@@ -750,57 +267,54 @@ jobs:
|
|||||||
| docker login git.fabledsword.com -u "${{ github.actor }}" --password-stdin
|
| docker login git.fabledsword.com -u "${{ github.actor }}" --password-stdin
|
||||||
|
|
||||||
- name: Download signed APK artifact
|
- name: Download signed APK artifact
|
||||||
# Tag and dev pushes — android-release just produced this. Only `main`
|
# Tag pushes only — android-release just produced this. Non-tag
|
||||||
# takes the "Bundle latest release APK" path below, because it is the
|
# builds take the "Bundle latest release APK" path below instead.
|
||||||
# one ref that moves a channel without building an APK of its own.
|
if: steps.guard.outputs.ready == 'true' && startsWith(github.ref, 'refs/tags/v')
|
||||||
if: >-
|
# Consuming half of the pair — never actions/download-artifact. Same fork,
|
||||||
steps.guard.outputs.ready == 'true' &&
|
# same reason: upstream's client-side GHES check rejects this hostname
|
||||||
(startsWith(github.ref, 'refs/tags/v') || github.ref == 'refs/heads/dev')
|
# before it connects. bvandeusen/download-artifact mirrors
|
||||||
# Consuming half of the pair: stock download-artifact, which works here for
|
# code.forgejo.org/forgejo/download-artifact.
|
||||||
# the same reason as the upload (gitea/runner 3.x edits the GHES refusal
|
#
|
||||||
# out of the bundle; snippet #2271). v8 runs on node24, which every
|
# SHA below is that fork's `v6` tag. Match on @actions/artifact, NOT on
|
||||||
# CI-runner image carries — the runner uses the image's own node.
|
# the action's own version number — the two actions release on unrelated
|
||||||
uses: actions/download-artifact@v8
|
# cadences, and download v5 would pair a ^2.3.2 client with this file's
|
||||||
|
# ^4.0.0 uploader. v6 is the tag whose bundled library major (^4.0.0) is
|
||||||
|
# the same one proven against this instance by the upload side.
|
||||||
|
# Deliberately NOT v7: it moves to node24 and upstream requires runner
|
||||||
|
# >= 2.327.1 for it, which act_runner does not claim to satisfy.
|
||||||
|
# Pinned, not tagged — the mirror auto-syncs every 8h.
|
||||||
|
uses: https://git.fabledsword.com/bvandeusen/download-artifact@8d4e9521a5f7e5f8b6351f341f719f9f45a92a3a
|
||||||
with:
|
with:
|
||||||
name: minstrel-apk
|
name: minstrel-apk
|
||||||
path: client/
|
path: client/
|
||||||
|
|
||||||
- name: Stage bundled APK + version sidecar
|
- name: Stage bundled APK + version sidecar
|
||||||
if: >-
|
if: steps.guard.outputs.ready == 'true' && startsWith(github.ref, 'refs/tags/v')
|
||||||
steps.guard.outputs.ready == 'true' &&
|
|
||||||
(startsWith(github.ref, 'refs/tags/v') || github.ref == 'refs/heads/dev')
|
|
||||||
shell: bash
|
shell: bash
|
||||||
env:
|
env:
|
||||||
# All three pulled from android-release's outputs so the sidecar the
|
# Pulled from android-release.outputs.version_name so the
|
||||||
# server hands clients matches exactly what is baked into the APK
|
# sidecar string the server hands clients matches the
|
||||||
# they are comparing against.
|
# versionName baked into the APK they're comparing against.
|
||||||
APK_VERSION_NAME: ${{ needs.android-release.outputs.version_name }}
|
APK_VERSION_NAME: ${{ needs.android-release.outputs.version_name }}
|
||||||
APK_VERSION_CODE: ${{ needs.android-release.outputs.version_code }}
|
|
||||||
APK_CHANNEL: ${{ needs.android-release.outputs.channel }}
|
|
||||||
run: |
|
run: |
|
||||||
set -euxo pipefail
|
set -euxo pipefail
|
||||||
# The artifact lands as `app-release.apk` (the original Gradle
|
# The artifact lands as `app-release.apk` (the original Gradle
|
||||||
# output name). The Dockerfile COPYs client/* into /app/client/
|
# output name). The Dockerfile COPYs client/* into /app/client/
|
||||||
# and the server reads minstrel.apk + minstrel.apk.version.
|
# and the server reads minstrel.apk + minstrel.apk.version.
|
||||||
mv client/app-release.apk client/minstrel.apk
|
mv client/app-release.apk client/minstrel.apk
|
||||||
printf '{"name":"%s","code":%s,"channel":"%s"}\n' \
|
echo "${APK_VERSION_NAME}" > client/minstrel.apk.version
|
||||||
"${APK_VERSION_NAME}" "${APK_VERSION_CODE}" "${APK_CHANNEL}" \
|
|
||||||
> client/minstrel.apk.version
|
|
||||||
cat client/minstrel.apk.version
|
|
||||||
ls -lh client/
|
ls -lh client/
|
||||||
|
|
||||||
- name: Bundle latest release APK (non-tag :latest builds)
|
- name: Bundle latest release APK (non-tag :latest builds)
|
||||||
# Main pushes don't build an APK, but they DO move :latest — so
|
# Main pushes don't build an APK, but they DO move :latest — so
|
||||||
# without this the in-app update channel would vanish from :latest
|
# without this the in-app update channel would vanish from :latest
|
||||||
# until the next tag. Pull the most-recent release's signed APK and
|
# until the next tag. Pull the most-recent release's signed APK and
|
||||||
# the sidecar published beside it, so what the server reports is what
|
# reconstruct its exact versionName (${TAG#v}.$(git rev-list --count
|
||||||
# that build actually recorded rather than something re-derived here.
|
# TAG) — identical to android-release's formula) so the version
|
||||||
|
# sidecar the server hands clients matches the installed build.
|
||||||
# Degrades to an empty client/ (404 update channel) — never a wrong
|
# Degrades to an empty client/ (404 update channel) — never a wrong
|
||||||
# version — if no release or APK asset can be resolved. That
|
# version — if no release / APK asset / tag-count can be resolved.
|
||||||
# degradation only actually works because the greps below carry
|
if: steps.guard.outputs.ready == 'true' && !startsWith(github.ref, 'refs/tags/v')
|
||||||
# `|| true`; under the runner's default pipefail a non-matching grep
|
|
||||||
# kills the step instead of falling through to the empty-case branch.
|
|
||||||
if: steps.guard.outputs.ready == 'true' && github.ref == 'refs/heads/main'
|
|
||||||
shell: bash
|
shell: bash
|
||||||
env:
|
env:
|
||||||
CI_TOKEN: ${{ secrets.CI_TOKEN }}
|
CI_TOKEN: ${{ secrets.CI_TOKEN }}
|
||||||
@@ -812,53 +326,26 @@ jobs:
|
|||||||
if [ -z "${REL_JSON}" ]; then
|
if [ -z "${REL_JSON}" ]; then
|
||||||
echo "::notice::no published release — image ships without bundled APK"; exit 0
|
echo "::notice::no published release — image ships without bundled APK"; exit 0
|
||||||
fi
|
fi
|
||||||
# `|| true` on every one of these, and it is load-bearing rather
|
TAG="$(printf '%s' "${REL_JSON}" | grep -oP '"tag_name":\s*"\K[^"]+' | head -1)"
|
||||||
# than defensive habit. The runner already invokes this shell as
|
APK_URL="$(printf '%s' "${REL_JSON}" | grep -oP '"browser_download_url":\s*"\K[^"]+' | grep -E '\.apk$' | head -1)"
|
||||||
# `bash -e -o pipefail`, so a pipeline whose grep matches NOTHING
|
|
||||||
# exits non-zero even though `head` succeeded — and the step dies at
|
|
||||||
# the assignment, before ever reaching the `if` written to handle the
|
|
||||||
# empty case. Every "degrades gracefully" branch below is unreachable
|
|
||||||
# without this.
|
|
||||||
TAG="$(printf '%s' "${REL_JSON}" | grep -oP '"tag_name":\s*"\K[^"]+' | head -1)" || true
|
|
||||||
APK_URL="$(printf '%s' "${REL_JSON}" | grep -oP '"browser_download_url":\s*"\K[^"]+' | grep -E '\.apk$' | head -1)" || true
|
|
||||||
if [ -z "${TAG}" ] || [ -z "${APK_URL}" ]; then
|
if [ -z "${TAG}" ] || [ -z "${APK_URL}" ]; then
|
||||||
echo "::notice::latest release '${TAG:-?}' has no APK asset — image ships without bundled APK"; exit 0
|
echo "::notice::latest release '${TAG:-?}' has no APK asset — image ships without bundled APK"; exit 0
|
||||||
fi
|
fi
|
||||||
curl -fsSL -H "Authorization: token ${CI_TOKEN}" -o client/minstrel.apk "${APK_URL}"
|
COUNT="$(git rev-list --count "${TAG}" 2>/dev/null || true)"
|
||||||
|
if [ -z "${COUNT}" ]; then
|
||||||
# Take the version the release RECORDED rather than recomputing it.
|
echo "::notice::could not resolve commit count for ${TAG} (tag not fetched?) — skipping APK bundle"; exit 0
|
||||||
# This used to re-derive the name from the tagged commit, which meant
|
|
||||||
# the formula lived in two files that had to be kept in step, and it
|
|
||||||
# could only ever recover the name — the ordering key is build-time
|
|
||||||
# minutes and does not exist anywhere after that build ends.
|
|
||||||
SIDECAR_URL="$(printf '%s' "${REL_JSON}" | grep -oP '"browser_download_url":\s*"\K[^"]+' | grep -E '\.apk\.version$' | head -1)" || true
|
|
||||||
if [ -n "${SIDECAR_URL}" ]; then
|
|
||||||
curl -fsSL -H "Authorization: token ${CI_TOKEN}" -o client/minstrel.apk.version "${SIDECAR_URL}"
|
|
||||||
cat client/minstrel.apk.version
|
|
||||||
else
|
|
||||||
# Releases published before sidecars were attached. Their name is
|
|
||||||
# still recoverable from the tag, but their ordering key genuinely
|
|
||||||
# is not — so it is reported ABSENT rather than guessed. A wrong
|
|
||||||
# key is an install the platform refuses; an absent one just tells
|
|
||||||
# the client to fall back to comparing names, which is exactly
|
|
||||||
# what those builds already do.
|
|
||||||
echo "::notice::release ${TAG} predates the version sidecar — bundling with name only, no ordering key"
|
|
||||||
printf '{"name":"%s","code":null,"channel":"stable"}\n' "${TAG#v}" > client/minstrel.apk.version
|
|
||||||
fi
|
fi
|
||||||
echo "::notice::bundled release APK from ${TAG}"
|
VERSION_NAME="${TAG#v}.${COUNT}"
|
||||||
|
curl -fsSL -H "Authorization: token ${CI_TOKEN}" -o client/minstrel.apk "${APK_URL}"
|
||||||
|
echo "${VERSION_NAME}" > client/minstrel.apk.version
|
||||||
|
echo "::notice::bundled release APK ${TAG} as version ${VERSION_NAME}"
|
||||||
ls -lh client/
|
ls -lh client/
|
||||||
|
|
||||||
- name: Build and push
|
- name: Build and push
|
||||||
if: steps.guard.outputs.ready == 'true'
|
if: steps.guard.outputs.ready == 'true'
|
||||||
# --pull: the Dockerfile's base images are floating tags (golang:1.26,
|
|
||||||
# debian:bookworm-slim). Without it the runner's daemon reuses
|
|
||||||
# whatever it cached, and the shipped binary can sit on a Go patch
|
|
||||||
# release govulncheck already flagged while the lane, which pulls
|
|
||||||
# fresh, reports clean.
|
|
||||||
run: |
|
run: |
|
||||||
docker buildx build --pull \
|
docker buildx build \
|
||||||
--build-arg MINSTREL_VERSION="${{ steps.tags.outputs.version }}" \
|
--build-arg MINSTREL_VERSION="${{ steps.tags.outputs.version }}" \
|
||||||
--build-arg MINSTREL_CHANNEL="${{ steps.tags.outputs.channel }}" \
|
|
||||||
--push ${{ steps.tags.outputs.args }} .
|
--push ${{ steps.tags.outputs.args }} .
|
||||||
|
|
||||||
# Verifies a tag release actually ended up complete, and names the specific
|
# Verifies a tag release actually ended up complete, and names the specific
|
||||||
@@ -869,8 +356,8 @@ jobs:
|
|||||||
# `failure` with none executed and image-release showed `skipped`. The run was
|
# `failure` with none executed and image-release showed `skipped`. The run was
|
||||||
# red, but the *release page rendered fine*, and `main`'s own push build had
|
# red, but the *release page rendered fine*, and `main`'s own push build had
|
||||||
# already moved `:latest`, so the code was deployable and nothing looked
|
# already moved `:latest`, so the code was deployable and nothing looked
|
||||||
# obviously wrong. The release was simply missing its APK and its image,
|
# obviously wrong. The release was simply missing its APK and its immutable
|
||||||
# which is easy to skim past.
|
# `:vYYYY.MM.DD` image, which is easy to skim past.
|
||||||
#
|
#
|
||||||
# This job cannot prevent that (the cause was a runner failing to launch, not
|
# This job cannot prevent that (the cause was a runner failing to launch, not
|
||||||
# anything in this file). What it does is turn an incomplete release into an
|
# anything in this file). What it does is turn an incomplete release into an
|
||||||
@@ -881,7 +368,7 @@ jobs:
|
|||||||
# above did NOT succeed.
|
# above did NOT succeed.
|
||||||
verify-release:
|
verify-release:
|
||||||
name: Verify release artifacts (tag releases only)
|
name: Verify release artifacts (tag releases only)
|
||||||
needs: [android-release, release-assets, image-release]
|
needs: [android-release, image-release]
|
||||||
if: ${{ always() && startsWith(github.ref, 'refs/tags/v') }}
|
if: ${{ always() && startsWith(github.ref, 'refs/tags/v') }}
|
||||||
runs-on: go-ci
|
runs-on: go-ci
|
||||||
container:
|
container:
|
||||||
@@ -921,30 +408,18 @@ jobs:
|
|||||||
# missing when v2026.08.07 had to be re-cut. `always()` on this job means
|
# missing when v2026.08.07 had to be re-cut. `always()` on this job means
|
||||||
# it runs even when image-release failed, so without this the guard would
|
# it runs even when image-release failed, so without this the guard would
|
||||||
# cheerfully verify an incomplete release.
|
# cheerfully verify an incomplete release.
|
||||||
#
|
- name: Immutable image tag must exist
|
||||||
# This asserted `:${TAG}` — the :vYYYY.MM.DD.HHMM image — until
|
|
||||||
# 2026-09-10. Version image tags are no longer published (rule 145), so
|
|
||||||
# that assertion would now fail every release for a tag nothing mints.
|
|
||||||
# The rollback target it was really protecting is the :<sha> image, which
|
|
||||||
# main's own build published for this same commit before the tag was cut.
|
|
||||||
#
|
|
||||||
# Checking it here earns its keep twice over: it still catches an image
|
|
||||||
# push that silently did not happen, and it additionally proves the
|
|
||||||
# ORDERING — a tag cut on a commit whose main build never completed has
|
|
||||||
# no rollback target, and that is worth failing on rather than
|
|
||||||
# discovering during an incident.
|
|
||||||
- name: Rollback image must exist for the tagged commit
|
|
||||||
shell: bash
|
shell: bash
|
||||||
run: |
|
run: |
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
|
TAG="${GITHUB_REF#refs/tags/}"
|
||||||
IMAGE="git.fabledsword.com/bvandeusen/minstrel"
|
IMAGE="git.fabledsword.com/bvandeusen/minstrel"
|
||||||
|
|
||||||
echo "${{ secrets.CI_TOKEN }}" \
|
echo "${{ secrets.CI_TOKEN }}" \
|
||||||
| docker login git.fabledsword.com -u "${{ github.actor }}" --password-stdin
|
| docker login git.fabledsword.com -u "${{ github.actor }}" --password-stdin
|
||||||
|
|
||||||
if ! docker manifest inspect "${IMAGE}:${GITHUB_SHA}" > /dev/null 2>&1; then
|
if ! docker manifest inspect "${IMAGE}:${TAG}" > /dev/null 2>&1; then
|
||||||
echo "::error::image ${IMAGE}:${GITHUB_SHA} does not exist — this commit has no rollback target."
|
echo "::error::image ${IMAGE}:${TAG} was never pushed — the release tag has no immutable image, so there is nothing to pin or roll back to. Re-run this workflow run."
|
||||||
echo "::error::That image is published by the MAIN build of this commit, not by the tag build. If main's build never ran or failed, fix that first; a release whose commit cannot be rolled back to is the thing this check exists to refuse."
|
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
echo "::notice::rollback target verified: ${IMAGE}:${GITHUB_SHA}"
|
echo "::notice::image verified: ${IMAGE}:${TAG}"
|
||||||
|
|||||||
@@ -0,0 +1,150 @@
|
|||||||
|
name: test-go
|
||||||
|
|
||||||
|
# Go server: vet + golangci-lint + short race tests. Runs on push to
|
||||||
|
# dev/main and PRs to main, scoped to Go-side files only — web-only or
|
||||||
|
# Flutter-only diffs don't trigger this workflow.
|
||||||
|
#
|
||||||
|
# Two jobs: `test` (fast — vet + lint + `go test -short -race`, no DB) and
|
||||||
|
# `integration` (full `go test -race` against an ephemeral Postgres).
|
||||||
|
#
|
||||||
|
# Integration-job DB wiring follows the act_runner shared-daemon pattern:
|
||||||
|
# the runner's Docker daemon also runs the operator's dev compose stack,
|
||||||
|
# so service containers get NO published ports (collision) and no
|
||||||
|
# service-name DNS. We discover the service container by the job-scoped
|
||||||
|
# name filter via the mounted docker socket and reach it by bridge IP.
|
||||||
|
# The exactly-one assertion is a hard guard — pointing tests at the dev
|
||||||
|
# Postgres would truncate it (the disaster Fable #339 exists to prevent).
|
||||||
|
#
|
||||||
|
# `web/build/` has a committed placeholder index.html so go:embed succeeds
|
||||||
|
# without needing the SPA to be freshly built. Real builds happen in
|
||||||
|
# release.yml (container) and locally during dev.
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [dev, main]
|
||||||
|
paths:
|
||||||
|
- '**/*.go'
|
||||||
|
- 'go.mod'
|
||||||
|
- 'go.sum'
|
||||||
|
- 'sqlc.yaml'
|
||||||
|
- 'Makefile'
|
||||||
|
- 'internal/**'
|
||||||
|
- 'cmd/**'
|
||||||
|
- '.golangci.yml'
|
||||||
|
- '.gitea/workflows/test-go.yml'
|
||||||
|
|
||||||
|
# pull_request trigger intentionally omitted — see test-web.yml for
|
||||||
|
# the rationale (single-author repo, push covers PR-merge equivalent).
|
||||||
|
concurrency:
|
||||||
|
group: ${{ github.workflow }}-${{ github.ref }}
|
||||||
|
cancel-in-progress: true
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
test:
|
||||||
|
runs-on: go-ci
|
||||||
|
container:
|
||||||
|
image: git.fabledsword.com/bvandeusen/ci-go:1.26
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Toolchain versions
|
||||||
|
run: |
|
||||||
|
go version
|
||||||
|
golangci-lint --version
|
||||||
|
|
||||||
|
- name: Generated code matches queries (sqlc)
|
||||||
|
run: make verify-generate
|
||||||
|
|
||||||
|
- name: go vet
|
||||||
|
run: go vet ./...
|
||||||
|
|
||||||
|
- name: golangci-lint
|
||||||
|
run: golangci-lint run ./...
|
||||||
|
|
||||||
|
- name: go test (short, race)
|
||||||
|
run: go test -short -race ./...
|
||||||
|
|
||||||
|
integration:
|
||||||
|
runs-on: go-ci
|
||||||
|
container:
|
||||||
|
image: git.fabledsword.com/bvandeusen/ci-go:1.26
|
||||||
|
services:
|
||||||
|
postgres:
|
||||||
|
image: postgres:16-alpine
|
||||||
|
env:
|
||||||
|
POSTGRES_USER: minstrel
|
||||||
|
POSTGRES_PASSWORD: minstrel
|
||||||
|
POSTGRES_DB: minstrel_test
|
||||||
|
# No `ports:` — the runner shares the operator's dev compose
|
||||||
|
# Docker daemon; publishing a fixed host port collides.
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Integration suite (discover service by bridge IP, migrate, test)
|
||||||
|
run: |
|
||||||
|
set -eux
|
||||||
|
# Discover THIS job's Postgres service container via the
|
||||||
|
# mounted docker socket. act_runner attaches the job
|
||||||
|
# container and its service container(s) to a shared per-job
|
||||||
|
# network, so scope discovery to a postgres that sits on a
|
||||||
|
# network THIS job container is also on. The old
|
||||||
|
# `--filter name=integration` matched EVERY concurrent
|
||||||
|
# integration run's postgres (a dev push + the main-merge run
|
||||||
|
# overlap → 2 candidates → false "expected exactly 1" abort).
|
||||||
|
# The operator's dev compose `minstrel-postgres-*` is never on
|
||||||
|
# this job's network; skip it explicitly as belt-and-suspenders
|
||||||
|
# (a wrong target would truncate real data).
|
||||||
|
SELF=$(cat /etc/hostname)
|
||||||
|
SELF_NETS=$(docker inspect -f '{{range $k,$v := .NetworkSettings.Networks}}{{$k}} {{end}}' "$SELF")
|
||||||
|
test -n "$SELF_NETS"
|
||||||
|
echo "self ($SELF) networks: $SELF_NETS"
|
||||||
|
PG_ID=""
|
||||||
|
PG_NAME=""
|
||||||
|
for cid in $(docker ps --filter "ancestor=postgres:16-alpine" -q); do
|
||||||
|
nm=$(docker inspect -f '{{.Name}}' "$cid" | sed 's#^/##')
|
||||||
|
case "$nm" in *minstrel-postgres*|*_postgres_*) continue ;; esac
|
||||||
|
for net in $(docker inspect -f '{{range $k,$v := .NetworkSettings.Networks}}{{$k}} {{end}}' "$cid"); do
|
||||||
|
case " $SELF_NETS " in *" $net "*) PG_ID="$cid"; PG_NAME="$nm"; break 2 ;; esac
|
||||||
|
done
|
||||||
|
done
|
||||||
|
test -n "$PG_ID" || { echo "FATAL: no postgres service container on this job's network (self nets: $SELF_NETS)"; exit 1; }
|
||||||
|
echo "selected postgres: $PG_ID $PG_NAME"
|
||||||
|
PG_IP=$(docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' "$PG_ID")
|
||||||
|
test -n "$PG_IP"
|
||||||
|
export MINSTREL_TEST_DATABASE_URL="postgres://minstrel:minstrel@${PG_IP}:5432/minstrel_test?sslmode=disable"
|
||||||
|
|
||||||
|
# Wait for Postgres to accept TCP (no health-check dependency).
|
||||||
|
for i in $(seq 1 60); do (echo > "/dev/tcp/${PG_IP}/5432") 2>/dev/null && break; sleep 2; done
|
||||||
|
|
||||||
|
# Relax durability on the throwaway CI Postgres. Our test pattern
|
||||||
|
# is dbtest.ResetDB → TRUNCATE … RESTART IDENTITY CASCADE before
|
||||||
|
# every test, and the per-TRUNCATE commit fsync is the dominant
|
||||||
|
# cost of the integration suite. The CI DB is rebuilt every run so
|
||||||
|
# fsync / full_page_writes / synchronous_commit buy nothing. Apply
|
||||||
|
# via docker exec because:
|
||||||
|
# - The act_runner `services:` block can't override the container
|
||||||
|
# command, so `postgres -c fsync=off` at boot isn't an option.
|
||||||
|
# - ALTER SYSTEM cannot run inside a transaction; psql -c
|
||||||
|
# auto-commits each statement, which is what we need.
|
||||||
|
# - fsync / full_page_writes are sighup GUCs and
|
||||||
|
# synchronous_commit is user-context, so pg_reload_conf() picks
|
||||||
|
# all three up with no restart.
|
||||||
|
# Non-fatal: a perms surprise degrades to "slower", never red CI.
|
||||||
|
docker exec "$PG_ID" psql -U minstrel -d minstrel_test \
|
||||||
|
-c "ALTER SYSTEM SET fsync = off" \
|
||||||
|
-c "ALTER SYSTEM SET synchronous_commit = off" \
|
||||||
|
-c "ALTER SYSTEM SET full_page_writes = off" \
|
||||||
|
-c "SELECT pg_reload_conf()" \
|
||||||
|
|| echo "WARN: durability relax failed; continuing"
|
||||||
|
|
||||||
|
# Apply embedded migrations to the fresh test DB, then run the
|
||||||
|
# full suite (no -short → integration tests execute). -p 1:
|
||||||
|
# every integration package TRUNCATEs the one shared test DB;
|
||||||
|
# concurrent package binaries → TRUNCATE deadlocks. Serialize
|
||||||
|
# package execution (the documented local invocation too).
|
||||||
|
MINSTREL_DATABASE_URL="$MINSTREL_TEST_DATABASE_URL" go run ./cmd/minstrel migrate
|
||||||
|
go test -p 1 -race ./...
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
name: test-web
|
||||||
|
|
||||||
|
# Web SPA: vitest + svelte-check. Runs on push to dev/main only —
|
||||||
|
# the `pull_request` trigger is intentionally omitted because every
|
||||||
|
# branch on this repo is local-only (no fork PRs), so the dev push
|
||||||
|
# fully covers what a PR run would re-execute. Keeping both events
|
||||||
|
# doubled CI cost on every commit.
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [dev, main]
|
||||||
|
paths:
|
||||||
|
- 'web/**'
|
||||||
|
- '.gitea/workflows/test-web.yml'
|
||||||
|
|
||||||
|
# Cancel an earlier in-flight run for the same ref when a newer
|
||||||
|
# commit arrives. With cancel-in-progress, rapid re-pushes don't
|
||||||
|
# pile up zombie runs.
|
||||||
|
concurrency:
|
||||||
|
group: ${{ github.workflow }}-${{ github.ref }}
|
||||||
|
cancel-in-progress: true
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
test:
|
||||||
|
runs-on: go-ci
|
||||||
|
container:
|
||||||
|
image: git.fabledsword.com/bvandeusen/ci-go:1.26
|
||||||
|
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
working-directory: web
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Install deps
|
||||||
|
run: npm ci
|
||||||
|
|
||||||
|
- name: Type-check + svelte-check
|
||||||
|
run: npm run check
|
||||||
|
|
||||||
|
- name: Vitest
|
||||||
|
run: npm test
|
||||||
@@ -12,11 +12,6 @@
|
|||||||
# Test binary, built with `go test -c`
|
# Test binary, built with `go test -c`
|
||||||
*.test
|
*.test
|
||||||
|
|
||||||
# `make build` output. bin/minstrel was tracked until 2026-09-10 — an 18 MB
|
|
||||||
# binary committed by accident, last refreshed by a commit about web test
|
|
||||||
# mocks, and re-dirtied by every local build since.
|
|
||||||
bin/
|
|
||||||
|
|
||||||
# Bundled Android APK + version sidecar (#397). Populated by CI for
|
# Bundled Android APK + version sidecar (#397). Populated by CI for
|
||||||
# tag releases; never committed. README in client/ explains the flow.
|
# tag releases; never committed. README in client/ explains the flow.
|
||||||
client/minstrel.apk
|
client/minstrel.apk
|
||||||
|
|||||||
+6
-21
@@ -7,7 +7,7 @@ RUN npm ci
|
|||||||
COPY web/ ./
|
COPY web/ ./
|
||||||
RUN npm run build
|
RUN npm run build
|
||||||
|
|
||||||
FROM golang:1.26-bookworm AS builder
|
FROM golang:1.25-bookworm AS builder
|
||||||
WORKDIR /src
|
WORKDIR /src
|
||||||
COPY go.mod go.sum ./
|
COPY go.mod go.sum ./
|
||||||
RUN go mod download
|
RUN go mod download
|
||||||
@@ -15,32 +15,17 @@ COPY . .
|
|||||||
# Overwrite the committed placeholder with the freshly-built SPA assets.
|
# Overwrite the committed placeholder with the freshly-built SPA assets.
|
||||||
COPY --from=web /web/build ./web/build
|
COPY --from=web /web/build ./web/build
|
||||||
ENV CGO_ENABLED=0
|
ENV CGO_ENABLED=0
|
||||||
# Version stamping. release.yml passes the DERIVED version name
|
# Version stamping: release.yml passes the git tag via MINSTREL_VERSION
|
||||||
# (YYYY.MM.DD.HHMM) and the lane's channel; a local `docker build` falls back
|
# build-arg; local `docker build` falls back to "dev". Surfaced at
|
||||||
# to "dev"/"local". Both are surfaced at /healthz.
|
# /healthz for operator-side image-version verification.
|
||||||
#
|
|
||||||
# These are two values on purpose (family rule 149): the same commit built on
|
|
||||||
# dev and on main reports the same NAME and differs only in CHANNEL. Folding
|
|
||||||
# the channel into the version string is what the rule forbids — the version
|
|
||||||
# used to BE the channel word here ("main"/"dev"), which meant two dev images
|
|
||||||
# eight weeks apart were indistinguishable.
|
|
||||||
ARG MINSTREL_VERSION=dev
|
ARG MINSTREL_VERSION=dev
|
||||||
ARG MINSTREL_CHANNEL=local
|
|
||||||
RUN go build -trimpath \
|
RUN go build -trimpath \
|
||||||
-ldflags="-s -w \
|
-ldflags="-s -w -X 'git.fabledsword.com/bvandeusen/minstrel/internal/server.ServerVersion=${MINSTREL_VERSION}'" \
|
||||||
-X 'git.fabledsword.com/bvandeusen/minstrel/internal/server.ServerVersion=${MINSTREL_VERSION}' \
|
|
||||||
-X 'git.fabledsword.com/bvandeusen/minstrel/internal/server.ServerChannel=${MINSTREL_CHANNEL}'" \
|
|
||||||
-o /out/minstrel ./cmd/minstrel
|
-o /out/minstrel ./cmd/minstrel
|
||||||
|
|
||||||
FROM debian:bookworm-slim
|
FROM debian:bookworm-slim
|
||||||
# ffmpeg: duration probes and the exact-tier audio hash (a SHA-256 of the
|
|
||||||
# encoded audio packets, so no decode). libchromaprint-tools: fpcalc, the
|
|
||||||
# acoustic fingerprint that tells the same recording at two bitrates apart
|
|
||||||
# from two different recordings (M400). Both are baked in at build time so a
|
|
||||||
# deployed instance never fetches either (rule 164); fpcalc is shelled out
|
|
||||||
# rather than bound because CGO_ENABLED=0 above rules out cgo.
|
|
||||||
RUN apt-get update \
|
RUN apt-get update \
|
||||||
&& apt-get install -y --no-install-recommends ca-certificates ffmpeg libchromaprint-tools \
|
&& apt-get install -y --no-install-recommends ca-certificates ffmpeg \
|
||||||
&& rm -rf /var/lib/apt/lists/*
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
RUN groupadd --system --gid 1000 minstrel \
|
RUN groupadd --system --gid 1000 minstrel \
|
||||||
|
|||||||
@@ -37,12 +37,8 @@ services:
|
|||||||
ports: ['4533:4533']
|
ports: ['4533:4533']
|
||||||
volumes:
|
volumes:
|
||||||
# Your music library. Point ./music at wherever your audio files
|
# Your music library. Point ./music at wherever your audio files
|
||||||
# live. Writable, because Minstrel deletes a file when an admin asks
|
# live. Mounted read-only — Minstrel never writes to your library.
|
||||||
# it to (for example, quarantine's "Delete file"). It never moves,
|
- ./music:/music:ro
|
||||||
# renames or retags anything. The container runs as uid 1000, so that
|
|
||||||
# user needs write access to the folders. Mount it :ro to forbid even
|
|
||||||
# deletes: those actions then refuse, say why, and delete nothing.
|
|
||||||
- ./music:/music
|
|
||||||
# Generated data: playlist cover collages, artist art, caches.
|
# Generated data: playlist cover collages, artist art, caches.
|
||||||
# The path must match MINSTREL_STORAGE_DATA_DIR, which the image
|
# The path must match MINSTREL_STORAGE_DATA_DIR, which the image
|
||||||
# sets to /app/data — keep this mount on /app/data or your cache
|
# sets to /app/data — keep this mount on /app/data or your cache
|
||||||
@@ -51,7 +47,7 @@ services:
|
|||||||
environment:
|
environment:
|
||||||
MINSTREL_DATABASE_URL: postgres://minstrel:minstrel@db:5432/minstrel?sslmode=disable
|
MINSTREL_DATABASE_URL: postgres://minstrel:minstrel@db:5432/minstrel?sslmode=disable
|
||||||
# Colon-separated library roots to scan; must match the container
|
# Colon-separated library roots to scan; must match the container
|
||||||
# path of the music mount above (/music here).
|
# path of the read-only music mount above (/music here).
|
||||||
MINSTREL_LIBRARY_SCAN_PATHS: /music
|
MINSTREL_LIBRARY_SCAN_PATHS: /music
|
||||||
depends_on: [db]
|
depends_on: [db]
|
||||||
|
|
||||||
@@ -116,21 +112,11 @@ Most operational keys have a `MINSTREL_<SECTION>_<FIELD>` env override. Recommen
|
|||||||
|
|
||||||
Image tags (`git.fabledsword.com/bvandeusen/minstrel:<tag>`):
|
Image tags (`git.fabledsword.com/bvandeusen/minstrel:<tag>`):
|
||||||
|
|
||||||
- `:latest` — production. Tracks `main`'s tip and moves on every `main` push and every release. What most operators should run.
|
- `:latest` — the newest blessed image. Moves on every `main` push **and** every release. Recommended for most operators.
|
||||||
- `:<commit-sha>` — the rollback unit. Every `main` push publishes one, so any production commit is addressable without a release ceremony. Immutable: a given SHA tag is never re-pushed. Pin one if you need a deployment that cannot change under you, and use it to roll back.
|
- `:vYYYY.MM.DD` — immutable per-day release tags. Pin one of these for a deployment you don't want moving under you. (Per-day CalVer — no trailing patch digit; a same-day re-cut moves the tag forward.)
|
||||||
- `:dev` — the rolling test channel, rebuilt on every push to `dev` and carrying its own freshly-built Android APK. Run this to try something before it ships. It moves constantly, has no per-commit tag, and its only recovery path is forward — if a `:dev` image is broken, the fix is the next push, not a rollback.
|
- `:main` — the rolling post-merge tip. Same image as `:latest` at push time; choose it if you want to track `main` explicitly rather than the release line.
|
||||||
|
|
||||||
That is the whole tag map. **There are no version-numbered image tags**, and no `:main`. Git and the build's own self-reported version answer "which build is this" — the Settings page shows it, and so does `/healthz`. Release *tags* in git are still `vYYYY.MM.DD.HHMM`; they name a changelog entry and the APK attached to it, not an image.
|
Every `:latest` and every `:vYYYY.MM.DD` bundles the current signed Android APK, so the in-app update channel is always live. Database migrations run automatically at startup; rollbacks require restoring a Postgres dump.
|
||||||
|
|
||||||
Rolling back to `:<commit-sha>` pins the **server code** at that commit — not the server-and-app pair. The Android APK is baked in at image build time, so a SHA image carries whichever app was current when that commit was built, which may be older than what `:latest` bundles now. If both halves matter, check what the image bundles rather than trusting the tag's name.
|
|
||||||
|
|
||||||
Every `:latest`, `:<commit-sha>` and `:dev` bundles a signed Android APK, so the in-app update channel is always live. All are signed with the same key, so a phone can move between the stable and dev channels without uninstalling — point it at a `:dev` server and the in-app updater offers that channel's build.
|
|
||||||
|
|
||||||
The app reports which channel it is on alongside its version, and decides whether an update is available using the build's ordering key rather than its displayed name — the same value Android installs by, so an offer it makes is one the platform will accept.
|
|
||||||
|
|
||||||
Database migrations run automatically at startup; rollbacks require restoring a Postgres dump.
|
|
||||||
|
|
||||||
Releases up to 2026-09-10 also published a `:vYYYY.MM.DD[.HHMM]` image tag. Those images still exist and still work — they are simply not extended.
|
|
||||||
|
|
||||||
## Specs
|
## Specs
|
||||||
|
|
||||||
@@ -154,8 +140,7 @@ Two concurrent dev processes:
|
|||||||
truncates your dev `minstrel` data (admin user, library, likes). It
|
truncates your dev `minstrel` data (admin user, library, likes). It
|
||||||
brings up the compose Postgres and creates the test DB if missing.
|
brings up the compose Postgres and creates the test DB if missing.
|
||||||
- CI runs both: a fast `go test -short -race` gate plus an integration
|
- CI runs both: a fast `go test -short -race` gate plus an integration
|
||||||
job with its own ephemeral Postgres (the `integration` lane in
|
job with its own ephemeral Postgres (`.gitea/workflows/test-go.yml`).
|
||||||
`.gitea/workflows/release.yml`, which also gates every image publish).
|
|
||||||
|
|
||||||
### Production build
|
### Production build
|
||||||
|
|
||||||
@@ -165,7 +150,7 @@ Two concurrent dev processes:
|
|||||||
|
|
||||||
- Day-to-day work happens on `dev` (or feature branches merged into `dev`).
|
- Day-to-day work happens on `dev` (or feature branches merged into `dev`).
|
||||||
- `main` is **protected** — changes land via PR from `dev`.
|
- `main` is **protected** — changes land via PR from `dev`.
|
||||||
- Releases are cut by tagging `v*` off `main`; the release workflow builds the signed APK, attaches it to the release, and refreshes `:latest` around it.
|
- Releases are cut by tagging `v*` off `main`; the release workflow builds and pushes the container image to the Gitea registry.
|
||||||
|
|
||||||
Task and milestone tracking: Fable (`Minstrel` project, id 12).
|
Task and milestone tracking: Fable (`Minstrel` project, id 12).
|
||||||
|
|
||||||
|
|||||||
@@ -21,24 +21,13 @@ android {
|
|||||||
applicationId = "com.fabledsword.minstrel"
|
applicationId = "com.fabledsword.minstrel"
|
||||||
minSdk = 26
|
minSdk = 26
|
||||||
targetSdk = 36
|
targetSdk = 36
|
||||||
// versionName / versionCode are released-build values injected by CI.
|
// versionName / versionCode are released-build values injected by
|
||||||
// Local / debug builds fall back to "dev" so the About card reads
|
// CI from the git tag + commit count. Local / debug builds fall
|
||||||
// honestly.
|
// back to "dev" so the About card reads honestly. Releases ship
|
||||||
//
|
// versionName="YYYY.MM.DD.<commits>" (e.g. "2026.06.02.142") and
|
||||||
// versionName is "YYYY.MM.DD.HHMM" from the COMMIT's timestamp, so
|
// versionCode=<commits>, which is monotonic forever and lets the
|
||||||
// every lane building this source reports the same string and the
|
// shared isVersionNewer comparator distinguish two same-day
|
||||||
// channel is the only thing that differs between them.
|
// re-cuts (the iteration suffix differs).
|
||||||
//
|
|
||||||
// versionCode is minutes since 2020-01-01 at BUILD time. It is the
|
|
||||||
// value the platform decides installs by, so it must be monotonic by
|
|
||||||
// construction.
|
|
||||||
//
|
|
||||||
// This comment used to say versionCode was a commit count and that it
|
|
||||||
// was "monotonic forever". It was neither — a commit count runs ahead
|
|
||||||
// on `dev`, so a dev build outranked the `main` release meant to
|
|
||||||
// replace it and Android refused the install as a downgrade. Worth
|
|
||||||
// knowing the claim was here, stated as a reassurance, while the bug
|
|
||||||
// it denied was live.
|
|
||||||
val versionNameOverride =
|
val versionNameOverride =
|
||||||
(project.findProperty("MINSTREL_VERSION_NAME") as String?)?.takeIf { it.isNotBlank() }
|
(project.findProperty("MINSTREL_VERSION_NAME") as String?)?.takeIf { it.isNotBlank() }
|
||||||
val versionCodeOverride =
|
val versionCodeOverride =
|
||||||
|
|||||||
@@ -15,14 +15,10 @@ import androidx.compose.material3.HorizontalDivider
|
|||||||
import androidx.compose.material3.MaterialTheme
|
import androidx.compose.material3.MaterialTheme
|
||||||
import androidx.compose.material3.OutlinedButton
|
import androidx.compose.material3.OutlinedButton
|
||||||
import androidx.compose.material3.Scaffold
|
import androidx.compose.material3.Scaffold
|
||||||
import androidx.compose.material3.SnackbarHost
|
|
||||||
import androidx.compose.material3.SnackbarHostState
|
|
||||||
import androidx.compose.material3.Text
|
import androidx.compose.material3.Text
|
||||||
import androidx.compose.material3.TextButton
|
import androidx.compose.material3.TextButton
|
||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
import androidx.compose.runtime.LaunchedEffect
|
|
||||||
import androidx.compose.runtime.getValue
|
import androidx.compose.runtime.getValue
|
||||||
import androidx.compose.runtime.remember
|
|
||||||
import androidx.compose.ui.Alignment
|
import androidx.compose.ui.Alignment
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
import androidx.compose.ui.text.style.TextOverflow
|
import androidx.compose.ui.text.style.TextOverflow
|
||||||
@@ -46,12 +42,6 @@ fun AdminQuarantineScreen(
|
|||||||
viewModel: AdminQuarantineViewModel = hiltViewModel(),
|
viewModel: AdminQuarantineViewModel = hiltViewModel(),
|
||||||
) {
|
) {
|
||||||
val state by viewModel.uiState.collectAsStateWithLifecycle()
|
val state by viewModel.uiState.collectAsStateWithLifecycle()
|
||||||
val snackbarHostState = remember { SnackbarHostState() }
|
|
||||||
LaunchedEffect(Unit) {
|
|
||||||
viewModel.transientMessages.collect { msg ->
|
|
||||||
snackbarHostState.showSnackbar(msg)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Scaffold(
|
Scaffold(
|
||||||
contentWindowInsets = ShellContentWindowInsets,
|
contentWindowInsets = ShellContentWindowInsets,
|
||||||
modifier = Modifier.fillMaxSize(),
|
modifier = Modifier.fillMaxSize(),
|
||||||
@@ -63,7 +53,6 @@ fun AdminQuarantineScreen(
|
|||||||
onBack = { navController.popBackStack() },
|
onBack = { navController.popBackStack() },
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
snackbarHost = { SnackbarHost(snackbarHostState) },
|
|
||||||
) { inner ->
|
) { inner ->
|
||||||
PullToRefreshScaffold(
|
PullToRefreshScaffold(
|
||||||
onRefresh = { viewModel.refresh().join() },
|
onRefresh = { viewModel.refresh().join() },
|
||||||
|
|||||||
+1
-14
@@ -10,13 +10,10 @@ import com.fabledsword.minstrel.events.EventsStream
|
|||||||
import com.fabledsword.minstrel.models.AdminQuarantineItemRef
|
import com.fabledsword.minstrel.models.AdminQuarantineItemRef
|
||||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||||
import kotlinx.coroutines.Job
|
import kotlinx.coroutines.Job
|
||||||
import kotlinx.coroutines.channels.Channel
|
|
||||||
import kotlinx.coroutines.flow.Flow
|
|
||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
import kotlinx.coroutines.flow.StateFlow
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
import kotlinx.coroutines.flow.asStateFlow
|
import kotlinx.coroutines.flow.asStateFlow
|
||||||
import kotlinx.coroutines.flow.filter
|
import kotlinx.coroutines.flow.filter
|
||||||
import kotlinx.coroutines.flow.receiveAsFlow
|
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
|
|
||||||
@@ -37,15 +34,6 @@ class AdminQuarantineViewModel @Inject constructor(
|
|||||||
private val internal = MutableStateFlow<AdminQuarantineUiState>(AdminQuarantineUiState.Loading)
|
private val internal = MutableStateFlow<AdminQuarantineUiState>(AdminQuarantineUiState.Loading)
|
||||||
val uiState: StateFlow<AdminQuarantineUiState> = internal.asStateFlow()
|
val uiState: StateFlow<AdminQuarantineUiState> = internal.asStateFlow()
|
||||||
|
|
||||||
/**
|
|
||||||
* One-shot messages for the screen's snackbar. A failed action has to say
|
|
||||||
* why: the row quietly reappearing reads as a glitch, and for a Delete
|
|
||||||
* file refused by a read-only library it hides the one thing the
|
|
||||||
* operator can fix (#3918).
|
|
||||||
*/
|
|
||||||
private val transientMessagesChannel = Channel<String>(Channel.BUFFERED)
|
|
||||||
val transientMessages: Flow<String> = transientMessagesChannel.receiveAsFlow()
|
|
||||||
|
|
||||||
init {
|
init {
|
||||||
refresh()
|
refresh()
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
@@ -98,9 +86,8 @@ class AdminQuarantineViewModel @Inject constructor(
|
|||||||
try {
|
try {
|
||||||
action(trackId)
|
action(trackId)
|
||||||
} catch (
|
} catch (
|
||||||
@Suppress("TooGenericExceptionCaught") e: Throwable,
|
@Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable,
|
||||||
) {
|
) {
|
||||||
transientMessagesChannel.trySend(ErrorCopy.fromThrowable(e))
|
|
||||||
refresh()
|
refresh()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -37,35 +37,18 @@ object ErrorCopy {
|
|||||||
* as connection failures.
|
* as connection failures.
|
||||||
*/
|
*/
|
||||||
fun fromThrowable(t: Throwable): String = when (t) {
|
fun fromThrowable(t: Throwable): String = when (t) {
|
||||||
is HttpException -> fromHttp(t)
|
is HttpException -> messageFor(codeFromHttp(t))
|
||||||
is IOException -> messageFor("connection_refused")
|
is IOException -> messageFor("connection_refused")
|
||||||
else -> TABLE.getValue("unknown")
|
else -> TABLE.getValue("unknown")
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
private fun codeFromHttp(e: HttpException): String {
|
||||||
* Codes whose server message carries specifics the operator needs in
|
|
||||||
* order to act — which directory, which uid — that fixed copy cannot say.
|
|
||||||
* For these the message follows the copy (#3918). Kept to a named set on
|
|
||||||
* purpose: most server messages are internal detail. Mirrors web's
|
|
||||||
* errors.ts.
|
|
||||||
*/
|
|
||||||
private val DETAIL_CODES = setOf("library_not_writable", "file_delete_failed")
|
|
||||||
|
|
||||||
private fun fromHttp(e: HttpException): String {
|
|
||||||
val body = bodyFromHttp(e)
|
|
||||||
val copy = messageFor(body.code.ifEmpty { "unknown" })
|
|
||||||
return if (body.code in DETAIL_CODES && body.message.isNotBlank()) {
|
|
||||||
"$copy ${body.message}"
|
|
||||||
} else {
|
|
||||||
copy
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun bodyFromHttp(e: HttpException): Body {
|
|
||||||
val raw = runCatching { e.response()?.errorBody()?.string() }.getOrNull()
|
val raw = runCatching { e.response()?.errorBody()?.string() }.getOrNull()
|
||||||
?: return Body()
|
?: return "unknown"
|
||||||
return runCatching { json.decodeFromString<Envelope>(raw).error }
|
val code = runCatching { json.decodeFromString<Envelope>(raw).error?.code }
|
||||||
.getOrNull() ?: Body()
|
.getOrNull()
|
||||||
|
.orEmpty()
|
||||||
|
return code.ifEmpty { "unknown" }
|
||||||
}
|
}
|
||||||
|
|
||||||
private val TABLE: Map<String, String> = mapOf(
|
private val TABLE: Map<String, String> = mapOf(
|
||||||
@@ -75,7 +58,6 @@ object ErrorCopy {
|
|||||||
"forbidden" to "You don't have permission to do that.",
|
"forbidden" to "You don't have permission to do that.",
|
||||||
"not_authorized" to "You don't have permission to do that.",
|
"not_authorized" to "You don't have permission to do that.",
|
||||||
"invalid_credentials" to "Wrong username or password.",
|
"invalid_credentials" to "Wrong username or password.",
|
||||||
"rate_limited" to "Too many attempts. Wait a few minutes and try again.",
|
|
||||||
"wrong_password" to "Current password is incorrect.",
|
"wrong_password" to "Current password is incorrect.",
|
||||||
"password_too_short" to "Password must be at least 8 characters.",
|
"password_too_short" to "Password must be at least 8 characters.",
|
||||||
"username_invalid" to "That username isn't valid.",
|
"username_invalid" to "That username isn't valid.",
|
||||||
@@ -117,8 +99,6 @@ object ErrorCopy {
|
|||||||
"request_not_pending" to "This request is no longer pending.",
|
"request_not_pending" to "This request is no longer pending.",
|
||||||
"request_not_found" to "That request no longer exists.",
|
"request_not_found" to "That request no longer exists.",
|
||||||
"track_not_found" to "That track no longer exists.",
|
"track_not_found" to "That track no longer exists.",
|
||||||
"library_not_writable" to "The music library isn't writable by the server.",
|
|
||||||
"file_delete_failed" to "The file couldn't be deleted.",
|
|
||||||
"album_not_found" to "That album no longer exists.",
|
"album_not_found" to "That album no longer exists.",
|
||||||
"artist_not_found" to "That artist no longer exists.",
|
"artist_not_found" to "That artist no longer exists.",
|
||||||
"playlist_not_found" to "That playlist no longer exists.",
|
"playlist_not_found" to "That playlist no longer exists.",
|
||||||
|
|||||||
@@ -1,26 +1,15 @@
|
|||||||
package com.fabledsword.minstrel.models
|
package com.fabledsword.minstrel.models
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The server-bundled APK, as reported by `GET /api/client/version`.
|
* Wire shape returned by `GET /api/client/version`. Mirrors
|
||||||
|
* the Flutter client's `UpdateInfo`.
|
||||||
*
|
*
|
||||||
* Three values that are deliberately kept apart:
|
* `version` is the server-bundled APK version (may have a leading
|
||||||
*
|
* "v" from the git tag); `apkUrl` is server-relative (e.g.
|
||||||
* - [version] is a LABEL for people — "YYYY.MM.DD.HHMM", derived from the
|
* `/api/client/apk`); `sizeBytes` is the download size.
|
||||||
* build's commit, so two channels carrying the same code read the same.
|
|
||||||
* Display this; never decide on it when [code] is present.
|
|
||||||
* - [code] is the ORDERING KEY, and is the same value Android itself
|
|
||||||
* installs by. It answers "may this be installed over that?", which the
|
|
||||||
* name cannot. Null when the server predates the field.
|
|
||||||
* - [channel] is a SIBLING FIELD, never a suffix inside the name. Reported
|
|
||||||
* verbatim rather than validated, so an unexpected value is shown rather
|
|
||||||
* than dropped.
|
|
||||||
*
|
|
||||||
* [apkUrl] is server-relative (e.g. `/api/client/apk`).
|
|
||||||
*/
|
*/
|
||||||
data class UpdateInfo(
|
data class UpdateInfo(
|
||||||
val version: String,
|
val version: String,
|
||||||
val code: Long?,
|
|
||||||
val channel: String?,
|
|
||||||
val apkUrl: String,
|
val apkUrl: String,
|
||||||
val sizeBytes: Long,
|
val sizeBytes: Long,
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -4,26 +4,12 @@ import kotlinx.serialization.SerialName
|
|||||||
import kotlinx.serialization.Serializable
|
import kotlinx.serialization.Serializable
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Wire shape for `GET /api/client/version`.
|
* Wire shape for `GET /api/client/version`. Defaults match Flutter:
|
||||||
*
|
* apk_url falls back to `/api/client/apk` if the server omits it.
|
||||||
* `apkUrl` falls back to `/api/client/apk` if the server omits it.
|
|
||||||
*
|
|
||||||
* [code] MUST stay nullable, and this is not a style preference. The app's
|
|
||||||
* Json is configured with `coerceInputValues = true`, which replaces a JSON
|
|
||||||
* null with the declared default for a NON-nullable property — so writing
|
|
||||||
* `val code: Long = 0` would turn "this server reports no ordering key" into
|
|
||||||
* "this build's ordering key is 0", silently, with no error anywhere. A
|
|
||||||
* nullable type is what keeps absent distinguishable from zero, and the
|
|
||||||
* distinction is the whole reason the field exists.
|
|
||||||
*
|
|
||||||
* A server predating the ordering key sends neither [code] nor [channel];
|
|
||||||
* both arrive null and the caller falls back to comparing names.
|
|
||||||
*/
|
*/
|
||||||
@Serializable
|
@Serializable
|
||||||
data class UpdateInfoWire(
|
data class UpdateInfoWire(
|
||||||
val version: String = "",
|
val version: String = "",
|
||||||
val code: Long? = null,
|
|
||||||
val channel: String? = null,
|
|
||||||
@SerialName("apk_url") val apkUrl: String = "/api/client/apk",
|
@SerialName("apk_url") val apkUrl: String = "/api/client/apk",
|
||||||
@SerialName("size_bytes") val sizeBytes: Long = 0,
|
@SerialName("size_bytes") val sizeBytes: Long = 0,
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -109,11 +109,8 @@ private fun MiniCover(coverUrl: String, contentDescription: String) {
|
|||||||
* NowPlayingScreen via [onExpandClick].
|
* NowPlayingScreen via [onExpandClick].
|
||||||
*
|
*
|
||||||
* Layout (Column):
|
* Layout (Column):
|
||||||
* - Slim seek slider pinned at the top (4dp track)
|
* - Slim seek slider at the top (4dp track)
|
||||||
* - Row: cover | title/artist column | like | prev | play/pause | next.
|
* - Row: cover | title/artist column | like | prev | play/pause | next
|
||||||
* Weighted so it fills the rest of the fixed-height bar and centres its
|
|
||||||
* own content; otherwise the row keeps its intrinsic 48dp and the
|
|
||||||
* leftover height collects at the bottom as dead surface.
|
|
||||||
*
|
*
|
||||||
* No kebab on the mini bar (operator 2026-06-01): the full kebab
|
* No kebab on the mini bar (operator 2026-06-01): the full kebab
|
||||||
* surface lives on NowPlayingScreen, and dropping it from the mini
|
* surface lives on NowPlayingScreen, and dropping it from the mini
|
||||||
@@ -167,12 +164,6 @@ fun MiniPlayer(
|
|||||||
durationMs = state.durationMs,
|
durationMs = state.durationMs,
|
||||||
)
|
)
|
||||||
MiniRow(
|
MiniRow(
|
||||||
// Take whatever the progress fill leaves. Without this the
|
|
||||||
// Column stacks 4dp + the row's intrinsic 48dp from the top
|
|
||||||
// and the remaining 28dp of an 80dp bar sits empty
|
|
||||||
// underneath — the content looked top-aligned rather than
|
|
||||||
// centred, with a dead strip above the gesture bar.
|
|
||||||
modifier = Modifier.weight(1f),
|
|
||||||
track = track,
|
track = track,
|
||||||
isPlaying = state.isPlaying,
|
isPlaying = state.isPlaying,
|
||||||
isUpnpLoading = state.isUpnpLoading,
|
isUpnpLoading = state.isUpnpLoading,
|
||||||
@@ -214,7 +205,6 @@ private fun MiniProgressFill(positionMs: Long, durationMs: Long) {
|
|||||||
@Composable
|
@Composable
|
||||||
@Suppress("LongParameterList")
|
@Suppress("LongParameterList")
|
||||||
private fun MiniRow(
|
private fun MiniRow(
|
||||||
modifier: Modifier,
|
|
||||||
track: TrackRef,
|
track: TrackRef,
|
||||||
isPlaying: Boolean,
|
isPlaying: Boolean,
|
||||||
isUpnpLoading: Boolean,
|
isUpnpLoading: Boolean,
|
||||||
@@ -226,7 +216,7 @@ private fun MiniRow(
|
|||||||
onToggleLike: () -> Unit,
|
onToggleLike: () -> Unit,
|
||||||
) {
|
) {
|
||||||
Row(
|
Row(
|
||||||
modifier = modifier
|
modifier = Modifier
|
||||||
.fillMaxWidth()
|
.fillMaxWidth()
|
||||||
.padding(horizontal = 12.dp),
|
.padding(horizontal = 12.dp),
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
|||||||
+4
-17
@@ -9,7 +9,7 @@ import com.fabledsword.minstrel.update.data.ApkInstaller
|
|||||||
import com.fabledsword.minstrel.update.data.InstallStage
|
import com.fabledsword.minstrel.update.data.InstallStage
|
||||||
import com.fabledsword.minstrel.update.data.UpdateRepository
|
import com.fabledsword.minstrel.update.data.UpdateRepository
|
||||||
import com.fabledsword.minstrel.update.data.isBusy
|
import com.fabledsword.minstrel.update.data.isBusy
|
||||||
import com.fabledsword.minstrel.update.data.isUpdateAvailable
|
import com.fabledsword.minstrel.update.data.isVersionNewer
|
||||||
import com.fabledsword.minstrel.update.data.message
|
import com.fabledsword.minstrel.update.data.message
|
||||||
import com.fabledsword.minstrel.update.data.stage
|
import com.fabledsword.minstrel.update.data.stage
|
||||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||||
@@ -37,10 +37,6 @@ sealed interface UpdateCheckResult {
|
|||||||
|
|
||||||
data class AboutUiState(
|
data class AboutUiState(
|
||||||
val installedVersion: String = BuildConfig.VERSION_NAME,
|
val installedVersion: String = BuildConfig.VERSION_NAME,
|
||||||
// The value the platform installs by, and therefore the one the update
|
|
||||||
// check must decide on. Held in state rather than read inline so a test
|
|
||||||
// can drive the comparison without a BuildConfig.
|
|
||||||
val installedCode: Long = BuildConfig.VERSION_CODE.toLong(),
|
|
||||||
val isChecking: Boolean = false,
|
val isChecking: Boolean = false,
|
||||||
val installStage: InstallStage = InstallStage.IDLE,
|
val installStage: InstallStage = InstallStage.IDLE,
|
||||||
val installMessage: String? = null,
|
val installMessage: String? = null,
|
||||||
@@ -49,9 +45,8 @@ data class AboutUiState(
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Backs the About card's update controls. "Check for updates" calls
|
* Backs the About card's update controls. "Check for updates" calls
|
||||||
* [UpdateRepository.getLatest], compares versus this build via
|
* [UpdateRepository.getLatest], compares versus the build's
|
||||||
* [isUpdateAvailable] — on the ordering key where the server reports one,
|
* VERSION_NAME via [isVersionNewer], and reports the terminal state.
|
||||||
* on the name otherwise — and reports the terminal state.
|
|
||||||
* When an update is available, [install] downloads the APK via
|
* When an update is available, [install] downloads the APK via
|
||||||
* [ApkInstaller] and installs it — routing the user to the "install
|
* [ApkInstaller] and installs it — routing the user to the "install
|
||||||
* unknown apps" settings page first when that permission hasn't been
|
* unknown apps" settings page first when that permission hasn't been
|
||||||
@@ -71,17 +66,9 @@ class AboutCardViewModel @Inject constructor(
|
|||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
internal.update { it.copy(isChecking = true, installMessage = null) }
|
internal.update { it.copy(isChecking = true, installMessage = null) }
|
||||||
val installed = internal.value.installedVersion
|
val installed = internal.value.installedVersion
|
||||||
val installedCode = internal.value.installedCode
|
|
||||||
val result = runCatching { repository.getLatest() }
|
val result = runCatching { repository.getLatest() }
|
||||||
.map { latest ->
|
.map { latest ->
|
||||||
if (
|
if (isVersionNewer(latest.version, installed)) {
|
||||||
isUpdateAvailable(
|
|
||||||
serverCode = latest.code,
|
|
||||||
serverName = latest.version,
|
|
||||||
installedCode = installedCode,
|
|
||||||
installedName = installed,
|
|
||||||
)
|
|
||||||
) {
|
|
||||||
UpdateCheckResult.UpdateAvailable(latest)
|
UpdateCheckResult.UpdateAvailable(latest)
|
||||||
} else {
|
} else {
|
||||||
UpdateCheckResult.Latest
|
UpdateCheckResult.Latest
|
||||||
|
|||||||
@@ -57,7 +57,7 @@ class PasswordViewModel @Inject constructor(
|
|||||||
try {
|
try {
|
||||||
repository.changePassword(current = s.current, next = s.next)
|
repository.changePassword(current = s.current, next = s.next)
|
||||||
internal.update {
|
internal.update {
|
||||||
PasswordUiState(message = "Password changed. Your other devices have been signed out.")
|
PasswordUiState(message = "Password changed.")
|
||||||
}
|
}
|
||||||
} catch (
|
} catch (
|
||||||
@Suppress("TooGenericExceptionCaught") e: Throwable,
|
@Suppress("TooGenericExceptionCaught") e: Throwable,
|
||||||
|
|||||||
+2
-10
@@ -19,8 +19,7 @@ private const val POLL_INTERVAL_MS = 24 * 60 * 60 * 1000L
|
|||||||
/**
|
/**
|
||||||
* Drives the shell's soft "update available" banner. Polls
|
* Drives the shell's soft "update available" banner. Polls
|
||||||
* `/api/client/version` at launch + every 24h and, when the bundled
|
* `/api/client/version` at launch + every 24h and, when the bundled
|
||||||
* APK outranks this build — by ordering key where the server reports one,
|
* APK is strictly newer than this build, exposes its [UpdateInfo] so
|
||||||
* by name otherwise — exposes its [UpdateInfo] so
|
|
||||||
* [com.fabledsword.minstrel.update.ui.UpdateBanner] can nudge an
|
* [com.fabledsword.minstrel.update.ui.UpdateBanner] can nudge an
|
||||||
* install. Mirrors Flutter's `ClientUpdateController`.
|
* install. Mirrors Flutter's `ClientUpdateController`.
|
||||||
*
|
*
|
||||||
@@ -59,13 +58,6 @@ class UpdateBannerController @Inject constructor(
|
|||||||
|
|
||||||
private suspend fun runOnce() {
|
private suspend fun runOnce() {
|
||||||
val info = runCatching { repository.getLatest() }.getOrNull() ?: return
|
val info = runCatching { repository.getLatest() }.getOrNull() ?: return
|
||||||
latest.value = info.takeIf {
|
latest.value = info.takeIf { isVersionNewer(it.version, BuildConfig.VERSION_NAME) }
|
||||||
isUpdateAvailable(
|
|
||||||
serverCode = it.code,
|
|
||||||
serverName = it.version,
|
|
||||||
installedCode = BuildConfig.VERSION_CODE.toLong(),
|
|
||||||
installedName = BuildConfig.VERSION_NAME,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -21,39 +21,10 @@ class UpdateRepository @Inject constructor(retrofit: Retrofit) {
|
|||||||
|
|
||||||
private fun UpdateInfoWire.toDomain(): UpdateInfo = UpdateInfo(
|
private fun UpdateInfoWire.toDomain(): UpdateInfo = UpdateInfo(
|
||||||
version = version,
|
version = version,
|
||||||
code = code,
|
|
||||||
channel = channel,
|
|
||||||
apkUrl = apkUrl,
|
apkUrl = apkUrl,
|
||||||
sizeBytes = sizeBytes,
|
sizeBytes = sizeBytes,
|
||||||
)
|
)
|
||||||
|
|
||||||
/**
|
|
||||||
* True when [server] should be offered over the installed build.
|
|
||||||
*
|
|
||||||
* **Decide on the ordering key whenever the server sends one.** That is the
|
|
||||||
* same value Android's package installer compares, so an offer made this way
|
|
||||||
* implies an install the platform will actually accept. The app used to
|
|
||||||
* compare NAMES while the platform installed by `versionCode`, with nothing
|
|
||||||
* keeping the two orderings consistent — so it could offer a build Android
|
|
||||||
* then refused as a downgrade, or stay quiet about one it would have taken.
|
|
||||||
*
|
|
||||||
* Name comparison survives only as the fallback for a server that predates
|
|
||||||
* the field. A null code means "this server cannot tell me" — never "zero" —
|
|
||||||
* because treating absent as zero would rank every such server as infinitely
|
|
||||||
* old and offer its build to everyone, forever.
|
|
||||||
*/
|
|
||||||
fun isUpdateAvailable(
|
|
||||||
serverCode: Long?,
|
|
||||||
serverName: String,
|
|
||||||
installedCode: Long,
|
|
||||||
installedName: String,
|
|
||||||
): Boolean =
|
|
||||||
if (serverCode != null) {
|
|
||||||
serverCode > installedCode
|
|
||||||
} else {
|
|
||||||
isVersionNewer(serverName, installedName)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* True when [server] is strictly newer than [installed]. Mirrors
|
* True when [server] is strictly newer than [installed]. Mirrors
|
||||||
* Flutter's `isVersionNewer` — splits both strings on `.`, parses
|
* Flutter's `isVersionNewer` — splits both strings on `.`, parses
|
||||||
|
|||||||
@@ -1,60 +0,0 @@
|
|||||||
package com.fabledsword.minstrel.api
|
|
||||||
|
|
||||||
import okhttp3.MediaType.Companion.toMediaType
|
|
||||||
import okhttp3.ResponseBody.Companion.toResponseBody
|
|
||||||
import org.junit.jupiter.api.Assertions.assertEquals
|
|
||||||
import org.junit.jupiter.api.Test
|
|
||||||
import retrofit2.HttpException
|
|
||||||
import retrofit2.Response
|
|
||||||
import java.io.IOException
|
|
||||||
|
|
||||||
class ErrorCopyTest {
|
|
||||||
private fun httpError(status: Int, body: String): HttpException =
|
|
||||||
HttpException(
|
|
||||||
Response.error<Unit>(status, body.toResponseBody("application/json".toMediaType())),
|
|
||||||
)
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun libraryNotWritableAppendsTheServerDetail() {
|
|
||||||
val detail = "Minstrel runs as uid 1000, gid 1000 and cannot delete from /music/A " +
|
|
||||||
"(read-only file system). The library mount must be writable by that user. " +
|
|
||||||
"Nothing was deleted."
|
|
||||||
val e = httpError(409, """{"error":{"code":"library_not_writable","message":"$detail"}}""")
|
|
||||||
|
|
||||||
assertEquals(
|
|
||||||
"${ErrorCopy.messageFor("library_not_writable")} $detail",
|
|
||||||
ErrorCopy.fromThrowable(e),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun detailCodeWithoutAMessageShowsTheCopyAlone() {
|
|
||||||
val e = httpError(409, """{"error":{"code":"library_not_writable","message":""}}""")
|
|
||||||
|
|
||||||
assertEquals(ErrorCopy.messageFor("library_not_writable"), ErrorCopy.fromThrowable(e))
|
|
||||||
}
|
|
||||||
|
|
||||||
// Server messages are usually internal detail; appending them for every
|
|
||||||
// code would leak driver errors into snackbars. This pins the scope.
|
|
||||||
@Test
|
|
||||||
fun otherCodesNeverCarryTheServerMessage() {
|
|
||||||
val e = httpError(404, """{"error":{"code":"track_not_found","message":"pgx: no rows"}}""")
|
|
||||||
|
|
||||||
assertEquals(ErrorCopy.messageFor("track_not_found"), ErrorCopy.fromThrowable(e))
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun anUnparseableBodyFallsBackToUnknown() {
|
|
||||||
val e = httpError(500, "not json")
|
|
||||||
|
|
||||||
assertEquals(ErrorCopy.messageFor("unknown"), ErrorCopy.fromThrowable(e))
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun transportFailureMapsToConnectionRefused() {
|
|
||||||
assertEquals(
|
|
||||||
ErrorCopy.messageFor("connection_refused"),
|
|
||||||
ErrorCopy.fromThrowable(IOException("refused")),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-163
@@ -1,163 +0,0 @@
|
|||||||
package com.fabledsword.minstrel.update.data
|
|
||||||
|
|
||||||
import org.junit.jupiter.api.Test
|
|
||||||
import kotlin.test.assertFalse
|
|
||||||
import kotlin.test.assertTrue
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The update channel had no tests at all before this. That is worth saying
|
|
||||||
* out loud, because the thing it decides — whether anyone is ever offered an
|
|
||||||
* update — fails silently in both directions: an update nobody is offered
|
|
||||||
* looks exactly like being up to date, and nobody files a bug about a prompt
|
|
||||||
* they never saw.
|
|
||||||
*/
|
|
||||||
class UpdateVersioningTest {
|
|
||||||
@Test
|
|
||||||
fun `decides on the ordering key when the server reports one`() {
|
|
||||||
assertTrue(
|
|
||||||
isUpdateAvailable(
|
|
||||||
serverCode = 3523847, serverName = "2026.09.10.1432",
|
|
||||||
installedCode = 3519456, installedName = "2026.09.09.1828",
|
|
||||||
),
|
|
||||||
)
|
|
||||||
assertFalse(
|
|
||||||
isUpdateAvailable(
|
|
||||||
serverCode = 3519456, serverName = "2026.09.09.1828",
|
|
||||||
installedCode = 3523847, installedName = "2026.09.10.1432",
|
|
||||||
),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun `an equal ordering key is not an update`() {
|
|
||||||
assertFalse(
|
|
||||||
isUpdateAvailable(
|
|
||||||
serverCode = 3523847, serverName = "2026.09.10.1432",
|
|
||||||
installedCode = 3523847, installedName = "2026.09.10.1432",
|
|
||||||
),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The property the whole rework exists for: the offer must agree with what
|
|
||||||
* the platform will actually install. Where the two disagree, the ordering
|
|
||||||
* key wins, because that is the value Android compares.
|
|
||||||
*/
|
|
||||||
@Test
|
|
||||||
fun `the ordering key wins even when the name disagrees`() {
|
|
||||||
// Name looks older, key is newer — e.g. an older commit rebuilt later.
|
|
||||||
assertTrue(
|
|
||||||
isUpdateAvailable(
|
|
||||||
serverCode = 9_000_000, serverName = "2020.01.01.0000",
|
|
||||||
installedCode = 1, installedName = "2099.12.31.2359",
|
|
||||||
),
|
|
||||||
)
|
|
||||||
// Name looks newer, key is not. Offering this would be offering an
|
|
||||||
// install the platform then refuses as a downgrade.
|
|
||||||
assertFalse(
|
|
||||||
isUpdateAvailable(
|
|
||||||
serverCode = 1, serverName = "2099.12.31.2359",
|
|
||||||
installedCode = 9_000_000, installedName = "2020.01.01.0000",
|
|
||||||
),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun `falls back to the name when the server reports no ordering key`() {
|
|
||||||
assertTrue(
|
|
||||||
isUpdateAvailable(
|
|
||||||
serverCode = null, serverName = "2026.09.10.1432",
|
|
||||||
installedCode = 3519456, installedName = "2026.09.09.1828",
|
|
||||||
),
|
|
||||||
)
|
|
||||||
assertFalse(
|
|
||||||
isUpdateAvailable(
|
|
||||||
serverCode = null, serverName = "2026.09.09.1828",
|
|
||||||
installedCode = 3519456, installedName = "2026.09.10.1432",
|
|
||||||
),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* A null code must never be read as zero. Zero would rank every
|
|
||||||
* older server as infinitely behind and offer its build to everyone,
|
|
||||||
* forever — so this asserts the fallback runs instead of a comparison
|
|
||||||
* against 0 succeeding by accident.
|
|
||||||
*/
|
|
||||||
@Test
|
|
||||||
fun `a null ordering key is absent, not zero`() {
|
|
||||||
// installedCode is 0 here: if null coerced to 0, "0 > 0" would be
|
|
||||||
// false and this would wrongly report no update despite a newer name.
|
|
||||||
assertTrue(
|
|
||||||
isUpdateAvailable(
|
|
||||||
serverCode = null, serverName = "2026.09.10.1432",
|
|
||||||
installedCode = 0, installedName = "2026.09.09.1828",
|
|
||||||
),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The recorded migration constraint, pinned so it cannot be forgotten:
|
|
||||||
* the old scheme's fourth segment was a commit count (~1895), the new
|
|
||||||
* one is HHMM. Across a day boundary the date decides and all is well.
|
|
||||||
*/
|
|
||||||
@Test
|
|
||||||
fun `new-scheme name outranks an old-scheme name on a later day`() {
|
|
||||||
assertTrue(isVersionNewer("2026.09.10.1432", "2026.09.09.1895"))
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* ...but on the SAME day the comparison comes down to HHMM against a
|
|
||||||
* commit count, and any build before ~19:00 UTC reads as older. This is
|
|
||||||
* why the first new-scheme release had to be cut on a later calendar day.
|
|
||||||
* Asserting the trap so nobody "fixes" it by accident.
|
|
||||||
*/
|
|
||||||
@Test
|
|
||||||
fun `same-day new-scheme name can read older than an old-scheme name`() {
|
|
||||||
assertFalse(isVersionNewer("2026.09.09.1828", "2026.09.09.1895"))
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun `name comparison degrades per segment rather than discarding`() {
|
|
||||||
// The string is still compared rather than rejected outright: an
|
|
||||||
// earlier segment decides and the unparseable tail never matters.
|
|
||||||
assertTrue(isVersionNewer("2026.09.10.1432-dev", "2026.09.09.1828"))
|
|
||||||
|
|
||||||
// A shorter name pads with zeros instead of being refused.
|
|
||||||
assertTrue(isVersionNewer("2026.09.10", "2026.09.09.9999"))
|
|
||||||
assertFalse(isVersionNewer("2026.09.10", "2026.09.10.0"))
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* What "costs that segment's precision" actually means, and it is worth
|
|
||||||
* pinning because it is a real edge rather than a nicety: when the
|
|
||||||
* unparseable segment is the DECIDING one, it reads as 0 and loses. So a
|
|
||||||
* `-dev` suffixed build compares as older than an unsuffixed one from the
|
|
||||||
* same minute.
|
|
||||||
*
|
|
||||||
* That is the correct behaviour for a degrading parser — it is bounded
|
|
||||||
* loss rather than a discarded string — but it is exactly why the channel
|
|
||||||
* belongs in its own field and never in the name.
|
|
||||||
*/
|
|
||||||
@Test
|
|
||||||
fun `an unparseable deciding segment reads as zero and loses`() {
|
|
||||||
assertFalse(isVersionNewer("2026.09.10.1432-dev", "2026.09.10.1000"))
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Both sides unparseable (branch-name builds) falls back to string
|
|
||||||
* inequality, so a dev build still surfaces rather than comparing equal
|
|
||||||
* and going silent.
|
|
||||||
*/
|
|
||||||
@Test
|
|
||||||
fun `two unparseable names fall back to string inequality`() {
|
|
||||||
assertTrue(isVersionNewer("main", "dev"))
|
|
||||||
assertFalse(isVersionNewer("dev", "dev"))
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun `a leading v is ignored on either side`() {
|
|
||||||
assertTrue(isVersionNewer("v2026.09.10.1432", "2026.09.09.1828"))
|
|
||||||
assertFalse(isVersionNewer("v2026.09.10.1432", "v2026.09.10.1432"))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Executable
BIN
Binary file not shown.
+55
-29
@@ -12,9 +12,8 @@ git.fabledsword.com/bvandeusen/ci-go:1.26
|
|||||||
git.fabledsword.com/bvandeusen/ci-android:36
|
git.fabledsword.com/bvandeusen/ci-android:36
|
||||||
```
|
```
|
||||||
|
|
||||||
- `ci-go:1.26` — the `go`, `integration` and `web` lanes, `release-assets`, and the container build (`image-release`). All CI lives in one workflow, `.gitea/workflows/release.yml`, so every publishing job can depend on every lane (rule 177).
|
- `ci-go:1.26` — Go server tests (`.gitea/workflows/test-go.yml`), web SPA tests (`.gitea/workflows/test-web.yml`), and the release container build (`release.yml`'s `image-release` job).
|
||||||
- `golang:1.26-bookworm` (Docker Hub) — the `govulncheck` lane. Deliberately the same image as the Dockerfile's builder stage rather than `ci-go`, so the standard library it checks is the one in the shipped binary. Keep the two in step.
|
- `ci-android:36` — native Kotlin/Compose client: ktlint + detekt + unit tests + debug APK (`.gitea/workflows/android.yml`), and the signed release APK (`release.yml`'s `android-release` job).
|
||||||
- `ci-android:36` — native Kotlin/Compose client: ktlint + detekt + unit tests + debug APK (the `android` lane), and the signed release APK (`android-release`).
|
|
||||||
|
|
||||||
**`ci-flutter` is no longer consumed, and `ci-flutter` can now be retired.**
|
**`ci-flutter` is no longer consumed, and `ci-flutter` can now be retired.**
|
||||||
The M8 rewrite replaced the Flutter client with the native Android app and
|
The M8 rewrite replaced the Flutter client with the native Android app and
|
||||||
@@ -31,9 +30,9 @@ split below. The label is a scheduling handle, not a toolchain assertion.
|
|||||||
|
|
||||||
### From `ci-go:1.26`
|
### From `ci-go:1.26`
|
||||||
- **Go** (1.26 toolchain) — `go vet`, `go test -race`, `go build`, `go mod`.
|
- **Go** (1.26 toolchain) — `go vet`, `go test -race`, `go build`, `go mod`.
|
||||||
- **Node + npm** — `npm ci`, `npm audit`, `npm test` and `npm run check` in the `web` lane.
|
- **Node + npm** — `npm ci` and `npm test` / `npm run check` in `test-web.yml`.
|
||||||
- **golangci-lint** — lint pass in the `go` lane.
|
- **golangci-lint** — lint pass in `test-go.yml`.
|
||||||
- **docker CLI** — bridge-IP discovery of the per-job Postgres service container in the `integration` lane (via the runner's shared `/var/run/docker.sock`).
|
- **docker CLI** — bridge-IP discovery of the per-job Postgres service container in `test-go.yml` integration job (via the runner's shared `/var/run/docker.sock`).
|
||||||
- **docker buildx** — release container build + push in `release.yml`.
|
- **docker buildx** — release container build + push in `release.yml`.
|
||||||
- **curl** — release-asset polling / upload in `release.yml`.
|
- **curl** — release-asset polling / upload in `release.yml`.
|
||||||
|
|
||||||
@@ -46,7 +45,7 @@ split below. The label is a scheduling handle, not a toolchain assertion.
|
|||||||
No NDK: the native client has no C/C++ sources (this is why it isn't on
|
No NDK: the native client has no C/C++ sources (this is why it isn't on
|
||||||
`ci-flutter`).
|
`ci-flutter`).
|
||||||
- **ktlint + detekt** — `./gradlew ktlintCheck` and `./gradlew detekt` in
|
- **ktlint + detekt** — `./gradlew ktlintCheck` and `./gradlew detekt` in
|
||||||
the `android` lane. Image pins track `android/gradle/libs.versions.toml` so local
|
`android.yml`. Image pins track `android/gradle/libs.versions.toml` so local
|
||||||
and CI checks agree.
|
and CI checks agree.
|
||||||
- **git** — `actions/checkout@v4` baseline (and any shell git operations).
|
- **git** — `actions/checkout@v4` baseline (and any shell git operations).
|
||||||
- **base64 + curl** — keystore decode + release-asset upload in `release.yml`'s
|
- **base64 + curl** — keystore decode + release-asset upload in `release.yml`'s
|
||||||
@@ -59,34 +58,61 @@ None.
|
|||||||
## Notes
|
## Notes
|
||||||
|
|
||||||
- **Label/image split.** Workflows keep `runs-on: go-ci` / `runs-on: flutter-ci` as the scheduling label per the [`ci-runners.md`](https://…/FabledRulebook/ci-runners.md) "label = scheduling handle, image = `container.image`" pattern. The labels are intentional handles, not toolchain assertions — which is why the Android jobs still schedule on `flutter-ci` while pulling `ci-android:36`. Switch them to `android-ci` if that runner label is ever registered; nothing breaks either way.
|
- **Label/image split.** Workflows keep `runs-on: go-ci` / `runs-on: flutter-ci` as the scheduling label per the [`ci-runners.md`](https://…/FabledRulebook/ci-runners.md) "label = scheduling handle, image = `container.image`" pattern. The labels are intentional handles, not toolchain assertions — which is why the Android jobs still schedule on `flutter-ci` while pulling `ci-android:36`. Switch them to `android-ci` if that runner label is ever registered; nothing breaks either way.
|
||||||
- **Integration-job docker-socket dependency.** The `integration` lane uses the runner's shared docker socket (`/var/run/docker.sock`) to bridge-IP-discover the per-job Postgres service container by name + network intersection — the dev compose's `minstrel-postgres-*` containers are explicitly skipped as belt-and-suspenders. Depends on `act_runner.valid_volumes` whitelisting the socket; if that ever stops auto-mounting, integration tests fail at the `docker inspect` step.
|
- **Integration-job docker-socket dependency.** `test-go.yml`'s integration job uses the runner's shared docker socket (`/var/run/docker.sock`) to bridge-IP-discover the per-job Postgres service container by name + network intersection — the dev compose's `minstrel-postgres-*` containers are explicitly skipped as belt-and-suspenders. Depends on `act_runner.valid_volumes` whitelisting the socket; if that ever stops auto-mounting, integration tests fail at the `docker inspect` step.
|
||||||
- **Go toolchain pin.** `go.mod` is on `go 1.25.0` because `golang.org/x/crypto v0.51.0` declares 1.25 as its minimum. `ci-go:1.26` satisfies this with headroom. Future `x/crypto` bumps that move the Go floor should be paired with an image-tag bump in this file + the workflows.
|
- **Go toolchain pin.** `go.mod` is on `go 1.25.0` because `golang.org/x/crypto v0.51.0` declares 1.25 as its minimum. `ci-go:1.26` satisfies this with headroom. Future `x/crypto` bumps that move the Go floor should be paired with an image-tag bump in this file + the workflows.
|
||||||
- **In-app update channel — `needs:`, not polling.** `release.yml`'s `image-release` job declares `needs: [android-release]`, so on tag pushes the signed APK is guaranteed present before the image build starts — no polling window, no race. (The old cross-workflow polling against `flutter.yml` is gone with that workflow.) On non-tag `main` pushes `android-release` is skipped and `image-release` instead pulls the most recent release's APK and reconstructs its exact `versionName`, so `:latest` never ships without an update channel. It degrades to an empty `client/` — never a wrong version — if no release, asset, or tag commit-count can be resolved.
|
- **In-app update channel — `needs:`, not polling.** `release.yml`'s `image-release` job declares `needs: [android-release]`, so on tag pushes the signed APK is guaranteed present before the image build starts — no polling window, no race. (The old cross-workflow polling against `flutter.yml` is gone with that workflow.) On non-tag `main` pushes `android-release` is skipped and `image-release` instead pulls the most recent release's APK and reconstructs its exact `versionName`, so `:latest` never ships without an update channel. It degrades to an empty `client/` — never a wrong version — if no release, asset, or tag commit-count can be resolved.
|
||||||
- **Cache server reachability.** The `web` lane does NOT use `cache: 'npm'` on `actions/setup-node` — the Gitea Actions cache server isn't reachable from this runner's container network and `setup-node` was burning ~4m41s on ETIMEDOUT before failing open. With the migration to `ci-go:1.26`, `setup-node` is removed entirely (Node is in the image). The cache concern reappears if a future change re-introduces a network-dependent action.
|
- **Cache server reachability.** `test-web.yml` does NOT use `cache: 'npm'` on `actions/setup-node` — the Gitea Actions cache server isn't reachable from this runner's container network and `setup-node` was burning ~4m41s on ETIMEDOUT before failing open. With the migration to `ci-go:1.26`, `setup-node` is removed entirely (Node is in the image). The cache concern reappears if a future change re-introduces a network-dependent action.
|
||||||
- **Artifacts — stock `actions/upload-artifact@v7` and `actions/download-artifact@v8`; never `@v3`.**
|
- **Artifacts — use the mirrored actions, never `actions/{upload,download}-artifact`.**
|
||||||
```yaml
|
```yaml
|
||||||
uses: actions/upload-artifact@v7
|
uses: https://git.fabledsword.com/bvandeusen/upload-artifact@cb8afe72b42edc798abfb8fcb556cf660d894245
|
||||||
uses: actions/download-artifact@v8
|
uses: https://git.fabledsword.com/bvandeusen/download-artifact@8d4e9521a5f7e5f8b6351f341f719f9f45a92a3a
|
||||||
```
|
```
|
||||||
Stock works on this forge since the runner moved to gitea/runner 3.x, which
|
Upstream's `@v4+` cannot work against this instance and no server-side change
|
||||||
edits the actions' client-side `isGhes()` refusal out of their bundles. Proven
|
will help: `isGhes()` rejects any hostname that isn't `github.com` /
|
||||||
on 2026-09-10 for upload v4–v7 and download v4–v8 (Scribe spike #3843). Until
|
`*.ghe.com` / `*.localhost` and throws before it opens a connection, so the
|
||||||
then this repo pinned SHA mirrors of the Forgejo project's forks, because
|
server is never asked what it supports. `@v3` is worse — it reports success,
|
||||||
upstream threw on the hostname before it opened a connection (Scribe 2255).
|
and Gitea then serves artifacts back only through the v4 API
|
||||||
|
(`content_encoding = application/zip`), so a v3 upload is stored but invisible
|
||||||
|
to every retrieval path. A green job producing nothing retrievable; that is how
|
||||||
|
72 unreachable artifacts accumulated on this repo. Scribe issues 2255 / 2270.
|
||||||
|
|
||||||
`@v3` is still broken: it reports success, and Gitea serves artifacts back only
|
Both are pull mirrors of the Forgejo project's forks
|
||||||
through the v4 API (`content_encoding = application/zip`), so a v3 upload is
|
(`code.forgejo.org/forgejo/{upload,download}-artifact`, one commit on upstream
|
||||||
stored but invisible to every retrieval path. That is how 72 unreachable
|
disabling that check), mirrored so CI depends on commits we hold and pinned by
|
||||||
artifacts accumulated on this repo (Scribe 2270).
|
SHA because the mirrors auto-sync every 8h — a moved upstream tag would
|
||||||
|
otherwise silently change what runs.
|
||||||
|
|
||||||
**Pairing no longer needs managing.** This entry used to pin upload v5 against
|
**Match the pins on `@actions/artifact`, not on the actions' own version
|
||||||
download v6 so both bundled `@actions/artifact` ^4.0.0, warning that a mismatch
|
numbers.** The two actions release on unrelated cadences, so equal version
|
||||||
across `release.yml`'s producer/consumer pair would list empty. Tested, and not
|
numbers do NOT mean a compatible pair — upload `v5` bundles `@actions/artifact`
|
||||||
true on this instance: every download major v4–v8 read the artifacts of every
|
^4.0.0 while download `v5` bundles ^2.3.2. The pins above are upload **v5** and
|
||||||
upload major v4–v7, by name and by pattern (CI-runner run 6312). The only real
|
download **v6**, which is the pairing that puts ^4.0.0 on both sides. This
|
||||||
protocol break is v3 → v4. node24 is no longer a concern either — every
|
matters because `release.yml` is a producer/consumer pair — `android-release`
|
||||||
CI-runner image carries Node 24 and the runner runs actions with the image's
|
uploads `minstrel-apk`, `image-release` downloads it — and a protocol mismatch
|
||||||
`node`.
|
across it yields an empty listing rather than an error, exactly the silent
|
||||||
|
failure this entry exists to prevent.
|
||||||
|
|
||||||
|
| tag | `@actions/artifact` | runtime |
|
||||||
|
|---|---|---|
|
||||||
|
| upload v4 | ^2.1.1 | node20 |
|
||||||
|
| **upload v5** ← pinned | **^4.0.0** | node20 |
|
||||||
|
| download v4 | ^2.1.1 | node20 |
|
||||||
|
| download v5 | ^2.3.2 | node20 |
|
||||||
|
| **download v6** ← pinned | **^4.0.0** | node20 |
|
||||||
|
| download v7 | ^5.0.0 | **node24** |
|
||||||
|
|
||||||
|
The only true protocol break in this history was **v3 → v4** (upstream:
|
||||||
|
"Downloading artifacts that were created from `actions/upload-artifact@v3` and
|
||||||
|
below are not supported"); v4-and-up are one family. Later majors are mostly
|
||||||
|
ergonomics and runtime — upload v4 forbids re-uploading a name and caps a job
|
||||||
|
at 500 artifacts; download v5 made by-ID extraction match by-name.
|
||||||
|
|
||||||
|
**Do not jump the download pin to v7.** That major is a runner requirement, not
|
||||||
|
a feature change: it moves to `runs.using: node24` and upstream states it
|
||||||
|
"requires a minimum Actions Runner version of 2.327.1 … if you are using
|
||||||
|
self-hosted runners, ensure they are updated before upgrading." act_runner is
|
||||||
|
not GitHub's runner and makes no such version claim, so node24 is unverified
|
||||||
|
here. Everything currently pinned is node20.
|
||||||
|
|
||||||
Upload steps set `if-no-files-found: error` rather than the default `warn`, so
|
Upload steps set `if-no-files-found: error` rather than the default `warn`, so
|
||||||
an upload that matches nothing fails its own job instead of failing the
|
an upload that matches nothing fails its own job instead of failing the
|
||||||
|
|||||||
-159
@@ -1,159 +0,0 @@
|
|||||||
#!/usr/bin/env bash
|
|
||||||
#
|
|
||||||
# Derives the three values a build is stamped with, and the tag that names it.
|
|
||||||
#
|
|
||||||
# name=YYYY.MM.DD.HHMM label for people, from the timestamp of the newest
|
|
||||||
# commit that CHANGED SOMETHING SHIPPED (see SHIPPED)
|
|
||||||
# code=<int> ordering key, minutes since 2020-01-01 at BUILD time
|
|
||||||
# tag=v<name> what a release of this commit must be called
|
|
||||||
#
|
|
||||||
# Usage: ci/version.sh [<commit-ish>] (default HEAD)
|
|
||||||
#
|
|
||||||
# This exists as a script rather than inline workflow YAML for one reason:
|
|
||||||
# release.yml only runs on `main` and on tags, so anything living inside it is
|
|
||||||
# unverifiable until a release is already happening — which is the worst
|
|
||||||
# possible moment to discover the version is wrong, because the failure mode
|
|
||||||
# is silent (an update nobody is offered looks exactly like being current).
|
|
||||||
# As a script it can be executed by a test on every push instead.
|
|
||||||
#
|
|
||||||
# The two clocks are deliberate and are NOT interchangeable:
|
|
||||||
#
|
|
||||||
# The NAME answers "is this the same code?" — so it must read identically on
|
|
||||||
# every lane that builds this commit. Commit time does that; build time
|
|
||||||
# prints two different strings for one thing.
|
|
||||||
#
|
|
||||||
# The CODE answers "may this be installed over that?" — so it must be
|
|
||||||
# monotonic BY CONSTRUCTION. Build time is; commit time is not (rebuild an
|
|
||||||
# older commit and it goes down, which on a phone is a refused install), and
|
|
||||||
# a commit COUNT is worse still, because it runs ahead on `dev` and inverts
|
|
||||||
# against `main`.
|
|
||||||
set -euo pipefail
|
|
||||||
|
|
||||||
readonly EPOCH_2020=1577836800 # 2020-01-01T00:00:00Z
|
|
||||||
readonly REF="${1:-HEAD}"
|
|
||||||
|
|
||||||
# Both clocks are overridable so a test can pin them. Nothing but tests should
|
|
||||||
# set these — the defaults are the real derivation.
|
|
||||||
# The paths that do NOT ship, in either artifact. Everything else counts.
|
|
||||||
#
|
|
||||||
# A DENYLIST, and the direction is the whole point. As an allowlist, the list
|
|
||||||
# has to be updated by whoever adds a directory and nothing fails if they
|
|
||||||
# don't — so the failure mode is a changed artifact keeping its old version,
|
|
||||||
# silently, on a green run. That is a build lying about what it is. Inverted,
|
|
||||||
# new content counts by default and the only way to wrongly EXCLUDE something
|
|
||||||
# is to name it here deliberately.
|
|
||||||
#
|
|
||||||
# The two error directions are not symmetric, which is why this is not taste:
|
|
||||||
# wrongly excluded → changed artifact, unchanged version. A silent lie.
|
|
||||||
# wrongly included → version moves when nothing shipped. Cosmetic noise in
|
|
||||||
# a string nobody sorts.
|
|
||||||
#
|
|
||||||
# THIS REPO SHIPS TWO ARTIFACTS FROM ONE DERIVATION, and that is why the list
|
|
||||||
# is shorter than it looks like it should be. The server image ships cmd/,
|
|
||||||
# internal/, shared/, web/, config.example.yaml and client/; the APK ships
|
|
||||||
# android/. Neither ships the other's sources — but excluding android/ here
|
|
||||||
# would stop an Android-only commit from moving the APK's OWN version, which
|
|
||||||
# is the dangerous direction. So this is the union: exclude only what ships in
|
|
||||||
# NEITHER, and accept that an Android commit also nudges the server's reported
|
|
||||||
# version. Over-inclusion across the two, which is the harmless direction.
|
|
||||||
#
|
|
||||||
# The family's other repos (roundtable / roundtable-android) each keep a
|
|
||||||
# tighter list because they are separate repos with one artifact apiece. Do
|
|
||||||
# not copy theirs onto this one.
|
|
||||||
readonly SHIPPED=(
|
|
||||||
.
|
|
||||||
':!.gitea' # CI workflows — including this script's own caller
|
|
||||||
':!ci' # CI scripts — including this script
|
|
||||||
':!docs'
|
|
||||||
':!tools' # asset/font generators; their OUTPUT ships, they do not
|
|
||||||
':!deploy' # test-database bootstrap SQL
|
|
||||||
':!bin' # local `make build` output
|
|
||||||
':!*.md'
|
|
||||||
':!Makefile'
|
|
||||||
':!docker-compose.yml'
|
|
||||||
':!.env.example'
|
|
||||||
':!.gitignore'
|
|
||||||
':!.dockerignore'
|
|
||||||
':!renovate.json'
|
|
||||||
':!.golangci.yml'
|
|
||||||
|
|
||||||
# TESTS DO NOT SHIP, so they must not re-version an artifact.
|
|
||||||
#
|
|
||||||
# Named as globs rather than a directory because this repo has no tests/
|
|
||||||
# tree to exclude: Go tests sit inline beside the code they cover, and the
|
|
||||||
# web suite sits beside its modules. `go build` drops *_test.go outright and
|
|
||||||
# the Vite build never imports a .test.ts, so neither reaches an artifact.
|
|
||||||
#
|
|
||||||
# A commit touching a test AND its source still moves the version — the
|
|
||||||
# source path matches on its own. Only a test-ONLY commit is inert, which is
|
|
||||||
# the whole intent.
|
|
||||||
#
|
|
||||||
# Patterns match what exists today and nothing speculative: there are no
|
|
||||||
# .spec.* files, no __tests__/ directories and no androidTest/ tree. If any
|
|
||||||
# appear they will re-version until named here, which is the harmless
|
|
||||||
# direction and the reason this list is a denylist.
|
|
||||||
':!*_test.go' # 158 files, inline beside the code
|
|
||||||
':!*.test.ts' # 114 files
|
|
||||||
':!*.test.js'
|
|
||||||
':!android/app/src/test' # JVM unit tests; no androidTest tree exists
|
|
||||||
':!web/vitest.config.ts' # test-harness config, not build config
|
|
||||||
':!web/vitest.setup.ts'
|
|
||||||
)
|
|
||||||
|
|
||||||
commit_epoch="${MINSTREL_COMMIT_EPOCH:-}"
|
|
||||||
if [ -z "${commit_epoch}" ]; then
|
|
||||||
commit_epoch="$(git log --format=%ct -1 "${REF}" -- "${SHIPPED[@]}")"
|
|
||||||
# Loudly, on purpose. A silent fallback here is the landmine this whole
|
|
||||||
# script exists to avoid: a plausible-looking version that is quietly wrong,
|
|
||||||
# on a green run. Realistically this means a shallow clone (no commit in
|
|
||||||
# range touches the shipped set) rather than a repo of pure CI config.
|
|
||||||
if [ -z "${commit_epoch}" ]; then
|
|
||||||
echo "version.sh: no commit under '${REF}' touches the shipped file set — shallow clone? (needs fetch-depth: 0)" >&2
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
fi
|
|
||||||
now_epoch="${MINSTREL_NOW_EPOCH:-$(date -u +%s)}"
|
|
||||||
|
|
||||||
if ! name="$(date -u -d "@${commit_epoch}" +%Y.%m.%d.%H%M 2>/dev/null)"; then
|
|
||||||
echo "version.sh: could not read a commit timestamp from '${commit_epoch}'" >&2
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
if ! [ "${now_epoch}" -eq "${now_epoch}" ] 2>/dev/null; then
|
|
||||||
echo "version.sh: build timestamp '${now_epoch}' is not a number" >&2
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
code=$(( (now_epoch - EPOCH_2020) / 60 ))
|
|
||||||
|
|
||||||
# Assert the shape here, at the source. A malformed name builds, signs and
|
|
||||||
# publishes perfectly happily; it only surfaces later as an update channel
|
|
||||||
# that has quietly stopped offering anything.
|
|
||||||
if [[ ! "${name}" =~ ^[0-9]{4}\.[0-9]{2}\.[0-9]{2}\.[0-9]{4}$ ]]; then
|
|
||||||
echo "version.sh: name '${name}' is not YYYY.MM.DD.HHMM" >&2
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
# A non-positive key means the build clock is set before 2020, and every
|
|
||||||
# comparison downstream would be nonsense.
|
|
||||||
if [ "${code}" -le 0 ]; then
|
|
||||||
echo "version.sh: ordering key '${code}' is not positive — build clock wrong?" >&2
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Android's versionCode is a signed 32-bit int and the platform refuses an APK
|
|
||||||
# whose code exceeds it. At ~525k minutes a year this is four thousand years
|
|
||||||
# away in normal operation, so the realistic cause is a build machine with a
|
|
||||||
# badly wrong clock — which produces a code that is not merely too large but
|
|
||||||
# also unreachably high, permanently blocking every real build that follows
|
|
||||||
# from ever outranking it. Cheaper to refuse the build than to discover that
|
|
||||||
# from a phone that will not update.
|
|
||||||
readonly VERSION_CODE_CEILING=2147483647
|
|
||||||
if [ "${code}" -gt "${VERSION_CODE_CEILING}" ]; then
|
|
||||||
echo "version.sh: ordering key '${code}' exceeds versionCode's int32 ceiling — build clock wrong?" >&2
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
# KEY=VALUE, which is also exactly $GITHUB_OUTPUT's format.
|
|
||||||
echo "name=${name}"
|
|
||||||
echo "code=${code}"
|
|
||||||
echo "tag=v${name}"
|
|
||||||
+1
-29
@@ -122,15 +122,7 @@ func run() error {
|
|||||||
}
|
}
|
||||||
defer pool.Close()
|
defer pool.Close()
|
||||||
|
|
||||||
// Fingerprinting settings (M400 #3913): one instance, shared by the scanner,
|
scanner := library.New(pool, logger, cfg.Library.ScanPaths)
|
||||||
// the fingerprint backfill, the duplicate sweep and the admin API, so a save
|
|
||||||
// reaches all of them without a restart. A load failure is logged, not fatal:
|
|
||||||
// the service falls back to the shipped defaults.
|
|
||||||
fpSettings, fpErr := library.NewFingerprintSettingsService(ctx, pool)
|
|
||||||
if fpErr != nil {
|
|
||||||
logger.Warn("fingerprint settings: using defaults", "err", fpErr)
|
|
||||||
}
|
|
||||||
scanner := library.New(pool, logger, cfg.Library.ScanPaths, fpSettings)
|
|
||||||
|
|
||||||
contact := cfg.Library.ContactEmail
|
contact := cfg.Library.ContactEmail
|
||||||
if contact == "" {
|
if contact == "" {
|
||||||
@@ -222,17 +214,6 @@ func run() error {
|
|||||||
// SQL, no external calls; empty on single-user servers.
|
// SQL, no external calls; empty on single-user servers.
|
||||||
go coplay.NewWorker(pool, logger.With("component", "coplay")).Run(ctx)
|
go coplay.NewWorker(pool, logger.With("component", "coplay")).Run(ctx)
|
||||||
|
|
||||||
// Fingerprint backfill (M400 #3908): fingerprints the tracks the scan never
|
|
||||||
// will — everything imported before fingerprinting existed, and rows derived
|
|
||||||
// by an older method. A worker of its own rather than a scan stage; see
|
|
||||||
// internal/library/fingerprint_backfill.go for why.
|
|
||||||
go library.NewFingerprintBackfillWorker(pool, logger.With("component", "fingerprint_backfill"), fpSettings).Run(ctx)
|
|
||||||
|
|
||||||
// Duplicate sweep (M400 #3910): proposes groups of tracks holding one
|
|
||||||
// recording, from the fingerprints above. Sweeps only when fingerprints have
|
|
||||||
// changed since the last sweep.
|
|
||||||
go library.NewDuplicateSweepWorker(pool, logger.With("component", "duplicate_sweep"), fpSettings).Run(ctx)
|
|
||||||
|
|
||||||
// Start the tag-enrichment worker (#1490). Reconciles the compiled-in
|
// Start the tag-enrichment worker (#1490). Reconciles the compiled-in
|
||||||
// tag providers with tag_provider_settings, bumps the sources version if
|
// tag providers with tag_provider_settings, bumps the sources version if
|
||||||
// the provider set changed (re-opening settled rows), then drains tracks
|
// the provider set changed (re-opening settled rows), then drains tracks
|
||||||
@@ -376,20 +357,11 @@ func run() error {
|
|||||||
srv.PlaylistScheduler = playlistScheduler
|
srv.PlaylistScheduler = playlistScheduler
|
||||||
srv.RecSettings = recSettings
|
srv.RecSettings = recSettings
|
||||||
srv.TagSettings = tagSettings
|
srv.TagSettings = tagSettings
|
||||||
srv.FingerprintSettings = fpSettings
|
|
||||||
// The sweeper above holds this same instance, so a save from the admin
|
|
||||||
// card changes what it does on its next tick (#3936).
|
|
||||||
srv.ReacqSettings = reacqSettings
|
|
||||||
srv.StreamSecret = cfg.StreamSecret
|
srv.StreamSecret = cfg.StreamSecret
|
||||||
httpServer := &http.Server{
|
httpServer := &http.Server{
|
||||||
Addr: cfg.Server.Address,
|
Addr: cfg.Server.Address,
|
||||||
Handler: srv.Router(),
|
Handler: srv.Router(),
|
||||||
ReadHeaderTimeout: 10 * time.Second,
|
ReadHeaderTimeout: 10 * time.Second,
|
||||||
// Closes keep-alive connections nobody is using. Deliberately no
|
|
||||||
// ReadTimeout or WriteTimeout: either would cut off audio streams and
|
|
||||||
// the SSE event stream. Request bodies get their own deadline in the
|
|
||||||
// server's limitRequestBody middleware instead.
|
|
||||||
IdleTimeout: 120 * time.Second,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
errCh := make(chan error, 1)
|
errCh := make(chan error, 1)
|
||||||
|
|||||||
+1
-1
@@ -8,7 +8,7 @@ version: "3.9"
|
|||||||
# tests at it:
|
# tests at it:
|
||||||
# make test-integration
|
# make test-integration
|
||||||
# (CI runs the same suite against its own ephemeral Postgres service —
|
# (CI runs the same suite against its own ephemeral Postgres service —
|
||||||
# see the `integration` job in .gitea/workflows/release.yml.)
|
# see .gitea/workflows/test-go.yml.)
|
||||||
#
|
#
|
||||||
# Full stack (server + db):
|
# Full stack (server + db):
|
||||||
# docker compose up --build
|
# docker compose up --build
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ require (
|
|||||||
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
|
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
|
||||||
github.com/robfig/cron/v3 v3.0.1 // indirect
|
github.com/robfig/cron/v3 v3.0.1 // indirect
|
||||||
github.com/rogpeppe/go-internal v1.14.1 // indirect
|
github.com/rogpeppe/go-internal v1.14.1 // indirect
|
||||||
golang.org/x/sync v0.21.0 // indirect
|
golang.org/x/sync v0.20.0 // indirect
|
||||||
golang.org/x/sys v0.44.0 // indirect
|
golang.org/x/sys v0.44.0 // indirect
|
||||||
golang.org/x/text v0.39.0 // indirect
|
golang.org/x/text v0.37.0 // indirect
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -95,12 +95,12 @@ go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
|
|||||||
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
|
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
|
||||||
golang.org/x/crypto v0.51.0 h1:IBPXwPfKxY7cWQZ38ZCIRPI50YLeevDLlLnyC5wRGTI=
|
golang.org/x/crypto v0.51.0 h1:IBPXwPfKxY7cWQZ38ZCIRPI50YLeevDLlLnyC5wRGTI=
|
||||||
golang.org/x/crypto v0.51.0/go.mod h1:8AdwkbraGNABw2kOX6YFPs3WM22XqI4EXEd8g+x7Oc8=
|
golang.org/x/crypto v0.51.0/go.mod h1:8AdwkbraGNABw2kOX6YFPs3WM22XqI4EXEd8g+x7Oc8=
|
||||||
golang.org/x/sync v0.21.0 h1:HLII4xRRTtCRkxYp4HNFF0Js/Og6q2i++KXbg0gHCwM=
|
golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
|
||||||
golang.org/x/sync v0.21.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||||
golang.org/x/sys v0.44.0 h1:ildZl3J4uzeKP07r2F++Op7E9B29JRUy+a27EibtBTQ=
|
golang.org/x/sys v0.44.0 h1:ildZl3J4uzeKP07r2F++Op7E9B29JRUy+a27EibtBTQ=
|
||||||
golang.org/x/sys v0.44.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
golang.org/x/sys v0.44.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||||
golang.org/x/text v0.39.0 h1:UbZz4pLOvn600D6Oh6GGEI6VAmndrEBLv8/6BEXzyus=
|
golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc=
|
||||||
golang.org/x/text v0.39.0/go.mod h1:3UwRclnC2g0TU9x8PZiyfOajCd1zaUNHF9cvqcQZ+ZM=
|
golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38=
|
||||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||||
|
|||||||
@@ -1,12 +1,10 @@
|
|||||||
package api
|
package api
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
|
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
|
||||||
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
|
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
|
||||||
"git.fabledsword.com/bvandeusen/minstrel/internal/library"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// coverageRollupResp is the wire shape for GET /api/admin/library/coverage.
|
// coverageRollupResp is the wire shape for GET /api/admin/library/coverage.
|
||||||
@@ -38,46 +36,3 @@ func (h *handlers) handleGetLibraryCoverage(w http.ResponseWriter, r *http.Reque
|
|||||||
PendingNoMbid: row.PendingNoMbid,
|
PendingNoMbid: row.PendingNoMbid,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// fingerprintCoverageResp is the wire shape for GET /api/admin/library/fingerprints.
|
|
||||||
// fingerprinted + rejected + pending = total. Missing tracks are not counted:
|
|
||||||
// there is no file to fingerprint. Enabled travels with the counts because with
|
|
||||||
// fingerprinting off (#3913) pending never shrinks, and a gauge that implies
|
|
||||||
// progress would be promising work nothing is doing.
|
|
||||||
type fingerprintCoverageResp struct {
|
|
||||||
Total int64 `json:"total"`
|
|
||||||
Fingerprinted int64 `json:"fingerprinted"`
|
|
||||||
Rejected int64 `json:"rejected"`
|
|
||||||
Pending int64 `json:"pending"`
|
|
||||||
Enabled bool `json:"enabled"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// fingerprintCoverage reads the gauge against the current settings: a print at
|
|
||||||
// another length counts as pending, because the backfill will re-derive it.
|
|
||||||
func (h *handlers) fingerprintCoverage(ctx context.Context) (fingerprintCoverageResp, error) {
|
|
||||||
cfg := h.fingerprintSettings.Get()
|
|
||||||
row, err := library.FingerprintCoverage(ctx, h.pool, cfg)
|
|
||||||
if err != nil {
|
|
||||||
return fingerprintCoverageResp{}, err
|
|
||||||
}
|
|
||||||
return fingerprintCoverageResp{
|
|
||||||
Total: row.Total,
|
|
||||||
Fingerprinted: row.Fingerprinted,
|
|
||||||
Rejected: row.Rejected,
|
|
||||||
Pending: row.Pending,
|
|
||||||
Enabled: cfg.Enabled,
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// handleGetFingerprintCoverage implements GET /api/admin/library/fingerprints:
|
|
||||||
// how far the fingerprint backfill (#3908) has got. The backfill is its own
|
|
||||||
// worker spanning many passes, with no scan run to attach a tally to, so its
|
|
||||||
// progress is read live here. Always 200; zeros on an empty library.
|
|
||||||
func (h *handlers) handleGetFingerprintCoverage(w http.ResponseWriter, r *http.Request) {
|
|
||||||
cov, err := h.fingerprintCoverage(r.Context())
|
|
||||||
if err != nil {
|
|
||||||
writeErrWithLog(w, h.logger, "admin: get fingerprint coverage", apierror.InternalMsg("lookup failed", err))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
writeJSON(w, http.StatusOK, cov)
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,316 +0,0 @@
|
|||||||
package api
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"encoding/json"
|
|
||||||
"errors"
|
|
||||||
"io"
|
|
||||||
"net/http"
|
|
||||||
|
|
||||||
"github.com/go-chi/chi/v5"
|
|
||||||
"github.com/jackc/pgx/v5"
|
|
||||||
"github.com/jackc/pgx/v5/pgtype"
|
|
||||||
|
|
||||||
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
|
|
||||||
"git.fabledsword.com/bvandeusen/minstrel/internal/library"
|
|
||||||
)
|
|
||||||
|
|
||||||
// duplicateMemberView is one copy in a proposed duplicate group. LikeCount and
|
|
||||||
// PlayCount span every user: the report is admin-only, and what a copy carries
|
|
||||||
// is the fact the operator weighs when choosing which to keep.
|
|
||||||
type duplicateMemberView struct {
|
|
||||||
TrackID string `json:"track_id"`
|
|
||||||
Title string `json:"title"`
|
|
||||||
ArtistName string `json:"artist_name"`
|
|
||||||
AlbumID string `json:"album_id"`
|
|
||||||
AlbumTitle string `json:"album_title"`
|
|
||||||
FilePath string `json:"file_path"`
|
|
||||||
FileFormat string `json:"file_format"`
|
|
||||||
FileSize int64 `json:"file_size"`
|
|
||||||
DurationSec int32 `json:"duration_sec"`
|
|
||||||
AddedAt string `json:"added_at"`
|
|
||||||
LikeCount int64 `json:"like_count"`
|
|
||||||
PlayCount int64 `json:"play_count"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// duplicateGroupView is one proposal. SurvivorTrackID and SurvivorReason are
|
|
||||||
// the copy the report proposes keeping and the rule that chose it
|
|
||||||
// (library.ProposeSurvivor) — a default the merge (#3911) lets the operator
|
|
||||||
// override.
|
|
||||||
type duplicateGroupView struct {
|
|
||||||
ID string `json:"id"`
|
|
||||||
Tier string `json:"tier"`
|
|
||||||
WorstBitErrorRate *float32 `json:"worst_bit_error_rate"`
|
|
||||||
DetectedAt string `json:"detected_at"`
|
|
||||||
SurvivorTrackID string `json:"survivor_track_id"`
|
|
||||||
SurvivorReason string `json:"survivor_reason"`
|
|
||||||
Members []duplicateMemberView `json:"members"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// duplicateSweepView is the latest sweep. State is "never" when none has run,
|
|
||||||
// which is what lets the page tell an empty report apart from a sweep that
|
|
||||||
// found nothing.
|
|
||||||
type duplicateSweepView struct {
|
|
||||||
State string `json:"state"`
|
|
||||||
StartedAt *string `json:"started_at"`
|
|
||||||
FinishedAt *string `json:"finished_at"`
|
|
||||||
Candidates *int32 `json:"candidates"`
|
|
||||||
GroupsFound *int32 `json:"groups_found"`
|
|
||||||
OversizeClusters *int32 `json:"oversize_clusters"`
|
|
||||||
ErrorMessage *string `json:"error_message"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// adminDuplicatesResponse is the paged report. Total counts groups.
|
|
||||||
type adminDuplicatesResponse struct {
|
|
||||||
Sweep duplicateSweepView `json:"sweep"`
|
|
||||||
Fingerprints fingerprintCoverageResp `json:"fingerprints"`
|
|
||||||
Total int64 `json:"total"`
|
|
||||||
Limit int `json:"limit"`
|
|
||||||
Offset int `json:"offset"`
|
|
||||||
Groups []duplicateGroupView `json:"groups"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// handleListDuplicates implements GET /api/admin/library/duplicates (#3912).
|
|
||||||
//
|
|
||||||
// Read-only. The sweep's state and the fingerprint backfill's progress travel
|
|
||||||
// with the groups because an empty report means three different things — still
|
|
||||||
// fingerprinting, never swept, or swept and clean — and the page has to say which.
|
|
||||||
func (h *handlers) handleListDuplicates(w http.ResponseWriter, r *http.Request) {
|
|
||||||
limit, offset, err := parsePaging(r.URL.Query())
|
|
||||||
if err != nil {
|
|
||||||
writeAdminJSONErr(w, http.StatusBadRequest, "invalid_paging")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
ctx := r.Context()
|
|
||||||
q := dbq.New(h.pool)
|
|
||||||
|
|
||||||
sweep := duplicateSweepView{State: "never"}
|
|
||||||
last, err := q.GetLatestDuplicateSweep(ctx)
|
|
||||||
switch {
|
|
||||||
case err == nil:
|
|
||||||
sweep = duplicateSweepViewOf(last)
|
|
||||||
case !errors.Is(err, pgx.ErrNoRows):
|
|
||||||
h.logger.Error("admin: latest duplicate sweep", "err", err)
|
|
||||||
writeAdminJSONErr(w, http.StatusInternalServerError, "server_error")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
cov, err := h.fingerprintCoverage(ctx)
|
|
||||||
if err != nil {
|
|
||||||
h.logger.Error("admin: fingerprint coverage", "err", err)
|
|
||||||
writeAdminJSONErr(w, http.StatusInternalServerError, "server_error")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
total, err := q.CountPendingDuplicateGroups(ctx)
|
|
||||||
if err != nil {
|
|
||||||
h.logger.Error("admin: count duplicate groups", "err", err)
|
|
||||||
writeAdminJSONErr(w, http.StatusInternalServerError, "server_error")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
rows, err := q.ListPendingDuplicateGroupMembers(ctx, dbq.ListPendingDuplicateGroupMembersParams{
|
|
||||||
PageLimit: int32(limit), PageOffset: int32(offset),
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
h.logger.Error("admin: list duplicate groups", "err", err)
|
|
||||||
writeAdminJSONErr(w, http.StatusInternalServerError, "server_error")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
writeJSON(w, http.StatusOK, adminDuplicatesResponse{
|
|
||||||
Sweep: sweep,
|
|
||||||
Fingerprints: cov,
|
|
||||||
Total: total,
|
|
||||||
Limit: limit,
|
|
||||||
Offset: offset,
|
|
||||||
Groups: foldDuplicateGroups(rows),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func duplicateSweepViewOf(s dbq.DuplicateSweep) duplicateSweepView {
|
|
||||||
v := duplicateSweepView{
|
|
||||||
State: "running",
|
|
||||||
Candidates: s.Candidates,
|
|
||||||
GroupsFound: s.GroupsFound,
|
|
||||||
OversizeClusters: s.OversizeClusters,
|
|
||||||
ErrorMessage: s.ErrorMessage,
|
|
||||||
}
|
|
||||||
started := formatTimestamp(s.StartedAt)
|
|
||||||
v.StartedAt = &started
|
|
||||||
if s.FinishedAt.Valid {
|
|
||||||
finished := formatTimestamp(s.FinishedAt)
|
|
||||||
v.FinishedAt = &finished
|
|
||||||
v.State = "finished"
|
|
||||||
}
|
|
||||||
return v
|
|
||||||
}
|
|
||||||
|
|
||||||
// foldDuplicateGroups folds the one-row-per-member query result into groups and
|
|
||||||
// proposes each group's survivor. It relies on the query ordering members of a
|
|
||||||
// group together, so a run-length fold is enough and the page order holds.
|
|
||||||
func foldDuplicateGroups(rows []dbq.ListPendingDuplicateGroupMembersRow) []duplicateGroupView {
|
|
||||||
groups := make([]duplicateGroupView, 0, 8)
|
|
||||||
var candidates [][]library.SurvivorCandidate
|
|
||||||
for _, row := range rows {
|
|
||||||
id := uuidToString(row.GroupID)
|
|
||||||
if n := len(groups); n == 0 || groups[n-1].ID != id {
|
|
||||||
groups = append(groups, duplicateGroupView{
|
|
||||||
ID: id,
|
|
||||||
Tier: row.Tier,
|
|
||||||
WorstBitErrorRate: row.WorstBitErrorRate,
|
|
||||||
DetectedAt: formatTimestamp(row.DetectedAt),
|
|
||||||
})
|
|
||||||
candidates = append(candidates, nil)
|
|
||||||
}
|
|
||||||
n := len(groups) - 1
|
|
||||||
trackID := uuidToString(row.TrackID)
|
|
||||||
groups[n].Members = append(groups[n].Members, duplicateMemberView{
|
|
||||||
TrackID: trackID,
|
|
||||||
Title: row.Title,
|
|
||||||
ArtistName: row.ArtistName,
|
|
||||||
AlbumID: uuidToString(row.AlbumID),
|
|
||||||
AlbumTitle: row.AlbumTitle,
|
|
||||||
FilePath: row.FilePath,
|
|
||||||
FileFormat: row.FileFormat,
|
|
||||||
FileSize: row.FileSize,
|
|
||||||
DurationSec: row.DurationMs / 1000,
|
|
||||||
AddedAt: formatTimestamp(row.AddedAt),
|
|
||||||
LikeCount: row.LikeCount,
|
|
||||||
PlayCount: row.PlayCount,
|
|
||||||
})
|
|
||||||
candidates[n] = append(candidates[n], library.SurvivorCandidate{
|
|
||||||
TrackID: trackID, FileFormat: row.FileFormat, FileSize: row.FileSize, AddedAt: row.AddedAt.Time,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
for i := range groups {
|
|
||||||
groups[i].SurvivorTrackID, groups[i].SurvivorReason = library.ProposeSurvivor(candidates[i])
|
|
||||||
}
|
|
||||||
return groups
|
|
||||||
}
|
|
||||||
|
|
||||||
// handleRunDuplicateSweep implements POST /api/admin/library/duplicates/sweep:
|
|
||||||
// 202 when a sweep starts, 409 sweep_in_progress when one is already running.
|
|
||||||
// The sweep outlives the request, so it runs on a background context, as
|
|
||||||
// handleTriggerScan's scan does.
|
|
||||||
func (h *handlers) handleRunDuplicateSweep(w http.ResponseWriter, _ *http.Request) {
|
|
||||||
// Runs whatever the sweep interval says: the interval paces the automatic
|
|
||||||
// sweep, and an operator pressing the button has already decided.
|
|
||||||
started, err := library.TryStartDuplicateSweep(
|
|
||||||
context.Background(), h.pool, h.logger.With("source", "manual"), h.fingerprintSettings.Get(),
|
|
||||||
)
|
|
||||||
if err != nil {
|
|
||||||
h.logger.Error("admin: start duplicate sweep", "err", err)
|
|
||||||
writeAdminJSONErr(w, http.StatusInternalServerError, "server_error")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if !started {
|
|
||||||
writeAdminJSONErr(w, http.StatusConflict, "sweep_in_progress")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
writeJSON(w, http.StatusAccepted, map[string]bool{"started": true})
|
|
||||||
}
|
|
||||||
|
|
||||||
// handleDismissDuplicateGroup implements POST
|
|
||||||
// /api/admin/library/duplicates/{id}/dismiss: "these are not duplicates". The
|
|
||||||
// sweep keeps the dismissal and will not propose that set of tracks again. 404
|
|
||||||
// duplicate_group_not_pending when the group was already resolved or is gone.
|
|
||||||
func (h *handlers) handleDismissDuplicateGroup(w http.ResponseWriter, r *http.Request) {
|
|
||||||
id, ok := parseUUID(chi.URLParam(r, "id"))
|
|
||||||
if !ok {
|
|
||||||
writeAdminJSONErr(w, http.StatusBadRequest, "invalid_id")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
n, err := dbq.New(h.pool).DismissDuplicateGroup(r.Context(), id)
|
|
||||||
if err != nil {
|
|
||||||
h.logger.Error("admin: dismiss duplicate group", "err", err)
|
|
||||||
writeAdminJSONErr(w, http.StatusInternalServerError, "server_error")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if n == 0 {
|
|
||||||
writeAdminJSONErr(w, http.StatusNotFound, "duplicate_group_not_pending")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
writeJSON(w, http.StatusOK, map[string]string{"status": "dismissed"})
|
|
||||||
}
|
|
||||||
|
|
||||||
// mergeDuplicateRequest chooses the copy to keep. An empty survivor_track_id
|
|
||||||
// keeps the report's proposal.
|
|
||||||
type mergeDuplicateRequest struct {
|
|
||||||
SurvivorTrackID string `json:"survivor_track_id"`
|
|
||||||
Unmonitor bool `json:"unmonitor"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// mergeDuplicateResponse reports what the merge removed. RemovedPaths are files
|
|
||||||
// deleted from disk; the operator reads them to know exactly what went.
|
|
||||||
type mergeDuplicateResponse struct {
|
|
||||||
SurvivorTrackID string `json:"survivor_track_id"`
|
|
||||||
RemovedPaths []string `json:"removed_paths"`
|
|
||||||
LidarrUnmonitorFailed *bool `json:"lidarr_unmonitor_failed,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// mergeRequestBodyLimit bounds the request body. It holds one id and a flag.
|
|
||||||
const mergeRequestBodyLimit = 1 << 16
|
|
||||||
|
|
||||||
// handleMergeDuplicateGroup implements POST /api/admin/library/duplicates/{id}/merge
|
|
||||||
// (#3911): keep one copy, move the others' likes, plays and playlist entries onto
|
|
||||||
// it, and delete the others' files and rows.
|
|
||||||
//
|
|
||||||
// Errors:
|
|
||||||
// - 409 library_not_writable / 500 file_delete_failed when a file could not be
|
|
||||||
// removed — nothing was changed (fileRemoveAPIError)
|
|
||||||
// - 404 duplicate_group_not_pending when the group was already resolved
|
|
||||||
// - 400 survivor_not_in_group, invalid_id, invalid_body
|
|
||||||
func (h *handlers) handleMergeDuplicateGroup(w http.ResponseWriter, r *http.Request) {
|
|
||||||
admin, ok := requireUser(w, r)
|
|
||||||
if !ok {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
groupID, ok := parseUUID(chi.URLParam(r, "id"))
|
|
||||||
if !ok {
|
|
||||||
writeAdminJSONErr(w, http.StatusBadRequest, "invalid_id")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
var body mergeDuplicateRequest
|
|
||||||
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, mergeRequestBodyLimit)).Decode(&body); err != nil && !errors.Is(err, io.EOF) {
|
|
||||||
writeAdminJSONErr(w, http.StatusBadRequest, "invalid_body")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
var survivorID pgtype.UUID // invalid: keep the proposal
|
|
||||||
if body.SurvivorTrackID != "" {
|
|
||||||
if survivorID, ok = parseUUID(body.SurvivorTrackID); !ok {
|
|
||||||
writeAdminJSONErr(w, http.StatusBadRequest, "invalid_id")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
res, unmonitorFailed, err := h.tracks.MergeDuplicates(r.Context(), groupID, survivorID, admin.ID, body.Unmonitor)
|
|
||||||
if err != nil {
|
|
||||||
if apiErr, ok := fileRemoveAPIError(err); ok {
|
|
||||||
logFileRemoveFailure(h.logger, apiErr, "group_id", uuidToString(groupID))
|
|
||||||
writeErr(w, apiErr)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
switch {
|
|
||||||
case errors.Is(err, library.ErrDuplicateGroupNotPending):
|
|
||||||
writeAdminJSONErr(w, http.StatusNotFound, "duplicate_group_not_pending")
|
|
||||||
case errors.Is(err, library.ErrSurvivorNotInGroup):
|
|
||||||
writeAdminJSONErr(w, http.StatusBadRequest, "survivor_not_in_group")
|
|
||||||
default:
|
|
||||||
h.logger.Error("admin: merge duplicate group", "group_id", uuidToString(groupID), "err", err)
|
|
||||||
writeAdminJSONErr(w, http.StatusInternalServerError, "server_error")
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
resp := mergeDuplicateResponse{
|
|
||||||
SurvivorTrackID: uuidToString(res.Survivor.TrackID),
|
|
||||||
RemovedPaths: make([]string, 0, len(res.Removed)),
|
|
||||||
}
|
|
||||||
for _, c := range res.Removed {
|
|
||||||
resp.RemovedPaths = append(resp.RemovedPaths, c.FilePath)
|
|
||||||
}
|
|
||||||
if body.Unmonitor && unmonitorFailed {
|
|
||||||
failed := true
|
|
||||||
resp.LidarrUnmonitorFailed = &failed
|
|
||||||
}
|
|
||||||
writeJSON(w, http.StatusOK, resp)
|
|
||||||
}
|
|
||||||
@@ -1,65 +0,0 @@
|
|||||||
package api
|
|
||||||
|
|
||||||
import (
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/jackc/pgx/v5/pgtype"
|
|
||||||
|
|
||||||
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
|
|
||||||
)
|
|
||||||
|
|
||||||
func dupUUID(b byte) pgtype.UUID {
|
|
||||||
var u pgtype.UUID
|
|
||||||
u.Bytes[15] = b
|
|
||||||
u.Valid = true
|
|
||||||
return u
|
|
||||||
}
|
|
||||||
|
|
||||||
func dupTS(t time.Time) pgtype.Timestamptz { return pgtype.Timestamptz{Time: t, Valid: true} }
|
|
||||||
|
|
||||||
// Rows arrive one per member, members of a group together. The fold must keep
|
|
||||||
// groups apart, keep the query's order, and propose each group's survivor from
|
|
||||||
// its own members only.
|
|
||||||
func TestFoldDuplicateGroups(t *testing.T) {
|
|
||||||
older := time.Date(2025, 1, 1, 0, 0, 0, 0, time.UTC)
|
|
||||||
newer := older.Add(48 * time.Hour)
|
|
||||||
ber := float32(0.04)
|
|
||||||
rows := []dbq.ListPendingDuplicateGroupMembersRow{
|
|
||||||
// Group 1: identical audio, sizes tie, the older copy should be kept.
|
|
||||||
{GroupID: dupUUID(1), Tier: "exact", DetectedAt: dupTS(newer), TrackID: dupUUID(10),
|
|
||||||
Title: "WWW", FileFormat: "mp3", FileSize: 6_900_000, DurationMs: 215_400, AddedAt: dupTS(newer), PlayCount: 3},
|
|
||||||
{GroupID: dupUUID(1), Tier: "exact", DetectedAt: dupTS(newer), TrackID: dupUUID(11),
|
|
||||||
Title: "WWW", FileFormat: "mp3", FileSize: 6_900_000, DurationMs: 215_400, AddedAt: dupTS(older), LikeCount: 1},
|
|
||||||
// Group 2: the same recording, FLAC against MP3.
|
|
||||||
{GroupID: dupUUID(2), Tier: "acoustic", WorstBitErrorRate: &ber, DetectedAt: dupTS(older), TrackID: dupUUID(20),
|
|
||||||
Title: "Lovesick", FileFormat: "mp3", FileSize: 9_000_000, DurationMs: 198_000, AddedAt: dupTS(older)},
|
|
||||||
{GroupID: dupUUID(2), Tier: "acoustic", WorstBitErrorRate: &ber, DetectedAt: dupTS(older), TrackID: dupUUID(21),
|
|
||||||
Title: "Lovesick", FileFormat: "flac", FileSize: 30_000_000, DurationMs: 198_000, AddedAt: dupTS(newer)},
|
|
||||||
}
|
|
||||||
|
|
||||||
got := foldDuplicateGroups(rows)
|
|
||||||
if len(got) != 2 {
|
|
||||||
t.Fatalf("folded %d groups, want 2", len(got))
|
|
||||||
}
|
|
||||||
|
|
||||||
g1, g2 := got[0], got[1]
|
|
||||||
if g1.ID != uuidToString(dupUUID(1)) || len(g1.Members) != 2 || g1.WorstBitErrorRate != nil {
|
|
||||||
t.Fatalf("group 1 = %+v, want the exact pair with no score", g1)
|
|
||||||
}
|
|
||||||
if g1.SurvivorTrackID != uuidToString(dupUUID(11)) || g1.SurvivorReason != "in the library longest" {
|
|
||||||
t.Errorf("group 1 survivor = (%s, %q), want the older copy", g1.SurvivorTrackID, g1.SurvivorReason)
|
|
||||||
}
|
|
||||||
if g1.Members[0].DurationSec != 215 || g1.Members[0].PlayCount != 3 || g1.Members[1].LikeCount != 1 {
|
|
||||||
t.Errorf("group 1 members lost their facts: %+v", g1.Members)
|
|
||||||
}
|
|
||||||
|
|
||||||
if g2.Tier != "acoustic" || g2.WorstBitErrorRate == nil || *g2.WorstBitErrorRate != ber {
|
|
||||||
t.Fatalf("group 2 = %+v, want the acoustic pair with its score", g2)
|
|
||||||
}
|
|
||||||
// Chosen from group 2's own members: a survivor leaking across groups is
|
|
||||||
// exactly what a wrong fold boundary would produce.
|
|
||||||
if g2.SurvivorTrackID != uuidToString(dupUUID(21)) || g2.SurvivorReason != "lossless (flac)" {
|
|
||||||
t.Errorf("group 2 survivor = (%s, %q), want the FLAC copy", g2.SurvivorTrackID, g2.SurvivorReason)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,67 +0,0 @@
|
|||||||
package api
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"errors"
|
|
||||||
"net/http"
|
|
||||||
|
|
||||||
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
|
|
||||||
"git.fabledsword.com/bvandeusen/minstrel/internal/library"
|
|
||||||
)
|
|
||||||
|
|
||||||
// fingerprintSettingsBody is the wire shape for GET and PUT
|
|
||||||
// /api/admin/library/fingerprint-settings (M400 #3913). The threshold travels as
|
|
||||||
// the bit-error rate the matcher uses; the card presents it as a match percentage.
|
|
||||||
type fingerprintSettingsBody struct {
|
|
||||||
Enabled bool `json:"enabled"`
|
|
||||||
ChromaprintLengthSec int32 `json:"chromaprint_length_sec"`
|
|
||||||
AcousticMaxBitErrorRate float64 `json:"acoustic_max_bit_error_rate"`
|
|
||||||
BackfillConcurrency int32 `json:"backfill_concurrency"`
|
|
||||||
SweepIntervalHours int32 `json:"sweep_interval_hours"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func fingerprintSettingsBodyOf(s library.FingerprintSettings) fingerprintSettingsBody {
|
|
||||||
return fingerprintSettingsBody{
|
|
||||||
Enabled: s.Enabled,
|
|
||||||
ChromaprintLengthSec: s.ChromaprintLengthSec,
|
|
||||||
AcousticMaxBitErrorRate: s.AcousticMaxBitErrorRate,
|
|
||||||
BackfillConcurrency: s.BackfillConcurrency,
|
|
||||||
SweepIntervalHours: s.SweepIntervalHours,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// handleGetFingerprintSettings implements GET /api/admin/library/fingerprint-settings.
|
|
||||||
func (h *handlers) handleGetFingerprintSettings(w http.ResponseWriter, _ *http.Request) {
|
|
||||||
writeJSON(w, http.StatusOK, fingerprintSettingsBodyOf(h.fingerprintSettings.Get()))
|
|
||||||
}
|
|
||||||
|
|
||||||
// handleUpdateFingerprintSettings implements PUT /api/admin/library/fingerprint-settings.
|
|
||||||
//
|
|
||||||
// A whole-row write. A body that leaves a field out decodes it as zero, which no
|
|
||||||
// field accepts, so a partial save is refused rather than zeroing what it omitted.
|
|
||||||
// The saved settings reach the scanner and both workers at once: they share the
|
|
||||||
// service instance.
|
|
||||||
func (h *handlers) handleUpdateFingerprintSettings(w http.ResponseWriter, r *http.Request) {
|
|
||||||
var req fingerprintSettingsBody
|
|
||||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
|
||||||
writeErr(w, apierror.BadRequest("invalid_body", "malformed JSON"))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
saved, err := h.fingerprintSettings.Set(r.Context(), library.FingerprintSettings{
|
|
||||||
Enabled: req.Enabled,
|
|
||||||
ChromaprintLengthSec: req.ChromaprintLengthSec,
|
|
||||||
AcousticMaxBitErrorRate: req.AcousticMaxBitErrorRate,
|
|
||||||
BackfillConcurrency: req.BackfillConcurrency,
|
|
||||||
SweepIntervalHours: req.SweepIntervalHours,
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
// Validation mirrors migration 0061's CHECKs and names the field.
|
|
||||||
if errors.Is(err, library.ErrFingerprintSettingOutOfRange) {
|
|
||||||
writeErr(w, apierror.BadRequest("invalid_setting", err.Error()))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
writeErrWithLog(w, h.logger, "admin fingerprint settings: update failed", apierror.Internal(err))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
writeJSON(w, http.StatusOK, fingerprintSettingsBodyOf(saved))
|
|
||||||
}
|
|
||||||
@@ -1,55 +0,0 @@
|
|||||||
package api
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"io"
|
|
||||||
"log/slog"
|
|
||||||
"net/http"
|
|
||||||
"net/http/httptest"
|
|
||||||
"strings"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"git.fabledsword.com/bvandeusen/minstrel/internal/library"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestGetFingerprintSettings_ServesDefaultsWithoutAService(t *testing.T) {
|
|
||||||
h := &handlers{logger: slog.New(slog.NewTextHandler(io.Discard, nil))}
|
|
||||||
rec := httptest.NewRecorder()
|
|
||||||
h.handleGetFingerprintSettings(rec, httptest.NewRequest(http.MethodGet, "/api/admin/library/fingerprint-settings", nil))
|
|
||||||
if rec.Code != http.StatusOK {
|
|
||||||
t.Fatalf("status = %d, want 200", rec.Code)
|
|
||||||
}
|
|
||||||
var got fingerprintSettingsBody
|
|
||||||
if err := json.NewDecoder(rec.Body).Decode(&got); err != nil {
|
|
||||||
t.Fatalf("decode: %v", err)
|
|
||||||
}
|
|
||||||
if want := fingerprintSettingsBodyOf(library.DefaultFingerprintSettings); got != want {
|
|
||||||
t.Fatalf("body = %+v, want the defaults %+v", got, want)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestUpdateFingerprintSettings_Rejects(t *testing.T) {
|
|
||||||
h := &handlers{logger: slog.New(slog.NewTextHandler(io.Discard, nil))}
|
|
||||||
for name, tc := range map[string]struct {
|
|
||||||
body string
|
|
||||||
code string
|
|
||||||
mentions string
|
|
||||||
}{
|
|
||||||
"a value out of range, naming the field": {
|
|
||||||
body: `{"enabled":true,"chromaprint_length_sec":5,"acoustic_max_bit_error_rate":0.15,"backfill_concurrency":2,"sweep_interval_hours":1}`,
|
|
||||||
code: "invalid_setting",
|
|
||||||
mentions: "chromaprint_length_sec",
|
|
||||||
},
|
|
||||||
// A partial body would otherwise zero every field it left out.
|
|
||||||
"a body missing fields": {body: `{"enabled":false}`, code: "invalid_setting"},
|
|
||||||
"malformed JSON": {body: `{"enabled":`, code: "invalid_body"},
|
|
||||||
} {
|
|
||||||
rec := httptest.NewRecorder()
|
|
||||||
h.handleUpdateFingerprintSettings(rec, httptest.NewRequest(
|
|
||||||
http.MethodPut, "/api/admin/library/fingerprint-settings", strings.NewReader(tc.body)))
|
|
||||||
body := rec.Body.String()
|
|
||||||
if rec.Code != http.StatusBadRequest || !strings.Contains(body, `"`+tc.code+`"`) || !strings.Contains(body, tc.mentions) {
|
|
||||||
t.Errorf("%s: status %d body %s; want 400 %s mentioning %q", name, rec.Code, body, tc.code, tc.mentions)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -23,16 +23,10 @@ type networkSettingsResp struct {
|
|||||||
// arrived and count them rather than guess.
|
// arrived and count them rather than guess.
|
||||||
ForwardedChain string `json:"forwarded_chain"`
|
ForwardedChain string `json:"forwarded_chain"`
|
||||||
RemoteAddr string `json:"remote_addr"`
|
RemoteAddr string `json:"remote_addr"`
|
||||||
// PublicURL is where users reach Minstrel; reset emails link to it and
|
|
||||||
// are not sent while it is empty.
|
|
||||||
PublicURL string `json:"public_url"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Both fields are optional so the proxy card and the public-address card can
|
|
||||||
// each save their own value without overwriting the other's.
|
|
||||||
type updateNetworkSettingsReq struct {
|
type updateNetworkSettingsReq struct {
|
||||||
TrustedProxyHops *int `json:"trusted_proxy_hops"`
|
TrustedProxyHops int `json:"trusted_proxy_hops"`
|
||||||
PublicURL *string `json:"public_url"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *handlers) handleGetNetworkSettings(w http.ResponseWriter, r *http.Request) {
|
func (h *handlers) handleGetNetworkSettings(w http.ResponseWriter, r *http.Request) {
|
||||||
@@ -45,38 +39,14 @@ func (h *handlers) handleUpdateNetworkSettings(w http.ResponseWriter, r *http.Re
|
|||||||
writeErr(w, apierror.BadRequest("invalid_body", "malformed JSON"))
|
writeErr(w, apierror.BadRequest("invalid_body", "malformed JSON"))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if req.TrustedProxyHops == nil && req.PublicURL == nil {
|
if err := h.netSettings.SetHops(r.Context(), req.TrustedProxyHops); err != nil {
|
||||||
writeErr(w, apierror.BadRequest("invalid_body", "nothing to update"))
|
if errors.Is(err, netsettings.ErrHopsOutOfRange) {
|
||||||
|
writeErr(w, apierror.BadRequest("invalid_hops", err.Error()))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeErrWithLog(w, h.logger, "admin network: update failed", apierror.Internal(err))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
// Validate everything before writing anything, so a bad public URL can't
|
|
||||||
// leave the hops half-saved.
|
|
||||||
if req.TrustedProxyHops != nil && (*req.TrustedProxyHops < 0 || *req.TrustedProxyHops > netsettings.MaxTrustedProxyHops) {
|
|
||||||
writeErr(w, apierror.BadRequest("invalid_hops", netsettings.ErrHopsOutOfRange.Error()))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if req.PublicURL != nil {
|
|
||||||
if _, err := netsettings.NormalizePublicURL(*req.PublicURL); err != nil {
|
|
||||||
writeErr(w, apierror.BadRequest("invalid_public_url", err.Error()))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if req.TrustedProxyHops != nil {
|
|
||||||
if err := h.netSettings.SetHops(r.Context(), *req.TrustedProxyHops); err != nil {
|
|
||||||
if errors.Is(err, netsettings.ErrHopsOutOfRange) {
|
|
||||||
writeErr(w, apierror.BadRequest("invalid_hops", err.Error()))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
writeErrWithLog(w, h.logger, "admin network: update failed", apierror.Internal(err))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if req.PublicURL != nil {
|
|
||||||
if err := h.netSettings.SetPublicURL(r.Context(), *req.PublicURL); err != nil {
|
|
||||||
writeErrWithLog(w, h.logger, "admin network: public URL update failed", apierror.Internal(err))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// Echo the payload recomputed under the NEW value, so the card can show
|
// Echo the payload recomputed under the NEW value, so the card can show
|
||||||
// immediately what the change did to this request's own address rather
|
// immediately what the change did to this request's own address rather
|
||||||
// than making the operator reload to find out.
|
// than making the operator reload to find out.
|
||||||
@@ -91,6 +61,5 @@ func (h *handlers) networkSettingsPayload(r *http.Request) networkSettingsResp {
|
|||||||
DetectedClientIP: auth.ClientIP(r, hops),
|
DetectedClientIP: auth.ClientIP(r, hops),
|
||||||
ForwardedChain: r.Header.Get("X-Forwarded-For"),
|
ForwardedChain: r.Header.Get("X-Forwarded-For"),
|
||||||
RemoteAddr: r.RemoteAddr,
|
RemoteAddr: r.RemoteAddr,
|
||||||
PublicURL: h.netSettings.PublicURL(),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -133,13 +133,6 @@ func (h *handlers) handleDeleteQuarantineFile(w http.ResponseWriter, r *http.Req
|
|||||||
}
|
}
|
||||||
action, err := h.lidarrQuarantine.DeleteFile(r.Context(), id, admin.ID)
|
action, err := h.lidarrQuarantine.DeleteFile(r.Context(), id, admin.ID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
// Written in the enveloped shape, not writeAdminJSONErr's bare code: the
|
|
||||||
// message is the part that tells the operator which directory and uid.
|
|
||||||
if apiErr, ok := fileRemoveAPIError(err); ok {
|
|
||||||
logFileRemoveFailure(h.logger, apiErr, "track_id", uuidToString(id))
|
|
||||||
writeErr(w, apiErr)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
switch {
|
switch {
|
||||||
case errors.Is(err, lidarrquarantine.ErrTrackNotFound):
|
case errors.Is(err, lidarrquarantine.ErrTrackNotFound):
|
||||||
writeAdminJSONErr(w, http.StatusNotFound, "track_not_found")
|
writeAdminJSONErr(w, http.StatusNotFound, "track_not_found")
|
||||||
|
|||||||
@@ -69,7 +69,7 @@ func installQuarantineClientFn(t *testing.T, h *handlers) {
|
|||||||
}
|
}
|
||||||
return lidarr.NewClient(c.BaseURL, c.APIKey)
|
return lidarr.NewClient(c.BaseURL, c.APIKey)
|
||||||
}
|
}
|
||||||
h.lidarrQuarantine = lidarrquarantine.NewService(h.pool, cfg, clientFn, h.dataDir)
|
h.lidarrQuarantine = lidarrquarantine.NewService(h.pool, cfg, clientFn)
|
||||||
}
|
}
|
||||||
|
|
||||||
// flagDirect bypasses the HTTP handler to seed a quarantine row via the
|
// flagDirect bypasses the HTTP handler to seed a quarantine row via the
|
||||||
|
|||||||
@@ -97,16 +97,14 @@ type tuningSnapshot struct {
|
|||||||
func (h *handlers) tuningSnapshot() tuningSnapshot {
|
func (h *handlers) tuningSnapshot() tuningSnapshot {
|
||||||
var out tuningSnapshot
|
var out tuningSnapshot
|
||||||
out.Profiles = map[string]weightsResp{
|
out.Profiles = map[string]weightsResp{
|
||||||
recsettings.ScopeRadio: weightsRespFrom(h.recSettings.Weights(recsettings.ScopeRadio)),
|
recsettings.ScopeRadio: weightsRespFrom(h.recSettings.Weights(recsettings.ScopeRadio)),
|
||||||
recsettings.ScopeDailyMix: weightsRespFrom(h.recSettings.Weights(recsettings.ScopeDailyMix)),
|
recsettings.ScopeDailyMix: weightsRespFrom(h.recSettings.Weights(recsettings.ScopeDailyMix)),
|
||||||
recsettings.ScopeSongsLike: weightsRespFrom(h.recSettings.Weights(recsettings.ScopeSongsLike)),
|
|
||||||
}
|
}
|
||||||
out.Taste = tasteRespFrom(h.recSettings.Taste())
|
out.Taste = tasteRespFrom(h.recSettings.Taste())
|
||||||
out.Discover = discoverRespFrom(h.recSettings.Discover())
|
out.Discover = discoverRespFrom(h.recSettings.Discover())
|
||||||
out.Shipped.Profiles = map[string]weightsResp{
|
out.Shipped.Profiles = map[string]weightsResp{
|
||||||
recsettings.ScopeRadio: weightsRespFrom(recsettings.ShippedRadioWeights()),
|
recsettings.ScopeRadio: weightsRespFrom(recsettings.ShippedRadioWeights()),
|
||||||
recsettings.ScopeDailyMix: weightsRespFrom(recsettings.ShippedDailyMixWeights()),
|
recsettings.ScopeDailyMix: weightsRespFrom(recsettings.ShippedDailyMixWeights()),
|
||||||
recsettings.ScopeSongsLike: weightsRespFrom(recsettings.ShippedSongsLikeWeights()),
|
|
||||||
}
|
}
|
||||||
out.Shipped.Taste = tasteRespFrom(recsettings.ShippedTasteTuning())
|
out.Shipped.Taste = tasteRespFrom(recsettings.ShippedTasteTuning())
|
||||||
out.Shipped.Discover = discoverRespFrom(recsettings.ShippedDiscoverTuning())
|
out.Shipped.Discover = discoverRespFrom(recsettings.ShippedDiscoverTuning())
|
||||||
|
|||||||
@@ -23,17 +23,15 @@ type removeTrackResponse struct {
|
|||||||
|
|
||||||
// handleRemoveTrack implements DELETE /api/admin/tracks/{id}?unmonitor=true|false.
|
// handleRemoveTrack implements DELETE /api/admin/tracks/{id}?unmonitor=true|false.
|
||||||
//
|
//
|
||||||
// Admin-only (gated by auth.RequireAdmin on the /admin route group). Deletes the
|
// Admin-only (gated by auth.RequireAdmin on the /admin route group). Always
|
||||||
// file, then the DB row, and runs the album/artist cascade tidy-up — and deletes
|
// deletes the file + DB row and runs the album/artist cascade tidy-up. When
|
||||||
// nothing at all when the file cannot be removed (#3918). When
|
|
||||||
// unmonitor=true and the track has an mbid, also calls Lidarr.UnmonitorTrack
|
// unmonitor=true and the track has an mbid, also calls Lidarr.UnmonitorTrack
|
||||||
// — failure there is non-fatal (the destructive part already completed) and
|
// — failure there is non-fatal (the destructive part already completed) and
|
||||||
// surfaces as `lidarr_unmonitor_failed: true` in the success envelope.
|
// surfaces as `lidarr_unmonitor_failed: true` in the success envelope.
|
||||||
//
|
//
|
||||||
// Per spec §5, Lidarr-side errors during the unmonitor step do NOT map to
|
// Per spec §5, Lidarr-side errors during the unmonitor step do NOT map to
|
||||||
// wire error codes. The codes this handler emits are not_found,
|
// wire error codes; the only error codes this handler emits are not_found,
|
||||||
// library_not_writable (409) and file_delete_failed when the file could not be
|
// server_error, plus the auth codes the middleware emits upstream.
|
||||||
// removed, server_error, plus the auth codes the middleware emits upstream.
|
|
||||||
func (h *handlers) handleRemoveTrack(w http.ResponseWriter, r *http.Request) {
|
func (h *handlers) handleRemoveTrack(w http.ResponseWriter, r *http.Request) {
|
||||||
idStr := chi.URLParam(r, "id")
|
idStr := chi.URLParam(r, "id")
|
||||||
trackID, ok := parseUUID(idStr)
|
trackID, ok := parseUUID(idStr)
|
||||||
@@ -68,11 +66,6 @@ func (h *handlers) handleRemoveTrack(w http.ResponseWriter, r *http.Request) {
|
|||||||
writeErr(w, &apierror.Error{Status: http.StatusNotFound, Code: "not_found", Message: "track not found"})
|
writeErr(w, &apierror.Error{Status: http.StatusNotFound, Code: "not_found", Message: "track not found"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if apiErr, ok := fileRemoveAPIError(err); ok {
|
|
||||||
logFileRemoveFailure(h.logger, apiErr, "track_id", idStr)
|
|
||||||
writeErr(w, apiErr)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
h.logger.Error("api: remove track failed", "err", err, "track_id", idStr)
|
h.logger.Error("api: remove track failed", "err", err, "track_id", idStr)
|
||||||
writeErr(w, apierror.InternalMsg("remove failed", err))
|
writeErr(w, apierror.InternalMsg("remove failed", err))
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -169,7 +169,7 @@ func (h *handlers) handleAdminCreateUser(w http.ResponseWriter, r *http.Request)
|
|||||||
user, err := q.CreateUserAdmin(r.Context(), dbq.CreateUserAdminParams{
|
user, err := q.CreateUserAdmin(r.Context(), dbq.CreateUserAdminParams{
|
||||||
Username: req.Username,
|
Username: req.Username,
|
||||||
PasswordHash: string(hash),
|
PasswordHash: string(hash),
|
||||||
ApiTokenHash: auth.HashAPIToken(apiToken),
|
ApiToken: apiToken,
|
||||||
IsAdmin: req.IsAdmin,
|
IsAdmin: req.IsAdmin,
|
||||||
DisplayName: req.DisplayName,
|
DisplayName: req.DisplayName,
|
||||||
})
|
})
|
||||||
@@ -285,19 +285,6 @@ func (h *handlers) handleAdminResetPassword(w http.ResponseWriter, r *http.Reque
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// The target's existing sessions end with the old password. An admin
|
|
||||||
// resetting their own password keeps the session they're using, the
|
|
||||||
// same as a self-service change.
|
|
||||||
sessID, ownSession := auth.SessionIDFromContext(r.Context())
|
|
||||||
if targetID == caller.ID && ownSession {
|
|
||||||
_, err = q.DeleteOtherSessionsForUser(r.Context(), dbq.DeleteOtherSessionsForUserParams{UserID: targetID, ID: sessID})
|
|
||||||
} else {
|
|
||||||
_, err = q.DeleteSessionsForUser(r.Context(), targetID)
|
|
||||||
}
|
|
||||||
if err != nil {
|
|
||||||
h.logger.Error("admin reset password: revoke sessions failed", "err", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
audit.WriteOrLog(r.Context(), h.pool, h.logger, caller.ID, targetID, audit.ActionPasswordResetAdmin, nil)
|
audit.WriteOrLog(r.Context(), h.pool, h.logger, caller.ID, targetID, audit.ActionPasswordResetAdmin, nil)
|
||||||
|
|
||||||
w.WriteHeader(http.StatusNoContent)
|
w.WriteHeader(http.StatusNoContent)
|
||||||
|
|||||||
+27
-77
@@ -7,7 +7,6 @@ package api
|
|||||||
import (
|
import (
|
||||||
"log/slog"
|
"log/slog"
|
||||||
"math/rand"
|
"math/rand"
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/go-chi/chi/v5"
|
"github.com/go-chi/chi/v5"
|
||||||
"github.com/jackc/pgx/v5/pgxpool"
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
@@ -25,7 +24,6 @@ import (
|
|||||||
"git.fabledsword.com/bvandeusen/minstrel/internal/playevents"
|
"git.fabledsword.com/bvandeusen/minstrel/internal/playevents"
|
||||||
"git.fabledsword.com/bvandeusen/minstrel/internal/playlists"
|
"git.fabledsword.com/bvandeusen/minstrel/internal/playlists"
|
||||||
"git.fabledsword.com/bvandeusen/minstrel/internal/reacquisition"
|
"git.fabledsword.com/bvandeusen/minstrel/internal/reacquisition"
|
||||||
"git.fabledsword.com/bvandeusen/minstrel/internal/recommendation"
|
|
||||||
"git.fabledsword.com/bvandeusen/minstrel/internal/recsettings"
|
"git.fabledsword.com/bvandeusen/minstrel/internal/recsettings"
|
||||||
"git.fabledsword.com/bvandeusen/minstrel/internal/tags"
|
"git.fabledsword.com/bvandeusen/minstrel/internal/tags"
|
||||||
"git.fabledsword.com/bvandeusen/minstrel/internal/tracks"
|
"git.fabledsword.com/bvandeusen/minstrel/internal/tracks"
|
||||||
@@ -34,51 +32,34 @@ import (
|
|||||||
// Mount attaches /api/* handlers to r. Public endpoints (login) are outside
|
// Mount attaches /api/* handlers to r. Public endpoints (login) are outside
|
||||||
// RequireUser; everything else is gated by the middleware. The events writer
|
// RequireUser; everything else is gated by the middleware. The events writer
|
||||||
// is shared with the Subsonic mount so /rest/scrobble feeds the same store.
|
// is shared with the Subsonic mount so /rest/scrobble feeds the same store.
|
||||||
func Mount(r chi.Router, pool *pgxpool.Pool, logger *slog.Logger, events *playevents.Writer, recCfg config.RecommendationConfig, recSettings *recsettings.Service, lidarrCfg *lidarrconfig.Service, lidarrReqs *lidarrrequests.Service, lidarrQuar *lidarrquarantine.Service, tracksSvc *tracks.Service, playlistsSvc *playlists.Service, coverEnricher *coverart.Enricher, coverSettings *coverart.SettingsService, tagSettings *tags.SettingsService, scanner *library.Scanner, scanCfg library.RunScanConfig, dataDir string, sender mailer.Sender, bus *eventbus.Bus, playlistScheduler *playlists.Scheduler, streamSecret []byte, netSettings *netsettings.Service, reacqSettings *reacquisition.SettingsService, fpSettings *library.FingerprintSettingsService) {
|
func Mount(r chi.Router, pool *pgxpool.Pool, logger *slog.Logger, events *playevents.Writer, recCfg config.RecommendationConfig, recSettings *recsettings.Service, lidarrCfg *lidarrconfig.Service, lidarrReqs *lidarrrequests.Service, lidarrQuar *lidarrquarantine.Service, tracksSvc *tracks.Service, playlistsSvc *playlists.Service, coverEnricher *coverart.Enricher, coverSettings *coverart.SettingsService, tagSettings *tags.SettingsService, scanner *library.Scanner, scanCfg library.RunScanConfig, dataDir string, sender mailer.Sender, bus *eventbus.Bus, playlistScheduler *playlists.Scheduler, streamSecret []byte, netSettings *netsettings.Service, reacqSettings *reacquisition.SettingsService) {
|
||||||
rng := rand.New(rand.NewSource(rand.Int63()))
|
rng := rand.New(rand.NewSource(rand.Int63()))
|
||||||
setupToken, err := auth.NewSetupToken()
|
|
||||||
if err != nil {
|
|
||||||
// crypto/rand failing means the platform can't make secrets at all;
|
|
||||||
// sessions would be minted from the same source. Nothing to degrade to.
|
|
||||||
panic("api: mint setup token: " + err.Error())
|
|
||||||
}
|
|
||||||
logSetupTokenIfNeeded(pool, logger, setupToken)
|
|
||||||
h := &handlers{
|
h := &handlers{
|
||||||
pool: pool, logger: logger, events: events, recCfg: recCfg,
|
pool: pool, logger: logger, events: events, recCfg: recCfg,
|
||||||
recSettings: recSettings,
|
recSettings: recSettings,
|
||||||
rng: rng.Float64,
|
rng: rng.Float64,
|
||||||
lidarrCfg: lidarrCfg,
|
lidarrCfg: lidarrCfg,
|
||||||
lidarrRequests: lidarrReqs,
|
lidarrRequests: lidarrReqs,
|
||||||
lidarrQuarantine: lidarrQuar,
|
lidarrQuarantine: lidarrQuar,
|
||||||
tracks: tracksSvc,
|
tracks: tracksSvc,
|
||||||
playlists: playlistsSvc,
|
playlists: playlistsSvc,
|
||||||
coverart: coverEnricher,
|
coverart: coverEnricher,
|
||||||
coverSettings: coverSettings,
|
coverSettings: coverSettings,
|
||||||
tagSettings: tagSettings,
|
tagSettings: tagSettings,
|
||||||
scanner: scanner,
|
scanner: scanner,
|
||||||
scanCfg: scanCfg,
|
scanCfg: scanCfg,
|
||||||
dataDir: dataDir,
|
dataDir: dataDir,
|
||||||
mailer: sender,
|
mailer: sender,
|
||||||
eventbus: bus,
|
eventbus: bus,
|
||||||
playlistScheduler: playlistScheduler,
|
playlistScheduler: playlistScheduler,
|
||||||
streamSecret: streamSecret,
|
streamSecret: streamSecret,
|
||||||
netSettings: netSettings,
|
netSettings: netSettings,
|
||||||
reacqSettings: reacqSettings,
|
reacqSettings: reacqSettings,
|
||||||
fingerprintSettings: fpSettings,
|
|
||||||
librarySize: recommendation.NewLibrarySize(nil),
|
|
||||||
loginGuard: auth.NewLoginGuard(),
|
|
||||||
setupToken: setupToken,
|
|
||||||
requireSetupToken: true,
|
|
||||||
registerLimit: auth.NewAttemptLimiter(registerPerAddressMax, time.Hour),
|
|
||||||
forgotAddressLimit: auth.NewAttemptLimiter(forgotPerAddressMax, time.Hour),
|
|
||||||
forgotEmailLimit: auth.NewAttemptLimiter(forgotPerEmailMax, time.Hour),
|
|
||||||
resetLimit: auth.NewAttemptLimiter(resetFailuresPerAddressMax, 15*time.Minute),
|
|
||||||
}
|
}
|
||||||
|
|
||||||
r.Route("/api", func(api chi.Router) {
|
r.Route("/api", func(api chi.Router) {
|
||||||
api.Post("/auth/login", h.handleLogin)
|
api.Post("/auth/login", h.handleLogin)
|
||||||
api.Post("/auth/register", h.handleRegister)
|
api.Post("/auth/register", h.handleRegister)
|
||||||
api.Get("/auth/setup-status", h.handleSetupStatus)
|
|
||||||
api.Post("/auth/forgot-password", h.handleForgotPassword)
|
api.Post("/auth/forgot-password", h.handleForgotPassword)
|
||||||
api.Post("/auth/reset-password", h.handleResetPassword)
|
api.Post("/auth/reset-password", h.handleResetPassword)
|
||||||
|
|
||||||
@@ -108,6 +89,7 @@ func Mount(r chi.Router, pool *pgxpool.Pool, logger *slog.Logger, events *playev
|
|||||||
authed.Put("/me/password", h.handleChangePassword)
|
authed.Put("/me/password", h.handleChangePassword)
|
||||||
authed.Put("/me/profile", h.handleUpdateMyProfile)
|
authed.Put("/me/profile", h.handleUpdateMyProfile)
|
||||||
authed.Put("/me/timezone", h.handlePutTimezone)
|
authed.Put("/me/timezone", h.handlePutTimezone)
|
||||||
|
authed.Get("/me/api-token", h.handleGetMyAPIToken)
|
||||||
authed.Post("/me/api-token", h.handleRegenerateMyAPIToken)
|
authed.Post("/me/api-token", h.handleRegenerateMyAPIToken)
|
||||||
authed.Get("/me/sessions", h.handleListMySessions)
|
authed.Get("/me/sessions", h.handleListMySessions)
|
||||||
authed.Delete("/me/sessions/{id}", h.handleRevokeMySession)
|
authed.Delete("/me/sessions/{id}", h.handleRevokeMySession)
|
||||||
@@ -231,16 +213,6 @@ func Mount(r chi.Router, pool *pgxpool.Pool, logger *slog.Logger, events *playev
|
|||||||
admin.Get("/library/missing", h.handleListMissingTracks)
|
admin.Get("/library/missing", h.handleListMissingTracks)
|
||||||
|
|
||||||
admin.Get("/library/coverage", h.handleGetLibraryCoverage)
|
admin.Get("/library/coverage", h.handleGetLibraryCoverage)
|
||||||
admin.Get("/library/fingerprints", h.handleGetFingerprintCoverage)
|
|
||||||
admin.Get("/library/fingerprint-settings", h.handleGetFingerprintSettings)
|
|
||||||
admin.Put("/library/fingerprint-settings", h.handleUpdateFingerprintSettings)
|
|
||||||
// Duplicates report (#3912): proposals from the duplicate sweep, a
|
|
||||||
// trigger to sweep now, dismissal, and the merge (#3911), which deletes
|
|
||||||
// the removed copies' files after moving their history onto the kept one.
|
|
||||||
admin.Get("/library/duplicates", h.handleListDuplicates)
|
|
||||||
admin.Post("/library/duplicates/sweep", h.handleRunDuplicateSweep)
|
|
||||||
admin.Post("/library/duplicates/{id}/dismiss", h.handleDismissDuplicateGroup)
|
|
||||||
admin.Post("/library/duplicates/{id}/merge", h.handleMergeDuplicateGroup)
|
|
||||||
|
|
||||||
admin.Get("/invites", h.handleListInvites)
|
admin.Get("/invites", h.handleListInvites)
|
||||||
admin.Post("/invites", h.handleCreateInvite)
|
admin.Post("/invites", h.handleCreateInvite)
|
||||||
@@ -296,16 +268,12 @@ func Mount(r chi.Router, pool *pgxpool.Pool, logger *slog.Logger, events *playev
|
|||||||
}
|
}
|
||||||
|
|
||||||
type handlers struct {
|
type handlers struct {
|
||||||
pool *pgxpool.Pool
|
pool *pgxpool.Pool
|
||||||
logger *slog.Logger
|
logger *slog.Logger
|
||||||
events *playevents.Writer
|
events *playevents.Writer
|
||||||
recCfg config.RecommendationConfig
|
recCfg config.RecommendationConfig
|
||||||
recSettings *recsettings.Service
|
recSettings *recsettings.Service
|
||||||
rng func() float64
|
rng func() float64
|
||||||
// librarySize memoises the track count that sizes the candidate pool
|
|
||||||
// (#3880). Held here rather than counted per request: the count is a
|
|
||||||
// full table scan, and library size only moves when a scan runs.
|
|
||||||
librarySize *recommendation.LibrarySize
|
|
||||||
lidarrCfg *lidarrconfig.Service
|
lidarrCfg *lidarrconfig.Service
|
||||||
lidarrRequests *lidarrrequests.Service
|
lidarrRequests *lidarrrequests.Service
|
||||||
lidarrQuarantine *lidarrquarantine.Service
|
lidarrQuarantine *lidarrquarantine.Service
|
||||||
@@ -324,24 +292,6 @@ type handlers struct {
|
|||||||
// missing files (milestone #290) — grace window, backoff, attempt caps.
|
// missing files (milestone #290) — grace window, backoff, attempt caps.
|
||||||
// Cached in the service, so the admin card reads it without a query.
|
// Cached in the service, so the admin card reads it without a query.
|
||||||
reacqSettings *reacquisition.SettingsService
|
reacqSettings *reacquisition.SettingsService
|
||||||
// fingerprintSettings is the fingerprinting policy (M400 #3913), the same
|
|
||||||
// instance the scanner and the fingerprint workers read, so a save from the
|
|
||||||
// admin card reaches them without a restart. Nil serves the defaults.
|
|
||||||
fingerprintSettings *library.FingerprintSettingsService
|
|
||||||
// setupToken must accompany the first registration while no users exist
|
|
||||||
// (see auth.SetupToken). requireSetupToken is set by Mount, the only
|
|
||||||
// production constructor; tests that build handlers directly leave it
|
|
||||||
// off unless they are testing it.
|
|
||||||
setupToken *auth.SetupToken
|
|
||||||
requireSetupToken bool
|
|
||||||
// loginGuard throttles failed logins per account and per address, and
|
|
||||||
// the limiters below cap the other unauthenticated auth routes. All are
|
|
||||||
// nil-safe, so tests that build handlers directly run unthrottled.
|
|
||||||
loginGuard *auth.LoginGuard
|
|
||||||
registerLimit *auth.AttemptLimiter
|
|
||||||
forgotAddressLimit *auth.AttemptLimiter
|
|
||||||
forgotEmailLimit *auth.AttemptLimiter
|
|
||||||
resetLimit *auth.AttemptLimiter
|
|
||||||
// netSettings caches the trusted reverse-proxy depth read by the auth
|
// netSettings caches the trusted reverse-proxy depth read by the auth
|
||||||
// middleware on every request and edited from the admin network card.
|
// middleware on every request and edited from the admin network card.
|
||||||
netSettings *netsettings.Service
|
netSettings *netsettings.Service
|
||||||
|
|||||||
+2
-30
@@ -19,20 +19,6 @@ import (
|
|||||||
// so an abandoned laptop doesn't stay logged in forever.
|
// so an abandoned laptop doesn't stay logged in forever.
|
||||||
const sessionCookieMaxAge = 30 * 24 * time.Hour
|
const sessionCookieMaxAge = 30 * 24 * time.Hour
|
||||||
|
|
||||||
// Limits on the unauthenticated auth routes other than login (which uses
|
|
||||||
// auth.LoginGuard). Per address, per window as wired in Mount.
|
|
||||||
const (
|
|
||||||
// registerPerAddressMax: 10 registrations an hour. Every attempt counts,
|
|
||||||
// typos included, which is still far above a household's need.
|
|
||||||
registerPerAddressMax = 10
|
|
||||||
// forgotPerAddressMax / forgotPerEmailMax: reset emails an hour. The
|
|
||||||
// per-email cap is what keeps one inbox from being mailbombed.
|
|
||||||
forgotPerAddressMax = 5
|
|
||||||
forgotPerEmailMax = 3
|
|
||||||
// resetFailuresPerAddressMax: wrong or expired reset tokens per 15 min.
|
|
||||||
resetFailuresPerAddressMax = 20
|
|
||||||
)
|
|
||||||
|
|
||||||
func (h *handlers) handleLogout(w http.ResponseWriter, r *http.Request) {
|
func (h *handlers) handleLogout(w http.ResponseWriter, r *http.Request) {
|
||||||
// The session token can be on the cookie OR bearer header — RequireUser
|
// The session token can be on the cookie OR bearer header — RequireUser
|
||||||
// accepted either. Re-resolve it here so we can delete the row.
|
// accepted either. Re-resolve it here so we can delete the row.
|
||||||
@@ -84,22 +70,10 @@ func (h *handlers) handleLogin(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Checked before any lookup or bcrypt, so a throttled guess costs the
|
|
||||||
// server nothing and learns nothing.
|
|
||||||
addr := auth.ClientIP(r, h.netSettings.Hops())
|
|
||||||
if blocked, wait := h.loginGuard.Blocked(req.Username, addr); blocked {
|
|
||||||
writeRateLimited(w, wait)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
q := dbq.New(h.pool)
|
q := dbq.New(h.pool)
|
||||||
user, err := q.GetUserByUsername(r.Context(), req.Username)
|
user, err := q.GetUserByUsername(r.Context(), req.Username)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if errors.Is(err, pgx.ErrNoRows) {
|
if errors.Is(err, pgx.ErrNoRows) {
|
||||||
// Same bcrypt time as a wrong password, so timing doesn't say
|
|
||||||
// which usernames exist.
|
|
||||||
auth.DummyVerify(req.Password)
|
|
||||||
h.loginGuard.Fail(req.Username, addr)
|
|
||||||
writeErr(w, apierror.Unauthorized("invalid_credentials", "invalid username or password"))
|
writeErr(w, apierror.Unauthorized("invalid_credentials", "invalid username or password"))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -108,11 +82,9 @@ func (h *handlers) handleLogin(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
if !auth.VerifyPassword(user.PasswordHash, req.Password) {
|
if !auth.VerifyPassword(user.PasswordHash, req.Password) {
|
||||||
h.loginGuard.Fail(req.Username, addr)
|
|
||||||
writeErr(w, apierror.Unauthorized("invalid_credentials", "invalid username or password"))
|
writeErr(w, apierror.Unauthorized("invalid_credentials", "invalid username or password"))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
h.loginGuard.Succeed(req.Username)
|
|
||||||
|
|
||||||
token, err := auth.MintSessionToken()
|
token, err := auth.MintSessionToken()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -128,7 +100,7 @@ func (h *handlers) handleLogin(w http.ResponseWriter, r *http.Request) {
|
|||||||
// the active-sessions surface: a session that was born somewhere the
|
// the active-sessions surface: a session that was born somewhere the
|
||||||
// user recognises but is being used from somewhere they don't is the
|
// user recognises but is being used from somewhere they don't is the
|
||||||
// case this whole surface exists to surface.
|
// case this whole surface exists to surface.
|
||||||
Ip: addr,
|
Ip: auth.ClientIP(r, h.netSettings.Hops()),
|
||||||
}); err != nil {
|
}); err != nil {
|
||||||
h.logger.Error("api: insert session failed", "err", err)
|
h.logger.Error("api: insert session failed", "err", err)
|
||||||
writeErr(w, apierror.InternalMsg("insert failed", err))
|
writeErr(w, apierror.InternalMsg("insert failed", err))
|
||||||
@@ -140,7 +112,7 @@ func (h *handlers) handleLogin(w http.ResponseWriter, r *http.Request) {
|
|||||||
Value: token,
|
Value: token,
|
||||||
Path: "/",
|
Path: "/",
|
||||||
HttpOnly: true,
|
HttpOnly: true,
|
||||||
Secure: auth.IsHTTPS(r, h.netSettings.Hops()), // plain HTTP and LAN stay functional (rule 94)
|
Secure: r.TLS != nil, // dev over http stays functional; prod over https gets Secure
|
||||||
SameSite: http.SameSiteStrictMode,
|
SameSite: http.SameSiteStrictMode,
|
||||||
MaxAge: int(sessionCookieMaxAge.Seconds()),
|
MaxAge: int(sessionCookieMaxAge.Seconds()),
|
||||||
})
|
})
|
||||||
|
|||||||
+12
-33
@@ -14,7 +14,6 @@ import (
|
|||||||
"github.com/jackc/pgx/v5/pgtype"
|
"github.com/jackc/pgx/v5/pgtype"
|
||||||
|
|
||||||
"git.fabledsword.com/bvandeusen/minstrel/internal/audit"
|
"git.fabledsword.com/bvandeusen/minstrel/internal/audit"
|
||||||
"git.fabledsword.com/bvandeusen/minstrel/internal/auth"
|
|
||||||
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
|
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
|
||||||
"git.fabledsword.com/bvandeusen/minstrel/internal/mailer"
|
"git.fabledsword.com/bvandeusen/minstrel/internal/mailer"
|
||||||
)
|
)
|
||||||
@@ -48,19 +47,6 @@ func (h *handlers) handleForgotPassword(w http.ResponseWriter, r *http.Request)
|
|||||||
}
|
}
|
||||||
email := strings.ToLower(strings.TrimSpace(req.Email))
|
email := strings.ToLower(strings.TrimSpace(req.Email))
|
||||||
|
|
||||||
// Throttled per address (a spray) and per email (a mailbomb of one
|
|
||||||
// inbox). Applied whether or not the email matches, so a 429 says
|
|
||||||
// nothing about which addresses are registered.
|
|
||||||
addr := auth.ClientIP(r, h.netSettings.Hops())
|
|
||||||
blockedAddr, waitAddr := h.forgotAddressLimit.Blocked(addr)
|
|
||||||
blockedEmail, waitEmail := h.forgotEmailLimit.Blocked(email)
|
|
||||||
if blockedAddr || blockedEmail {
|
|
||||||
writeRateLimited(w, max(waitAddr, waitEmail))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
h.forgotAddressLimit.Record(addr)
|
|
||||||
h.forgotEmailLimit.Record(email)
|
|
||||||
|
|
||||||
q := dbq.New(h.pool)
|
q := dbq.New(h.pool)
|
||||||
var matched bool
|
var matched bool
|
||||||
var auditTarget pgtype.UUID
|
var auditTarget pgtype.UUID
|
||||||
@@ -69,7 +55,7 @@ func (h *handlers) handleForgotPassword(w http.ResponseWriter, r *http.Request)
|
|||||||
if err == nil && user.Email != nil && *user.Email != "" {
|
if err == nil && user.Email != nil && *user.Email != "" {
|
||||||
matched = true
|
matched = true
|
||||||
auditTarget = user.ID
|
auditTarget = user.ID
|
||||||
if sendErr := h.sendResetEmail(r.Context(), user); sendErr != nil {
|
if sendErr := h.sendResetEmail(r.Context(), r, user); sendErr != nil {
|
||||||
h.logger.Warn("forgot-password: send failed",
|
h.logger.Warn("forgot-password: send failed",
|
||||||
"email", email, "err", sendErr)
|
"email", email, "err", sendErr)
|
||||||
// fall through; response is still 200
|
// fall through; response is still 200
|
||||||
@@ -89,7 +75,7 @@ func (h *handlers) handleForgotPassword(w http.ResponseWriter, r *http.Request)
|
|||||||
// sendResetEmail generates a token, persists it, renders + sends the
|
// sendResetEmail generates a token, persists it, renders + sends the
|
||||||
// email. Returns the underlying error (caller logs it but doesn't
|
// email. Returns the underlying error (caller logs it but doesn't
|
||||||
// surface to the HTTP response).
|
// surface to the HTTP response).
|
||||||
func (h *handlers) sendResetEmail(ctx context.Context, user dbq.User) error {
|
func (h *handlers) sendResetEmail(ctx context.Context, r *http.Request, user dbq.User) error {
|
||||||
if h.mailer == nil {
|
if h.mailer == nil {
|
||||||
return errors.New("forgot-password: no mailer configured")
|
return errors.New("forgot-password: no mailer configured")
|
||||||
}
|
}
|
||||||
@@ -109,10 +95,7 @@ func (h *handlers) sendResetEmail(ctx context.Context, user dbq.User) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
resetURL, err := buildResetURL(h.netSettings.PublicURL(), token)
|
resetURL := buildResetURL(r, token)
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
textBody, htmlBody, err := mailer.RenderResetEmail(mailer.ResetEmailVars{
|
textBody, htmlBody, err := mailer.RenderResetEmail(mailer.ResetEmailVars{
|
||||||
Username: user.Username,
|
Username: user.Username,
|
||||||
ResetURL: resetURL,
|
ResetURL: resetURL,
|
||||||
@@ -130,18 +113,14 @@ func (h *handlers) sendResetEmail(ctx context.Context, user dbq.User) error {
|
|||||||
return h.mailer.Send(ctx, *user.Email, mailer.ResetEmailSubject, textBody, htmlBody)
|
return h.mailer.Send(ctx, *user.Email, mailer.ResetEmailSubject, textBody, htmlBody)
|
||||||
}
|
}
|
||||||
|
|
||||||
// errNoPublicURL stops a reset email from going out before the operator has
|
func buildResetURL(r *http.Request, token string) string {
|
||||||
// said where Minstrel lives. It surfaces in the log, not the response, which
|
scheme := "http"
|
||||||
// stays the same opaque 200 either way.
|
if r.TLS != nil {
|
||||||
var errNoPublicURL = errors.New("forgot-password: no public URL set (Admin → Integrations → Public address); reset email not sent")
|
scheme = "https"
|
||||||
|
|
||||||
// buildResetURL builds the emailed link from the operator-set public URL.
|
|
||||||
// It deliberately ignores the request: the Host header is whatever the
|
|
||||||
// requester sent, and building from it let a forged Host plant a real reset
|
|
||||||
// token on a link to someone else's server.
|
|
||||||
func buildResetURL(publicURL, token string) (string, error) {
|
|
||||||
if publicURL == "" {
|
|
||||||
return "", errNoPublicURL
|
|
||||||
}
|
}
|
||||||
return publicURL + "/reset-password/" + token, nil
|
host := r.Host
|
||||||
|
if host == "" {
|
||||||
|
host = "localhost"
|
||||||
|
}
|
||||||
|
return scheme + "://" + host + "/reset-password/" + token
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,59 +7,11 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
"net/http/httptest"
|
"net/http/httptest"
|
||||||
"os"
|
"os"
|
||||||
"strings"
|
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/jackc/pgx/v5/pgxpool"
|
|
||||||
|
|
||||||
"git.fabledsword.com/bvandeusen/minstrel/internal/mailer"
|
"git.fabledsword.com/bvandeusen/minstrel/internal/mailer"
|
||||||
"git.fabledsword.com/bvandeusen/minstrel/internal/netsettings"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// withPublicURL gives h a network-settings service holding url, restoring an
|
|
||||||
// empty value afterwards so other tests see the default.
|
|
||||||
func withPublicURL(t *testing.T, h *handlers, pool *pgxpool.Pool, url string) {
|
|
||||||
t.Helper()
|
|
||||||
ns, err := netsettings.New(context.Background(), pool, nil)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("netsettings: %v", err)
|
|
||||||
}
|
|
||||||
if err := ns.SetPublicURL(context.Background(), url); err != nil {
|
|
||||||
t.Fatalf("set public url: %v", err)
|
|
||||||
}
|
|
||||||
t.Cleanup(func() { _ = ns.SetPublicURL(context.Background(), "") })
|
|
||||||
h.netSettings = ns
|
|
||||||
}
|
|
||||||
|
|
||||||
// With no public URL set, a reset email is not sent at all, and the response
|
|
||||||
// is still the same opaque 200.
|
|
||||||
func TestForgotPassword_NoPublicURL_SendsNothing(t *testing.T) {
|
|
||||||
if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" {
|
|
||||||
t.Skip("MINSTREL_TEST_DATABASE_URL not set")
|
|
||||||
}
|
|
||||||
h, pool := testHandlers(t)
|
|
||||||
fake := &mailer.FakeSender{}
|
|
||||||
h.mailer = fake
|
|
||||||
withPublicURL(t, h, pool, "")
|
|
||||||
|
|
||||||
user := seedUser(t, pool, "nourl", "pw", false)
|
|
||||||
if _, err := pool.Exec(context.Background(),
|
|
||||||
"UPDATE users SET email = 'nourl@example.com' WHERE id = $1", user.ID); err != nil {
|
|
||||||
t.Fatalf("seed email: %v", err)
|
|
||||||
}
|
|
||||||
req := httptest.NewRequest(http.MethodPost, "/api/auth/forgot-password",
|
|
||||||
bytes.NewReader([]byte(`{"email":"nourl@example.com"}`)))
|
|
||||||
rec := httptest.NewRecorder()
|
|
||||||
h.handleForgotPassword(rec, req)
|
|
||||||
|
|
||||||
if rec.Code != http.StatusOK {
|
|
||||||
t.Errorf("status = %d, want 200", rec.Code)
|
|
||||||
}
|
|
||||||
if len(fake.Sent) != 0 {
|
|
||||||
t.Errorf("sent %d emails with no public URL set, want 0", len(fake.Sent))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestForgotPassword_KnownEmail_SendsMail(t *testing.T) {
|
func TestForgotPassword_KnownEmail_SendsMail(t *testing.T) {
|
||||||
if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" {
|
if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" {
|
||||||
t.Skip("MINSTREL_TEST_DATABASE_URL not set")
|
t.Skip("MINSTREL_TEST_DATABASE_URL not set")
|
||||||
@@ -67,7 +19,6 @@ func TestForgotPassword_KnownEmail_SendsMail(t *testing.T) {
|
|||||||
h, pool := testHandlers(t)
|
h, pool := testHandlers(t)
|
||||||
fake := &mailer.FakeSender{}
|
fake := &mailer.FakeSender{}
|
||||||
h.mailer = fake
|
h.mailer = fake
|
||||||
withPublicURL(t, h, pool, "https://music.example.com")
|
|
||||||
|
|
||||||
user := seedUser(t, pool, "forgotuser", "pw", false)
|
user := seedUser(t, pool, "forgotuser", "pw", false)
|
||||||
if _, err := pool.Exec(context.Background(),
|
if _, err := pool.Exec(context.Background(),
|
||||||
@@ -78,8 +29,7 @@ func TestForgotPassword_KnownEmail_SendsMail(t *testing.T) {
|
|||||||
body := `{"email":"forgot@example.com"}`
|
body := `{"email":"forgot@example.com"}`
|
||||||
req := httptest.NewRequest(http.MethodPost, "/api/auth/forgot-password",
|
req := httptest.NewRequest(http.MethodPost, "/api/auth/forgot-password",
|
||||||
bytes.NewReader([]byte(body)))
|
bytes.NewReader([]byte(body)))
|
||||||
// A forged Host must not reach the link: it comes from the public URL.
|
req.Host = "minstrel.example.com"
|
||||||
req.Host = "attacker.example.net"
|
|
||||||
rec := httptest.NewRecorder()
|
rec := httptest.NewRecorder()
|
||||||
h.handleForgotPassword(rec, req)
|
h.handleForgotPassword(rec, req)
|
||||||
|
|
||||||
@@ -93,12 +43,6 @@ func TestForgotPassword_KnownEmail_SendsMail(t *testing.T) {
|
|||||||
if got.To != "forgot@example.com" {
|
if got.To != "forgot@example.com" {
|
||||||
t.Errorf("To = %q, want forgot@example.com", got.To)
|
t.Errorf("To = %q, want forgot@example.com", got.To)
|
||||||
}
|
}
|
||||||
if !strings.Contains(got.TextBody, "https://music.example.com/reset-password/") {
|
|
||||||
t.Errorf("reset link not built from the public URL:\n%s", got.TextBody)
|
|
||||||
}
|
|
||||||
if strings.Contains(got.TextBody+got.HTMLBody, "attacker.example.net") {
|
|
||||||
t.Error("the request's Host header reached the emailed link")
|
|
||||||
}
|
|
||||||
// Token row was inserted.
|
// Token row was inserted.
|
||||||
var tokenCount int
|
var tokenCount int
|
||||||
if err := pool.QueryRow(context.Background(),
|
if err := pool.QueryRow(context.Background(),
|
||||||
|
|||||||
@@ -1,10 +1,8 @@
|
|||||||
package api
|
package api
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"log/slog"
|
|
||||||
"net/http"
|
"net/http"
|
||||||
"regexp"
|
"regexp"
|
||||||
"time"
|
"time"
|
||||||
@@ -12,7 +10,6 @@ import (
|
|||||||
"github.com/jackc/pgerrcode"
|
"github.com/jackc/pgerrcode"
|
||||||
"github.com/jackc/pgx/v5"
|
"github.com/jackc/pgx/v5"
|
||||||
"github.com/jackc/pgx/v5/pgconn"
|
"github.com/jackc/pgx/v5/pgconn"
|
||||||
"github.com/jackc/pgx/v5/pgxpool"
|
|
||||||
"golang.org/x/crypto/bcrypt"
|
"golang.org/x/crypto/bcrypt"
|
||||||
|
|
||||||
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
|
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
|
||||||
@@ -29,12 +26,9 @@ var usernameRe = regexp.MustCompile(`^[a-zA-Z0-9_-]{3,32}$`)
|
|||||||
const minPasswordLength = 8
|
const minPasswordLength = 8
|
||||||
|
|
||||||
type registerReq struct {
|
type registerReq struct {
|
||||||
Username string `json:"username"`
|
Username string `json:"username"`
|
||||||
Password string `json:"password"`
|
Password string `json:"password"`
|
||||||
InviteToken string `json:"invite_token"`
|
InviteToken string `json:"invite_token"`
|
||||||
// SetupToken is required only for the very first account; see
|
|
||||||
// auth.SetupToken.
|
|
||||||
SetupToken string `json:"setup_token"`
|
|
||||||
DisplayName *string `json:"display_name"`
|
DisplayName *string `json:"display_name"`
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -61,15 +55,6 @@ type registerReq struct {
|
|||||||
// - 409 username_taken (PG unique violation on users.username)
|
// - 409 username_taken (PG unique violation on users.username)
|
||||||
// - 500 server_error otherwise
|
// - 500 server_error otherwise
|
||||||
func (h *handlers) handleRegister(w http.ResponseWriter, r *http.Request) {
|
func (h *handlers) handleRegister(w http.ResponseWriter, r *http.Request) {
|
||||||
// Every attempt counts, not only failures: a successful registration is
|
|
||||||
// the thing being sprayed when the mode is open.
|
|
||||||
addr := auth.ClientIP(r, h.netSettings.Hops())
|
|
||||||
if blocked, wait := h.registerLimit.Blocked(addr); blocked {
|
|
||||||
writeRateLimited(w, wait)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
h.registerLimit.Record(addr)
|
|
||||||
|
|
||||||
var req registerReq
|
var req registerReq
|
||||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||||
writeErr(w, apierror.BadRequest("invalid_body", "invalid JSON body"))
|
writeErr(w, apierror.BadRequest("invalid_body", "invalid JSON body"))
|
||||||
@@ -94,19 +79,6 @@ func (h *handlers) handleRegister(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// The first account becomes admin, so it must prove it can read the
|
|
||||||
// server log. Checked before the invite logic, which the empty-users
|
|
||||||
// state skips.
|
|
||||||
if userCount == 0 && h.requireSetupToken && !h.setupToken.Matches(req.SetupToken) {
|
|
||||||
// Repeat the token in the log at the moment someone needs it: the
|
|
||||||
// boot line may have scrolled away, or users may have been deleted
|
|
||||||
// since boot.
|
|
||||||
h.logger.Warn("register: first-admin registration needs the setup token",
|
|
||||||
"setup_token", h.setupToken.Value())
|
|
||||||
writeErr(w, apierror.Forbidden("setup_token_invalid", "the setup token from the server log is required to create the first account"))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Validate invite (skipped on empty-users state; skipped in 'open' mode).
|
// Validate invite (skipped on empty-users state; skipped in 'open' mode).
|
||||||
usedInviteToken := ""
|
usedInviteToken := ""
|
||||||
if userCount > 0 {
|
if userCount > 0 {
|
||||||
@@ -161,7 +133,7 @@ func (h *handlers) handleRegister(w http.ResponseWriter, r *http.Request) {
|
|||||||
user, err := q.CreateUserFirstAdminRace(r.Context(), dbq.CreateUserFirstAdminRaceParams{
|
user, err := q.CreateUserFirstAdminRace(r.Context(), dbq.CreateUserFirstAdminRaceParams{
|
||||||
Username: req.Username,
|
Username: req.Username,
|
||||||
PasswordHash: string(hash),
|
PasswordHash: string(hash),
|
||||||
ApiTokenHash: auth.HashAPIToken(apiToken),
|
ApiToken: apiToken,
|
||||||
DisplayName: req.DisplayName,
|
DisplayName: req.DisplayName,
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -203,7 +175,7 @@ func (h *handlers) handleRegister(w http.ResponseWriter, r *http.Request) {
|
|||||||
UserID: user.ID,
|
UserID: user.ID,
|
||||||
TokenHash: auth.HashSessionToken(sessionToken),
|
TokenHash: auth.HashSessionToken(sessionToken),
|
||||||
UserAgent: r.UserAgent(),
|
UserAgent: r.UserAgent(),
|
||||||
Ip: addr,
|
Ip: auth.ClientIP(r, h.netSettings.Hops()),
|
||||||
}); err != nil {
|
}); err != nil {
|
||||||
h.logger.Error("register: insert session failed", "err", err)
|
h.logger.Error("register: insert session failed", "err", err)
|
||||||
writeErr(w, apierror.Internal(err))
|
writeErr(w, apierror.Internal(err))
|
||||||
@@ -214,7 +186,7 @@ func (h *handlers) handleRegister(w http.ResponseWriter, r *http.Request) {
|
|||||||
Value: sessionToken,
|
Value: sessionToken,
|
||||||
Path: "/",
|
Path: "/",
|
||||||
HttpOnly: true,
|
HttpOnly: true,
|
||||||
Secure: auth.IsHTTPS(r, h.netSettings.Hops()), // plain HTTP and LAN stay functional (rule 94)
|
Secure: r.TLS != nil,
|
||||||
SameSite: http.SameSiteStrictMode,
|
SameSite: http.SameSiteStrictMode,
|
||||||
MaxAge: int(sessionCookieMaxAge.Seconds()),
|
MaxAge: int(sessionCookieMaxAge.Seconds()),
|
||||||
})
|
})
|
||||||
@@ -251,31 +223,3 @@ func (h *handlers) handleRegister(w http.ResponseWriter, r *http.Request) {
|
|||||||
},
|
},
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// handleSetupStatus implements GET /api/auth/setup-status. It tells the
|
|
||||||
// register screen whether to ask for the setup token, i.e. whether no
|
|
||||||
// account exists yet. Public, since it is needed before anyone can sign in;
|
|
||||||
// "this server has no users" is not worth hiding from someone who could
|
|
||||||
// simply try to register.
|
|
||||||
func (h *handlers) handleSetupStatus(w http.ResponseWriter, r *http.Request) {
|
|
||||||
n, err := dbq.New(h.pool).CountUsers(r.Context())
|
|
||||||
if err != nil {
|
|
||||||
writeErrWithLog(w, h.logger, "setup status: count users failed", apierror.Internal(err))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
writeJSON(w, http.StatusOK, map[string]bool{"setup_required": n == 0})
|
|
||||||
}
|
|
||||||
|
|
||||||
// logSetupTokenIfNeeded writes the setup token to the log at boot when the
|
|
||||||
// instance has no accounts yet, with the instruction for using it.
|
|
||||||
func logSetupTokenIfNeeded(pool *pgxpool.Pool, logger *slog.Logger, token *auth.SetupToken) {
|
|
||||||
if pool == nil || logger == nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
n, err := dbq.New(pool).CountUsers(context.Background())
|
|
||||||
if err != nil || n > 0 {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
logger.Warn("no accounts yet: open the web app, choose Create account, and enter this setup token to become the admin",
|
|
||||||
"setup_token", token.Value())
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -273,75 +273,3 @@ func TestRegister_FirstAdminRace(t *testing.T) {
|
|||||||
// not "exactly one" (which would require serializable isolation).
|
// not "exactly one" (which would require serializable isolation).
|
||||||
t.Logf("admin count after race = %d (>=1 is the invariant)", adminCount)
|
t.Logf("admin count after race = %d (>=1 is the invariant)", adminCount)
|
||||||
}
|
}
|
||||||
|
|
||||||
// With the gate on (as Mount sets it), the first account needs the setup
|
|
||||||
// token from the log; a missing or wrong one is refused and creates nothing.
|
|
||||||
func TestRegister_FirstUserNeedsSetupToken(t *testing.T) {
|
|
||||||
if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" {
|
|
||||||
t.Skip("MINSTREL_TEST_DATABASE_URL not set")
|
|
||||||
}
|
|
||||||
h, _ := testHandlers(t)
|
|
||||||
resetUsers(t, h)
|
|
||||||
token, err := auth.NewSetupToken()
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("mint: %v", err)
|
|
||||||
}
|
|
||||||
h.setupToken = token
|
|
||||||
h.requireSetupToken = true
|
|
||||||
|
|
||||||
register := func(body string) int {
|
|
||||||
req := httptest.NewRequest(http.MethodPost, "/api/auth/register", bytes.NewReader([]byte(body)))
|
|
||||||
rec := httptest.NewRecorder()
|
|
||||||
h.handleRegister(rec, req)
|
|
||||||
return rec.Code
|
|
||||||
}
|
|
||||||
|
|
||||||
if code := register(`{"username":"squatter","password":"abcd1234"}`); code != http.StatusForbidden {
|
|
||||||
t.Errorf("no token: status = %d, want 403", code)
|
|
||||||
}
|
|
||||||
if code := register(`{"username":"squatter","password":"abcd1234","setup_token":"wrong"}`); code != http.StatusForbidden {
|
|
||||||
t.Errorf("wrong token: status = %d, want 403", code)
|
|
||||||
}
|
|
||||||
var n int
|
|
||||||
if err := h.pool.QueryRow(context.Background(), `SELECT count(*) FROM users`).Scan(&n); err != nil {
|
|
||||||
t.Fatalf("count: %v", err)
|
|
||||||
}
|
|
||||||
if n != 0 {
|
|
||||||
t.Fatalf("a refused registration created %d account(s)", n)
|
|
||||||
}
|
|
||||||
|
|
||||||
if code := register(`{"username":"operator","password":"abcd1234","setup_token":"` + token.Value() + `"}`); code != http.StatusOK {
|
|
||||||
t.Fatalf("right token: status = %d, want 200", code)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Once an account exists the token plays no part: the second user is
|
|
||||||
// governed by registration mode, not the setup token.
|
|
||||||
if _, err := h.pool.Exec(context.Background(),
|
|
||||||
`UPDATE registration_settings SET mode = 'open' WHERE id = true`); err != nil {
|
|
||||||
t.Fatalf("open mode: %v", err)
|
|
||||||
}
|
|
||||||
t.Cleanup(func() {
|
|
||||||
_, _ = h.pool.Exec(context.Background(),
|
|
||||||
`UPDATE registration_settings SET mode = 'invite_only' WHERE id = true`)
|
|
||||||
})
|
|
||||||
if code := register(`{"username":"second","password":"abcd1234"}`); code != http.StatusOK {
|
|
||||||
t.Errorf("second user without token: status = %d, want 200", code)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestSetupToken_MatchesOnlyItself(t *testing.T) {
|
|
||||||
tok, err := auth.NewSetupToken()
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("mint: %v", err)
|
|
||||||
}
|
|
||||||
if !tok.Matches(tok.Value()) {
|
|
||||||
t.Error("token does not match itself")
|
|
||||||
}
|
|
||||||
if tok.Matches("") || tok.Matches(tok.Value()+"x") {
|
|
||||||
t.Error("token matched something else")
|
|
||||||
}
|
|
||||||
var none *auth.SetupToken
|
|
||||||
if none.Matches("") || none.Matches("anything") {
|
|
||||||
t.Error("a nil token must fail closed")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -10,7 +10,6 @@ import (
|
|||||||
|
|
||||||
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
|
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
|
||||||
"git.fabledsword.com/bvandeusen/minstrel/internal/audit"
|
"git.fabledsword.com/bvandeusen/minstrel/internal/audit"
|
||||||
"git.fabledsword.com/bvandeusen/minstrel/internal/auth"
|
|
||||||
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
|
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -43,15 +42,6 @@ func (h *handlers) handleResetPassword(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Tokens carry 256 bits, so guessing one is hopeless; the limit is on
|
|
||||||
// failed tries per address so that nobody gets to find that out at our
|
|
||||||
// expense.
|
|
||||||
addr := auth.ClientIP(r, h.netSettings.Hops())
|
|
||||||
if blocked, wait := h.resetLimit.Blocked(addr); blocked {
|
|
||||||
writeRateLimited(w, wait)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
q := dbq.New(h.pool)
|
q := dbq.New(h.pool)
|
||||||
|
|
||||||
// Look up the reset record so we know which user to update before
|
// Look up the reset record so we know which user to update before
|
||||||
@@ -60,7 +50,6 @@ func (h *handlers) handleResetPassword(w http.ResponseWriter, r *http.Request) {
|
|||||||
reset, err := q.GetPasswordReset(r.Context(), req.Token)
|
reset, err := q.GetPasswordReset(r.Context(), req.Token)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if errors.Is(err, pgx.ErrNoRows) {
|
if errors.Is(err, pgx.ErrNoRows) {
|
||||||
h.resetLimit.Record(addr)
|
|
||||||
writeErr(w, apierror.BadRequest("invalid_token", ""))
|
writeErr(w, apierror.BadRequest("invalid_token", ""))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -80,7 +69,6 @@ func (h *handlers) handleResetPassword(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
if rows == 0 {
|
if rows == 0 {
|
||||||
h.resetLimit.Record(addr)
|
|
||||||
writeErr(w, apierror.BadRequest("invalid_token", ""))
|
writeErr(w, apierror.BadRequest("invalid_token", ""))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -104,13 +92,6 @@ func (h *handlers) handleResetPassword(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// End every session the account has. Whoever needed a reset isn't signed
|
|
||||||
// in anywhere they rely on, and whoever may have learned the old password
|
|
||||||
// must not stay signed in on it.
|
|
||||||
if _, err := q.DeleteSessionsForUser(r.Context(), reset.UserID); err != nil {
|
|
||||||
h.logger.Error("reset password: revoke sessions failed", "err", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
audit.WriteOrLog(r.Context(), h.pool, h.logger, reset.UserID, reset.UserID, audit.ActionPasswordResetByEmail, nil)
|
audit.WriteOrLog(r.Context(), h.pool, h.logger, reset.UserID, reset.UserID, audit.ActionPasswordResetByEmail, nil)
|
||||||
|
|
||||||
w.WriteHeader(http.StatusNoContent)
|
w.WriteHeader(http.StatusNoContent)
|
||||||
|
|||||||
@@ -65,7 +65,7 @@ func testHandlers(t *testing.T) (*handlers, *pgxpool.Pool) {
|
|||||||
}
|
}
|
||||||
lidarrCfg := lidarrconfig.New(pool)
|
lidarrCfg := lidarrconfig.New(pool)
|
||||||
lidarrReqs := lidarrrequests.NewService(pool, lidarrCfg, nil, nil)
|
lidarrReqs := lidarrrequests.NewService(pool, lidarrCfg, nil, nil)
|
||||||
lidarrQuar := lidarrquarantine.NewService(pool, lidarrCfg, nil, "")
|
lidarrQuar := lidarrquarantine.NewService(pool, lidarrCfg, nil)
|
||||||
// tracks.Service has no Lidarr unmonitorer in tests by default; the
|
// tracks.Service has no Lidarr unmonitorer in tests by default; the
|
||||||
// admin-tracks tests below override h.tracks via installTracksLidarrStub
|
// admin-tracks tests below override h.tracks via installTracksLidarrStub
|
||||||
// when they need a stubbed Lidarr.
|
// when they need a stubbed Lidarr.
|
||||||
@@ -91,7 +91,7 @@ func seedUser(t *testing.T, pool *pgxpool.Pool, username, password string, isAdm
|
|||||||
u, err := dbq.New(pool).CreateUser(context.Background(), dbq.CreateUserParams{
|
u, err := dbq.New(pool).CreateUser(context.Background(), dbq.CreateUserParams{
|
||||||
Username: prefixed,
|
Username: prefixed,
|
||||||
PasswordHash: string(hash),
|
PasswordHash: string(hash),
|
||||||
ApiTokenHash: "test-api-token-" + prefixed,
|
ApiToken: "test-api-token-" + prefixed,
|
||||||
IsAdmin: isAdmin,
|
IsAdmin: isAdmin,
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -179,36 +179,6 @@ func TestHandleLogin_UnknownUserReturns401(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// A guesser who reaches the account limit is refused with 429 before any
|
|
||||||
// password check, so even the right password is turned away until the window
|
|
||||||
// passes, and the response says when to come back.
|
|
||||||
func TestHandleLogin_ThrottledAfterRepeatedFailures(t *testing.T) {
|
|
||||||
h, pool := testHandlers(t)
|
|
||||||
h.loginGuard = auth.NewLoginGuard()
|
|
||||||
seedUser(t, pool, "alice", "hunter2", false)
|
|
||||||
|
|
||||||
login := func(password string) *httptest.ResponseRecorder {
|
|
||||||
body := strings.NewReader(`{"username":"test-alice","password":"` + password + `"}`)
|
|
||||||
req := httptest.NewRequest(http.MethodPost, "/api/auth/login", body)
|
|
||||||
req.Header.Set("Content-Type", "application/json")
|
|
||||||
w := httptest.NewRecorder()
|
|
||||||
h.handleLogin(w, req)
|
|
||||||
return w
|
|
||||||
}
|
|
||||||
for i := 0; i < 10; i++ {
|
|
||||||
if w := login("wrong"); w.Code != http.StatusUnauthorized {
|
|
||||||
t.Fatalf("attempt %d: status = %d, want 401", i+1, w.Code)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
w := login("hunter2")
|
|
||||||
if w.Code != http.StatusTooManyRequests {
|
|
||||||
t.Fatalf("status = %d, want 429 once the account limit is reached", w.Code)
|
|
||||||
}
|
|
||||||
if w.Header().Get("Retry-After") == "" {
|
|
||||||
t.Error("429 without Retry-After")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestHandleLogin_MalformedBodyReturns400(t *testing.T) {
|
func TestHandleLogin_MalformedBodyReturns400(t *testing.T) {
|
||||||
h, _ := testHandlers(t)
|
h, _ := testHandlers(t)
|
||||||
req := httptest.NewRequest(http.MethodPost, "/api/auth/login",
|
req := httptest.NewRequest(http.MethodPost, "/api/auth/login",
|
||||||
|
|||||||
@@ -6,21 +6,19 @@ package api
|
|||||||
// /app/client/ at image build time.
|
// /app/client/ at image build time.
|
||||||
//
|
//
|
||||||
// Both endpoints are authenticated — the bandwidth cost of the APK
|
// Both endpoints are authenticated — the bandwidth cost of the APK
|
||||||
// (~30-60 MB) makes anonymous access an abuse vector. The client only
|
// (~30-60 MB) makes anonymous access an abuse vector. The Flutter
|
||||||
// polls after login, so this gate is invisible to the actual update flow.
|
// client's polling only fires after login (banner mounts in the post-
|
||||||
|
// login shell), so this gate is invisible to the actual update flow.
|
||||||
//
|
//
|
||||||
// /api/client/apk additionally rate-limits per user to a single
|
// /api/client/apk additionally rate-limits per user to a single
|
||||||
// download every 60s. Real install flows fire one download per
|
// download every 60s. Real install flows fire one download per
|
||||||
// update; anything tighter is scripted/abusive.
|
// update; anything tighter is scripted/abusive.
|
||||||
//
|
//
|
||||||
// Returns 404 gracefully when the APK isn't present (dev environments,
|
// Returns 404 gracefully when the APK isn't present (dev environments,
|
||||||
// pre-CI-wiring); the client treats 404 as "no update channel available."
|
// pre-CI-wiring); the Flutter client treats 404 as "no update channel
|
||||||
//
|
// available."
|
||||||
// (These paragraphs said "the Flutter client" until 2026-09-10. That client
|
|
||||||
// was deleted in v2026.08.18 — the Android app is the only one now.)
|
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
|
||||||
"errors"
|
"errors"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
@@ -86,36 +84,8 @@ func clientAPKAllowDownload(userID string, now time.Time) time.Duration {
|
|||||||
return 0
|
return 0
|
||||||
}
|
}
|
||||||
|
|
||||||
// clientVersionSidecar is the JSON written beside the bundled APK by
|
|
||||||
// release.yml. It carries three values that are deliberately separate:
|
|
||||||
//
|
|
||||||
// - Name is a LABEL for people, "YYYY.MM.DD.HHMM" from the commit's
|
|
||||||
// timestamp. Two channels carrying the same code report the same name.
|
|
||||||
// - Code is the ORDERING KEY, minutes since 2020-01-01 at build time, and
|
|
||||||
// is the value Android itself installs by. It answers "may this be
|
|
||||||
// installed over that?" — the name never does.
|
|
||||||
// - Channel is a SIBLING FIELD, never a suffix inside the name.
|
|
||||||
//
|
|
||||||
// JSON rather than a positional line on purpose. The obvious growth path for
|
|
||||||
// the old one-value file was "<name> <code>", which a first-space split
|
|
||||||
// silently mangles the moment a third field appears: the code stops parsing,
|
|
||||||
// and the reader falls back to name comparison WITHOUT erroring.
|
|
||||||
type clientVersionSidecar struct {
|
|
||||||
Name string `json:"name"`
|
|
||||||
// Pointer, not int64: absent must stay distinguishable from zero. An
|
|
||||||
// artifact published before codes were recorded genuinely has no code —
|
|
||||||
// zero would claim it is infinitely old rather than unknown.
|
|
||||||
Code *int64 `json:"code"`
|
|
||||||
Channel string `json:"channel"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type clientVersionResponse struct {
|
type clientVersionResponse struct {
|
||||||
Version string `json:"version"`
|
Version string `json:"version"`
|
||||||
// omitempty on both: the client must be able to tell "this server does
|
|
||||||
// not report a code" from "this build's code is 0", because those call
|
|
||||||
// for different behaviour on the other end.
|
|
||||||
Code *int64 `json:"code,omitempty"`
|
|
||||||
Channel string `json:"channel,omitempty"`
|
|
||||||
APKURL string `json:"apk_url"`
|
APKURL string `json:"apk_url"`
|
||||||
SizeBytes int64 `json:"size_bytes"`
|
SizeBytes int64 `json:"size_bytes"`
|
||||||
}
|
}
|
||||||
@@ -147,25 +117,8 @@ func (h *handlers) handleClientVersion(w http.ResponseWriter, _ *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
var sidecar clientVersionSidecar
|
|
||||||
if err := json.Unmarshal(versionBytes, &sidecar); err != nil {
|
|
||||||
// Fail LOUDLY rather than serving a blank version. The failure mode
|
|
||||||
// this avoids is the one that never gets reported: if an unreadable
|
|
||||||
// sidecar produced an empty name, every client would compare against
|
|
||||||
// nothing, conclude it was current, and go quiet — "I cannot read
|
|
||||||
// this" and "there is nothing newer" would be the same answer.
|
|
||||||
writeErrWithLog(w, h.logger, "client_version: sidecar is not valid JSON", err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if sidecar.Name == "" {
|
|
||||||
http.Error(w, `{"error":{"code":"bad_client_version","message":"version sidecar has no name"}}`, http.StatusInternalServerError)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
writeJSON(w, http.StatusOK, clientVersionResponse{
|
writeJSON(w, http.StatusOK, clientVersionResponse{
|
||||||
Version: strings.TrimSpace(sidecar.Name),
|
Version: strings.TrimSpace(string(versionBytes)),
|
||||||
Code: sidecar.Code,
|
|
||||||
Channel: strings.TrimSpace(sidecar.Channel),
|
|
||||||
APKURL: "/api/client/apk",
|
APKURL: "/api/client/apk",
|
||||||
SizeBytes: stat.Size(),
|
SizeBytes: stat.Size(),
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -77,32 +77,18 @@ func TestClientVersion_404WhenAPKButNoVersion(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// writeClientAssets stages an APK plus a raw sidecar body, and returns the
|
func TestClientVersion_200WithBothFiles(t *testing.T) {
|
||||||
// APK's size so callers can assert size_bytes without recomputing it.
|
|
||||||
func writeClientAssets(t *testing.T, sidecar string) int64 {
|
|
||||||
t.Helper()
|
|
||||||
dir := withClientAPKDir(t)
|
dir := withClientAPKDir(t)
|
||||||
body := []byte("fake apk content")
|
body := []byte("fake apk content")
|
||||||
if err := os.WriteFile(filepath.Join(dir, clientAPKFilename), body, 0o644); err != nil {
|
if err := os.WriteFile(filepath.Join(dir, clientAPKFilename), body, 0o644); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
if err := os.WriteFile(filepath.Join(dir, clientVersionFile), []byte(sidecar), 0o644); err != nil {
|
if err := os.WriteFile(filepath.Join(dir, clientVersionFile), []byte("v2026.05.10\n"), 0o644); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
return int64(len(body))
|
|
||||||
}
|
|
||||||
|
|
||||||
func getClientVersion(t *testing.T) *httptest.ResponseRecorder {
|
|
||||||
t.Helper()
|
|
||||||
h := &handlers{logger: slog.New(slog.NewTextHandler(io.Discard, nil))}
|
h := &handlers{logger: slog.New(slog.NewTextHandler(io.Discard, nil))}
|
||||||
rr := httptest.NewRecorder()
|
rr := httptest.NewRecorder()
|
||||||
h.handleClientVersion(rr, httptest.NewRequest(http.MethodGet, "/api/client/version", nil))
|
h.handleClientVersion(rr, httptest.NewRequest(http.MethodGet, "/api/client/version", nil))
|
||||||
return rr
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestClientVersion_200WithBothFiles(t *testing.T) {
|
|
||||||
size := writeClientAssets(t, `{"name":"2026.09.10.1432","code":3523847,"channel":"stable"}`+"\n")
|
|
||||||
rr := getClientVersion(t)
|
|
||||||
if rr.Code != http.StatusOK {
|
if rr.Code != http.StatusOK {
|
||||||
t.Fatalf("want 200, got %d (body: %s)", rr.Code, rr.Body.String())
|
t.Fatalf("want 200, got %d (body: %s)", rr.Code, rr.Body.String())
|
||||||
}
|
}
|
||||||
@@ -110,69 +96,14 @@ func TestClientVersion_200WithBothFiles(t *testing.T) {
|
|||||||
if err := json.Unmarshal(rr.Body.Bytes(), &resp); err != nil {
|
if err := json.Unmarshal(rr.Body.Bytes(), &resp); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
if resp.Version != "2026.09.10.1432" {
|
if resp.Version != "v2026.05.10" {
|
||||||
t.Errorf("version: want 2026.09.10.1432, got %q", resp.Version)
|
t.Errorf("version: want trimmed v2026.05.10, got %q", resp.Version)
|
||||||
}
|
|
||||||
if resp.Code == nil {
|
|
||||||
t.Fatal("code: want 3523847, got absent — the client decides on this, so absent means it silently falls back to name comparison")
|
|
||||||
}
|
|
||||||
if *resp.Code != 3523847 {
|
|
||||||
t.Errorf("code: want 3523847, got %d", *resp.Code)
|
|
||||||
}
|
|
||||||
if resp.Channel != "stable" {
|
|
||||||
t.Errorf("channel: want stable, got %q", resp.Channel)
|
|
||||||
}
|
}
|
||||||
if resp.APKURL != "/api/client/apk" {
|
if resp.APKURL != "/api/client/apk" {
|
||||||
t.Errorf("apk_url: want /api/client/apk, got %q", resp.APKURL)
|
t.Errorf("apk_url: want /api/client/apk, got %q", resp.APKURL)
|
||||||
}
|
}
|
||||||
if resp.SizeBytes != size {
|
if resp.SizeBytes != int64(len(body)) {
|
||||||
t.Errorf("size_bytes: want %d, got %d", size, resp.SizeBytes)
|
t.Errorf("size_bytes: want %d, got %d", len(body), resp.SizeBytes)
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// A release published before ordering keys were recorded has a name and
|
|
||||||
// genuinely no code. That must arrive as ABSENT, not as 0 — zero would claim
|
|
||||||
// the build is infinitely old and offer an update to everyone forever.
|
|
||||||
func TestClientVersion_CodeAbsentIsOmittedNotZero(t *testing.T) {
|
|
||||||
writeClientAssets(t, `{"name":"2026.09.09","code":null,"channel":"stable"}`)
|
|
||||||
rr := getClientVersion(t)
|
|
||||||
if rr.Code != http.StatusOK {
|
|
||||||
t.Fatalf("want 200, got %d (body: %s)", rr.Code, rr.Body.String())
|
|
||||||
}
|
|
||||||
var resp clientVersionResponse
|
|
||||||
if err := json.Unmarshal(rr.Body.Bytes(), &resp); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if resp.Code != nil {
|
|
||||||
t.Errorf("code: want absent, got %d", *resp.Code)
|
|
||||||
}
|
|
||||||
// The wire must omit the key entirely, so a client can distinguish
|
|
||||||
// "this server reports no code" from "this build's code is 0".
|
|
||||||
var raw map[string]any
|
|
||||||
if err := json.Unmarshal(rr.Body.Bytes(), &raw); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if _, present := raw["code"]; present {
|
|
||||||
t.Errorf("code key should be omitted entirely, body was %s", rr.Body.String())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// The failure this guards is the one nobody reports: if an unreadable sidecar
|
|
||||||
// produced an empty version, every client would compare against nothing,
|
|
||||||
// decide it was current, and go quiet. "I cannot read this" and "there is
|
|
||||||
// nothing newer" must not be the same answer.
|
|
||||||
func TestClientVersion_MalformedSidecarErrorsRatherThanReportingNothing(t *testing.T) {
|
|
||||||
for _, sidecar := range []string{
|
|
||||||
"2026.09.10.1432", // the OLD plain-text format
|
|
||||||
`{"name":"x",`, // truncated JSON
|
|
||||||
`{"code":123,"channel":"dev"}`, // valid JSON, no name
|
|
||||||
"",
|
|
||||||
} {
|
|
||||||
writeClientAssets(t, sidecar)
|
|
||||||
rr := getClientVersion(t)
|
|
||||||
if rr.Code == http.StatusOK {
|
|
||||||
t.Errorf("sidecar %q: want an error status, got 200 with body %s", sidecar, rr.Body.String())
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -3,10 +3,7 @@ package api
|
|||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"log/slog"
|
"log/slog"
|
||||||
"math"
|
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
|
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
|
||||||
)
|
)
|
||||||
@@ -39,17 +36,6 @@ func writeErr(w http.ResponseWriter, err error) {
|
|||||||
}})
|
}})
|
||||||
}
|
}
|
||||||
|
|
||||||
// writeRateLimited answers 429 with Retry-After in whole seconds, rounded
|
|
||||||
// up so a client that honours it never arrives a moment early.
|
|
||||||
func writeRateLimited(w http.ResponseWriter, wait time.Duration) {
|
|
||||||
secs := int(math.Ceil(wait.Seconds()))
|
|
||||||
if secs < 1 {
|
|
||||||
secs = 1
|
|
||||||
}
|
|
||||||
w.Header().Set("Retry-After", strconv.Itoa(secs))
|
|
||||||
writeErr(w, apierror.TooManyRequests("rate_limited", "too many attempts; try again later"))
|
|
||||||
}
|
|
||||||
|
|
||||||
// writeErrWithLog logs the error at Error level and writes the response.
|
// writeErrWithLog logs the error at Error level and writes the response.
|
||||||
// Use for 500-class errors where the operator needs the cause in logs.
|
// Use for 500-class errors where the operator needs the cause in logs.
|
||||||
func writeErrWithLog(w http.ResponseWriter, logger *slog.Logger, msg string, err error) {
|
func writeErrWithLog(w http.ResponseWriter, logger *slog.Logger, msg string, err error) {
|
||||||
|
|||||||
@@ -1,58 +0,0 @@
|
|||||||
package api
|
|
||||||
|
|
||||||
import (
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"log/slog"
|
|
||||||
"net/http"
|
|
||||||
|
|
||||||
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
|
|
||||||
"git.fabledsword.com/bvandeusen/minstrel/internal/library"
|
|
||||||
)
|
|
||||||
|
|
||||||
// fileRemoveAPIError answers a delete that could not reach the track's file
|
|
||||||
// (#3918). Both delete endpoints use it, so the operator gets the same
|
|
||||||
// explanation from the admin remove-track action and from quarantine's Delete
|
|
||||||
// file.
|
|
||||||
//
|
|
||||||
// The unwritable case is a 409 rather than a 500 because nothing is broken: the
|
|
||||||
// request conflicts with how the library is mounted, and the fix is the
|
|
||||||
// operator's. The message names the directory — removal writes to the parent,
|
|
||||||
// not the file — and the uid/gid the process runs as, which is the half of a
|
|
||||||
// permission problem invisible from the host. Every case says nothing was
|
|
||||||
// deleted, because that is exactly what the operator will be worried about.
|
|
||||||
func fileRemoveAPIError(err error) (*apierror.Error, bool) {
|
|
||||||
var fre *library.FileRemoveError
|
|
||||||
if !errors.As(err, &fre) {
|
|
||||||
return nil, false
|
|
||||||
}
|
|
||||||
if fre.NotWritable() {
|
|
||||||
return &apierror.Error{
|
|
||||||
Status: http.StatusConflict,
|
|
||||||
Code: "library_not_writable",
|
|
||||||
Message: fmt.Sprintf(
|
|
||||||
"Minstrel runs as uid %d, gid %d and cannot delete from %s (%s). "+
|
|
||||||
"The library mount must be writable by that user. Nothing was deleted.",
|
|
||||||
fre.UID, fre.GID, fre.Dir(), fre.Reason()),
|
|
||||||
Cause: err,
|
|
||||||
}, true
|
|
||||||
}
|
|
||||||
return &apierror.Error{
|
|
||||||
Status: http.StatusInternalServerError,
|
|
||||||
Code: "file_delete_failed",
|
|
||||||
Message: fmt.Sprintf("Could not delete %s (%s). Nothing was deleted.", fre.Path, fre.Reason()),
|
|
||||||
Cause: err,
|
|
||||||
}, true
|
|
||||||
}
|
|
||||||
|
|
||||||
// logFileRemoveFailure records a delete that could not reach its file. An
|
|
||||||
// unwritable library is an environment fact the operator can fix, so it is a
|
|
||||||
// Warn; anything else is a real fault.
|
|
||||||
func logFileRemoveFailure(logger *slog.Logger, apiErr *apierror.Error, attrs ...any) {
|
|
||||||
attrs = append(attrs, "code", apiErr.Code, "err", apiErr.Cause)
|
|
||||||
if apiErr.Status == http.StatusConflict {
|
|
||||||
logger.Warn("api: track file could not be deleted", attrs...)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
logger.Error("api: track file could not be deleted", attrs...)
|
|
||||||
}
|
|
||||||
@@ -1,96 +0,0 @@
|
|||||||
package api
|
|
||||||
|
|
||||||
import (
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"io/fs"
|
|
||||||
"net/http"
|
|
||||||
"strings"
|
|
||||||
"syscall"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"git.fabledsword.com/bvandeusen/minstrel/internal/library"
|
|
||||||
)
|
|
||||||
|
|
||||||
const removeTestPath = "/music/Moe Shop/WWW (2020)/01 - WWW.mp3"
|
|
||||||
|
|
||||||
// removeFailure builds the error a delete service returns when the file would
|
|
||||||
// not go, wrapped the way lidarrquarantine.DeleteFile and tracks.RemoveTrack
|
|
||||||
// wrap it — the mapping has to see through that.
|
|
||||||
func removeFailure(errno syscall.Errno) error {
|
|
||||||
return fmt.Errorf("delete file: %w", &library.FileRemoveError{
|
|
||||||
Path: removeTestPath, UID: 1000, GID: 1000,
|
|
||||||
Err: &fs.PathError{Op: "remove", Path: removeTestPath, Err: errno},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestFileRemoveAPIError(t *testing.T) {
|
|
||||||
cases := []struct {
|
|
||||||
name string
|
|
||||||
errno syscall.Errno
|
|
||||||
wantStatus int
|
|
||||||
wantCode string
|
|
||||||
wantIn []string
|
|
||||||
}{
|
|
||||||
{
|
|
||||||
name: "read-only mount", errno: syscall.EROFS,
|
|
||||||
wantStatus: http.StatusConflict, wantCode: "library_not_writable",
|
|
||||||
wantIn: []string{"uid 1000, gid 1000", "/music/Moe Shop/WWW (2020)", "read-only file system", "Nothing was deleted"},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "permission denied", errno: syscall.EACCES,
|
|
||||||
wantStatus: http.StatusConflict, wantCode: "library_not_writable",
|
|
||||||
wantIn: []string{"permission denied", "Nothing was deleted"},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "operation not permitted", errno: syscall.EPERM,
|
|
||||||
wantStatus: http.StatusConflict, wantCode: "library_not_writable",
|
|
||||||
wantIn: []string{"operation not permitted"},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "i/o error", errno: syscall.EIO,
|
|
||||||
wantStatus: http.StatusInternalServerError, wantCode: "file_delete_failed",
|
|
||||||
wantIn: []string{removeTestPath, "input/output error", "Nothing was deleted"},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
for _, tc := range cases {
|
|
||||||
t.Run(tc.name, func(t *testing.T) {
|
|
||||||
apiErr, ok := fileRemoveAPIError(removeFailure(tc.errno))
|
|
||||||
if !ok {
|
|
||||||
t.Fatal("a wrapped *library.FileRemoveError was not recognised")
|
|
||||||
}
|
|
||||||
if apiErr.Status != tc.wantStatus || apiErr.Code != tc.wantCode {
|
|
||||||
t.Fatalf("got %d %s, want %d %s", apiErr.Status, apiErr.Code, tc.wantStatus, tc.wantCode)
|
|
||||||
}
|
|
||||||
for _, want := range tc.wantIn {
|
|
||||||
if !strings.Contains(apiErr.Message, want) {
|
|
||||||
t.Errorf("message %q lacks %q", apiErr.Message, want)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// The unwritable answer must name the DIRECTORY. Removal needs write access to
|
|
||||||
// the parent, so a message naming the file would send the operator to fix the
|
|
||||||
// wrong permissions. The directory is a prefix of the file path, which is why a
|
|
||||||
// plain "contains the directory" check could never catch that regression.
|
|
||||||
func TestFileRemoveAPIError_NotWritableNamesTheDirectoryNotTheFile(t *testing.T) {
|
|
||||||
apiErr, _ := fileRemoveAPIError(removeFailure(syscall.EROFS))
|
|
||||||
if strings.Contains(apiErr.Message, "01 - WWW.mp3") {
|
|
||||||
t.Fatalf("message names the file rather than its directory: %q", apiErr.Message)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestFileRemoveAPIError_IgnoresOtherErrors(t *testing.T) {
|
|
||||||
for name, err := range map[string]error{
|
|
||||||
"nil": nil,
|
|
||||||
"plain error": errors.New("delete track: connection reset"),
|
|
||||||
"path error": &fs.PathError{Op: "remove", Path: removeTestPath, Err: syscall.EROFS},
|
|
||||||
"not found": library.ErrTrackNotFound,
|
|
||||||
} {
|
|
||||||
if _, ok := fileRemoveAPIError(err); ok {
|
|
||||||
t.Errorf("%s: mapped as a file-remove failure", name)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -465,7 +465,7 @@ func TestRoutesRegisteredInMount(t *testing.T) {
|
|||||||
r := chi.NewRouter()
|
r := chi.NewRouter()
|
||||||
w := playevents.NewWriter(h.pool, slog.New(slog.NewTextHandler(io.Discard, nil)),
|
w := playevents.NewWriter(h.pool, slog.New(slog.NewTextHandler(io.Discard, nil)),
|
||||||
30*time.Minute, 0.5, 30000)
|
30*time.Minute, 0.5, 30000)
|
||||||
Mount(r, h.pool, h.logger, w, config.RecommendationConfig{RadioSize: 50, RadioSizeMax: 200, RecentlyPlayedHours: 1}, h.recSettings, h.lidarrCfg, h.lidarrRequests, h.lidarrQuarantine, h.tracks, h.playlists, h.coverart, h.coverSettings, h.tagSettings, h.scanner, h.scanCfg, h.dataDir, nil, eventbus.New(), nil, nil, h.netSettings, nil, nil)
|
Mount(r, h.pool, h.logger, w, config.RecommendationConfig{RadioSize: 50, RadioSizeMax: 200, RecentlyPlayedHours: 1}, h.recSettings, h.lidarrCfg, h.lidarrRequests, h.lidarrQuarantine, h.tracks, h.playlists, h.coverart, h.coverSettings, h.tagSettings, h.scanner, h.scanCfg, h.dataDir, nil, eventbus.New(), nil, nil, h.netSettings, nil)
|
||||||
|
|
||||||
paths := []string{
|
paths := []string{
|
||||||
"/api/artists",
|
"/api/artists",
|
||||||
@@ -484,9 +484,6 @@ func TestRoutesRegisteredInMount(t *testing.T) {
|
|||||||
// wired.
|
// wired.
|
||||||
"/api/admin/library/missing",
|
"/api/admin/library/missing",
|
||||||
"/api/admin/library/reacquisition",
|
"/api/admin/library/reacquisition",
|
||||||
"/api/admin/library/fingerprints",
|
|
||||||
"/api/admin/library/fingerprint-settings",
|
|
||||||
"/api/admin/library/duplicates",
|
|
||||||
}
|
}
|
||||||
for _, p := range paths {
|
for _, p := range paths {
|
||||||
req := httptest.NewRequest(http.MethodGet, p, nil)
|
req := httptest.NewRequest(http.MethodGet, p, nil)
|
||||||
|
|||||||
@@ -8,7 +8,6 @@ import (
|
|||||||
|
|
||||||
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
|
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
|
||||||
"git.fabledsword.com/bvandeusen/minstrel/internal/audit"
|
"git.fabledsword.com/bvandeusen/minstrel/internal/audit"
|
||||||
"git.fabledsword.com/bvandeusen/minstrel/internal/auth"
|
|
||||||
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
|
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -62,19 +61,6 @@ func (h *handlers) handleChangePassword(w http.ResponseWriter, r *http.Request)
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Sign out every other device. A password change is often the response
|
|
||||||
// to suspecting someone else has it, and their session would otherwise
|
|
||||||
// outlive the password it was opened with. The device making the change
|
|
||||||
// stays signed in.
|
|
||||||
if sessID, ok := auth.SessionIDFromContext(r.Context()); ok {
|
|
||||||
if _, err := q.DeleteOtherSessionsForUser(r.Context(), dbq.DeleteOtherSessionsForUserParams{
|
|
||||||
UserID: user.ID,
|
|
||||||
ID: sessID,
|
|
||||||
}); err != nil {
|
|
||||||
h.logger.Error("change password: revoke other sessions failed", "err", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
audit.WriteOrLog(r.Context(), h.pool, h.logger, user.ID, user.ID, audit.ActionPasswordChangeSelf, nil)
|
audit.WriteOrLog(r.Context(), h.pool, h.logger, user.ID, user.ID, audit.ActionPasswordChangeSelf, nil)
|
||||||
|
|
||||||
w.WriteHeader(http.StatusNoContent)
|
w.WriteHeader(http.StatusNoContent)
|
||||||
|
|||||||
@@ -13,11 +13,23 @@ type apiTokenResp struct {
|
|||||||
APIToken string `json:"api_token"`
|
APIToken string `json:"api_token"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// handleGetMyAPIToken implements GET /api/me/api-token.
|
||||||
|
func (h *handlers) handleGetMyAPIToken(w http.ResponseWriter, r *http.Request) {
|
||||||
|
user, ok := requireUser(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
q := dbq.New(h.pool)
|
||||||
|
current, err := q.GetUserByID(r.Context(), user.ID)
|
||||||
|
if err != nil {
|
||||||
|
h.logger.Error("get api token: lookup failed", "err", err)
|
||||||
|
writeErr(w, apierror.Internal(err))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeJSON(w, http.StatusOK, apiTokenResp{APIToken: current.ApiToken})
|
||||||
|
}
|
||||||
|
|
||||||
// handleRegenerateMyAPIToken implements POST /api/me/api-token.
|
// handleRegenerateMyAPIToken implements POST /api/me/api-token.
|
||||||
//
|
|
||||||
// Only the key's hash is stored, so this response is the one time the key
|
|
||||||
// can be read. There is deliberately no GET: a key that has been shown and
|
|
||||||
// lost is replaced, not looked up.
|
|
||||||
func (h *handlers) handleRegenerateMyAPIToken(w http.ResponseWriter, r *http.Request) {
|
func (h *handlers) handleRegenerateMyAPIToken(w http.ResponseWriter, r *http.Request) {
|
||||||
user, ok := requireUser(w, r)
|
user, ok := requireUser(w, r)
|
||||||
if !ok {
|
if !ok {
|
||||||
@@ -30,10 +42,11 @@ func (h *handlers) handleRegenerateMyAPIToken(w http.ResponseWriter, r *http.Req
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
q := dbq.New(h.pool)
|
q := dbq.New(h.pool)
|
||||||
if err := q.RegenerateApiToken(r.Context(), dbq.RegenerateApiTokenParams{
|
updated, err := q.RegenerateApiToken(r.Context(), dbq.RegenerateApiTokenParams{
|
||||||
ID: user.ID,
|
ID: user.ID,
|
||||||
ApiTokenHash: auth.HashAPIToken(newToken),
|
ApiToken: newToken,
|
||||||
}); err != nil {
|
})
|
||||||
|
if err != nil {
|
||||||
h.logger.Error("regenerate api token: update failed", "err", err)
|
h.logger.Error("regenerate api token: update failed", "err", err)
|
||||||
writeErr(w, apierror.Internal(err))
|
writeErr(w, apierror.Internal(err))
|
||||||
return
|
return
|
||||||
@@ -41,5 +54,5 @@ func (h *handlers) handleRegenerateMyAPIToken(w http.ResponseWriter, r *http.Req
|
|||||||
|
|
||||||
audit.WriteOrLog(r.Context(), h.pool, h.logger, user.ID, user.ID, audit.ActionTokenRegenerate, nil)
|
audit.WriteOrLog(r.Context(), h.pool, h.logger, user.ID, user.ID, audit.ActionTokenRegenerate, nil)
|
||||||
|
|
||||||
writeJSON(w, http.StatusOK, apiTokenResp{APIToken: newToken})
|
writeJSON(w, http.StatusOK, apiTokenResp{APIToken: updated.ApiToken})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,23 +8,47 @@ import (
|
|||||||
"os"
|
"os"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"git.fabledsword.com/bvandeusen/minstrel/internal/auth"
|
|
||||||
"github.com/go-chi/chi/v5"
|
"github.com/go-chi/chi/v5"
|
||||||
)
|
)
|
||||||
|
|
||||||
func newMeTokenRouter(h *handlers) chi.Router {
|
func newMeTokenRouter(h *handlers) chi.Router {
|
||||||
r := chi.NewRouter()
|
r := chi.NewRouter()
|
||||||
|
r.Get("/api/me/api-token", h.handleGetMyAPIToken)
|
||||||
r.Post("/api/me/api-token", h.handleRegenerateMyAPIToken)
|
r.Post("/api/me/api-token", h.handleRegenerateMyAPIToken)
|
||||||
return r
|
return r
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestGetAPIToken_ReturnsCurrentToken(t *testing.T) {
|
||||||
|
if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" {
|
||||||
|
t.Skip("MINSTREL_TEST_DATABASE_URL not set")
|
||||||
|
}
|
||||||
|
h, pool := testHandlers(t)
|
||||||
|
user := seedUser(t, pool, "tok1", "pw", false)
|
||||||
|
|
||||||
|
req := httptest.NewRequest(http.MethodGet, "/api/me/api-token", nil)
|
||||||
|
req = withUser(req, user)
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
newMeTokenRouter(h).ServeHTTP(rec, req)
|
||||||
|
|
||||||
|
if rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("status = %d, want 200; body=%s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
var resp apiTokenResp
|
||||||
|
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
|
||||||
|
t.Fatalf("decode: %v", err)
|
||||||
|
}
|
||||||
|
if resp.APIToken != user.ApiToken {
|
||||||
|
t.Errorf("api_token = %q, want %q", resp.APIToken, user.ApiToken)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestRegenerateAPIToken_IssuesNewToken(t *testing.T) {
|
func TestRegenerateAPIToken_IssuesNewToken(t *testing.T) {
|
||||||
if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" {
|
if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" {
|
||||||
t.Skip("MINSTREL_TEST_DATABASE_URL not set")
|
t.Skip("MINSTREL_TEST_DATABASE_URL not set")
|
||||||
}
|
}
|
||||||
h, pool := testHandlers(t)
|
h, pool := testHandlers(t)
|
||||||
user := seedUser(t, pool, "tok2", "pw", false)
|
user := seedUser(t, pool, "tok2", "pw", false)
|
||||||
oldHash := user.ApiTokenHash
|
oldToken := user.ApiToken
|
||||||
|
|
||||||
req := httptest.NewRequest(http.MethodPost, "/api/me/api-token", nil)
|
req := httptest.NewRequest(http.MethodPost, "/api/me/api-token", nil)
|
||||||
req = withUser(req, user)
|
req = withUser(req, user)
|
||||||
@@ -41,20 +65,20 @@ func TestRegenerateAPIToken_IssuesNewToken(t *testing.T) {
|
|||||||
if resp.APIToken == "" {
|
if resp.APIToken == "" {
|
||||||
t.Fatalf("api_token is empty")
|
t.Fatalf("api_token is empty")
|
||||||
}
|
}
|
||||||
// The DB holds the new key's hash, never the key, and the old key no
|
if resp.APIToken == oldToken {
|
||||||
// longer matches.
|
t.Errorf("api_token unchanged after regenerate")
|
||||||
var dbHash string
|
}
|
||||||
|
|
||||||
|
// Verify DB row has the new token and old token no longer matches.
|
||||||
|
var dbToken string
|
||||||
if err := pool.QueryRow(context.Background(),
|
if err := pool.QueryRow(context.Background(),
|
||||||
"SELECT api_token_hash FROM users WHERE id = $1", user.ID).Scan(&dbHash); err != nil {
|
"SELECT api_token FROM users WHERE id = $1", user.ID).Scan(&dbToken); err != nil {
|
||||||
t.Fatalf("read token hash: %v", err)
|
t.Fatalf("read token: %v", err)
|
||||||
}
|
}
|
||||||
if dbHash != auth.HashAPIToken(resp.APIToken) {
|
if dbToken != resp.APIToken {
|
||||||
t.Errorf("DB api_token_hash = %q, want hash of the returned key", dbHash)
|
t.Errorf("DB api_token = %q, want %q", dbToken, resp.APIToken)
|
||||||
}
|
}
|
||||||
if dbHash == oldHash {
|
if dbToken == oldToken {
|
||||||
t.Errorf("old key hash still in DB after regenerate")
|
t.Errorf("old token still in DB after regenerate")
|
||||||
}
|
|
||||||
if dbHash == resp.APIToken {
|
|
||||||
t.Errorf("DB holds the raw key")
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -117,7 +117,7 @@ func (h *handlers) handleGetCover(w http.ResponseWriter, r *http.Request) {
|
|||||||
// clients skip the conditional GET for the bulk of a session, but
|
// clients skip the conditional GET for the bulk of a session, but
|
||||||
// stale art clears within 24h after a re-scan. ServeContent below
|
// stale art clears within 24h after a re-scan. ServeContent below
|
||||||
// still emits Last-Modified for the conditional path when needed.
|
// still emits Last-Modified for the conditional path when needed.
|
||||||
w.Header().Set("Cache-Control", "private, max-age=86400, must-revalidate")
|
w.Header().Set("Cache-Control", "public, max-age=86400, must-revalidate")
|
||||||
http.ServeContent(w, r, filepath.Base(path), info.ModTime(), f)
|
http.ServeContent(w, r, filepath.Base(path), info.ModTime(), f)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -197,6 +197,6 @@ func (h *handlers) handleGetStream(w http.ResponseWriter, r *http.Request) {
|
|||||||
// max-age + immutable lets the client cache (LockCachingAudioSource
|
// max-age + immutable lets the client cache (LockCachingAudioSource
|
||||||
// on the Flutter side, browser cache on web) skip even the
|
// on the Flutter side, browser cache on web) skip even the
|
||||||
// conditional GET on repeat plays.
|
// conditional GET on repeat plays.
|
||||||
w.Header().Set("Cache-Control", "private, max-age=31536000, immutable")
|
w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
|
||||||
http.ServeContent(w, r, filepath.Base(track.FilePath), info.ModTime(), f)
|
http.ServeContent(w, r, filepath.Base(track.FilePath), info.ModTime(), f)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -406,7 +406,7 @@ func (h *handlers) handleGetPlaylistCover(w http.ResponseWriter, r *http.Request
|
|||||||
// (system playlists re-rendered on rebuild, user playlists when
|
// (system playlists re-rendered on rebuild, user playlists when
|
||||||
// modified). 5 minutes is short enough for normal edits to feel
|
// modified). 5 minutes is short enough for normal edits to feel
|
||||||
// fresh, long enough to skip repeat fetches during a session.
|
// fresh, long enough to skip repeat fetches during a session.
|
||||||
w.Header().Set("Cache-Control", "private, max-age=300, must-revalidate")
|
w.Header().Set("Cache-Control", "public, max-age=300, must-revalidate")
|
||||||
http.ServeFile(w, r, full)
|
http.ServeFile(w, r, full)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+2
-24
@@ -87,24 +87,10 @@ func (h *handlers) handleRadio(w http.ResponseWriter, r *http.Request) {
|
|||||||
currentVec.DeviceClass = latestDeviceClass(r.Context(), q, user.ID, h.logger)
|
currentVec.DeviceClass = latestDeviceClass(r.Context(), q, user.ID, h.logger)
|
||||||
|
|
||||||
exclude := parseExcludeParam(r.URL.Query().Get("exclude"))
|
exclude := parseExcludeParam(r.URL.Query().Get("exclude"))
|
||||||
// Size the pool to the library (#3880). A fixed ~170 candidates samples a
|
limits := recommendation.DefaultCandidateSourceLimits()
|
||||||
// shrinking fraction of a growing collection, which is what made the
|
|
||||||
// recommendations feel less relevant as the library grew. Degrades to the
|
|
||||||
// base limits if the count is unavailable — never fails the request over a
|
|
||||||
// sizing hint.
|
|
||||||
librarySize := h.librarySize.Get(r.Context(), func(ctx context.Context) (int64, error) {
|
|
||||||
return recommendation.CountLibraryTracks(ctx, q)
|
|
||||||
})
|
|
||||||
limits := recommendation.ScaleForLibrary(
|
|
||||||
recommendation.DefaultCandidateSourceLimits(), librarySize,
|
|
||||||
)
|
|
||||||
candidates, err := recommendation.LoadCandidatesFromSimilarity(
|
candidates, err := recommendation.LoadCandidatesFromSimilarity(
|
||||||
r.Context(), q, user.ID, seedID,
|
r.Context(), q, user.ID, seedID,
|
||||||
h.recCfg.RecentlyPlayedHours, currentVec, exclude, limits,
|
h.recCfg.RecentlyPlayedHours, currentVec, exclude, limits,
|
||||||
// A fresh seed per request (#3889): radio is a new session each time
|
|
||||||
// and SHOULD draw differently. The system mixes are the surfaces that
|
|
||||||
// promise repeatability; this is not one of them.
|
|
||||||
strconv.FormatInt(time.Now().UnixNano(), 36),
|
|
||||||
)
|
)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
h.logger.Warn("api: radio: similarity-pool failed; falling back to whole-library", "err", err)
|
h.logger.Warn("api: radio: similarity-pool failed; falling back to whole-library", "err", err)
|
||||||
@@ -122,15 +108,7 @@ func (h *handlers) handleRadio(w http.ResponseWriter, r *http.Request) {
|
|||||||
// Scoring weights come from the DB-backed tuning lab (#1250) —
|
// Scoring weights come from the DB-backed tuning lab (#1250) —
|
||||||
// read per request so an admin change takes effect live.
|
// read per request so an admin change takes effect live.
|
||||||
weights := h.recSettings.Weights(recsettings.ScopeRadio)
|
weights := h.recSettings.Weights(recsettings.ScopeRadio)
|
||||||
// Diversity caps (#3882). Radio had none while every sibling surface did,
|
picks := recommendation.Shuffle(candidates, weights, time.Now().UTC(), h.rng, limit-1)
|
||||||
// which is how a whole session could come back from one artist. Scaled to
|
|
||||||
// the requested length so a 20-track radio and a 200-track one are capped
|
|
||||||
// alike; Shuffle relaxes them rather than returning a short radio.
|
|
||||||
//
|
|
||||||
// limit-1 because the seed track occupies the first slot and is prepended
|
|
||||||
// below — the caps govern the tracks that FOLLOW it.
|
|
||||||
caps := recommendation.RadioDiversityCaps(limit - 1)
|
|
||||||
picks := recommendation.Shuffle(candidates, weights, time.Now().UTC(), h.rng, limit-1, caps)
|
|
||||||
|
|
||||||
out := make([]TrackRef, 0, len(picks)+1)
|
out := make([]TrackRef, 0, len(picks)+1)
|
||||||
out = append(out, trackRefFrom(track, album.Title, artist.Name))
|
out = append(out, trackRefFrom(track, album.Title, artist.Name))
|
||||||
|
|||||||
@@ -1,139 +0,0 @@
|
|||||||
package api
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"errors"
|
|
||||||
"net/http"
|
|
||||||
"net/http/httptest"
|
|
||||||
"strings"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"github.com/jackc/pgx/v5"
|
|
||||||
"github.com/jackc/pgx/v5/pgtype"
|
|
||||||
"github.com/jackc/pgx/v5/pgxpool"
|
|
||||||
|
|
||||||
"git.fabledsword.com/bvandeusen/minstrel/internal/auth"
|
|
||||||
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
|
|
||||||
)
|
|
||||||
|
|
||||||
func sessionExists(t *testing.T, pool *pgxpool.Pool, id pgtype.UUID) bool {
|
|
||||||
t.Helper()
|
|
||||||
var exists bool
|
|
||||||
if err := pool.QueryRow(context.Background(),
|
|
||||||
`SELECT EXISTS (SELECT 1 FROM sessions WHERE id = $1)`, id,
|
|
||||||
).Scan(&exists); err != nil {
|
|
||||||
t.Fatalf("exists check: %v", err)
|
|
||||||
}
|
|
||||||
return exists
|
|
||||||
}
|
|
||||||
|
|
||||||
// Sessions expire server-side on two limits, and an expired one stops
|
|
||||||
// authenticating at once rather than when the GC sweep gets to it.
|
|
||||||
func TestSessionExpiry_IdleAndAbsoluteLimits(t *testing.T) {
|
|
||||||
_, pool := testHandlers(t)
|
|
||||||
user := seedUser(t, pool, "alice", "hunter2", false)
|
|
||||||
q := dbq.New(pool)
|
|
||||||
|
|
||||||
mint := func(setup string) []byte {
|
|
||||||
token, err := auth.MintSessionToken()
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("mint: %v", err)
|
|
||||||
}
|
|
||||||
hash := auth.HashSessionToken(token)
|
|
||||||
sess, err := q.InsertSession(context.Background(), dbq.InsertSessionParams{
|
|
||||||
UserID: user.ID, TokenHash: hash, UserAgent: "test", Ip: "192.0.2.1",
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("insert: %v", err)
|
|
||||||
}
|
|
||||||
if setup != "" {
|
|
||||||
if _, err := pool.Exec(context.Background(), `UPDATE sessions SET `+setup+` WHERE id = $1`, sess.ID); err != nil {
|
|
||||||
t.Fatalf("age session: %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return hash
|
|
||||||
}
|
|
||||||
|
|
||||||
fresh := mint("")
|
|
||||||
idle := mint(`last_seen_at = now() - interval '31 days'`)
|
|
||||||
old := mint(`created_at = now() - interval '366 days'`)
|
|
||||||
|
|
||||||
if _, err := q.GetSessionByTokenHash(context.Background(), fresh); err != nil {
|
|
||||||
t.Errorf("fresh session: %v, want found", err)
|
|
||||||
}
|
|
||||||
for name, hash := range map[string][]byte{"idle": idle, "absolute": old} {
|
|
||||||
if _, err := q.GetSessionByTokenHash(context.Background(), hash); !errors.Is(err, pgx.ErrNoRows) {
|
|
||||||
t.Errorf("%s-expired session: err = %v, want ErrNoRows", name, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
listed, err := q.ListSessionsForUser(context.Background(), user.ID)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("list: %v", err)
|
|
||||||
}
|
|
||||||
if len(listed) != 1 {
|
|
||||||
t.Errorf("listed %d sessions, want only the live one", len(listed))
|
|
||||||
}
|
|
||||||
|
|
||||||
swept, err := q.GcDeleteExpiredSessions(context.Background())
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("gc: %v", err)
|
|
||||||
}
|
|
||||||
if swept != 2 {
|
|
||||||
t.Errorf("gc swept %d, want the 2 expired rows", swept)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Changing your password signs out every other device and keeps this one.
|
|
||||||
func TestHandleChangePassword_RevokesOtherSessions(t *testing.T) {
|
|
||||||
h, pool := testHandlers(t)
|
|
||||||
user := seedUser(t, pool, "alice", "hunter2", false)
|
|
||||||
current := seedSession(t, pool, user.ID, "192.0.2.1")
|
|
||||||
other := seedSession(t, pool, user.ID, "198.51.100.7")
|
|
||||||
|
|
||||||
body := strings.NewReader(`{"current_password":"hunter2","new_password":"correct-horse"}`)
|
|
||||||
req := httptest.NewRequest(http.MethodPut, "/api/me/password", body)
|
|
||||||
req.Header.Set("Content-Type", "application/json")
|
|
||||||
req = withSession(req, user, current)
|
|
||||||
w := httptest.NewRecorder()
|
|
||||||
h.handleChangePassword(w, req)
|
|
||||||
|
|
||||||
if w.Code != http.StatusNoContent {
|
|
||||||
t.Fatalf("status = %d body = %s", w.Code, w.Body.String())
|
|
||||||
}
|
|
||||||
if !sessionExists(t, pool, current) {
|
|
||||||
t.Error("the device that changed the password was signed out")
|
|
||||||
}
|
|
||||||
if sessionExists(t, pool, other) {
|
|
||||||
t.Error("another device's session survived the password change")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// A reset by email ends every session the account has.
|
|
||||||
func TestHandleResetPassword_RevokesAllSessions(t *testing.T) {
|
|
||||||
h, pool := testHandlers(t)
|
|
||||||
user := seedUser(t, pool, "alice", "hunter2", false)
|
|
||||||
s1 := seedSession(t, pool, user.ID, "192.0.2.1")
|
|
||||||
s2 := seedSession(t, pool, user.ID, "198.51.100.7")
|
|
||||||
|
|
||||||
const token = "reset-token-for-session-lifecycle-test"
|
|
||||||
if _, err := pool.Exec(context.Background(),
|
|
||||||
`INSERT INTO password_resets (token, user_id, expires_at) VALUES ($1, $2, now() + interval '1 hour')`,
|
|
||||||
token, user.ID,
|
|
||||||
); err != nil {
|
|
||||||
t.Fatalf("seed reset: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
body := strings.NewReader(`{"token":"` + token + `","new_password":"correct-horse"}`)
|
|
||||||
req := httptest.NewRequest(http.MethodPost, "/api/auth/reset-password", body)
|
|
||||||
req.Header.Set("Content-Type", "application/json")
|
|
||||||
w := httptest.NewRecorder()
|
|
||||||
h.handleResetPassword(w, req)
|
|
||||||
|
|
||||||
if w.Code != http.StatusNoContent {
|
|
||||||
t.Fatalf("status = %d body = %s", w.Code, w.Body.String())
|
|
||||||
}
|
|
||||||
if sessionExists(t, pool, s1) || sessionExists(t, pool, s2) {
|
|
||||||
t.Error("a session survived the password reset")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -54,10 +54,6 @@ func Unauthorized(code, message string) *Error {
|
|||||||
return &Error{Status: 401, Code: code, Message: message}
|
return &Error{Status: 401, Code: code, Message: message}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TooManyRequests(code, message string) *Error {
|
|
||||||
return &Error{Status: 429, Code: code, Message: message}
|
|
||||||
}
|
|
||||||
|
|
||||||
func Internal(cause error) *Error {
|
func Internal(cause error) *Error {
|
||||||
return &Error{Status: 500, Code: "server_error", Message: "internal server error", Cause: cause}
|
return &Error{Status: 500, Code: "server_error", Message: "internal server error", Cause: cause}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -55,11 +55,6 @@ const (
|
|||||||
// exercised.
|
// exercised.
|
||||||
ActionSessionRevoke Action = "session_revoke"
|
ActionSessionRevoke Action = "session_revoke"
|
||||||
ActionSessionRevokeOthers Action = "session_revoke_others"
|
ActionSessionRevokeOthers Action = "session_revoke_others"
|
||||||
|
|
||||||
// Duplicate merge (#3911). Irreversible: a copy's file and row are removed
|
|
||||||
// and its history moved onto the copy kept. The metadata names both, so the
|
|
||||||
// log can answer "where did that file go" long after the report is gone.
|
|
||||||
ActionDuplicateMerge Action = "duplicate_merge"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// Write inserts one audit_log row. metadata is marshaled as JSON;
|
// Write inserts one audit_log row. metadata is marshaled as JSON;
|
||||||
|
|||||||
@@ -168,7 +168,6 @@ func TestWrite_AllActionConstantsArePersisted(t *testing.T) {
|
|||||||
audit.ActionTokenRegenerate,
|
audit.ActionTokenRegenerate,
|
||||||
audit.ActionForgotPasswordInit,
|
audit.ActionForgotPasswordInit,
|
||||||
audit.ActionPasswordResetByEmail,
|
audit.ActionPasswordResetByEmail,
|
||||||
audit.ActionDuplicateMerge,
|
|
||||||
}
|
}
|
||||||
for _, a := range actions {
|
for _, a := range actions {
|
||||||
if err := audit.Write(context.Background(), pool, nilUUID, nilUUID, a, nil); err != nil {
|
if err := audit.Write(context.Background(), pool, nilUUID, nilUUID, a, nil); err != nil {
|
||||||
|
|||||||
@@ -65,36 +65,6 @@ func ClientIP(r *http.Request, trustedProxyHops int) string {
|
|||||||
return remote
|
return remote
|
||||||
}
|
}
|
||||||
|
|
||||||
// IsHTTPS reports whether the client reached us over HTTPS, reading through
|
|
||||||
// trustedProxyHops reverse proxies by the same rule as ClientIP.
|
|
||||||
//
|
|
||||||
// TLS terminates at the operator's proxy (rule 94), so r.TLS is nil in every
|
|
||||||
// real deployment and only X-Forwarded-Proto can say what the client used.
|
|
||||||
// That header is believed only when hops >= 1: with no trusted proxy it is
|
|
||||||
// just something any client can send. Proxies that append rather than
|
|
||||||
// overwrite produce a comma list, read positionally like X-Forwarded-For.
|
|
||||||
//
|
|
||||||
// This decides only HTTPS-only behaviour (the cookie Secure flag, HSTS). It
|
|
||||||
// must never drive a redirect: plain-HTTP and LAN use keep working.
|
|
||||||
func IsHTTPS(r *http.Request, trustedProxyHops int) bool {
|
|
||||||
if r.TLS != nil {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
if trustedProxyHops <= 0 {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
raw := r.Header.Get("X-Forwarded-Proto")
|
|
||||||
if strings.TrimSpace(raw) == "" {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
parts := strings.Split(raw, ",")
|
|
||||||
idx := len(parts) - trustedProxyHops
|
|
||||||
if idx < 0 {
|
|
||||||
idx = 0
|
|
||||||
}
|
|
||||||
return strings.EqualFold(strings.TrimSpace(parts[idx]), "https")
|
|
||||||
}
|
|
||||||
|
|
||||||
// forwardedChain returns the X-Forwarded-For entries in wire order, or the
|
// forwardedChain returns the X-Forwarded-For entries in wire order, or the
|
||||||
// single X-Real-IP value when XFF is absent.
|
// single X-Real-IP value when XFF is absent.
|
||||||
//
|
//
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
package auth
|
package auth
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"crypto/tls"
|
|
||||||
"net/http"
|
"net/http"
|
||||||
"testing"
|
"testing"
|
||||||
)
|
)
|
||||||
@@ -169,45 +168,3 @@ func TestClientIP(t *testing.T) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestIsHTTPS(t *testing.T) {
|
|
||||||
tests := []struct {
|
|
||||||
name string
|
|
||||||
hops int
|
|
||||||
proto string
|
|
||||||
tls bool
|
|
||||||
want bool
|
|
||||||
}{
|
|
||||||
// The three cases rule 94 names.
|
|
||||||
{name: "hops 0 ignores a forwarded https", hops: 0, proto: "https", want: false},
|
|
||||||
{name: "hops 1 believes a forwarded https", hops: 1, proto: "https", want: true},
|
|
||||||
{name: "plain request is not https", hops: 1, want: false},
|
|
||||||
|
|
||||||
{name: "forwarded http is not https", hops: 1, proto: "http", want: false},
|
|
||||||
{name: "case-insensitive", hops: 1, proto: "HTTPS", want: true},
|
|
||||||
{name: "direct TLS is https whatever the hops", hops: 0, tls: true, want: true},
|
|
||||||
// An appending chain is read positionally: with one trusted hop the
|
|
||||||
// last entry is our proxy's word, and a client-supplied first entry
|
|
||||||
// cannot flip it.
|
|
||||||
{name: "appended chain reads our proxy's entry", hops: 1, proto: "https, http", want: false},
|
|
||||||
{name: "two hops read the CDN's entry", hops: 2, proto: "https, http", want: true},
|
|
||||||
{name: "over-counted hops clamp to the first entry", hops: 5, proto: "https", want: true},
|
|
||||||
}
|
|
||||||
for _, tc := range tests {
|
|
||||||
t.Run(tc.name, func(t *testing.T) {
|
|
||||||
r, err := http.NewRequest(http.MethodGet, "/api/auth/login", nil)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("NewRequest: %v", err)
|
|
||||||
}
|
|
||||||
if tc.proto != "" {
|
|
||||||
r.Header.Set("X-Forwarded-Proto", tc.proto)
|
|
||||||
}
|
|
||||||
if tc.tls {
|
|
||||||
r.TLS = &tls.ConnectionState{}
|
|
||||||
}
|
|
||||||
if got := IsHTTPS(r, tc.hops); got != tc.want {
|
|
||||||
t.Errorf("IsHTTPS(hops=%d, proto=%q) = %v, want %v", tc.hops, tc.proto, got, tc.want)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,205 +0,0 @@
|
|||||||
package auth
|
|
||||||
|
|
||||||
import (
|
|
||||||
"strings"
|
|
||||||
"sync"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"golang.org/x/crypto/bcrypt"
|
|
||||||
)
|
|
||||||
|
|
||||||
// AttemptLimiter caps how many attempts a key may make inside a fixed
|
|
||||||
// window. It is the throttle in front of every password-shaped check:
|
|
||||||
// native login, register, forgot/reset password and Subsonic /rest auth.
|
|
||||||
//
|
|
||||||
// In memory on purpose. Minstrel is a single process, the counts only need
|
|
||||||
// to outlive a guessing run rather than a restart, and a table would put a
|
|
||||||
// write on every failed login. Each key costs one small struct, and expired
|
|
||||||
// keys are swept as the map grows, so a spray across many addresses cannot
|
|
||||||
// hold memory past one window.
|
|
||||||
type AttemptLimiter struct {
|
|
||||||
max int
|
|
||||||
window time.Duration
|
|
||||||
now func() time.Time
|
|
||||||
|
|
||||||
mu sync.Mutex
|
|
||||||
buckets map[string]*attemptBucket
|
|
||||||
nextSweep int
|
|
||||||
}
|
|
||||||
|
|
||||||
type attemptBucket struct {
|
|
||||||
count int
|
|
||||||
start time.Time
|
|
||||||
}
|
|
||||||
|
|
||||||
// sweepFloor is the map size below which expired keys are left in place;
|
|
||||||
// past it, a sweep runs whenever the map doubles from its last swept size.
|
|
||||||
const sweepFloor = 1024
|
|
||||||
|
|
||||||
// NewAttemptLimiter returns a limiter allowing max attempts per key per
|
|
||||||
// window.
|
|
||||||
func NewAttemptLimiter(max int, window time.Duration) *AttemptLimiter {
|
|
||||||
return &AttemptLimiter{
|
|
||||||
max: max,
|
|
||||||
window: window,
|
|
||||||
now: time.Now,
|
|
||||||
buckets: map[string]*attemptBucket{},
|
|
||||||
nextSweep: sweepFloor,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Blocked reports whether key has used its attempts for the current window,
|
|
||||||
// and if so how long until the window resets. It records nothing, so a check
|
|
||||||
// can run before the expensive work and the outcome be recorded after.
|
|
||||||
func (l *AttemptLimiter) Blocked(key string) (bool, time.Duration) {
|
|
||||||
if l == nil || key == "" {
|
|
||||||
return false, 0
|
|
||||||
}
|
|
||||||
l.mu.Lock()
|
|
||||||
defer l.mu.Unlock()
|
|
||||||
b, ok := l.buckets[key]
|
|
||||||
if !ok {
|
|
||||||
return false, 0
|
|
||||||
}
|
|
||||||
now := l.now()
|
|
||||||
if now.Sub(b.start) >= l.window {
|
|
||||||
delete(l.buckets, key)
|
|
||||||
return false, 0
|
|
||||||
}
|
|
||||||
if b.count < l.max {
|
|
||||||
return false, 0
|
|
||||||
}
|
|
||||||
return true, b.start.Add(l.window).Sub(now)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Record counts one attempt against key.
|
|
||||||
func (l *AttemptLimiter) Record(key string) {
|
|
||||||
if l == nil || key == "" {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
l.mu.Lock()
|
|
||||||
defer l.mu.Unlock()
|
|
||||||
now := l.now()
|
|
||||||
b, ok := l.buckets[key]
|
|
||||||
if !ok || now.Sub(b.start) >= l.window {
|
|
||||||
l.buckets[key] = &attemptBucket{count: 1, start: now}
|
|
||||||
l.maybeSweep(now)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
b.count++
|
|
||||||
}
|
|
||||||
|
|
||||||
// Reset forgets key, as after a successful login: the user who finally got
|
|
||||||
// their password right should not carry their typos into the next window.
|
|
||||||
func (l *AttemptLimiter) Reset(key string) {
|
|
||||||
if l == nil || key == "" {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
l.mu.Lock()
|
|
||||||
defer l.mu.Unlock()
|
|
||||||
delete(l.buckets, key)
|
|
||||||
}
|
|
||||||
|
|
||||||
// maybeSweep drops expired buckets once the map has doubled since the last
|
|
||||||
// sweep. Callers hold l.mu.
|
|
||||||
func (l *AttemptLimiter) maybeSweep(now time.Time) {
|
|
||||||
if len(l.buckets) < l.nextSweep {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
for k, b := range l.buckets {
|
|
||||||
if now.Sub(b.start) >= l.window {
|
|
||||||
delete(l.buckets, k)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
l.nextSweep = max(sweepFloor, 2*len(l.buckets))
|
|
||||||
}
|
|
||||||
|
|
||||||
// LoginGuard pairs a per-account and a per-address limiter, the shape every
|
|
||||||
// password check uses. The account limit stops a slow guess at one user from
|
|
||||||
// many addresses; the address limit stops one address spraying many users.
|
|
||||||
// Only failures are recorded, so a user who signs in correctly is never
|
|
||||||
// counted at all.
|
|
||||||
type LoginGuard struct {
|
|
||||||
account *AttemptLimiter
|
|
||||||
address *AttemptLimiter
|
|
||||||
}
|
|
||||||
|
|
||||||
// Login limits: 10 failures per account and 50 per address per 15 minutes,
|
|
||||||
// the same numbers ThoughtSync settled on. Generous enough that a user
|
|
||||||
// fumbling a password manager never meets them, tight enough that an online
|
|
||||||
// guess against bcrypt gets ~1,000 tries a day per account.
|
|
||||||
const (
|
|
||||||
loginWindow = 15 * time.Minute
|
|
||||||
loginAccountMax = 10
|
|
||||||
loginAddressMax = 50
|
|
||||||
)
|
|
||||||
|
|
||||||
// NewLoginGuard returns a guard with the default login limits.
|
|
||||||
func NewLoginGuard() *LoginGuard {
|
|
||||||
return &LoginGuard{
|
|
||||||
account: NewAttemptLimiter(loginAccountMax, loginWindow),
|
|
||||||
address: NewAttemptLimiter(loginAddressMax, loginWindow),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Blocked reports whether either the account or the address is over its
|
|
||||||
// limit, with the longer of the two waits. Check it BEFORE verifying the
|
|
||||||
// password, so a blocked guess costs no bcrypt.
|
|
||||||
func (g *LoginGuard) Blocked(account, address string) (bool, time.Duration) {
|
|
||||||
if g == nil {
|
|
||||||
return false, 0
|
|
||||||
}
|
|
||||||
aBlocked, aWait := g.account.Blocked(accountKey(account))
|
|
||||||
ipBlocked, ipWait := g.address.Blocked(address)
|
|
||||||
return aBlocked || ipBlocked, max(aWait, ipWait)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fail records a failed attempt against both the account and the address.
|
|
||||||
// An unknown username counts against its name all the same, so the limit
|
|
||||||
// gives away nothing about which accounts exist.
|
|
||||||
func (g *LoginGuard) Fail(account, address string) {
|
|
||||||
if g == nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
g.account.Record(accountKey(account))
|
|
||||||
g.address.Record(address)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Succeed clears the account's failures. The address keeps its count: one
|
|
||||||
// address that guessed fifty accounts and got one right is still spraying.
|
|
||||||
func (g *LoginGuard) Succeed(account string) {
|
|
||||||
if g == nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
g.account.Reset(accountKey(account))
|
|
||||||
}
|
|
||||||
|
|
||||||
// accountKey folds case so "Admin" and "admin" share one budget. Usernames
|
|
||||||
// are compared exactly by the lookup, but the guesser shouldn't get a fresh
|
|
||||||
// allowance per capitalisation.
|
|
||||||
func accountKey(account string) string {
|
|
||||||
return strings.ToLower(strings.TrimSpace(account))
|
|
||||||
}
|
|
||||||
|
|
||||||
var (
|
|
||||||
dummyHashOnce sync.Once
|
|
||||||
dummyHash []byte
|
|
||||||
)
|
|
||||||
|
|
||||||
// DummyVerify spends the same bcrypt time a real password check would, for
|
|
||||||
// the path where the username doesn't exist. Without it, an unknown user
|
|
||||||
// answers in microseconds and a known one in ~50ms, and the uniform error
|
|
||||||
// message hides nothing.
|
|
||||||
func DummyVerify(plaintext string) {
|
|
||||||
dummyHashOnce.Do(func() {
|
|
||||||
// What the hash is of doesn't matter — no account carries it. Its
|
|
||||||
// cost does: DefaultCost, the same as every stored password.
|
|
||||||
h, err := bcrypt.GenerateFromPassword([]byte("minstrel-dummy-password"), bcrypt.DefaultCost)
|
|
||||||
if err == nil {
|
|
||||||
dummyHash = h
|
|
||||||
}
|
|
||||||
})
|
|
||||||
if dummyHash != nil {
|
|
||||||
_ = bcrypt.CompareHashAndPassword(dummyHash, []byte(plaintext))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,114 +0,0 @@
|
|||||||
package auth
|
|
||||||
|
|
||||||
import (
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
// fakeClock lets a test step through a window without sleeping.
|
|
||||||
type fakeClock struct{ t time.Time }
|
|
||||||
|
|
||||||
func (c *fakeClock) now() time.Time { return c.t }
|
|
||||||
|
|
||||||
func newTestLimiter(max int, window time.Duration) (*AttemptLimiter, *fakeClock) {
|
|
||||||
c := &fakeClock{t: time.Date(2026, 10, 6, 12, 0, 0, 0, time.UTC)}
|
|
||||||
l := NewAttemptLimiter(max, window)
|
|
||||||
l.now = c.now
|
|
||||||
return l, c
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestAttemptLimiter_BlocksAtMaxAndReportsWait(t *testing.T) {
|
|
||||||
l, c := newTestLimiter(3, 15*time.Minute)
|
|
||||||
for i := 0; i < 3; i++ {
|
|
||||||
if blocked, _ := l.Blocked("k"); blocked {
|
|
||||||
t.Fatalf("blocked after %d attempts, want allowed below max", i)
|
|
||||||
}
|
|
||||||
l.Record("k")
|
|
||||||
}
|
|
||||||
c.t = c.t.Add(5 * time.Minute)
|
|
||||||
blocked, wait := l.Blocked("k")
|
|
||||||
if !blocked {
|
|
||||||
t.Fatal("not blocked after max attempts")
|
|
||||||
}
|
|
||||||
if wait != 10*time.Minute {
|
|
||||||
t.Errorf("wait = %v, want the 10m left in the window", wait)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestAttemptLimiter_WindowExpiryClears(t *testing.T) {
|
|
||||||
l, c := newTestLimiter(1, time.Minute)
|
|
||||||
l.Record("k")
|
|
||||||
if blocked, _ := l.Blocked("k"); !blocked {
|
|
||||||
t.Fatal("want blocked inside the window")
|
|
||||||
}
|
|
||||||
c.t = c.t.Add(time.Minute)
|
|
||||||
if blocked, _ := l.Blocked("k"); blocked {
|
|
||||||
t.Fatal("still blocked once the window has passed")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestAttemptLimiter_KeysAreIndependentAndResetClears(t *testing.T) {
|
|
||||||
l, _ := newTestLimiter(1, time.Minute)
|
|
||||||
l.Record("a")
|
|
||||||
if blocked, _ := l.Blocked("b"); blocked {
|
|
||||||
t.Fatal("one key's attempts blocked another")
|
|
||||||
}
|
|
||||||
l.Reset("a")
|
|
||||||
if blocked, _ := l.Blocked("a"); blocked {
|
|
||||||
t.Fatal("Reset did not clear the key")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestAttemptLimiter_SweepDropsExpiredKeys(t *testing.T) {
|
|
||||||
l, c := newTestLimiter(5, time.Minute)
|
|
||||||
// One short of the floor: no sweep yet, however stale these become.
|
|
||||||
for i := 0; i < sweepFloor-1; i++ {
|
|
||||||
l.Record("k" + time.Duration(i).String())
|
|
||||||
}
|
|
||||||
c.t = c.t.Add(2 * time.Minute)
|
|
||||||
l.Record("fresh") // reaches the floor and triggers a sweep
|
|
||||||
if n := len(l.buckets); n != 1 {
|
|
||||||
t.Errorf("buckets after sweep = %d, want only the fresh key", n)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestAttemptLimiter_NilAndEmptyKeyAreNoOps(t *testing.T) {
|
|
||||||
var l *AttemptLimiter
|
|
||||||
l.Record("k")
|
|
||||||
if blocked, _ := l.Blocked("k"); blocked {
|
|
||||||
t.Error("nil limiter blocked")
|
|
||||||
}
|
|
||||||
real, _ := newTestLimiter(1, time.Minute)
|
|
||||||
real.Record("")
|
|
||||||
if blocked, _ := real.Blocked(""); blocked {
|
|
||||||
t.Error("empty key was counted")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestLoginGuard_AccountLimitSpansAddressesAndFoldsCase(t *testing.T) {
|
|
||||||
g := NewLoginGuard()
|
|
||||||
for i := 0; i < loginAccountMax; i++ {
|
|
||||||
g.Fail("Alice", "10.0.0."+string(rune('0'+i%10)))
|
|
||||||
}
|
|
||||||
if blocked, _ := g.Blocked("alice", "192.0.2.1"); !blocked {
|
|
||||||
t.Fatal("account limit should hold from a fresh address and any capitalisation")
|
|
||||||
}
|
|
||||||
g.Succeed("ALICE")
|
|
||||||
if blocked, _ := g.Blocked("alice", "192.0.2.1"); blocked {
|
|
||||||
t.Fatal("Succeed should clear the account's failures")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestLoginGuard_AddressLimitSpansAccounts(t *testing.T) {
|
|
||||||
g := NewLoginGuard()
|
|
||||||
for i := 0; i < loginAddressMax; i++ {
|
|
||||||
g.Fail("user"+time.Duration(i).String(), "203.0.113.9")
|
|
||||||
}
|
|
||||||
if blocked, _ := g.Blocked("someone-new", "203.0.113.9"); !blocked {
|
|
||||||
t.Fatal("address that sprayed many accounts should be blocked")
|
|
||||||
}
|
|
||||||
g.Succeed("someone-new")
|
|
||||||
if blocked, _ := g.Blocked("someone-new", "203.0.113.9"); !blocked {
|
|
||||||
t.Fatal("a success must not clear the address count")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -5,7 +5,6 @@ import (
|
|||||||
"crypto/rand"
|
"crypto/rand"
|
||||||
"crypto/sha256"
|
"crypto/sha256"
|
||||||
"encoding/base64"
|
"encoding/base64"
|
||||||
"encoding/hex"
|
|
||||||
"errors"
|
"errors"
|
||||||
"log/slog"
|
"log/slog"
|
||||||
"net/http"
|
"net/http"
|
||||||
@@ -42,15 +41,6 @@ func HashSessionToken(token string) []byte {
|
|||||||
return sum[:]
|
return sum[:]
|
||||||
}
|
}
|
||||||
|
|
||||||
// HashAPIToken maps a raw API key (the OpenSubsonic apiKey) to the
|
|
||||||
// `users.api_token_hash` column: sha256, hex. The key is minted with
|
|
||||||
// MintSessionToken, so it carries the same 256 bits and the same reasoning
|
|
||||||
// as HashSessionToken applies. Hex rather than bytes so the column stays
|
|
||||||
// text and a migration can compute it in SQL from the old plaintext.
|
|
||||||
func HashAPIToken(token string) string {
|
|
||||||
return hex.EncodeToString(HashSessionToken(token))
|
|
||||||
}
|
|
||||||
|
|
||||||
// VerifyPassword is the canonical bcrypt comparison. Returns false on a
|
// VerifyPassword is the canonical bcrypt comparison. Returns false on a
|
||||||
// malformed hash so callers don't need to distinguish "hash invalid" from
|
// malformed hash so callers don't need to distinguish "hash invalid" from
|
||||||
// "password wrong" — both are auth failures from the client's perspective.
|
// "password wrong" — both are auth failures from the client's perspective.
|
||||||
|
|||||||
@@ -1,46 +0,0 @@
|
|||||||
package auth
|
|
||||||
|
|
||||||
import (
|
|
||||||
"crypto/rand"
|
|
||||||
"crypto/subtle"
|
|
||||||
"encoding/hex"
|
|
||||||
)
|
|
||||||
|
|
||||||
// SetupToken guards the first-admin registration. Until the first account
|
|
||||||
// exists, register makes whoever calls it the admin, so a fresh instance on a
|
|
||||||
// public address belonged to whoever found it first. Now that call also has
|
|
||||||
// to carry this token, which is generated at startup and written only to the
|
|
||||||
// server log: proof that the caller can read the operator's logs.
|
|
||||||
//
|
|
||||||
// The token lives in memory. A restart mints a new one and logs it again,
|
|
||||||
// which is the behaviour wanted: an old token from a log line someone else
|
|
||||||
// saw stops working.
|
|
||||||
type SetupToken struct {
|
|
||||||
value string
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewSetupToken mints a 128-bit token.
|
|
||||||
func NewSetupToken() (*SetupToken, error) {
|
|
||||||
b := make([]byte, 16)
|
|
||||||
if _, err := rand.Read(b); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return &SetupToken{value: hex.EncodeToString(b)}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Value returns the token for logging.
|
|
||||||
func (t *SetupToken) Value() string {
|
|
||||||
if t == nil {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
return t.value
|
|
||||||
}
|
|
||||||
|
|
||||||
// Matches reports whether supplied is the token, in constant time. A nil
|
|
||||||
// token never matches anything, so a missing token fails closed.
|
|
||||||
func (t *SetupToken) Matches(supplied string) bool {
|
|
||||||
if t == nil || t.value == "" || supplied == "" {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
return subtle.ConstantTimeCompare([]byte(t.value), []byte(supplied)) == 1
|
|
||||||
}
|
|
||||||
@@ -42,7 +42,7 @@ func discardLogger() *slog.Logger { return slog.New(slog.NewTextHandler(io.Disca
|
|||||||
func seedUser(t *testing.T, q *dbq.Queries, name string) pgtype.UUID {
|
func seedUser(t *testing.T, q *dbq.Queries, name string) pgtype.UUID {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
u, err := q.CreateUser(context.Background(), dbq.CreateUserParams{
|
u, err := q.CreateUser(context.Background(), dbq.CreateUserParams{
|
||||||
Username: dbtest.TestUserPrefix + name, PasswordHash: "x", ApiTokenHash: name + "-tok", IsAdmin: false,
|
Username: dbtest.TestUserPrefix + name, PasswordHash: "x", ApiToken: name + "-tok", IsAdmin: false,
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("seed user %s: %v", name, err)
|
t.Fatalf("seed user %s: %v", name, err)
|
||||||
|
|||||||
@@ -1,457 +0,0 @@
|
|||||||
// Code generated by sqlc. DO NOT EDIT.
|
|
||||||
// versions:
|
|
||||||
// sqlc v1.31.1
|
|
||||||
// source: duplicates.sql
|
|
||||||
|
|
||||||
package dbq
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
|
|
||||||
"github.com/jackc/pgx/v5/pgtype"
|
|
||||||
)
|
|
||||||
|
|
||||||
const addDuplicateGroupMember = `-- name: AddDuplicateGroupMember :exec
|
|
||||||
INSERT INTO duplicate_group_members (group_id, track_id)
|
|
||||||
VALUES ($1, $2)
|
|
||||||
ON CONFLICT DO NOTHING
|
|
||||||
`
|
|
||||||
|
|
||||||
type AddDuplicateGroupMemberParams struct {
|
|
||||||
GroupID pgtype.UUID
|
|
||||||
TrackID pgtype.UUID
|
|
||||||
}
|
|
||||||
|
|
||||||
func (q *Queries) AddDuplicateGroupMember(ctx context.Context, arg AddDuplicateGroupMemberParams) error {
|
|
||||||
_, err := q.db.Exec(ctx, addDuplicateGroupMember, arg.GroupID, arg.TrackID)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
const countPendingDuplicateGroups = `-- name: CountPendingDuplicateGroups :one
|
|
||||||
SELECT count(*)::bigint
|
|
||||||
FROM duplicate_groups g
|
|
||||||
WHERE g.status = 'pending'
|
|
||||||
AND (SELECT count(*) FROM duplicate_group_members m WHERE m.group_id = g.id) >= 2
|
|
||||||
`
|
|
||||||
|
|
||||||
// Proposals awaiting review. A group left with one member — its other tracks
|
|
||||||
// deleted since the sweep — is no proposal at all and is not counted; the next
|
|
||||||
// sweep retires it.
|
|
||||||
func (q *Queries) CountPendingDuplicateGroups(ctx context.Context) (int64, error) {
|
|
||||||
row := q.db.QueryRow(ctx, countPendingDuplicateGroups)
|
|
||||||
var column_1 int64
|
|
||||||
err := row.Scan(&column_1)
|
|
||||||
return column_1, err
|
|
||||||
}
|
|
||||||
|
|
||||||
const deleteStalePendingDuplicateGroups = `-- name: DeleteStalePendingDuplicateGroups :execrows
|
|
||||||
DELETE FROM duplicate_groups g
|
|
||||||
WHERE g.status = 'pending'
|
|
||||||
AND g.last_seen_sweep_id IS DISTINCT FROM $1
|
|
||||||
AND (g.last_seen_sweep_id IS NULL
|
|
||||||
OR (SELECT s.started_at FROM duplicate_sweeps s WHERE s.id = g.last_seen_sweep_id)
|
|
||||||
< (SELECT s.started_at FROM duplicate_sweeps s WHERE s.id = $1))
|
|
||||||
`
|
|
||||||
|
|
||||||
// A pending proposal this sweep did not find again no longer describes the
|
|
||||||
// library: a member was re-fingerprinted, merged away or went missing. Dismissed
|
|
||||||
// groups are kept regardless — they are the memory of a decision.
|
|
||||||
//
|
|
||||||
// Only proposals last confirmed by an EARLIER sweep go. Should two sweeps ever
|
|
||||||
// overlap (a manual trigger racing the worker), neither may delete what the other
|
|
||||||
// has just found.
|
|
||||||
func (q *Queries) DeleteStalePendingDuplicateGroups(ctx context.Context, sweepID pgtype.UUID) (int64, error) {
|
|
||||||
result, err := q.db.Exec(ctx, deleteStalePendingDuplicateGroups, sweepID)
|
|
||||||
if err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
return result.RowsAffected(), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
const dismissDuplicateGroup = `-- name: DismissDuplicateGroup :execrows
|
|
||||||
UPDATE duplicate_groups
|
|
||||||
SET status = 'dismissed', resolved_at = now()
|
|
||||||
WHERE id = $1 AND status = 'pending'
|
|
||||||
`
|
|
||||||
|
|
||||||
// "These are not duplicates." Only a pending group can be dismissed; zero rows
|
|
||||||
// means it was already resolved or no longer exists.
|
|
||||||
func (q *Queries) DismissDuplicateGroup(ctx context.Context, id pgtype.UUID) (int64, error) {
|
|
||||||
result, err := q.db.Exec(ctx, dismissDuplicateGroup, id)
|
|
||||||
if err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
return result.RowsAffected(), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
const finishDuplicateSweep = `-- name: FinishDuplicateSweep :exec
|
|
||||||
UPDATE duplicate_sweeps
|
|
||||||
SET finished_at = now(),
|
|
||||||
candidates = $1,
|
|
||||||
groups_found = $2,
|
|
||||||
oversize_clusters = $3,
|
|
||||||
error_message = NULLIF($4::text, '')
|
|
||||||
WHERE id = $5
|
|
||||||
`
|
|
||||||
|
|
||||||
type FinishDuplicateSweepParams struct {
|
|
||||||
Candidates *int32
|
|
||||||
GroupsFound *int32
|
|
||||||
OversizeClusters *int32
|
|
||||||
ErrorMessage string
|
|
||||||
ID pgtype.UUID
|
|
||||||
}
|
|
||||||
|
|
||||||
func (q *Queries) FinishDuplicateSweep(ctx context.Context, arg FinishDuplicateSweepParams) error {
|
|
||||||
_, err := q.db.Exec(ctx, finishDuplicateSweep,
|
|
||||||
arg.Candidates,
|
|
||||||
arg.GroupsFound,
|
|
||||||
arg.OversizeClusters,
|
|
||||||
arg.ErrorMessage,
|
|
||||||
arg.ID,
|
|
||||||
)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
const getInFlightDuplicateSweep = `-- name: GetInFlightDuplicateSweep :one
|
|
||||||
SELECT id, started_at
|
|
||||||
FROM duplicate_sweeps
|
|
||||||
WHERE finished_at IS NULL
|
|
||||||
ORDER BY started_at DESC
|
|
||||||
LIMIT 1
|
|
||||||
`
|
|
||||||
|
|
||||||
type GetInFlightDuplicateSweepRow struct {
|
|
||||||
ID pgtype.UUID
|
|
||||||
StartedAt pgtype.Timestamptz
|
|
||||||
}
|
|
||||||
|
|
||||||
// The guard against two sweeps at once: "in flight" is finished_at IS NULL.
|
|
||||||
func (q *Queries) GetInFlightDuplicateSweep(ctx context.Context) (GetInFlightDuplicateSweepRow, error) {
|
|
||||||
row := q.db.QueryRow(ctx, getInFlightDuplicateSweep)
|
|
||||||
var i GetInFlightDuplicateSweepRow
|
|
||||||
err := row.Scan(&i.ID, &i.StartedAt)
|
|
||||||
return i, err
|
|
||||||
}
|
|
||||||
|
|
||||||
const getLatestDuplicateSweep = `-- name: GetLatestDuplicateSweep :one
|
|
||||||
SELECT id, started_at, finished_at, candidates, groups_found, oversize_clusters, error_message
|
|
||||||
FROM duplicate_sweeps
|
|
||||||
ORDER BY started_at DESC
|
|
||||||
LIMIT 1
|
|
||||||
`
|
|
||||||
|
|
||||||
func (q *Queries) GetLatestDuplicateSweep(ctx context.Context) (DuplicateSweep, error) {
|
|
||||||
row := q.db.QueryRow(ctx, getLatestDuplicateSweep)
|
|
||||||
var i DuplicateSweep
|
|
||||||
err := row.Scan(
|
|
||||||
&i.ID,
|
|
||||||
&i.StartedAt,
|
|
||||||
&i.FinishedAt,
|
|
||||||
&i.Candidates,
|
|
||||||
&i.GroupsFound,
|
|
||||||
&i.OversizeClusters,
|
|
||||||
&i.ErrorMessage,
|
|
||||||
)
|
|
||||||
return i, err
|
|
||||||
}
|
|
||||||
|
|
||||||
const getLatestFingerprintComputedAt = `-- name: GetLatestFingerprintComputedAt :one
|
|
||||||
SELECT max(computed_at)::timestamptz AS latest FROM track_fingerprints
|
|
||||||
`
|
|
||||||
|
|
||||||
// Whether a sweep has anything new to look at: fingerprints written since the
|
|
||||||
// last sweep started.
|
|
||||||
func (q *Queries) GetLatestFingerprintComputedAt(ctx context.Context) (pgtype.Timestamptz, error) {
|
|
||||||
row := q.db.QueryRow(ctx, getLatestFingerprintComputedAt)
|
|
||||||
var latest pgtype.Timestamptz
|
|
||||||
err := row.Scan(&latest)
|
|
||||||
return latest, err
|
|
||||||
}
|
|
||||||
|
|
||||||
const listDismissedDuplicateMemberSets = `-- name: ListDismissedDuplicateMemberSets :many
|
|
||||||
SELECT g.id, array_agg(m.track_id ORDER BY m.track_id)::uuid[] AS track_ids
|
|
||||||
FROM duplicate_groups g
|
|
||||||
JOIN duplicate_group_members m ON m.group_id = g.id
|
|
||||||
WHERE g.status = 'dismissed'
|
|
||||||
GROUP BY g.id
|
|
||||||
`
|
|
||||||
|
|
||||||
type ListDismissedDuplicateMemberSetsRow struct {
|
|
||||||
ID pgtype.UUID
|
|
||||||
TrackIds []pgtype.UUID
|
|
||||||
}
|
|
||||||
|
|
||||||
// What the operator has already said are not duplicates. A new proposal whose
|
|
||||||
// every member sat together in one of these is not proposed again.
|
|
||||||
func (q *Queries) ListDismissedDuplicateMemberSets(ctx context.Context) ([]ListDismissedDuplicateMemberSetsRow, error) {
|
|
||||||
rows, err := q.db.Query(ctx, listDismissedDuplicateMemberSets)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
defer rows.Close()
|
|
||||||
var items []ListDismissedDuplicateMemberSetsRow
|
|
||||||
for rows.Next() {
|
|
||||||
var i ListDismissedDuplicateMemberSetsRow
|
|
||||||
if err := rows.Scan(&i.ID, &i.TrackIds); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
items = append(items, i)
|
|
||||||
}
|
|
||||||
if err := rows.Err(); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return items, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
const listDuplicateCandidates = `-- name: ListDuplicateCandidates :many
|
|
||||||
SELECT t.id, t.duration_ms, f.audio_stream_sha256, f.chromaprint
|
|
||||||
FROM tracks t
|
|
||||||
JOIN track_fingerprints f ON f.track_id = t.id
|
|
||||||
WHERE t.missing_since IS NULL
|
|
||||||
AND f.fingerprint_version >= $1
|
|
||||||
AND f.chromaprint IS NOT NULL
|
|
||||||
-- Only chromaprints taken at the current length: prints at two lengths are not
|
|
||||||
-- comparable, and after a length change the backfill is still re-deriving the
|
|
||||||
-- rest (#3913).
|
|
||||||
AND f.chromaprint_length_sec = $2
|
|
||||||
AND (t.duration_ms, t.id) > ($3::integer, $4::uuid)
|
|
||||||
ORDER BY t.duration_ms, t.id
|
|
||||||
LIMIT $5
|
|
||||||
`
|
|
||||||
|
|
||||||
type ListDuplicateCandidatesParams struct {
|
|
||||||
CurrentVersion int16
|
|
||||||
ChromaprintLengthSec int32
|
|
||||||
AfterDurationMs int32
|
|
||||||
AfterID pgtype.UUID
|
|
||||||
PageLimit int32
|
|
||||||
}
|
|
||||||
|
|
||||||
type ListDuplicateCandidatesRow struct {
|
|
||||||
ID pgtype.UUID
|
|
||||||
DurationMs int32
|
|
||||||
AudioStreamSha256 []byte
|
|
||||||
Chromaprint []int32
|
|
||||||
}
|
|
||||||
|
|
||||||
// The acoustic tier's input, one page at a time in (duration_ms, id) order so the
|
|
||||||
// sweep holds only a sliding window of durations. Tracks without a chromaprint
|
|
||||||
// cannot be compared acoustically and are left out; any exact duplicates among
|
|
||||||
// them come from ListExactDuplicateHashes.
|
|
||||||
func (q *Queries) ListDuplicateCandidates(ctx context.Context, arg ListDuplicateCandidatesParams) ([]ListDuplicateCandidatesRow, error) {
|
|
||||||
rows, err := q.db.Query(ctx, listDuplicateCandidates,
|
|
||||||
arg.CurrentVersion,
|
|
||||||
arg.ChromaprintLengthSec,
|
|
||||||
arg.AfterDurationMs,
|
|
||||||
arg.AfterID,
|
|
||||||
arg.PageLimit,
|
|
||||||
)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
defer rows.Close()
|
|
||||||
var items []ListDuplicateCandidatesRow
|
|
||||||
for rows.Next() {
|
|
||||||
var i ListDuplicateCandidatesRow
|
|
||||||
if err := rows.Scan(
|
|
||||||
&i.ID,
|
|
||||||
&i.DurationMs,
|
|
||||||
&i.AudioStreamSha256,
|
|
||||||
&i.Chromaprint,
|
|
||||||
); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
items = append(items, i)
|
|
||||||
}
|
|
||||||
if err := rows.Err(); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return items, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
const listExactDuplicateHashes = `-- name: ListExactDuplicateHashes :many
|
|
||||||
SELECT f.audio_stream_sha256,
|
|
||||||
array_agg(t.id ORDER BY t.id)::uuid[] AS track_ids
|
|
||||||
FROM track_fingerprints f
|
|
||||||
JOIN tracks t ON t.id = f.track_id
|
|
||||||
WHERE t.missing_since IS NULL
|
|
||||||
AND f.fingerprint_version >= $1
|
|
||||||
AND f.audio_stream_sha256 IS NOT NULL
|
|
||||||
GROUP BY f.audio_stream_sha256
|
|
||||||
HAVING count(*) > 1
|
|
||||||
`
|
|
||||||
|
|
||||||
type ListExactDuplicateHashesRow struct {
|
|
||||||
AudioStreamSha256 []byte
|
|
||||||
TrackIds []pgtype.UUID
|
|
||||||
}
|
|
||||||
|
|
||||||
// The exact tier, library-wide in one pass: identical encoded audio shared by
|
|
||||||
// more than one present track.
|
|
||||||
func (q *Queries) ListExactDuplicateHashes(ctx context.Context, currentVersion int16) ([]ListExactDuplicateHashesRow, error) {
|
|
||||||
rows, err := q.db.Query(ctx, listExactDuplicateHashes, currentVersion)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
defer rows.Close()
|
|
||||||
var items []ListExactDuplicateHashesRow
|
|
||||||
for rows.Next() {
|
|
||||||
var i ListExactDuplicateHashesRow
|
|
||||||
if err := rows.Scan(&i.AudioStreamSha256, &i.TrackIds); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
items = append(items, i)
|
|
||||||
}
|
|
||||||
if err := rows.Err(); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return items, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
const listPendingDuplicateGroupMembers = `-- name: ListPendingDuplicateGroupMembers :many
|
|
||||||
WITH page AS (
|
|
||||||
SELECT g.id, g.tier, g.worst_bit_error_rate, g.detected_at
|
|
||||||
FROM duplicate_groups g
|
|
||||||
WHERE g.status = 'pending'
|
|
||||||
AND (SELECT count(*) FROM duplicate_group_members m WHERE m.group_id = g.id) >= 2
|
|
||||||
ORDER BY g.detected_at DESC, g.id
|
|
||||||
LIMIT $2 OFFSET $1
|
|
||||||
)
|
|
||||||
SELECT p.id AS group_id,
|
|
||||||
p.tier,
|
|
||||||
p.worst_bit_error_rate,
|
|
||||||
p.detected_at,
|
|
||||||
t.id AS track_id,
|
|
||||||
t.title,
|
|
||||||
artists.name AS artist_name,
|
|
||||||
albums.id AS album_id,
|
|
||||||
albums.title AS album_title,
|
|
||||||
t.file_path,
|
|
||||||
t.file_format,
|
|
||||||
t.file_size,
|
|
||||||
t.duration_ms,
|
|
||||||
t.added_at,
|
|
||||||
(SELECT count(*) FROM general_likes l WHERE l.track_id = t.id)::bigint AS like_count,
|
|
||||||
(SELECT count(*) FROM play_events e WHERE e.track_id = t.id)::bigint AS play_count
|
|
||||||
FROM page p
|
|
||||||
JOIN duplicate_group_members m ON m.group_id = p.id
|
|
||||||
JOIN tracks t ON t.id = m.track_id
|
|
||||||
JOIN albums ON albums.id = t.album_id
|
|
||||||
JOIN artists ON artists.id = t.artist_id
|
|
||||||
ORDER BY p.detected_at DESC, p.id, t.id
|
|
||||||
`
|
|
||||||
|
|
||||||
type ListPendingDuplicateGroupMembersParams struct {
|
|
||||||
PageOffset int32
|
|
||||||
PageLimit int32
|
|
||||||
}
|
|
||||||
|
|
||||||
type ListPendingDuplicateGroupMembersRow struct {
|
|
||||||
GroupID pgtype.UUID
|
|
||||||
Tier string
|
|
||||||
WorstBitErrorRate *float32
|
|
||||||
DetectedAt pgtype.Timestamptz
|
|
||||||
TrackID pgtype.UUID
|
|
||||||
Title string
|
|
||||||
ArtistName string
|
|
||||||
AlbumID pgtype.UUID
|
|
||||||
AlbumTitle string
|
|
||||||
FilePath string
|
|
||||||
FileFormat string
|
|
||||||
FileSize int64
|
|
||||||
DurationMs int32
|
|
||||||
AddedAt pgtype.Timestamptz
|
|
||||||
LikeCount int64
|
|
||||||
PlayCount int64
|
|
||||||
}
|
|
||||||
|
|
||||||
// One page of proposals, newest first, flattened to one row per member so the
|
|
||||||
// handler folds them without a query per group. What each copy carries — likes
|
|
||||||
// and plays from every user — is here because it is what the operator weighs
|
|
||||||
// when deciding which copy to keep.
|
|
||||||
func (q *Queries) ListPendingDuplicateGroupMembers(ctx context.Context, arg ListPendingDuplicateGroupMembersParams) ([]ListPendingDuplicateGroupMembersRow, error) {
|
|
||||||
rows, err := q.db.Query(ctx, listPendingDuplicateGroupMembers, arg.PageOffset, arg.PageLimit)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
defer rows.Close()
|
|
||||||
var items []ListPendingDuplicateGroupMembersRow
|
|
||||||
for rows.Next() {
|
|
||||||
var i ListPendingDuplicateGroupMembersRow
|
|
||||||
if err := rows.Scan(
|
|
||||||
&i.GroupID,
|
|
||||||
&i.Tier,
|
|
||||||
&i.WorstBitErrorRate,
|
|
||||||
&i.DetectedAt,
|
|
||||||
&i.TrackID,
|
|
||||||
&i.Title,
|
|
||||||
&i.ArtistName,
|
|
||||||
&i.AlbumID,
|
|
||||||
&i.AlbumTitle,
|
|
||||||
&i.FilePath,
|
|
||||||
&i.FileFormat,
|
|
||||||
&i.FileSize,
|
|
||||||
&i.DurationMs,
|
|
||||||
&i.AddedAt,
|
|
||||||
&i.LikeCount,
|
|
||||||
&i.PlayCount,
|
|
||||||
); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
items = append(items, i)
|
|
||||||
}
|
|
||||||
if err := rows.Err(); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return items, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
const startDuplicateSweep = `-- name: StartDuplicateSweep :one
|
|
||||||
INSERT INTO duplicate_sweeps DEFAULT VALUES RETURNING id, started_at
|
|
||||||
`
|
|
||||||
|
|
||||||
type StartDuplicateSweepRow struct {
|
|
||||||
ID pgtype.UUID
|
|
||||||
StartedAt pgtype.Timestamptz
|
|
||||||
}
|
|
||||||
|
|
||||||
func (q *Queries) StartDuplicateSweep(ctx context.Context) (StartDuplicateSweepRow, error) {
|
|
||||||
row := q.db.QueryRow(ctx, startDuplicateSweep)
|
|
||||||
var i StartDuplicateSweepRow
|
|
||||||
err := row.Scan(&i.ID, &i.StartedAt)
|
|
||||||
return i, err
|
|
||||||
}
|
|
||||||
|
|
||||||
const upsertDuplicateGroup = `-- name: UpsertDuplicateGroup :one
|
|
||||||
INSERT INTO duplicate_groups (member_key, tier, worst_bit_error_rate, last_seen_sweep_id)
|
|
||||||
VALUES ($1, $2, $3, $4)
|
|
||||||
ON CONFLICT (member_key) DO UPDATE
|
|
||||||
SET tier = EXCLUDED.tier,
|
|
||||||
worst_bit_error_rate = EXCLUDED.worst_bit_error_rate,
|
|
||||||
last_seen_sweep_id = EXCLUDED.last_seen_sweep_id
|
|
||||||
WHERE duplicate_groups.status = 'pending'
|
|
||||||
RETURNING id
|
|
||||||
`
|
|
||||||
|
|
||||||
type UpsertDuplicateGroupParams struct {
|
|
||||||
MemberKey string
|
|
||||||
Tier string
|
|
||||||
WorstBitErrorRate *float32
|
|
||||||
SweepID pgtype.UUID
|
|
||||||
}
|
|
||||||
|
|
||||||
// Proposes a group, or refreshes one already pending. A group already dismissed
|
|
||||||
// or merged is left exactly as it is: the WHERE on the update makes the conflict
|
|
||||||
// a no-op, and the caller sees no row.
|
|
||||||
func (q *Queries) UpsertDuplicateGroup(ctx context.Context, arg UpsertDuplicateGroupParams) (pgtype.UUID, error) {
|
|
||||||
row := q.db.QueryRow(ctx, upsertDuplicateGroup,
|
|
||||||
arg.MemberKey,
|
|
||||||
arg.Tier,
|
|
||||||
arg.WorstBitErrorRate,
|
|
||||||
arg.SweepID,
|
|
||||||
)
|
|
||||||
var id pgtype.UUID
|
|
||||||
err := row.Scan(&id)
|
|
||||||
return id, err
|
|
||||||
}
|
|
||||||
@@ -1,72 +0,0 @@
|
|||||||
// Code generated by sqlc. DO NOT EDIT.
|
|
||||||
// versions:
|
|
||||||
// sqlc v1.31.1
|
|
||||||
// source: fingerprint_settings.sql
|
|
||||||
|
|
||||||
package dbq
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
)
|
|
||||||
|
|
||||||
const getFingerprintSettings = `-- name: GetFingerprintSettings :one
|
|
||||||
SELECT id, enabled, chromaprint_length_sec, acoustic_max_bit_error_rate, backfill_concurrency, sweep_interval_hours, updated_at FROM fingerprint_settings WHERE id = true
|
|
||||||
`
|
|
||||||
|
|
||||||
func (q *Queries) GetFingerprintSettings(ctx context.Context) (FingerprintSetting, error) {
|
|
||||||
row := q.db.QueryRow(ctx, getFingerprintSettings)
|
|
||||||
var i FingerprintSetting
|
|
||||||
err := row.Scan(
|
|
||||||
&i.ID,
|
|
||||||
&i.Enabled,
|
|
||||||
&i.ChromaprintLengthSec,
|
|
||||||
&i.AcousticMaxBitErrorRate,
|
|
||||||
&i.BackfillConcurrency,
|
|
||||||
&i.SweepIntervalHours,
|
|
||||||
&i.UpdatedAt,
|
|
||||||
)
|
|
||||||
return i, err
|
|
||||||
}
|
|
||||||
|
|
||||||
const updateFingerprintSettings = `-- name: UpdateFingerprintSettings :one
|
|
||||||
UPDATE fingerprint_settings
|
|
||||||
SET enabled = $1,
|
|
||||||
chromaprint_length_sec = $2,
|
|
||||||
acoustic_max_bit_error_rate = $3,
|
|
||||||
backfill_concurrency = $4,
|
|
||||||
sweep_interval_hours = $5,
|
|
||||||
updated_at = now()
|
|
||||||
WHERE id = true
|
|
||||||
RETURNING id, enabled, chromaprint_length_sec, acoustic_max_bit_error_rate, backfill_concurrency, sweep_interval_hours, updated_at
|
|
||||||
`
|
|
||||||
|
|
||||||
type UpdateFingerprintSettingsParams struct {
|
|
||||||
Enabled bool
|
|
||||||
ChromaprintLengthSec int32
|
|
||||||
AcousticMaxBitErrorRate float64
|
|
||||||
BackfillConcurrency int32
|
|
||||||
SweepIntervalHours int32
|
|
||||||
}
|
|
||||||
|
|
||||||
// Whole-row write from the admin card; migration 0061's CHECKs are the backstop
|
|
||||||
// behind the service's own validation.
|
|
||||||
func (q *Queries) UpdateFingerprintSettings(ctx context.Context, arg UpdateFingerprintSettingsParams) (FingerprintSetting, error) {
|
|
||||||
row := q.db.QueryRow(ctx, updateFingerprintSettings,
|
|
||||||
arg.Enabled,
|
|
||||||
arg.ChromaprintLengthSec,
|
|
||||||
arg.AcousticMaxBitErrorRate,
|
|
||||||
arg.BackfillConcurrency,
|
|
||||||
arg.SweepIntervalHours,
|
|
||||||
)
|
|
||||||
var i FingerprintSetting
|
|
||||||
err := row.Scan(
|
|
||||||
&i.ID,
|
|
||||||
&i.Enabled,
|
|
||||||
&i.ChromaprintLengthSec,
|
|
||||||
&i.AcousticMaxBitErrorRate,
|
|
||||||
&i.BackfillConcurrency,
|
|
||||||
&i.SweepIntervalHours,
|
|
||||||
&i.UpdatedAt,
|
|
||||||
)
|
|
||||||
return i, err
|
|
||||||
}
|
|
||||||
@@ -1,172 +0,0 @@
|
|||||||
// Code generated by sqlc. DO NOT EDIT.
|
|
||||||
// versions:
|
|
||||||
// sqlc v1.31.1
|
|
||||||
// source: fingerprints.sql
|
|
||||||
|
|
||||||
package dbq
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
|
|
||||||
"github.com/jackc/pgx/v5/pgtype"
|
|
||||||
)
|
|
||||||
|
|
||||||
const deleteTrackFingerprint = `-- name: DeleteTrackFingerprint :exec
|
|
||||||
DELETE FROM track_fingerprints WHERE track_id = $1
|
|
||||||
`
|
|
||||||
|
|
||||||
// A file changed but could not be fingerprinted, for a reason unrelated to the
|
|
||||||
// file. The stored row describes the OLD bytes, so it goes and the backfill
|
|
||||||
// re-derives it — nothing may keep trusting a stale identity.
|
|
||||||
func (q *Queries) DeleteTrackFingerprint(ctx context.Context, trackID pgtype.UUID) error {
|
|
||||||
_, err := q.db.Exec(ctx, deleteTrackFingerprint, trackID)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
const getFingerprintCoverage = `-- name: GetFingerprintCoverage :one
|
|
||||||
SELECT count(*)::bigint AS total,
|
|
||||||
count(*) FILTER (
|
|
||||||
WHERE f.fingerprint_version >= $1
|
|
||||||
AND f.chromaprint_length_sec = $2
|
|
||||||
AND f.audio_stream_sha256 IS NOT NULL AND f.chromaprint IS NOT NULL
|
|
||||||
)::bigint AS fingerprinted,
|
|
||||||
count(*) FILTER (
|
|
||||||
WHERE f.fingerprint_version >= $1
|
|
||||||
AND f.chromaprint_length_sec = $2
|
|
||||||
AND (f.audio_stream_sha256 IS NULL OR f.chromaprint IS NULL)
|
|
||||||
)::bigint AS rejected,
|
|
||||||
count(*) FILTER (
|
|
||||||
WHERE f.track_id IS NULL
|
|
||||||
OR f.fingerprint_version < $1
|
|
||||||
OR f.chromaprint_length_sec <> $2
|
|
||||||
)::bigint AS pending
|
|
||||||
FROM tracks t
|
|
||||||
LEFT JOIN track_fingerprints f ON f.track_id = t.id
|
|
||||||
WHERE t.missing_since IS NULL
|
|
||||||
`
|
|
||||||
|
|
||||||
type GetFingerprintCoverageParams struct {
|
|
||||||
CurrentVersion int16
|
|
||||||
ChromaprintLengthSec int32
|
|
||||||
}
|
|
||||||
|
|
||||||
type GetFingerprintCoverageRow struct {
|
|
||||||
Total int64
|
|
||||||
Fingerprinted int64
|
|
||||||
Rejected int64
|
|
||||||
Pending int64
|
|
||||||
}
|
|
||||||
|
|
||||||
// The admin gauge for the backfill. fingerprinted + rejected + pending = total.
|
|
||||||
// "Current" means derived by the current method AT the current length: a row at
|
|
||||||
// another length is pending, because the backfill will re-derive it. rejected is
|
|
||||||
// a current row with a NULL half: a tool ran and refused the file, which is
|
|
||||||
// settled rather than waiting. Missing tracks are excluded, or the gauge could
|
|
||||||
// never reach the end.
|
|
||||||
func (q *Queries) GetFingerprintCoverage(ctx context.Context, arg GetFingerprintCoverageParams) (GetFingerprintCoverageRow, error) {
|
|
||||||
row := q.db.QueryRow(ctx, getFingerprintCoverage, arg.CurrentVersion, arg.ChromaprintLengthSec)
|
|
||||||
var i GetFingerprintCoverageRow
|
|
||||||
err := row.Scan(
|
|
||||||
&i.Total,
|
|
||||||
&i.Fingerprinted,
|
|
||||||
&i.Rejected,
|
|
||||||
&i.Pending,
|
|
||||||
)
|
|
||||||
return i, err
|
|
||||||
}
|
|
||||||
|
|
||||||
const listTracksNeedingFingerprint = `-- name: ListTracksNeedingFingerprint :many
|
|
||||||
SELECT t.id, t.file_path
|
|
||||||
FROM tracks t
|
|
||||||
LEFT JOIN track_fingerprints f ON f.track_id = t.id
|
|
||||||
WHERE t.missing_since IS NULL
|
|
||||||
-- A row taken at another length is as stale as one from an older method:
|
|
||||||
-- chromaprints at two lengths cannot be compared (#3913).
|
|
||||||
AND (f.track_id IS NULL
|
|
||||||
OR f.fingerprint_version < $1
|
|
||||||
OR f.chromaprint_length_sec <> $2)
|
|
||||||
AND t.id > $3
|
|
||||||
ORDER BY t.id
|
|
||||||
LIMIT $4
|
|
||||||
`
|
|
||||||
|
|
||||||
type ListTracksNeedingFingerprintParams struct {
|
|
||||||
CurrentVersion int16
|
|
||||||
ChromaprintLengthSec int32
|
|
||||||
AfterID pgtype.UUID
|
|
||||||
BatchLimit int32
|
|
||||||
}
|
|
||||||
|
|
||||||
type ListTracksNeedingFingerprintRow struct {
|
|
||||||
ID pgtype.UUID
|
|
||||||
FilePath string
|
|
||||||
}
|
|
||||||
|
|
||||||
// The backfill's work queue (#3908): tracks with no fingerprint, or one derived
|
|
||||||
// by an older method. Keyset-paged on id so a pass visits each track at most
|
|
||||||
// once. That cursor is load-bearing: an inconclusive attempt writes no row, so
|
|
||||||
// without it a file that keeps timing out would be listed again straight away
|
|
||||||
// and retried in a tight loop. Missing tracks are skipped — there is no file to
|
|
||||||
// read.
|
|
||||||
func (q *Queries) ListTracksNeedingFingerprint(ctx context.Context, arg ListTracksNeedingFingerprintParams) ([]ListTracksNeedingFingerprintRow, error) {
|
|
||||||
rows, err := q.db.Query(ctx, listTracksNeedingFingerprint,
|
|
||||||
arg.CurrentVersion,
|
|
||||||
arg.ChromaprintLengthSec,
|
|
||||||
arg.AfterID,
|
|
||||||
arg.BatchLimit,
|
|
||||||
)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
defer rows.Close()
|
|
||||||
var items []ListTracksNeedingFingerprintRow
|
|
||||||
for rows.Next() {
|
|
||||||
var i ListTracksNeedingFingerprintRow
|
|
||||||
if err := rows.Scan(&i.ID, &i.FilePath); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
items = append(items, i)
|
|
||||||
}
|
|
||||||
if err := rows.Err(); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return items, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
const upsertTrackFingerprint = `-- name: UpsertTrackFingerprint :exec
|
|
||||||
INSERT INTO track_fingerprints (
|
|
||||||
track_id, audio_stream_sha256, chromaprint, fingerprint_version, chromaprint_length_sec
|
|
||||||
) VALUES (
|
|
||||||
$1, $2, $3,
|
|
||||||
$4, $5
|
|
||||||
)
|
|
||||||
ON CONFLICT (track_id) DO UPDATE SET
|
|
||||||
audio_stream_sha256 = EXCLUDED.audio_stream_sha256,
|
|
||||||
chromaprint = EXCLUDED.chromaprint,
|
|
||||||
fingerprint_version = EXCLUDED.fingerprint_version,
|
|
||||||
chromaprint_length_sec = EXCLUDED.chromaprint_length_sec,
|
|
||||||
computed_at = now()
|
|
||||||
`
|
|
||||||
|
|
||||||
type UpsertTrackFingerprintParams struct {
|
|
||||||
TrackID pgtype.UUID
|
|
||||||
AudioStreamSha256 []byte
|
|
||||||
Chromaprint []int32
|
|
||||||
FingerprintVersion int16
|
|
||||||
ChromaprintLengthSec int32
|
|
||||||
}
|
|
||||||
|
|
||||||
// Written whenever a track's fingerprint is derived: by the scan when a file is
|
|
||||||
// new or its bytes changed, and by the backfill (#3908) for rows derived by an
|
|
||||||
// older method. Replaces the row wholesale — a fingerprint of the old bytes has
|
|
||||||
// no standing once the file has changed.
|
|
||||||
func (q *Queries) UpsertTrackFingerprint(ctx context.Context, arg UpsertTrackFingerprintParams) error {
|
|
||||||
_, err := q.db.Exec(ctx, upsertTrackFingerprint,
|
|
||||||
arg.TrackID,
|
|
||||||
arg.AudioStreamSha256,
|
|
||||||
arg.Chromaprint,
|
|
||||||
arg.FingerprintVersion,
|
|
||||||
arg.ChromaprintLengthSec,
|
|
||||||
)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
@@ -84,22 +84,6 @@ func (q *Queries) GcDeleteExpiredPasswordResets(ctx context.Context) (int64, err
|
|||||||
return result.RowsAffected(), nil
|
return result.RowsAffected(), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
const gcDeleteExpiredSessions = `-- name: GcDeleteExpiredSessions :execrows
|
|
||||||
DELETE FROM sessions
|
|
||||||
WHERE last_seen_at <= now() - interval '30 days'
|
|
||||||
OR created_at <= now() - interval '365 days'
|
|
||||||
`
|
|
||||||
|
|
||||||
// Sessions past their idle (30 days) or absolute (1 year) limit. They already
|
|
||||||
// fail auth through GetSessionByTokenHash's filter; this only clears the rows.
|
|
||||||
func (q *Queries) GcDeleteExpiredSessions(ctx context.Context) (int64, error) {
|
|
||||||
result, err := q.db.Exec(ctx, gcDeleteExpiredSessions)
|
|
||||||
if err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
return result.RowsAffected(), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
const gcExpireScrobbleQueueFailedRows = `-- name: GcExpireScrobbleQueueFailedRows :execrows
|
const gcExpireScrobbleQueueFailedRows = `-- name: GcExpireScrobbleQueueFailedRows :execrows
|
||||||
DELETE FROM scrobble_queue
|
DELETE FROM scrobble_queue
|
||||||
WHERE status = 'failed'
|
WHERE status = 'failed'
|
||||||
|
|||||||
@@ -1,339 +0,0 @@
|
|||||||
// Code generated by sqlc. DO NOT EDIT.
|
|
||||||
// versions:
|
|
||||||
// sqlc v1.31.1
|
|
||||||
// source: merge.sql
|
|
||||||
|
|
||||||
package dbq
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
|
|
||||||
"github.com/jackc/pgx/v5/pgtype"
|
|
||||||
)
|
|
||||||
|
|
||||||
const listDuplicateGroupMergeMembers = `-- name: ListDuplicateGroupMergeMembers :many
|
|
||||||
SELECT t.id, t.file_path, t.file_format, t.file_size, t.added_at, t.album_id,
|
|
||||||
t.mbid, albums.mbid AS album_mbid
|
|
||||||
FROM duplicate_group_members m
|
|
||||||
JOIN tracks t ON t.id = m.track_id
|
|
||||||
JOIN albums ON albums.id = t.album_id
|
|
||||||
WHERE m.group_id = $1
|
|
||||||
ORDER BY t.id
|
|
||||||
`
|
|
||||||
|
|
||||||
type ListDuplicateGroupMergeMembersRow struct {
|
|
||||||
ID pgtype.UUID
|
|
||||||
FilePath string
|
|
||||||
FileFormat string
|
|
||||||
FileSize int64
|
|
||||||
AddedAt pgtype.Timestamptz
|
|
||||||
AlbumID pgtype.UUID
|
|
||||||
Mbid *string
|
|
||||||
AlbumMbid *string
|
|
||||||
}
|
|
||||||
|
|
||||||
func (q *Queries) ListDuplicateGroupMergeMembers(ctx context.Context, groupID pgtype.UUID) ([]ListDuplicateGroupMergeMembersRow, error) {
|
|
||||||
rows, err := q.db.Query(ctx, listDuplicateGroupMergeMembers, groupID)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
defer rows.Close()
|
|
||||||
var items []ListDuplicateGroupMergeMembersRow
|
|
||||||
for rows.Next() {
|
|
||||||
var i ListDuplicateGroupMergeMembersRow
|
|
||||||
if err := rows.Scan(
|
|
||||||
&i.ID,
|
|
||||||
&i.FilePath,
|
|
||||||
&i.FileFormat,
|
|
||||||
&i.FileSize,
|
|
||||||
&i.AddedAt,
|
|
||||||
&i.AlbumID,
|
|
||||||
&i.Mbid,
|
|
||||||
&i.AlbumMbid,
|
|
||||||
); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
items = append(items, i)
|
|
||||||
}
|
|
||||||
if err := rows.Err(); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return items, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
const lockDuplicateGroupForMerge = `-- name: LockDuplicateGroupForMerge :one
|
|
||||||
|
|
||||||
SELECT id, tier, status
|
|
||||||
FROM duplicate_groups
|
|
||||||
WHERE id = $1
|
|
||||||
FOR UPDATE
|
|
||||||
`
|
|
||||||
|
|
||||||
type LockDuplicateGroupForMergeRow struct {
|
|
||||||
ID pgtype.UUID
|
|
||||||
Tier string
|
|
||||||
Status string
|
|
||||||
}
|
|
||||||
|
|
||||||
// Duplicate merge (Scribe #3911). Every statement here runs inside the one
|
|
||||||
// transaction library.MergeDuplicateGroup opens, after the removed copy's file
|
|
||||||
// is already gone. The loser's own track row is deleted last with DeleteTrack;
|
|
||||||
// what these do is move everything it carries onto the survivor first, so that
|
|
||||||
// delete's CASCADE finds nothing left to destroy.
|
|
||||||
// Locks the group for the rest of the transaction, so two merges of one group
|
|
||||||
// cannot run at once.
|
|
||||||
func (q *Queries) LockDuplicateGroupForMerge(ctx context.Context, id pgtype.UUID) (LockDuplicateGroupForMergeRow, error) {
|
|
||||||
row := q.db.QueryRow(ctx, lockDuplicateGroupForMerge, id)
|
|
||||||
var i LockDuplicateGroupForMergeRow
|
|
||||||
err := row.Scan(&i.ID, &i.Tier, &i.Status)
|
|
||||||
return i, err
|
|
||||||
}
|
|
||||||
|
|
||||||
const markDuplicateGroupMerged = `-- name: MarkDuplicateGroupMerged :execrows
|
|
||||||
UPDATE duplicate_groups
|
|
||||||
SET status = 'merged', resolved_at = now()
|
|
||||||
WHERE id = $1 AND status = 'pending'
|
|
||||||
`
|
|
||||||
|
|
||||||
func (q *Queries) MarkDuplicateGroupMerged(ctx context.Context, id pgtype.UUID) (int64, error) {
|
|
||||||
result, err := q.db.Exec(ctx, markDuplicateGroupMerged, id)
|
|
||||||
if err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
return result.RowsAffected(), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
const mergeCopyGeneralLikes = `-- name: MergeCopyGeneralLikes :many
|
|
||||||
|
|
||||||
INSERT INTO general_likes (user_id, track_id, liked_at)
|
|
||||||
SELECT user_id, $1::uuid, liked_at
|
|
||||||
FROM general_likes
|
|
||||||
WHERE track_id = $2::uuid
|
|
||||||
ON CONFLICT (user_id, track_id) DO UPDATE
|
|
||||||
SET liked_at = LEAST(general_likes.liked_at, EXCLUDED.liked_at)
|
|
||||||
RETURNING user_id
|
|
||||||
`
|
|
||||||
|
|
||||||
type MergeCopyGeneralLikesParams struct {
|
|
||||||
SurvivorID pgtype.UUID
|
|
||||||
LoserID pgtype.UUID
|
|
||||||
}
|
|
||||||
|
|
||||||
// Collision-safe merges: a unique key includes track_id, so the survivor may
|
|
||||||
// already hold a matching row. Copy what it lacks; DeleteTrack's CASCADE then
|
|
||||||
// removes the loser's originals.
|
|
||||||
// One like per user. A user who liked both copies keeps a single like, dated to
|
|
||||||
// the earlier of the two.
|
|
||||||
func (q *Queries) MergeCopyGeneralLikes(ctx context.Context, arg MergeCopyGeneralLikesParams) ([]pgtype.UUID, error) {
|
|
||||||
rows, err := q.db.Query(ctx, mergeCopyGeneralLikes, arg.SurvivorID, arg.LoserID)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
defer rows.Close()
|
|
||||||
var items []pgtype.UUID
|
|
||||||
for rows.Next() {
|
|
||||||
var user_id pgtype.UUID
|
|
||||||
if err := rows.Scan(&user_id); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
items = append(items, user_id)
|
|
||||||
}
|
|
||||||
if err := rows.Err(); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return items, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
const mergeCopyTrackSimilarity = `-- name: MergeCopyTrackSimilarity :execrows
|
|
||||||
INSERT INTO track_similarity (track_a_id, track_b_id, score, source, fetched_at)
|
|
||||||
SELECT CASE WHEN track_a_id = $1::uuid THEN $2::uuid ELSE track_a_id END,
|
|
||||||
CASE WHEN track_b_id = $1::uuid THEN $2::uuid ELSE track_b_id END,
|
|
||||||
score, source, fetched_at
|
|
||||||
FROM track_similarity
|
|
||||||
WHERE (track_a_id = $1::uuid OR track_b_id = $1::uuid)
|
|
||||||
AND (CASE WHEN track_a_id = $1::uuid THEN $2::uuid ELSE track_a_id END)
|
|
||||||
<> (CASE WHEN track_b_id = $1::uuid THEN $2::uuid ELSE track_b_id END)
|
|
||||||
ON CONFLICT (track_a_id, track_b_id, source) DO NOTHING
|
|
||||||
`
|
|
||||||
|
|
||||||
type MergeCopyTrackSimilarityParams struct {
|
|
||||||
LoserID pgtype.UUID
|
|
||||||
SurvivorID pgtype.UUID
|
|
||||||
}
|
|
||||||
|
|
||||||
// Rewrites the loser to the survivor on either side of an edge. An edge between
|
|
||||||
// the two copies would become a track similar to itself — the table forbids
|
|
||||||
// that, and it means nothing — so it is dropped. An edge the survivor already
|
|
||||||
// has from the same source is kept as it is.
|
|
||||||
func (q *Queries) MergeCopyTrackSimilarity(ctx context.Context, arg MergeCopyTrackSimilarityParams) (int64, error) {
|
|
||||||
result, err := q.db.Exec(ctx, mergeCopyTrackSimilarity, arg.LoserID, arg.SurvivorID)
|
|
||||||
if err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
return result.RowsAffected(), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
const mergeCopyTrackTags = `-- name: MergeCopyTrackTags :execrows
|
|
||||||
INSERT INTO track_tags (track_id, tag, weight)
|
|
||||||
SELECT $1::uuid, tag, weight
|
|
||||||
FROM track_tags
|
|
||||||
WHERE track_id = $2::uuid
|
|
||||||
ON CONFLICT (track_id, tag) DO NOTHING
|
|
||||||
`
|
|
||||||
|
|
||||||
type MergeCopyTrackTagsParams struct {
|
|
||||||
SurvivorID pgtype.UUID
|
|
||||||
LoserID pgtype.UUID
|
|
||||||
}
|
|
||||||
|
|
||||||
func (q *Queries) MergeCopyTrackTags(ctx context.Context, arg MergeCopyTrackTagsParams) (int64, error) {
|
|
||||||
result, err := q.db.Exec(ctx, mergeCopyTrackTags, arg.SurvivorID, arg.LoserID)
|
|
||||||
if err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
return result.RowsAffected(), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
const mergeInheritTrackMbid = `-- name: MergeInheritTrackMbid :exec
|
|
||||||
UPDATE tracks AS survivor
|
|
||||||
SET mbid = loser.mbid
|
|
||||||
FROM tracks AS loser
|
|
||||||
WHERE survivor.id = $1::uuid
|
|
||||||
AND loser.id = $2::uuid
|
|
||||||
AND survivor.mbid IS NULL
|
|
||||||
AND loser.mbid IS NOT NULL
|
|
||||||
`
|
|
||||||
|
|
||||||
type MergeInheritTrackMbidParams struct {
|
|
||||||
SurvivorID pgtype.UUID
|
|
||||||
LoserID pgtype.UUID
|
|
||||||
}
|
|
||||||
|
|
||||||
// A recording MBID is what the similarity pipeline keys on. If only the removed
|
|
||||||
// copy carried one, the survivor takes it rather than going dark to similarity.
|
|
||||||
func (q *Queries) MergeInheritTrackMbid(ctx context.Context, arg MergeInheritTrackMbidParams) error {
|
|
||||||
_, err := q.db.Exec(ctx, mergeInheritTrackMbid, arg.SurvivorID, arg.LoserID)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
const mergeRepointContextualLikes = `-- name: MergeRepointContextualLikes :execrows
|
|
||||||
UPDATE contextual_likes SET track_id = $1::uuid WHERE track_id = $2::uuid
|
|
||||||
`
|
|
||||||
|
|
||||||
type MergeRepointContextualLikesParams struct {
|
|
||||||
SurvivorID pgtype.UUID
|
|
||||||
LoserID pgtype.UUID
|
|
||||||
}
|
|
||||||
|
|
||||||
func (q *Queries) MergeRepointContextualLikes(ctx context.Context, arg MergeRepointContextualLikesParams) (int64, error) {
|
|
||||||
result, err := q.db.Exec(ctx, mergeRepointContextualLikes, arg.SurvivorID, arg.LoserID)
|
|
||||||
if err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
return result.RowsAffected(), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
const mergeRepointLidarrRequests = `-- name: MergeRepointLidarrRequests :execrows
|
|
||||||
UPDATE lidarr_requests SET matched_track_id = $1::uuid
|
|
||||||
WHERE matched_track_id = $2::uuid
|
|
||||||
`
|
|
||||||
|
|
||||||
type MergeRepointLidarrRequestsParams struct {
|
|
||||||
SurvivorID pgtype.UUID
|
|
||||||
LoserID pgtype.UUID
|
|
||||||
}
|
|
||||||
|
|
||||||
func (q *Queries) MergeRepointLidarrRequests(ctx context.Context, arg MergeRepointLidarrRequestsParams) (int64, error) {
|
|
||||||
result, err := q.db.Exec(ctx, mergeRepointLidarrRequests, arg.SurvivorID, arg.LoserID)
|
|
||||||
if err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
return result.RowsAffected(), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
const mergeRepointPlayEvents = `-- name: MergeRepointPlayEvents :execrows
|
|
||||||
|
|
||||||
UPDATE play_events SET track_id = $1::uuid WHERE track_id = $2::uuid
|
|
||||||
`
|
|
||||||
|
|
||||||
type MergeRepointPlayEventsParams struct {
|
|
||||||
SurvivorID pgtype.UUID
|
|
||||||
LoserID pgtype.UUID
|
|
||||||
}
|
|
||||||
|
|
||||||
// Plain repoints: no unique key involves track_id, so moving rows cannot collide.
|
|
||||||
func (q *Queries) MergeRepointPlayEvents(ctx context.Context, arg MergeRepointPlayEventsParams) (int64, error) {
|
|
||||||
result, err := q.db.Exec(ctx, mergeRepointPlayEvents, arg.SurvivorID, arg.LoserID)
|
|
||||||
if err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
return result.RowsAffected(), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
const mergeRepointPlaybackErrors = `-- name: MergeRepointPlaybackErrors :execrows
|
|
||||||
UPDATE playback_errors SET track_id = $1::uuid WHERE track_id = $2::uuid
|
|
||||||
`
|
|
||||||
|
|
||||||
type MergeRepointPlaybackErrorsParams struct {
|
|
||||||
SurvivorID pgtype.UUID
|
|
||||||
LoserID pgtype.UUID
|
|
||||||
}
|
|
||||||
|
|
||||||
func (q *Queries) MergeRepointPlaybackErrors(ctx context.Context, arg MergeRepointPlaybackErrorsParams) (int64, error) {
|
|
||||||
result, err := q.db.Exec(ctx, mergeRepointPlaybackErrors, arg.SurvivorID, arg.LoserID)
|
|
||||||
if err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
return result.RowsAffected(), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
const mergeRepointPlaylistTracks = `-- name: MergeRepointPlaylistTracks :many
|
|
||||||
UPDATE playlist_tracks SET track_id = $1::uuid
|
|
||||||
WHERE track_id = $2::uuid
|
|
||||||
RETURNING playlist_id
|
|
||||||
`
|
|
||||||
|
|
||||||
type MergeRepointPlaylistTracksParams struct {
|
|
||||||
SurvivorID pgtype.UUID
|
|
||||||
LoserID pgtype.UUID
|
|
||||||
}
|
|
||||||
|
|
||||||
// playlist_tracks is keyed by (playlist_id, position), so repointing keeps every
|
|
||||||
// entry exactly where it was. A playlist that held both copies simply holds the
|
|
||||||
// survivor twice — the user put two entries there, and both stay.
|
|
||||||
func (q *Queries) MergeRepointPlaylistTracks(ctx context.Context, arg MergeRepointPlaylistTracksParams) ([]pgtype.UUID, error) {
|
|
||||||
rows, err := q.db.Query(ctx, mergeRepointPlaylistTracks, arg.SurvivorID, arg.LoserID)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
defer rows.Close()
|
|
||||||
var items []pgtype.UUID
|
|
||||||
for rows.Next() {
|
|
||||||
var playlist_id pgtype.UUID
|
|
||||||
if err := rows.Scan(&playlist_id); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
items = append(items, playlist_id)
|
|
||||||
}
|
|
||||||
if err := rows.Err(); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return items, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
const mergeRepointSkipEvents = `-- name: MergeRepointSkipEvents :execrows
|
|
||||||
UPDATE skip_events SET track_id = $1::uuid WHERE track_id = $2::uuid
|
|
||||||
`
|
|
||||||
|
|
||||||
type MergeRepointSkipEventsParams struct {
|
|
||||||
SurvivorID pgtype.UUID
|
|
||||||
LoserID pgtype.UUID
|
|
||||||
}
|
|
||||||
|
|
||||||
func (q *Queries) MergeRepointSkipEvents(ctx context.Context, arg MergeRepointSkipEventsParams) (int64, error) {
|
|
||||||
result, err := q.db.Exec(ctx, mergeRepointSkipEvents, arg.SurvivorID, arg.LoserID)
|
|
||||||
if err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
return result.RowsAffected(), nil
|
|
||||||
}
|
|
||||||
@@ -297,42 +297,6 @@ type DiscoverTuning struct {
|
|||||||
UpdatedAt pgtype.Timestamptz
|
UpdatedAt pgtype.Timestamptz
|
||||||
}
|
}
|
||||||
|
|
||||||
type DuplicateGroup struct {
|
|
||||||
ID pgtype.UUID
|
|
||||||
MemberKey string
|
|
||||||
Tier string
|
|
||||||
WorstBitErrorRate *float32
|
|
||||||
Status string
|
|
||||||
DetectedAt pgtype.Timestamptz
|
|
||||||
LastSeenSweepID pgtype.UUID
|
|
||||||
ResolvedAt pgtype.Timestamptz
|
|
||||||
}
|
|
||||||
|
|
||||||
type DuplicateGroupMember struct {
|
|
||||||
GroupID pgtype.UUID
|
|
||||||
TrackID pgtype.UUID
|
|
||||||
}
|
|
||||||
|
|
||||||
type DuplicateSweep struct {
|
|
||||||
ID pgtype.UUID
|
|
||||||
StartedAt pgtype.Timestamptz
|
|
||||||
FinishedAt pgtype.Timestamptz
|
|
||||||
Candidates *int32
|
|
||||||
GroupsFound *int32
|
|
||||||
OversizeClusters *int32
|
|
||||||
ErrorMessage *string
|
|
||||||
}
|
|
||||||
|
|
||||||
type FingerprintSetting struct {
|
|
||||||
ID bool
|
|
||||||
Enabled bool
|
|
||||||
ChromaprintLengthSec int32
|
|
||||||
AcousticMaxBitErrorRate float64
|
|
||||||
BackfillConcurrency int32
|
|
||||||
SweepIntervalHours int32
|
|
||||||
UpdatedAt pgtype.Timestamptz
|
|
||||||
}
|
|
||||||
|
|
||||||
type GeneralLike struct {
|
type GeneralLike struct {
|
||||||
UserID pgtype.UUID
|
UserID pgtype.UUID
|
||||||
TrackID pgtype.UUID
|
TrackID pgtype.UUID
|
||||||
@@ -430,7 +394,6 @@ type MissingReacquisition struct {
|
|||||||
type NetworkSetting struct {
|
type NetworkSetting struct {
|
||||||
ID bool
|
ID bool
|
||||||
TrustedProxyHops int32
|
TrustedProxyHops int32
|
||||||
PublicUrl string
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type PasswordReset struct {
|
type PasswordReset struct {
|
||||||
@@ -704,15 +667,6 @@ type Track struct {
|
|||||||
MissingSince pgtype.Timestamptz
|
MissingSince pgtype.Timestamptz
|
||||||
}
|
}
|
||||||
|
|
||||||
type TrackFingerprint struct {
|
|
||||||
TrackID pgtype.UUID
|
|
||||||
AudioStreamSha256 []byte
|
|
||||||
Chromaprint []int32
|
|
||||||
FingerprintVersion int16
|
|
||||||
ComputedAt pgtype.Timestamptz
|
|
||||||
ChromaprintLengthSec int32
|
|
||||||
}
|
|
||||||
|
|
||||||
type TrackSimilarity struct {
|
type TrackSimilarity struct {
|
||||||
TrackAID pgtype.UUID
|
TrackAID pgtype.UUID
|
||||||
TrackBID pgtype.UUID
|
TrackBID pgtype.UUID
|
||||||
@@ -731,6 +685,7 @@ type User struct {
|
|||||||
ID pgtype.UUID
|
ID pgtype.UUID
|
||||||
Username string
|
Username string
|
||||||
PasswordHash string
|
PasswordHash string
|
||||||
|
ApiToken string
|
||||||
IsAdmin bool
|
IsAdmin bool
|
||||||
CreatedAt pgtype.Timestamptz
|
CreatedAt pgtype.Timestamptz
|
||||||
SubsonicPassword *string
|
SubsonicPassword *string
|
||||||
@@ -742,7 +697,6 @@ type User struct {
|
|||||||
Timezone string
|
Timezone string
|
||||||
TimezoneUpdatedAt pgtype.Timestamptz
|
TimezoneUpdatedAt pgtype.Timestamptz
|
||||||
DebugModeEnabled bool
|
DebugModeEnabled bool
|
||||||
ApiTokenHash string
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type UserInvite struct {
|
type UserInvite struct {
|
||||||
|
|||||||
@@ -10,34 +10,23 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
const getNetworkSettings = `-- name: GetNetworkSettings :one
|
const getNetworkSettings = `-- name: GetNetworkSettings :one
|
||||||
SELECT id, trusted_proxy_hops, public_url FROM network_settings WHERE id = true
|
SELECT id, trusted_proxy_hops FROM network_settings WHERE id = true
|
||||||
`
|
`
|
||||||
|
|
||||||
func (q *Queries) GetNetworkSettings(ctx context.Context) (NetworkSetting, error) {
|
func (q *Queries) GetNetworkSettings(ctx context.Context) (NetworkSetting, error) {
|
||||||
row := q.db.QueryRow(ctx, getNetworkSettings)
|
row := q.db.QueryRow(ctx, getNetworkSettings)
|
||||||
var i NetworkSetting
|
var i NetworkSetting
|
||||||
err := row.Scan(&i.ID, &i.TrustedProxyHops, &i.PublicUrl)
|
err := row.Scan(&i.ID, &i.TrustedProxyHops)
|
||||||
return i, err
|
|
||||||
}
|
|
||||||
|
|
||||||
const updatePublicURL = `-- name: UpdatePublicURL :one
|
|
||||||
UPDATE network_settings SET public_url = $1 WHERE id = true RETURNING id, trusted_proxy_hops, public_url
|
|
||||||
`
|
|
||||||
|
|
||||||
func (q *Queries) UpdatePublicURL(ctx context.Context, publicUrl string) (NetworkSetting, error) {
|
|
||||||
row := q.db.QueryRow(ctx, updatePublicURL, publicUrl)
|
|
||||||
var i NetworkSetting
|
|
||||||
err := row.Scan(&i.ID, &i.TrustedProxyHops, &i.PublicUrl)
|
|
||||||
return i, err
|
return i, err
|
||||||
}
|
}
|
||||||
|
|
||||||
const updateTrustedProxyHops = `-- name: UpdateTrustedProxyHops :one
|
const updateTrustedProxyHops = `-- name: UpdateTrustedProxyHops :one
|
||||||
UPDATE network_settings SET trusted_proxy_hops = $1 WHERE id = true RETURNING id, trusted_proxy_hops, public_url
|
UPDATE network_settings SET trusted_proxy_hops = $1 WHERE id = true RETURNING id, trusted_proxy_hops
|
||||||
`
|
`
|
||||||
|
|
||||||
func (q *Queries) UpdateTrustedProxyHops(ctx context.Context, trustedProxyHops int32) (NetworkSetting, error) {
|
func (q *Queries) UpdateTrustedProxyHops(ctx context.Context, trustedProxyHops int32) (NetworkSetting, error) {
|
||||||
row := q.db.QueryRow(ctx, updateTrustedProxyHops, trustedProxyHops)
|
row := q.db.QueryRow(ctx, updateTrustedProxyHops, trustedProxyHops)
|
||||||
var i NetworkSetting
|
var i NetworkSetting
|
||||||
err := row.Scan(&i.ID, &i.TrustedProxyHops, &i.PublicUrl)
|
err := row.Scan(&i.ID, &i.TrustedProxyHops)
|
||||||
return i, err
|
return i, err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -829,7 +829,7 @@ similar_artists AS (
|
|||||||
JOIN seed_artist sa ON asim.artist_a_id = sa.artist_id
|
JOIN seed_artist sa ON asim.artist_a_id = sa.artist_id
|
||||||
WHERE asim.source = 'listenbrainz'
|
WHERE asim.source = 'listenbrainz'
|
||||||
AND t.id NOT IN (SELECT id FROM excluded_ids)
|
AND t.id NOT IN (SELECT id FROM excluded_ids)
|
||||||
ORDER BY asim.score DESC, md5(t.id::text || $12::text)
|
ORDER BY asim.score DESC, random()
|
||||||
LIMIT $6
|
LIMIT $6
|
||||||
),
|
),
|
||||||
tag_overlap AS (
|
tag_overlap AS (
|
||||||
@@ -857,7 +857,7 @@ likes_overlap AS (
|
|||||||
WHERE t.id = gl.track_id
|
WHERE t.id = gl.track_id
|
||||||
AND trim(g_overlap.g) IN (SELECT tag FROM seed_tags)
|
AND trim(g_overlap.g) IN (SELECT tag FROM seed_tags)
|
||||||
)
|
)
|
||||||
ORDER BY md5(gl.track_id::text || $12::text)
|
ORDER BY random()
|
||||||
LIMIT $8
|
LIMIT $8
|
||||||
),
|
),
|
||||||
taste_overlap AS (
|
taste_overlap AS (
|
||||||
@@ -884,7 +884,7 @@ coplay_artists AS (
|
|||||||
WHERE asim.source = 'user_cooccurrence'
|
WHERE asim.source = 'user_cooccurrence'
|
||||||
AND t.id NOT IN (SELECT id FROM excluded_ids)
|
AND t.id NOT IN (SELECT id FROM excluded_ids)
|
||||||
AND t.id <> $2
|
AND t.id <> $2
|
||||||
ORDER BY asim.score DESC, md5(t.id::text || $12::text)
|
ORDER BY asim.score DESC, random()
|
||||||
LIMIT $11
|
LIMIT $11
|
||||||
),
|
),
|
||||||
random_fill AS (
|
random_fill AS (
|
||||||
@@ -900,7 +900,7 @@ random_fill AS (
|
|||||||
UNION SELECT track_id FROM taste_overlap
|
UNION SELECT track_id FROM taste_overlap
|
||||||
UNION SELECT track_id FROM coplay_artists
|
UNION SELECT track_id FROM coplay_artists
|
||||||
)
|
)
|
||||||
ORDER BY md5(t.id::text || $12::text)
|
ORDER BY random()
|
||||||
LIMIT $9
|
LIMIT $9
|
||||||
)
|
)
|
||||||
SELECT
|
SELECT
|
||||||
@@ -938,18 +938,17 @@ GROUP BY t.id, t.title, t.album_id, t.artist_id, t.duration_ms, t.file_path,
|
|||||||
`
|
`
|
||||||
|
|
||||||
type LoadRadioCandidatesV2Params struct {
|
type LoadRadioCandidatesV2Params struct {
|
||||||
UserID pgtype.UUID
|
UserID pgtype.UUID
|
||||||
ID pgtype.UUID
|
ID pgtype.UUID
|
||||||
Column3 interface{}
|
Column3 interface{}
|
||||||
Column4 []pgtype.UUID
|
Column4 []pgtype.UUID
|
||||||
Limit int32
|
Limit int32
|
||||||
Limit_2 int32
|
Limit_2 int32
|
||||||
Limit_3 int32
|
Limit_3 int32
|
||||||
Limit_4 int32
|
Limit_4 int32
|
||||||
Limit_5 int32
|
Limit_5 int32
|
||||||
Limit_6 int32
|
Limit_6 int32
|
||||||
Limit_7 int32
|
Limit_7 int32
|
||||||
Column12 string
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type LoadRadioCandidatesV2Row struct {
|
type LoadRadioCandidatesV2Row struct {
|
||||||
@@ -972,22 +971,8 @@ type LoadRadioCandidatesV2Row struct {
|
|||||||
// enter the pool even when the similarity/random arms miss them; scored
|
// enter the pool even when the similarity/random arms miss them; scored
|
||||||
// in Go via TasteMatch, so sim_score here is 0 pool-inclusion),
|
// in Go via TasteMatch, so sim_score here is 0 pool-inclusion),
|
||||||
// $11 coplay_artists K (#1533 — tracks by artists co-played across the
|
// $11 coplay_artists K (#1533 — tracks by artists co-played across the
|
||||||
// instance with the seed's artist; source='user_cooccurrence'),
|
// instance with the seed's artist; source='user_cooccurrence').
|
||||||
// $12 order_seed (text) — see below.
|
|
||||||
//
|
//
|
||||||
// $12 REPLACES `ORDER BY random()` IN FOUR ARMS (#3889). Those arms returned
|
|
||||||
// a stable set only while their LIMIT exceeded the rows eligible for them: at
|
|
||||||
// that point they returned all of them and the order stopped mattering,
|
|
||||||
// because the caller sorts by track id before scoring. Below that threshold
|
|
||||||
// they returned a random SUBSET, and two builds on the same day drew
|
|
||||||
// different ones — so "daily determinism" held by accident, and only for
|
|
||||||
// libraries smaller than the limits.
|
|
||||||
//
|
|
||||||
// md5(id || seed) keeps the intent — an arbitrary spread that changes when
|
|
||||||
// the seed does — while making it reproducible for a given seed. The CALLER
|
|
||||||
// decides what that means: system mixes pass a per-(user, day) string and get
|
|
||||||
// the determinism they promise; radio passes a fresh value per request and
|
|
||||||
// keeps varying, which is what a radio should do.
|
|
||||||
// Returns same shape as LoadRadioCandidates plus similarity_score column.
|
// Returns same shape as LoadRadioCandidates plus similarity_score column.
|
||||||
func (q *Queries) LoadRadioCandidatesV2(ctx context.Context, arg LoadRadioCandidatesV2Params) ([]LoadRadioCandidatesV2Row, error) {
|
func (q *Queries) LoadRadioCandidatesV2(ctx context.Context, arg LoadRadioCandidatesV2Params) ([]LoadRadioCandidatesV2Row, error) {
|
||||||
rows, err := q.db.Query(ctx, loadRadioCandidatesV2,
|
rows, err := q.db.Query(ctx, loadRadioCandidatesV2,
|
||||||
@@ -1002,7 +987,6 @@ func (q *Queries) LoadRadioCandidatesV2(ctx context.Context, arg LoadRadioCandid
|
|||||||
arg.Limit_5,
|
arg.Limit_5,
|
||||||
arg.Limit_6,
|
arg.Limit_6,
|
||||||
arg.Limit_7,
|
arg.Limit_7,
|
||||||
arg.Column12,
|
|
||||||
)
|
)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
|
|||||||
@@ -69,38 +69,10 @@ func (q *Queries) DeleteSessionForUser(ctx context.Context, arg DeleteSessionFor
|
|||||||
return result.RowsAffected(), nil
|
return result.RowsAffected(), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
const deleteSessionsForUser = `-- name: DeleteSessionsForUser :execrows
|
|
||||||
DELETE FROM sessions WHERE user_id = $1
|
|
||||||
`
|
|
||||||
|
|
||||||
// Every session the user has, the caller's included. A password reset uses
|
|
||||||
// it: whoever forgot the password is not signed in anywhere they trust, and
|
|
||||||
// whoever may have learned it must be signed out everywhere.
|
|
||||||
func (q *Queries) DeleteSessionsForUser(ctx context.Context, userID pgtype.UUID) (int64, error) {
|
|
||||||
result, err := q.db.Exec(ctx, deleteSessionsForUser, userID)
|
|
||||||
if err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
return result.RowsAffected(), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
const getSessionByTokenHash = `-- name: GetSessionByTokenHash :one
|
const getSessionByTokenHash = `-- name: GetSessionByTokenHash :one
|
||||||
SELECT id, user_id, token_hash, user_agent, created_at, last_seen_at, created_ip, last_ip FROM sessions
|
SELECT id, user_id, token_hash, user_agent, created_at, last_seen_at, created_ip, last_ip FROM sessions WHERE token_hash = $1
|
||||||
WHERE token_hash = $1
|
|
||||||
AND last_seen_at > now() - interval '30 days'
|
|
||||||
AND created_at > now() - interval '365 days'
|
|
||||||
`
|
`
|
||||||
|
|
||||||
// Expired sessions are invisible here, so they fail auth the moment they
|
|
||||||
// lapse rather than whenever the GC sweep next runs. Two limits:
|
|
||||||
//
|
|
||||||
// idle 30 days — a token nobody has used in a month is abandoned, and
|
|
||||||
// matches the web cookie's lifetime;
|
|
||||||
// absolute 1 year — even a token in daily use is re-issued yearly, so a
|
|
||||||
// stolen one that is being used quietly does not live
|
|
||||||
// forever.
|
|
||||||
//
|
|
||||||
// Keep in step with ListSessionsForUser and GcDeleteExpiredSessions.
|
|
||||||
func (q *Queries) GetSessionByTokenHash(ctx context.Context, tokenHash []byte) (Session, error) {
|
func (q *Queries) GetSessionByTokenHash(ctx context.Context, tokenHash []byte) (Session, error) {
|
||||||
row := q.db.QueryRow(ctx, getSessionByTokenHash, tokenHash)
|
row := q.db.QueryRow(ctx, getSessionByTokenHash, tokenHash)
|
||||||
var i Session
|
var i Session
|
||||||
@@ -155,17 +127,11 @@ func (q *Queries) InsertSession(ctx context.Context, arg InsertSessionParams) (S
|
|||||||
}
|
}
|
||||||
|
|
||||||
const listSessionsForUser = `-- name: ListSessionsForUser :many
|
const listSessionsForUser = `-- name: ListSessionsForUser :many
|
||||||
SELECT id, user_id, token_hash, user_agent, created_at, last_seen_at, created_ip, last_ip FROM sessions
|
SELECT id, user_id, token_hash, user_agent, created_at, last_seen_at, created_ip, last_ip FROM sessions WHERE user_id = $1 ORDER BY last_seen_at DESC
|
||||||
WHERE user_id = $1
|
|
||||||
AND last_seen_at > now() - interval '30 days'
|
|
||||||
AND created_at > now() - interval '365 days'
|
|
||||||
ORDER BY last_seen_at DESC
|
|
||||||
`
|
`
|
||||||
|
|
||||||
// Most-recently-active first: the row a user is most likely to act on is the
|
// Most-recently-active first: the row a user is most likely to act on is the
|
||||||
// one that moved last, and an unfamiliar entry at the top is the alarm.
|
// one that moved last, and an unfamiliar entry at the top is the alarm.
|
||||||
// Expired rows are left out: they no longer authenticate, so listing them
|
|
||||||
// as active would be wrong. Same limits as GetSessionByTokenHash.
|
|
||||||
func (q *Queries) ListSessionsForUser(ctx context.Context, userID pgtype.UUID) ([]Session, error) {
|
func (q *Queries) ListSessionsForUser(ctx context.Context, userID pgtype.UUID) ([]Session, error) {
|
||||||
rows, err := q.db.Query(ctx, listSessionsForUser, userID)
|
rows, err := q.db.Query(ctx, listSessionsForUser, userID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@@ -148,36 +148,39 @@ func (q *Queries) DeleteTrack(ctx context.Context, id pgtype.UUID) (DeleteTrackR
|
|||||||
return i, err
|
return i, err
|
||||||
}
|
}
|
||||||
|
|
||||||
const findMissingTrackByAudioHash = `-- name: FindMissingTrackByAudioHash :many
|
const findMissingTrackByFingerprint = `-- name: FindMissingTrackByFingerprint :many
|
||||||
SELECT t.id, t.file_path
|
SELECT id, file_path FROM tracks
|
||||||
FROM tracks t
|
WHERE missing_since IS NOT NULL
|
||||||
JOIN track_fingerprints f ON f.track_id = t.id
|
AND file_size = $1
|
||||||
WHERE t.missing_since IS NOT NULL
|
AND duration_ms = $2
|
||||||
AND f.audio_stream_sha256 = $1
|
|
||||||
LIMIT 2
|
LIMIT 2
|
||||||
`
|
`
|
||||||
|
|
||||||
type FindMissingTrackByAudioHashRow struct {
|
type FindMissingTrackByFingerprintParams struct {
|
||||||
|
FileSize int64
|
||||||
|
DurationMs int32
|
||||||
|
}
|
||||||
|
|
||||||
|
type FindMissingTrackByFingerprintRow struct {
|
||||||
ID pgtype.UUID
|
ID pgtype.UUID
|
||||||
FilePath string
|
FilePath string
|
||||||
}
|
}
|
||||||
|
|
||||||
// Move detection fallback for files with no MBID (#2528, #3914). The audio stream
|
// Move detection fallback for files with no MBID (#2528). Exact byte size AND
|
||||||
// hash identifies the encoded audio itself, so it survives a rename, a move and a
|
// exact decoded duration is a strong pair: a plain move or rename preserves
|
||||||
// retag — anything short of a re-encode. It replaced (file_size, duration_ms),
|
// both, while a re-encode changes at least one — and a re-encode genuinely is a
|
||||||
// which could pair two unrelated files that happened to share a byte count and a
|
// different file, so failing to match there is correct rather than a gap.
|
||||||
// duration, and missed a file retagged in place, whose size changes.
|
|
||||||
//
|
//
|
||||||
// Same missing-only constraint and same LIMIT 2 rationale as the MBID variant.
|
// Same missing-only constraint and same LIMIT 2 rationale as the MBID variant.
|
||||||
func (q *Queries) FindMissingTrackByAudioHash(ctx context.Context, audioStreamSha256 []byte) ([]FindMissingTrackByAudioHashRow, error) {
|
func (q *Queries) FindMissingTrackByFingerprint(ctx context.Context, arg FindMissingTrackByFingerprintParams) ([]FindMissingTrackByFingerprintRow, error) {
|
||||||
rows, err := q.db.Query(ctx, findMissingTrackByAudioHash, audioStreamSha256)
|
rows, err := q.db.Query(ctx, findMissingTrackByFingerprint, arg.FileSize, arg.DurationMs)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
defer rows.Close()
|
defer rows.Close()
|
||||||
var items []FindMissingTrackByAudioHashRow
|
var items []FindMissingTrackByFingerprintRow
|
||||||
for rows.Next() {
|
for rows.Next() {
|
||||||
var i FindMissingTrackByAudioHashRow
|
var i FindMissingTrackByFingerprintRow
|
||||||
if err := rows.Scan(&i.ID, &i.FilePath); err != nil {
|
if err := rows.Scan(&i.ID, &i.FilePath); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -52,15 +52,15 @@ func (q *Queries) CountUsers(ctx context.Context) (int64, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const createUser = `-- name: CreateUser :one
|
const createUser = `-- name: CreateUser :one
|
||||||
INSERT INTO users (username, password_hash, api_token_hash, is_admin, display_name)
|
INSERT INTO users (username, password_hash, api_token, is_admin, display_name)
|
||||||
VALUES ($1, $2, $3, $4, $5)
|
VALUES ($1, $2, $3, $4, $5)
|
||||||
RETURNING id, username, password_hash, is_admin, created_at, subsonic_password, listenbrainz_token, listenbrainz_enabled, display_name, auto_approve_requests, email, timezone, timezone_updated_at, debug_mode_enabled, api_token_hash
|
RETURNING id, username, password_hash, api_token, is_admin, created_at, subsonic_password, listenbrainz_token, listenbrainz_enabled, display_name, auto_approve_requests, email, timezone, timezone_updated_at, debug_mode_enabled
|
||||||
`
|
`
|
||||||
|
|
||||||
type CreateUserParams struct {
|
type CreateUserParams struct {
|
||||||
Username string
|
Username string
|
||||||
PasswordHash string
|
PasswordHash string
|
||||||
ApiTokenHash string
|
ApiToken string
|
||||||
IsAdmin bool
|
IsAdmin bool
|
||||||
DisplayName *string
|
DisplayName *string
|
||||||
}
|
}
|
||||||
@@ -69,7 +69,7 @@ func (q *Queries) CreateUser(ctx context.Context, arg CreateUserParams) (User, e
|
|||||||
row := q.db.QueryRow(ctx, createUser,
|
row := q.db.QueryRow(ctx, createUser,
|
||||||
arg.Username,
|
arg.Username,
|
||||||
arg.PasswordHash,
|
arg.PasswordHash,
|
||||||
arg.ApiTokenHash,
|
arg.ApiToken,
|
||||||
arg.IsAdmin,
|
arg.IsAdmin,
|
||||||
arg.DisplayName,
|
arg.DisplayName,
|
||||||
)
|
)
|
||||||
@@ -78,6 +78,7 @@ func (q *Queries) CreateUser(ctx context.Context, arg CreateUserParams) (User, e
|
|||||||
&i.ID,
|
&i.ID,
|
||||||
&i.Username,
|
&i.Username,
|
||||||
&i.PasswordHash,
|
&i.PasswordHash,
|
||||||
|
&i.ApiToken,
|
||||||
&i.IsAdmin,
|
&i.IsAdmin,
|
||||||
&i.CreatedAt,
|
&i.CreatedAt,
|
||||||
&i.SubsonicPassword,
|
&i.SubsonicPassword,
|
||||||
@@ -89,21 +90,20 @@ func (q *Queries) CreateUser(ctx context.Context, arg CreateUserParams) (User, e
|
|||||||
&i.Timezone,
|
&i.Timezone,
|
||||||
&i.TimezoneUpdatedAt,
|
&i.TimezoneUpdatedAt,
|
||||||
&i.DebugModeEnabled,
|
&i.DebugModeEnabled,
|
||||||
&i.ApiTokenHash,
|
|
||||||
)
|
)
|
||||||
return i, err
|
return i, err
|
||||||
}
|
}
|
||||||
|
|
||||||
const createUserAdmin = `-- name: CreateUserAdmin :one
|
const createUserAdmin = `-- name: CreateUserAdmin :one
|
||||||
INSERT INTO users (username, password_hash, api_token_hash, is_admin, display_name)
|
INSERT INTO users (username, password_hash, api_token, is_admin, display_name)
|
||||||
VALUES ($1, $2, $3, $4, $5)
|
VALUES ($1, $2, $3, $4, $5)
|
||||||
RETURNING id, username, password_hash, is_admin, created_at, subsonic_password, listenbrainz_token, listenbrainz_enabled, display_name, auto_approve_requests, email, timezone, timezone_updated_at, debug_mode_enabled, api_token_hash
|
RETURNING id, username, password_hash, api_token, is_admin, created_at, subsonic_password, listenbrainz_token, listenbrainz_enabled, display_name, auto_approve_requests, email, timezone, timezone_updated_at, debug_mode_enabled
|
||||||
`
|
`
|
||||||
|
|
||||||
type CreateUserAdminParams struct {
|
type CreateUserAdminParams struct {
|
||||||
Username string
|
Username string
|
||||||
PasswordHash string
|
PasswordHash string
|
||||||
ApiTokenHash string
|
ApiToken string
|
||||||
IsAdmin bool
|
IsAdmin bool
|
||||||
DisplayName *string
|
DisplayName *string
|
||||||
}
|
}
|
||||||
@@ -115,7 +115,7 @@ func (q *Queries) CreateUserAdmin(ctx context.Context, arg CreateUserAdminParams
|
|||||||
row := q.db.QueryRow(ctx, createUserAdmin,
|
row := q.db.QueryRow(ctx, createUserAdmin,
|
||||||
arg.Username,
|
arg.Username,
|
||||||
arg.PasswordHash,
|
arg.PasswordHash,
|
||||||
arg.ApiTokenHash,
|
arg.ApiToken,
|
||||||
arg.IsAdmin,
|
arg.IsAdmin,
|
||||||
arg.DisplayName,
|
arg.DisplayName,
|
||||||
)
|
)
|
||||||
@@ -124,6 +124,7 @@ func (q *Queries) CreateUserAdmin(ctx context.Context, arg CreateUserAdminParams
|
|||||||
&i.ID,
|
&i.ID,
|
||||||
&i.Username,
|
&i.Username,
|
||||||
&i.PasswordHash,
|
&i.PasswordHash,
|
||||||
|
&i.ApiToken,
|
||||||
&i.IsAdmin,
|
&i.IsAdmin,
|
||||||
&i.CreatedAt,
|
&i.CreatedAt,
|
||||||
&i.SubsonicPassword,
|
&i.SubsonicPassword,
|
||||||
@@ -135,25 +136,24 @@ func (q *Queries) CreateUserAdmin(ctx context.Context, arg CreateUserAdminParams
|
|||||||
&i.Timezone,
|
&i.Timezone,
|
||||||
&i.TimezoneUpdatedAt,
|
&i.TimezoneUpdatedAt,
|
||||||
&i.DebugModeEnabled,
|
&i.DebugModeEnabled,
|
||||||
&i.ApiTokenHash,
|
|
||||||
)
|
)
|
||||||
return i, err
|
return i, err
|
||||||
}
|
}
|
||||||
|
|
||||||
const createUserFirstAdminRace = `-- name: CreateUserFirstAdminRace :one
|
const createUserFirstAdminRace = `-- name: CreateUserFirstAdminRace :one
|
||||||
INSERT INTO users (username, password_hash, api_token_hash, is_admin, display_name)
|
INSERT INTO users (username, password_hash, api_token, is_admin, display_name)
|
||||||
VALUES (
|
VALUES (
|
||||||
$1, $2, $3,
|
$1, $2, $3,
|
||||||
(SELECT NOT EXISTS (SELECT 1 FROM users)),
|
(SELECT NOT EXISTS (SELECT 1 FROM users)),
|
||||||
$4
|
$4
|
||||||
)
|
)
|
||||||
RETURNING id, username, password_hash, is_admin, created_at, subsonic_password, listenbrainz_token, listenbrainz_enabled, display_name, auto_approve_requests, email, timezone, timezone_updated_at, debug_mode_enabled, api_token_hash
|
RETURNING id, username, password_hash, api_token, is_admin, created_at, subsonic_password, listenbrainz_token, listenbrainz_enabled, display_name, auto_approve_requests, email, timezone, timezone_updated_at, debug_mode_enabled
|
||||||
`
|
`
|
||||||
|
|
||||||
type CreateUserFirstAdminRaceParams struct {
|
type CreateUserFirstAdminRaceParams struct {
|
||||||
Username string
|
Username string
|
||||||
PasswordHash string
|
PasswordHash string
|
||||||
ApiTokenHash string
|
ApiToken string
|
||||||
DisplayName *string
|
DisplayName *string
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -174,7 +174,7 @@ func (q *Queries) CreateUserFirstAdminRace(ctx context.Context, arg CreateUserFi
|
|||||||
row := q.db.QueryRow(ctx, createUserFirstAdminRace,
|
row := q.db.QueryRow(ctx, createUserFirstAdminRace,
|
||||||
arg.Username,
|
arg.Username,
|
||||||
arg.PasswordHash,
|
arg.PasswordHash,
|
||||||
arg.ApiTokenHash,
|
arg.ApiToken,
|
||||||
arg.DisplayName,
|
arg.DisplayName,
|
||||||
)
|
)
|
||||||
var i User
|
var i User
|
||||||
@@ -182,6 +182,7 @@ func (q *Queries) CreateUserFirstAdminRace(ctx context.Context, arg CreateUserFi
|
|||||||
&i.ID,
|
&i.ID,
|
||||||
&i.Username,
|
&i.Username,
|
||||||
&i.PasswordHash,
|
&i.PasswordHash,
|
||||||
|
&i.ApiToken,
|
||||||
&i.IsAdmin,
|
&i.IsAdmin,
|
||||||
&i.CreatedAt,
|
&i.CreatedAt,
|
||||||
&i.SubsonicPassword,
|
&i.SubsonicPassword,
|
||||||
@@ -193,7 +194,6 @@ func (q *Queries) CreateUserFirstAdminRace(ctx context.Context, arg CreateUserFi
|
|||||||
&i.Timezone,
|
&i.Timezone,
|
||||||
&i.TimezoneUpdatedAt,
|
&i.TimezoneUpdatedAt,
|
||||||
&i.DebugModeEnabled,
|
&i.DebugModeEnabled,
|
||||||
&i.ApiTokenHash,
|
|
||||||
)
|
)
|
||||||
return i, err
|
return i, err
|
||||||
}
|
}
|
||||||
@@ -240,7 +240,7 @@ func (q *Queries) GetListenBrainzConfig(ctx context.Context, id pgtype.UUID) (Ge
|
|||||||
}
|
}
|
||||||
|
|
||||||
const getOldestAdmin = `-- name: GetOldestAdmin :one
|
const getOldestAdmin = `-- name: GetOldestAdmin :one
|
||||||
SELECT id, username, password_hash, is_admin, created_at, subsonic_password, listenbrainz_token, listenbrainz_enabled, display_name, auto_approve_requests, email, timezone, timezone_updated_at, debug_mode_enabled, api_token_hash FROM users
|
SELECT id, username, password_hash, api_token, is_admin, created_at, subsonic_password, listenbrainz_token, listenbrainz_enabled, display_name, auto_approve_requests, email, timezone, timezone_updated_at, debug_mode_enabled FROM users
|
||||||
WHERE is_admin = true
|
WHERE is_admin = true
|
||||||
ORDER BY created_at, id
|
ORDER BY created_at, id
|
||||||
LIMIT 1
|
LIMIT 1
|
||||||
@@ -260,6 +260,7 @@ func (q *Queries) GetOldestAdmin(ctx context.Context) (User, error) {
|
|||||||
&i.ID,
|
&i.ID,
|
||||||
&i.Username,
|
&i.Username,
|
||||||
&i.PasswordHash,
|
&i.PasswordHash,
|
||||||
|
&i.ApiToken,
|
||||||
&i.IsAdmin,
|
&i.IsAdmin,
|
||||||
&i.CreatedAt,
|
&i.CreatedAt,
|
||||||
&i.SubsonicPassword,
|
&i.SubsonicPassword,
|
||||||
@@ -271,22 +272,22 @@ func (q *Queries) GetOldestAdmin(ctx context.Context) (User, error) {
|
|||||||
&i.Timezone,
|
&i.Timezone,
|
||||||
&i.TimezoneUpdatedAt,
|
&i.TimezoneUpdatedAt,
|
||||||
&i.DebugModeEnabled,
|
&i.DebugModeEnabled,
|
||||||
&i.ApiTokenHash,
|
|
||||||
)
|
)
|
||||||
return i, err
|
return i, err
|
||||||
}
|
}
|
||||||
|
|
||||||
const getUserByAPITokenHash = `-- name: GetUserByAPITokenHash :one
|
const getUserByAPIToken = `-- name: GetUserByAPIToken :one
|
||||||
SELECT id, username, password_hash, is_admin, created_at, subsonic_password, listenbrainz_token, listenbrainz_enabled, display_name, auto_approve_requests, email, timezone, timezone_updated_at, debug_mode_enabled, api_token_hash FROM users WHERE api_token_hash = $1
|
SELECT id, username, password_hash, api_token, is_admin, created_at, subsonic_password, listenbrainz_token, listenbrainz_enabled, display_name, auto_approve_requests, email, timezone, timezone_updated_at, debug_mode_enabled FROM users WHERE api_token = $1
|
||||||
`
|
`
|
||||||
|
|
||||||
func (q *Queries) GetUserByAPITokenHash(ctx context.Context, apiTokenHash string) (User, error) {
|
func (q *Queries) GetUserByAPIToken(ctx context.Context, apiToken string) (User, error) {
|
||||||
row := q.db.QueryRow(ctx, getUserByAPITokenHash, apiTokenHash)
|
row := q.db.QueryRow(ctx, getUserByAPIToken, apiToken)
|
||||||
var i User
|
var i User
|
||||||
err := row.Scan(
|
err := row.Scan(
|
||||||
&i.ID,
|
&i.ID,
|
||||||
&i.Username,
|
&i.Username,
|
||||||
&i.PasswordHash,
|
&i.PasswordHash,
|
||||||
|
&i.ApiToken,
|
||||||
&i.IsAdmin,
|
&i.IsAdmin,
|
||||||
&i.CreatedAt,
|
&i.CreatedAt,
|
||||||
&i.SubsonicPassword,
|
&i.SubsonicPassword,
|
||||||
@@ -298,13 +299,12 @@ func (q *Queries) GetUserByAPITokenHash(ctx context.Context, apiTokenHash string
|
|||||||
&i.Timezone,
|
&i.Timezone,
|
||||||
&i.TimezoneUpdatedAt,
|
&i.TimezoneUpdatedAt,
|
||||||
&i.DebugModeEnabled,
|
&i.DebugModeEnabled,
|
||||||
&i.ApiTokenHash,
|
|
||||||
)
|
)
|
||||||
return i, err
|
return i, err
|
||||||
}
|
}
|
||||||
|
|
||||||
const getUserByEmail = `-- name: GetUserByEmail :one
|
const getUserByEmail = `-- name: GetUserByEmail :one
|
||||||
SELECT id, username, password_hash, is_admin, created_at, subsonic_password, listenbrainz_token, listenbrainz_enabled, display_name, auto_approve_requests, email, timezone, timezone_updated_at, debug_mode_enabled, api_token_hash FROM users WHERE lower(email) = lower($1)
|
SELECT id, username, password_hash, api_token, is_admin, created_at, subsonic_password, listenbrainz_token, listenbrainz_enabled, display_name, auto_approve_requests, email, timezone, timezone_updated_at, debug_mode_enabled FROM users WHERE lower(email) = lower($1)
|
||||||
`
|
`
|
||||||
|
|
||||||
// Used by forgot-password lookup. Lowercase comparison both sides
|
// Used by forgot-password lookup. Lowercase comparison both sides
|
||||||
@@ -317,6 +317,7 @@ func (q *Queries) GetUserByEmail(ctx context.Context, lower string) (User, error
|
|||||||
&i.ID,
|
&i.ID,
|
||||||
&i.Username,
|
&i.Username,
|
||||||
&i.PasswordHash,
|
&i.PasswordHash,
|
||||||
|
&i.ApiToken,
|
||||||
&i.IsAdmin,
|
&i.IsAdmin,
|
||||||
&i.CreatedAt,
|
&i.CreatedAt,
|
||||||
&i.SubsonicPassword,
|
&i.SubsonicPassword,
|
||||||
@@ -328,13 +329,12 @@ func (q *Queries) GetUserByEmail(ctx context.Context, lower string) (User, error
|
|||||||
&i.Timezone,
|
&i.Timezone,
|
||||||
&i.TimezoneUpdatedAt,
|
&i.TimezoneUpdatedAt,
|
||||||
&i.DebugModeEnabled,
|
&i.DebugModeEnabled,
|
||||||
&i.ApiTokenHash,
|
|
||||||
)
|
)
|
||||||
return i, err
|
return i, err
|
||||||
}
|
}
|
||||||
|
|
||||||
const getUserByID = `-- name: GetUserByID :one
|
const getUserByID = `-- name: GetUserByID :one
|
||||||
SELECT id, username, password_hash, is_admin, created_at, subsonic_password, listenbrainz_token, listenbrainz_enabled, display_name, auto_approve_requests, email, timezone, timezone_updated_at, debug_mode_enabled, api_token_hash FROM users WHERE id = $1
|
SELECT id, username, password_hash, api_token, is_admin, created_at, subsonic_password, listenbrainz_token, listenbrainz_enabled, display_name, auto_approve_requests, email, timezone, timezone_updated_at, debug_mode_enabled FROM users WHERE id = $1
|
||||||
`
|
`
|
||||||
|
|
||||||
func (q *Queries) GetUserByID(ctx context.Context, id pgtype.UUID) (User, error) {
|
func (q *Queries) GetUserByID(ctx context.Context, id pgtype.UUID) (User, error) {
|
||||||
@@ -344,6 +344,7 @@ func (q *Queries) GetUserByID(ctx context.Context, id pgtype.UUID) (User, error)
|
|||||||
&i.ID,
|
&i.ID,
|
||||||
&i.Username,
|
&i.Username,
|
||||||
&i.PasswordHash,
|
&i.PasswordHash,
|
||||||
|
&i.ApiToken,
|
||||||
&i.IsAdmin,
|
&i.IsAdmin,
|
||||||
&i.CreatedAt,
|
&i.CreatedAt,
|
||||||
&i.SubsonicPassword,
|
&i.SubsonicPassword,
|
||||||
@@ -355,13 +356,12 @@ func (q *Queries) GetUserByID(ctx context.Context, id pgtype.UUID) (User, error)
|
|||||||
&i.Timezone,
|
&i.Timezone,
|
||||||
&i.TimezoneUpdatedAt,
|
&i.TimezoneUpdatedAt,
|
||||||
&i.DebugModeEnabled,
|
&i.DebugModeEnabled,
|
||||||
&i.ApiTokenHash,
|
|
||||||
)
|
)
|
||||||
return i, err
|
return i, err
|
||||||
}
|
}
|
||||||
|
|
||||||
const getUserByUsername = `-- name: GetUserByUsername :one
|
const getUserByUsername = `-- name: GetUserByUsername :one
|
||||||
SELECT id, username, password_hash, is_admin, created_at, subsonic_password, listenbrainz_token, listenbrainz_enabled, display_name, auto_approve_requests, email, timezone, timezone_updated_at, debug_mode_enabled, api_token_hash FROM users WHERE username = $1
|
SELECT id, username, password_hash, api_token, is_admin, created_at, subsonic_password, listenbrainz_token, listenbrainz_enabled, display_name, auto_approve_requests, email, timezone, timezone_updated_at, debug_mode_enabled FROM users WHERE username = $1
|
||||||
`
|
`
|
||||||
|
|
||||||
func (q *Queries) GetUserByUsername(ctx context.Context, username string) (User, error) {
|
func (q *Queries) GetUserByUsername(ctx context.Context, username string) (User, error) {
|
||||||
@@ -371,6 +371,7 @@ func (q *Queries) GetUserByUsername(ctx context.Context, username string) (User,
|
|||||||
&i.ID,
|
&i.ID,
|
||||||
&i.Username,
|
&i.Username,
|
||||||
&i.PasswordHash,
|
&i.PasswordHash,
|
||||||
|
&i.ApiToken,
|
||||||
&i.IsAdmin,
|
&i.IsAdmin,
|
||||||
&i.CreatedAt,
|
&i.CreatedAt,
|
||||||
&i.SubsonicPassword,
|
&i.SubsonicPassword,
|
||||||
@@ -382,7 +383,6 @@ func (q *Queries) GetUserByUsername(ctx context.Context, username string) (User,
|
|||||||
&i.Timezone,
|
&i.Timezone,
|
||||||
&i.TimezoneUpdatedAt,
|
&i.TimezoneUpdatedAt,
|
||||||
&i.DebugModeEnabled,
|
&i.DebugModeEnabled,
|
||||||
&i.ApiTokenHash,
|
|
||||||
)
|
)
|
||||||
return i, err
|
return i, err
|
||||||
}
|
}
|
||||||
@@ -471,21 +471,39 @@ func (q *Queries) ListUsers(ctx context.Context) ([]ListUsersRow, error) {
|
|||||||
return items, nil
|
return items, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
const regenerateApiToken = `-- name: RegenerateApiToken :exec
|
const regenerateApiToken = `-- name: RegenerateApiToken :one
|
||||||
UPDATE users SET api_token_hash = $2 WHERE id = $1
|
UPDATE users SET api_token = $2 WHERE id = $1
|
||||||
|
RETURNING id, username, password_hash, api_token, is_admin, created_at, subsonic_password, listenbrainz_token, listenbrainz_enabled, display_name, auto_approve_requests, email, timezone, timezone_updated_at, debug_mode_enabled
|
||||||
`
|
`
|
||||||
|
|
||||||
type RegenerateApiTokenParams struct {
|
type RegenerateApiTokenParams struct {
|
||||||
ID pgtype.UUID
|
ID pgtype.UUID
|
||||||
ApiTokenHash string
|
ApiToken string
|
||||||
}
|
}
|
||||||
|
|
||||||
// Self-service: caller wants a new API token. Used by the /settings
|
// Self-service: caller wants a new API token. Used by the /settings
|
||||||
// API Token card's "Regenerate" button. Only the hash is stored; the
|
// API Token card's "Regenerate" button.
|
||||||
// handler returns the raw key once.
|
func (q *Queries) RegenerateApiToken(ctx context.Context, arg RegenerateApiTokenParams) (User, error) {
|
||||||
func (q *Queries) RegenerateApiToken(ctx context.Context, arg RegenerateApiTokenParams) error {
|
row := q.db.QueryRow(ctx, regenerateApiToken, arg.ID, arg.ApiToken)
|
||||||
_, err := q.db.Exec(ctx, regenerateApiToken, arg.ID, arg.ApiTokenHash)
|
var i User
|
||||||
return err
|
err := row.Scan(
|
||||||
|
&i.ID,
|
||||||
|
&i.Username,
|
||||||
|
&i.PasswordHash,
|
||||||
|
&i.ApiToken,
|
||||||
|
&i.IsAdmin,
|
||||||
|
&i.CreatedAt,
|
||||||
|
&i.SubsonicPassword,
|
||||||
|
&i.ListenbrainzToken,
|
||||||
|
&i.ListenbrainzEnabled,
|
||||||
|
&i.DisplayName,
|
||||||
|
&i.AutoApproveRequests,
|
||||||
|
&i.Email,
|
||||||
|
&i.Timezone,
|
||||||
|
&i.TimezoneUpdatedAt,
|
||||||
|
&i.DebugModeEnabled,
|
||||||
|
)
|
||||||
|
return i, err
|
||||||
}
|
}
|
||||||
|
|
||||||
const resetUserPassword = `-- name: ResetUserPassword :exec
|
const resetUserPassword = `-- name: ResetUserPassword :exec
|
||||||
@@ -512,7 +530,7 @@ const setDebugMode = `-- name: SetDebugMode :one
|
|||||||
UPDATE users
|
UPDATE users
|
||||||
SET debug_mode_enabled = $2
|
SET debug_mode_enabled = $2
|
||||||
WHERE id = $1
|
WHERE id = $1
|
||||||
RETURNING id, username, password_hash, is_admin, created_at, subsonic_password, listenbrainz_token, listenbrainz_enabled, display_name, auto_approve_requests, email, timezone, timezone_updated_at, debug_mode_enabled, api_token_hash
|
RETURNING id, username, password_hash, api_token, is_admin, created_at, subsonic_password, listenbrainz_token, listenbrainz_enabled, display_name, auto_approve_requests, email, timezone, timezone_updated_at, debug_mode_enabled
|
||||||
`
|
`
|
||||||
|
|
||||||
type SetDebugModeParams struct {
|
type SetDebugModeParams struct {
|
||||||
@@ -530,6 +548,7 @@ func (q *Queries) SetDebugMode(ctx context.Context, arg SetDebugModeParams) (Use
|
|||||||
&i.ID,
|
&i.ID,
|
||||||
&i.Username,
|
&i.Username,
|
||||||
&i.PasswordHash,
|
&i.PasswordHash,
|
||||||
|
&i.ApiToken,
|
||||||
&i.IsAdmin,
|
&i.IsAdmin,
|
||||||
&i.CreatedAt,
|
&i.CreatedAt,
|
||||||
&i.SubsonicPassword,
|
&i.SubsonicPassword,
|
||||||
@@ -541,7 +560,6 @@ func (q *Queries) SetDebugMode(ctx context.Context, arg SetDebugModeParams) (Use
|
|||||||
&i.Timezone,
|
&i.Timezone,
|
||||||
&i.TimezoneUpdatedAt,
|
&i.TimezoneUpdatedAt,
|
||||||
&i.DebugModeEnabled,
|
&i.DebugModeEnabled,
|
||||||
&i.ApiTokenHash,
|
|
||||||
)
|
)
|
||||||
return i, err
|
return i, err
|
||||||
}
|
}
|
||||||
@@ -599,7 +617,7 @@ const updateUserAdmin = `-- name: UpdateUserAdmin :one
|
|||||||
UPDATE users
|
UPDATE users
|
||||||
SET is_admin = $2
|
SET is_admin = $2
|
||||||
WHERE id = $1
|
WHERE id = $1
|
||||||
RETURNING id, username, password_hash, is_admin, created_at, subsonic_password, listenbrainz_token, listenbrainz_enabled, display_name, auto_approve_requests, email, timezone, timezone_updated_at, debug_mode_enabled, api_token_hash
|
RETURNING id, username, password_hash, api_token, is_admin, created_at, subsonic_password, listenbrainz_token, listenbrainz_enabled, display_name, auto_approve_requests, email, timezone, timezone_updated_at, debug_mode_enabled
|
||||||
`
|
`
|
||||||
|
|
||||||
type UpdateUserAdminParams struct {
|
type UpdateUserAdminParams struct {
|
||||||
@@ -616,6 +634,7 @@ func (q *Queries) UpdateUserAdmin(ctx context.Context, arg UpdateUserAdminParams
|
|||||||
&i.ID,
|
&i.ID,
|
||||||
&i.Username,
|
&i.Username,
|
||||||
&i.PasswordHash,
|
&i.PasswordHash,
|
||||||
|
&i.ApiToken,
|
||||||
&i.IsAdmin,
|
&i.IsAdmin,
|
||||||
&i.CreatedAt,
|
&i.CreatedAt,
|
||||||
&i.SubsonicPassword,
|
&i.SubsonicPassword,
|
||||||
@@ -627,7 +646,6 @@ func (q *Queries) UpdateUserAdmin(ctx context.Context, arg UpdateUserAdminParams
|
|||||||
&i.Timezone,
|
&i.Timezone,
|
||||||
&i.TimezoneUpdatedAt,
|
&i.TimezoneUpdatedAt,
|
||||||
&i.DebugModeEnabled,
|
&i.DebugModeEnabled,
|
||||||
&i.ApiTokenHash,
|
|
||||||
)
|
)
|
||||||
return i, err
|
return i, err
|
||||||
}
|
}
|
||||||
@@ -636,7 +654,7 @@ const updateUserAutoApprove = `-- name: UpdateUserAutoApprove :one
|
|||||||
UPDATE users
|
UPDATE users
|
||||||
SET auto_approve_requests = $2
|
SET auto_approve_requests = $2
|
||||||
WHERE id = $1
|
WHERE id = $1
|
||||||
RETURNING id, username, password_hash, is_admin, created_at, subsonic_password, listenbrainz_token, listenbrainz_enabled, display_name, auto_approve_requests, email, timezone, timezone_updated_at, debug_mode_enabled, api_token_hash
|
RETURNING id, username, password_hash, api_token, is_admin, created_at, subsonic_password, listenbrainz_token, listenbrainz_enabled, display_name, auto_approve_requests, email, timezone, timezone_updated_at, debug_mode_enabled
|
||||||
`
|
`
|
||||||
|
|
||||||
type UpdateUserAutoApproveParams struct {
|
type UpdateUserAutoApproveParams struct {
|
||||||
@@ -652,6 +670,7 @@ func (q *Queries) UpdateUserAutoApprove(ctx context.Context, arg UpdateUserAutoA
|
|||||||
&i.ID,
|
&i.ID,
|
||||||
&i.Username,
|
&i.Username,
|
||||||
&i.PasswordHash,
|
&i.PasswordHash,
|
||||||
|
&i.ApiToken,
|
||||||
&i.IsAdmin,
|
&i.IsAdmin,
|
||||||
&i.CreatedAt,
|
&i.CreatedAt,
|
||||||
&i.SubsonicPassword,
|
&i.SubsonicPassword,
|
||||||
@@ -663,7 +682,6 @@ func (q *Queries) UpdateUserAutoApprove(ctx context.Context, arg UpdateUserAutoA
|
|||||||
&i.Timezone,
|
&i.Timezone,
|
||||||
&i.TimezoneUpdatedAt,
|
&i.TimezoneUpdatedAt,
|
||||||
&i.DebugModeEnabled,
|
&i.DebugModeEnabled,
|
||||||
&i.ApiTokenHash,
|
|
||||||
)
|
)
|
||||||
return i, err
|
return i, err
|
||||||
}
|
}
|
||||||
@@ -673,7 +691,7 @@ UPDATE users
|
|||||||
SET display_name = $2,
|
SET display_name = $2,
|
||||||
email = $3
|
email = $3
|
||||||
WHERE id = $1
|
WHERE id = $1
|
||||||
RETURNING id, username, password_hash, is_admin, created_at, subsonic_password, listenbrainz_token, listenbrainz_enabled, display_name, auto_approve_requests, email, timezone, timezone_updated_at, debug_mode_enabled, api_token_hash
|
RETURNING id, username, password_hash, api_token, is_admin, created_at, subsonic_password, listenbrainz_token, listenbrainz_enabled, display_name, auto_approve_requests, email, timezone, timezone_updated_at, debug_mode_enabled
|
||||||
`
|
`
|
||||||
|
|
||||||
type UpdateUserProfileParams struct {
|
type UpdateUserProfileParams struct {
|
||||||
@@ -691,6 +709,7 @@ func (q *Queries) UpdateUserProfile(ctx context.Context, arg UpdateUserProfilePa
|
|||||||
&i.ID,
|
&i.ID,
|
||||||
&i.Username,
|
&i.Username,
|
||||||
&i.PasswordHash,
|
&i.PasswordHash,
|
||||||
|
&i.ApiToken,
|
||||||
&i.IsAdmin,
|
&i.IsAdmin,
|
||||||
&i.CreatedAt,
|
&i.CreatedAt,
|
||||||
&i.SubsonicPassword,
|
&i.SubsonicPassword,
|
||||||
@@ -702,7 +721,6 @@ func (q *Queries) UpdateUserProfile(ctx context.Context, arg UpdateUserProfilePa
|
|||||||
&i.Timezone,
|
&i.Timezone,
|
||||||
&i.TimezoneUpdatedAt,
|
&i.TimezoneUpdatedAt,
|
||||||
&i.DebugModeEnabled,
|
&i.DebugModeEnabled,
|
||||||
&i.ApiTokenHash,
|
|
||||||
)
|
)
|
||||||
return i, err
|
return i, err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,16 +0,0 @@
|
|||||||
-- Drop the rows the narrower constraints are about to forbid, or re-adding
|
|
||||||
-- them fails against existing data (the 0051 down-migration pattern).
|
|
||||||
DELETE FROM recommendation_weight_profiles WHERE profile = 'songs_like';
|
|
||||||
DELETE FROM recommendation_tuning_audit WHERE scope = 'songs_like';
|
|
||||||
|
|
||||||
ALTER TABLE recommendation_tuning_audit
|
|
||||||
DROP CONSTRAINT recommendation_tuning_audit_scope_check;
|
|
||||||
ALTER TABLE recommendation_tuning_audit
|
|
||||||
ADD CONSTRAINT recommendation_tuning_audit_scope_check
|
|
||||||
CHECK (scope IN ('radio', 'daily_mix', 'taste', 'discover'));
|
|
||||||
|
|
||||||
ALTER TABLE recommendation_weight_profiles
|
|
||||||
DROP CONSTRAINT recommendation_weight_profiles_profile_check;
|
|
||||||
ALTER TABLE recommendation_weight_profiles
|
|
||||||
ADD CONSTRAINT recommendation_weight_profiles_profile_check
|
|
||||||
CHECK (profile IN ('radio', 'daily_mix'));
|
|
||||||
@@ -1,37 +0,0 @@
|
|||||||
-- 0057_songs_like_tuning.up.sql — a THIRD weight profile, for Songs-like
|
|
||||||
-- (Scribe #3881, milestone #398).
|
|
||||||
--
|
|
||||||
-- Songs-like shared the `daily_mix` profile with For-You, and that is the bug.
|
|
||||||
-- The two surfaces want opposite things: For-You is a broad "what will they
|
|
||||||
-- enjoy today", Songs-like answers "what sounds like THIS", and under one set
|
|
||||||
-- of weights the broad answer wins. Operator, 2026-09-10: "I'm expecting to
|
|
||||||
-- get a consistent sound and style from the experience... I was getting a
|
|
||||||
-- seeming wide variety of music from each one when I was hoping to stay in a
|
|
||||||
-- certain neighborhood."
|
|
||||||
--
|
|
||||||
-- Under the shared daily_mix weights, an UNRELATED track the user had liked
|
|
||||||
-- and not played recently scored 1.0 + 2.0 + 1.0 = 4.0 before taste, while a
|
|
||||||
-- PERFECT similarity match they had not liked scored 1.0 + 1.5 = 2.5. Liking
|
|
||||||
-- something outranked sounding like the seed. Splitting the profile is what
|
|
||||||
-- lets similarity dominate here without making For-You narrow.
|
|
||||||
--
|
|
||||||
-- Rows are seeded by the recsettings boot reconcile, not here, so shipped
|
|
||||||
-- defaults live in exactly one place (Go) — same as 0040.
|
|
||||||
|
|
||||||
-- Rule #36: a new value for a CHECK-gated column needs the constraint
|
|
||||||
-- rewritten in the SAME change, or the first row written under the new
|
|
||||||
-- profile fails at runtime rather than at migrate time.
|
|
||||||
ALTER TABLE recommendation_weight_profiles
|
|
||||||
DROP CONSTRAINT recommendation_weight_profiles_profile_check;
|
|
||||||
ALTER TABLE recommendation_weight_profiles
|
|
||||||
ADD CONSTRAINT recommendation_weight_profiles_profile_check
|
|
||||||
CHECK (profile IN ('radio', 'daily_mix', 'songs_like'));
|
|
||||||
|
|
||||||
-- The audit table gates the same name on a separate constraint. Missing this
|
|
||||||
-- one would let the profile be seeded and then fail on the first knob turn —
|
|
||||||
-- green at boot, 500 on first use.
|
|
||||||
ALTER TABLE recommendation_tuning_audit
|
|
||||||
DROP CONSTRAINT recommendation_tuning_audit_scope_check;
|
|
||||||
ALTER TABLE recommendation_tuning_audit
|
|
||||||
ADD CONSTRAINT recommendation_tuning_audit_scope_check
|
|
||||||
CHECK (scope IN ('radio', 'daily_mix', 'taste', 'discover', 'songs_like'));
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
DROP TABLE track_fingerprints;
|
|
||||||
@@ -1,38 +0,0 @@
|
|||||||
-- 0058_track_fingerprints.up.sql — an acoustic identity per track (Scribe
|
|
||||||
-- milestone #400: #3905, #3906).
|
|
||||||
--
|
|
||||||
-- A table of its own rather than columns on tracks, for the hot path's sake:
|
|
||||||
-- tracks is read with SELECT * by eight queries, among them ListTracksByAlbum,
|
|
||||||
-- SearchTracks and GetTracksByIDs — album pages, search, the Subsonic surface.
|
|
||||||
-- A ~4 KB chromaprint column on tracks would be de-TOASTed on every one of
|
|
||||||
-- those reads to carry a value only the duplicate sweep ever looks at.
|
|
||||||
--
|
|
||||||
-- What a row means, which the backfill depends on:
|
|
||||||
-- no row never fingerprinted
|
|
||||||
-- fingerprint_version < current derived by an older method; re-derive it
|
|
||||||
-- fingerprint_version = current attempted; a NULL value means that tool
|
|
||||||
-- failed on this file, and it is not retried
|
|
||||||
-- until the file changes
|
|
||||||
-- A failure that says nothing about the file — a timeout, a cancelled scan, a
|
|
||||||
-- missing binary — writes no row at all, so the backfill tries again.
|
|
||||||
CREATE TABLE track_fingerprints (
|
|
||||||
-- CASCADE is right here, unlike for the likes and play history M400's
|
|
||||||
-- merge has to carry across: a fingerprint describes one file's bytes and
|
|
||||||
-- means nothing once that file's row is gone.
|
|
||||||
track_id uuid PRIMARY KEY REFERENCES tracks (id) ON DELETE CASCADE,
|
|
||||||
-- SHA-256 of the ENCODED audio packets (ffmpeg -c:a copy -f hash), not of
|
|
||||||
-- decoded samples. internal/library/fingerprint.go says why.
|
|
||||||
audio_stream_sha256 bytea
|
|
||||||
CHECK (audio_stream_sha256 IS NULL OR octet_length(audio_stream_sha256) = 32),
|
|
||||||
-- fpcalc -raw -signed: the same 32 bits per item, stored signed because
|
|
||||||
-- integer is.
|
|
||||||
chromaprint integer[],
|
|
||||||
fingerprint_version smallint NOT NULL,
|
|
||||||
computed_at timestamptz NOT NULL DEFAULT now()
|
|
||||||
);
|
|
||||||
|
|
||||||
-- The exact duplicate tier is an equality match on this column. Partial
|
|
||||||
-- because a NULL is never looked up — it only means the hash was not taken.
|
|
||||||
CREATE INDEX track_fingerprints_audio_stream_sha256
|
|
||||||
ON track_fingerprints (audio_stream_sha256)
|
|
||||||
WHERE audio_stream_sha256 IS NOT NULL;
|
|
||||||
@@ -1,4 +0,0 @@
|
|||||||
DROP INDEX IF EXISTS tracks_duration_id_idx;
|
|
||||||
DROP TABLE duplicate_group_members;
|
|
||||||
DROP TABLE duplicate_groups;
|
|
||||||
DROP TABLE duplicate_sweeps;
|
|
||||||
@@ -1,54 +0,0 @@
|
|||||||
-- 0059_duplicate_groups.up.sql — proposed duplicates and the sweeps that find
|
|
||||||
-- them (Scribe milestone #400: #3910).
|
|
||||||
--
|
|
||||||
-- The sweep compares fingerprints (track_fingerprints, 0058) and proposes groups
|
|
||||||
-- of tracks that hold one recording. Nothing here merges anything: a group is a
|
|
||||||
-- proposal the operator reviews, and the merge (#3911) is a separate act.
|
|
||||||
|
|
||||||
-- One row per sweep. Lets the report tell "the sweep has never run" apart from
|
|
||||||
-- "it ran and found nothing", and gives the in-flight guard something to check,
|
|
||||||
-- the same way scan_runs does for the library scan.
|
|
||||||
CREATE TABLE duplicate_sweeps (
|
|
||||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
||||||
started_at timestamptz NOT NULL DEFAULT now(),
|
|
||||||
finished_at timestamptz,
|
|
||||||
candidates integer,
|
|
||||||
groups_found integer,
|
|
||||||
oversize_clusters integer,
|
|
||||||
error_message text
|
|
||||||
);
|
|
||||||
CREATE INDEX duplicate_sweeps_started_at_idx ON duplicate_sweeps (started_at DESC);
|
|
||||||
|
|
||||||
CREATE TABLE duplicate_groups (
|
|
||||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
||||||
-- The group's identity: its member track ids, sorted and joined. A sweep
|
|
||||||
-- that finds the same tracks again updates this row rather than proposing
|
|
||||||
-- them twice, and a dismissal stays attached to the set it was made about.
|
|
||||||
member_key text NOT NULL UNIQUE,
|
|
||||||
-- Rule 36: a new value for either CHECK swaps the constraint in the same
|
|
||||||
-- migration.
|
|
||||||
tier text NOT NULL CHECK (tier IN ('exact', 'acoustic')),
|
|
||||||
-- Largest disagreement between any two members; NULL for exact groups,
|
|
||||||
-- which have no score.
|
|
||||||
worst_bit_error_rate real,
|
|
||||||
status text NOT NULL DEFAULT 'pending'
|
|
||||||
CHECK (status IN ('pending', 'dismissed', 'merged')),
|
|
||||||
detected_at timestamptz NOT NULL DEFAULT now(),
|
|
||||||
last_seen_sweep_id uuid REFERENCES duplicate_sweeps (id) ON DELETE SET NULL,
|
|
||||||
resolved_at timestamptz
|
|
||||||
);
|
|
||||||
CREATE INDEX duplicate_groups_status_idx ON duplicate_groups (status);
|
|
||||||
|
|
||||||
CREATE TABLE duplicate_group_members (
|
|
||||||
group_id uuid NOT NULL REFERENCES duplicate_groups (id) ON DELETE CASCADE,
|
|
||||||
-- CASCADE is right here: a track that genuinely leaves the library has no
|
|
||||||
-- place in a proposal about its duplicates.
|
|
||||||
track_id uuid NOT NULL REFERENCES tracks (id) ON DELETE CASCADE,
|
|
||||||
PRIMARY KEY (group_id, track_id)
|
|
||||||
);
|
|
||||||
CREATE INDEX duplicate_group_members_track_idx ON duplicate_group_members (track_id);
|
|
||||||
|
|
||||||
-- The sweep streams candidates in (duration_ms, id) order, keyset-paged, so it
|
|
||||||
-- only ever holds a few seconds' worth of durations in memory. Without this each
|
|
||||||
-- page would sort the whole library again.
|
|
||||||
CREATE INDEX tracks_duration_id_idx ON tracks (duration_ms, id);
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
DROP INDEX IF EXISTS play_events_track_idx;
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
-- 0060_play_events_track_index.up.sql — play_events by track (Scribe #3912, #3911).
|
|
||||||
--
|
|
||||||
-- play_events is indexed by (user_id, started_at) and (user_id, track_id), both
|
|
||||||
-- led by user. Nothing reached it by track alone until the duplicates report,
|
|
||||||
-- which shows each copy's play count — a scan of the whole table per copy — and
|
|
||||||
-- the merge (#3911), which repoints a duplicate's play history onto the copy
|
|
||||||
-- being kept. Both ask "every play of this track", whoever played it.
|
|
||||||
CREATE INDEX play_events_track_idx ON play_events (track_id);
|
|
||||||
@@ -1,2 +0,0 @@
|
|||||||
ALTER TABLE track_fingerprints DROP COLUMN chromaprint_length_sec;
|
|
||||||
DROP TABLE fingerprint_settings;
|
|
||||||
@@ -1,50 +0,0 @@
|
|||||||
-- 0061_fingerprint_settings.up.sql — fingerprinting's knobs, in admin Settings
|
|
||||||
-- (Scribe #3913, milestone #400). Rule 25: anything an operator might tune is a
|
|
||||||
-- database row, changed without a restart. Singleton in the style of
|
|
||||||
-- reacquisition_settings (0056).
|
|
||||||
CREATE TABLE fingerprint_settings (
|
|
||||||
id boolean PRIMARY KEY DEFAULT true,
|
|
||||||
|
|
||||||
-- Fingerprinting new files, the backfill, and the duplicate sweep. Off stops
|
|
||||||
-- the decode work entirely — the reason to turn it off is a slow NAS, and
|
|
||||||
-- that is the operator's call. On by default: a library that cannot tell its
|
|
||||||
-- duplicates apart is what milestone #400 exists to end.
|
|
||||||
enabled boolean NOT NULL DEFAULT true,
|
|
||||||
|
|
||||||
-- Seconds of audio fpcalc fingerprints. Chromaprints taken at different
|
|
||||||
-- lengths cannot be compared, which is why track_fingerprints records the
|
|
||||||
-- length each row was taken at (below): change this and every chromaprint is
|
|
||||||
-- re-derived, and until then only rows at the new length are compared.
|
|
||||||
chromaprint_length_sec integer NOT NULL DEFAULT 120,
|
|
||||||
|
|
||||||
-- The most disagreement two aligned fingerprints may show and still be
|
|
||||||
-- proposed as one recording. Unrelated audio sits near 0.5, so the ceiling
|
|
||||||
-- stays well clear of it.
|
|
||||||
acoustic_max_bit_error_rate double precision NOT NULL DEFAULT 0.15,
|
|
||||||
|
|
||||||
-- Files the backfill decodes at once. Decoding competes with playback
|
|
||||||
-- transcoding for CPU and with streaming for the mount.
|
|
||||||
backfill_concurrency integer NOT NULL DEFAULT 2,
|
|
||||||
|
|
||||||
-- The least time between duplicate sweeps. A sweep still runs only when
|
|
||||||
-- fingerprints have changed since the last one.
|
|
||||||
sweep_interval_hours integer NOT NULL DEFAULT 1,
|
|
||||||
|
|
||||||
-- When the settings were last saved. A new threshold or length can change
|
|
||||||
-- what a sweep finds, so a save makes a sweep due.
|
|
||||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
|
||||||
|
|
||||||
CONSTRAINT fingerprint_settings_singleton CHECK (id = true),
|
|
||||||
CONSTRAINT fingerprint_settings_length_range
|
|
||||||
CHECK (chromaprint_length_sec >= 30 AND chromaprint_length_sec <= 600),
|
|
||||||
CONSTRAINT fingerprint_settings_threshold_range
|
|
||||||
CHECK (acoustic_max_bit_error_rate >= 0.01 AND acoustic_max_bit_error_rate <= 0.35),
|
|
||||||
CONSTRAINT fingerprint_settings_concurrency_range
|
|
||||||
CHECK (backfill_concurrency >= 1 AND backfill_concurrency <= 8),
|
|
||||||
CONSTRAINT fingerprint_settings_sweep_interval_range
|
|
||||||
CHECK (sweep_interval_hours >= 1 AND sweep_interval_hours <= 168)
|
|
||||||
);
|
|
||||||
INSERT INTO fingerprint_settings (id) VALUES (true) ON CONFLICT (id) DO NOTHING;
|
|
||||||
|
|
||||||
-- Every row written so far was taken at fpcalc's default length.
|
|
||||||
ALTER TABLE track_fingerprints ADD COLUMN chromaprint_length_sec integer NOT NULL DEFAULT 120;
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
ALTER TABLE network_settings DROP COLUMN IF EXISTS public_url;
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
-- The address users reach Minstrel at, e.g. https://music.example.com.
|
|
||||||
--
|
|
||||||
-- Password-reset links used to be built from the request's Host header,
|
|
||||||
-- which the requester controls: a forgot-password call with a forged Host
|
|
||||||
-- would email the victim a real reset token on a link to the attacker's
|
|
||||||
-- server. Links are now built only from this operator-set value, and none
|
|
||||||
-- are sent while it is empty (M462 #4981).
|
|
||||||
ALTER TABLE network_settings ADD COLUMN public_url text NOT NULL DEFAULT '';
|
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
-- The keys cannot be recovered from their hashes. Rolling back gives every
|
|
||||||
-- user a new random key; Subsonic clients using apiKey need the new one.
|
|
||||||
ALTER TABLE users ADD COLUMN api_token text;
|
|
||||||
UPDATE users SET api_token = md5(random()::text || id::text || clock_timestamp()::text);
|
|
||||||
ALTER TABLE users ALTER COLUMN api_token SET NOT NULL;
|
|
||||||
ALTER TABLE users ADD CONSTRAINT users_api_token_key UNIQUE (api_token);
|
|
||||||
ALTER TABLE users DROP COLUMN api_token_hash;
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
-- API keys (the OpenSubsonic apiKey) are stored as their sha256, hex, the
|
|
||||||
-- same way session tokens are. A leaked database row or backup no longer
|
|
||||||
-- hands out working keys. Existing keys are hashed in place, so every
|
|
||||||
-- Subsonic client keeps working; the key itself can no longer be shown
|
|
||||||
-- again, only replaced (M462 #4983).
|
|
||||||
ALTER TABLE users ADD COLUMN api_token_hash text;
|
|
||||||
UPDATE users SET api_token_hash = encode(sha256(convert_to(api_token, 'UTF8')), 'hex');
|
|
||||||
ALTER TABLE users ALTER COLUMN api_token_hash SET NOT NULL;
|
|
||||||
ALTER TABLE users ADD CONSTRAINT users_api_token_hash_key UNIQUE (api_token_hash);
|
|
||||||
ALTER TABLE users DROP COLUMN api_token;
|
|
||||||
@@ -1,156 +0,0 @@
|
|||||||
-- name: StartDuplicateSweep :one
|
|
||||||
INSERT INTO duplicate_sweeps DEFAULT VALUES RETURNING id, started_at;
|
|
||||||
|
|
||||||
-- name: FinishDuplicateSweep :exec
|
|
||||||
UPDATE duplicate_sweeps
|
|
||||||
SET finished_at = now(),
|
|
||||||
candidates = sqlc.arg(candidates),
|
|
||||||
groups_found = sqlc.arg(groups_found),
|
|
||||||
oversize_clusters = sqlc.arg(oversize_clusters),
|
|
||||||
error_message = NULLIF(sqlc.arg(error_message)::text, '')
|
|
||||||
WHERE id = sqlc.arg(id);
|
|
||||||
|
|
||||||
-- name: GetInFlightDuplicateSweep :one
|
|
||||||
-- The guard against two sweeps at once: "in flight" is finished_at IS NULL.
|
|
||||||
SELECT id, started_at
|
|
||||||
FROM duplicate_sweeps
|
|
||||||
WHERE finished_at IS NULL
|
|
||||||
ORDER BY started_at DESC
|
|
||||||
LIMIT 1;
|
|
||||||
|
|
||||||
-- name: GetLatestDuplicateSweep :one
|
|
||||||
SELECT id, started_at, finished_at, candidates, groups_found, oversize_clusters, error_message
|
|
||||||
FROM duplicate_sweeps
|
|
||||||
ORDER BY started_at DESC
|
|
||||||
LIMIT 1;
|
|
||||||
|
|
||||||
-- name: GetLatestFingerprintComputedAt :one
|
|
||||||
-- Whether a sweep has anything new to look at: fingerprints written since the
|
|
||||||
-- last sweep started.
|
|
||||||
SELECT max(computed_at)::timestamptz AS latest FROM track_fingerprints;
|
|
||||||
|
|
||||||
-- name: ListExactDuplicateHashes :many
|
|
||||||
-- The exact tier, library-wide in one pass: identical encoded audio shared by
|
|
||||||
-- more than one present track.
|
|
||||||
SELECT f.audio_stream_sha256,
|
|
||||||
array_agg(t.id ORDER BY t.id)::uuid[] AS track_ids
|
|
||||||
FROM track_fingerprints f
|
|
||||||
JOIN tracks t ON t.id = f.track_id
|
|
||||||
WHERE t.missing_since IS NULL
|
|
||||||
AND f.fingerprint_version >= sqlc.arg(current_version)
|
|
||||||
AND f.audio_stream_sha256 IS NOT NULL
|
|
||||||
GROUP BY f.audio_stream_sha256
|
|
||||||
HAVING count(*) > 1;
|
|
||||||
|
|
||||||
-- name: ListDuplicateCandidates :many
|
|
||||||
-- The acoustic tier's input, one page at a time in (duration_ms, id) order so the
|
|
||||||
-- sweep holds only a sliding window of durations. Tracks without a chromaprint
|
|
||||||
-- cannot be compared acoustically and are left out; any exact duplicates among
|
|
||||||
-- them come from ListExactDuplicateHashes.
|
|
||||||
SELECT t.id, t.duration_ms, f.audio_stream_sha256, f.chromaprint
|
|
||||||
FROM tracks t
|
|
||||||
JOIN track_fingerprints f ON f.track_id = t.id
|
|
||||||
WHERE t.missing_since IS NULL
|
|
||||||
AND f.fingerprint_version >= sqlc.arg(current_version)
|
|
||||||
AND f.chromaprint IS NOT NULL
|
|
||||||
-- Only chromaprints taken at the current length: prints at two lengths are not
|
|
||||||
-- comparable, and after a length change the backfill is still re-deriving the
|
|
||||||
-- rest (#3913).
|
|
||||||
AND f.chromaprint_length_sec = sqlc.arg(chromaprint_length_sec)
|
|
||||||
AND (t.duration_ms, t.id) > (sqlc.arg(after_duration_ms)::integer, sqlc.arg(after_id)::uuid)
|
|
||||||
ORDER BY t.duration_ms, t.id
|
|
||||||
LIMIT sqlc.arg(page_limit);
|
|
||||||
|
|
||||||
-- name: ListDismissedDuplicateMemberSets :many
|
|
||||||
-- What the operator has already said are not duplicates. A new proposal whose
|
|
||||||
-- every member sat together in one of these is not proposed again.
|
|
||||||
SELECT g.id, array_agg(m.track_id ORDER BY m.track_id)::uuid[] AS track_ids
|
|
||||||
FROM duplicate_groups g
|
|
||||||
JOIN duplicate_group_members m ON m.group_id = g.id
|
|
||||||
WHERE g.status = 'dismissed'
|
|
||||||
GROUP BY g.id;
|
|
||||||
|
|
||||||
-- name: UpsertDuplicateGroup :one
|
|
||||||
-- Proposes a group, or refreshes one already pending. A group already dismissed
|
|
||||||
-- or merged is left exactly as it is: the WHERE on the update makes the conflict
|
|
||||||
-- a no-op, and the caller sees no row.
|
|
||||||
INSERT INTO duplicate_groups (member_key, tier, worst_bit_error_rate, last_seen_sweep_id)
|
|
||||||
VALUES (sqlc.arg(member_key), sqlc.arg(tier), sqlc.narg(worst_bit_error_rate), sqlc.arg(sweep_id))
|
|
||||||
ON CONFLICT (member_key) DO UPDATE
|
|
||||||
SET tier = EXCLUDED.tier,
|
|
||||||
worst_bit_error_rate = EXCLUDED.worst_bit_error_rate,
|
|
||||||
last_seen_sweep_id = EXCLUDED.last_seen_sweep_id
|
|
||||||
WHERE duplicate_groups.status = 'pending'
|
|
||||||
RETURNING id;
|
|
||||||
|
|
||||||
-- name: AddDuplicateGroupMember :exec
|
|
||||||
INSERT INTO duplicate_group_members (group_id, track_id)
|
|
||||||
VALUES (sqlc.arg(group_id), sqlc.arg(track_id))
|
|
||||||
ON CONFLICT DO NOTHING;
|
|
||||||
|
|
||||||
-- name: DeleteStalePendingDuplicateGroups :execrows
|
|
||||||
-- A pending proposal this sweep did not find again no longer describes the
|
|
||||||
-- library: a member was re-fingerprinted, merged away or went missing. Dismissed
|
|
||||||
-- groups are kept regardless — they are the memory of a decision.
|
|
||||||
--
|
|
||||||
-- Only proposals last confirmed by an EARLIER sweep go. Should two sweeps ever
|
|
||||||
-- overlap (a manual trigger racing the worker), neither may delete what the other
|
|
||||||
-- has just found.
|
|
||||||
DELETE FROM duplicate_groups g
|
|
||||||
WHERE g.status = 'pending'
|
|
||||||
AND g.last_seen_sweep_id IS DISTINCT FROM sqlc.arg(sweep_id)
|
|
||||||
AND (g.last_seen_sweep_id IS NULL
|
|
||||||
OR (SELECT s.started_at FROM duplicate_sweeps s WHERE s.id = g.last_seen_sweep_id)
|
|
||||||
< (SELECT s.started_at FROM duplicate_sweeps s WHERE s.id = sqlc.arg(sweep_id)));
|
|
||||||
|
|
||||||
-- name: CountPendingDuplicateGroups :one
|
|
||||||
-- Proposals awaiting review. A group left with one member — its other tracks
|
|
||||||
-- deleted since the sweep — is no proposal at all and is not counted; the next
|
|
||||||
-- sweep retires it.
|
|
||||||
SELECT count(*)::bigint
|
|
||||||
FROM duplicate_groups g
|
|
||||||
WHERE g.status = 'pending'
|
|
||||||
AND (SELECT count(*) FROM duplicate_group_members m WHERE m.group_id = g.id) >= 2;
|
|
||||||
|
|
||||||
-- name: ListPendingDuplicateGroupMembers :many
|
|
||||||
-- One page of proposals, newest first, flattened to one row per member so the
|
|
||||||
-- handler folds them without a query per group. What each copy carries — likes
|
|
||||||
-- and plays from every user — is here because it is what the operator weighs
|
|
||||||
-- when deciding which copy to keep.
|
|
||||||
WITH page AS (
|
|
||||||
SELECT g.id, g.tier, g.worst_bit_error_rate, g.detected_at
|
|
||||||
FROM duplicate_groups g
|
|
||||||
WHERE g.status = 'pending'
|
|
||||||
AND (SELECT count(*) FROM duplicate_group_members m WHERE m.group_id = g.id) >= 2
|
|
||||||
ORDER BY g.detected_at DESC, g.id
|
|
||||||
LIMIT sqlc.arg(page_limit) OFFSET sqlc.arg(page_offset)
|
|
||||||
)
|
|
||||||
SELECT p.id AS group_id,
|
|
||||||
p.tier,
|
|
||||||
p.worst_bit_error_rate,
|
|
||||||
p.detected_at,
|
|
||||||
t.id AS track_id,
|
|
||||||
t.title,
|
|
||||||
artists.name AS artist_name,
|
|
||||||
albums.id AS album_id,
|
|
||||||
albums.title AS album_title,
|
|
||||||
t.file_path,
|
|
||||||
t.file_format,
|
|
||||||
t.file_size,
|
|
||||||
t.duration_ms,
|
|
||||||
t.added_at,
|
|
||||||
(SELECT count(*) FROM general_likes l WHERE l.track_id = t.id)::bigint AS like_count,
|
|
||||||
(SELECT count(*) FROM play_events e WHERE e.track_id = t.id)::bigint AS play_count
|
|
||||||
FROM page p
|
|
||||||
JOIN duplicate_group_members m ON m.group_id = p.id
|
|
||||||
JOIN tracks t ON t.id = m.track_id
|
|
||||||
JOIN albums ON albums.id = t.album_id
|
|
||||||
JOIN artists ON artists.id = t.artist_id
|
|
||||||
ORDER BY p.detected_at DESC, p.id, t.id;
|
|
||||||
|
|
||||||
-- name: DismissDuplicateGroup :execrows
|
|
||||||
-- "These are not duplicates." Only a pending group can be dismissed; zero rows
|
|
||||||
-- means it was already resolved or no longer exists.
|
|
||||||
UPDATE duplicate_groups
|
|
||||||
SET status = 'dismissed', resolved_at = now()
|
|
||||||
WHERE id = sqlc.arg(id) AND status = 'pending';
|
|
||||||
@@ -1,15 +0,0 @@
|
|||||||
-- name: GetFingerprintSettings :one
|
|
||||||
SELECT * FROM fingerprint_settings WHERE id = true;
|
|
||||||
|
|
||||||
-- name: UpdateFingerprintSettings :one
|
|
||||||
-- Whole-row write from the admin card; migration 0061's CHECKs are the backstop
|
|
||||||
-- behind the service's own validation.
|
|
||||||
UPDATE fingerprint_settings
|
|
||||||
SET enabled = sqlc.arg(enabled),
|
|
||||||
chromaprint_length_sec = sqlc.arg(chromaprint_length_sec),
|
|
||||||
acoustic_max_bit_error_rate = sqlc.arg(acoustic_max_bit_error_rate),
|
|
||||||
backfill_concurrency = sqlc.arg(backfill_concurrency),
|
|
||||||
sweep_interval_hours = sqlc.arg(sweep_interval_hours),
|
|
||||||
updated_at = now()
|
|
||||||
WHERE id = true
|
|
||||||
RETURNING *;
|
|
||||||
@@ -1,70 +0,0 @@
|
|||||||
-- name: UpsertTrackFingerprint :exec
|
|
||||||
-- Written whenever a track's fingerprint is derived: by the scan when a file is
|
|
||||||
-- new or its bytes changed, and by the backfill (#3908) for rows derived by an
|
|
||||||
-- older method. Replaces the row wholesale — a fingerprint of the old bytes has
|
|
||||||
-- no standing once the file has changed.
|
|
||||||
INSERT INTO track_fingerprints (
|
|
||||||
track_id, audio_stream_sha256, chromaprint, fingerprint_version, chromaprint_length_sec
|
|
||||||
) VALUES (
|
|
||||||
sqlc.arg(track_id), sqlc.narg(audio_stream_sha256), sqlc.narg(chromaprint),
|
|
||||||
sqlc.arg(fingerprint_version), sqlc.arg(chromaprint_length_sec)
|
|
||||||
)
|
|
||||||
ON CONFLICT (track_id) DO UPDATE SET
|
|
||||||
audio_stream_sha256 = EXCLUDED.audio_stream_sha256,
|
|
||||||
chromaprint = EXCLUDED.chromaprint,
|
|
||||||
fingerprint_version = EXCLUDED.fingerprint_version,
|
|
||||||
chromaprint_length_sec = EXCLUDED.chromaprint_length_sec,
|
|
||||||
computed_at = now();
|
|
||||||
|
|
||||||
-- name: DeleteTrackFingerprint :exec
|
|
||||||
-- A file changed but could not be fingerprinted, for a reason unrelated to the
|
|
||||||
-- file. The stored row describes the OLD bytes, so it goes and the backfill
|
|
||||||
-- re-derives it — nothing may keep trusting a stale identity.
|
|
||||||
DELETE FROM track_fingerprints WHERE track_id = $1;
|
|
||||||
|
|
||||||
-- name: ListTracksNeedingFingerprint :many
|
|
||||||
-- The backfill's work queue (#3908): tracks with no fingerprint, or one derived
|
|
||||||
-- by an older method. Keyset-paged on id so a pass visits each track at most
|
|
||||||
-- once. That cursor is load-bearing: an inconclusive attempt writes no row, so
|
|
||||||
-- without it a file that keeps timing out would be listed again straight away
|
|
||||||
-- and retried in a tight loop. Missing tracks are skipped — there is no file to
|
|
||||||
-- read.
|
|
||||||
SELECT t.id, t.file_path
|
|
||||||
FROM tracks t
|
|
||||||
LEFT JOIN track_fingerprints f ON f.track_id = t.id
|
|
||||||
WHERE t.missing_since IS NULL
|
|
||||||
-- A row taken at another length is as stale as one from an older method:
|
|
||||||
-- chromaprints at two lengths cannot be compared (#3913).
|
|
||||||
AND (f.track_id IS NULL
|
|
||||||
OR f.fingerprint_version < sqlc.arg(current_version)
|
|
||||||
OR f.chromaprint_length_sec <> sqlc.arg(chromaprint_length_sec))
|
|
||||||
AND t.id > sqlc.arg(after_id)
|
|
||||||
ORDER BY t.id
|
|
||||||
LIMIT sqlc.arg(batch_limit);
|
|
||||||
|
|
||||||
-- name: GetFingerprintCoverage :one
|
|
||||||
-- The admin gauge for the backfill. fingerprinted + rejected + pending = total.
|
|
||||||
-- "Current" means derived by the current method AT the current length: a row at
|
|
||||||
-- another length is pending, because the backfill will re-derive it. rejected is
|
|
||||||
-- a current row with a NULL half: a tool ran and refused the file, which is
|
|
||||||
-- settled rather than waiting. Missing tracks are excluded, or the gauge could
|
|
||||||
-- never reach the end.
|
|
||||||
SELECT count(*)::bigint AS total,
|
|
||||||
count(*) FILTER (
|
|
||||||
WHERE f.fingerprint_version >= sqlc.arg(current_version)
|
|
||||||
AND f.chromaprint_length_sec = sqlc.arg(chromaprint_length_sec)
|
|
||||||
AND f.audio_stream_sha256 IS NOT NULL AND f.chromaprint IS NOT NULL
|
|
||||||
)::bigint AS fingerprinted,
|
|
||||||
count(*) FILTER (
|
|
||||||
WHERE f.fingerprint_version >= sqlc.arg(current_version)
|
|
||||||
AND f.chromaprint_length_sec = sqlc.arg(chromaprint_length_sec)
|
|
||||||
AND (f.audio_stream_sha256 IS NULL OR f.chromaprint IS NULL)
|
|
||||||
)::bigint AS rejected,
|
|
||||||
count(*) FILTER (
|
|
||||||
WHERE f.track_id IS NULL
|
|
||||||
OR f.fingerprint_version < sqlc.arg(current_version)
|
|
||||||
OR f.chromaprint_length_sec <> sqlc.arg(chromaprint_length_sec)
|
|
||||||
)::bigint AS pending
|
|
||||||
FROM tracks t
|
|
||||||
LEFT JOIN track_fingerprints f ON f.track_id = t.id
|
|
||||||
WHERE t.missing_since IS NULL;
|
|
||||||
@@ -68,10 +68,3 @@ UPDATE system_playlist_runs
|
|||||||
DELETE FROM password_resets
|
DELETE FROM password_resets
|
||||||
WHERE (used_at IS NOT NULL AND used_at < now() - INTERVAL '7 days')
|
WHERE (used_at IS NOT NULL AND used_at < now() - INTERVAL '7 days')
|
||||||
OR (used_at IS NULL AND expires_at < now() - INTERVAL '1 hour');
|
OR (used_at IS NULL AND expires_at < now() - INTERVAL '1 hour');
|
||||||
|
|
||||||
-- name: GcDeleteExpiredSessions :execrows
|
|
||||||
-- Sessions past their idle (30 days) or absolute (1 year) limit. They already
|
|
||||||
-- fail auth through GetSessionByTokenHash's filter; this only clears the rows.
|
|
||||||
DELETE FROM sessions
|
|
||||||
WHERE last_seen_at <= now() - interval '30 days'
|
|
||||||
OR created_at <= now() - interval '365 days';
|
|
||||||
|
|||||||
@@ -1,101 +0,0 @@
|
|||||||
-- Duplicate merge (Scribe #3911). Every statement here runs inside the one
|
|
||||||
-- transaction library.MergeDuplicateGroup opens, after the removed copy's file
|
|
||||||
-- is already gone. The loser's own track row is deleted last with DeleteTrack;
|
|
||||||
-- what these do is move everything it carries onto the survivor first, so that
|
|
||||||
-- delete's CASCADE finds nothing left to destroy.
|
|
||||||
|
|
||||||
-- name: LockDuplicateGroupForMerge :one
|
|
||||||
-- Locks the group for the rest of the transaction, so two merges of one group
|
|
||||||
-- cannot run at once.
|
|
||||||
SELECT id, tier, status
|
|
||||||
FROM duplicate_groups
|
|
||||||
WHERE id = sqlc.arg(id)
|
|
||||||
FOR UPDATE;
|
|
||||||
|
|
||||||
-- name: ListDuplicateGroupMergeMembers :many
|
|
||||||
SELECT t.id, t.file_path, t.file_format, t.file_size, t.added_at, t.album_id,
|
|
||||||
t.mbid, albums.mbid AS album_mbid
|
|
||||||
FROM duplicate_group_members m
|
|
||||||
JOIN tracks t ON t.id = m.track_id
|
|
||||||
JOIN albums ON albums.id = t.album_id
|
|
||||||
WHERE m.group_id = sqlc.arg(group_id)
|
|
||||||
ORDER BY t.id;
|
|
||||||
|
|
||||||
-- Plain repoints: no unique key involves track_id, so moving rows cannot collide.
|
|
||||||
|
|
||||||
-- name: MergeRepointPlayEvents :execrows
|
|
||||||
UPDATE play_events SET track_id = sqlc.arg(survivor_id)::uuid WHERE track_id = sqlc.arg(loser_id)::uuid;
|
|
||||||
|
|
||||||
-- name: MergeRepointSkipEvents :execrows
|
|
||||||
UPDATE skip_events SET track_id = sqlc.arg(survivor_id)::uuid WHERE track_id = sqlc.arg(loser_id)::uuid;
|
|
||||||
|
|
||||||
-- name: MergeRepointContextualLikes :execrows
|
|
||||||
UPDATE contextual_likes SET track_id = sqlc.arg(survivor_id)::uuid WHERE track_id = sqlc.arg(loser_id)::uuid;
|
|
||||||
|
|
||||||
-- name: MergeRepointPlaybackErrors :execrows
|
|
||||||
UPDATE playback_errors SET track_id = sqlc.arg(survivor_id)::uuid WHERE track_id = sqlc.arg(loser_id)::uuid;
|
|
||||||
|
|
||||||
-- name: MergeRepointLidarrRequests :execrows
|
|
||||||
UPDATE lidarr_requests SET matched_track_id = sqlc.arg(survivor_id)::uuid
|
|
||||||
WHERE matched_track_id = sqlc.arg(loser_id)::uuid;
|
|
||||||
|
|
||||||
-- name: MergeRepointPlaylistTracks :many
|
|
||||||
-- playlist_tracks is keyed by (playlist_id, position), so repointing keeps every
|
|
||||||
-- entry exactly where it was. A playlist that held both copies simply holds the
|
|
||||||
-- survivor twice — the user put two entries there, and both stay.
|
|
||||||
UPDATE playlist_tracks SET track_id = sqlc.arg(survivor_id)::uuid
|
|
||||||
WHERE track_id = sqlc.arg(loser_id)::uuid
|
|
||||||
RETURNING playlist_id;
|
|
||||||
|
|
||||||
-- Collision-safe merges: a unique key includes track_id, so the survivor may
|
|
||||||
-- already hold a matching row. Copy what it lacks; DeleteTrack's CASCADE then
|
|
||||||
-- removes the loser's originals.
|
|
||||||
|
|
||||||
-- name: MergeCopyGeneralLikes :many
|
|
||||||
-- One like per user. A user who liked both copies keeps a single like, dated to
|
|
||||||
-- the earlier of the two.
|
|
||||||
INSERT INTO general_likes (user_id, track_id, liked_at)
|
|
||||||
SELECT user_id, sqlc.arg(survivor_id)::uuid, liked_at
|
|
||||||
FROM general_likes
|
|
||||||
WHERE track_id = sqlc.arg(loser_id)::uuid
|
|
||||||
ON CONFLICT (user_id, track_id) DO UPDATE
|
|
||||||
SET liked_at = LEAST(general_likes.liked_at, EXCLUDED.liked_at)
|
|
||||||
RETURNING user_id;
|
|
||||||
|
|
||||||
-- name: MergeCopyTrackTags :execrows
|
|
||||||
INSERT INTO track_tags (track_id, tag, weight)
|
|
||||||
SELECT sqlc.arg(survivor_id)::uuid, tag, weight
|
|
||||||
FROM track_tags
|
|
||||||
WHERE track_id = sqlc.arg(loser_id)::uuid
|
|
||||||
ON CONFLICT (track_id, tag) DO NOTHING;
|
|
||||||
|
|
||||||
-- name: MergeCopyTrackSimilarity :execrows
|
|
||||||
-- Rewrites the loser to the survivor on either side of an edge. An edge between
|
|
||||||
-- the two copies would become a track similar to itself — the table forbids
|
|
||||||
-- that, and it means nothing — so it is dropped. An edge the survivor already
|
|
||||||
-- has from the same source is kept as it is.
|
|
||||||
INSERT INTO track_similarity (track_a_id, track_b_id, score, source, fetched_at)
|
|
||||||
SELECT CASE WHEN track_a_id = sqlc.arg(loser_id)::uuid THEN sqlc.arg(survivor_id)::uuid ELSE track_a_id END,
|
|
||||||
CASE WHEN track_b_id = sqlc.arg(loser_id)::uuid THEN sqlc.arg(survivor_id)::uuid ELSE track_b_id END,
|
|
||||||
score, source, fetched_at
|
|
||||||
FROM track_similarity
|
|
||||||
WHERE (track_a_id = sqlc.arg(loser_id)::uuid OR track_b_id = sqlc.arg(loser_id)::uuid)
|
|
||||||
AND (CASE WHEN track_a_id = sqlc.arg(loser_id)::uuid THEN sqlc.arg(survivor_id)::uuid ELSE track_a_id END)
|
|
||||||
<> (CASE WHEN track_b_id = sqlc.arg(loser_id)::uuid THEN sqlc.arg(survivor_id)::uuid ELSE track_b_id END)
|
|
||||||
ON CONFLICT (track_a_id, track_b_id, source) DO NOTHING;
|
|
||||||
|
|
||||||
-- name: MergeInheritTrackMbid :exec
|
|
||||||
-- A recording MBID is what the similarity pipeline keys on. If only the removed
|
|
||||||
-- copy carried one, the survivor takes it rather than going dark to similarity.
|
|
||||||
UPDATE tracks AS survivor
|
|
||||||
SET mbid = loser.mbid
|
|
||||||
FROM tracks AS loser
|
|
||||||
WHERE survivor.id = sqlc.arg(survivor_id)::uuid
|
|
||||||
AND loser.id = sqlc.arg(loser_id)::uuid
|
|
||||||
AND survivor.mbid IS NULL
|
|
||||||
AND loser.mbid IS NOT NULL;
|
|
||||||
|
|
||||||
-- name: MarkDuplicateGroupMerged :execrows
|
|
||||||
UPDATE duplicate_groups
|
|
||||||
SET status = 'merged', resolved_at = now()
|
|
||||||
WHERE id = sqlc.arg(id) AND status = 'pending';
|
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user