# Vectry Event Subscription

> Dispara la ejecución del workflow a partir de eventos internos del sistema (Event Bus).

Source: https://docs.sommatic.ai/es/nodes/event.trigger/

- Slug: `event.trigger`
- Familia: Triggers
- Versión: 1.0.0
- Estado: Experimental. Todavía nada se suscribe al bus de eventos, así que este trigger nunca inicia una ejecución por sí solo; no lee `filters` ni `since`.
- Ejecución: async

Dispara la ejecución del workflow a partir de eventos internos del sistema (Event Bus).

Este trigger se suscribe al Vectry Causal Event Bus. Escucha eventos de negocio o del sistema concretos (p. ej., "Order Created", "User Signup") e inicia el workflow cuando ocurre un evento que coincide.

**Características:**
- **Filtrado:** Suscríbete solo a los eventos que cumplan criterios concretos (dominio, entidad, etiqueta).
- **Reproducción:** Procesa eventos históricos ("since") o solo los nuevos.
- **Coincidencia de patrones:** Dispara ante secuencias de eventos complejas (si está configurado).

**Casos de uso:**
- Enviar un correo de bienvenida cuando ocurre un evento 'UserCreated'.
- Auditar transacciones de alto valor.

## Configuración

- `filters` (array<object>, obligatorio): Criterios de coincidencia de los eventos.
- `since` (string, opcional): Marca de tiempo (ISO) o "now". Por defecto: `now`.

Su configuración muestra los ajustes de ejecución compartidos, pero este nodo aún no aplica reintentos (`retryOnFail`, `maxTries`). Ningún nodo aplica `continueOnFail`.

## Puertos de salida

- `out` (por defecto): Event Received
- `error`: Error

## Contrato de salida

- `event_id` (string, opcional)
- `source` (string, opcional)
- `type` (string, opcional)
- `payload` (object, opcional)

## En expresiones

Lo que un nodo posterior puede leer de la salida de este nodo con `$("Vectry Event Subscription").item.json.<ruta>` (escribe la etiqueta de tu nodo en lugar de `Vectry Event Subscription`). **Editor** marca las rutas que sugiere el editor de workflows en Previous Nodes (el contrato de salida); **Worker** marca las rutas que el worker devuelve de verdad por `out`, según la salida que muestra Puertos.

- `$("Vectry Event Subscription").item.json.event_id` (string) = `"evt_01JDX4Q8M2"`
- `$("Vectry Event Subscription").item.json.source` (string) = `"vectry"`
- `$("Vectry Event Subscription").item.json.type` (string) = `"order.created"`
- `$("Vectry Event Subscription").item.json.payload` (object) = `{…}`
- `$("Vectry Event Subscription").item.json.payload.order_id` (string) = `"ord_123"` (El editor no la sugiere)
- `$("Vectry Event Subscription").item.json.payload.total` (number) = `129.99` (El editor no la sugiere)
- `$("Vectry Event Subscription").item.json.payload.currency` (string) = `"USD"` (El editor no la sugiere)


## Cómo funciona

Nodo de entrada para workflows impulsados por eventos. Reorganiza la entrada de la ejecución en `{ event_id, source, type, payload }`; en esta versión no se suscribe al bus de eventos y sus filtros no se aplican.

1. Qué lo inicia: en esta versión ningún componente del backend se suscribe al bus de eventos para este nodo. El workflow se ejecuta cuando se inicia de forma explícita (ejecución manual o solicitud de ejecución) con una entrada con forma de evento.
2. Lee el ítem de entrada tal cual; la configuración del nodo no se lee ni se resuelve.
3. Entrega `event_id` (por defecto `unknown`), `source` (por defecto `vectry`), `type` (por defecto `unknown`) y `payload`: el campo `payload` de la entrada si existe; si no, la entrada completa.

## En un workflow

### Nodo

