Alerts API - arilonUK/iotagentmesh GitHub Wiki

Alerts API

The Alerts API provides comprehensive alert management for IoT devices, including rule configuration, notification handling, and automated response systems within the IoT Agent Mesh platform.

Overview

The alert system enables:

  • Flexible rule-based alerting on telemetry data
  • Multi-channel notification delivery (email, SMS, webhook)
  • Alert severity levels and escalation policies
  • Automated acknowledgment and resolution workflows
  • Historical alert tracking and analytics
  • Integration with external monitoring systems

Base Endpoint

/rest/v1/alerts
/rest/v1/alert-rules

Authentication

All endpoints require JWT authentication with appropriate organization access permissions.

Required Headers:

Authorization: Bearer YOUR_JWT_TOKEN
apikey: YOUR_SUPABASE_ANON_KEY
Content-Type: application/json

Alert Rules Management

Create Alert Rule

Define a new alert rule for monitoring telemetry data.

POST /rest/v1/alert-rules

Request Body

{
  "name": "High Temperature Alert",
  "description": "Alert when temperature exceeds 35°C",
  "agent_id": "agent_01H8K2M3N4P5Q6R7S8T9U0V1W2",
  "conditions": {
    "field": "temperature",
    "operator": "gt",
    "value": 35,
    "duration_seconds": 300,
    "evaluation_window": "5m"
  },
  "severity": "high",
  "enabled": true,
  "notification_channels": ["email", "sms"],
  "notification_settings": {
    "email": {
      "recipients": ["[email protected]", "[email protected]"],
      "subject_template": "High Temperature Alert - {{agent_name}}",
      "body_template": "Temperature {{current_value}}°C exceeds threshold {{threshold}}°C"
    },
    "sms": {
      "recipients": ["+1-555-0123", "+1-555-0124"],
      "message_template": "ALERT: {{agent_name}} temp {{current_value}}°C > {{threshold}}°C"
    }
  },
  "escalation_policy": {
    "enabled": true,
    "escalate_after_minutes": 15,
    "escalation_contacts": ["[email protected]"]
  },
  "auto_resolve": {
    "enabled": true,
    "resolve_when": "value_below_threshold",
    "resolve_threshold": 30
  }
}

Response

{
  "data": [
    {
      "id": "rule_01H8K3L4M5N6O7P8Q9R0S1T2U3V4",
      "organization_id": "org_01H8K2M3N4P5Q6R7S8T9U0V1W2",
      "name": "High Temperature Alert",
      "description": "Alert when temperature exceeds 35°C",
      "agent_id": "agent_01H8K2M3N4P5Q6R7S8T9U0V1W2",
      "conditions": {
        "field": "temperature",
        "operator": "gt",
        "value": 35,
        "duration_seconds": 300,
        "evaluation_window": "5m"
      },
      "severity": "high",
      "enabled": true,
      "notification_channels": ["email", "sms"],
      "notification_settings": {
        "email": {
          "recipients": ["[email protected]", "[email protected]"],
          "subject_template": "High Temperature Alert - {{agent_name}}",
          "body_template": "Temperature {{current_value}}°C exceeds threshold {{threshold}}°C"
        },
        "sms": {
          "recipients": ["+1-555-0123", "+1-555-0124"],
          "message_template": "ALERT: {{agent_name}} temp {{current_value}}°C > {{threshold}}°C"
        }
      },
      "escalation_policy": {
        "enabled": true,
        "escalate_after_minutes": 15,
        "escalation_contacts": ["[email protected]"]
      },
      "auto_resolve": {
        "enabled": true,
        "resolve_when": "value_below_threshold",
        "resolve_threshold": 30
      },
      "statistics": {
        "triggered_count": 0,
        "last_triggered": null,
        "avg_resolution_time_minutes": null
      },
      "created_at": "2024-07-23T17:00:00Z",
      "updated_at": "2024-07-23T17:00:00Z"
    }
  ]
}

Code Examples

JavaScript/TypeScript:

const { data: alertRule, error } = await supabase
  .from('alert-rules')
  .insert({
    name: 'High Temperature Alert',
    description: 'Alert when temperature exceeds 35°C',
    agent_id: 'agent_01H8K2M3N4P5Q6R7S8T9U0V1W2',
    conditions: {
      field: 'temperature',
      operator: 'gt',
      value: 35,
      duration_seconds: 300
    },
    severity: 'high',
    enabled: true,
    notification_channels: ['email', 'sms']
  })
  .select()
  .single()

if (error) throw error console.log('Alert rule created:', alertRule)


