# Deployment

For a live Apache/PHP/MySQL VPS without Docker, follow the [LAMP VPS setup guide](lamp-vps-setup.md). It includes migration of an existing client database without demo seeders.

Living document — grows as each phase adds worker commands (SPEC §6). As of Phase 7: `sms:dispatch`, `sms:retry`, `sms:export`, and `sms:webhooks` (continuous workers), plus `sms:audit-balances` and `sms:aggregate-stats` (nightly/periodic cron), all exist. Phase 5 intentionally does not add `sms:poll-dlr` — BulkSMSBD's DLR mechanism is unconfirmed (docs/providers/bulksmsbd.md); polling is only needed if they turn out not to push DLRs, so it's deferred until that's known. Later phases add `sms:prune-logs` and `sms:archive` — each gets added to the samples below when it lands.

## Local dev (Docker)

Workers are opt-in so a plain `docker compose up -d` stays a fast web-only loop:

```bash
docker compose --profile workers up -d worker retry scheduler export webhooks
```

See [README.md](../README.md) for the rest of the local setup.

## Production: supervisor (continuous workers)

`sms:dispatch` and `sms:retry` are both continuous workers — each processes whatever is claimable and returns immediately, so they're supervised as tight loops, not cron jobs. Multiple processes of either are safe to run concurrently (`SELECT ... FOR UPDATE SKIP LOCKED`); scale `sms:dispatch` by raising `numprocs`. `sms:retry` only needs one process — it just requeues, `sms:dispatch` does the real work — on a short interval so a message's backoff window doesn't sit idle once it passes.

`/etc/supervisor/conf.d/abmsms-worker.conf`:

```ini
[program:abmsms-dispatch]
command=/bin/sh -c "php /var/www/abmsms/spark sms:dispatch --limit 500; sleep 2"
directory=/var/www/abmsms
autostart=true
autorestart=true
numprocs=2
process_name=%(program_name)s_%(process_num)02d
user=www-data
redirect_stderr=true
stdout_logfile=/var/www/abmsms/writable/logs/supervisor-dispatch.log
stopwaitsecs=15

[program:abmsms-retry]
command=/bin/sh -c "php /var/www/abmsms/spark sms:retry --limit 500; sleep 30"
directory=/var/www/abmsms
autostart=true
autorestart=true
numprocs=1
user=www-data
redirect_stderr=true
stdout_logfile=/var/www/abmsms/writable/logs/supervisor-retry.log
stopwaitsecs=15

[program:abmsms-export]
command=/bin/sh -c "php /var/www/abmsms/spark sms:export --limit 10; sleep 15"
directory=/var/www/abmsms
autostart=true
autorestart=true
numprocs=1
user=www-data
redirect_stderr=true
stdout_logfile=/var/www/abmsms/writable/logs/supervisor-export.log
stopwaitsecs=15

[program:abmsms-webhooks]
command=/bin/sh -c "php /var/www/abmsms/spark sms:webhooks --limit 200; sleep 10"
directory=/var/www/abmsms
autostart=true
autorestart=true
numprocs=1
user=www-data
redirect_stderr=true
stdout_logfile=/var/www/abmsms/writable/logs/supervisor-webhooks.log
stopwaitsecs=15
```

**Every `--option` here is space-separated (`--limit 500`), never `--limit=500`** - CI4's CLI argument parser (`CLI::parseCommandLine()`) doesn't split on `=` at all, so `--limit=500` silently becomes an unrecognized option key (`"limit=500"`) and the command falls back to its coded default with no warning. Found via live-testing Phase 10's new commands; every `--limit=N` in this file and in `docker-compose.yml` had this exact bug from Phase 3 onward until now - fixed project-wide, see the matching CLAUDE.md gotcha.

After editing:

```bash
sudo supervisorctl reread
sudo supervisorctl update
sudo supervisorctl status
```

## Production: crontab (periodic jobs)

