# Event Handling

The globalMOO API provides event notifications for important state changes and asynchronous operations.

## Event Format

Events follow this structure:

```json
{
    "id": 123,
    "created_at": "2025-01-31T10:00:00.000Z",
    "updated_at": "2025-01-31T10:00:00.000Z",
    "disabled_at": null,
    "name": "project.created",
    "subject": "optional-subject-id",
    "data": {
        // Event-specific data object
    }
}
```

## Event Types

| Event Name        | Description                | Data Type |
| ----------------- | -------------------------- | --------- |
| project.created   | New project created        | Project   |
| inverse.suggested | New inverse step suggested | Inverse   |

## SDK Event Handling

{% tabs %}
{% tab title="Python" %}

```python
from globalmoo.client import Client

client = Client()

# Handle webhook payload
event = client.handle_event(webhook_payload)

# Event data is automatically mapped to correct type
if event.name == "project.created":
    project = event.data  # Project object
    print(f"Project {project.id} created")
elif event.name == "inverse.suggested":
    inverse = event.data  # Inverse object
    print(f"Inverse step {inverse.iteration} suggested")
```

{% endtab %}

{% tab title="PHP" %}

```php
use GlobalMoo\Client;

$client = new Client();

// Handle webhook payload
$event = $client->handleEvent($webhookPayload);

// Event data is automatically mapped to correct type
switch ($event->name) {
    case 'project.created':
        $project = $event->data;  // Project object
        echo "Project {$project->id} created";
        break;
    case 'inverse.suggested':
        $inverse = $event->data;  // Inverse object
        echo "Inverse step {$inverse->iteration} suggested";
        break;
}
```

{% endtab %}

{% tab title="Node.js" %}

```javascript
const { Client } = require('globalmoo');

const client = new Client();

// Handle webhook payload
const event = client.handleEvent(webhookPayload);

// Event data is automatically mapped to correct type
switch (event.name) {
    case 'project.created':
        const project = event.data;  // Project object
        console.log(`Project ${project.id} created`);
        break;
    case 'inverse.suggested':
        const inverse = event.data;  // Inverse object
        console.log(`Inverse step ${inverse.iteration} suggested`);
        break;
}
```

{% endtab %}
{% endtabs %}

## Validation & Error Handling

Events are validated before processing:

1. Basic JSON validation
2. Required fields check
3. Event name validation
4. Data type mapping
5. Field type validation

Possible exceptions:

* InvalidArgumentException: Invalid JSON or missing fields
* InvalidEventException: Unknown event type
* ValidationException: Invalid data format

Example error handling:

```python
try:
    event = client.handle_event(payload)
except InvalidArgumentException as e:
    print(f"Invalid event format: {e}")
    # Log error, request retransmission
except InvalidEventException as e:
    print(f"Unknown event type: {e}")
    # Log error, notify administrators
except ValidationException as e:
    print(f"Invalid event data: {e}")
    # Log error, investigate data corruption
```

## Best Practices

1. Always validate event payloads
2. Use type-safe event handling
3. Implement idempotency checks
4. Log event processing
5. Handle errors gracefully
6. Process events asynchronously
7. Monitor event throughput

## Integration Example

Complete webhook handler example:

```python
from flask import Flask, request
from globalmoo.client import Client
from globalmoo.exceptions import GlobalMooException

app = Flask(__name__)
client = Client()

@app.route('/webhook', methods=['POST'])
def handle_webhook():
    try:
        # Get raw payload
        payload = request.get_data().decode('utf-8')
        
        # Process event
        event = client.handle_event(payload)
        
        # Handle specific events
        if event.name == "project.created":
            handle_new_project(event.data)
        elif event.name == "inverse.suggested":
            handle_inverse_suggestion(event.data)
            
        return {'status': 'success'}, 200
        
    except GlobalMooException as e:
        # Log error details
        print(f"Error processing webhook: {e}")
        return {'error': str(e)}, 400
        
def handle_new_project(project):
    """Handle new project creation event"""
    print(f"New project {project.id} created")
    # Add project setup logic
    
def handle_inverse_suggestion(inverse):
    """Handle new inverse suggestion event"""
    print(f"Inverse step {inverse.iteration} suggested")
    # Add inverse processing logic
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://globalmoo.gitbook.io/globalmoo-documentation/core/events.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
