# api.dsp.com

DSP API (Fastify + Prisma + MySQL).

## Advertiser site rechecks

Automatic rechecks are disabled by default (`SITE_RECHECK_ENABLED=false`).
Set it to `true` with `CRONS_ENABLED=true` to run the scheduler. Manual Verify,
Retry, and automatic rechecks use the same live browser verifier, connected by
the application automatically. No custom checker or new advertiser-side snippet
is required. Install its Chromium runtime on the API host with
`npm run site:browser:install` after installing dependencies. Linux hosts also
need Chromium's system libraries and a non-root account with browser sandbox
support.

Manual Verify and Retry remain synchronous. An accessible page without the
expected pixel returns a normal Failed result; by default, a saved historical beacon
alone cannot verify the site. No additional verification-page URL field is required.

The verifier opens the site's page in an isolated browser and looks for a fresh
beacon from the expected pixel and domain, including JavaScript-inserted pixels.
Old events do not count in live verification. The existing hosted pixel now
reports its page origin and path automatically, without query strings or fragments.
That address is used for later checks; older sites with no recorded page address
fall back to `https://{domain}/`. The local test fixture is the only exception:
with `NODE_ENV=development`, `*.localtest.me` defaults to
`http://{domain}:8080/test.html`. This default does not apply to other domains or
staging/production. A recorded pixel page still takes precedence.
For a pixel on a non-homepage URL, a normal page
visit records the address without changing or reinstalling the snippet.

Public-page fetching blocks private networks, checks DNS at connection time,
and validates redirects. In development only, recorded `*.localtest.me` pages
and a loopback pixel API can use their recorded ports. For example, loading
`http://example1.localtest.me:8080/test.html` records that site's exact local
address. No global URL-template environment variable is used. A nonexistent
main-page domain (DNS `ENOTFOUND`) counts as a missed check, as do HTTP 404/410
responses. Verified sites still receive their warning and configured grace period
before a second miss makes them Failed. Temporary DNS failures, timeouts,
connection errors, HTTP 5xx, and unavailable pixel/CDN scripts remain inconclusive.
These errors leave verification state and check dates unchanged; manual requests
return 503 and scheduled failures are logged for retry on the next sweep. The default
check budget is 20000 milliseconds (`SITE_VERIFICATION_TIMEOUT_MS`).

Defaults are 12-hour polling (`SITE_RECHECK_CRON_SCHEDULE="0 */12 * * *"`), a
604800-second recheck interval (7 days), and an 86400-second grace period
(24 hours). Local testing can override polling to `"*/4 * * * *"`, the interval
to `900`, and grace to `300`. Tests can inject deterministic checker results
without introducing a public test endpoint.

### Verify a dev or staging pixel installed on your laptop

For a site such as `mani.localtest.me` registered on dev or staging, enable the
following on that **API server** (or local API), and restart it:

```dotenv
SITE_VERIFICATION_ALLOW_LOCALTEST_BEACONS=true
```

Paste that site's pixel snippet (from the same environment) into
`scripts/site-verification-local/test.html`. Serve it locally and open
`http://mani.localtest.me:8080/test.html` (adjust the port to your local server).
Do not open it as `file://` or `localhost`: the browser hostname must match the
registered site. Leave the script URL pointing to that API so its beacon is recorded
in its database. Then click Verify or Retry in that environment's UI. No tunnel is
needed; the browser sends the beacon to the API, rather than the API trying to open
your laptop.

This opt-in accepts **any previously recorded beacon** with the exact pixel ID
and `*.localtest.me` domain, regardless of age. It applies to Verify, Retry, and
automatic rechecks, and also works on a local API. As a result, removing a local
test pixel does not make the site fail while its matching event remains stored.
This is a testing shortcut, not proof of current installation or domain ownership.
Other domains always keep live browser verification. The flag defaults to `false`
and enabling it with `NODE_ENV=production` is rejected. Set it back to `false` and
restart to restore live checks for local-test domains too.

### Recheck scheduling

Each completed check sets `lastCheckedAt` and its own `nextCheckAt`. A first
automatic miss leaves the site Verified with `recheckWarningAt`; the next miss
after grace marks it Failed. Passing clears the warning. Failed checks, including
manual Retry, schedule the next automatic check after the interval. Manual Retry
remains synchronous and never adds a Pending transition.

