# eb-event-tracing

Part of **EB**

# EventBridge Event Tracing

## Capabilities Overview

| Sub-capability | Calling Mode | Description |
|----------------|--------------|-------------|
| Query Event Trace Data | Synchronous | Retrieve comprehensive trace data for event flows within a time range, including event ID, source, type, and delivery time. |
| Discover Event Source Schema | Synchronous | Automatically discover the schema and sample data of a MySQL event source, including tables, columns, and records. |

## API Calling Patterns

### Authentication
Use **Bearer Token** authentication as the primary method.

- Include the header: `Authorization: Bearer <your_api_key>`
- Store your API key in the environment variable: `DASHSCOPE_API_KEY`
- This method is used consistently across all EventBridge tracing APIs.

### Service Endpoint
The APIs use region-specific endpoints with the following pattern:

- China regions: `https://api.aliyun.com/api/eventbridge/2020-04-01/{operation}`
- International regions: `https://api.alibabacloud.com/api/eventbridge/2020-04-01/{operation}`

Common regions include `cn-hangzhou`, `cn-shanghai`, and `ap-southeast-1`.

### Synchronous Request Pattern
Both supported operations (`QueryTracedEvents` and `DiscoverEventSource`) follow a synchronous request-response pattern:

1. Send an HTTP request (GET for `QueryTracedEvents`, POST for `DiscoverEventSource`) to the appropriate endpoint.
2. Include required parameters in the query string or request body.
3. Receive a complete JSON response immediately (no polling or streaming).
4. Parse the `Data` field for results; check `Success` and `Code` for status.

No asynchronous or streaming patterns are used in this domain.

## Parameter Reference

### Query Event Trace Data

| Parameter | Type | Required | Default | Constraints | Description |
|----------|------|----------|---------|-------------|-------------|
| EventBusName | string | Yes | — | — | The name of the event bus. |
| StartTime | integer | Yes | — | — | The beginning of the time range (UNIX timestamp in milliseconds). |
| EndTime | integer | Yes | — | — | The end of the time range (UNIX timestamp in milliseconds). |
| Limit | integer | No | — | max 100 | Maximum number of entries per page. |
| NextToken | string | No | — | — | Token for retrieving the next page of results. |
| EventSource | string | No | — | — | The name of the event source. |
| Subject | string | No | — | — | The event subject. |
| EventType | string | No | — | — | The event type. |
| MatchedRule | string | No | — | — | The name of the matched rule. |

### Discover Event Source Schema

| Parameter | Type | Required | Default | Constraints | Description |
|----------|------|----------|---------|-------------|-------------|
| RegionId | string | Yes | — | — | The region ID. |
| HostName | string | Yes | — | — | The database endpoint. |
| Port | integer | Yes | — | — | The connection port of the database. |
| DatabaseName | string | Yes | — | — | The database name. |
| TableName | string | Yes | — | — | Table name in `${DatabaseName}.${TableName}` format. |
| User | string | Yes | — | — | The database username. |
| Password | string | Yes | — | — | The database password. |
| NetworkType | string | Yes | — | one of: PrivateNetwork, PublicNetwork | The network type. |
| VpcId | string | Yes | — | — | The ID of the Virtual Private Cloud (VPC). |
| VSwitchIds | string | Yes | — | — | The vSwitch ID. |
| SecurityGroupId | string | Yes | — | — | The security group ID. |
| Offset | string | Yes | — | — | The offset for paging the query results. |
| Limit | string | Yes | — | — | The maximum number of entries per page. |
| SourceMySQLParameters | object | No | — | — | The MySQL source parameters. |

## Code Examples

### Query Event Trace Data - curl - China

```bash
curl -X GET "https://api.aliyun.com/api/eventbridge/2020-04-01/QueryTracedEvents?EventBusName=test-custom-bus&StartTime=1661773500000&EndTime=1661773600000&Limit=10" \
  -H "Authorization: Bearer $DASHSCOPE_API_KEY" \
  -H "Content-Type: application/json"
```

### Discover MySQL Event Source Schema - curl - International

```bash
curl -X POST "https://api.alibabacloud.com/api/eventbridge/2020-04-01/DiscoverEventSource" \
  -H "Authorization: Bearer $DASHSCOPE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "RegionId": "ap-southeast-1",
    "HostName": "rm-xxxx.mysql.rds.aliyuncs.com",
    "Port": 3306,
    "DatabaseName": "database1",
    "TableName": "database1.ai_festival_gift_ranking",
    "User": "admin",
    "Password": "secure_password",
    "NetworkType": "PrivateNetwork",
    "VpcId": "vpc-xxxx",
    "VSwitchIds": "vsw-xxxx",
    "SecurityGroupId": "sg-xxxx",
    "Offset": "0",
    "Limit": "10"
  }'
```

### Parse Query Response - Python

