diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e23f695..dffe178 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -32,8 +32,6 @@ jobs: - uses: actions/checkout@v4 with: persist-credentials: false - - name: Check local preview reset safeguards - run: python3 -B -m unittest discover -s tests -p 'test_local_preview.py' - uses: actions/setup-node@v4 with: node-version: 24 diff --git a/README.md b/README.md index f083d2f..cfe1b21 100644 --- a/README.md +++ b/README.md @@ -35,7 +35,6 @@ Data persists in `data/postgres` and `data/audio` across container rebuilds. Bac ## Documentation -- [Local preview and resetting test data](docs/local-preview.md): the Mac’s isolated production-based test environment. - [Development and testing](docs/testing.md): local setup, isolated tests, and device checks. - [Product and technical specification](docs/wavecase-specification.md): behavior, access rules, audio policies, and repository structure. - [Implementation status](docs/implementation-status.md): supported scope and remaining acceptance work. diff --git a/docs/local-preview.md b/docs/local-preview.md deleted file mode 100644 index 227a4ff..0000000 --- a/docs/local-preview.md +++ /dev/null @@ -1,62 +0,0 @@ -# Local production-based test data - -The Mac's `wavecase-ui-preview` Compose project serves the working tree at -http://localhost:3000, bound to loopback. It uses its own named database and audio -volumes, independent of production and staging. Its saved Compose configuration -and environment are in `data/local-preview/` (gitignored). - -The stable baseline is in `data/local-preview/baseline/`: a PostgreSQL dump, -`audio.tar`, and a manifest with capture time and SHA-256 checksums. It contains -production tracks, versions, artist profiles, releases, and media. The captured -owner identity is replaced with a placeholder. Production passkeys, sessions, -registration/recovery tokens, private share links, comments, reupload requests, -and listener/download analytics are excluded. Job queues are not copied. -The files still contain real music and metadata; keep this directory local. - -## Reset the preview - -From the repository root, with Docker running and the preview database started: - -```sh -python3 scripts/local-test-data.py reset -``` - -Reset requires exactly one existing local account. It stops only the preview web -and worker, saves the current database and media under a timestamped -`data/local-preview/before-reset-*` directory, and replaces preview content with -the baseline. The existing local account, passkey and sessions are preserved; -copied content belongs to that account. The web runs pending application -migrations before the worker restarts. Refresh the browser after completion. -Each reset keeps a backup, including media; old backups can be removed manually -when no longer needed. If restoration fails, the preview stays stopped and the -backup path is reported. Never apply these dumps to production. - -Start or rebuild the preview after a reboot or code change: - -```sh -docker compose -p wavecase-ui-preview --project-directory data/local-preview up --build -d -``` - -Stop it without removing test data: - -```sh -docker compose -p wavecase-ui-preview --project-directory data/local-preview down -``` - -## Capture a new baseline - -The current baseline remains unchanged by resets. To deliberately refresh it, -archive/rename the existing `baseline` directory, then run: - -```sh -python3 scripts/local-test-data.py capture -``` - -Capture reads only from `wavecase-prod-db-1` and `wavecase-prod-web-1`. It does not -stop production. It requires one production account and no pending audio jobs, -checks for content changes during capture, and verifies referenced media exist. -If production content changes, retry after activity finishes. Sanitization uses a -temporary `wavecase_seed` database inside the preview database container, never -production. Partial captures are kept under `capture-*` for inspection; they are -not usable baselines. The tool intentionally supports this Mac's named containers -and one-owner preview, rather than arbitrary environments or multiple accounts. diff --git a/docs/operations.md b/docs/operations.md index e3334d8..f1bf98e 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -71,3 +71,12 @@ The supplied Compose file uses `build: .`; it does not select published images. | Explicit migration job | `["npm", "run", "db:migrate"]` | If run separately, start web with `["npm", "start"]`. | The image includes FFmpeg and ffprobe; PostgreSQL runs separately. Publishing images never triggers a deployment. + + +## Local test data + +Use the repository's Compose setup for an independent local database and media +store. Installation-specific tools that export production content, sanitize it +or reset a configured preview belong to the operator's infrastructure tooling. +They are not prerequisites for running or developing this application. Keep any +real content and exports out of Git; `data/` remains ignored. diff --git a/docs/testing.md b/docs/testing.md index 59b827c..0c4be38 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -54,7 +54,6 @@ docker compose run --rm --no-deps web sh -ec 'export DATABASE_URL="${DATABASE_UR Create the database only once. Building the image also checks the production build. The URL substitution assumes the supplied Compose database name, `wavecase`. Use a separate checkout and Compose project from a running installation; set `COMPOSE_PROJECT_NAME=wavecase-check` for these commands if checkout names collide. [CI](../.github/workflows/ci.yml) uses its own PostgreSQL service and runs the complete suite. It also checks formatting and fails when `app/server/schema.ts` has changes without a generated migration or when `THIRD_PARTY_NOTICES.md` is out of date. -CI also runs `python3 -B -m unittest discover -s tests -p 'test_local_preview.py'`, which covers the reset safeguards in `scripts/local-test-data.py` ([local preview](local-preview.md)). Run it after changing that script. | Coverage | Tests | | --- | --- | diff --git a/scripts/local-test-data.py b/scripts/local-test-data.py deleted file mode 100644 index a446342..0000000 --- a/scripts/local-test-data.py +++ /dev/null @@ -1,167 +0,0 @@ -#!/usr/bin/env python3 -"""Capture production content read-only, or reset the isolated local UI preview.""" -import argparse -from datetime import datetime, timezone -import hashlib -import json -import os -from pathlib import Path -import subprocess -import tarfile -import time -import uuid - -ROOT = Path(__file__).resolve().parents[1] -DATA = ROOT / 'data' / 'local-preview' -BASE = DATA / 'baseline' -DB = 'wavecase-ui-preview-db-1' -WEB = 'wavecase-ui-preview-web-1' -WORKER = 'wavecase-ui-preview-worker-1' -PROD = 'wavecase-prod-db-1' -CONTENT = ['tracks', 'versions', 'artists', 'releases', 'release_tracks'] -EXCLUDE = ['sessions', 'passkeys', 'challenges', 'invitations', 'recoveries', - 'links', 'comments', 'events', 'reupload_requests', 'release_events'] - - -def checksum(handle): - digest = hashlib.sha256() - for block in iter(lambda: handle.read(1024 * 1024), b''): - digest.update(block) - return digest.hexdigest() - - -def run(*args, **kwargs): - return subprocess.run(args, check=True, **kwargs) - - -def sql(container, database, query): - return run('docker', 'exec', '-i', container, 'psql', '-X', '-U', 'wavecase', - '-d', database, '-v', 'ON_ERROR_STOP=1', '-At', input=query.encode(), - stdout=subprocess.PIPE).stdout.decode().strip() - - -def dump(container, database, *extra): - return run('docker', 'exec', container, 'pg_dump', '-U', 'wavecase', - '--no-owner', '--no-privileges', *extra, database, - stdout=subprocess.PIPE).stdout - - -def restore(database, contents): - run('docker', 'exec', '-i', DB, 'pg_restore', '-U', 'wavecase', '-d', database, - '--no-owner', '--no-privileges', '--exit-on-error', input=contents) - - -def fingerprint(): - return sql(PROD, 'wavecase', '\n'.join( - f'SELECT md5(coalesce(json_agg(t ORDER BY id)::text, \'[]\')) FROM {table} t;' - for table in CONTENT)) - - -def capture(): - if BASE.exists(): - raise SystemExit('Baseline already exists; keep it stable. Archive/rename it before capturing a new one.') - pending = sql(PROD, 'wavecase', 'SELECT (SELECT count(*) FROM versions WHERE "pendingOriginal" IS NOT NULL) + (SELECT count(*) FROM release_tracks WHERE "pendingOriginal" IS NOT NULL);') - if pending != '0': - raise SystemExit('Production is processing audio. Retry after uploads finish.') - if sql(PROD, 'wavecase', 'SELECT count(*) FROM users;') != '1': - raise SystemExit('This local preview seed supports one owner; review ownership before copying multiple accounts.') - work = DATA / ('capture-' + datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ')) - work.mkdir(mode=0o700) - before = fingerprint() - raw = dump(PROD, 'wavecase', '-Fc', '-n', 'public', '-n', 'drizzle', - *[f'--exclude-table-data=public.{table}' for table in EXCLUDE]) - sql(DB, 'postgres', 'CREATE DATABASE wavecase_seed;') - try: - sql(DB, 'wavecase_seed', 'DROP SCHEMA public;') - restore('wavecase_seed', raw) - sql(DB, 'wavecase_seed', "UPDATE users SET name='Preview owner', email='preview@example.test', admin=true, disabled=false; UPDATE settings SET \"openRegistration\"=false;") - (work / 'database.dump').write_bytes(dump(DB, 'wavecase_seed', '-Fc', '-n', 'public', '-n', 'drizzle')) - with (work / 'audio.tar').open('wb') as out: - run('docker', 'exec', 'wavecase-prod-web-1', 'tar', '-cf', '-', '-C', '/data/audio', '.', stdout=out) - if fingerprint() != before: - raise SystemExit(f'Production content changed during capture. Partial copy kept at {work}; retry capture.') - references = sql(DB, 'wavecase_seed', ' UNION '.join([ - 'SELECT cover AS path FROM tracks', 'SELECT original FROM versions', - 'SELECT playback FROM versions', 'SELECT image FROM artists', - 'SELECT cover FROM releases', 'SELECT original FROM release_tracks', - 'SELECT playback FROM release_tracks']) + ';').splitlines() - with tarfile.open(work / 'audio.tar') as archive: - names = {m.name.removeprefix('./') for m in archive if m.isfile()} - if any(path and path not in names for path in references): - raise SystemExit('Snapshot is missing referenced media; do not use this copy.') - manifest = {'captured_utc': datetime.now(timezone.utc).isoformat(), - 'excluded_table_data': EXCLUDE, 'source': 'wavecase-prod', - 'content_fingerprint': before, 'files': {}} - for name in ['database.dump', 'audio.tar']: - with (work / name).open('rb') as handle: - manifest['files'][name] = checksum(handle) - (work / 'manifest.json').write_text(json.dumps(manifest, indent=2) + '\n') - work.rename(BASE) - print(f'Baseline saved: {BASE}') - finally: - sql(DB, 'postgres', 'DROP DATABASE wavecase_seed WITH (FORCE);') - - -def reset(): - manifest = json.loads((BASE / 'manifest.json').read_text()) - for name in ['database.dump', 'audio.tar']: - expected = manifest['files'][name] - with (BASE / name).open('rb') as handle: - if checksum(handle) != expected: - raise SystemExit('Baseline checksum mismatch; refusing reset.') - user = sql(DB, 'wavecase', 'SELECT id FROM users;') - try: - uuid.UUID(user) - except ValueError: - raise SystemExit('Reset requires exactly one existing local account.') from None - run('docker', 'stop', WEB, WORKER, stdout=subprocess.DEVNULL) - backup = DATA / ('before-reset-' + datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ')) - backup.mkdir(mode=0o700) - backup_complete = False - try: - (backup / 'database.dump').write_bytes(dump(DB, 'wavecase', '-Fc')) - auth = dump(DB, 'wavecase', '--data-only', '-t', 'users', '-t', 'passkeys', '-t', 'sessions') - with (backup / 'audio.tar').open('wb') as out: - run('docker', 'run', '--rm', '--network', 'none', '-v', - 'wavecase-ui-preview_preview-audio:/data/audio:ro', '--entrypoint', 'tar', - 'wavecase-ui-preview-web', '-cf', '-', '-C', '/data/audio', '.', stdout=out) - backup_complete = True - sql(DB, 'wavecase', 'SET client_min_messages=warning; DROP SCHEMA public CASCADE; DROP SCHEMA IF EXISTS drizzle CASCADE; DROP SCHEMA IF EXISTS pgboss CASCADE;') - restore('wavecase', (BASE / 'database.dump').read_bytes()) - run('docker', 'exec', '-i', DB, 'psql', '-X', '-U', 'wavecase', '-d', 'wavecase', - '-v', 'ON_ERROR_STOP=1', input=auth, stdout=subprocess.DEVNULL) - sql(DB, 'wavecase', f'''BEGIN; -UPDATE tracks SET "ownerId"='{user}'; -UPDATE artists SET "ownerId"='{user}'; -DELETE FROM users WHERE id <> '{user}'; -COMMIT;''') - with (BASE / 'audio.tar').open('rb') as inp: - run('docker', 'run', '--rm', '-i', '--network', 'none', '-v', - 'wavecase-ui-preview_preview-audio:/data/audio', '--entrypoint', 'sh', - 'wavecase-ui-preview-web', '-c', - 'find /data/audio -mindepth 1 -delete && tar -xf - -C /data/audio', stdin=inp) - except BaseException: - if backup_complete: - print(f'Reset failed. Preview stays stopped; previous complete data is saved at {backup}.') - else: - print(f'Backup failed before replacement. Existing preview data is unchanged; services stay stopped. Partial backup: {backup}') - raise - run('docker', 'start', WEB, stdout=subprocess.DEVNULL) - for _ in range(45): - status = run('docker', 'inspect', '--format', '{{.State.Health.Status}}', WEB, stdout=subprocess.PIPE).stdout.strip() - if status == b'healthy': - break - time.sleep(1) - else: - raise SystemExit(f'Web did not become healthy. Worker stays stopped; backup: {backup}') - run('docker', 'start', WORKER, stdout=subprocess.DEVNULL) - print(f'Preview reset. Local account preserved. Previous state: {backup}') - - -if __name__ == '__main__': - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument('action', choices=['capture', 'reset']) - args = parser.parse_args() - os.umask(0o077) - DATA.mkdir(parents=True, exist_ok=True, mode=0o700) - {'capture': capture, 'reset': reset}[args.action]() diff --git a/tests/test_local_preview.py b/tests/test_local_preview.py deleted file mode 100644 index 0df71da..0000000 --- a/tests/test_local_preview.py +++ /dev/null @@ -1,68 +0,0 @@ -"""Exercise reset failure boundaries without Docker or installation data.""" -import contextlib -import importlib.util -import io -import json -from pathlib import Path -import subprocess -import tempfile -import unittest -from unittest.mock import patch - -spec = importlib.util.spec_from_file_location( - 'preview', Path(__file__).resolve().parents[1] / 'scripts/local-test-data.py') -preview = importlib.util.module_from_spec(spec) -spec.loader.exec_module(preview) - - -class ResetSafety(unittest.TestCase): - def setUp(self): - self.temp = tempfile.TemporaryDirectory() - self.addCleanup(self.temp.cleanup) - self.data = Path(self.temp.name) - self.base = self.data / 'baseline' - self.base.mkdir() - manifest = {'files': {}} - for name in ['database.dump', 'audio.tar']: - (self.base / name).write_bytes(b'test-only fixture') - with (self.base / name).open('rb') as handle: - manifest['files'][name] = preview.checksum(handle) - (self.base / 'manifest.json').write_text(json.dumps(manifest)) - for name, value in [('DATA', self.data), ('BASE', self.base)]: - mock = patch.object(preview, name, value) - mock.start() - self.addCleanup(mock.stop) - - def test_corrupt_baseline_never_contacts_docker(self): - (self.base / 'audio.tar').write_bytes(b'corrupted') - with patch.object(preview, 'run') as run: - with self.assertRaisesRegex(SystemExit, 'checksum mismatch'): - preview.reset() - run.assert_not_called() - - def test_missing_checksum_never_contacts_docker(self): - (self.base / 'manifest.json').write_text('{"files": {}}') - with patch.object(preview, 'run') as run: - with self.assertRaises(KeyError): - preview.reset() - run.assert_not_called() - - def test_multiple_owners_never_stop_or_modify_preview(self): - with patch.object(preview, 'sql', return_value='owner1\nowner2'), patch.object(preview, 'run') as run: - with self.assertRaisesRegex(SystemExit, 'exactly one'): - preview.reset() - run.assert_not_called() - - def test_failed_backup_does_not_replace_data_or_claim_complete_backup(self): - output = io.StringIO() - with patch.object(preview, 'sql', return_value='00000000-0000-4000-8000-000000000001') as sql, patch.object(preview, 'run') as run, patch.object(preview, 'dump', side_effect=subprocess.CalledProcessError(1, 'pg_dump')), contextlib.redirect_stdout(output): - with self.assertRaises(subprocess.CalledProcessError): - preview.reset() - self.assertEqual(sql.call_count, 1) # Owner check only; no DROP/restore. - run.assert_called_once_with('docker', 'stop', preview.WEB, preview.WORKER, stdout=subprocess.DEVNULL) - self.assertIn('Existing preview data is unchanged', output.getvalue()) - self.assertNotIn('previous complete data', output.getvalue()) - - -if __name__ == '__main__': - unittest.main()