# eb-event-integration

Part of **EB**

<!-- intent-backlink:auto -->

> 💡 **Path Selection**: This skill is one implementation path for [Integrate external services via events (e.g., DingTalk, Lark)](../../intent/eb-integrate-events/SKILL.md). If you're unsure which path to take, check the routing skill first.

# EventBridge Event Integration

## Capabilities Overview

| Sub-capability | Calling Mode | Description |
|----------------|--------------|-------------|
| Configure MySQL Source | Synchronous | Set up MySQL as an event source for change data capture. |
| Configure PostgreSQL CDC Source | Synchronous | Set up PostgreSQL as an event source for change data capture. |

## API Calling Patterns

### Authentication
Use Bearer Token authentication via the `Authorization` header.

- Header format: `Authorization: Bearer <your_api_key>`
- Environment variable: `EVENTBRIDGE_API_KEY`
- Note: Some examples reference `DASHSCOPE_API_KEY`, but for EventBridge Event Integration APIs, use `EVENTBRIDGE_API_KEY`.

### Service Endpoint
EventBridge Event Integration APIs use region-specific endpoints:

- Endpoint pattern: `https://eventbridge.<region>.aliyuncs.com`
- Common regions: `cn-hangzhou`, `cn-shanghai`, `cn-beijing`

### Synchronous Configuration Flow
Both MySQL and PostgreSQL source configurations follow a synchronous request-response pattern:

1. Send a POST request to the region-specific endpoint with source configuration parameters in the JSON body.
2. Include the `Authorization: Bearer <api_key>` header.
3. The service validates connectivity, permissions, and parameters immediately.
4. On success, returns a `200 OK` response with confirmation metadata.
5. On failure, returns an error code with details (see Error Handling).

No polling or async task ID is involved—configuration is applied atomically in one call.

## Parameter Reference

### Configure PostgreSQL CDC Source

| Parameter | Type | Required | Default | Constraints | Description |
|----------|------|----------|---------|-------------|-------------|
| RegionId | string | Yes | — | Valid Alibaba Cloud region ID | The ID of the region where the PostgreSQL instance resides. |
| HostName | string | Yes | — | — | The hostname or IP address of the PostgreSQL database server. |
| Port | integer | Yes | 5432 | 0–65535 | The port number of the PostgreSQL database server. |
| User | string | Yes | — | — | The username for connecting to the PostgreSQL database. Must have replication privilege. |
| Password | string | Yes | — | — | The password for the PostgreSQL database user. |
| DatabaseName | string | Yes | — | — | The name of the PostgreSQL database to capture change events from. |
| SchemaName | string | No | — | — | The PostgreSQL schema to monitor for change events. |
| TableNames | string | No | — | — | The table or tables to monitor (comma-separated). |
| SnapshotMode | string | No | — | `initial`, `never`, `always` | Snapshot strategy when the connector starts. |
| NetworkType | string | No | — | `PublicNetwork`, `PrivateNetwork` | Network type for connecting to the PostgreSQL instance. |
| VpcId | string | No | — | — | VPC ID (required if NetworkType is `PrivateNetwork`). |
| VSwitchIds | string | No | — | — | vSwitch ID(s) in the VPC (comma-separated if multiple). |
| SecurityGroupId | string | No | — | — | Security group ID associated with the VPC. |

### Configure MySQL Source
Parameter details are not explicitly listed in the extracted documentation, but the configuration follows similar patterns to PostgreSQL, including host, port, credentials, database, tables, and network settings. Refer to the console UI or API reference for exact fields.

## Code Examples

### Configure PostgreSQL CDC Source - Python - cn-hangzhou

```python
import os
import requests
import json

api_key = os.getenv("EVENTBRIDGE_API_KEY")
url = "https://eventbridge.cn-hangzhou.aliyuncs.com/configurePostgreSQLSource"

headers = {
    "Authorization": f"Bearer {api_key}",
    "Content-Type": "application/json"
}

payload = {
    "RegionId": "cn-hangzhou",
    "HostName": "pg.example.com",
    "Port": 5432,
    "User": "cdc_user",
    "Password": "secure_password",
    "DatabaseName": "inventory",
    "SchemaName": "public",
    "TableNames": "products,orders",
    "SnapshotMode": "initial",
    "NetworkType": "PublicNetwork"
}

response = requests.post(url, headers=headers, data=json.dumps(payload))
print(response.status_code)
print(response.json())
```

