# Active EMEA Tenant Monitor

Daily Lambda flow:

1. Select candidate tenants from the DevOps DB.
2. Query billing configs and Stripe payment methods through the DevOps billing proxy.
3. Use `cluster_metrics.py` to calculate `cluster_count` and `tenant_avg_qps`.
4. Extract `email_domain` and classify it through `domain_intelligence` cache or web search.
5. Upsert the latest result into `emea_active_tenants` by `tenant_id`.
6. Select tenants created in the last 24 hours, reuse domain intelligence, and upsert them into `emea_new_signup`.

Fan-out Lambda flow:

1. `fanout/dispatcher_function.py` selects active candidate tenants and new signups from the DevOps DB.
2. The dispatcher sends one SQS message per tenant to `EMEA-Tenants-Monitor-Fanout-Queue`.
3. `fanout/worker_function.py` consumes the queue and processes each tenant with the same enrichment and upsert logic.
4. The worker sends the existing scoring SQS message after each tenant is written or its failure is recorded.
5. Messages that still cannot be persisted after retries go to `EMEA-Tenants-Monitor-Fanout-DLQ`.

Required environment variables:

```text
DEVOPS_DB_HOST
DEVOPS_DB_PORT
DEVOPS_DB_USER
DEVOPS_DB_PASSWORD
DEVOPS_DB_NAME

TARGET_DB_HOST
TARGET_DATABASE_URL
TARGET_DB_PORT
TARGET_DB_USER
TARGET_DB_PASSWORD
TARGET_DB_NAME

DEVOPS_API_TOKEN
CLINIC_API_KEY
```

Optional environment variables:

```text
TENANT_SELECT_SQL
OPERATOR_EMAIL
OPENAI_API_KEY
OPENAI_WEB_SEARCH_MODEL
DOMAIN_INTELLIGENCE_TTL_DAYS
LLM_TIMEOUT_SECONDS
DEVOPS_BASE_URL
NEW_SIGNUP_SELECT_SQL
BILLING_REQUEST_INTERVAL_SECONDS
BILLING_RETRY_COUNT
```

The fan-out template supplies these task-specific variables:

```text
MONITOR_QUEUE_URL
SCORING_QUEUE_URL
```

Use `schema.sql` to create `emea_active_tenants`, `domain_intelligence`, and `emea_new_signup`.

For TiDB Serverless, prefer `TARGET_DATABASE_URL` for the target database. It follows the same pattern as `tidb-slack-ai-bot`: parse the database URL and connect with TLS 1.2 or newer. `DATABASE_URL` is also accepted as a fallback for the target DB.

## Deploy

`fanout-template.yaml` deploys the production fan-out resources from `fanout/`:

- `EMEA-Tenants-Monitor-Fanout-Dispatcher-Task`
- `EMEA-Tenants-Monitor-Fanout-Worker-Task`
- `EMEA-Tenants-Monitor-Fanout-Queue`
- `EMEA-Tenants-Monitor-Fanout-DLQ`

Production traffic uses the fan-out stack. The fan-out dispatcher runs daily at 15:30 Asia/Shanghai (07:30 UTC).

Build the fan-out stack:

```bash
sam build --template-file fanout-template.yaml
```

Deploy with the configured AWS profile and region:

```bash
sam deploy --guided --template-file .aws-sam/build/template.yaml \
  --profile 552185537300_DBaaS-DevUser-Role \
  --region us-west-2
```

Supply the database credentials and API keys as deployment parameters; do not commit them to the repository.
