# Vibecarbon Docker Compose
# PostgreSQL + Hono API + Traefik reverse proxy

services:
  # ===========================================
  # REVERSE PROXY
  # ===========================================
  traefik:
    # Docker Hub's multi-arch index, for local `vibecarbon up` (Apple Silicon
    # included). Servers never pull this: docker-compose.prod.yml swaps in our
    # amd64 ghcr mirror of the SAME tag, so a cloud IP's anonymous Docker Hub
    # quota cannot stall a deploy (tests/unit/deploy/core-images-from-mirror-census.test.ts).
    image: traefik:v3.7.19@sha256:aa942a00bce033c909bf1f7e861d93761be4b31a035f10d2410d33e38a8f41cf
    container_name: ${PROJECT_NAME}-traefik
    restart: unless-stopped
    security_opt:
      - no-new-privileges:true
    cap_drop:
      - ALL
    cap_add:
      - NET_BIND_SERVICE
    read_only: true
    tmpfs:
      - /tmp
    command:
      - "--api.dashboard=true"
      - "--api.insecure=true"
      - "--providers.docker=true"
      - "--providers.docker.endpoint=unix:///var/run/docker.sock"
      - "--providers.docker.exposedbydefault=false"
      # Constrain discovery to THIS compose project. Traefik watches the whole
      # docker socket; with two vibecarbon projects running side-by-side, each
      # traefik would otherwise adopt BOTH projects' identically-named services
      # as backends of one load balancer — half of them on a network this
      # traefik isn't attached to → intermittent Gateway Timeouts on every
      # stack (RCA 2026-07-17: my-app + swim2 dev stacks cross-contaminated).
      # `com.docker.compose.project` is compose's automatic project label and
      # always equals PROJECT_NAME for stacks created by `vibecarbon create`.
      - "--providers.docker.constraints=Label(`com.docker.compose.project`,`${PROJECT_NAME}`)"
      - "--providers.file.directory=/etc/traefik/dynamic"
      - "--entrypoints.web.address=:80"
      - "--log.level=INFO"
    ports:
      - "${DEV_TRAEFIK_PORT:-80}:80"
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock:ro
      - ./volumes/traefik:/etc/traefik/dynamic:ro
    networks:
      - vibecarbon-network
    labels:
      - "traefik.enable=true"
      # Subdomain routing - auth added via prod overlay (docker-compose.prod.yml)
      - "traefik.http.routers.dashboard.rule=Host(`traefik.${DOMAIN:-localhost}`)"
      - "traefik.http.routers.dashboard.entrypoints=web"
      - "traefik.http.routers.dashboard.service=api@internal"

  # ===========================================
  # APPLICATION
  # ===========================================
  app:
    build:
      context: .
      args:
        VITE_PROJECT_NAME: ${PROJECT_NAME}
        VITE_PLAUSIBLE_DOMAIN: ${VITE_PLAUSIBLE_DOMAIN:-}
        VITE_PLAUSIBLE_SCRIPT_URL: ${VITE_PLAUSIBLE_SCRIPT_URL:-}
        VITE_GITHUB_REPO_URL: ${VITE_GITHUB_REPO_URL:-}
    container_name: ${PROJECT_NAME}-app
    restart: unless-stopped
    # Make every configure-managed runtime key (billing/OAuth/SMTP) available to
    # the app container in local dev. On a server the prod overlay swaps this
    # for app.env, which holds only the app's own keys. The `environment:`
    # overrides below still take precedence over either file.
    env_file:
      - .env
    security_opt:
      - no-new-privileges:true
    cap_drop:
      - ALL
    read_only: true
    tmpfs:
      - /tmp
    environment:
      - NODE_ENV=production
      - SITE_URL=${SITE_URL:-http://localhost:5173}
      # Auth runs in-process (src/server/auth/). The secret signs session
      # cookies and auth tokens; `vibecarbon create` writes it to .env.local.
      # The prod overlay refuses to start without it.
      - BETTER_AUTH_SECRET=${BETTER_AUTH_SECRET:-}
      - BETTER_AUTH_URL=${SITE_URL:-http://localhost:5173}
      # The API server talks to Postgres directly (src/server/db/client.ts),
      # as its own role, app_service: never as the owner, whose password
      # only app-migrate below gets. These win over .env, whose DB_HOST=localhost
      # and owner DB_USER/DB_PASSWORD are for local tools. DB_NAME defaults
      # to postgres.
      - DB_HOST=db
      - DB_PORT=5432
      - DB_USER=app_service
      - DB_PASSWORD=${APP_DB_PASSWORD:?APP_DB_PASSWORD missing, run vibecarbon upgrade to write it to .env}
      # env_file above hands the app all of .env, owner credentials included.
      # Blank them here (environment wins over env_file), so a local app holds
      # no database password but its own.
      - POSTGRES_PASSWORD=
      - REPL_PASSWORD=
      - N8N_DB_PASSWORD=
      - N8N_ENCRYPTION_KEY=
      - METABASE_DB_PASSWORD=
      - OBSERVABILITY_DB_PASSWORD=
    depends_on:
      # Data and auth both live in Postgres. The app starts once the db is
      # healthy and app-migrate has applied the migrations and set up the
      # app_service role.
      db:
        condition: service_healthy
      app-migrate:
        condition: service_completed_successfully
    networks:
      - vibecarbon-network
    labels:
      - "traefik.enable=true"
      - "traefik.http.routers.app.rule=Host(`localhost`)"
      - "traefik.http.routers.app.entrypoints=web"
      - "traefik.http.services.app.loadbalancer.server.port=3000"

  # The migrate step (src/server/db/migrate-cli.ts): a one-shot of the app
  # image that applies db/migrations as the owner, postgres, then creates or
  # updates the app's own role, app_service, with APP_DB_PASSWORD. It is the
  # only service besides db that holds the owner password (the app's
  # environment blanks the one its env_file carries), and it exits when
  # done; the app waits for it to complete successfully. On a compose-ha
  # standby it finds a read-only database and exits 0 at once: migrations and
  # the role arrive from the primary by replication.
  app-migrate:
    build:
      context: .
      args:
        VITE_PROJECT_NAME: ${PROJECT_NAME}
        VITE_PLAUSIBLE_DOMAIN: ${VITE_PLAUSIBLE_DOMAIN:-}
        VITE_PLAUSIBLE_SCRIPT_URL: ${VITE_PLAUSIBLE_SCRIPT_URL:-}
        VITE_GITHUB_REPO_URL: ${VITE_GITHUB_REPO_URL:-}
    container_name: ${PROJECT_NAME}-app-migrate
    command: ["node", "dist/server/migrate-cli.js"]
    restart: "no"
    security_opt:
      - no-new-privileges:true
    cap_drop:
      - ALL
    read_only: true
    tmpfs:
      - /tmp
    environment:
      - NODE_ENV=production
      - PROJECT_NAME=${PROJECT_NAME}
      - DB_HOST=db
      - DB_PORT=5432
      - DB_USER=postgres
      - DB_PASSWORD=${POSTGRES_PASSWORD}
      - APP_DB_PASSWORD=${APP_DB_PASSWORD:?APP_DB_PASSWORD missing, run vibecarbon upgrade to write it to .env}
    depends_on:
      db:
        condition: service_healthy
    networks:
      - vibecarbon-network

  # ===========================================
  # DATABASE
  # ===========================================

  # PostgreSQL Database
  db:
    # vibecarbon's published db image (official postgres Alpine + pg_cron +
    # wal-g + a baked postgresql.conf, built once from docker/postgres-walg in
    # the vibecarbon repo). Pulled, never built: locally, on compose servers
    # and on k8s alike. DB_IMAGE / DB_IMAGE_TAG are written into .env by
    # `vibecarbon create` and refreshed by `vibecarbon upgrade` and every
    # deploy, so the tag always matches the CLI that manages the project.
    image: ${DB_IMAGE:?DB_IMAGE missing, run vibecarbon upgrade to write it to .env}:${DB_IMAGE_TAG:?DB_IMAGE_TAG missing, run vibecarbon upgrade to write it to .env}
    container_name: ${PROJECT_NAME}-db
    restart: unless-stopped
    security_opt:
      - no-new-privileges:true
    # db-guard.sh refuses to boot over an interrupted `vibecarbon restore`
    # (its in-progress marker in PGDATA), then execs the image's own
    # db-entrypoint.sh with the same arguments. Run through sh so the scaffold
    # copy's file mode does not matter.
    entrypoint: ["sh", "/usr/local/bin/db-guard.sh"]
    healthcheck:
      test: ["CMD", "pg_isready", "-U", "postgres", "-h", "localhost"]
      interval: 5s
      timeout: 5s
      retries: 10
      # First-time init (initdb plus the entrypoint's temporary server) runs
      # before the server accepts TCP connections (it took ~60-150s on the
      # previous image under fanout-3 load — observed
      # restore re-deploy failing at deploy.compose.up=160s while the same db
      # eventually became healthy ~3min later, fanout9 e1 2026-05-01). Without
      # start_period, retries × interval = 50s expires before first init
      # completes, compose marks db unhealthy, and dependent services fail
      # with "dependency failed to start". start_period suppresses the
      # unhealthy verdict during initial boot.
      start_period: 180s
    command:
      - postgres
      - -c
      - config_file=/etc/postgresql/postgresql.conf
      - -c
      - wal_level=replica
      - -c
      - archive_mode=on
      - -c
      # Fault-tolerant wrapper around `wal-g wal-push`. If wal-g fails (S3
      # outage, bad creds, missing bucket), the wrapper retries with backoff
      # then logs "WAL_ARCHIVE_FAILED" to stderr and exits 0 so PG can recycle
      # the segment instead of pinning the entire pg_wal directory. Without
      # this, a single archive failure pins WAL forever and fills the disk
      # within days (~20 GiB/day of WAL on an idle database given
      # archive_timeout below, measured on the previous image, whose bundled
      # extensions generated background writes every minute; pg_cron still
      # writes when jobs run). RCA: prod-1 2026-05-26, 58 GiB of WAL retained
      # in 3 days because wal-g couldn't reach the configured S3 bucket;
      # disk filled, db went into Error state, /api/v1/notifications 500'd,
      # whole stack down. Trade-off: a persistent archive outage leaves a
      # PITR gap, but the DB stays up — strictly better than the previous
      # behavior for a SaaS template. Grep `docker logs db` for
      # WAL_ARCHIVE_FAILED to detect silent backup regressions.
      # Invoke via `bash` rather than relying on the script's exec bit: the
      # create-time scaffold copy (copyFileSync) drops +x, and a 0644 script
      # made postgres fail archiving with exit 126 ("not executable"), which
      # silently re-pins WAL. bash-invoking it (like reconcile.sh) is immune to
      # the file mode, so the fault-tolerant wrapper always runs.
      - archive_command=bash /etc/postgresql/wal-archive.sh %p
      - -c
      # 60s was too aggressive — on an idle database, that forces a
      # 16 MiB segment switch every minute regardless of write volume (PG14+
      # is supposed to skip empty switches, but background writes such as
      # pg_cron's job runs are enough to trip it). 23 GiB/day of WAL baseline.
      # 900s (15 min) drops baseline to ~1.5 GiB/day with an RPO cap that's
      # plenty for SaaS workloads. Override via postgresql.conf or compose
      # if tighter RPO is needed.
      - archive_timeout=900
      - -c
      # hot_standby=on lets a server in recovery mode (i.e. our standby)
      # accept read-only psql connections. Required so failover's
      # pg_promote() call can connect to the standby (psql connections
      # otherwise return "database is not accepting connections / Hot
      # standby mode is disabled" and pg_promote can't be invoked).
      # No-op on the primary — hot_standby only affects standbys. The PG
      # default is on, but the previous image's config shipped it off
      # (seen on 15.8.1.085), so set it explicitly rather than trusting
      # the image. RCA: compose-ha 2026-05-01 fanout13 failover —
      # pg_promote retried 5 times against an unreachable standby psql
      # before aborting.
      - hot_standby=on
      - -c
      # Explicit connection ceiling (image default is 100). Real consumers —
      # the app's pools + replication + superuser_reserved — sit well below
      # it; 200 leaves headroom for the HA standby and scale-ups so the
      # ceiling can't be hit. The database has no public port: operators
      # reach it through `vibecarbon shell` / SSH. See docs/security.md.
      - max_connections=200
      - -c
      # Replication slot WAL cap. The HA standby streams through a physical
      # slot, and a slot holds WAL on the primary until its standby confirms
      # it: with no cap, a standby that stays down for about a week fills the
      # primary's volume and takes the serving database down. Past 4GB the
      # slot goes `lost` instead (`vibecarbon status` shows it) and the next
      # `vibecarbon deploy` reseeds the standby. No-op without a slot.
      - max_slot_wal_keep_size=4GB
      - -c
      # The floor a briefly disconnected standby catches up from without its
      # slot.
      - wal_keep_size=512MB
      - -c
      # The streaming standby plus a reseed's basebackup, with headroom.
      - max_wal_senders=10
    environment:
      # The official image's superuser. Named explicitly so `docker compose
      # exec db` scripts (metabase-init.sh, n8n-init.sh) get it as their user.
      POSTGRES_USER: postgres
      POSTGRES_HOST: /var/run/postgresql
      PGPORT: 5432
      POSTGRES_PORT: 5432
      PGPASSWORD: ${POSTGRES_PASSWORD}
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
      PGDATABASE: postgres
      POSTGRES_DB: postgres
      # WAL-G Configuration
      # `:-` defaults so local dev (no .env-set S3 creds) doesn't trigger
      # `WARN The "S3_*" variable is not set` for every compose invocation.
      # WAL-G is dormant locally without these anyway; the warns were pure
      # noise.
      #
      # WALG_S3_PREFIX_BASE is one path per ENVIRONMENT (VC_ENV, which the
      # deploy bundle writes into the server .env), so two environments of a
      # project never share a backup stream. Inside it each database lineage
      # has its own folder, named by its system identifier: every script that
      # runs wal-g sources /etc/postgresql/walg-env.sh (mounted below), which
      # exports WALG_S3_PREFIX=<base>/<system identifier>. A destroyed and
      # redeployed environment is a new database, so it never archives into,
      # or takes over the newest base of, the archive the old one left. Nothing
      # else sets WALG_S3_PREFIX (tests/unit/deploy/walg-lineage-prefix-census
      # .test.ts). It is a SINGLE canonical path per environment (NO role
      # segment). Reads
      # (backup-fetch/restore/reseed) and writes (backup-push/wal-push) must all
      # agree on ONE prefix — otherwise a standby restoring/reseeding would read
      # an empty `…/walg/standby` and fail with "No backups found". Anti-collision
      # (finding #3: a standby / bring-up-phase independent primary must never
      # WRITE into this prefix) is enforced by the wal-g role WRITE-GUARD: the
      # role file under /var/lib/vibecarbon/role (bound read-only from the
      # host's .vibecarbon-role in docker-compose.prod.yml, written by the CLI,
      # src/lib/deploy/walg-role.js). wal-archive.sh and the backup path read it
      # through walg-env.sh and write only when it says primary.
      WALG_S3_PREFIX_BASE: s3://${S3_BACKUP_BUCKET:-${S3_BUCKET:-}}/backups/${PROJECT_NAME}/${VC_ENV:-local}/walg
      # A WAL segment name already in the archive with other bytes is refused,
      # never overwritten: an archive that is somebody else's history stays
      # intact even if a guard above ever failed.
      WALG_PREVENT_WAL_OVERWRITE: "true"
      AWS_ACCESS_KEY_ID: ${S3_ACCESS_KEY:-}
      AWS_SECRET_ACCESS_KEY: ${S3_SECRET_KEY:-}
      AWS_ENDPOINT: ${S3_ENDPOINT:-}
      AWS_REGION: ${S3_REGION:-us-east-1}
      WALG_COMPRESSION_METHOD: lz4
    volumes:
      - db_data:/var/lib/postgresql/data
      - ./volumes/db/wal-archive.sh:/etc/postgresql/wal-archive.sh:ro,Z
      - ./volumes/db/walg-env.sh:/etc/postgresql/walg-env.sh:ro,Z
      - ./volumes/db/db-guard.sh:/usr/local/bin/db-guard.sh:ro,Z
    networks:
      - vibecarbon-network

volumes:
  db_data:

networks:
  vibecarbon-network:
    driver: bridge
    # Pin the IPAM subnet in the BASE file (not an overlay) so EVERY docker
    # compose op resolves the identical network — regardless of which overlays
    # (-f flags) it loads. The observability overlay pins Traefik to a static IP
    # on this network (<prefix>.10, for Grafana's auth-proxy trust boundary); if
    # the subnet lived only in that overlay, any op run without it (compose
    # scale's `run --rm db`, compose-ha's `up -d db`) would see a DYNAMIC subnet,
    # mismatch the live pinned network, and force a mid-op network recreate that
    # fails with "has active endpoints" while sibling containers are attached.
    # A /24 (256 addrs) keeps the pinned range small to minimise the chance it
    # collides with a subnet the host already routes.
    #
    # The prefix comes from DEV_SUBNET_PREFIX so several projects can share one
    # Docker daemon: with a fixed subnet, the second project's `up` dies with
    # "Pool overlaps with other one on this address space". `vibecarbon up`
    # detects that and writes a free prefix to .env — which compose reads on
    # every invocation (unlike .env.local, which only wrapper scripts merge),
    # so bare `docker compose` ops still resolve the same subnet. The
    # observability overlay's ipv4_address and GF_AUTH_PROXY_WHITELIST derive
    # from this SAME variable and move with it.
    #
    # ip_range partitions the subnet: Docker hands DYNAMIC addresses only from
    # the upper /25 (.128-.254), so a static ipv4_address pinned below .128
    # (the observability overlay pins Traefik to .10) can never be squatted by
    # a dynamically-allocated sibling. Without this, any recreate wave that
    # released and re-allocated addresses could hand .10 to another container,
    # after which Traefik fails to start with "Address already in use" on
    # every subsequent up — observed on the 2026-08-06 d1 warm deploys (rest
    # landed on .10; traefik and the site stayed down until teardown). Pins
    # live below .128, dynamics above; both derive from DEV_SUBNET_PREFIX.
    ipam:
      config:
        - subnet: ${DEV_SUBNET_PREFIX:-172.30.0}.0/24
          ip_range: ${DEV_SUBNET_PREFIX:-172.30.0}.128/25