`/etc/cron.d/abmsms` (as `www-data`, or via `crontab -u www-data -e`):

```cron
# SPEC §3.3 - drift is a P1, not a rounding curiosity. Nightly.
0 2 * * * www-data php /var/www/abmsms/spark sms:audit-balances >> /var/www/abmsms/writable/logs/cron-audit-balances.log 2>&1

# SPEC §5.4 Phase 6 - correctness backstop for the live-incremented
# sms_daily_stats figures (Services\Sms\DailyStatsRecorder). Hourly, not
# strictly nightly: it only ever repairs the handful of transitions the
# live increment deliberately skips (see that class's docblock), so
# there's no harm running it often, and it keeps staleness bounded to
# under an hour instead of a full day. On a 1M-row sms_messages table this
# takes a few seconds (benchmarked at Phase 6) - fine even hourly.
15 * * * * www-data php /var/www/abmsms/spark sms:aggregate-stats >> /var/www/abmsms/writable/logs/cron-aggregate-stats.log 2>&1

# SPEC §3.6 - sms_api_logs retention. Low priority, nightly is plenty.
30 2 * * * www-data php /var/www/abmsms/spark sms:prune-logs >> /var/www/abmsms/writable/logs/cron-prune-logs.log 2>&1

# SPEC §3.4 - keeps sms_messages from growing unbounded by moving old,
# terminal-status rows into sms_messages_archive. Low priority, nightly.
45 2 * * * www-data php /var/www/abmsms/spark sms:archive >> /var/www/abmsms/writable/logs/cron-archive.log 2>&1
```

Both default their retention/age window from `Config\Abmsms` (`$apiLogRetentionDays` / `$messageArchiveAfterDays`) - only pass `--older-than <days>` if you need a one-off override.

`sms:export` (Phase 6, SPEC §5.4: "file generated by worker") and `sms:webhooks` (Phase 7, SPEC §5.5) are both continuous workers, not cron jobs - see the supervisor block above, same "process what's claimable and return" shape as `sms:dispatch`/`sms:retry`.

## DLR webhook URL (give this to each upstream provider)

`POST https://<host>/webhook/dlr/{provider_slug}`, where `{provider_slug}` is that provider's `sms_providers.adapter` value (e.g. `bulksmsbd`). Unauthenticated as of Phase 5 — see `Controllers\Webhook\DlrController`'s docblock for why, and add inbound auth here once a given provider's supported mechanism is confirmed.

## Outbound webhooks (we call the tenant, SPEC §5.5)

`X-Abm-Signature: hex hmac_sha256(endpoint_secret, raw_body)` — a plain HMAC-SHA256 of the exact raw JSON body bytes (`Libraries\WebhookSignature`), distinct from the inbound API's more elaborate Mode B scheme (`Libraries\HmacSignature`). Headers: `X-Abm-Signature`, `X-Abm-Event` (`message.delivered` / `message.failed` as of Phase 7 — `balance.low` is a defined event with no trigger yet, see `App\Enums\WebhookEvent`), `X-Abm-Delivery-Id` (stable across retries of the same delivery). Backoff: 1m/5m/15m/1h/6h, then the delivery is abandoned and its endpoint marked `degraded` (auto-recovers to `active` on the next successful delivery to that endpoint — `disabled` is the only state this worker never sets itself, an explicit tenant/admin action). Tenant-facing endpoint registration (`sms_webhook_endpoints` CRUD, "send test event" button) shipped in Phase 9 — `Controllers\Tenant\WebhookController`.

## Admin panel (Phase 8, SPEC §8)

`https://<host>/admin/login` - session-authenticated, CSRF-protected, server-rendered (no separate deploy step, ships with the app). `spark db:seed AdminUserSeeder` creates the first super_admin login (credentials printed once - see the seeder). From then on, `Admin Users` in the panel itself is how further admins get onboarded (`Controllers\Admin\AdminUserController`, super_admin only). Session expiry is `Config\Session::$expiration` (2h); `Filters\AdminAuthFilter` re-checks `admin_users.status` on every request, so disabling an account revokes an already-open session immediately, not just future logins. Login throttling: 5 failures per email locks that email out for 15 minutes (cache-based, `Controllers\Admin\AuthController`).