```json
{
  "node_id": "node-order-created",
  "label": "Order created",
  "operator_slug": "event.trigger",
  "operator_version": "1.0.0",
  "config": {
    "filters": [
      {
        "system_domain": "sales",
        "system_entity": "order",
        "operation": "created"
      }
    ],
    "since": "now"
  }
}
```

### Envelope

```json
{
  "ok": true,
  "data": {
    "event_id": "evt_01JDX4Q8M2",
    "source": "vectry",
    "type": "order.created",
    "payload": {
      "order_id": "ord_123",
      "total": 129.99,
      "currency": "USD"
    }
  },
  "port": "out"
}
```

## Puertos de salida (comportamiento en el código)

### `out`

Siempre, salvo que ocurra una excepción inesperada.

```json
{
  "event_id": "evt_01JDX4Q8M2",
  "source": "vectry",
  "type": "order.created",
  "payload": {
    "order_id": "ord_123",
    "total": 129.99,
    "currency": "USD"
  }
}
```

### `error`

Solo ante una excepción inesperada al leer la entrada; la salida es `{ error, response }`. No se alcanza en el uso normal.

```json
{
  "error": "<exception message>",
  "response": null
}
```

## Comportamiento en el código

- `filters`: Declarado y obligatorio en el esquema, pero no se lee: no se filtra ningún evento. `since` tampoco se lee.

## Notas y límites

- Usa este nodo como punto de entrada tipado: inicia el workflow con `{ event_id, source, type, payload }` y lee los datos del evento más adelante en `$json.payload`.
- Con datos de muestra el motor omite el nodo y entrega la entrada de muestra sin cambios por `out`.


## Contratos (JSON Schema)

### All (`*.definition.js`)

```json
{
  "slug": "event.trigger",
  "name": "Vectry Event Subscription",
  "category": "triggers",
  "version": "1.0.0",
  "description": "Trigger workflow execution based on internal system events (Event Bus).\n\n  This trigger subscribes to the Vectry Causal Event Bus. It listens for specific business or system events (e.g., \"Order Created\", \"User Signup\") and initiates the workflow when a matching event occurs.\n\n  **Features:**\n  - **Filtering:** Subscribe only to events matching specific criteria (domain, entity, tag).\n  - **Replay:** Process historical events (\"since\") or only new ones.\n  - **Pattern Matching:** Trigger on complex event sequences (if configured).\n\n  **Use Cases:**\n  - Sending a Welcome Email when a 'UserCreated' event occurs.\n  - Auditing high-value transactions.",
  "capabilities": [
    "event-subscription",
    "internal-bus",
    "pubsub",
    "vectry"
  ],
  "config_schema": {
    "type": "object",
    "required": [
      "filters"
    ],
    "properties": {
      "filters": {
        "type": "array",
        "title": "Event Filters",
        "description": "Match criteria for events.",
        "items": {
          "type": "object",
          "properties": {
            "system_domain": {
              "type": "string",
              "title": "Domain"
            },
            "system_entity": {
              "type": "string",
              "title": "Entity"
            },
            "operation": {
              "type": "string",
              "title": "Operation"
            },
            "tags": {
              "type": "array",
              "items": {
                "type": "string"
              }
            }
          }
        }
      },
      "since": {
        "type": "string",
        "title": "Start From",
        "default": "now",
        "description": "Timestamp (ISO) or \"now\"."
      },
      "execution": {
        "type": "object",
        "title": "Execution Settings",
        "properties": {
          "alwaysOutputData": {
            "type": "boolean",
            "title": "Always Output Data",
            "description": "Always output data, even on error (if configured).",
            "default": false
          },
          "retryOnFail": {
            "type": "boolean",
            "title": "Retry On Fail",
            "description": "Retry the execution if it fails.",
            "default": false
          },
          "maxTries": {
            "type": "integer",
            "title": "Max Retries",
            "description": "Number of retries.",
            "default": 3,
            "displayOptions": {
              "show": {
                "retryOnFail": [
                  true
                ]
              }
            }
          },
          "waitBetweenTries": {
            "type": "integer",
            "title": "Wait Between Retries (ms)",
            "default": 1000,
            "displayOptions": {
              "show": {
                "retryOnFail": [
                  true
                ]
              }
            }
          },
          "continueOnFail": {
            "type": "boolean",
            "title": "Continue On Fail",
            "description": "Do not crash workflow on error.",
            "default": false
          },
          "timeout_ms": {
            "type": "integer",
            "title": "Timeout (ms)",
            "description": "Max execution time for this node before it is killed, in milliseconds. Honored by long-running operators (e.g. OCR/extraction, inline code). Default 300000 (5 min).",
            "default": 300000
          }
        }
      }
    }
  },
  "input_contract_schema": null,
  "output_contract_schema": {
    "type": "object",
    "description": "The event payload.",
    "properties": {
      "event_id": {
        "type": "string"
      },
      "source": {
        "type": "string"
      },
      "type": {
        "type": "string"
      },
      "payload": {
        "type": "object"
      }
    }
  },
  "ports": [
    {
      "port_id": "out",
      "label": "Event Received",
      "is_default": true
    },
    {
      "port_id": "error",
      "label": "Error"
    }
  ],
  "execution_mode": "async",
  "tags": [
    "vectry",
    "events",
    "bus",
    "reactive"
  ],
  "is_stateful": false,
  "publisher": {
    "identity": "org_sommatic_ai",
    "profile": {
      "name": "Sommatic AI",
      "verified": true,
      "url": "https://me.veripass.com/sommatic",
      "logo_url": null
    }
  }
}
```