List Alert Rules

Retrieve all alert rules for the organization.

GET /rest/v1/alert-rules

Query Parameters

Parameter Type Required Description
select string No Columns to return (default: *)
agent_id string No Filter by agent ID
enabled boolean No Filter by enabled status
severity string No Filter by severity level
order string No Sort order (default: created_at.desc)

Rate limits are per authenticated user per organization.

# Alerts API

The Alerts API provides comprehensive alert management for IoT devices, including rule configuration, notification handling, and automated response systems within the IoT Agent Mesh platform.

Overview

The alert system enables:

  • Flexible rule-based alerting on telemetry data
  • Multi-channel notification delivery (email, SMS, webhook)
  • Alert severity levels and escalation policies
  • Automated acknowledgment and resolution workflows
  • Historical alert tracking and analytics
  • Integration with external monitoring systems

Base Endpoint

/rest/v1/alerts
/rest/v1/alert-rules

Authentication

All endpoints require JWT authentication with appropriate organization access permissions.

Required Headers:

Authorization: Bearer YOUR_JWT_TOKEN
apikey: YOUR_SUPABASE_ANON_KEY
Content-Type: application/json

Alert Rules Management

Create Alert Rule

Define a new alert rule for monitoring telemetry data.

POST /rest/v1/alert-rules

Request Body

{
  "name": "High Temperature Alert",
  "description": "Alert when temperature exceeds 35°C",
  "agent_id": "agent_01H8K2M3N4P5Q6R7S8T9U0V1W2",
  "conditions": {
    "field": "temperature",
    "operator": "gt",
    "value": 35,
    "duration_seconds": 300,
    "evaluation_window": "5m"
  },
  "severity": "high",
  "enabled": true,
  "notification_channels": ["email", "sms"],
  "notification_settings": {
    "email": {
      "recipients": ["[email protected]", "[email protected]"],
      "subject_template": "High Temperature Alert - {{agent_name}}",
      "body_template": "Temperature {{current_value}}°C exceeds threshold {{threshold}}°C"
    },
    "sms": {
      "recipients": ["+1-555-0123", "+1-555-0124"],
      "message_template": "ALERT: {{agent_name}} temp {{current_value}}°C > {{threshold}}°C"
    }
  },
  "escalation_policy": {
    "enabled": true,
    "escalate_after_minutes": 15,
    "escalation_contacts": ["[email protected]"]
  },
  "auto_resolve": {
    "enabled": true,
    "resolve_when": "value_below_threshold",
    "resolve_threshold": 30
  }
}

Response

{
  "data": [
    {
      "id": "rule_01H8K3L4M5N6O7P8Q9R0S1T2U3V4",
      "organization_id": "org_01H8K2M3N4P5Q6R7S8T9U0V1W2",
      "name": "High Temperature Alert",
      "description": "Alert when temperature exceeds 35°C",
      "agent_id": "agent_01H8K2M3N4P5Q6R7S8T9U0V1W2",
      "conditions": {
        "field": "temperature",
        "operator": "gt",
        "value": 35,
        "duration_seconds": 300,
        "evaluation_window": "5m"
      },
      "severity": "high",
      "enabled": true,
      "notification_channels": ["email", "sms"],
      "notification_settings": {
        "email": {
          "recipients": ["[email protected]", "[email protected]"],
          "subject_template": "High Temperature Alert - {{agent_name}}",
          "body_template": "Temperature {{current_value}}°C exceeds threshold {{threshold}}°C"
        },
        "sms": {
          "recipients": ["+1-555-0123", "+1-555-0124"],
          "message_template": "ALERT: {{agent_name}} temp {{current_value}}°C > {{threshold}}°C"
        }
      },
      "escalation_policy": {
        "enabled": true,
        "escalate_after_minutes": 15,
        "escalation_contacts": ["[email protected]"]
      },
      "auto_resolve": {
        "enabled": true,
        "resolve_when": "value_below_threshold",
        "resolve_threshold": 30
      },
      "statistics": {
        "triggered_count": 0,
        "last_triggered": null,
        "avg_resolution_time_minutes": null
      },
      "created_at": "2024-07-23T17:00:00Z",
      "updated_at": "2024-07-23T17:00:00Z"
    }
  ]
}

Code Examples

JavaScript/TypeScript:

const { data: alertRule, error } = await supabase
  .from('alert-rules')
  .insert({
    name: 'High Temperature Alert',
    description: 'Alert when temperature exceeds 35°C',
    agent_id: 'agent_01H8K2M3N4P5Q6R7S8T9U0V1W2',
    conditions: {
      field: 'temperature',
      operator: 'gt',
      value: 35,
      duration_seconds: 300
    },
    severity: 'high',
    enabled: true,
    notification_channels: ['email', 'sms']
  })
  .select()
  .single()

