Files
karaoke-gen/infrastructure/modules/database.py
T
Andrew Beveridge ☄️andClaude Opus 4.8 1e99f9e0d5 feat(admin): per-job/user locale badge + "emails sent to user" history (#930)
## Summary

Two admin-only features so support/intervention work can (a) know what
language/country a user is using the product in, and (b) see the exact
emails ever sent to a user, rendered as they appeared in the inbox with
full delivery metadata.

### A — Language / country visibility (admin-only)
- New `get_full_locale_from_request()` captures the real UI language
(any of 33, not the narrowed en/es/de email locale) on **every**
job-creation path (URL, upload, audio-search, bulk, made-for-you via
Stripe metadata). Stored as `Job.locale` (+ added to the dashboard
summary projection) and `User.ui_locale` (kept separate from
`User.locale`).
- `LocaleBadge` (flag + language) shown in the admin jobs table, admin
job detail (+ country via the existing `IpInfo` on the creation IP), the
user-detail header, and the customer `JobCard` **gated to admins only**
— regular users never see it.
- Country is derived from IP (existing `ip_geolocation_service`); no new
capture.

### B — "Emails sent to this user"
- Every send routes through one `EmailService._log_and_send` chokepoint
that persists each email to a new Firestore `email_log` collection
(rendered HTML + Postmark MessageID), best-effort so it can never break
or delay a send. Single-use auth/capability tokens (magic-link, review,
referral) are **redacted** before persistence.
- `PostmarkAdminService` merges the Postmark Messages API (last ~45
days: exact HTML + opens/clicks/bounce/delivery status, paginated) with
the Firestore log (permanent), de-duplicated by message id.
- Endpoints `GET /api/admin/users/{email}/emails` and `GET
/api/admin/emails/{id}`; the user-detail "Emails Sent" card opens a
modal rendering the email in a sandboxed `<iframe srcDoc>` with a
metadata side panel.
- New Firestore composite index (`email_log` recipient + created_at)
added to Pulumi.

## Testing
- **41 new backend tests** (locale capture incl. q=0, email logging +
token redaction, PostmarkAdminService incl. pagination + 45-day
fallback, job-locale persistence, admin endpoints) — all pass.
- **10 new frontend tests** (LocaleBadge, UserEmailsCard list +
sandboxed-iframe modal) — all pass.
- Regression sweep on related existing suites: green. Preview-email flow
smoke-tested through the new chokepoint.

## Notes
- `pulumi up` for the new `email_log` index should be applied before
merge (done locally).
- `Job.locale` populates for new jobs going forward; historical jobs
fall back to the submitting user's locale where shown.

Local CodeRabbit review completed and addressed (token redaction,
pagination, row a11y, locale-overwrite guard, q=0 handling).

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

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-23 01:51:42 -04:00

335 lines
14 KiB
Python

"""
Firestore database resources.
Manages the Firestore database, composite indexes, and TTL configuration.
"""
import pulumi
import pulumi_gcp as gcp
from pulumi_gcp import firestore
from config import PROJECT_ID
def create_database() -> dict:
"""
Create Firestore database and all composite indexes.
Returns:
dict: Dictionary containing all created resources for export.
"""
resources = {}
# ==================== Firestore Database ====================
firestore_db = firestore.Database(
"karaoke-firestore",
project=PROJECT_ID,
name="(default)",
location_id="us-central1",
type="FIRESTORE_NATIVE",
concurrency_mode="PESSIMISTIC",
app_engine_integration_mode="DISABLED",
point_in_time_recovery_enablement="POINT_IN_TIME_RECOVERY_ENABLED",
)
resources["firestore_db"] = firestore_db
# ==================== Firestore Composite Indexes ====================
# These are required for queries that filter/sort on multiple fields.
# Jobs: query by user_email, order by created_at (for user job lists)
resources["firestore_index_jobs_user_email"] = firestore.Index(
"firestore-index-jobs-user-email",
project=PROJECT_ID,
database=firestore_db.name,
collection="jobs",
fields=[
firestore.IndexFieldArgs(field_path="user_email", order="ASCENDING"),
firestore.IndexFieldArgs(field_path="created_at", order="DESCENDING"),
],
opts=pulumi.ResourceOptions(depends_on=[firestore_db]),
)
# Jobs: query by status, order by created_at (for admin/system job lists)
resources["firestore_index_jobs_status"] = firestore.Index(
"firestore-index-jobs-status",
project=PROJECT_ID,
database=firestore_db.name,
collection="jobs",
fields=[
firestore.IndexFieldArgs(field_path="status", order="ASCENDING"),
firestore.IndexFieldArgs(field_path="created_at", order="DESCENDING"),
],
opts=pulumi.ResourceOptions(depends_on=[firestore_db]),
)
# Jobs: query by tenant_id, order by created_at (for tenant portal job lists)
resources["firestore_index_jobs_tenant"] = firestore.Index(
"firestore-index-jobs-tenant",
project=PROJECT_ID,
database=firestore_db.name,
collection="jobs",
fields=[
firestore.IndexFieldArgs(field_path="tenant_id", order="ASCENDING"),
firestore.IndexFieldArgs(field_path="created_at", order="DESCENDING"),
],
opts=pulumi.ResourceOptions(depends_on=[firestore_db]),
)
# Jobs: query by user_email + tenant_id, order by created_at (for tenant user job lists)
resources["firestore_index_jobs_user_tenant"] = firestore.Index(
"firestore-index-jobs-user-tenant",
project=PROJECT_ID,
database=firestore_db.name,
collection="jobs",
fields=[
firestore.IndexFieldArgs(field_path="user_email", order="ASCENDING"),
firestore.IndexFieldArgs(field_path="tenant_id", order="ASCENDING"),
firestore.IndexFieldArgs(field_path="created_at", order="DESCENDING"),
],
opts=pulumi.ResourceOptions(depends_on=[firestore_db]),
)
# Jobs: query by customer_email + made_for_you, order by created_at
# Used for finding existing made-for-you orders for a customer
resources["firestore_index_jobs_customer_mfy"] = firestore.Index(
"firestore-index-jobs-customer-mfy",
project=PROJECT_ID,
database=firestore_db.name,
collection="jobs",
fields=[
firestore.IndexFieldArgs(field_path="customer_email", order="ASCENDING"),
firestore.IndexFieldArgs(field_path="made_for_you", order="ASCENDING"),
firestore.IndexFieldArgs(field_path="created_at", order="DESCENDING"),
],
opts=pulumi.ResourceOptions(depends_on=[firestore_db]),
)
# Jobs: query by request_metadata.client_id + tenant_id, order by created_at.
# Powers GET /api/jobs?client_id= — the idempotency lookup for externally
# created jobs (the Fiverr agent tags jobs client_id="fiverr:{order_id}").
# Without it that query 400s ("The query requires an index").
resources["firestore_index_jobs_client_id"] = firestore.Index(
"firestore-index-jobs-client-id",
project=PROJECT_ID,
database=firestore_db.name,
collection="jobs",
fields=[
firestore.IndexFieldArgs(field_path="request_metadata.client_id", order="ASCENDING"),
firestore.IndexFieldArgs(field_path="tenant_id", order="ASCENDING"),
firestore.IndexFieldArgs(field_path="created_at", order="DESCENDING"),
],
opts=pulumi.ResourceOptions(depends_on=[firestore_db]),
)
# Sessions: query by user_email + is_active, order by created_at
resources["firestore_index_sessions_active"] = firestore.Index(
"firestore-index-sessions-active",
project=PROJECT_ID,
database=firestore_db.name,
collection="sessions",
fields=[
firestore.IndexFieldArgs(field_path="is_active", order="ASCENDING"),
firestore.IndexFieldArgs(field_path="user_email", order="ASCENDING"),
firestore.IndexFieldArgs(field_path="created_at", order="DESCENDING"),
],
opts=pulumi.ResourceOptions(depends_on=[firestore_db]),
)
# Magic links: query by email, order by created_at
resources["firestore_index_magic_links"] = firestore.Index(
"firestore-index-magic-links",
project=PROJECT_ID,
database=firestore_db.name,
collection="magic_links",
fields=[
firestore.IndexFieldArgs(field_path="email", 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 created_at
resources["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
resources["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
resources["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
resources["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]),
)
# Gen Users: query by signup_ip, order by created_at (anti-abuse investigation)
resources["firestore_index_gen_users_signup_ip"] = firestore.Index(
"firestore-index-gen-users-signup-ip",
project=PROJECT_ID,
database=firestore_db.name,
collection="gen_users",
fields=[
firestore.IndexFieldArgs(field_path="signup_ip", order="ASCENDING"),
firestore.IndexFieldArgs(field_path="created_at", order="DESCENDING"),
],
opts=pulumi.ResourceOptions(depends_on=[firestore_db]),
)
# Gen Users: query by device_fingerprint, order by created_at (anti-abuse investigation)
resources["firestore_index_gen_users_device_fingerprint"] = firestore.Index(
"firestore-index-gen-users-device-fingerprint",
project=PROJECT_ID,
database=firestore_db.name,
collection="gen_users",
fields=[
firestore.IndexFieldArgs(field_path="device_fingerprint", order="ASCENDING"),
firestore.IndexFieldArgs(field_path="created_at", order="DESCENDING"),
],
opts=pulumi.ResourceOptions(depends_on=[firestore_db]),
)
# Stripe Payments: query by customer_email, order by created_at
# Used for admin user detail page payment history
resources["firestore_index_stripe_payments_email"] = firestore.Index(
"firestore-index-stripe-payments-email",
project=PROJECT_ID,
database=firestore_db.name,
collection="stripe_payments",
fields=[
firestore.IndexFieldArgs(field_path="customer_email", order="ASCENDING"),
firestore.IndexFieldArgs(field_path="created_at", order="DESCENDING"),
],
opts=pulumi.ResourceOptions(depends_on=[firestore_db]),
)
# Email log: query by recipient, order by created_at
# Used for the admin user-detail "Emails sent to this user" history view
resources["firestore_index_email_log_recipient"] = firestore.Index(
"firestore-index-email-log-recipient",
project=PROJECT_ID,
database=firestore_db.name,
collection="email_log",
fields=[
firestore.IndexFieldArgs(field_path="recipient", order="ASCENDING"),
firestore.IndexFieldArgs(field_path="created_at", order="DESCENDING"),
],
opts=pulumi.ResourceOptions(depends_on=[firestore_db]),
)
# Audio separation jobs: query by status + updated_at (for cleanup of old jobs)
resources["firestore_index_audio_separation_jobs_cleanup"] = firestore.Index(
"firestore-index-audio-separation-jobs-cleanup",
project=PROJECT_ID,
database=firestore_db.name,
collection="audio_separation_jobs",
fields=[
firestore.IndexFieldArgs(field_path="status", order="ASCENDING"),
firestore.IndexFieldArgs(field_path="updated_at", order="ASCENDING"),
],
opts=pulumi.ResourceOptions(depends_on=[firestore_db]),
)
# ==================== Firestore TTL Field Configuration ====================
# TTL policies automatically delete documents after expiration.
# Worker logs TTL: logs subcollection documents expire after 30 days
resources["firestore_field_logs_ttl"] = firestore.Field(
"firestore-field-logs-ttl",
project=PROJECT_ID,
database=firestore_db.name,
collection="logs", # Subcollection name (applies to all jobs/{job_id}/logs)
field="ttl_expiry",
ttl_config={}, # Empty block enables TTL based on ttl_expiry field
index_config={}, # Disable indexing on TTL field
opts=pulumi.ResourceOptions(depends_on=[firestore_db]),
)
# Search sessions TTL: short-lived sessions from guided job creation flow expire after 30 minutes
# Sessions are created by POST /api/audio-search/search-standalone and consumed by
# POST /api/jobs/create-from-search. The TTL is a safety net for abandoned sessions.
resources["firestore_field_search_sessions_ttl"] = firestore.Field(
"firestore-field-search-sessions-ttl",
project=PROJECT_ID,
database=firestore_db.name,
collection="search_sessions",
field="ttl_expiry",
ttl_config={}, # Empty block enables TTL based on ttl_expiry field
index_config={}, # Disable indexing on TTL field
opts=pulumi.ResourceOptions(depends_on=[firestore_db]),
)
# ==================== Review Sessions Collection Group Index ====================
# The cross-job session search uses a collection group query on
# review_sessions ordered by updated_at DESC. Firestore requires a
# single-field index exemption with COLLECTION_GROUP scope for this.
# Created via REST API (gcloud doesn't support query-scope for field exemptions):
#
# curl -X PATCH \
# "https://firestore.googleapis.com/v1/projects/nomadkaraoke/databases/(default)/collectionGroups/review_sessions/fields/updated_at" \
# -H "Authorization: Bearer $(gcloud auth print-access-token)" \
# -H "Content-Type: application/json" \
# -d '{"indexConfig":{"indexes":[
# {"queryScope":"COLLECTION","fields":[{"fieldPath":"updated_at","order":"ASCENDING"}]},
# {"queryScope":"COLLECTION","fields":[{"fieldPath":"updated_at","order":"DESCENDING"}]},
# {"queryScope":"COLLECTION_GROUP","fields":[{"fieldPath":"updated_at","order":"DESCENDING"}]}
# ]}}'
#
# Pulumi doesn't have a native resource for single-field index
# exemptions — manage via gcloud/REST if it needs recreation.
# ==================== Firestore Indexes for Logs Subcollection ====================
# Logs: query by worker, order by timestamp
resources["firestore_index_logs_worker_timestamp"] = firestore.Index(
"firestore-index-logs-worker-timestamp",
project=PROJECT_ID,
database=firestore_db.name,
collection="logs", # Subcollection name
fields=[
firestore.IndexFieldArgs(field_path="worker", order="ASCENDING"),
firestore.IndexFieldArgs(field_path="timestamp", order="ASCENDING"),
],
opts=pulumi.ResourceOptions(depends_on=[firestore_db]),
)
return resources