Apply the equivalent live-verification schema change through the environment's
migration owner and run `npm run db:generate` before starting the updated API.
In development, the Prisma live-verification migration resets non-warning legacy
schedules once; coordinate that data change separately for Go-owned databases. On the
first enabled scheduler startup, Verified/Failed sites without a due date are
scheduled from that time plus the configured interval (7 days by default), without
inventing check timestamps. Grace dates and already initialized schedules are
preserved on subsequent restarts. Changing timing settings affects subsequent checks,
not already persisted schedules. Polling can delay dispatch by up to one tick.
Multi-process scheduling requires the shared Redis cron lock.

Site failure blocks new campaigns when no Verified sites remain, new creative
domains, and new creative attachments (including the selected conversion site).
It does not change delivery, existing attachments, detachment, or resume.
Attachment selectors filter out unverified creative domains before pagination:
`GET /creatives?selector=true&excludeLineItemId=...` returns only usable creatives,
and returns an empty list if the line item's conversion site is unverified.
`GET /line-items?selectable=true&creativeId=...` returns no line items for an
unverified creative domain and excludes line items with unverified conversion sites.
Verified sites with a grace-period warning remain selectable. The normal Creative
Library and existing-attachment endpoints still include existing creatives.

## Geo location data (countries / states / cities / DMAs)

Full guide: [`data/geo/GEO-DATA-GUIDE.md`](./data/geo/GEO-DATA-GUIDE.md)

These commands live in **this API repo** (`api.dsp.com`), not in the UI repo.

### Which command to use? (exactly 3)

| Command                                 | When to use it                   | What it does                                         |
| --------------------------------------- | -------------------------------- | ---------------------------------------------------- |
| `npm run geo:build -- [targets]`        | Rebuild CSV file(s) from sources | Writes `data/geo/*` only — **no DB**                 |
| `npm run geo:load:dry-run -- [targets]` | Preview before writing           | Reports inserts/updates — **no DB write**            |
| `npm run geo:load -- [targets]`         | Apply catalog to MySQL           | Upsert + soft-deactivate missing — **never deletes** |

**Targets** (optional; default = all): `countries` · `states` · `cities` · `dmas` · `all`

```bash
# Full refresh (Jira complete datasets)
npm run geo:build
npm run geo:load:dry-run
npm run geo:load

# States only (e.g. after ISO subdivision rebuild) — fast
npm run geo:build -- states
npm run geo:load -- states

# Cities only
npm run geo:build -- cities
npm run geo:load:dry-run -- cities
npm run geo:load -- cities
```

Build/load **refuse incomplete city/state files** (city count must match cities5000; states must include all 50 US + full ISO top-level set from build meta).

Geo typeahead is DB-backed (max 20). Display/Video: available countries + **US-only** states/cities/DMAs. Text: every country.

Targeting avoids redundant location suggestions: selected countries are omitted
from state/city results, and selected states are omitted from city results.
`geo-options` accepts optional CSV `excludeCountries` (ISO alpha-2, e.g. `CA`)
and `excludeStates` (full subdivision codes, e.g. `US-FL`). State suggestions
include their nullable `code` for resolving saved selections. Exclusions apply
before the result limit and preserve channel restrictions. Existing positive
`countries`/`states` filters used by billing retain their original meaning.

Billing city suggestions filter `dsp_ref_geo_city.region_code` by the selected state's
`dsp_ref_geo_state.code` (for example, Miami uses `US-FL`). The basic reference seed
backfills missing region codes on its original cities without overwriting existing
mappings. For full country/state/city coverage, load the existing CSV datasets;
updating CSV files alone does not update the database. Reload the billing page after
loading to discard previously cached empty search results.

### Safe for existing data?

- Saved targeting on campaigns/profiles is **not** changed by these commands.
- Migration only **adds** columns (does not wipe old rows).
- Loader never deletes catalog rows; it can only mark missing ones inactive.

---

## Database schema and deployment

The API runs in one of two database modes, chosen by `USE_SHARED_DB` in `.env`:

- `USE_SHARED_DB=false` (default): the API owns the database. Prisma migrations
  manage the schema and startup runs the reference seed.
- `USE_SHARED_DB=true`: `DATABASE_URL` points at the shared database owned by the
  DSP backend (shared adcomDB). The backend's migrations
  (`ad.com-dsp/src/storage/mysql/migrations`) manage the schema; the Prisma client
  uses the same mappings as development, Prisma migration commands refuse to run,
  startup skips the reference seed, and `geo:load` uses `data/geo/staging`.

Before moving an environment onto the shared database, verify schema and
reference-data compatibility, set `USE_SHARED_DB=true` and the shared
`DATABASE_URL`, then run `npm run db:generate`.