if (error) throw error
console.log('Alert rule created:', alertRule)

List Alert Rules

Retrieve all alert rules for the organization.

GET /rest/v1/alert-rules

Query Parameters

Parameter Type Required Description
select string No Columns to return (default: *)
agent_id string No Filter by agent ID
enabled boolean No Filter by enabled status
severity string No Filter by severity level
order string No Sort order (default: created_at.desc)

Response

{
  "data": [
    {
      "id": "rule_01H8K3L4M5N6O7P8Q9R0S1T2U3V4",
      "name": "High Temperature Alert",
      "description": "Alert when temperature exceeds 35°C",
      "agent_id": "agent_01H8K2M3N4P5Q6R7S8T9U0V1W2",
      "agent_name": "Temperature Sensor 01",
      "conditions": {
        "field": "temperature",
        "operator": "gt",
        "value": 35
      },
      "severity": "high",
      "enabled": true,
      "notification_channels": ["email", "sms"],
      "statistics": {
        "triggered_count": 12,
        "last_triggered": "2024-07-22T14:30:00Z",
        "avg_resolution_time_minutes": 8.5
      },
      "created_at": "2024-07-23T17:00:00Z"
    }
  ]
}

Active Alerts Management

List Active Alerts

Retrieve all currently active alerts.

GET /rest/v1/alerts

Query Parameters

Parameter Type Required Description
status string No Filter by status (active, acknowledged, resolved)
severity string No Filter by severity (low, medium, high, critical)
agent_id string No Filter by agent ID
rule_id string No Filter by alert rule ID
order string No Sort order (default: created_at.desc)

Response

{
  "data": [
    {
      "id": "alert_01H8K3L4M5N6O7P8Q9R0S1T2U3V4",
      "rule_id": "rule_01H8K3L4M5N6O7P8Q9R0S1T2U3V4",
      "rule_name": "High Temperature Alert",
      "agent_id": "agent_01H8K2M3N4P5Q6R7S8T9U0V1W2",
      "agent_name": "Temperature Sensor 01",
      "severity": "high",
      "status": "active",
      "message": "Temperature 38.5°C exceeds threshold 35°C",
      "trigger_data": {
        "current_value": 38.5,
        "threshold": 35,
        "field": "temperature",
        "timestamp": "2024-07-23T16:45:00Z"
      },
      "notifications_sent": {
        "email": {
          "sent": true,
          "sent_at": "2024-07-23T16:45:30Z",
          "recipients": ["[email protected]", "[email protected]"]
        },
        "sms": {
          "sent": true,
          "sent_at": "2024-07-23T16:45:35Z",
          "recipients": ["+1-555-0123", "+1-555-0124"]
        }
      },
      "acknowledged_by": null,
      "acknowledged_at": null,
      "resolved_at": null,
      "created_at": "2024-07-23T16:45:00Z",
      "updated_at": "2024-07-23T16:45:35Z"
    }
  ]
}

Code Examples

JavaScript/TypeScript:

// Get all active alerts
const { data: activeAlerts } = await supabase
  .from('alerts')
  .select(`
    *,
    agent:agents(name),
    alert_rule:alert_rules(name)
  `)
  .eq('status', 'active')
  .order('created_at', { ascending: false })

// Get high severity alerts
const { data: criticalAlerts } = await supabase
  .from('alerts')
  .select('*')
  .in('severity', ['high', 'critical'])
  .eq('status', 'active')

Acknowledge Alert

Acknowledge an active alert to indicate it's being handled.

POST /rest/v1/alerts/{alert_id}/acknowledge

Request Body

{
  "acknowledged_by": "user_01H8K2M3N4P5Q6R7S8T9U0V1W2",
  "acknowledgment_note": "Investigating temperature spike in warehouse A"
}

Response

{
  "data": [
    {
      "id": "alert_01H8K3L4M5N6O7P8Q9R0S1T2U3V4",
      "status": "acknowledged",
      "acknowledged_by": "user_01H8K2M3N4P5Q6R7S8T9U0V1W2",
      "acknowledged_at": "2024-07-23T16:50:00Z",
      "acknowledgment_note": "Investigating temperature spike in warehouse A",
      "updated_at": "2024-07-23T16:50:00Z"
    }
  ]
}

Code Examples

JavaScript/TypeScript:

// Acknowledge an alert
const response = await supabase.functions.invoke('acknowledge-alert', {
  body: {
    alert_id: 'alert_01H8K3L4M5N6O7P8Q9R0S1T2U3V4',
    acknowledgment_note: 'Investigating temperature spike in warehouse A'
  }
})

console.log('Alert acknowledged:', response.data)

Resolve Alert

Mark an alert as resolved.

POST /rest/v1/alerts/{alert_id}/resolve

Request Body

{
  "resolved_by": "user_01H8K2M3N4P5Q6R7S8T9U0V1W2",
  "resolution_note": "Temperature returned to normal after HVAC adjustment",
  "resolution_action": "hvac_adjustment"
}

Response

{
  "data": [
    {
      "id": "alert_01H8K3L4M5N6O7P8Q9R0S1T2U3V4",
      "status": "resolved",
      "resolved_by": "user_01H8K2M3N4P5Q6R7S8T9U0V1W2",
      "resolved_at": "2024-07-23T17:15:00Z",
      "resolution_note": "Temperature returned to normal after HVAC adjustment",
      "resolution_action": "hvac_adjustment",
      "resolution_time_minutes": 30,
      "updated_at": "2024-07-23T17:15:00Z"
    }
  ]
}

Alert Analytics

Alert Statistics

Get comprehensive alert statistics for the organization.

GET /functions/v1/alert-statistics

Query Parameters

Parameter Type Required Description
time_range string No Time range (24h, 7d, 30d, custom)
start_date string No Start date for custom range
end_date string No End date for custom range
agent_id string No Filter by specific agent

Response

{
  "time_range": "30d",
  "summary": {
    "total_alerts": 156,
    "active_alerts": 3,
    "acknowledged_alerts": 8,
    "resolved_alerts": 145,
    "avg_resolution_time_minutes": 12.5
  },
  "by_severity": {
    "critical": 12,
    "high": 45,
    "medium": 78,
    "low": 21
  },
  "by_agent": [
    {
      "agent_id": "agent_01H8K2M3N4P5Q6R7S8T9U0V1W2",
      "agent_name": "Temperature Sensor 01",
      "alert_count": 25,
      "avg_resolution_time_minutes": 8.2
    }
  ],
  "trending": {
    "daily_counts": [
      {
        "date": "2024-07-23",
        "count": 8,
        "resolved": 6
      }
    ]
  },
  "top_alert_rules": [
    {
      "rule_id": "rule_01H8K3L4M5N6O7P8Q9R0S1T2U3V4",
      "rule_name": "High Temperature Alert",
      "trigger_count": 25,
      "avg_resolution_time_minutes": 8.2
    }
  ]
}

Notification Channels

Configure Email Notifications

POST /functions/v1/configure-email-notifications

Request Body

{
  "smtp_settings": {
    "host": "smtp.company.com",
    "port": 587,
    "username": "[email protected]",
    "password": "secure_password",
    "use_tls": true
  },
  "default_sender": {
    "email": "[email protected]",
    "name": "IoT Alert System"
  },
  "templates": {
    "alert_triggered": {
      "subject": "ALERT: {{severity}} - {{agent_name}}",
      "body_html": "<h2>Alert Triggered</h2><p>{{message}}</p><p>Time: {{timestamp}}</p>",
      "body_text": "ALERT: {{message}} at {{timestamp}}"
    },
    "alert_resolved": {
      "subject": "RESOLVED: {{agent_name}} Alert",
      "body_html": "<h2>Alert Resolved</h2><p>{{resolution_note}}</p>",
      "body_text": "Alert resolved: {{resolution_note}}"
    }
  }
}

Configure SMS Notifications

POST /functions/v1/configure-sms-notifications

Request Body

{
  "provider": "twilio",
  "settings": {
    "account_sid": "your_twilio_account_sid",
    "auth_token": "your_twilio_auth_token",
    "from_number": "+1-555-0100"
  },
  "templates": {
    "alert_triggered": "ALERT {{severity}}: {{agent_name}} - {{message}}",
    "alert_resolved": "RESOLVED: {{agent_name}} alert - {{resolution_note}}"
  }
}

Configure Webhook Notifications

POST /functions/v1/configure-webhook-notifications

Request Body