```python
import os
import json

# Example response parsing after calling QueryTracedEvents
response_json = {
  "Message": "",
  "RequestId": "d9e4628b-8b34-4f33-82be-5aac50aac0ba",
  "Data": {
    "NextToken": "1000",
    "Events": [
      {
        "EventId": "07E-1OCckaVzNB92BIFFh4xgydOF1wd",
        "EventBusName": "test-custom-bus",
        "EventReceivedTime": 1661773573100,
        "EventSource": "acs.resourcemanager",
        "EventType": "eventbridge:Events:HTTPEvent"
      }
    ],
    "Total": 6
  },
  "Code": "200",
  "Success": True
}

if response_json["Success"]:
    for event in response_json["Data"]["Events"]:
        print(f"Event ID: {event['EventId']}, Source: {event['EventSource']}")
    if "NextToken" in response_json["Data"]:
        print(f"Next page token: {response_json['Data']['NextToken']}")
```

### Handle Discovery Response - Python

```python
# Example parsing of DiscoverEventSource response
discovery_response = {
  "Code": "Success",
  "Data": {
    "SourceMySQLDiscovery": {
      "DatabaseNames": ["database1"],
      "TableNames": ["ai_festival_gift_ranking"],
      "TableSchema": {
        "TableName": "map",
        "Columns": [
          {
            "Field": "id",
            "IsNull": "NO",
            "Extra": "auto_increment",
            "Type": "int",
            "Key": "PRI"
          }
        ]
      },
      "SimpleData": "[{\"is_active\":\"1\",\"name\":\"0c0c5d1a-e844-44a8-902d-4f62cbcb0479\",\"id\":\"21\"}]"
    }
  },
  "Message": "success",
  "RequestId": "C7043799-F4DA-5290-9249-97C35987****",
  "Success": True
}

if discovery_response["Success"]:
    schema = discovery_response["Data"]["SourceMySQLDiscovery"]
    print("Discovered tables:", schema["TableNames"])
    print("Sample data:", json.loads(schema["SimpleData"]))
```

## Response Format

```json
{
  "Message": "EventBusNotExist",
  "RequestId": "d9e4628b-8b34-4f33-82be-5aac50aac0ba",
  "Data": {
    "NextToken": "1000",
    "Events": [
      {
        "EventId": "07E-1OCckaVzNB92BIFFh4xgydOF1wd",
        "EventBusName": "test-custom-bus",
        "EventReceivedTime": 1661773573100,
        "EventSource": "acs.resourcemanager",
        "EventType": "eventbridge:Events:HTTPEvent"
      }
    ],
    "Total": 6
  },
  "Code": "200",
  "Success": true
}
```

**Key Fields**:
- `Data.Events` — List of traced events with IDs, sources, types, and timestamps
- `Data.NextToken` — Token for paginated results; absent if no more pages
- `Data.Total` — Total number of matching events (may exceed page limit)
- `RequestId` — Unique identifier for troubleshooting
- `Success` — Boolean indicating whether the request succeeded

## Error Handling

| Error Code | Description | Recommended Action |
|------------|-------------|---------------------|
| 403 | Service not enable | Ensure the EventBridge service is activated in your Alibaba Cloud account. |

## Common Questions

Q: How do I paginate through large result sets in `QueryTracedEvents`?
A: Use the `NextToken` from the response in subsequent requests as the `NextToken` parameter. Continue until the response no longer includes a `NextToken`.

Q: What time format does `StartTime` and `EndTime` use?
A: Both parameters require UNIX timestamps in **milliseconds**, not seconds. For example, `1661773573100` represents August 29, 2022, 19:46:13.100 UTC.

Q: Can I discover non-MySQL event source schemas?
A: The current `DiscoverEventSource` API only supports MySQL databases. Support for other sources may be added in future versions.

Q: Why am I getting a 403 error even with a valid API key?
A: The 403 "Service not enable" error indicates that the EventBridge service isn't activated in your Alibaba Cloud account. Visit the EventBridge console to enable it before making API calls.

Q: Are there rate limits on these tracing APIs?
A: The documentation does not specify explicit rate limits. However, as with most Alibaba Cloud APIs, excessive usage may be throttled. Implement standard retry logic with exponential backoff if you encounter transient errors.

## Pricing & Billing

### Billing Model
Billing is based on **per-request** usage for both `QueryTracedEvents` and `DiscoverEventSource`.

### Price Reference
Pricing details are not provided in the current documentation. Consult the official Alibaba Cloud EventBridge pricing page for up-to-date rates.

### Free Tier
No free tier information is available in the extracted documentation.

### Usage Limits
No specific usage quotas or limits are documented for these tracing APIs.

### Billing Notes
Since billing is per-request, each call to `QueryTracedEvents` or `DiscoverEventSource` counts as one billable request, regardless of the number of results returned.