## Tenant portal (Phase 9, SPEC §9)

`https://<host>/portal/login` - same session/CSRF/login-throttling shape as the admin panel, but a completely separate identity and session-key space (`Libraries\TenantContext`, prefixed `portal_*` vs the admin panel's `admin_*` - both share the one `ci_session` cookie/store, so this is what stops one login from clobbering the other). `spark db:seed TestTenantSeeder` creates the first portal login (`owner@abmsoft.test`, credentials printed once). Role capability split (`App\Enums\TenantRole`): `viewer` is read-only, `operator` can also send/request a sender ID, only `owner` can manage API credentials and webhook endpoints. Full English/Bangla toggle (`app/Language/{en,bn}/Portal.php`, kept in exact key-for-key sync) - `Filters\TenantLocaleFilter` sets locale on every `portal/*` request including the login screen, from the tenant's session preference (`portal/lang/{en,bn}`, no auth required to switch).

## Co-hosting behind an existing Caddy (or any other shared edge proxy)

If this isn't the only project on the VPS, don't run a second Caddy/nginx bound to 80/443 - reuse whatever is already the edge:

1. `docker network create edge_net` (once).
2. `docker network connect edge_net <existing-caddy-container>` - **live-attaches a running container to an additional network with zero restart/downtime** (`docker compose up` would instead recreate the container to add a network - use the plain `docker network connect` CLI command against the already-running container name instead, specifically to avoid that).
3. This project's own `docker-compose.prod.yml` already declares `web` on `edge_net` (`external: true`) - nothing more to do on this side.
4. Append (never edit in place) a new site block to the existing Caddyfile: `sms.nextmotogear.com { reverse_proxy abmsms-web-1:80 ... }` - back up the file first, `caddy validate --config ...` before touching the running instance, then `docker exec <caddy-container> caddy reload --config /etc/caddy/Caddyfile` (graceful, zero-downtime - never `docker compose restart`, which would drop live connections on every other site that same Caddy serves).

This is exactly how `sms.nextmotogear.com` is deployed alongside the sibling `nextmotogear.com` project's own Caddy on the same VM - see that project's Caddyfile for the actual two-site-block result.

## Environment

Production `.env` differs from local dev in at minimum:

- `CI_ENVIRONMENT = production`
- `app.forceGlobalSecureRequests = true` (SPEC §11: force HTTPS, HSTS)
- Real database credentials, not the docker-compose dev ones
- A production `encryption.key` (`php spark key:generate`, once, then never regenerate without a rotation plan — it's what protects `sms_api_credentials.api_secret_hash` and `sms_providers.credentials`)
- Real upstream provider credentials (Phase 4) — never committed, never logged (SPEC §11 `redactSecrets()`)

**`Config\App::$proxyIPs` must be set behind any TLS-terminating reverse proxy** (Caddy, nginx, an LB) - found on the actual first production deploy, since local dev never sits behind one so this never surfaces there. `Request::isSecure()` only trusts an incoming `X-Forwarded-Proto: https` header when the immediate peer IP is in `$proxyIPs`; left at its CI4 default (`[]`), every request looks insecure to the app no matter how it actually arrived, and `forceGlobalSecureRequests` redirects it to itself forever (an infinite redirect loop, not an error page - easy to misdiagnose as a Caddy problem instead). Already set correctly in this repo (trusts the private RFC 1918 ranges - safe because only our own nginx container, on a Docker-internal network never exposed publicly, can ever be that immediate peer); re-verify it's still set if `app/Config/App.php` is ever regenerated from a fresh CI4 skeleton.