{
  "webhooks": [
    {
      "name": "Slack Integration",
      "url": "https://hooks.slack.com/services/YOUR/SLACK/WEBHOOK",
      "method": "POST",
      "headers": {
        "Content-Type": "application/json"
      },
      "payload_template": {
        "text": "Alert: {{message}}",
        "channel": "#alerts",
        "username": "IoT Monitor",
        "attachments": [
          {
            "color": "{{severity_color}}",
            "fields": [
              {
                "title": "Agent",
                "value": "{{agent_name}}",
                "short": true
              },
              {
                "title": "Severity",
                "value": "{{severity}}",
                "short": true
              }
            ]
          }
        ]
      },
      "retry_config": {
        "max_retries": 3,
        "retry_delay_seconds": 30
      }
    }
  ]
}

Advanced Alert Rules

Complex Conditions

Create alert rules with multiple conditions and advanced logic.

{
  "name": "Multi-Condition Environmental Alert",
  "conditions": {
    "type": "compound",
    "operator": "AND",
    "rules": [
      {
        "field": "temperature",
        "operator": "gt",
        "value": 30
      },
      {
        "field": "humidity",
        "operator": "lt",
        "value": 40
      }
    ]
  },
  "evaluation_settings": {
    "window": "10m",
    "threshold_percentage": 80,
    "min_data_points": 5
  }
}

Time-Based Rules

{
  "name": "Business Hours Only Alert",
  "conditions": {
    "field": "temperature",
    "operator": "gt",
    "value": 35
  },
  "time_restrictions": {
    "timezone": "America/New_York",
    "business_hours_only": true,
    "schedule": {
      "monday": {"start": "09:00", "end": "17:00"},
      "tuesday": {"start": "09:00", "end": "17:00"},
      "wednesday": {"start": "09:00", "end": "17:00"},
      "thursday": {"start": "09:00", "end": "17:00"},
      "friday": {"start": "09:00", "end": "17:00"}
    }
  }
}

Anomaly Detection Rules

{
  "name": "Temperature Anomaly Detection",
  "conditions": {
    "type": "anomaly",
    "field": "temperature",
    "algorithm": "statistical",
    "settings": {
      "baseline_period_days": 7,
      "sensitivity": "medium",
      "min_deviation_percentage": 15
    }
  }
}

Error Responses

Common Error Codes

HTTP Code Error Code Description
400 INVALID_RULE_CONDITIONS Alert rule conditions are invalid
400 INVALID_NOTIFICATION_CONFIG Notification configuration is invalid
401 UNAUTHORIZED Missing or invalid JWT token
403 FORBIDDEN Insufficient permissions for alert operation
404 ALERT_NOT_FOUND Alert or alert rule not found
409 RULE_NAME_EXISTS Alert rule name already exists
422 UNPROCESSABLE_ENTITY Invalid alert data or configuration
429 RATE_LIMIT_EXCEEDED Too many alert API requests

Example Error Response

{
  "error": {
    "code": "INVALID_RULE_CONDITIONS",
    "message": "Alert rule conditions contain invalid field reference",
    "details": {
      "field": "conditions.field",
      "value": "invalid_field_name",
      "reason": "Field 'invalid_field_name' does not exist in telemetry schema"
    }
  },
  "status": 400
}

Best Practices

Rule Design

  1. Specific Conditions: Create specific, actionable alert conditions
  2. Appropriate Thresholds: Set thresholds based on historical data analysis
  3. Severity Levels: Use severity levels consistently across rules
  4. Time Windows: Configure appropriate evaluation windows to avoid noise

Notification Management

  1. Channel Selection: Choose appropriate notification channels for severity levels
  2. Escalation Policies: Implement escalation for critical alerts
  3. Rate Limiting: Avoid notification spam with rate limiting
  4. Template Consistency: Use consistent message templates

Performance Optimization

  1. Rule Efficiency: Design efficient alert rules to minimize processing overhead
  2. Batch Processing: Use batch operations for managing multiple alerts
  3. Historical Cleanup: Regularly archive resolved alerts
  4. Monitoring: Monitor alert system performance and adjust as needed

Related Resources

  • [Telemetry API](API-Telemetry.md) - Data source for alert conditions
  • [IoT Agents API](API-IoT-Agents.md) - Managing agents that trigger alerts
  • [Edge Functions API](API-Edge-Functions.md) - Custom alert processing logic
  • [Webhooks API](API-Webhooks.md) - Webhook notification configuration

Rate Limits

Operation Rate Limit Window
List Alerts 200 requests 1 minute
Create Alert Rule 20 requests 1 minute
Update Alert Rule 50 requests 1 minute
Acknowledge Alert 100 requests 1 minute
Resolve Alert 100 requests 1 minute
Alert Statistics 30 requests 1 minute
Configure Notifications 5 requests 1 minute

Rate limits are per authenticated user per organization.

⚠️ **GitHub.com Fallback** ⚠️