### config_schema

```json
{
  "type": "object",
  "required": [
    "filters"
  ],
  "properties": {
    "filters": {
      "type": "array",
      "title": "Event Filters",
      "description": "Match criteria for events.",
      "items": {
        "type": "object",
        "properties": {
          "system_domain": {
            "type": "string",
            "title": "Domain"
          },
          "system_entity": {
            "type": "string",
            "title": "Entity"
          },
          "operation": {
            "type": "string",
            "title": "Operation"
          },
          "tags": {
            "type": "array",
            "items": {
              "type": "string"
            }
          }
        }
      }
    },
    "since": {
      "type": "string",
      "title": "Start From",
      "default": "now",
      "description": "Timestamp (ISO) or \"now\"."
    },
    "execution": {
      "type": "object",
      "title": "Execution Settings",
      "properties": {
        "alwaysOutputData": {
          "type": "boolean",
          "title": "Always Output Data",
          "description": "Always output data, even on error (if configured).",
          "default": false
        },
        "retryOnFail": {
          "type": "boolean",
          "title": "Retry On Fail",
          "description": "Retry the execution if it fails.",
          "default": false
        },
        "maxTries": {
          "type": "integer",
          "title": "Max Retries",
          "description": "Number of retries.",
          "default": 3,
          "displayOptions": {
            "show": {
              "retryOnFail": [
                true
              ]
            }
          }
        },
        "waitBetweenTries": {
          "type": "integer",
          "title": "Wait Between Retries (ms)",
          "default": 1000,
          "displayOptions": {
            "show": {
              "retryOnFail": [
                true
              ]
            }
          }
        },
        "continueOnFail": {
          "type": "boolean",
          "title": "Continue On Fail",
          "description": "Do not crash workflow on error.",
          "default": false
        },
        "timeout_ms": {
          "type": "integer",
          "title": "Timeout (ms)",
          "description": "Max execution time for this node before it is killed, in milliseconds. Honored by long-running operators (e.g. OCR/extraction, inline code). Default 300000 (5 min).",
          "default": 300000
        }
      }
    }
  }
}
```

### output_contract_schema

```json
{
  "type": "object",
  "description": "The event payload.",
  "properties": {
    "event_id": {
      "type": "string"
    },
    "source": {
      "type": "string"
    },
    "type": {
      "type": "string"
    },
    "payload": {
      "type": "object"
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "out",
    "label": "Event Received",
    "is_default": true
  },
  {
    "port_id": "error",
    "label": "Error"
  }
]
```