- **Development:** run `npm run db:migrate:dev`, then `npm run db:generate`.
  Keep the existing Prisma migrations and review new ones. `npm run deploy:dev`
  applies existing migrations before generating the client and reloading PM2.
- **Staging:** set `NODE_ENV=staging` and `USE_SHARED_DB=true` in the API's `.env`,
  apply schema changes and required reference data through the owning team, and run
  `npm run deploy:staging`. It installs dependencies, generates the shared-DB
  Prisma Client with unprefixed table names, builds and reloads PM2 without
  running migrations. Startup skips the reference seed and logs that it was
  skipped. Ensure the PM2 process runs with the same values; inherited
  environment variables can override `.env`.
- **Production:** `npm run deploy` does not run migrations. With
  `USE_SHARED_DB=false`, startup still runs the reference
  seed. `npm start` runs `dist/server.js`.
- Never run `db:migrate`, `db:migrate:dev`, `db:deploy`, or `db:push` against
  staging or production. They refuse to run when `USE_SHARED_DB=true`. Do not mark
  the historical Prisma migrations as applied there just to satisfy migration
  status. Review external CI/CD and deployment hooks for migration commands too;
  they are outside this repository's control.

Keep the Go schema, the development migrations, and `prisma/schema.prisma`
aligned before releasing changes. To compare a target MySQL database with the
Prisma schema, set `DATABASE_URL` to a read-only account on that target and run
`npm run db:check-schema:shared` for the shared database or `npm run db:check-schema`
for an API-owned one. This Prisma 6 read-only diff returns 0 for no
differences, 2 for differences, and 1 for an error. Review differences manually:
extra Go-owned tables can appear in the diff, and Prisma cannot detect every
database feature or prove runtime compatibility. Do not execute the diff as SQL.
If using `prisma db pull` for inspection, use a temporary schema file and review
the result rather than overwriting the committed schema.

Use least-privilege database accounts for staging and production: grant only the
required table-level DML permissions, not schema-altering privileges. With
`USE_SHARED_DB=false`, the API seeds and updates reference rows at startup, including
deleting unsupported text-ad subtype rows. Normal API requests and jobs can also
modify data on the shared database. A successful connection log confirms
the `SELECT 1` check only, not schema compatibility or successful startup; it is
emitted at info level and may be filtered by `LOG_LEVEL`.

The checked-in Prisma schema maps tables and renamed columns directly to the
shared names in both modes. The local rename migration requires destination
table names to be unused; review any conflicts before applying it. Never apply
Prisma migrations to the shared Go-owned database. The local fee/date migration
sets the default `platform_fee` to 10 without changing existing fees, converts
flight dates only when their time is midnight, and remaps legacy creative and
optimization references. Resolve any non-midnight dates or in-use native formats
before applying it. MySQL DDL is not atomic across the migration: a failure can
leave earlier changes or temporary date checks in place. Back up and rehearse
recovery before applying it. The API and UI fee and reference changes require
the corresponding database changes and a coordinated deployment.

Advertiser and user IDs remain `BigInt` in Prisma; converting them to the shared
schema's signed `Int` types and aligning the remaining foreign keys and reference
values requires further work. The audit-log foreign key must remain deferred while
its historical actor references are unresolved.

Tests apply pending Prisma migrations and write test data:
run them only against a disposable test database, not the database used by the
local API. When `DATABASE_URL` already names a test database, the test setup uses
it even if `TEST_DATABASE_URL` is set. Table-name changes alone do not guarantee
that the shared database's columns, constraints, or required tables match the API schema.
In particular, signup and authenticated sessions require the `auth_session`
`act_as_*` columns; the database-owning team must add them before deployment if
they are missing. Otherwise signup can create an account but fail to create its
session.

## Common scripts

| Script                     | Purpose                                                      |
| -------------------------- | ------------------------------------------------------------ |
| `npm run dev`              | Start API in watch mode                                      |
| `npm run build`            | Compile TypeScript                                           |
| `npm run test`             | Run tests                                                    |
| `npm run db:up`            | Start local MySQL (Docker)                                   |
| `npm run db:migrate:dev`   | Create/apply development migrations                          |
| `npm run db:deploy`        | Apply migrations to a Prisma-owned development database only |
| `npm run db:status`        | Check Prisma migration history (development)                 |
| `npm run db:check-schema`  | Read-only database/schema diff                               |
| `npm run db:generate`      | Generate Prisma Client                                       |
| `npm run geo:build`        | Rebuild geo CSV files                                        |
| `npm run geo:load:dry-run` | Preview geo DB sync                                          |
| `npm run geo:load`         | Apply geo CSV → DB                                           |
