Skip to content

Webhook

Invia da Potato notifiche webhook HTTP firmate con HMAC per 7 tipi di evento di annotazione, con ritentativi a backoff esponenziale, monitoraggio da admin e verifica in Python e Node.

Novità della v2.4.0

I webhook permettono a Potato di avvisare sistemi esterni quando si verifica un evento di annotazione, senza bisogno di polling. Puoi collegarti a pipeline di dati, far scattare alert, aggiornare dashboard o avviare in automatico l'elaborazione a valle.

Panoramica

Potato invia una richiesta HTTP POST all'endpoint che hai configurato ogni volta che scatta un evento supportato. I payload sono in JSON e firmati con HMAC-SHA256, così puoi verificare che arrivino davvero dalla tua istanza di Potato.

La consegna dei webhook è del tutto non bloccante: le richieste di annotazione non vengono mai rallentate dai webhook in volo. Le consegne fallite vengono ritentate con backoff esponenziale.

Configurazione

Aggiungi una sezione webhooks alla configurazione YAML:

yaml
webhooks:
  enabled: true
  endpoints:
    - name: "my-pipeline"
      url: "https://your-system.example.com/potato-events"
      secret: "your-signing-secret"        # optional but recommended
      events:
        - annotation.created
        - item.fully_annotated
        - task.completed
      active: true
      timeout: 10

Più endpoint

Puoi configurare più endpoint, ciascuno con le proprie sottoscrizioni agli eventi:

yaml
webhooks:
  enabled: true
  endpoints:
    - name: "data-pipeline"
      url: "https://pipeline.example.com/annotations"
      secret: ${WEBHOOK_SECRET_1}
      events:
        - annotation.created
        - item.fully_annotated
    - name: "slack-alerts"
      url: "https://hooks.slack.com/services/..."
      events:
        - task.completed
        - quality.attention_check_failed
    - name: "catch-all"
      url: "https://logging.example.com/potato"
      events:
        - "*"          # subscribe to all events

Tipi di evento

EventoScatta quando
annotation.createdUn annotatore invia un'etichetta per un'istanza
annotation.updatedUn annotatore modifica un'etichetta già inviata
item.fully_annotatedUn'istanza raggiunge il numero di annotazioni sovrapposte richiesto
task.completedTutte le istanze del task sono state annotate per intero
user.phase_completedUn annotatore completa una fase (flusso di lavoro della modalità solo)
quality.attention_check_failedUn annotatore non supera un controllo di attenzione
webhook.testAttivato a mano dall'API di amministrazione per fare prove

Usa "*" per sottoscrivere tutti i tipi di evento, presenti e futuri.

Formato dei payload

Tutti gli eventi condividono la stessa struttura di base:

json
{
  "event_id": "evt_01HXYZ...",
  "event_type": "annotation.created",
  "timestamp": "2026-03-17T14:23:01Z",
  "task_name": "sentiment-study",
  "data": {
    ...
  }
}

Payload di annotation.created

json
{
  "event_type": "annotation.created",
  "data": {
    "annotator_id": "user123",
    "instance_id": "doc_042",
    "annotation": {
      "sentiment": "positive",
      "confidence": "high"
    },
    "submitted_at": "2026-03-17T14:23:01Z"
  }
}

Payload di item.fully_annotated

json
{
  "event_type": "item.fully_annotated",
  "data": {
    "instance_id": "doc_042",
    "annotator_count": 3,
    "annotations": [
      {"annotator_id": "user1", "sentiment": "positive"},
      {"annotator_id": "user2", "sentiment": "positive"},
      {"annotator_id": "user3", "sentiment": "neutral"}
    ]
  }
}

Payload di task.completed

json
{
  "event_type": "task.completed",
  "data": {
    "task_name": "sentiment-study",
    "total_instances": 500,
    "total_annotations": 1500,
    "completed_at": "2026-03-17T15:00:00Z"
  }
}

Verifica delle firme

Quando è configurato un secret, Potato firma ogni richiesta secondo Standard Webhooks (HMAC-SHA256). Vengono inclusi tre header:

HeaderValore
webhook-idID univoco della consegna
webhook-timestampTimestamp Unix della consegna
webhook-signatureFirma HMAC-SHA256

Verifica in Python

python
import hmac
import hashlib
import time
 
def verify_webhook(payload_bytes: bytes, headers: dict, secret: str) -> bool:
    webhook_id = headers.get("webhook-id", "")
    timestamp = headers.get("webhook-timestamp", "")
    signature = headers.get("webhook-signature", "")
 
    # Reject stale requests (older than 5 minutes)
    if abs(time.time() - int(timestamp)) > 300:
        return False
 
    signed_content = f"{webhook_id}.{timestamp}.{payload_bytes.decode()}"
    expected = hmac.new(
        secret.encode(),
        signed_content.encode(),
        hashlib.sha256
    ).hexdigest()
 
    return hmac.compare_digest(f"v1,{expected}", signature)

Verifica in Node.js

javascript
const crypto = require('crypto');
 
function verifyWebhook(payload, headers, secret) {
  const webhookId = headers['webhook-id'];
  const timestamp = headers['webhook-timestamp'];
  const signature = headers['webhook-signature'];
 
  // Reject stale requests
  if (Math.abs(Date.now() / 1000 - parseInt(timestamp)) > 300) {
    return false;
  }
 
  const signedContent = `${webhookId}.${timestamp}.${payload}`;
  const expected = crypto
    .createHmac('sha256', secret)
    .update(signedContent)
    .digest('hex');
 
  return crypto.timingSafeEqual(
    Buffer.from(`v1,${expected}`),
    Buffer.from(signature)
  );
}

Comportamento dei ritentativi

Le consegne fallite (risposta diversa da 2xx oppure timeout) vengono ritentate in automatico:

TentativoAttesa
1 (iniziale)Immediato
25 secondi
330 secondi
45 minuti
530 minuti
61 ora

Dopo 6 tentativi falliti, la consegna viene marcata come fallita in modo definitivo. La coda dei ritentativi è salvata su SQLite in {output_dir}/.webhooks/webhook_retries.db, quindi i ritentativi in sospeso sopravvivono al riavvio del server.

Monitoraggio e prove

API di amministrazione

Controlla lo stato e le statistiche dei webhook:

bash
# List all webhooks and their delivery statistics
curl -H "X-API-Key: $ADMIN_API_KEY" \
  http://localhost:8000/admin/api/webhooks

Risposta:

json
{
  "endpoints": [
    {
      "name": "my-pipeline",
      "url": "https://...",
      "events": ["annotation.created"],
      "active": true,
      "stats": {
        "total_emitted": 1240,
        "total_failed": 3,
        "pending_retries": 0,
        "last_success": "2026-03-17T14:23:01Z"
      }
    }
  ]
}

Inviare un webhook di prova

bash
curl -X POST -H "X-API-Key: $ADMIN_API_KEY" \
  http://localhost:8000/admin/api/webhooks/test \
  -H "Content-Type: application/json" \
  -d '{"endpoint_name": "my-pipeline"}'

Questo comando invia subito un evento webhook.test all'endpoint indicato.

Riferimento completo di configurazione

yaml
webhooks:
  enabled: true
  endpoints:
    - name: string           # unique name for this endpoint
      url: string            # HTTPS URL to POST to
      secret: string         # optional HMAC secret for signature verification
      events:                # list of event types, or ["*"] for all
        - annotation.created
      active: true           # set false to disable without removing
      timeout: 10            # request timeout in seconds (default: 10)
      max_retries: 6         # max retry attempts (default: 6)

Approfondimenti

Per i dettagli implementativi, vedi la documentazione sorgente.