### Configure MySQL Source via Console Equivalent - Bash (curl)

```bash
curl -X POST \
  https://eventbridge.cn-shanghai.aliyuncs.com/configureMySQLSource \
  -H "Authorization: Bearer $EVENTBRIDGE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "RegionId": "cn-shanghai",
    "HostName": "mysql.internal",
    "Port": 3306,
    "User": "eb_cdc",
    "Password": "password123",
    "DatabaseName": "sales_db",
    "TableNames": "customers,transactions",
    "BinlogFormat": "ROW",
    "NetworkType": "PrivateNetwork",
    "VpcId": "vpc-abc123",
    "VSwitchIds": "vsw-def456",
    "SecurityGroupId": "sg-789xyz"
  }'
```

### Validate PostgreSQL Replication Privilege - Python

```python
# This example checks prerequisites before configuration
import psycopg2

def check_replication_privilege(host, port, user, password, db):
    conn = psycopg2.connect(
        host=host,
        port=port,
        user=user,
        password=password,
        dbname=db
    )
    cur = conn.cursor()
    cur.execute("SHOW wal_level;")
    wal_level = cur.fetchone()[0]
    cur.execute("SELECT rolreplication FROM pg_roles WHERE rolname = %s;", (user,))
    has_replication = cur.fetchone()[0]
    conn.close()
    return wal_level == 'logical' and has_replication

# Usage
if check_replication_privilege("pg.example.com", 5432, "cdc_user", "pass", "inventory"):
    print("PostgreSQL is ready for CDC.")
else:
    print("Configure logical replication and user privileges first.")
```

### List Supported Regions - Bash

```bash
# EventBridge Event Integration is available in these regions:
echo "Supported regions: cn-hangzhou, cn-shanghai, cn-beijing, ap-southeast-1, cn-shanghai"
```

## Pricing & Billing

### Billing Model
Per-request billing for source configuration and ongoing CDC event capture.

### Price Reference

| Tier | Input Price | Output Price |
|------|-------------|--------------|
| default | ¥0.0005 per request | ¥0.0003 per request |
| EventBridge CDC | ¥0.0001 per request | ¥0.0001 per request |

### Free Tier
- MySQL/General: 10,000 free requests per month
- PostgreSQL CDC: 1,000 free requests per month

### Usage Limits
- Account-level QPS limit: 100 requests per second
- PostgreSQL CDC: Maximum 8K tokens per request

### Billing Notes
- Data transfer costs apply based on volume.
- Async tasks (if used in other contexts) are billed on completion.
- CDC pricing includes both initial snapshot and continuous change streaming.

## FAQ

Q: What database privileges are required for CDC?
A: For PostgreSQL, the user must have the `REPLICATION` attribute and access to logical replication slots. For MySQL, the user needs `REPLICATION CLIENT`, `REPLICATION SLAVE`, and `SELECT` on monitored tables, with `binlog_format=ROW`.

Q: Can I connect to databases in a VPC?
A: Yes. Set `NetworkType` to `PrivateNetwork` and provide `VpcId`, `VSwitchIds`, and `SecurityGroupId` to allow EventBridge to access your private database instance.

Q: How are table changes represented in events?
A: Each row change (INSERT, UPDATE, DELETE) generates a structured event containing before/after images, transaction metadata, and operation type. The exact schema depends on the source database and configuration.

Q: Is SSL/TLS supported for database connections?
A: Yes. EventBridge enforces encrypted connections by default for public endpoints. For VPC connections, encryption is handled within the secure network boundary.

Q: What happens if the database goes offline?
A: The CDC connector will retry with exponential backoff. Events are buffered during short outages. Prolonged disconnections may require reconfiguration or snapshot resumption based on `SnapshotMode`.

## Environment Requirements

- Set the API key: `export EVENTBRIDGE_API_KEY=your_access_key_here`
- Required SDKs: Standard HTTP client (e.g., `requests` in Python, `OkHttp` in Java)
- No specific runtime version requirements beyond standard TLS 1.2+ support