Compare commits

...
Author SHA1 Message Date
Andrew BeveridgeandClaude Opus 4.5 8e5e81d6b8 docs: Add gen_users migration documentation
- README.md: Add entry in Recent Changes about user database separation
- ARCHITECTURE.md: Add Firestore Collections section documenting gen_users
- LESSONS-LEARNED.md: Add lesson about separate collections for multi-app projects

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-03 16:59:24 -05:00
Andrew Beveridge 73faacaebe Merge branch 'main' of github.com:nomadkaraoke/karaoke-gen 2026-01-03 16:59:11 -05:00
Andrew BeveridgeandClaude Opus 4.5 499c386ad7 fix: Remove double slashes in GCS upload paths
The prefix already ends with "/" from the gcs_uri, adding another "/"
creates paths like "encoded//file.mp4" instead of "encoded/file.mp4"

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-03 16:49:33 -05:00
Andrew Beveridge ☄️andClaude Opus 4.5 ab05ec8bee feat: Migrate user storage to gen_users collection (#173)
## Summary
Separates karaoke-gen user data from karaoke-decide by using a dedicated
`gen_users` collection instead of the shared `users` collection.

**Problem:** Both karaoke-gen and karaoke-decide were using the same
`users` collection in Firestore with incompatible schemas:
- karaoke-gen: email as doc ID, has `credits`, `role`, `is_active`
- karaoke-decide: hash as doc ID, has `user_id`, `is_guest`, `quiz_*`
fields

**Solution:** karaoke-gen now uses its own `gen_users` collection.

## Changes
- Updated `USERS_COLLECTION` constant from `"users"` to `"gen_users"`
- Updated all hardcoded `db.collection("users")` references to use the
constant
- Updated Pulumi Firestore indexes for `gen_users` collection
- Added migration script (already executed)

## Migration Status
✅ 42 karaoke-gen users migrated to `gen_users` collection
✅ 36 karaoke-decide users remain in `users` collection (untouched)
✅ Firestore indexes created for `gen_users`

## Test plan
- [ ] Admin dashboard loads user list from `gen_users`
- [ ] User login/signup works
- [ ] Credit operations work

@coderabbitai ignore

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-03 21:43:47 +00:00
Andrew Beveridge 3f5a423f98 Merge branch 'main' of github.com:nomadkaraoke/karaoke-gen 2026-01-03 16:26:55 -05:00
Andrew Beveridge ☄️andClaude Opus 4.5 69dd904f60 fix: Handle string dates in admin user detail endpoint (#172)
## Summary
Some jobs have created_at stored as string instead of datetime, causing
500 errors in admin user detail.

## Changes
Check for isoformat method before calling it.

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-03 21:21:20 +00:00
Andrew BeveridgeandClaude Opus 4.5 b87e29d622 Fix GCE encoding worker output paths and format handling
- Convert local file paths to blob paths after upload (backend expects
  paths like "jobs/id/encoded/file.mp4", not full gs:// URIs)
- Add mp4_4k_lossless and mp4_4k_lossy format handlers to match what
  video worker sends

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-03 16:07:31 -05:00
Andrew Beveridge ☄️andClaude Opus 4.5 06bba48199 fix: Admin dashboard improvements (#171)
## Summary
- Fix user detail page navigation (404 when clicking on user in admin
panel)
- Add admin token support to `/api/users/me` endpoint (allows
token-based login)
- Add Firestore composite indexes for admin user queries (fixes 500
errors)

## Changes
1. **Frontend**: Fixed navigation from `/admin/users/{email}` to
`/admin/users/detail?email={email}`
2. **Backend**: Updated `/me` endpoint to accept admin tokens in
addition to session tokens
3. **Infrastructure**: Added 4 Firestore indexes for `users` collection
(already deployed via Pulumi)

## Test plan
- [ ] Navigate to `/admin/users` and click on a user - should load
detail page
- [ ] Use admin token in "use access token instead" login - should
authenticate as admin

@coderabbitai ignore

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-03 20:39:33 +00:00
9 changed files with 320 additions and 15 deletions

No files matched your search

+2 -2
View File
@@ -15,7 +15,7 @@ from pydantic import BaseModel
from backend.api.dependencies import require_admin
from backend.services.auth_service import UserType
from backend.services.user_service import get_user_service, UserService
from backend.services.user_service import get_user_service, UserService, USERS_COLLECTION
from backend.services.job_manager import JobManager
from backend.models.job import JobStatus
@@ -90,7 +90,7 @@ async def get_admin_stats_overview(
return 0
# User statistics
users_collection = db.collection("users")
users_collection = db.collection(USERS_COLLECTION)
total_users = get_count(users_collection)
+31 -6
View File
@@ -29,7 +29,7 @@ from backend.models.user import (
BetaFeedbackResponse,
BetaTesterFeedback,
)
from backend.services.user_service import get_user_service, UserService
from backend.services.user_service import get_user_service, UserService, USERS_COLLECTION
from backend.services.email_service import get_email_service, EmailService
from backend.services.stripe_service import get_stripe_service, StripeService, CREDIT_PACKAGES
from backend.api.dependencies import require_admin
@@ -228,15 +228,34 @@ async def get_current_user(
"""
Get the current user's profile.
Requires a valid session token.
Requires a valid session token or admin token.
"""
from backend.services.auth_service import get_auth_service
if not authorization:
raise HTTPException(status_code=401, detail="Not authenticated")
# Extract token
token = authorization.replace("Bearer ", "") if authorization.startswith("Bearer ") else authorization
# Validate session
# First try auth service (handles admin tokens and auth_tokens)
auth_service = get_auth_service()
auth_result = auth_service.validate_token_full(token)
if auth_result.is_valid and auth_result.user_email:
# Get or create user record for the authenticated email
user = user_service.get_or_create_user(auth_result.user_email)
user_public = UserPublic(
email=user.email,
role=user.role if not auth_result.is_admin else UserRole.ADMIN,
credits=user.credits,
display_name=user.display_name,
total_jobs_created=user.total_jobs_created,
total_jobs_completed=user.total_jobs_completed,
)
return UserProfileResponse(user=user_public, has_session=True)
# Fall back to session validation (for magic link sessions)
valid, user, message = user_service.validate_session(token)
if not valid or not user:
@@ -665,7 +684,7 @@ async def list_users(
limit = min(limit, 100)
db = user_service.db
query = db.collection("users")
query = db.collection(USERS_COLLECTION)
# Filter inactive users
if not include_inactive:
@@ -744,12 +763,18 @@ async def get_user_detail(
recent_jobs = []
for job_doc in jobs_query.stream():
job_data = job_doc.to_dict()
created_at = job_data.get("created_at")
# Handle both datetime objects and ISO strings
if created_at:
created_at_str = created_at.isoformat() if hasattr(created_at, 'isoformat') else str(created_at)
else:
created_at_str = None
recent_jobs.append({
"job_id": job_data.get("job_id"),
"status": job_data.get("status"),
"artist": job_data.get("artist"),
"title": job_data.get("title"),
"created_at": job_data.get("created_at").isoformat() if job_data.get("created_at") else None,
"created_at": created_at_str,
})
# Count active sessions
@@ -927,7 +952,7 @@ async def get_beta_stats(
from google.cloud.firestore_v1 import aggregation
# Count beta testers by status using efficient aggregation queries
users_collection = user_service.db.collection("users")
users_collection = user_service.db.collection(USERS_COLLECTION)
# Helper function to get count using aggregation
def get_count(query) -> int:
+1 -1
View File
@@ -32,7 +32,7 @@ logger = logging.getLogger(__name__)
# Collection names
USERS_COLLECTION = "users"
USERS_COLLECTION = "gen_users"
MAGIC_LINKS_COLLECTION = "magic_links"
SESSIONS_COLLECTION = "sessions"
PROCESSED_STRIPE_SESSIONS_COLLECTION = "processed_stripe_sessions"
+14
View File
@@ -155,6 +155,20 @@ LyricsTranscriber LyricsTranscriber
| Genius | Reference lyrics | Yes |
| YouTube API | Video upload | Optional |
## Firestore Collections
karaoke-gen shares a GCP project (`nomadkaraoke`) with karaoke-decide, but uses separate Firestore collections:
| Collection | Purpose | Key Fields |
|------------|---------|------------|
| `gen_users` | karaoke-gen user accounts | email, credits, role, is_active |
| `jobs` | Karaoke generation jobs | job_id, user_email, status, state_data |
| `sessions` | Magic link auth sessions | user_email, token, expires_at |
| `magic_links` | Passwordless auth tokens | email, token, expires_at, used |
| `beta_feedback` | Beta program feedback | user_email, ratings, comments |
**Note**: The `users` collection in the same Firestore instance belongs to karaoke-decide (different schema: user_id, is_guest, quiz_* fields). Don't use it for karaoke-gen.
## Tech Stack
- **Backend**: FastAPI, Python 3.12, Cloud Run
+19
View File
@@ -4,6 +4,25 @@ Key insights for future AI agents working on this codebase.
## Architecture Decisions
### Separate Collections for Multi-App Projects
**Problem**: karaoke-gen and karaoke-decide shared the same `users` Firestore collection with incompatible schemas. karaoke-gen users have `credits`, `role`, `is_active`; karaoke-decide users have `user_id`, `is_guest`, `quiz_*` fields.
**Symptoms**:
- Admin dashboard showed users from both apps mixed together
- Potential for data corruption if wrong app writes to wrong user
- Hard to run collection-wide queries (indexes, aggregations) for one app
**Solution**: Migrate karaoke-gen to dedicated `gen_users` collection. Created migration script that:
1. Identified karaoke-gen users by schema (has `credits` + `role` + `is_active`, lacks `user_id` + `is_guest`)
2. Copied 42 users to `gen_users` with same document IDs (email addresses)
3. Updated Pulumi indexes from `users` to `gen_users`
4. Left karaoke-decide's `users` collection untouched
**Key insight**: When multiple apps share a GCP project, use distinct collection names from day one. Prefixing collections with app name (e.g., `gen_users`, `decide_users`) avoids schema conflicts and makes ownership clear.
**Migration script**: `scripts/migrate_users_to_gen_users.py` - supports `--dry-run` and `--delete` flags.
### LyricsTranscriber: Library, Not Server
**Problem**: LyricsTranscriber's `ReviewServer` blocks waiting for human input - incompatible with async cloud architecture.
+2
View File
@@ -36,6 +36,8 @@
## Recent Changes
- **User Database Separation** (2026-01-03): Migrated karaoke-gen users from shared `users` collection to dedicated `gen_users` collection. This separates karaoke-gen user data from karaoke-decide user data (both apps share the same GCP project/Firestore instance). Migration script in `scripts/migrate_users_to_gen_users.py`. See [ARCHITECTURE.md](ARCHITECTURE.md#firestore-collections) for collection details.
- **Admin Dashboard** (2026-01-03): Added comprehensive admin dashboard at `/admin` with: stats overview (users, jobs, credits), user management (search, sort, add credits, toggle role, enable/disable), job browser (filter by status/user, view details, delete), and beta program monitoring. Query-param based routing for static export compatibility. See [API.md](API.md#admin-endpoints) for backend endpoints.
- **GCE Encoding Worker** (2026-01-03): Added optional high-performance encoding on dedicated GCE VM (C4-standard-8 with Intel Granite Rapids 3.9 GHz). Uses `USE_GCE_ENCODING=true` env var. Falls back to Cloud Run if unavailable. See [ARCHITECTURE.md](ARCHITECTURE.md).
+1 -1
View File
@@ -245,7 +245,7 @@ export default function AdminUsersPage() {
<TableRow
key={user.email}
className="cursor-pointer hover:bg-muted/50"
onClick={() => router.push(`/admin/users/${encodeURIComponent(user.email)}`)}
onClick={() => router.push(`/admin/users/detail?email=${encodeURIComponent(user.email)}`)}
>
<TableCell className="font-medium">
{user.display_name || user.email}
+97 -5
View File
@@ -92,6 +92,58 @@ firestore_index_magic_links = firestore.Index(
opts=pulumi.ResourceOptions(depends_on=[firestore_db]),
)
# Gen Users: query by is_active, order by created_at (for admin user list)
firestore_index_gen_users_active_created = firestore.Index(
"firestore-index-gen-users-active-created",
project=project_id,
database=firestore_db.name,
collection="gen_users",
fields=[
firestore.IndexFieldArgs(field_path="is_active", order="ASCENDING"),
firestore.IndexFieldArgs(field_path="created_at", order="DESCENDING"),
],
opts=pulumi.ResourceOptions(depends_on=[firestore_db]),
)
# Gen Users: query by is_active, order by last_login_at (for admin user list sorting)
firestore_index_gen_users_active_login = firestore.Index(
"firestore-index-gen-users-active-login",
project=project_id,
database=firestore_db.name,
collection="gen_users",
fields=[
firestore.IndexFieldArgs(field_path="is_active", order="ASCENDING"),
firestore.IndexFieldArgs(field_path="last_login_at", order="DESCENDING"),
],
opts=pulumi.ResourceOptions(depends_on=[firestore_db]),
)
# Gen Users: query by is_active, order by credits (for admin user list sorting)
firestore_index_gen_users_active_credits = firestore.Index(
"firestore-index-gen-users-active-credits",
project=project_id,
database=firestore_db.name,
collection="gen_users",
fields=[
firestore.IndexFieldArgs(field_path="is_active", order="ASCENDING"),
firestore.IndexFieldArgs(field_path="credits", order="DESCENDING"),
],
opts=pulumi.ResourceOptions(depends_on=[firestore_db]),
)
# Gen Users: query by is_active, order by email (for admin user list sorting)
firestore_index_gen_users_active_email = firestore.Index(
"firestore-index-gen-users-active-email",
project=project_id,
database=firestore_db.name,
collection="gen_users",
fields=[
firestore.IndexFieldArgs(field_path="is_active", order="ASCENDING"),
firestore.IndexFieldArgs(field_path="email", order="ASCENDING"),
],
opts=pulumi.ResourceOptions(depends_on=[firestore_db]),
)
# Create Cloud Storage Bucket
bucket = storage.Bucket(
"karaoke-storage",
@@ -755,6 +807,10 @@ pulumi.export("firestore_index_jobs_user_email", firestore_index_jobs_user_email
pulumi.export("firestore_index_jobs_status", firestore_index_jobs_status.name)
pulumi.export("firestore_index_sessions_active", firestore_index_sessions_active.name)
pulumi.export("firestore_index_magic_links", firestore_index_magic_links.name)
pulumi.export("firestore_index_gen_users_active_created", firestore_index_gen_users_active_created.name)
pulumi.export("firestore_index_gen_users_active_login", firestore_index_gen_users_active_login.name)
pulumi.export("firestore_index_gen_users_active_credits", firestore_index_gen_users_active_credits.name)
pulumi.export("firestore_index_gen_users_active_email", firestore_index_gen_users_active_email.name)
pulumi.export("service_account_email", service_account.email)
pulumi.export("artifact_repo_url", artifact_repo.name.apply(
lambda name: f"us-central1-docker.pkg.dev/{project_id}/karaoke-repo"
@@ -1212,12 +1268,12 @@ def upload_to_gcs(local_path: Path, gcs_uri: str):
# Upload a file or folder to GCS
parts = gcs_uri.replace("gs://", "").split("/", 1)
bucket_name = parts[0]
prefix = parts[1] if len(parts) > 1 else ""
prefix = parts[1].rstrip("/") if len(parts) > 1 else ""
bucket = storage_client.bucket(bucket_name)
if local_path.is_file():
blob_name = f"{prefix}/{local_path.name}".strip("/")
blob_name = f"{prefix}/{local_path.name}" if prefix else local_path.name
blob = bucket.blob(blob_name)
blob.upload_from_filename(str(local_path))
logger.info(f"Uploaded: {local_path} -> gs://{bucket_name}/{blob_name}")
@@ -1225,7 +1281,7 @@ def upload_to_gcs(local_path: Path, gcs_uri: str):
for file in local_path.rglob("*"):
if file.is_file():
rel_path = file.relative_to(local_path)
blob_name = f"{prefix}/{rel_path}".strip("/")
blob_name = f"{prefix}/{rel_path}" if prefix else str(rel_path)
blob = bucket.blob(blob_name)
blob.upload_from_filename(str(file))
logger.info(f"Uploaded: {file} -> gs://{bucket_name}/{blob_name}")
@@ -1269,8 +1325,9 @@ def run_encoding(job_id: str, work_dir: Path, config: dict):
progress = 10 + int((i / total_formats) * 80)
jobs[job_id]["progress"] = progress
if fmt == "mp4_4k":
output_file = output_dir / "output_4k.mp4"
if fmt == "mp4_4k_lossless" or fmt == "mp4_4k":
# High quality 4K - CRF 18 (visually lossless)
output_file = output_dir / "output_4k_lossless.mp4"
cmd = [
"ffmpeg", "-y",
"-i", str(input_video),
@@ -1288,6 +1345,26 @@ def run_encoding(job_id: str, work_dir: Path, config: dict):
"-threads", "24",
str(output_file)
])
elif fmt == "mp4_4k_lossy":
# Smaller 4K file - CRF 23 (good quality, smaller size)
output_file = output_dir / "output_4k_lossy.mp4"
cmd = [
"ffmpeg", "-y",
"-i", str(input_video),
]
if instrumental:
cmd.extend(["-i", str(instrumental)])
cmd.extend([
"-map", "0:v",
"-map", "1:a" if instrumental else "0:a",
"-c:v", "libx264",
"-preset", "medium",
"-crf", "23",
"-c:a", "aac",
"-b:a", "192k",
"-threads", "24",
str(output_file)
])
elif fmt == "mp4_720p":
output_file = output_dir / "output_720p.mp4"
cmd = [
@@ -1360,6 +1437,21 @@ async def process_job(job_id: str, request: EncodeRequest):
logger.info(f"Uploading to {request.output_gcs_path}")
upload_to_gcs(output_dir, request.output_gcs_path)
# Convert local paths to blob paths (backend expects blob paths, not full gs:// URIs)
# output_gcs_path is like "gs://bucket/jobs/id/encoded/"
# We need paths like "jobs/id/encoded/output_4k.mp4"
gcs_path = request.output_gcs_path.replace("gs://", "")
parts = gcs_path.split("/", 1)
prefix = parts[1].rstrip("/") if len(parts) > 1 else ""
local_output_files = jobs[job_id].get("output_files", [])
blob_paths = []
for local_path in local_output_files:
filename = Path(local_path).name
blob_path = f"{prefix}/{filename}" if prefix else filename
blob_paths.append(blob_path)
jobs[job_id]["output_files"] = blob_paths
logger.info(f"Output files (blob paths): {blob_paths}")
jobs[job_id]["status"] = "complete"
jobs[job_id]["progress"] = 100
logger.info(f"Job {job_id} complete")
+153
View File
@@ -0,0 +1,153 @@
#!/usr/bin/env python3
"""
Migration script to copy karaoke-gen users from 'users' collection to 'gen_users' collection.
This script:
1. Identifies karaoke-gen users in the 'users' collection (by presence of 'credits' field)
2. Copies them to the 'gen_users' collection (preserving document ID = email)
3. Optionally deletes the old documents from 'users' collection
Run with:
python scripts/migrate_users_to_gen_users.py --dry-run # Preview only
python scripts/migrate_users_to_gen_users.py # Execute migration
python scripts/migrate_users_to_gen_users.py --delete # Also delete old docs
"""
import argparse
import sys
from google.cloud import firestore
def is_karaoke_gen_user(doc_data: dict) -> bool:
"""
Determine if a user document belongs to karaoke-gen.
karaoke-gen users have:
- Document ID = email address (contains @)
- 'credits' field
- 'role' field with value 'user' or 'admin'
- 'is_active' field
karaoke-decide users have:
- Document ID = hash or guest_xxx
- 'user_id' field
- 'is_guest' field
"""
# Check for karaoke-gen specific fields
has_credits = 'credits' in doc_data
has_role = doc_data.get('role') in ['user', 'admin']
has_is_active = 'is_active' in doc_data
# Check for karaoke-decide specific fields
has_user_id = 'user_id' in doc_data
has_is_guest = 'is_guest' in doc_data
# karaoke-gen users have credits/role/is_active but NOT user_id/is_guest
return has_credits and has_role and has_is_active and not has_user_id and not has_is_guest
def migrate_users(dry_run: bool = True, delete_old: bool = False):
"""
Migrate karaoke-gen users from 'users' to 'gen_users' collection.
"""
db = firestore.Client(project='nomadkaraoke')
users_collection = db.collection('users')
gen_users_collection = db.collection('gen_users')
# Get all documents from users collection
print("Fetching all documents from 'users' collection...")
all_docs = list(users_collection.stream())
print(f"Found {len(all_docs)} total documents in 'users' collection")
# Filter to karaoke-gen users
gen_users = []
decide_users = []
unknown_users = []
for doc in all_docs:
doc_data = doc.to_dict()
doc_id = doc.id
if is_karaoke_gen_user(doc_data):
gen_users.append((doc_id, doc_data))
elif 'user_id' in doc_data or 'is_guest' in doc_data:
decide_users.append(doc_id)
else:
unknown_users.append(doc_id)
print(f"\nClassification results:")
print(f" - karaoke-gen users: {len(gen_users)}")
print(f" - karaoke-decide users: {len(decide_users)}")
print(f" - Unknown/other: {len(unknown_users)}")
if unknown_users:
print(f"\nUnknown users (first 5): {unknown_users[:5]}")
if dry_run:
print(f"\n[DRY RUN] Would migrate {len(gen_users)} users to 'gen_users' collection:")
for doc_id, doc_data in gen_users[:10]:
email = doc_data.get('email', doc_id)
credits = doc_data.get('credits', 0)
print(f" - {email} (credits: {credits})")
if len(gen_users) > 10:
print(f" ... and {len(gen_users) - 10} more")
return
# Execute migration
print(f"\nMigrating {len(gen_users)} users to 'gen_users' collection...")
migrated = 0
errors = 0
for doc_id, doc_data in gen_users:
try:
# Use the same document ID (email) in the new collection
gen_users_collection.document(doc_id).set(doc_data)
migrated += 1
if migrated % 10 == 0:
print(f" Migrated {migrated}/{len(gen_users)}...")
except Exception as e:
print(f" ERROR migrating {doc_id}: {e}")
errors += 1
print(f"\nMigration complete: {migrated} migrated, {errors} errors")
# Optionally delete old documents
if delete_old and errors == 0:
print(f"\nDeleting old documents from 'users' collection...")
deleted = 0
for doc_id, _ in gen_users:
try:
users_collection.document(doc_id).delete()
deleted += 1
except Exception as e:
print(f" ERROR deleting {doc_id}: {e}")
print(f"Deleted {deleted} documents from 'users' collection")
elif delete_old and errors > 0:
print("\nSkipping deletion due to migration errors")
def main():
parser = argparse.ArgumentParser(description='Migrate karaoke-gen users to gen_users collection')
parser.add_argument('--dry-run', action='store_true', help='Preview migration without making changes')
parser.add_argument('--delete', action='store_true', help='Delete old documents after successful migration')
args = parser.parse_args()
# Default to dry-run if neither flag is set
dry_run = args.dry_run or not args.delete
if not dry_run:
print("=" * 60)
print("WARNING: This will modify production data!")
print("=" * 60)
response = input("Type 'yes' to continue: ")
if response.lower() != 'yes':
print("Aborted")
sys.exit(1)
migrate_users(dry_run=dry_run, delete_old=args.delete)
if __name__ == '__main__':
main()