From afa9078df7c65e5c972c60ffe52b6c76bdf7d789 Mon Sep 17 00:00:00 2001 From: Chirag Aggarwal Date: Thu, 26 Nov 2026 12:48:55 +0000 Subject: [PATCH] feat: monitors, alerts and escalations --- CHANGELOG.md | 7 + appwrite/client.py | 4 +- appwrite/encoders/value_class_encoder.py | 44 + appwrite/enums/alert_comparator.py | 8 + appwrite/enums/alert_metric.py | 34 + appwrite/enums/alert_status.py | 6 + appwrite/enums/monitor_method.py | 11 + appwrite/enums/monitor_record.py | 10 + appwrite/enums/monitor_resource_type.py | 11 + appwrite/enums/monitor_result.py | 17 + appwrite/enums/monitor_severity.py | 8 + appwrite/enums/monitor_status.py | 6 + appwrite/enums/monitor_tls_mode.py | 8 + appwrite/enums/monitor_type.py | 10 + appwrite/models/__init__.py | 14 + appwrite/models/alert.py | 156 +++ appwrite/models/alert_list.py | 34 + appwrite/models/escalation.py | 54 + appwrite/models/escalation_list.py | 34 + appwrite/models/escalation_step.py | 38 + appwrite/models/monitor.py | 189 +++ appwrite/models/monitor_list.py | 34 + appwrite/services/alerts.py | 144 +++ appwrite/services/monitors.py | 1124 +++++++++++++++++ appwrite/services/organization.py | 241 ++++ docs/examples/alerts/get.md | 18 + docs/examples/alerts/list.md | 19 + docs/examples/alerts/update.md | 19 + docs/examples/monitors/create-dns-monitor.md | 38 + docs/examples/monitors/create-http-monitor.md | 41 + docs/examples/monitors/create-smtp-monitor.md | 38 + docs/examples/monitors/create-tcp-monitor.md | 33 + .../examples/monitors/create-usage-monitor.md | 30 + docs/examples/monitors/delete.md | 15 + docs/examples/monitors/get.md | 18 + docs/examples/monitors/list.md | 19 + docs/examples/monitors/update-dns-monitor.md | 38 + docs/examples/monitors/update-http-monitor.md | 41 + docs/examples/monitors/update-smtp-monitor.md | 38 + docs/examples/monitors/update-tcp-monitor.md | 33 + .../examples/monitors/update-usage-monitor.md | 30 + .../organization/create-escalation.md | 37 + .../organization/delete-escalation.md | 15 + docs/examples/organization/get-escalation.md | 18 + .../examples/organization/list-escalations.md | 19 + .../organization/update-escalation.md | 37 + pyproject.toml | 2 +- setup.py | 4 +- test/services/test_alerts.py | 145 +++ test/services/test_monitors.py | 880 +++++++++++++ test/services/test_organization.py | 166 +++ 51 files changed, 4032 insertions(+), 5 deletions(-) create mode 100644 appwrite/enums/alert_comparator.py create mode 100644 appwrite/enums/alert_metric.py create mode 100644 appwrite/enums/alert_status.py create mode 100644 appwrite/enums/monitor_method.py create mode 100644 appwrite/enums/monitor_record.py create mode 100644 appwrite/enums/monitor_resource_type.py create mode 100644 appwrite/enums/monitor_result.py create mode 100644 appwrite/enums/monitor_severity.py create mode 100644 appwrite/enums/monitor_status.py create mode 100644 appwrite/enums/monitor_tls_mode.py create mode 100644 appwrite/enums/monitor_type.py create mode 100644 appwrite/models/alert.py create mode 100644 appwrite/models/alert_list.py create mode 100644 appwrite/models/escalation.py create mode 100644 appwrite/models/escalation_list.py create mode 100644 appwrite/models/escalation_step.py create mode 100644 appwrite/models/monitor.py create mode 100644 appwrite/models/monitor_list.py create mode 100644 appwrite/services/alerts.py create mode 100644 appwrite/services/monitors.py create mode 100644 docs/examples/alerts/get.md create mode 100644 docs/examples/alerts/list.md create mode 100644 docs/examples/alerts/update.md create mode 100644 docs/examples/monitors/create-dns-monitor.md create mode 100644 docs/examples/monitors/create-http-monitor.md create mode 100644 docs/examples/monitors/create-smtp-monitor.md create mode 100644 docs/examples/monitors/create-tcp-monitor.md create mode 100644 docs/examples/monitors/create-usage-monitor.md create mode 100644 docs/examples/monitors/delete.md create mode 100644 docs/examples/monitors/get.md create mode 100644 docs/examples/monitors/list.md create mode 100644 docs/examples/monitors/update-dns-monitor.md create mode 100644 docs/examples/monitors/update-http-monitor.md create mode 100644 docs/examples/monitors/update-smtp-monitor.md create mode 100644 docs/examples/monitors/update-tcp-monitor.md create mode 100644 docs/examples/monitors/update-usage-monitor.md create mode 100644 docs/examples/organization/create-escalation.md create mode 100644 docs/examples/organization/delete-escalation.md create mode 100644 docs/examples/organization/get-escalation.md create mode 100644 docs/examples/organization/list-escalations.md create mode 100644 docs/examples/organization/update-escalation.md create mode 100644 test/services/test_alerts.py create mode 100644 test/services/test_monitors.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 5bb6f140..c1fb8c8a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,12 @@ # Change Log +## 28.2.0 + +* Added: `monitors` service to create, list, get, update and delete HTTP, DNS, TCP, SMTP and usage monitors +* Added: `alerts` service to list and get alerts, and acknowledge them with `alerts.update` +* Added: `organization.listEscalations`, `createEscalation`, `getEscalation`, `updateEscalation` and `deleteEscalation` +* Added: `Monitor`, `Alert`, `Escalation` and `EscalationStep` models, their list models, and the `Monitor*` and `Alert*` enums + ## 28.1.0 * Added: `messaging.create_bird_email_provider`, `update_bird_email_provider`, `create_bird_sms_provider` and `update_bird_sms_provider` for the Bird email and SMS providers diff --git a/appwrite/client.py b/appwrite/client.py index b17316d4..c12941fb 100644 --- a/appwrite/client.py +++ b/appwrite/client.py @@ -20,11 +20,11 @@ def __init__(self): self._endpoint = 'https://cloud.appwrite.io/v1' self._global_headers = { 'content-type': '', - 'user-agent': f'AppwritePythonSDK/28.1.0 ({platform.uname().system}; {platform.uname().version}; {platform.uname().machine})', + 'user-agent': f'AppwritePythonSDK/28.2.0 ({platform.uname().system}; {platform.uname().version}; {platform.uname().machine})', 'x-sdk-name': 'Python', 'x-sdk-platform': 'server', 'x-sdk-language': 'python', - 'x-sdk-version': '28.1.0', + 'x-sdk-version': '28.2.0', 'X-Appwrite-Response-Format': '2.7.2', } self._config = {} diff --git a/appwrite/encoders/value_class_encoder.py b/appwrite/encoders/value_class_encoder.py index c2243620..5d1c9d31 100644 --- a/appwrite/encoders/value_class_encoder.py +++ b/appwrite/encoders/value_class_encoder.py @@ -32,6 +32,10 @@ from ..enums.firebase_migration_resource import FirebaseMigrationResource from ..enums.n_host_migration_resource import NHostMigrationResource from ..enums.supabase_migration_resource import SupabaseMigrationResource +from ..enums.monitor_record import MonitorRecord +from ..enums.monitor_severity import MonitorSeverity +from ..enums.monitor_method import MonitorMethod +from ..enums.monitor_tls_mode import MonitorTlsMode from ..enums.region import Region from ..enums.project_auth_method_id import ProjectAuthMethodId from ..enums.environment_resource import EnvironmentResource @@ -74,6 +78,13 @@ from ..enums.execution_resource_type import ExecutionResourceType from ..enums.execution_trigger import ExecutionTrigger from ..enums.execution_status import ExecutionStatus +from ..enums.monitor_type import MonitorType +from ..enums.monitor_resource_type import MonitorResourceType +from ..enums.monitor_status import MonitorStatus +from ..enums.monitor_result import MonitorResult +from ..enums.alert_status import AlertStatus +from ..enums.alert_metric import AlertMetric +from ..enums.alert_comparator import AlertComparator from ..enums.o_auth2_github_prompt import OAuth2GithubPrompt from ..enums.o_auth2_discord_prompt import OAuth2DiscordPrompt from ..enums.o_auth2_google_prompt import OAuth2GooglePrompt @@ -195,6 +206,18 @@ def default(self, o): if isinstance(o, SupabaseMigrationResource): return o.value + if isinstance(o, MonitorRecord): + return o.value + + if isinstance(o, MonitorSeverity): + return o.value + + if isinstance(o, MonitorMethod): + return o.value + + if isinstance(o, MonitorTlsMode): + return o.value + if isinstance(o, Region): return o.value @@ -321,6 +344,27 @@ def default(self, o): if isinstance(o, ExecutionStatus): return o.value + if isinstance(o, MonitorType): + return o.value + + if isinstance(o, MonitorResourceType): + return o.value + + if isinstance(o, MonitorStatus): + return o.value + + if isinstance(o, MonitorResult): + return o.value + + if isinstance(o, AlertStatus): + return o.value + + if isinstance(o, AlertMetric): + return o.value + + if isinstance(o, AlertComparator): + return o.value + if isinstance(o, OAuth2GithubPrompt): return o.value diff --git a/appwrite/enums/alert_comparator.py b/appwrite/enums/alert_comparator.py new file mode 100644 index 00000000..9ce6d441 --- /dev/null +++ b/appwrite/enums/alert_comparator.py @@ -0,0 +1,8 @@ +from enum import Enum + + +class AlertComparator(Enum): + GREATERTHAN = "greaterThan" + GREATERTHANEQUAL = "greaterThanEqual" + LESSTHAN = "lessThan" + LESSTHANEQUAL = "lessThanEqual" diff --git a/appwrite/enums/alert_metric.py b/appwrite/enums/alert_metric.py new file mode 100644 index 00000000..31ccbe6a --- /dev/null +++ b/appwrite/enums/alert_metric.py @@ -0,0 +1,34 @@ +from enum import Enum + + +class AlertMetric(Enum): + NETWORK_REQUESTS = "network.requests" + NETWORK_INBOUND = "network.inbound" + NETWORK_OUTBOUND = "network.outbound" + EXECUTIONS = "executions" + EXECUTIONS_MBSECONDS = "executions.mbSeconds" + REALTIME_CONNECTIONS = "realtime.connections" + WEBHOOKS_EVENTS_SENT = "webhooks.events.sent" + WEBHOOKS_EVENTS_FAILED = "webhooks.events.failed" + USERS_MAU = "users.mau" + AUTH_METHOD_PHONE = "auth.method.phone" + USERS = "users" + DATABASES_OPERATIONS_READS = "databases.operations.reads" + DATABASES_OPERATIONS_WRITES = "databases.operations.writes" + DATABASES_STORAGE = "databases.storage" + STORAGE = "storage" + FILES_STORAGE = "files.storage" + MESSAGES_SENT = "messages.sent" + MESSAGES_SMS_SENT = "messages.sms.sent" + MESSAGES_FAILED = "messages.failed" + AVATARS_SCREENSHOTSGENERATED = "avatars.screenshotsGenerated" + DEDICATEDDATABASES_CPU = "dedicatedDatabases.cpu" + DEDICATEDDATABASES_MEMORY = "dedicatedDatabases.memory" + DEDICATEDDATABASES_STORAGE = "dedicatedDatabases.storage" + DEDICATEDDATABASES_CONNECTIONS = "dedicatedDatabases.connections" + DEDICATEDDATABASES_QPS = "dedicatedDatabases.qps" + DEDICATEDDATABASES_IOPSREAD = "dedicatedDatabases.iopsRead" + DEDICATEDDATABASES_IOPSWRITE = "dedicatedDatabases.iopsWrite" + ANALYTICS_EVENTS = "analytics.events" + ANALYTICS_PAGEVIEWS = "analytics.pageviews" + BILLING_BUDGETUSED = "billing.budgetUsed" diff --git a/appwrite/enums/alert_status.py b/appwrite/enums/alert_status.py new file mode 100644 index 00000000..d2c18ee2 --- /dev/null +++ b/appwrite/enums/alert_status.py @@ -0,0 +1,6 @@ +from enum import Enum + + +class AlertStatus(Enum): + FIRING = "firing" + RESOLVED = "resolved" diff --git a/appwrite/enums/monitor_method.py b/appwrite/enums/monitor_method.py new file mode 100644 index 00000000..16897b34 --- /dev/null +++ b/appwrite/enums/monitor_method.py @@ -0,0 +1,11 @@ +from enum import Enum + + +class MonitorMethod(Enum): + GET = "GET" + HEAD = "HEAD" + POST = "POST" + PUT = "PUT" + PATCH = "PATCH" + DELETE = "DELETE" + OPTIONS = "OPTIONS" diff --git a/appwrite/enums/monitor_record.py b/appwrite/enums/monitor_record.py new file mode 100644 index 00000000..4184d738 --- /dev/null +++ b/appwrite/enums/monitor_record.py @@ -0,0 +1,10 @@ +from enum import Enum + + +class MonitorRecord(Enum): + A = "A" + AAAA = "AAAA" + CNAME = "CNAME" + MX = "MX" + TXT = "TXT" + NS = "NS" diff --git a/appwrite/enums/monitor_resource_type.py b/appwrite/enums/monitor_resource_type.py new file mode 100644 index 00000000..96a798b3 --- /dev/null +++ b/appwrite/enums/monitor_resource_type.py @@ -0,0 +1,11 @@ +from enum import Enum + + +class MonitorResourceType(Enum): + PROJECT = "project" + DATABASE = "database" + BUCKET = "bucket" + FUNCTION = "function" + SITE = "site" + DEDICATEDDATABASE = "dedicatedDatabase" + ORGANIZATION = "organization" diff --git a/appwrite/enums/monitor_result.py b/appwrite/enums/monitor_result.py new file mode 100644 index 00000000..339d77d8 --- /dev/null +++ b/appwrite/enums/monitor_result.py @@ -0,0 +1,17 @@ +from enum import Enum + + +class MonitorResult(Enum): + OK = "ok" + DNS_FAILED = "dns_failed" + CONNECT_REFUSED = "connect_refused" + CONNECT_TIMEOUT = "connect_timeout" + CONNECT_FAILED = "connect_failed" + TLS_FAILED = "tls_failed" + TLS_EXPIRING = "tls_expiring" + STATUS_MISMATCH = "status_mismatch" + ANSWER_MISMATCH = "answer_mismatch" + SMTP_REJECTED = "smtp_rejected" + TARGET_DENIED = "target_denied" + TIMEOUT = "timeout" + RULE_MATCHED = "rule_matched" diff --git a/appwrite/enums/monitor_severity.py b/appwrite/enums/monitor_severity.py new file mode 100644 index 00000000..e49138ea --- /dev/null +++ b/appwrite/enums/monitor_severity.py @@ -0,0 +1,8 @@ +from enum import Enum + + +class MonitorSeverity(Enum): + INFO = "info" + WARNING = "warning" + ERROR = "error" + CRITICAL = "critical" diff --git a/appwrite/enums/monitor_status.py b/appwrite/enums/monitor_status.py new file mode 100644 index 00000000..0db403d9 --- /dev/null +++ b/appwrite/enums/monitor_status.py @@ -0,0 +1,6 @@ +from enum import Enum + + +class MonitorStatus(Enum): + OK = "ok" + FIRING = "firing" diff --git a/appwrite/enums/monitor_tls_mode.py b/appwrite/enums/monitor_tls_mode.py new file mode 100644 index 00000000..cf80261b --- /dev/null +++ b/appwrite/enums/monitor_tls_mode.py @@ -0,0 +1,8 @@ +from enum import Enum + + +class MonitorTlsMode(Enum): + NONE = "none" + STARTTLS = "starttls" + IMPLICIT = "implicit" + AUTO = "auto" diff --git a/appwrite/enums/monitor_type.py b/appwrite/enums/monitor_type.py new file mode 100644 index 00000000..51aa2f72 --- /dev/null +++ b/appwrite/enums/monitor_type.py @@ -0,0 +1,10 @@ +from enum import Enum + + +class MonitorType(Enum): + USAGE = "usage" + HTTP = "http" + DNS = "dns" + TCP = "tcp" + SMTP = "smtp" + BUDGET = "budget" diff --git a/appwrite/models/__init__.py b/appwrite/models/__init__.py index f3113b63..d93ffe93 100644 --- a/appwrite/models/__init__.py +++ b/appwrite/models/__init__.py @@ -23,6 +23,9 @@ from .execution_list import ExecutionList from .project_list import ProjectList from .webhook_list import WebhookList +from .monitor_list import MonitorList +from .alert_list import AlertList +from .escalation_list import EscalationList from .key_list import KeyList from .country_list import CountryList from .continent_list import ContinentList @@ -131,6 +134,10 @@ from .project_service import ProjectService from .project_protocol import ProjectProtocol from .webhook import Webhook +from .monitor import Monitor +from .alert import Alert +from .escalation_step import EscalationStep +from .escalation import Escalation from .key import Key from .ephemeral_key import EphemeralKey from .mock_number import MockNumber @@ -369,6 +376,9 @@ 'ExecutionList', 'ProjectList', 'WebhookList', + 'MonitorList', + 'AlertList', + 'EscalationList', 'KeyList', 'CountryList', 'ContinentList', @@ -477,6 +487,10 @@ 'ProjectService', 'ProjectProtocol', 'Webhook', + 'Monitor', + 'Alert', + 'EscalationStep', + 'Escalation', 'Key', 'EphemeralKey', 'MockNumber', diff --git a/appwrite/models/alert.py b/appwrite/models/alert.py new file mode 100644 index 00000000..103312b0 --- /dev/null +++ b/appwrite/models/alert.py @@ -0,0 +1,156 @@ +from typing import Any, Dict, List, Optional, Union, cast +from pydantic import Field, PrivateAttr, model_validator + +from .base_model import AppwriteModel +from ..enums.alert_status import AlertStatus +from ..enums.monitor_severity import MonitorSeverity +from ..enums.alert_metric import AlertMetric +from ..enums.alert_comparator import AlertComparator +from ..enums.monitor_type import MonitorType +from ..enums.monitor_resource_type import MonitorResourceType +from ..enums.monitor_result import MonitorResult + + +class Alert(AppwriteModel): + """ + Alert + + Attributes + ---------- + id : str + Alert ID. + createdat : str + Date the alert started firing, in ISO 8601 format. + updatedat : str + Alert update date in ISO 8601 format. + monitorid : str + ID of the monitor that raised the alert. + projectid : str + ID of the project the alert is about. Empty for an alert of the whole organization. + name : str + Name of the monitor when the alert fired. + status : AlertStatus + Whether the alert is still firing or has resolved. + resolvedat : Optional[str] + Date the alert resolved, in ISO 8601 format. Empty while it fires. + acknowledgedat : Optional[str] + Date a member acknowledged the alert, in ISO 8601 format. Empty while nobody has. + acknowledgedby : str + ID of the user who acknowledged the alert. Empty while nobody has, or when it was acknowledged with an API key. + acknowledgedbyname : str + Name of the user who acknowledged the alert, when they did. + escalationid : str + ID of the escalation notifying the team of this alert. Empty when the monitor notified its `notify` roles instead. + escalationstep : float + Index of the escalation's next step to notify, counting from 0. Equal to the number of steps once the last round has gone out. + escalationround : float + How many times the escalation's steps have been repeated for this alert. + escalatesat : Optional[str] + When the next step is notified, in ISO 8601 format. Null when nothing is due: the alert was acknowledged or resolved, or every step has gone out. + rules : List[Any] + The monitor's rules when the alert fired, as query strings. + severity : MonitorSeverity + The monitor's severity when the alert fired: `info`, `warning`, `error` or `critical`. + metric : Optional[AlertMetric] + Metric the alert fired on. Null for a probe monitor's alert. + comparator : Optional[AlertComparator] + How the metric was compared with the threshold. Null for a probe monitor's alert. + threshold : float + Threshold the metric crossed, in the metric's unit. + value : float + Latest reading while the alert fired: the metric's value for a usage monitor, and for a probe monitor its `latency`. + peak : float + Reading furthest past the threshold while the alert fired. + type : MonitorType + Type of the monitor that raised the alert. + resourcetype : MonitorResourceType + Type of the resource the alert fired on: the project, or one database, bucket, function or site. + resourceid : str + ID of the resource the alert fired on. The project ID for a project-wide monitor. + notifications : float + How many times the alert was announced as firing: once when it fired, and again after each cooldown while it kept firing. + latency : Optional[float] + Probe monitors: response time in milliseconds of the latest check recorded on the alert. + result : Optional[MonitorResult] + What the failing check of a probe monitor found when the alert opened, such as `connect_refused`. Null for a usage monitor's alert. + """ + + id: str = Field(..., alias='$id') + createdat: str = Field(..., alias='$createdAt') + updatedat: str = Field(..., alias='$updatedAt') + monitorid: str = Field(..., alias='monitorId') + projectid: str = Field(..., alias='projectId') + name: str = Field(..., alias='name') + status: AlertStatus = Field(..., alias='status') + resolvedat: Optional[str] = Field(default=None, alias='resolvedAt') + acknowledgedat: Optional[str] = Field(default=None, alias='acknowledgedAt') + acknowledgedby: str = Field(..., alias='acknowledgedBy') + acknowledgedbyname: str = Field(..., alias='acknowledgedByName') + escalationid: str = Field(..., alias='escalationId') + escalationstep: float = Field(..., alias='escalationStep') + escalationround: float = Field(..., alias='escalationRound') + escalatesat: Optional[str] = Field(default=None, alias='escalatesAt') + rules: List[Any] = Field(..., alias='rules') + severity: MonitorSeverity = Field(..., alias='severity') + metric: Optional[AlertMetric] = Field(default=None, alias='metric') + comparator: Optional[AlertComparator] = Field(default=None, alias='comparator') + threshold: float = Field(..., alias='threshold') + value: float = Field(..., alias='value') + peak: float = Field(..., alias='peak') + type: MonitorType = Field(..., alias='type') + resourcetype: MonitorResourceType = Field(..., alias='resourceType') + resourceid: str = Field(..., alias='resourceId') + notifications: float = Field(..., alias='notifications') + latency: Optional[float] = Field(default=None, alias='latency') + result: Optional[MonitorResult] = Field(default=None, alias='result') + + @model_validator(mode='before') + @classmethod + def _apply_defaults(cls, data: Any) -> Any: + if not isinstance(data, dict): + return data + + data = dict(data) + if '$id' not in data and 'id' not in data: + data['$id'] = '' + if '$createdAt' not in data and 'createdat' not in data: + data['$createdAt'] = '' + if '$updatedAt' not in data and 'updatedat' not in data: + data['$updatedAt'] = '' + if 'monitorId' not in data and 'monitorid' not in data: + data['monitorId'] = '' + if 'projectId' not in data and 'projectid' not in data: + data['projectId'] = '' + if 'name' not in data: + data['name'] = '' + if 'status' not in data: + data['status'] = 'firing' + if 'acknowledgedBy' not in data and 'acknowledgedby' not in data: + data['acknowledgedBy'] = '' + if 'acknowledgedByName' not in data and 'acknowledgedbyname' not in data: + data['acknowledgedByName'] = '' + if 'escalationId' not in data and 'escalationid' not in data: + data['escalationId'] = '' + if 'escalationStep' not in data and 'escalationstep' not in data: + data['escalationStep'] = 0 + if 'escalationRound' not in data and 'escalationround' not in data: + data['escalationRound'] = 0 + if 'rules' not in data: + data['rules'] = [] + if 'severity' not in data: + data['severity'] = 'warning' + if 'threshold' not in data: + data['threshold'] = 0 + if 'value' not in data: + data['value'] = 0 + if 'peak' not in data: + data['peak'] = 0 + if 'type' not in data: + data['type'] = 'usage' + if 'resourceType' not in data and 'resourcetype' not in data: + data['resourceType'] = 'project' + if 'resourceId' not in data and 'resourceid' not in data: + data['resourceId'] = '' + if 'notifications' not in data: + data['notifications'] = 0 + return data diff --git a/appwrite/models/alert_list.py b/appwrite/models/alert_list.py new file mode 100644 index 00000000..29f8eac3 --- /dev/null +++ b/appwrite/models/alert_list.py @@ -0,0 +1,34 @@ +from typing import Any, Dict, List, Optional, Union, cast +from pydantic import Field, PrivateAttr, model_validator + +from .base_model import AppwriteModel +from .alert import Alert + + +class AlertList(AppwriteModel): + """ + Alerts List + + Attributes + ---------- + total : float + Total number of alerts that matched your query. + alerts : List[Alert] + List of alerts. + """ + + total: float = Field(..., alias='total') + alerts: List[Alert] = Field(..., alias='alerts') + + @model_validator(mode='before') + @classmethod + def _apply_defaults(cls, data: Any) -> Any: + if not isinstance(data, dict): + return data + + data = dict(data) + if 'total' not in data: + data['total'] = 0 + if 'alerts' not in data: + data['alerts'] = [] + return data diff --git a/appwrite/models/escalation.py b/appwrite/models/escalation.py new file mode 100644 index 00000000..26cf3b9f --- /dev/null +++ b/appwrite/models/escalation.py @@ -0,0 +1,54 @@ +from typing import Any, Dict, List, Optional, Union, cast +from pydantic import Field, PrivateAttr, model_validator + +from .base_model import AppwriteModel +from .escalation_step import EscalationStep + + +class Escalation(AppwriteModel): + """ + Escalation + + Attributes + ---------- + id : str + Escalation ID. + createdat : str + Escalation creation date in ISO 8601 format. + updatedat : str + Escalation update date in ISO 8601 format. + name : str + Escalation name. + steps : List[EscalationStep] + Who is notified of a firing alert, in order, until a member acknowledges it. + repeat : float + How many more times the steps run from the first, a monitor's cooldown after the last step, while nobody has acknowledged the alert. + """ + + id: str = Field(..., alias='$id') + createdat: str = Field(..., alias='$createdAt') + updatedat: str = Field(..., alias='$updatedAt') + name: str = Field(..., alias='name') + steps: List[EscalationStep] = Field(..., alias='steps') + repeat: float = Field(..., alias='repeat') + + @model_validator(mode='before') + @classmethod + def _apply_defaults(cls, data: Any) -> Any: + if not isinstance(data, dict): + return data + + data = dict(data) + if '$id' not in data and 'id' not in data: + data['$id'] = '' + if '$createdAt' not in data and 'createdat' not in data: + data['$createdAt'] = '' + if '$updatedAt' not in data and 'updatedat' not in data: + data['$updatedAt'] = '' + if 'name' not in data: + data['name'] = '' + if 'steps' not in data: + data['steps'] = [] + if 'repeat' not in data: + data['repeat'] = 0 + return data diff --git a/appwrite/models/escalation_list.py b/appwrite/models/escalation_list.py new file mode 100644 index 00000000..369363cb --- /dev/null +++ b/appwrite/models/escalation_list.py @@ -0,0 +1,34 @@ +from typing import Any, Dict, List, Optional, Union, cast +from pydantic import Field, PrivateAttr, model_validator + +from .base_model import AppwriteModel +from .escalation import Escalation + + +class EscalationList(AppwriteModel): + """ + Escalations List + + Attributes + ---------- + total : float + Total number of escalations that matched your query. + escalations : List[Escalation] + List of escalations. + """ + + total: float = Field(..., alias='total') + escalations: List[Escalation] = Field(..., alias='escalations') + + @model_validator(mode='before') + @classmethod + def _apply_defaults(cls, data: Any) -> Any: + if not isinstance(data, dict): + return data + + data = dict(data) + if 'total' not in data: + data['total'] = 0 + if 'escalations' not in data: + data['escalations'] = [] + return data diff --git a/appwrite/models/escalation_step.py b/appwrite/models/escalation_step.py new file mode 100644 index 00000000..7dfe1832 --- /dev/null +++ b/appwrite/models/escalation_step.py @@ -0,0 +1,38 @@ +from typing import Any, Dict, List, Optional, Union, cast +from pydantic import Field, PrivateAttr, model_validator + +from .base_model import AppwriteModel + + +class EscalationStep(AppwriteModel): + """ + Escalation Step + + Attributes + ---------- + delay : float + Seconds to wait before notifying this step: after the alert fires for the first step, after the previous step for the others. + roles : List[Any] + Organization roles whose confirmed members this step notifies. + userids : List[Any] + IDs of the organization's members this step notifies, whatever their role. + """ + + delay: float = Field(..., alias='delay') + roles: List[Any] = Field(..., alias='roles') + userids: List[Any] = Field(..., alias='userIds') + + @model_validator(mode='before') + @classmethod + def _apply_defaults(cls, data: Any) -> Any: + if not isinstance(data, dict): + return data + + data = dict(data) + if 'delay' not in data: + data['delay'] = 0 + if 'roles' not in data: + data['roles'] = [] + if 'userIds' not in data and 'userids' not in data: + data['userIds'] = [] + return data diff --git a/appwrite/models/monitor.py b/appwrite/models/monitor.py new file mode 100644 index 00000000..0a63203c --- /dev/null +++ b/appwrite/models/monitor.py @@ -0,0 +1,189 @@ +from typing import Any, Dict, List, Optional, Union, cast +from pydantic import Field, PrivateAttr, model_validator + +from .base_model import AppwriteModel +from ..enums.monitor_type import MonitorType +from ..enums.monitor_resource_type import MonitorResourceType +from ..enums.monitor_severity import MonitorSeverity +from ..enums.monitor_status import MonitorStatus +from ..enums.monitor_method import MonitorMethod +from ..enums.monitor_record import MonitorRecord +from ..enums.monitor_tls_mode import MonitorTlsMode +from ..enums.monitor_result import MonitorResult + + +class Monitor(AppwriteModel): + """ + Monitor + + Attributes + ---------- + id : str + Monitor ID. + createdat : str + Monitor creation date in ISO 8601 format. + updatedat : str + Monitor update date in ISO 8601 format. + name : str + Monitor name. + projectid : str + Project ID. + rules : List[Any] + Rules that must all hold for the monitor to fire, as query strings. A usage monitor has one comparing a metric with a threshold, optionally scoped with `equal('resourceType')` and `equal('resourceId')`. A probe monitor fires when its rules match the check, over these variables: `http` `statusCode`, `latency`, `certificateDays` and `certificateLifetime`; `dns` `answer`, `answers` and `latency`; `tcp` `latency`; `smtp` `code`, `latency`, `certificateDays` and `certificateLifetime`. A failed connection fires whatever the rules. + type : MonitorType + What the monitor checks: `usage` compares a usage metric with a threshold; `http`, `dns`, `tcp` and `smtp` probe a target on their own interval. + resourcetype : MonitorResourceType + Type of the resource the monitor watches, from its rules: the project, or one database, bucket, function or site. + resourceid : str + ID of the resource the monitor watches, from its rules. The project ID for a project-wide monitor. + window : float + Seconds a counter metric is summed over, and a growth metric is measured across. Gauges compare their latest value. Usage is read a short lag behind the evaluation (`_APP_ALERTS_USAGE_LAG`, 120 seconds by default) so events still being written are counted by the next evaluation. + cooldown : float + Minimum seconds between two team notifications of this monitor firing. Events fire on every change regardless. + enabled : bool + Whether the monitor is evaluated. + notify : List[Any] + Organization roles whose confirmed members get an email and a console notification when the monitor fires and resolves. Empty when the alert events are the only delivery. Not used while `escalationId` is set. + escalationid : str + ID of the organization's escalation that notifies the team of this monitor's alerts, step by step until one is acknowledged. When set, `notify` is not used. Empty to notify the `notify` roles once. + severity : MonitorSeverity + How urgent the monitor's alerts are: `info`, `warning`, `error` or `critical`. Critical alerts may be delivered with higher urgency by the notification channels that support it. + status : MonitorStatus + Whether the monitor is firing, as of its last evaluation. + value : Optional[float] + Metric value at the last evaluation. Null before the first evaluation, and when the last evaluation (`evaluatedAt`) found no usage recorded to read: without data a monitor is not compared, so it keeps its status and open alert. + evaluatedat : Optional[str] + Last evaluation date in ISO 8601 format. + alertid : str + ID of the alert the monitor is firing for. Empty while it is not firing. + triggeredat : Optional[str] + Date the monitor last announced an alert, in ISO 8601 format. + interval : float + Probe monitors: seconds between two checks, read back raised to the plan's minimum. 0 for usage monitors, which are evaluated on the server's interval. + timeout : float + Probe monitors: seconds a check may take before it fails. + url : str + HTTP monitors: URL requested. + method : Optional[MonitorMethod] + HTTP monitors: method the URL is requested with. Null for other types. + headers : Optional[Dict[str, Any]] + HTTP monitors: headers sent, as an object of header names and values. + body : str + HTTP monitors: request body sent. + domain : str + DNS monitors: domain queried. + record : Optional[MonitorRecord] + DNS monitors: record type queried. Null for other types. + resolver : str + DNS monitors: resolver queried. Empty for the server's DNS resolver. + host : str + TCP and SMTP monitors: hostname or IP address connected to. + port : float + TCP and SMTP monitors: port connected to. + tlsmode : Optional[MonitorTlsMode] + SMTP monitors: how the connection is secured. `auto` picks implicit TLS on port 465, STARTTLS on 587 and none otherwise. Null for other types. + result : Optional[MonitorResult] + Probe monitors: what the last check found. `ok` passes; anything else opened the monitor's alert. Null before the first check. + latency : Optional[float] + Probe monitors: milliseconds the last check took. + code : Optional[float] + Probe monitors: last status code an HTTP target answered with, reply code an SMTP server sent, or response code a DNS resolver returned. + certificateexpiresat : Optional[str] + Probe monitors: expiry date of the TLS certificate the last check saw, in ISO 8601 format. Null without TLS. + """ + + id: str = Field(..., alias='$id') + createdat: str = Field(..., alias='$createdAt') + updatedat: str = Field(..., alias='$updatedAt') + name: str = Field(..., alias='name') + projectid: str = Field(..., alias='projectId') + rules: List[Any] = Field(..., alias='rules') + type: MonitorType = Field(..., alias='type') + resourcetype: MonitorResourceType = Field(..., alias='resourceType') + resourceid: str = Field(..., alias='resourceId') + window: float = Field(..., alias='window') + cooldown: float = Field(..., alias='cooldown') + enabled: bool = Field(..., alias='enabled') + notify: List[Any] = Field(..., alias='notify') + escalationid: str = Field(..., alias='escalationId') + severity: MonitorSeverity = Field(..., alias='severity') + status: MonitorStatus = Field(..., alias='status') + value: Optional[float] = Field(default=None, alias='value') + evaluatedat: Optional[str] = Field(default=None, alias='evaluatedAt') + alertid: str = Field(..., alias='alertId') + triggeredat: Optional[str] = Field(default=None, alias='triggeredAt') + interval: float = Field(..., alias='interval') + timeout: float = Field(..., alias='timeout') + url: str = Field(..., alias='url') + method: Optional[MonitorMethod] = Field(default=None, alias='method') + headers: Optional[Dict[str, Any]] = Field(default=None, alias='headers') + body: str = Field(..., alias='body') + domain: str = Field(..., alias='domain') + record: Optional[MonitorRecord] = Field(default=None, alias='record') + resolver: str = Field(..., alias='resolver') + host: str = Field(..., alias='host') + port: float = Field(..., alias='port') + tlsmode: Optional[MonitorTlsMode] = Field(default=None, alias='tlsMode') + result: Optional[MonitorResult] = Field(default=None, alias='result') + latency: Optional[float] = Field(default=None, alias='latency') + code: Optional[float] = Field(default=None, alias='code') + certificateexpiresat: Optional[str] = Field(default=None, alias='certificateExpiresAt') + + @model_validator(mode='before') + @classmethod + def _apply_defaults(cls, data: Any) -> Any: + if not isinstance(data, dict): + return data + + data = dict(data) + if '$id' not in data and 'id' not in data: + data['$id'] = '' + if '$createdAt' not in data and 'createdat' not in data: + data['$createdAt'] = '' + if '$updatedAt' not in data and 'updatedat' not in data: + data['$updatedAt'] = '' + if 'name' not in data: + data['name'] = '' + if 'projectId' not in data and 'projectid' not in data: + data['projectId'] = '' + if 'rules' not in data: + data['rules'] = [] + if 'type' not in data: + data['type'] = 'usage' + if 'resourceType' not in data and 'resourcetype' not in data: + data['resourceType'] = 'project' + if 'resourceId' not in data and 'resourceid' not in data: + data['resourceId'] = '' + if 'window' not in data: + data['window'] = 3600 + if 'cooldown' not in data: + data['cooldown'] = 3600 + if 'enabled' not in data: + data['enabled'] = True + if 'notify' not in data: + data['notify'] = ['owner'] + if 'escalationId' not in data and 'escalationid' not in data: + data['escalationId'] = '' + if 'severity' not in data: + data['severity'] = 'warning' + if 'status' not in data: + data['status'] = 'ok' + if 'alertId' not in data and 'alertid' not in data: + data['alertId'] = '' + if 'interval' not in data: + data['interval'] = 0 + if 'timeout' not in data: + data['timeout'] = 0 + if 'url' not in data: + data['url'] = '' + if 'body' not in data: + data['body'] = '' + if 'domain' not in data: + data['domain'] = '' + if 'resolver' not in data: + data['resolver'] = '' + if 'host' not in data: + data['host'] = '' + if 'port' not in data: + data['port'] = 0 + return data diff --git a/appwrite/models/monitor_list.py b/appwrite/models/monitor_list.py new file mode 100644 index 00000000..84d36493 --- /dev/null +++ b/appwrite/models/monitor_list.py @@ -0,0 +1,34 @@ +from typing import Any, Dict, List, Optional, Union, cast +from pydantic import Field, PrivateAttr, model_validator + +from .base_model import AppwriteModel +from .monitor import Monitor + + +class MonitorList(AppwriteModel): + """ + Monitors List + + Attributes + ---------- + total : float + Total number of monitors that matched your query. + monitors : List[Monitor] + List of monitors. + """ + + total: float = Field(..., alias='total') + monitors: List[Monitor] = Field(..., alias='monitors') + + @model_validator(mode='before') + @classmethod + def _apply_defaults(cls, data: Any) -> Any: + if not isinstance(data, dict): + return data + + data = dict(data) + if 'total' not in data: + data['total'] = 0 + if 'monitors' not in data: + data['monitors'] = [] + return data diff --git a/appwrite/services/alerts.py b/appwrite/services/alerts.py new file mode 100644 index 00000000..7faba69b --- /dev/null +++ b/appwrite/services/alerts.py @@ -0,0 +1,144 @@ +from ..service import Service +from urllib.parse import quote +from typing import Any, Dict, List, Optional, Union +from ..exception import AppwriteException +from appwrite.utils.deprecated import deprecated +from ..models.alert_list import AlertList +from ..models.alert import Alert + + +class Alerts(Service): + + def __init__(self, client) -> None: + super(Alerts, self).__init__(client) + + def list( + self, + queries: Optional[List[str]] = None, + total: Optional[bool] = None, + ) -> AlertList: + """ + Get a list of the alerts the project's monitors raised, open and resolved. An alert is created when a monitor starts firing and resolved when it recovers. Use queries to filter by monitor, status, type or resource, order by `$createdAt` for the latest first, and `Query.search('search', term)` to search alert and monitor IDs, names and metrics. + + Parameters + ---------- + queries : Optional[List[str]] + Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: monitorId, name, status, type, resourceType, resourceId, metric, resolvedAt, severity, acknowledgedAt, escalationId, search + total : Optional[bool] + When set to false, the total count returned will be 0 and will not be calculated. + Returns + ------- + AlertList + API response as a typed Pydantic model + + Raises + ------ + AppwriteException + If API request fails + """ + + api_path = '/alerts' + api_params = {} + if queries is not None: + api_params['queries'] = self._normalize_value(queries) + if total is not None: + api_params['total'] = self._normalize_value(total) + + response = self.client.call( + 'get', + api_path, + { + 'X-Appwrite-Project': self.client.get_config('project'), + 'accept': 'application/json', + }, + api_params, + ) + + return self._parse_response(response, model=AlertList) + + def get( + self, + alert_id: str, + ) -> Alert: + """ + Get an alert by its unique ID: the monitor that raised it, when it fired and resolved, and the readings while it fired. + + Parameters + ---------- + alert_id : str + Alert ID. + Returns + ------- + Alert + API response as a typed Pydantic model + + Raises + ------ + AppwriteException + If API request fails + """ + + api_path = '/alerts/{alertId}' + api_params = {} + if alert_id is None or alert_id == '': + raise AppwriteException('Missing required parameter: "alert_id"') + api_path = api_path.replace('{alertId}', self._encode_path(alert_id)) + + response = self.client.call( + 'get', + api_path, + { + 'X-Appwrite-Project': self.client.get_config('project'), + 'accept': 'application/json', + }, + api_params, + ) + + return self._parse_response(response, model=Alert) + + def update( + self, + alert_id: str, + acknowledged: bool, + ) -> Alert: + """ + Acknowledge a firing alert, or undo that. Everyone who can read the alert sees who acknowledged it and when. The alert keeps firing until its monitor recovers; a resolved alert keeps its acknowledgement and cannot be changed. + + Parameters + ---------- + alert_id : str + Alert ID. + acknowledged : bool + Whether the alert is acknowledged. False undoes an acknowledgement. + Returns + ------- + Alert + API response as a typed Pydantic model + + Raises + ------ + AppwriteException + If API request fails + """ + + api_path = '/alerts/{alertId}' + api_params = {} + if alert_id is None or alert_id == '': + raise AppwriteException('Missing required parameter: "alert_id"') + if acknowledged is None: + raise AppwriteException('Missing required parameter: "acknowledged"') + api_path = api_path.replace('{alertId}', self._encode_path(alert_id)) + api_params['acknowledged'] = self._normalize_value(acknowledged) + + response = self.client.call( + 'patch', + api_path, + { + 'X-Appwrite-Project': self.client.get_config('project'), + 'content-type': 'application/json', + 'accept': 'application/json', + }, + api_params, + ) + + return self._parse_response(response, model=Alert) diff --git a/appwrite/services/monitors.py b/appwrite/services/monitors.py new file mode 100644 index 00000000..92e3729a --- /dev/null +++ b/appwrite/services/monitors.py @@ -0,0 +1,1124 @@ +from ..service import Service +from urllib.parse import quote +from typing import Any, Dict, List, Optional, Union +from ..exception import AppwriteException +from appwrite.utils.deprecated import deprecated +from ..models.monitor_list import MonitorList +from ..enums.monitor_record import MonitorRecord +from ..enums.monitor_severity import MonitorSeverity +from ..models.monitor import Monitor +from ..enums.monitor_method import MonitorMethod +from ..enums.monitor_tls_mode import MonitorTlsMode + + +class Monitors(Service): + + def __init__(self, client) -> None: + super(Monitors, self).__init__(client) + + def list( + self, + queries: Optional[List[str]] = None, + total: Optional[bool] = None, + ) -> MonitorList: + """ + Get a list of the project's monitors of every type. Use queries to filter by type, resource, severity or status, and `Query.search('search', term)` to search monitor IDs, names, metrics and resources. + + Parameters + ---------- + queries : Optional[List[str]] + Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: name, type, resourceType, resourceId, enabled, severity, escalationId, status, evaluatedAt, triggeredAt, search + total : Optional[bool] + When set to false, the total count returned will be 0 and will not be calculated. + Returns + ------- + MonitorList + API response as a typed Pydantic model + + Raises + ------ + AppwriteException + If API request fails + """ + + api_path = '/monitors' + api_params = {} + if queries is not None: + api_params['queries'] = self._normalize_value(queries) + if total is not None: + api_params['total'] = self._normalize_value(total) + + response = self.client.call( + 'get', + api_path, + { + 'X-Appwrite-Project': self.client.get_config('project'), + 'accept': 'application/json', + }, + api_params, + ) + + return self._parse_response(response, model=MonitorList) + + def create_dns_monitor( + self, + monitor_id: str, + name: str, + domain: str, + record: Optional[MonitorRecord] = None, + resolver: Optional[str] = None, + rules: Optional[List[str]] = None, + interval: Optional[float] = None, + timeout: Optional[float] = None, + cooldown: Optional[float] = None, + enabled: Optional[bool] = None, + notify: Optional[List[str]] = None, + severity: Optional[MonitorSeverity] = None, + escalation_id: Optional[str] = None, + ) -> Monitor: + """ + Create a DNS monitor. It asks a resolver for a domain's records of one type on its own interval, and opens an alert when the resolver fails, or when its rules match the answers, by default when there is no such record. Each alert fires the `monitors.[monitorId].alerts.[alertId].create` event when it opens and `.update` when a check passes again, for project webhooks, functions and realtime, and notifies the organization's members by email and in the console. + + Parameters + ---------- + monitor_id : str + Monitor ID. Choose a custom ID or generate a random ID with `ID.unique()`. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. + name : str + Monitor name. Max length: 128 chars. + domain : str + Domain to query, such as `example.com`. + record : Optional[MonitorRecord] + Record type to query: `A`, `AAAA`, `CNAME`, `MX`, `TXT` or `NS`. Defaults to `A`. + resolver : Optional[str] + Resolver to query, as an IP address with an optional port, such as `1.1.1.1` or `[2606:4700:4700::1111]:53`. Defaults to the server's DNS resolver. + rules : Optional[List[str]] + Rules that describe the failing state, as query strings generated with the Query class. The monitor fires when they match. Transport failures, such as timeouts, DNS failures, refused connections and denied targets, always fire. Variables: `answer` (the first record returned, compared lowercased without the trailing dot), `answers` (number of records returned), `latency` (milliseconds the check took). Operators: `equal`, `notEqual`, `lessThan`, `lessThanEqual`, `greaterThan`, `greaterThanEqual`, `between`, `notBetween`. `answer` takes `equal` and `notEqual` only. Combine rules with `or` and `and`; top-level rules must all match. Without rules it fires when the resolver returns no answers. + interval : Optional[float] + Seconds between two checks, between 1 and 2592000. The scheduler runs on a one second tick, so one second is the shortest interval. Defaults to 60, or to the shortest interval your plan allows when that is longer. Reads back raised to your plan's minimum interval when the plan no longer allows it. + timeout : Optional[float] + Seconds a check may take before it fails, between 1 and 60, and no longer than the interval. + cooldown : Optional[float] + Minimum seconds between two team notifications of this monitor firing, between 300 and 2592000. Events fire on every change between firing and resolved regardless. + enabled : Optional[bool] + Set to false to create the monitor without checking it. + notify : Optional[List[str]] + Organization roles whose confirmed members get an email and a console notification when the monitor fires and resolves. Each must be an organization role, such as `owner` or `developer`. Defaults to owners; pass an empty list to rely on the alert events alone. + severity : Optional[MonitorSeverity] + How urgent the monitor's alerts are: `info`, `warning`, `error` or `critical`. Critical alerts may be delivered with higher urgency by the notification channels that support it, such as a push that rings through silent mode. + escalation_id : Optional[str] + ID of an escalation of the organization that notifies the team of this monitor's alerts step by step, until a member acknowledges the alert or it resolves. When set, `notify` is not used. Leave empty to notify the `notify` roles once. + Returns + ------- + Monitor + API response as a typed Pydantic model + + Raises + ------ + AppwriteException + If API request fails + """ + + api_path = '/monitors/dns' + api_params = {} + if monitor_id is None: + raise AppwriteException('Missing required parameter: "monitor_id"') + if name is None: + raise AppwriteException('Missing required parameter: "name"') + if domain is None: + raise AppwriteException('Missing required parameter: "domain"') + api_params['monitorId'] = self._normalize_value(monitor_id) + api_params['name'] = self._normalize_value(name) + api_params['domain'] = self._normalize_value(domain) + if record is not None: + api_params['record'] = self._normalize_value(record) + if resolver is not None: + api_params['resolver'] = self._normalize_value(resolver) + if rules is not None: + api_params['rules'] = self._normalize_value(rules) + if interval is not None: + api_params['interval'] = self._normalize_value(interval) + if timeout is not None: + api_params['timeout'] = self._normalize_value(timeout) + if cooldown is not None: + api_params['cooldown'] = self._normalize_value(cooldown) + if enabled is not None: + api_params['enabled'] = self._normalize_value(enabled) + if notify is not None: + api_params['notify'] = self._normalize_value(notify) + if severity is not None: + api_params['severity'] = self._normalize_value(severity) + if escalation_id is not None: + api_params['escalationId'] = self._normalize_value(escalation_id) + + response = self.client.call( + 'post', + api_path, + { + 'X-Appwrite-Project': self.client.get_config('project'), + 'content-type': 'application/json', + 'accept': 'application/json', + }, + api_params, + ) + + return self._parse_response(response, model=Monitor) + + def update_dns_monitor( + self, + monitor_id: str, + name: Optional[str] = None, + domain: Optional[str] = None, + record: Optional[MonitorRecord] = None, + resolver: Optional[str] = None, + rules: Optional[List[str]] = None, + interval: Optional[float] = None, + timeout: Optional[float] = None, + cooldown: Optional[float] = None, + enabled: Optional[bool] = None, + notify: Optional[List[str]] = None, + severity: Optional[MonitorSeverity] = None, + escalation_id: Optional[str] = None, + ) -> Monitor: + """ + Update a DNS monitor by its unique ID. Only the parameters passed change; the monitor's state, its last check and its open alert are kept. Passing `rules` replaces all of them. + + Parameters + ---------- + monitor_id : str + Monitor ID. + name : Optional[str] + Monitor name. Max length: 128 chars. + domain : Optional[str] + Domain to query, such as `example.com`. + record : Optional[MonitorRecord] + Record type to query: `A`, `AAAA`, `CNAME`, `MX`, `TXT` or `NS`. + resolver : Optional[str] + Resolver to query, as an IP address with an optional port, such as `1.1.1.1` or `[2606:4700:4700::1111]:53`. Pass an empty string to use the server's DNS resolver. + rules : Optional[List[str]] + Rules that describe the failing state, as query strings generated with the Query class. The monitor fires when they match. Transport failures, such as timeouts, DNS failures, refused connections and denied targets, always fire. Variables: `answer` (the first record returned, compared lowercased without the trailing dot), `answers` (number of records returned), `latency` (milliseconds the check took). Operators: `equal`, `notEqual`, `lessThan`, `lessThanEqual`, `greaterThan`, `greaterThanEqual`, `between`, `notBetween`. `answer` takes `equal` and `notEqual` only. Combine rules with `or` and `and`; top-level rules must all match. Without rules it fires when the resolver returns no answers. Replaces the current rules; an empty list restores the defaults. + interval : Optional[float] + Seconds between two checks, between 1 and 2592000. The scheduler runs on a one second tick, so one second is the shortest interval. Reads back raised to your plan's minimum interval when the plan no longer allows it. + timeout : Optional[float] + Seconds a check may take before it fails, between 1 and 60, and no longer than the interval. + cooldown : Optional[float] + Minimum seconds between two team notifications of this monitor firing, between 300 and 2592000. Events fire on every change between firing and resolved regardless. + enabled : Optional[bool] + Whether the monitor is checked. + notify : Optional[List[str]] + Organization roles whose confirmed members get an email and a console notification when the monitor fires and resolves. Each must be an organization role, such as `owner` or `developer`. Pass an empty list to rely on the alert events alone. + severity : Optional[MonitorSeverity] + How urgent the monitor's alerts are: `info`, `warning`, `error` or `critical`. Critical alerts may be delivered with higher urgency by the notification channels that support it, such as a push that rings through silent mode. + escalation_id : Optional[str] + ID of an escalation of the organization that notifies the team of this monitor's alerts step by step, until a member acknowledges the alert or it resolves. When set, `notify` is not used. Pass an empty string to go back to the `notify` roles. + Returns + ------- + Monitor + API response as a typed Pydantic model + + Raises + ------ + AppwriteException + If API request fails + """ + + api_path = '/monitors/dns/{monitorId}' + api_params = {} + if monitor_id is None or monitor_id == '': + raise AppwriteException('Missing required parameter: "monitor_id"') + api_path = api_path.replace('{monitorId}', self._encode_path(monitor_id)) + if name is not None: + api_params['name'] = self._normalize_value(name) + if domain is not None: + api_params['domain'] = self._normalize_value(domain) + if record is not None: + api_params['record'] = self._normalize_value(record) + if resolver is not None: + api_params['resolver'] = self._normalize_value(resolver) + if rules is not None: + api_params['rules'] = self._normalize_value(rules) + if interval is not None: + api_params['interval'] = self._normalize_value(interval) + if timeout is not None: + api_params['timeout'] = self._normalize_value(timeout) + if cooldown is not None: + api_params['cooldown'] = self._normalize_value(cooldown) + if enabled is not None: + api_params['enabled'] = self._normalize_value(enabled) + if notify is not None: + api_params['notify'] = self._normalize_value(notify) + if severity is not None: + api_params['severity'] = self._normalize_value(severity) + if escalation_id is not None: + api_params['escalationId'] = self._normalize_value(escalation_id) + + response = self.client.call( + 'patch', + api_path, + { + 'X-Appwrite-Project': self.client.get_config('project'), + 'content-type': 'application/json', + 'accept': 'application/json', + }, + api_params, + ) + + return self._parse_response(response, model=Monitor) + + def create_http_monitor( + self, + monitor_id: str, + name: str, + url: str, + method: Optional[MonitorMethod] = None, + headers: Optional[Dict[str, Any]] = None, + body: Optional[str] = None, + rules: Optional[List[str]] = None, + interval: Optional[float] = None, + timeout: Optional[float] = None, + cooldown: Optional[float] = None, + enabled: Optional[bool] = None, + notify: Optional[List[str]] = None, + severity: Optional[MonitorSeverity] = None, + escalation_id: Optional[str] = None, + ) -> Monitor: + """ + Create an HTTP monitor. It requests a URL on its own interval, following redirects, and opens an alert when the request fails or when its rules match the response, by default a status outside 2xx or the certificate of an HTTPS URL about to expire. The response body is discarded as it arrives. Each alert fires the `monitors.[monitorId].alerts.[alertId].create` event when it opens and `.update` when a check passes again, for project webhooks, functions and realtime, and notifies the organization's members by email and in the console. + + Parameters + ---------- + monitor_id : str + Monitor ID. Choose a custom ID or generate a random ID with `ID.unique()`. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. + name : str + Monitor name. Max length: 128 chars. + url : str + URL to request, with an `http` or `https` scheme. + method : Optional[MonitorMethod] + HTTP method to request the URL with: `GET`, `HEAD`, `POST`, `PUT`, `PATCH`, `DELETE` or `OPTIONS`. Defaults to `GET`. + headers : Optional[Dict[str, Any]] + HTTP headers to send, as an object of header names and values. Each name must be a valid HTTP header name. + body : Optional[str] + Request body to send. Max length: 16384 chars. + rules : Optional[List[str]] + Rules that describe the failing state, as query strings generated with the Query class. The monitor fires when they match. Transport failures, such as timeouts, DNS failures, refused connections and denied targets, always fire. Variables: `statusCode` (HTTP status), `latency` (milliseconds the check took), `certificateDays` (whole days until the certificate expires), `certificateLifetime` (percent of the certificate's lifetime left). Operators: `equal`, `notEqual`, `lessThan`, `lessThanEqual`, `greaterThan`, `greaterThanEqual`, `between`, `notBetween`. Combine rules with `or` and `and`; top-level rules must all match. Without rules it fires on a status code outside 200 to 299, or on a certificate with fewer than 14 days and less than 25% of its lifetime left. + interval : Optional[float] + Seconds between two checks, between 1 and 2592000. The scheduler runs on a one second tick, so one second is the shortest interval. Defaults to 60, or to the shortest interval your plan allows when that is longer. Reads back raised to your plan's minimum interval when the plan no longer allows it. + timeout : Optional[float] + Seconds a check may take before it fails, between 1 and 60, and no longer than the interval. + cooldown : Optional[float] + Minimum seconds between two team notifications of this monitor firing, between 300 and 2592000. Events fire on every change between firing and resolved regardless. + enabled : Optional[bool] + Set to false to create the monitor without checking it. + notify : Optional[List[str]] + Organization roles whose confirmed members get an email and a console notification when the monitor fires and resolves. Each must be an organization role, such as `owner` or `developer`. Defaults to owners; pass an empty list to rely on the alert events alone. + severity : Optional[MonitorSeverity] + How urgent the monitor's alerts are: `info`, `warning`, `error` or `critical`. Critical alerts may be delivered with higher urgency by the notification channels that support it, such as a push that rings through silent mode. + escalation_id : Optional[str] + ID of an escalation of the organization that notifies the team of this monitor's alerts step by step, until a member acknowledges the alert or it resolves. When set, `notify` is not used. Leave empty to notify the `notify` roles once. + Returns + ------- + Monitor + API response as a typed Pydantic model + + Raises + ------ + AppwriteException + If API request fails + """ + + api_path = '/monitors/http' + api_params = {} + if monitor_id is None: + raise AppwriteException('Missing required parameter: "monitor_id"') + if name is None: + raise AppwriteException('Missing required parameter: "name"') + if url is None: + raise AppwriteException('Missing required parameter: "url"') + api_params['monitorId'] = self._normalize_value(monitor_id) + api_params['name'] = self._normalize_value(name) + api_params['url'] = self._normalize_value(url) + if method is not None: + api_params['method'] = self._normalize_value(method) + if headers is not None: + api_params['headers'] = self._normalize_value(headers) + if body is not None: + api_params['body'] = self._normalize_value(body) + if rules is not None: + api_params['rules'] = self._normalize_value(rules) + if interval is not None: + api_params['interval'] = self._normalize_value(interval) + if timeout is not None: + api_params['timeout'] = self._normalize_value(timeout) + if cooldown is not None: + api_params['cooldown'] = self._normalize_value(cooldown) + if enabled is not None: + api_params['enabled'] = self._normalize_value(enabled) + if notify is not None: + api_params['notify'] = self._normalize_value(notify) + if severity is not None: + api_params['severity'] = self._normalize_value(severity) + if escalation_id is not None: + api_params['escalationId'] = self._normalize_value(escalation_id) + + response = self.client.call( + 'post', + api_path, + { + 'X-Appwrite-Project': self.client.get_config('project'), + 'content-type': 'application/json', + 'accept': 'application/json', + }, + api_params, + ) + + return self._parse_response(response, model=Monitor) + + def update_http_monitor( + self, + monitor_id: str, + name: Optional[str] = None, + url: Optional[str] = None, + method: Optional[MonitorMethod] = None, + headers: Optional[Dict[str, Any]] = None, + body: Optional[str] = None, + rules: Optional[List[str]] = None, + interval: Optional[float] = None, + timeout: Optional[float] = None, + cooldown: Optional[float] = None, + enabled: Optional[bool] = None, + notify: Optional[List[str]] = None, + severity: Optional[MonitorSeverity] = None, + escalation_id: Optional[str] = None, + ) -> Monitor: + """ + Update an HTTP monitor by its unique ID. Only the parameters passed change; the monitor's state, its last check and its open alert are kept. Passing `rules` replaces all of them. + + Parameters + ---------- + monitor_id : str + Monitor ID. + name : Optional[str] + Monitor name. Max length: 128 chars. + url : Optional[str] + URL to request, with an `http` or `https` scheme. + method : Optional[MonitorMethod] + HTTP method to request the URL with: `GET`, `HEAD`, `POST`, `PUT`, `PATCH`, `DELETE` or `OPTIONS`. + headers : Optional[Dict[str, Any]] + HTTP headers to send, as an object of header names and values. Each name must be a valid HTTP header name. + body : Optional[str] + Request body to send. Max length: 16384 chars. + rules : Optional[List[str]] + Rules that describe the failing state, as query strings generated with the Query class. The monitor fires when they match. Transport failures, such as timeouts, DNS failures, refused connections and denied targets, always fire. Variables: `statusCode` (HTTP status), `latency` (milliseconds the check took), `certificateDays` (whole days until the certificate expires), `certificateLifetime` (percent of the certificate's lifetime left). Operators: `equal`, `notEqual`, `lessThan`, `lessThanEqual`, `greaterThan`, `greaterThanEqual`, `between`, `notBetween`. Combine rules with `or` and `and`; top-level rules must all match. Without rules it fires on a status code outside 200 to 299, or on a certificate with fewer than 14 days and less than 25% of its lifetime left. Replaces the current rules; an empty list restores the defaults. + interval : Optional[float] + Seconds between two checks, between 1 and 2592000. The scheduler runs on a one second tick, so one second is the shortest interval. Reads back raised to your plan's minimum interval when the plan no longer allows it. + timeout : Optional[float] + Seconds a check may take before it fails, between 1 and 60, and no longer than the interval. + cooldown : Optional[float] + Minimum seconds between two team notifications of this monitor firing, between 300 and 2592000. Events fire on every change between firing and resolved regardless. + enabled : Optional[bool] + Whether the monitor is checked. + notify : Optional[List[str]] + Organization roles whose confirmed members get an email and a console notification when the monitor fires and resolves. Each must be an organization role, such as `owner` or `developer`. Pass an empty list to rely on the alert events alone. + severity : Optional[MonitorSeverity] + How urgent the monitor's alerts are: `info`, `warning`, `error` or `critical`. Critical alerts may be delivered with higher urgency by the notification channels that support it, such as a push that rings through silent mode. + escalation_id : Optional[str] + ID of an escalation of the organization that notifies the team of this monitor's alerts step by step, until a member acknowledges the alert or it resolves. When set, `notify` is not used. Pass an empty string to go back to the `notify` roles. + Returns + ------- + Monitor + API response as a typed Pydantic model + + Raises + ------ + AppwriteException + If API request fails + """ + + api_path = '/monitors/http/{monitorId}' + api_params = {} + if monitor_id is None or monitor_id == '': + raise AppwriteException('Missing required parameter: "monitor_id"') + api_path = api_path.replace('{monitorId}', self._encode_path(monitor_id)) + if name is not None: + api_params['name'] = self._normalize_value(name) + if url is not None: + api_params['url'] = self._normalize_value(url) + if method is not None: + api_params['method'] = self._normalize_value(method) + if headers is not None: + api_params['headers'] = self._normalize_value(headers) + if body is not None: + api_params['body'] = self._normalize_value(body) + if rules is not None: + api_params['rules'] = self._normalize_value(rules) + if interval is not None: + api_params['interval'] = self._normalize_value(interval) + if timeout is not None: + api_params['timeout'] = self._normalize_value(timeout) + if cooldown is not None: + api_params['cooldown'] = self._normalize_value(cooldown) + if enabled is not None: + api_params['enabled'] = self._normalize_value(enabled) + if notify is not None: + api_params['notify'] = self._normalize_value(notify) + if severity is not None: + api_params['severity'] = self._normalize_value(severity) + if escalation_id is not None: + api_params['escalationId'] = self._normalize_value(escalation_id) + + response = self.client.call( + 'patch', + api_path, + { + 'X-Appwrite-Project': self.client.get_config('project'), + 'content-type': 'application/json', + 'accept': 'application/json', + }, + api_params, + ) + + return self._parse_response(response, model=Monitor) + + def create_smtp_monitor( + self, + monitor_id: str, + name: str, + host: str, + port: float, + tls_mode: Optional[MonitorTlsMode] = None, + rules: Optional[List[str]] = None, + interval: Optional[float] = None, + timeout: Optional[float] = None, + cooldown: Optional[float] = None, + enabled: Optional[bool] = None, + notify: Optional[List[str]] = None, + severity: Optional[MonitorSeverity] = None, + escalation_id: Optional[str] = None, + ) -> Monitor: + """ + Create an SMTP monitor. It reads a mail server's greeting, sends `EHLO` and, as its TLS mode asks, upgrades with `STARTTLS` or speaks TLS from the start, on its own interval. It opens an alert when the server cannot be reached, refuses the session or fails the TLS handshake, or when its rules match. It never authenticates or sends mail. Each alert fires the `monitors.[monitorId].alerts.[alertId].create` event when it opens and `.update` when a check passes again, for project webhooks, functions and realtime, and notifies the organization's members by email and in the console. + + Parameters + ---------- + monitor_id : str + Monitor ID. Choose a custom ID or generate a random ID with `ID.unique()`. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. + name : str + Monitor name. Max length: 128 chars. + host : str + Hostname or IP address of the mail server. + port : float + Port to connect to, such as 25, 465 or 587. + tls_mode : Optional[MonitorTlsMode] + TLS mode: `auto` (`implicit` on port 465, `starttls` on 587 and `none` otherwise), `none`, `starttls` (upgrade after the greeting, and fail when the server does not offer it) or `implicit` (TLS from the first byte). Defaults to `auto`. + rules : Optional[List[str]] + Rules that describe the failing state, as query strings generated with the Query class. The monitor fires when they match. Transport failures, such as timeouts, DNS failures, refused connections and denied targets, always fire. Variables: `code` (SMTP reply code), `latency` (milliseconds the check took), `certificateDays` (whole days until the certificate expires), `certificateLifetime` (percent of the certificate's lifetime left). Operators: `equal`, `notEqual`, `lessThan`, `lessThanEqual`, `greaterThan`, `greaterThanEqual`, `between`, `notBetween`. Combine rules with `or` and `and`; top-level rules must all match. Without rules it fires on transport failures only. + interval : Optional[float] + Seconds between two checks, between 1 and 2592000. The scheduler runs on a one second tick, so one second is the shortest interval. Defaults to 60, or to the shortest interval your plan allows when that is longer. Reads back raised to your plan's minimum interval when the plan no longer allows it. + timeout : Optional[float] + Seconds a check may take before it fails, between 1 and 60, and no longer than the interval. + cooldown : Optional[float] + Minimum seconds between two team notifications of this monitor firing, between 300 and 2592000. Events fire on every change between firing and resolved regardless. + enabled : Optional[bool] + Set to false to create the monitor without checking it. + notify : Optional[List[str]] + Organization roles whose confirmed members get an email and a console notification when the monitor fires and resolves. Each must be an organization role, such as `owner` or `developer`. Defaults to owners; pass an empty list to rely on the alert events alone. + severity : Optional[MonitorSeverity] + How urgent the monitor's alerts are: `info`, `warning`, `error` or `critical`. Critical alerts may be delivered with higher urgency by the notification channels that support it, such as a push that rings through silent mode. + escalation_id : Optional[str] + ID of an escalation of the organization that notifies the team of this monitor's alerts step by step, until a member acknowledges the alert or it resolves. When set, `notify` is not used. Leave empty to notify the `notify` roles once. + Returns + ------- + Monitor + API response as a typed Pydantic model + + Raises + ------ + AppwriteException + If API request fails + """ + + api_path = '/monitors/smtp' + api_params = {} + if monitor_id is None: + raise AppwriteException('Missing required parameter: "monitor_id"') + if name is None: + raise AppwriteException('Missing required parameter: "name"') + if host is None: + raise AppwriteException('Missing required parameter: "host"') + if port is None: + raise AppwriteException('Missing required parameter: "port"') + api_params['monitorId'] = self._normalize_value(monitor_id) + api_params['name'] = self._normalize_value(name) + api_params['host'] = self._normalize_value(host) + api_params['port'] = self._normalize_value(port) + if tls_mode is not None: + api_params['tlsMode'] = self._normalize_value(tls_mode) + if rules is not None: + api_params['rules'] = self._normalize_value(rules) + if interval is not None: + api_params['interval'] = self._normalize_value(interval) + if timeout is not None: + api_params['timeout'] = self._normalize_value(timeout) + if cooldown is not None: + api_params['cooldown'] = self._normalize_value(cooldown) + if enabled is not None: + api_params['enabled'] = self._normalize_value(enabled) + if notify is not None: + api_params['notify'] = self._normalize_value(notify) + if severity is not None: + api_params['severity'] = self._normalize_value(severity) + if escalation_id is not None: + api_params['escalationId'] = self._normalize_value(escalation_id) + + response = self.client.call( + 'post', + api_path, + { + 'X-Appwrite-Project': self.client.get_config('project'), + 'content-type': 'application/json', + 'accept': 'application/json', + }, + api_params, + ) + + return self._parse_response(response, model=Monitor) + + def update_smtp_monitor( + self, + monitor_id: str, + name: Optional[str] = None, + host: Optional[str] = None, + port: Optional[float] = None, + tls_mode: Optional[MonitorTlsMode] = None, + rules: Optional[List[str]] = None, + interval: Optional[float] = None, + timeout: Optional[float] = None, + cooldown: Optional[float] = None, + enabled: Optional[bool] = None, + notify: Optional[List[str]] = None, + severity: Optional[MonitorSeverity] = None, + escalation_id: Optional[str] = None, + ) -> Monitor: + """ + Update an SMTP monitor by its unique ID. Only the parameters passed change; the monitor's state, its last check and its open alert are kept. Passing `rules` replaces all of them. + + Parameters + ---------- + monitor_id : str + Monitor ID. + name : Optional[str] + Monitor name. Max length: 128 chars. + host : Optional[str] + Hostname or IP address of the mail server. + port : Optional[float] + Port to connect to, such as 25, 465 or 587. + tls_mode : Optional[MonitorTlsMode] + TLS mode: `auto` (`implicit` on port 465, `starttls` on 587 and `none` otherwise), `none`, `starttls` (upgrade after the greeting, and fail when the server does not offer it) or `implicit` (TLS from the first byte). + rules : Optional[List[str]] + Rules that describe the failing state, as query strings generated with the Query class. The monitor fires when they match. Transport failures, such as timeouts, DNS failures, refused connections and denied targets, always fire. Variables: `code` (SMTP reply code), `latency` (milliseconds the check took), `certificateDays` (whole days until the certificate expires), `certificateLifetime` (percent of the certificate's lifetime left). Operators: `equal`, `notEqual`, `lessThan`, `lessThanEqual`, `greaterThan`, `greaterThanEqual`, `between`, `notBetween`. Combine rules with `or` and `and`; top-level rules must all match. Without rules it fires on transport failures only. Replaces the current rules; an empty list removes them. + interval : Optional[float] + Seconds between two checks, between 1 and 2592000. The scheduler runs on a one second tick, so one second is the shortest interval. Reads back raised to your plan's minimum interval when the plan no longer allows it. + timeout : Optional[float] + Seconds a check may take before it fails, between 1 and 60, and no longer than the interval. + cooldown : Optional[float] + Minimum seconds between two team notifications of this monitor firing, between 300 and 2592000. Events fire on every change between firing and resolved regardless. + enabled : Optional[bool] + Whether the monitor is checked. + notify : Optional[List[str]] + Organization roles whose confirmed members get an email and a console notification when the monitor fires and resolves. Each must be an organization role, such as `owner` or `developer`. Pass an empty list to rely on the alert events alone. + severity : Optional[MonitorSeverity] + How urgent the monitor's alerts are: `info`, `warning`, `error` or `critical`. Critical alerts may be delivered with higher urgency by the notification channels that support it, such as a push that rings through silent mode. + escalation_id : Optional[str] + ID of an escalation of the organization that notifies the team of this monitor's alerts step by step, until a member acknowledges the alert or it resolves. When set, `notify` is not used. Pass an empty string to go back to the `notify` roles. + Returns + ------- + Monitor + API response as a typed Pydantic model + + Raises + ------ + AppwriteException + If API request fails + """ + + api_path = '/monitors/smtp/{monitorId}' + api_params = {} + if monitor_id is None or monitor_id == '': + raise AppwriteException('Missing required parameter: "monitor_id"') + api_path = api_path.replace('{monitorId}', self._encode_path(monitor_id)) + if name is not None: + api_params['name'] = self._normalize_value(name) + if host is not None: + api_params['host'] = self._normalize_value(host) + if port is not None: + api_params['port'] = self._normalize_value(port) + if tls_mode is not None: + api_params['tlsMode'] = self._normalize_value(tls_mode) + if rules is not None: + api_params['rules'] = self._normalize_value(rules) + if interval is not None: + api_params['interval'] = self._normalize_value(interval) + if timeout is not None: + api_params['timeout'] = self._normalize_value(timeout) + if cooldown is not None: + api_params['cooldown'] = self._normalize_value(cooldown) + if enabled is not None: + api_params['enabled'] = self._normalize_value(enabled) + if notify is not None: + api_params['notify'] = self._normalize_value(notify) + if severity is not None: + api_params['severity'] = self._normalize_value(severity) + if escalation_id is not None: + api_params['escalationId'] = self._normalize_value(escalation_id) + + response = self.client.call( + 'patch', + api_path, + { + 'X-Appwrite-Project': self.client.get_config('project'), + 'content-type': 'application/json', + 'accept': 'application/json', + }, + api_params, + ) + + return self._parse_response(response, model=Monitor) + + def create_tcp_monitor( + self, + monitor_id: str, + name: str, + host: str, + port: float, + rules: Optional[List[str]] = None, + interval: Optional[float] = None, + timeout: Optional[float] = None, + cooldown: Optional[float] = None, + enabled: Optional[bool] = None, + notify: Optional[List[str]] = None, + severity: Optional[MonitorSeverity] = None, + escalation_id: Optional[str] = None, + ) -> Monitor: + """ + Create a TCP monitor. It opens a connection to a host and port on its own interval and closes it at once, and opens an alert when the connection cannot be made, or when its rules match. Each alert fires the `monitors.[monitorId].alerts.[alertId].create` event when it opens and `.update` when a check passes again, for project webhooks, functions and realtime, and notifies the organization's members by email and in the console. + + Parameters + ---------- + monitor_id : str + Monitor ID. Choose a custom ID or generate a random ID with `ID.unique()`. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. + name : str + Monitor name. Max length: 128 chars. + host : str + Hostname or IP address to connect to. + port : float + Port to connect to. + rules : Optional[List[str]] + Rules that describe the failing state, as query strings generated with the Query class. The monitor fires when they match. Transport failures, such as timeouts, DNS failures, refused connections and denied targets, always fire. Variables: `latency` (milliseconds the check took). Operators: `equal`, `notEqual`, `lessThan`, `lessThanEqual`, `greaterThan`, `greaterThanEqual`, `between`, `notBetween`. Combine rules with `or` and `and`; top-level rules must all match. Without rules it fires on transport failures only. + interval : Optional[float] + Seconds between two checks, between 1 and 2592000. The scheduler runs on a one second tick, so one second is the shortest interval. Defaults to 60, or to the shortest interval your plan allows when that is longer. Reads back raised to your plan's minimum interval when the plan no longer allows it. + timeout : Optional[float] + Seconds a check may take before it fails, between 1 and 60, and no longer than the interval. + cooldown : Optional[float] + Minimum seconds between two team notifications of this monitor firing, between 300 and 2592000. Events fire on every change between firing and resolved regardless. + enabled : Optional[bool] + Set to false to create the monitor without checking it. + notify : Optional[List[str]] + Organization roles whose confirmed members get an email and a console notification when the monitor fires and resolves. Each must be an organization role, such as `owner` or `developer`. Defaults to owners; pass an empty list to rely on the alert events alone. + severity : Optional[MonitorSeverity] + How urgent the monitor's alerts are: `info`, `warning`, `error` or `critical`. Critical alerts may be delivered with higher urgency by the notification channels that support it, such as a push that rings through silent mode. + escalation_id : Optional[str] + ID of an escalation of the organization that notifies the team of this monitor's alerts step by step, until a member acknowledges the alert or it resolves. When set, `notify` is not used. Leave empty to notify the `notify` roles once. + Returns + ------- + Monitor + API response as a typed Pydantic model + + Raises + ------ + AppwriteException + If API request fails + """ + + api_path = '/monitors/tcp' + api_params = {} + if monitor_id is None: + raise AppwriteException('Missing required parameter: "monitor_id"') + if name is None: + raise AppwriteException('Missing required parameter: "name"') + if host is None: + raise AppwriteException('Missing required parameter: "host"') + if port is None: + raise AppwriteException('Missing required parameter: "port"') + api_params['monitorId'] = self._normalize_value(monitor_id) + api_params['name'] = self._normalize_value(name) + api_params['host'] = self._normalize_value(host) + api_params['port'] = self._normalize_value(port) + if rules is not None: + api_params['rules'] = self._normalize_value(rules) + if interval is not None: + api_params['interval'] = self._normalize_value(interval) + if timeout is not None: + api_params['timeout'] = self._normalize_value(timeout) + if cooldown is not None: + api_params['cooldown'] = self._normalize_value(cooldown) + if enabled is not None: + api_params['enabled'] = self._normalize_value(enabled) + if notify is not None: + api_params['notify'] = self._normalize_value(notify) + if severity is not None: + api_params['severity'] = self._normalize_value(severity) + if escalation_id is not None: + api_params['escalationId'] = self._normalize_value(escalation_id) + + response = self.client.call( + 'post', + api_path, + { + 'X-Appwrite-Project': self.client.get_config('project'), + 'content-type': 'application/json', + 'accept': 'application/json', + }, + api_params, + ) + + return self._parse_response(response, model=Monitor) + + def update_tcp_monitor( + self, + monitor_id: str, + name: Optional[str] = None, + host: Optional[str] = None, + port: Optional[float] = None, + rules: Optional[List[str]] = None, + interval: Optional[float] = None, + timeout: Optional[float] = None, + cooldown: Optional[float] = None, + enabled: Optional[bool] = None, + notify: Optional[List[str]] = None, + severity: Optional[MonitorSeverity] = None, + escalation_id: Optional[str] = None, + ) -> Monitor: + """ + Update a TCP monitor by its unique ID. Only the parameters passed change; the monitor's state, its last check and its open alert are kept. Passing `rules` replaces all of them. + + Parameters + ---------- + monitor_id : str + Monitor ID. + name : Optional[str] + Monitor name. Max length: 128 chars. + host : Optional[str] + Hostname or IP address to connect to. + port : Optional[float] + Port to connect to. + rules : Optional[List[str]] + Rules that describe the failing state, as query strings generated with the Query class. The monitor fires when they match. Transport failures, such as timeouts, DNS failures, refused connections and denied targets, always fire. Variables: `latency` (milliseconds the check took). Operators: `equal`, `notEqual`, `lessThan`, `lessThanEqual`, `greaterThan`, `greaterThanEqual`, `between`, `notBetween`. Combine rules with `or` and `and`; top-level rules must all match. Without rules it fires on transport failures only. Replaces the current rules; an empty list removes them. + interval : Optional[float] + Seconds between two checks, between 1 and 2592000. The scheduler runs on a one second tick, so one second is the shortest interval. Reads back raised to your plan's minimum interval when the plan no longer allows it. + timeout : Optional[float] + Seconds a check may take before it fails, between 1 and 60, and no longer than the interval. + cooldown : Optional[float] + Minimum seconds between two team notifications of this monitor firing, between 300 and 2592000. Events fire on every change between firing and resolved regardless. + enabled : Optional[bool] + Whether the monitor is checked. + notify : Optional[List[str]] + Organization roles whose confirmed members get an email and a console notification when the monitor fires and resolves. Each must be an organization role, such as `owner` or `developer`. Pass an empty list to rely on the alert events alone. + severity : Optional[MonitorSeverity] + How urgent the monitor's alerts are: `info`, `warning`, `error` or `critical`. Critical alerts may be delivered with higher urgency by the notification channels that support it, such as a push that rings through silent mode. + escalation_id : Optional[str] + ID of an escalation of the organization that notifies the team of this monitor's alerts step by step, until a member acknowledges the alert or it resolves. When set, `notify` is not used. Pass an empty string to go back to the `notify` roles. + Returns + ------- + Monitor + API response as a typed Pydantic model + + Raises + ------ + AppwriteException + If API request fails + """ + + api_path = '/monitors/tcp/{monitorId}' + api_params = {} + if monitor_id is None or monitor_id == '': + raise AppwriteException('Missing required parameter: "monitor_id"') + api_path = api_path.replace('{monitorId}', self._encode_path(monitor_id)) + if name is not None: + api_params['name'] = self._normalize_value(name) + if host is not None: + api_params['host'] = self._normalize_value(host) + if port is not None: + api_params['port'] = self._normalize_value(port) + if rules is not None: + api_params['rules'] = self._normalize_value(rules) + if interval is not None: + api_params['interval'] = self._normalize_value(interval) + if timeout is not None: + api_params['timeout'] = self._normalize_value(timeout) + if cooldown is not None: + api_params['cooldown'] = self._normalize_value(cooldown) + if enabled is not None: + api_params['enabled'] = self._normalize_value(enabled) + if notify is not None: + api_params['notify'] = self._normalize_value(notify) + if severity is not None: + api_params['severity'] = self._normalize_value(severity) + if escalation_id is not None: + api_params['escalationId'] = self._normalize_value(escalation_id) + + response = self.client.call( + 'patch', + api_path, + { + 'X-Appwrite-Project': self.client.get_config('project'), + 'content-type': 'application/json', + 'accept': 'application/json', + }, + api_params, + ) + + return self._parse_response(response, model=Monitor) + + def create_usage_monitor( + self, + monitor_id: str, + name: str, + rules: List[str], + window: Optional[float] = None, + cooldown: Optional[float] = None, + enabled: Optional[bool] = None, + notify: Optional[List[str]] = None, + severity: Optional[MonitorSeverity] = None, + escalation_id: Optional[str] = None, + ) -> Monitor: + """ + Create a usage monitor. It reads a usage metric of the project, or of one of its databases, buckets, functions or sites, on a schedule, and opens an alert when all its rules hold. Each alert fires the `monitors.[monitorId].alerts.[alertId].create` event when it opens and `.update` when usage recovers, for project webhooks, functions and realtime, and notifies the confirmed members of the `notify` roles by email and in the console, or the steps of the escalation set by `escalationId`. + + Parameters + ---------- + monitor_id : str + Monitor ID. Choose a custom ID or generate a random ID with `ID.unique()`. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. + name : str + Monitor name. Max length: 128 chars. + rules : List[str] + Rules that must all hold for the monitor to fire, as query strings generated with the Query class: one comparing a usage metric, named as the usage endpoints name it (such as `network.outbound` or `databases.operations.reads`), with a threshold in the metric's unit (bytes for storage and bandwidth, MB-seconds for GB-hours, a count otherwise), and optionally `equal` rules on `resourceType` and `resourceId` to watch one database, bucket, function or site instead of the whole project. + window : Optional[float] + Seconds a counter metric is summed over, between 60 and 2592000. Gauges compare their latest value. + cooldown : Optional[float] + Minimum seconds between two team notifications of this monitor firing, between 300 and 2592000. Events fire on every change between firing and resolved regardless. + enabled : Optional[bool] + Set to false to create the monitor without evaluating it. + notify : Optional[List[str]] + Organization roles whose confirmed members get an email and a console notification when the monitor fires and resolves. Each must be an organization role, such as `owner` or `developer`. Defaults to owners; pass an empty list to rely on the alert events alone. + severity : Optional[MonitorSeverity] + How urgent the monitor's alerts are: `info`, `warning`, `error` or `critical`. Critical alerts may be delivered with higher urgency by the notification channels that support it, such as a push that rings through silent mode. + escalation_id : Optional[str] + ID of an escalation of the organization that notifies the team of this monitor's alerts step by step, until a member acknowledges the alert or it resolves. When set, `notify` is not used. Leave empty to notify the `notify` roles once. + Returns + ------- + Monitor + API response as a typed Pydantic model + + Raises + ------ + AppwriteException + If API request fails + """ + + api_path = '/monitors/usage' + api_params = {} + if monitor_id is None: + raise AppwriteException('Missing required parameter: "monitor_id"') + if name is None: + raise AppwriteException('Missing required parameter: "name"') + if rules is None: + raise AppwriteException('Missing required parameter: "rules"') + api_params['monitorId'] = self._normalize_value(monitor_id) + api_params['name'] = self._normalize_value(name) + api_params['rules'] = self._normalize_value(rules) + if window is not None: + api_params['window'] = self._normalize_value(window) + if cooldown is not None: + api_params['cooldown'] = self._normalize_value(cooldown) + if enabled is not None: + api_params['enabled'] = self._normalize_value(enabled) + if notify is not None: + api_params['notify'] = self._normalize_value(notify) + if severity is not None: + api_params['severity'] = self._normalize_value(severity) + if escalation_id is not None: + api_params['escalationId'] = self._normalize_value(escalation_id) + + response = self.client.call( + 'post', + api_path, + { + 'X-Appwrite-Project': self.client.get_config('project'), + 'content-type': 'application/json', + 'accept': 'application/json', + }, + api_params, + ) + + return self._parse_response(response, model=Monitor) + + def update_usage_monitor( + self, + monitor_id: str, + name: Optional[str] = None, + rules: Optional[List[str]] = None, + window: Optional[float] = None, + cooldown: Optional[float] = None, + enabled: Optional[bool] = None, + notify: Optional[List[str]] = None, + severity: Optional[MonitorSeverity] = None, + escalation_id: Optional[str] = None, + ) -> Monitor: + """ + Update a usage monitor by its unique ID. Only the parameters passed change; the monitor's state and its open alert are kept. Passing `rules` replaces all of them. + + Parameters + ---------- + monitor_id : str + Monitor ID. + name : Optional[str] + Monitor name. Max length: 128 chars. + rules : Optional[List[str]] + Rules that must all hold for the monitor to fire, as query strings generated with the Query class: one comparing a usage metric, named as the usage endpoints name it (such as `network.outbound` or `databases.operations.reads`), with a threshold in the metric's unit (bytes for storage and bandwidth, MB-seconds for GB-hours, a count otherwise), and optionally `equal` rules on `resourceType` and `resourceId` to watch one database, bucket, function or site instead of the whole project. Replaces the current rules. + window : Optional[float] + Seconds a counter metric is summed over, between 60 and 2592000. Gauges compare their latest value. + cooldown : Optional[float] + Minimum seconds between two team notifications of this monitor firing, between 300 and 2592000. Events fire on every change between firing and resolved regardless. + enabled : Optional[bool] + Whether the monitor is evaluated. + notify : Optional[List[str]] + Organization roles whose confirmed members get an email and a console notification when the monitor fires and resolves. Each must be an organization role, such as `owner` or `developer`. Pass an empty list to rely on the alert events alone; pass null or omit to keep the current roles. + severity : Optional[MonitorSeverity] + How urgent the monitor's alerts are: `info`, `warning`, `error` or `critical`. Critical alerts may be delivered with higher urgency by the notification channels that support it, such as a push that rings through silent mode. Omit to keep the current one. + escalation_id : Optional[str] + ID of an escalation of the organization that notifies the team of this monitor's alerts step by step, until a member acknowledges the alert or it resolves. When set, `notify` is not used. Pass an empty string to go back to the `notify` roles; pass null or omit to keep the current one. + Returns + ------- + Monitor + API response as a typed Pydantic model + + Raises + ------ + AppwriteException + If API request fails + """ + + api_path = '/monitors/usage/{monitorId}' + api_params = {} + if monitor_id is None or monitor_id == '': + raise AppwriteException('Missing required parameter: "monitor_id"') + api_path = api_path.replace('{monitorId}', self._encode_path(monitor_id)) + if name is not None: + api_params['name'] = self._normalize_value(name) + if rules is not None: + api_params['rules'] = self._normalize_value(rules) + if window is not None: + api_params['window'] = self._normalize_value(window) + if cooldown is not None: + api_params['cooldown'] = self._normalize_value(cooldown) + if enabled is not None: + api_params['enabled'] = self._normalize_value(enabled) + if notify is not None: + api_params['notify'] = self._normalize_value(notify) + if severity is not None: + api_params['severity'] = self._normalize_value(severity) + if escalation_id is not None: + api_params['escalationId'] = self._normalize_value(escalation_id) + + response = self.client.call( + 'patch', + api_path, + { + 'X-Appwrite-Project': self.client.get_config('project'), + 'content-type': 'application/json', + 'accept': 'application/json', + }, + api_params, + ) + + return self._parse_response(response, model=Monitor) + + def get( + self, + monitor_id: str, + ) -> Monitor: + """ + Get a monitor by its unique ID, with its state as of its last evaluation. + + Parameters + ---------- + monitor_id : str + Monitor ID. + Returns + ------- + Monitor + API response as a typed Pydantic model + + Raises + ------ + AppwriteException + If API request fails + """ + + api_path = '/monitors/{monitorId}' + api_params = {} + if monitor_id is None or monitor_id == '': + raise AppwriteException('Missing required parameter: "monitor_id"') + api_path = api_path.replace('{monitorId}', self._encode_path(monitor_id)) + + response = self.client.call( + 'get', + api_path, + { + 'X-Appwrite-Project': self.client.get_config('project'), + 'accept': 'application/json', + }, + api_params, + ) + + return self._parse_response(response, model=Monitor) + + def delete( + self, + monitor_id: str, + ) -> Dict[str, Any]: + """ + Delete a monitor by its unique ID. It stops being evaluated; an alert it is firing is resolved and kept with the rest of its alert history. + + Parameters + ---------- + monitor_id : str + Monitor ID. + Returns + ------- + Dict[str, Any] + API response as a dictionary + + Raises + ------ + AppwriteException + If API request fails + """ + + api_path = '/monitors/{monitorId}' + api_params = {} + if monitor_id is None or monitor_id == '': + raise AppwriteException('Missing required parameter: "monitor_id"') + api_path = api_path.replace('{monitorId}', self._encode_path(monitor_id)) + + response = self.client.call( + 'delete', + api_path, + { + 'X-Appwrite-Project': self.client.get_config('project'), + 'content-type': 'application/json', + 'accept': 'application/json', + }, + api_params, + ) + + return response diff --git a/appwrite/services/organization.py b/appwrite/services/organization.py index 301589c7..6a5366eb 100644 --- a/appwrite/services/organization.py +++ b/appwrite/services/organization.py @@ -4,6 +4,8 @@ from ..exception import AppwriteException from appwrite.utils.deprecated import deprecated from ..models.organization import Organization as OrganizationModel +from ..models.escalation_list import EscalationList +from ..models.escalation import Escalation from ..models.app_installation_list import AppInstallationList from ..models.app_installation import AppInstallation from ..models.membership_list import MembershipList @@ -139,6 +141,245 @@ def delete( return response + def list_escalations( + self, + queries: Optional[List[str]] = None, + total: Optional[bool] = None, + ) -> EscalationList: + """ + Get a list of your organization's escalations. Use `Query.search('search', term)` to search escalation IDs and names. + + Parameters + ---------- + queries : Optional[List[str]] + Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: name, repeat, search + total : Optional[bool] + When set to false, the total count returned will be 0 and will not be calculated. + Returns + ------- + EscalationList + API response as a typed Pydantic model + + Raises + ------ + AppwriteException + If API request fails + """ + + api_path = '/organization/escalations' + api_params = {} + if queries is not None: + api_params['queries'] = self._normalize_value(queries) + if total is not None: + api_params['total'] = self._normalize_value(total) + + response = self.client.call( + 'get', + api_path, + { + 'X-Appwrite-Project': self.client.get_config('project'), + 'accept': 'application/json', + }, + api_params, + ) + + return self._parse_response(response, model=EscalationList) + + def create_escalation( + self, + escalation_id: str, + name: str, + steps: List[Dict[str, Any]], + repeat: Optional[float] = None, + ) -> Escalation: + """ + Create an escalation for your organization. A monitor using it notifies the escalation's steps one after another while its alert fires, each by email, push and in the console, until a member acknowledges the alert or it resolves. Each step waits its `delay` in seconds, after the alert fires for the first step and after the previous step for the others, then notifies the members holding its `roles` and those named in `userIds`. With `repeat`, the steps run again from the first, a monitor's cooldown after the last step. + + Parameters + ---------- + escalation_id : str + Escalation ID. Choose a custom ID or generate a random ID with `ID.unique()`. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. + name : str + Escalation name. Max length: 128 chars. + steps : List[Dict[str, Any]] + Steps notified in order while nobody acknowledges the alert. Each step is an object with `delay` (seconds to wait before the step, 0 to 2592000, default 0), `roles` (organization roles such as `owner` or `developer`) and `userIds` (organization members who accepted their invitation). A step names each role and member at most once and needs at least one of `roles` or `userIds`. Maximum of 100 steps. + repeat : Optional[float] + How many more times the steps run from the first while nobody acknowledges the alert, between 0 and 9. Each round starts a monitor's cooldown after the last step. + Returns + ------- + Escalation + API response as a typed Pydantic model + + Raises + ------ + AppwriteException + If API request fails + """ + + api_path = '/organization/escalations' + api_params = {} + if escalation_id is None: + raise AppwriteException('Missing required parameter: "escalation_id"') + if name is None: + raise AppwriteException('Missing required parameter: "name"') + if steps is None: + raise AppwriteException('Missing required parameter: "steps"') + api_params['escalationId'] = self._normalize_value(escalation_id) + api_params['name'] = self._normalize_value(name) + api_params['steps'] = self._normalize_value(steps) + if repeat is not None: + api_params['repeat'] = self._normalize_value(repeat) + + response = self.client.call( + 'post', + api_path, + { + 'X-Appwrite-Project': self.client.get_config('project'), + 'content-type': 'application/json', + 'accept': 'application/json', + }, + api_params, + ) + + return self._parse_response(response, model=Escalation) + + def get_escalation( + self, + escalation_id: str, + ) -> Escalation: + """ + Get one of your organization's escalations by its ID. + + Parameters + ---------- + escalation_id : str + Escalation ID. + Returns + ------- + Escalation + API response as a typed Pydantic model + + Raises + ------ + AppwriteException + If API request fails + """ + + api_path = '/organization/escalations/{escalationId}' + api_params = {} + if escalation_id is None or escalation_id == '': + raise AppwriteException('Missing required parameter: "escalation_id"') + api_path = api_path.replace('{escalationId}', self._encode_path(escalation_id)) + + response = self.client.call( + 'get', + api_path, + { + 'X-Appwrite-Project': self.client.get_config('project'), + 'accept': 'application/json', + }, + api_params, + ) + + return self._parse_response(response, model=Escalation) + + def update_escalation( + self, + escalation_id: str, + name: Optional[str] = None, + steps: Optional[List[Dict[str, Any]]] = None, + repeat: Optional[float] = None, + ) -> Escalation: + """ + Update an escalation's name, steps or repeats; what you leave out stays as it is. Alerts already escalating keep the steps they started with; the next alert uses the new ones. + + Parameters + ---------- + escalation_id : str + Escalation ID. + name : Optional[str] + Escalation name. Max length: 128 chars. + steps : Optional[List[Dict[str, Any]]] + Steps notified in order while nobody acknowledges the alert. Each step is an object with `delay` (seconds to wait before the step, 0 to 2592000, default 0), `roles` (organization roles such as `owner` or `developer`) and `userIds` (organization members who accepted their invitation). A step names each role and member at most once and needs at least one of `roles` or `userIds`. Maximum of 100 steps. + repeat : Optional[float] + How many more times the steps run from the first while nobody acknowledges the alert, between 0 and 9. Each round starts a monitor's cooldown after the last step. + Returns + ------- + Escalation + API response as a typed Pydantic model + + Raises + ------ + AppwriteException + If API request fails + """ + + api_path = '/organization/escalations/{escalationId}' + api_params = {} + if escalation_id is None or escalation_id == '': + raise AppwriteException('Missing required parameter: "escalation_id"') + api_path = api_path.replace('{escalationId}', self._encode_path(escalation_id)) + if name is not None: + api_params['name'] = self._normalize_value(name) + if steps is not None: + api_params['steps'] = self._normalize_value(steps) + if repeat is not None: + api_params['repeat'] = self._normalize_value(repeat) + + response = self.client.call( + 'patch', + api_path, + { + 'X-Appwrite-Project': self.client.get_config('project'), + 'content-type': 'application/json', + 'accept': 'application/json', + }, + api_params, + ) + + return self._parse_response(response, model=Escalation) + + def delete_escalation( + self, + escalation_id: str, + ) -> Dict[str, Any]: + """ + Delete an escalation. An escalation that a monitor uses cannot be deleted: move the monitor to another escalation or to `notify` roles first. Open alerts keep the steps they started with. + + Parameters + ---------- + escalation_id : str + Escalation ID. + Returns + ------- + Dict[str, Any] + API response as a dictionary + + Raises + ------ + AppwriteException + If API request fails + """ + + api_path = '/organization/escalations/{escalationId}' + api_params = {} + if escalation_id is None or escalation_id == '': + raise AppwriteException('Missing required parameter: "escalation_id"') + api_path = api_path.replace('{escalationId}', self._encode_path(escalation_id)) + + response = self.client.call( + 'delete', + api_path, + { + 'X-Appwrite-Project': self.client.get_config('project'), + 'content-type': 'application/json', + 'accept': 'application/json', + }, + api_params, + ) + + return response + def list_installations( self, queries: Optional[List[str]] = None, diff --git a/docs/examples/alerts/get.md b/docs/examples/alerts/get.md new file mode 100644 index 00000000..19234d32 --- /dev/null +++ b/docs/examples/alerts/get.md @@ -0,0 +1,18 @@ +```python +from appwrite.client import Client +from appwrite.services.alerts import Alerts +from appwrite.models import Alert + +client = Client() +client.set_endpoint('https://.cloud.appwrite.io/v1') # Your API Endpoint +client.set_project('') # Your project ID +client.set_key('') # Your secret API key + +alerts = Alerts(client) + +result: Alert = alerts.get( + alert_id = '' +) + +print(result.model_dump()) +``` diff --git a/docs/examples/alerts/list.md b/docs/examples/alerts/list.md new file mode 100644 index 00000000..f13c95d4 --- /dev/null +++ b/docs/examples/alerts/list.md @@ -0,0 +1,19 @@ +```python +from appwrite.client import Client +from appwrite.services.alerts import Alerts +from appwrite.models import AlertList + +client = Client() +client.set_endpoint('https://.cloud.appwrite.io/v1') # Your API Endpoint +client.set_project('') # Your project ID +client.set_key('') # Your secret API key + +alerts = Alerts(client) + +result: AlertList = alerts.list( + queries = [], # optional + total = False # optional +) + +print(result.model_dump()) +``` diff --git a/docs/examples/alerts/update.md b/docs/examples/alerts/update.md new file mode 100644 index 00000000..33202f7d --- /dev/null +++ b/docs/examples/alerts/update.md @@ -0,0 +1,19 @@ +```python +from appwrite.client import Client +from appwrite.services.alerts import Alerts +from appwrite.models import Alert + +client = Client() +client.set_endpoint('https://.cloud.appwrite.io/v1') # Your API Endpoint +client.set_project('') # Your project ID +client.set_key('') # Your secret API key + +alerts = Alerts(client) + +result: Alert = alerts.update( + alert_id = '', + acknowledged = True +) + +print(result.model_dump()) +``` diff --git a/docs/examples/monitors/create-dns-monitor.md b/docs/examples/monitors/create-dns-monitor.md new file mode 100644 index 00000000..90bca5f6 --- /dev/null +++ b/docs/examples/monitors/create-dns-monitor.md @@ -0,0 +1,38 @@ +```python +from appwrite.client import Client +from appwrite.services.monitors import Monitors +from appwrite.models import Monitor +from appwrite.enums.monitor_record import MonitorRecord +from appwrite.enums.monitor_severity import MonitorSeverity +from appwrite.query import Query + +client = Client() +client.set_endpoint('https://.cloud.appwrite.io/v1') # Your API Endpoint +client.set_project('') # Your project ID +client.set_key('') # Your secret API key + +monitors = Monitors(client) + +result: Monitor = monitors.create_dns_monitor( + monitor_id = '', + name = '', + domain = 'example.com', + record = MonitorRecord.A, # optional + resolver = '1.1.1.1', # optional + rules = [ + Query.or_queries([ + Query.equal('answers', 0), + Query.greater_than('latency', 1000) + ]) + ], # optional + interval = 60, # optional + timeout = 10, # optional + cooldown = 300, # optional + enabled = True, # optional + notify = ["owner"], # optional + severity = MonitorSeverity.INFO, # optional + escalation_id = '' # optional +) + +print(result.model_dump()) +``` diff --git a/docs/examples/monitors/create-http-monitor.md b/docs/examples/monitors/create-http-monitor.md new file mode 100644 index 00000000..6fc8c2e0 --- /dev/null +++ b/docs/examples/monitors/create-http-monitor.md @@ -0,0 +1,41 @@ +```python +from appwrite.client import Client +from appwrite.services.monitors import Monitors +from appwrite.models import Monitor +from appwrite.enums.monitor_method import MonitorMethod +from appwrite.enums.monitor_severity import MonitorSeverity +from appwrite.query import Query + +client = Client() +client.set_endpoint('https://.cloud.appwrite.io/v1') # Your API Endpoint +client.set_project('') # Your project ID +client.set_key('') # Your secret API key + +monitors = Monitors(client) + +result: Monitor = monitors.create_http_monitor( + monitor_id = '', + name = '', + url = 'https://api.example.com/health', + method = MonitorMethod.GET, # optional + headers = { + "Authorization": "Bearer " + }, # optional + body = '', # optional + rules = [ + Query.or_queries([ + Query.not_between('statusCode', 200, 299), + Query.greater_than('latency', 2000) + ]) + ], # optional + interval = 60, # optional + timeout = 10, # optional + cooldown = 300, # optional + enabled = True, # optional + notify = ["owner"], # optional + severity = MonitorSeverity.INFO, # optional + escalation_id = '' # optional +) + +print(result.model_dump()) +``` diff --git a/docs/examples/monitors/create-smtp-monitor.md b/docs/examples/monitors/create-smtp-monitor.md new file mode 100644 index 00000000..b50f88c8 --- /dev/null +++ b/docs/examples/monitors/create-smtp-monitor.md @@ -0,0 +1,38 @@ +```python +from appwrite.client import Client +from appwrite.services.monitors import Monitors +from appwrite.models import Monitor +from appwrite.enums.monitor_tls_mode import MonitorTlsMode +from appwrite.enums.monitor_severity import MonitorSeverity +from appwrite.query import Query + +client = Client() +client.set_endpoint('https://.cloud.appwrite.io/v1') # Your API Endpoint +client.set_project('') # Your project ID +client.set_key('') # Your secret API key + +monitors = Monitors(client) + +result: Monitor = monitors.create_smtp_monitor( + monitor_id = '', + name = '', + host = 'smtp.example.com', + port = 587, + tls_mode = MonitorTlsMode.NONE, # optional + rules = [ + Query.or_queries([ + Query.less_than('certificateDays', 14), + Query.greater_than('latency', 2000) + ]) + ], # optional + interval = 60, # optional + timeout = 10, # optional + cooldown = 300, # optional + enabled = True, # optional + notify = ["owner"], # optional + severity = MonitorSeverity.INFO, # optional + escalation_id = '' # optional +) + +print(result.model_dump()) +``` diff --git a/docs/examples/monitors/create-tcp-monitor.md b/docs/examples/monitors/create-tcp-monitor.md new file mode 100644 index 00000000..42cb5768 --- /dev/null +++ b/docs/examples/monitors/create-tcp-monitor.md @@ -0,0 +1,33 @@ +```python +from appwrite.client import Client +from appwrite.services.monitors import Monitors +from appwrite.models import Monitor +from appwrite.enums.monitor_severity import MonitorSeverity +from appwrite.query import Query + +client = Client() +client.set_endpoint('https://.cloud.appwrite.io/v1') # Your API Endpoint +client.set_project('') # Your project ID +client.set_key('') # Your secret API key + +monitors = Monitors(client) + +result: Monitor = monitors.create_tcp_monitor( + monitor_id = '', + name = '', + host = 'db.example.com', + port = 5432, + rules = [ + Query.greater_than('latency', 1000) + ], # optional + interval = 60, # optional + timeout = 10, # optional + cooldown = 300, # optional + enabled = True, # optional + notify = ["owner"], # optional + severity = MonitorSeverity.INFO, # optional + escalation_id = '' # optional +) + +print(result.model_dump()) +``` diff --git a/docs/examples/monitors/create-usage-monitor.md b/docs/examples/monitors/create-usage-monitor.md new file mode 100644 index 00000000..a18ad12e --- /dev/null +++ b/docs/examples/monitors/create-usage-monitor.md @@ -0,0 +1,30 @@ +```python +from appwrite.client import Client +from appwrite.services.monitors import Monitors +from appwrite.models import Monitor +from appwrite.enums.monitor_severity import MonitorSeverity +from appwrite.query import Query + +client = Client() +client.set_endpoint('https://.cloud.appwrite.io/v1') # Your API Endpoint +client.set_project('') # Your project ID +client.set_key('') # Your secret API key + +monitors = Monitors(client) + +result: Monitor = monitors.create_usage_monitor( + monitor_id = '', + name = '', + rules = [ + Query.greater_than('network.outbound', 5000000000) + ], + window = 3600, # optional + cooldown = 1800, # optional + enabled = True, # optional + notify = ["owner"], # optional + severity = MonitorSeverity.INFO, # optional + escalation_id = '' # optional +) + +print(result.model_dump()) +``` diff --git a/docs/examples/monitors/delete.md b/docs/examples/monitors/delete.md new file mode 100644 index 00000000..f98a72e2 --- /dev/null +++ b/docs/examples/monitors/delete.md @@ -0,0 +1,15 @@ +```python +from appwrite.client import Client +from appwrite.services.monitors import Monitors + +client = Client() +client.set_endpoint('https://.cloud.appwrite.io/v1') # Your API Endpoint +client.set_project('') # Your project ID +client.set_key('') # Your secret API key + +monitors = Monitors(client) + +result = monitors.delete( + monitor_id = '' +) +``` diff --git a/docs/examples/monitors/get.md b/docs/examples/monitors/get.md new file mode 100644 index 00000000..e5ab4f4e --- /dev/null +++ b/docs/examples/monitors/get.md @@ -0,0 +1,18 @@ +```python +from appwrite.client import Client +from appwrite.services.monitors import Monitors +from appwrite.models import Monitor + +client = Client() +client.set_endpoint('https://.cloud.appwrite.io/v1') # Your API Endpoint +client.set_project('') # Your project ID +client.set_key('') # Your secret API key + +monitors = Monitors(client) + +result: Monitor = monitors.get( + monitor_id = '' +) + +print(result.model_dump()) +``` diff --git a/docs/examples/monitors/list.md b/docs/examples/monitors/list.md new file mode 100644 index 00000000..94998b27 --- /dev/null +++ b/docs/examples/monitors/list.md @@ -0,0 +1,19 @@ +```python +from appwrite.client import Client +from appwrite.services.monitors import Monitors +from appwrite.models import MonitorList + +client = Client() +client.set_endpoint('https://.cloud.appwrite.io/v1') # Your API Endpoint +client.set_project('') # Your project ID +client.set_key('') # Your secret API key + +monitors = Monitors(client) + +result: MonitorList = monitors.list( + queries = [], # optional + total = False # optional +) + +print(result.model_dump()) +``` diff --git a/docs/examples/monitors/update-dns-monitor.md b/docs/examples/monitors/update-dns-monitor.md new file mode 100644 index 00000000..dd8cb05d --- /dev/null +++ b/docs/examples/monitors/update-dns-monitor.md @@ -0,0 +1,38 @@ +```python +from appwrite.client import Client +from appwrite.services.monitors import Monitors +from appwrite.models import Monitor +from appwrite.enums.monitor_record import MonitorRecord +from appwrite.enums.monitor_severity import MonitorSeverity +from appwrite.query import Query + +client = Client() +client.set_endpoint('https://.cloud.appwrite.io/v1') # Your API Endpoint +client.set_project('') # Your project ID +client.set_key('') # Your secret API key + +monitors = Monitors(client) + +result: Monitor = monitors.update_dns_monitor( + monitor_id = '', + name = '', # optional + domain = 'example.com', # optional + record = MonitorRecord.A, # optional + resolver = '1.1.1.1', # optional + rules = [ + Query.or_queries([ + Query.equal('answers', 0), + Query.greater_than('latency', 1000) + ]) + ], # optional + interval = 60, # optional + timeout = 10, # optional + cooldown = 300, # optional + enabled = True, # optional + notify = ["owner"], # optional + severity = MonitorSeverity.INFO, # optional + escalation_id = '' # optional +) + +print(result.model_dump()) +``` diff --git a/docs/examples/monitors/update-http-monitor.md b/docs/examples/monitors/update-http-monitor.md new file mode 100644 index 00000000..1b5e7aa2 --- /dev/null +++ b/docs/examples/monitors/update-http-monitor.md @@ -0,0 +1,41 @@ +```python +from appwrite.client import Client +from appwrite.services.monitors import Monitors +from appwrite.models import Monitor +from appwrite.enums.monitor_method import MonitorMethod +from appwrite.enums.monitor_severity import MonitorSeverity +from appwrite.query import Query + +client = Client() +client.set_endpoint('https://.cloud.appwrite.io/v1') # Your API Endpoint +client.set_project('') # Your project ID +client.set_key('') # Your secret API key + +monitors = Monitors(client) + +result: Monitor = monitors.update_http_monitor( + monitor_id = '', + name = '', # optional + url = 'https://api.example.com/health', # optional + method = MonitorMethod.GET, # optional + headers = { + "Authorization": "Bearer " + }, # optional + body = '', # optional + rules = [ + Query.or_queries([ + Query.not_between('statusCode', 200, 299), + Query.greater_than('latency', 2000) + ]) + ], # optional + interval = 60, # optional + timeout = 10, # optional + cooldown = 300, # optional + enabled = True, # optional + notify = ["owner"], # optional + severity = MonitorSeverity.INFO, # optional + escalation_id = '' # optional +) + +print(result.model_dump()) +``` diff --git a/docs/examples/monitors/update-smtp-monitor.md b/docs/examples/monitors/update-smtp-monitor.md new file mode 100644 index 00000000..d8183070 --- /dev/null +++ b/docs/examples/monitors/update-smtp-monitor.md @@ -0,0 +1,38 @@ +```python +from appwrite.client import Client +from appwrite.services.monitors import Monitors +from appwrite.models import Monitor +from appwrite.enums.monitor_tls_mode import MonitorTlsMode +from appwrite.enums.monitor_severity import MonitorSeverity +from appwrite.query import Query + +client = Client() +client.set_endpoint('https://.cloud.appwrite.io/v1') # Your API Endpoint +client.set_project('') # Your project ID +client.set_key('') # Your secret API key + +monitors = Monitors(client) + +result: Monitor = monitors.update_smtp_monitor( + monitor_id = '', + name = '', # optional + host = 'smtp.example.com', # optional + port = 587, # optional + tls_mode = MonitorTlsMode.NONE, # optional + rules = [ + Query.or_queries([ + Query.less_than('certificateDays', 14), + Query.greater_than('latency', 2000) + ]) + ], # optional + interval = 60, # optional + timeout = 10, # optional + cooldown = 300, # optional + enabled = True, # optional + notify = ["owner"], # optional + severity = MonitorSeverity.INFO, # optional + escalation_id = '' # optional +) + +print(result.model_dump()) +``` diff --git a/docs/examples/monitors/update-tcp-monitor.md b/docs/examples/monitors/update-tcp-monitor.md new file mode 100644 index 00000000..746f583a --- /dev/null +++ b/docs/examples/monitors/update-tcp-monitor.md @@ -0,0 +1,33 @@ +```python +from appwrite.client import Client +from appwrite.services.monitors import Monitors +from appwrite.models import Monitor +from appwrite.enums.monitor_severity import MonitorSeverity +from appwrite.query import Query + +client = Client() +client.set_endpoint('https://.cloud.appwrite.io/v1') # Your API Endpoint +client.set_project('') # Your project ID +client.set_key('') # Your secret API key + +monitors = Monitors(client) + +result: Monitor = monitors.update_tcp_monitor( + monitor_id = '', + name = '', # optional + host = 'db.example.com', # optional + port = 5432, # optional + rules = [ + Query.greater_than('latency', 1000) + ], # optional + interval = 60, # optional + timeout = 10, # optional + cooldown = 300, # optional + enabled = True, # optional + notify = ["owner"], # optional + severity = MonitorSeverity.INFO, # optional + escalation_id = '' # optional +) + +print(result.model_dump()) +``` diff --git a/docs/examples/monitors/update-usage-monitor.md b/docs/examples/monitors/update-usage-monitor.md new file mode 100644 index 00000000..1f5eb943 --- /dev/null +++ b/docs/examples/monitors/update-usage-monitor.md @@ -0,0 +1,30 @@ +```python +from appwrite.client import Client +from appwrite.services.monitors import Monitors +from appwrite.models import Monitor +from appwrite.enums.monitor_severity import MonitorSeverity +from appwrite.query import Query + +client = Client() +client.set_endpoint('https://.cloud.appwrite.io/v1') # Your API Endpoint +client.set_project('') # Your project ID +client.set_key('') # Your secret API key + +monitors = Monitors(client) + +result: Monitor = monitors.update_usage_monitor( + monitor_id = '', + name = '', # optional + rules = [ + Query.greater_than('network.outbound', 5000000000) + ], # optional + window = 3600, # optional + cooldown = 1800, # optional + enabled = True, # optional + notify = ["owner"], # optional + severity = MonitorSeverity.INFO, # optional + escalation_id = '' # optional +) + +print(result.model_dump()) +``` diff --git a/docs/examples/organization/create-escalation.md b/docs/examples/organization/create-escalation.md new file mode 100644 index 00000000..e326cd2e --- /dev/null +++ b/docs/examples/organization/create-escalation.md @@ -0,0 +1,37 @@ +```python +from appwrite.client import Client +from appwrite.services.organization import Organization +from appwrite.models import Escalation + +client = Client() +client.set_endpoint('https://.cloud.appwrite.io/v1') # Your API Endpoint +client.set_project('') # Your project ID +client.set_key('') # Your secret API key + +organization = Organization(client) + +result: Escalation = organization.create_escalation( + escalation_id = '', + name = '', + steps = [ + { + "delay": 0, + "roles": [ + "owner" + ] + }, + { + "delay": 900, + "roles": [ + "developer" + ], + "userIds": [ + "" + ] + } + ], + repeat = 1 # optional +) + +print(result.model_dump()) +``` diff --git a/docs/examples/organization/delete-escalation.md b/docs/examples/organization/delete-escalation.md new file mode 100644 index 00000000..0bd65078 --- /dev/null +++ b/docs/examples/organization/delete-escalation.md @@ -0,0 +1,15 @@ +```python +from appwrite.client import Client +from appwrite.services.organization import Organization + +client = Client() +client.set_endpoint('https://.cloud.appwrite.io/v1') # Your API Endpoint +client.set_project('') # Your project ID +client.set_key('') # Your secret API key + +organization = Organization(client) + +result = organization.delete_escalation( + escalation_id = '' +) +``` diff --git a/docs/examples/organization/get-escalation.md b/docs/examples/organization/get-escalation.md new file mode 100644 index 00000000..2072f16b --- /dev/null +++ b/docs/examples/organization/get-escalation.md @@ -0,0 +1,18 @@ +```python +from appwrite.client import Client +from appwrite.services.organization import Organization +from appwrite.models import Escalation + +client = Client() +client.set_endpoint('https://.cloud.appwrite.io/v1') # Your API Endpoint +client.set_project('') # Your project ID +client.set_key('') # Your secret API key + +organization = Organization(client) + +result: Escalation = organization.get_escalation( + escalation_id = '' +) + +print(result.model_dump()) +``` diff --git a/docs/examples/organization/list-escalations.md b/docs/examples/organization/list-escalations.md new file mode 100644 index 00000000..c5aacff2 --- /dev/null +++ b/docs/examples/organization/list-escalations.md @@ -0,0 +1,19 @@ +```python +from appwrite.client import Client +from appwrite.services.organization import Organization +from appwrite.models import EscalationList + +client = Client() +client.set_endpoint('https://.cloud.appwrite.io/v1') # Your API Endpoint +client.set_project('') # Your project ID +client.set_key('') # Your secret API key + +organization = Organization(client) + +result: EscalationList = organization.list_escalations( + queries = [], # optional + total = False # optional +) + +print(result.model_dump()) +``` diff --git a/docs/examples/organization/update-escalation.md b/docs/examples/organization/update-escalation.md new file mode 100644 index 00000000..3057d52a --- /dev/null +++ b/docs/examples/organization/update-escalation.md @@ -0,0 +1,37 @@ +```python +from appwrite.client import Client +from appwrite.services.organization import Organization +from appwrite.models import Escalation + +client = Client() +client.set_endpoint('https://.cloud.appwrite.io/v1') # Your API Endpoint +client.set_project('') # Your project ID +client.set_key('') # Your secret API key + +organization = Organization(client) + +result: Escalation = organization.update_escalation( + escalation_id = '', + name = '', # optional + steps = [ + { + "delay": 0, + "roles": [ + "owner" + ] + }, + { + "delay": 900, + "roles": [ + "developer" + ], + "userIds": [ + "" + ] + } + ], # optional + repeat = 1 # optional +) + +print(result.model_dump()) +``` diff --git a/pyproject.toml b/pyproject.toml index cd83769e..4713d396 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "appwrite" -version = "28.1.0" +version = "28.2.0" description = "Appwrite is an open-source self-hosted backend server that abstracts and simplifies complex and repetitive development tasks behind a very simple REST API" readme = "README.md" requires-python = ">=3.10" diff --git a/setup.py b/setup.py index 79f098c9..48c46c7f 100644 --- a/setup.py +++ b/setup.py @@ -8,7 +8,7 @@ setuptools.setup( name='appwrite', packages=setuptools.find_packages(), - version='28.1.0', + version='28.2.0', license='BSD-3-Clause', description='Appwrite is an open-source self-hosted backend server that abstracts and simplifies complex and repetitive development tasks behind a very simple REST API', long_description=long_description, @@ -18,7 +18,7 @@ maintainer='Appwrite Team', maintainer_email='team@appwrite.io', url='https://appwrite.io/support', - download_url='https://github.com/appwrite/sdk-for-python/archive/28.1.0.tar.gz', + download_url='https://github.com/appwrite/sdk-for-python/archive/28.2.0.tar.gz', install_requires=[ 'requests>=2.34.2,<3', 'urllib3>=2.8.0,<3', diff --git a/test/services/test_alerts.py b/test/services/test_alerts.py new file mode 100644 index 00000000..cacd6d2a --- /dev/null +++ b/test/services/test_alerts.py @@ -0,0 +1,145 @@ +import json +import re +import requests_mock +import unittest +from urllib.parse import parse_qs, unquote, urlsplit + +from appwrite.client import Client +from appwrite.input_file import InputFile +from appwrite.models import * +from appwrite.services.alerts import Alerts + + +class AlertsServiceTest(unittest.TestCase): + + def setUp(self): + self.client = Client() + self.alerts = Alerts(self.client) + + @requests_mock.Mocker() + def test_list(self, m): + data = { + "total": 5.0, + "alerts": [], + } + headers = {'Content-Type': 'application/json'} + m.request( + 'GET', + requests_mock.ANY, + text=json.dumps(data), + headers=headers, + ) + response = self.alerts.list( + queries=[], + total=False, + ) + request = m.last_request + url = urlsplit(request.url) + self.assertEqual( + unquote(url.path), + '/v1/alerts', + ) + sent = parse_qs(url.query, keep_blank_values=True) + self.assertEqual( + sent, + { + 'total': ['false'], + }, + ) + self.assertEqual(response.to_dict(), data) + + @requests_mock.Mocker() + def test_get(self, m): + data = { + "$id": "5e5ea5c16897e", + "$createdAt": "2020-10-15T06:38:00.000+00:00", + "$updatedAt": "2020-10-15T06:38:00.000+00:00", + "monitorId": "5e5ea5c16897e", + "projectId": "5e5ea5c16897e", + "name": "Bandwidth spike", + "status": "firing", + "acknowledgedBy": "5e5ea5c16897e", + "acknowledgedByName": "Jane Doe", + "escalationId": "5e5ea5c16897e", + "escalationStep": 1.0, + "escalationRound": 0.0, + "rules": [], + "severity": "warning", + "threshold": 5000000, + "value": 7250000, + "peak": 9100000, + "type": "usage", + "resourceType": "database", + "resourceId": "5e5ea5c16897e", + "notifications": 1.0, + } + headers = {'Content-Type': 'application/json'} + m.request( + 'GET', + requests_mock.ANY, + text=json.dumps(data), + headers=headers, + ) + response = self.alerts.get( + '', + ) + request = m.last_request + url = urlsplit(request.url) + self.assertEqual( + unquote(url.path), + '/v1/alerts/', + ) + sent = parse_qs(url.query, keep_blank_values=True) + self.assertEqual(sent, {}) + self.assertEqual(response.to_dict(), data) + + @requests_mock.Mocker() + def test_update(self, m): + data = { + "$id": "5e5ea5c16897e", + "$createdAt": "2020-10-15T06:38:00.000+00:00", + "$updatedAt": "2020-10-15T06:38:00.000+00:00", + "monitorId": "5e5ea5c16897e", + "projectId": "5e5ea5c16897e", + "name": "Bandwidth spike", + "status": "firing", + "acknowledgedBy": "5e5ea5c16897e", + "acknowledgedByName": "Jane Doe", + "escalationId": "5e5ea5c16897e", + "escalationStep": 1.0, + "escalationRound": 0.0, + "rules": [], + "severity": "warning", + "threshold": 5000000, + "value": 7250000, + "peak": 9100000, + "type": "usage", + "resourceType": "database", + "resourceId": "5e5ea5c16897e", + "notifications": 1.0, + } + headers = {'Content-Type': 'application/json'} + m.request( + 'PATCH', + requests_mock.ANY, + text=json.dumps(data), + headers=headers, + ) + response = self.alerts.update( + '', + False, + ) + request = m.last_request + url = urlsplit(request.url) + self.assertEqual( + unquote(url.path), + '/v1/alerts/', + ) + sent = json.loads(request.body or '{}') + self.assertEqual( + sent, + { + 'acknowledged': False, + }, + ) + self.assertEqual(response.to_dict(), data) diff --git a/test/services/test_monitors.py b/test/services/test_monitors.py new file mode 100644 index 00000000..236ca393 --- /dev/null +++ b/test/services/test_monitors.py @@ -0,0 +1,880 @@ +import json +import re +import requests_mock +import unittest +from urllib.parse import parse_qs, unquote, urlsplit + +from appwrite.client import Client +from appwrite.input_file import InputFile +from appwrite.models import * +from appwrite.services.monitors import Monitors + + +class MonitorsServiceTest(unittest.TestCase): + + def setUp(self): + self.client = Client() + self.monitors = Monitors(self.client) + + @requests_mock.Mocker() + def test_list(self, m): + data = { + "total": 5.0, + "monitors": [], + } + headers = {'Content-Type': 'application/json'} + m.request( + 'GET', + requests_mock.ANY, + text=json.dumps(data), + headers=headers, + ) + response = self.monitors.list( + queries=[], + total=False, + ) + request = m.last_request + url = urlsplit(request.url) + self.assertEqual( + unquote(url.path), + '/v1/monitors', + ) + sent = parse_qs(url.query, keep_blank_values=True) + self.assertEqual( + sent, + { + 'total': ['false'], + }, + ) + self.assertEqual(response.to_dict(), data) + + @requests_mock.Mocker() + def test_create_dns_monitor(self, m): + data = { + "$id": "5e5ea5c16897e", + "$createdAt": "2020-10-15T06:38:00.000+00:00", + "$updatedAt": "2020-10-15T06:38:00.000+00:00", + "name": "Bandwidth spike", + "projectId": "5e5ea5c16897e", + "rules": [], + "type": "usage", + "resourceType": "database", + "resourceId": "main", + "window": 3600.0, + "cooldown": 3600.0, + "enabled": True, + "notify": [], + "escalationId": "5e5ea5c16897e", + "severity": "warning", + "status": "ok", + "alertId": "5e5ea5c16897e", + "interval": 60.0, + "timeout": 10.0, + "url": "https://example.com/health", + "body": "", + "domain": "example.com", + "resolver": "1.1.1.1", + "host": "mail.example.com", + "port": 587.0, + } + headers = {'Content-Type': 'application/json'} + m.request( + 'POST', + requests_mock.ANY, + text=json.dumps(data), + headers=headers, + ) + response = self.monitors.create_dns_monitor( + '', + '', + 'example.com', + record='A', + resolver='1.1.1.1', + rules=[], + interval=1, + timeout=1, + cooldown=1, + enabled=False, + notify=[], + severity='info', + escalation_id='', + ) + request = m.last_request + url = urlsplit(request.url) + self.assertEqual( + unquote(url.path), + '/v1/monitors/dns', + ) + sent = json.loads(request.body or '{}') + self.assertEqual( + sent, + { + 'monitorId': '', + 'name': '', + 'domain': 'example.com', + 'record': 'A', + 'resolver': '1.1.1.1', + 'rules': [], + 'interval': 1, + 'timeout': 1, + 'cooldown': 1, + 'enabled': False, + 'notify': [], + 'severity': 'info', + 'escalationId': '', + }, + ) + self.assertEqual(response.to_dict(), data) + + @requests_mock.Mocker() + def test_update_dns_monitor(self, m): + data = { + "$id": "5e5ea5c16897e", + "$createdAt": "2020-10-15T06:38:00.000+00:00", + "$updatedAt": "2020-10-15T06:38:00.000+00:00", + "name": "Bandwidth spike", + "projectId": "5e5ea5c16897e", + "rules": [], + "type": "usage", + "resourceType": "database", + "resourceId": "main", + "window": 3600.0, + "cooldown": 3600.0, + "enabled": True, + "notify": [], + "escalationId": "5e5ea5c16897e", + "severity": "warning", + "status": "ok", + "alertId": "5e5ea5c16897e", + "interval": 60.0, + "timeout": 10.0, + "url": "https://example.com/health", + "body": "", + "domain": "example.com", + "resolver": "1.1.1.1", + "host": "mail.example.com", + "port": 587.0, + } + headers = {'Content-Type': 'application/json'} + m.request( + 'PATCH', + requests_mock.ANY, + text=json.dumps(data), + headers=headers, + ) + response = self.monitors.update_dns_monitor( + '', + name='', + domain='example.com', + record='A', + resolver='1.1.1.1', + rules=[], + interval=1, + timeout=1, + cooldown=1, + enabled=False, + notify=[], + severity='info', + escalation_id='', + ) + request = m.last_request + url = urlsplit(request.url) + self.assertEqual( + unquote(url.path), + '/v1/monitors/dns/', + ) + sent = json.loads(request.body or '{}') + self.assertEqual( + sent, + { + 'name': '', + 'domain': 'example.com', + 'record': 'A', + 'resolver': '1.1.1.1', + 'rules': [], + 'interval': 1, + 'timeout': 1, + 'cooldown': 1, + 'enabled': False, + 'notify': [], + 'severity': 'info', + 'escalationId': '', + }, + ) + self.assertEqual(response.to_dict(), data) + + @requests_mock.Mocker() + def test_create_http_monitor(self, m): + data = { + "$id": "5e5ea5c16897e", + "$createdAt": "2020-10-15T06:38:00.000+00:00", + "$updatedAt": "2020-10-15T06:38:00.000+00:00", + "name": "Bandwidth spike", + "projectId": "5e5ea5c16897e", + "rules": [], + "type": "usage", + "resourceType": "database", + "resourceId": "main", + "window": 3600.0, + "cooldown": 3600.0, + "enabled": True, + "notify": [], + "escalationId": "5e5ea5c16897e", + "severity": "warning", + "status": "ok", + "alertId": "5e5ea5c16897e", + "interval": 60.0, + "timeout": 10.0, + "url": "https://example.com/health", + "body": "", + "domain": "example.com", + "resolver": "1.1.1.1", + "host": "mail.example.com", + "port": 587.0, + } + headers = {'Content-Type': 'application/json'} + m.request( + 'POST', + requests_mock.ANY, + text=json.dumps(data), + headers=headers, + ) + response = self.monitors.create_http_monitor( + '', + '', + 'https://api.example.com/health', + method='GET', + headers={}, + body='', + rules=[], + interval=1, + timeout=1, + cooldown=1, + enabled=False, + notify=[], + severity='info', + escalation_id='', + ) + request = m.last_request + url = urlsplit(request.url) + self.assertEqual( + unquote(url.path), + '/v1/monitors/http', + ) + sent = json.loads(request.body or '{}') + self.assertEqual( + sent, + { + 'monitorId': '', + 'name': '', + 'url': 'https://api.example.com/health', + 'method': 'GET', + 'headers': {}, + 'body': '', + 'rules': [], + 'interval': 1, + 'timeout': 1, + 'cooldown': 1, + 'enabled': False, + 'notify': [], + 'severity': 'info', + 'escalationId': '', + }, + ) + self.assertEqual(response.to_dict(), data) + + @requests_mock.Mocker() + def test_update_http_monitor(self, m): + data = { + "$id": "5e5ea5c16897e", + "$createdAt": "2020-10-15T06:38:00.000+00:00", + "$updatedAt": "2020-10-15T06:38:00.000+00:00", + "name": "Bandwidth spike", + "projectId": "5e5ea5c16897e", + "rules": [], + "type": "usage", + "resourceType": "database", + "resourceId": "main", + "window": 3600.0, + "cooldown": 3600.0, + "enabled": True, + "notify": [], + "escalationId": "5e5ea5c16897e", + "severity": "warning", + "status": "ok", + "alertId": "5e5ea5c16897e", + "interval": 60.0, + "timeout": 10.0, + "url": "https://example.com/health", + "body": "", + "domain": "example.com", + "resolver": "1.1.1.1", + "host": "mail.example.com", + "port": 587.0, + } + headers = {'Content-Type': 'application/json'} + m.request( + 'PATCH', + requests_mock.ANY, + text=json.dumps(data), + headers=headers, + ) + response = self.monitors.update_http_monitor( + '', + name='', + url='https://api.example.com/health', + method='GET', + headers={}, + body='', + rules=[], + interval=1, + timeout=1, + cooldown=1, + enabled=False, + notify=[], + severity='info', + escalation_id='', + ) + request = m.last_request + url = urlsplit(request.url) + self.assertEqual( + unquote(url.path), + '/v1/monitors/http/', + ) + sent = json.loads(request.body or '{}') + self.assertEqual( + sent, + { + 'name': '', + 'url': 'https://api.example.com/health', + 'method': 'GET', + 'headers': {}, + 'body': '', + 'rules': [], + 'interval': 1, + 'timeout': 1, + 'cooldown': 1, + 'enabled': False, + 'notify': [], + 'severity': 'info', + 'escalationId': '', + }, + ) + self.assertEqual(response.to_dict(), data) + + @requests_mock.Mocker() + def test_create_smtp_monitor(self, m): + data = { + "$id": "5e5ea5c16897e", + "$createdAt": "2020-10-15T06:38:00.000+00:00", + "$updatedAt": "2020-10-15T06:38:00.000+00:00", + "name": "Bandwidth spike", + "projectId": "5e5ea5c16897e", + "rules": [], + "type": "usage", + "resourceType": "database", + "resourceId": "main", + "window": 3600.0, + "cooldown": 3600.0, + "enabled": True, + "notify": [], + "escalationId": "5e5ea5c16897e", + "severity": "warning", + "status": "ok", + "alertId": "5e5ea5c16897e", + "interval": 60.0, + "timeout": 10.0, + "url": "https://example.com/health", + "body": "", + "domain": "example.com", + "resolver": "1.1.1.1", + "host": "mail.example.com", + "port": 587.0, + } + headers = {'Content-Type': 'application/json'} + m.request( + 'POST', + requests_mock.ANY, + text=json.dumps(data), + headers=headers, + ) + response = self.monitors.create_smtp_monitor( + '', + '', + 'smtp.example.com', + 1, + tls_mode='none', + rules=[], + interval=1, + timeout=1, + cooldown=1, + enabled=False, + notify=[], + severity='info', + escalation_id='', + ) + request = m.last_request + url = urlsplit(request.url) + self.assertEqual( + unquote(url.path), + '/v1/monitors/smtp', + ) + sent = json.loads(request.body or '{}') + self.assertEqual( + sent, + { + 'monitorId': '', + 'name': '', + 'host': 'smtp.example.com', + 'port': 1, + 'tlsMode': 'none', + 'rules': [], + 'interval': 1, + 'timeout': 1, + 'cooldown': 1, + 'enabled': False, + 'notify': [], + 'severity': 'info', + 'escalationId': '', + }, + ) + self.assertEqual(response.to_dict(), data) + + @requests_mock.Mocker() + def test_update_smtp_monitor(self, m): + data = { + "$id": "5e5ea5c16897e", + "$createdAt": "2020-10-15T06:38:00.000+00:00", + "$updatedAt": "2020-10-15T06:38:00.000+00:00", + "name": "Bandwidth spike", + "projectId": "5e5ea5c16897e", + "rules": [], + "type": "usage", + "resourceType": "database", + "resourceId": "main", + "window": 3600.0, + "cooldown": 3600.0, + "enabled": True, + "notify": [], + "escalationId": "5e5ea5c16897e", + "severity": "warning", + "status": "ok", + "alertId": "5e5ea5c16897e", + "interval": 60.0, + "timeout": 10.0, + "url": "https://example.com/health", + "body": "", + "domain": "example.com", + "resolver": "1.1.1.1", + "host": "mail.example.com", + "port": 587.0, + } + headers = {'Content-Type': 'application/json'} + m.request( + 'PATCH', + requests_mock.ANY, + text=json.dumps(data), + headers=headers, + ) + response = self.monitors.update_smtp_monitor( + '', + name='', + host='smtp.example.com', + port=1, + tls_mode='none', + rules=[], + interval=1, + timeout=1, + cooldown=1, + enabled=False, + notify=[], + severity='info', + escalation_id='', + ) + request = m.last_request + url = urlsplit(request.url) + self.assertEqual( + unquote(url.path), + '/v1/monitors/smtp/', + ) + sent = json.loads(request.body or '{}') + self.assertEqual( + sent, + { + 'name': '', + 'host': 'smtp.example.com', + 'port': 1, + 'tlsMode': 'none', + 'rules': [], + 'interval': 1, + 'timeout': 1, + 'cooldown': 1, + 'enabled': False, + 'notify': [], + 'severity': 'info', + 'escalationId': '', + }, + ) + self.assertEqual(response.to_dict(), data) + + @requests_mock.Mocker() + def test_create_tcp_monitor(self, m): + data = { + "$id": "5e5ea5c16897e", + "$createdAt": "2020-10-15T06:38:00.000+00:00", + "$updatedAt": "2020-10-15T06:38:00.000+00:00", + "name": "Bandwidth spike", + "projectId": "5e5ea5c16897e", + "rules": [], + "type": "usage", + "resourceType": "database", + "resourceId": "main", + "window": 3600.0, + "cooldown": 3600.0, + "enabled": True, + "notify": [], + "escalationId": "5e5ea5c16897e", + "severity": "warning", + "status": "ok", + "alertId": "5e5ea5c16897e", + "interval": 60.0, + "timeout": 10.0, + "url": "https://example.com/health", + "body": "", + "domain": "example.com", + "resolver": "1.1.1.1", + "host": "mail.example.com", + "port": 587.0, + } + headers = {'Content-Type': 'application/json'} + m.request( + 'POST', + requests_mock.ANY, + text=json.dumps(data), + headers=headers, + ) + response = self.monitors.create_tcp_monitor( + '', + '', + 'db.example.com', + 1, + rules=[], + interval=1, + timeout=1, + cooldown=1, + enabled=False, + notify=[], + severity='info', + escalation_id='', + ) + request = m.last_request + url = urlsplit(request.url) + self.assertEqual( + unquote(url.path), + '/v1/monitors/tcp', + ) + sent = json.loads(request.body or '{}') + self.assertEqual( + sent, + { + 'monitorId': '', + 'name': '', + 'host': 'db.example.com', + 'port': 1, + 'rules': [], + 'interval': 1, + 'timeout': 1, + 'cooldown': 1, + 'enabled': False, + 'notify': [], + 'severity': 'info', + 'escalationId': '', + }, + ) + self.assertEqual(response.to_dict(), data) + + @requests_mock.Mocker() + def test_update_tcp_monitor(self, m): + data = { + "$id": "5e5ea5c16897e", + "$createdAt": "2020-10-15T06:38:00.000+00:00", + "$updatedAt": "2020-10-15T06:38:00.000+00:00", + "name": "Bandwidth spike", + "projectId": "5e5ea5c16897e", + "rules": [], + "type": "usage", + "resourceType": "database", + "resourceId": "main", + "window": 3600.0, + "cooldown": 3600.0, + "enabled": True, + "notify": [], + "escalationId": "5e5ea5c16897e", + "severity": "warning", + "status": "ok", + "alertId": "5e5ea5c16897e", + "interval": 60.0, + "timeout": 10.0, + "url": "https://example.com/health", + "body": "", + "domain": "example.com", + "resolver": "1.1.1.1", + "host": "mail.example.com", + "port": 587.0, + } + headers = {'Content-Type': 'application/json'} + m.request( + 'PATCH', + requests_mock.ANY, + text=json.dumps(data), + headers=headers, + ) + response = self.monitors.update_tcp_monitor( + '', + name='', + host='db.example.com', + port=1, + rules=[], + interval=1, + timeout=1, + cooldown=1, + enabled=False, + notify=[], + severity='info', + escalation_id='', + ) + request = m.last_request + url = urlsplit(request.url) + self.assertEqual( + unquote(url.path), + '/v1/monitors/tcp/', + ) + sent = json.loads(request.body or '{}') + self.assertEqual( + sent, + { + 'name': '', + 'host': 'db.example.com', + 'port': 1, + 'rules': [], + 'interval': 1, + 'timeout': 1, + 'cooldown': 1, + 'enabled': False, + 'notify': [], + 'severity': 'info', + 'escalationId': '', + }, + ) + self.assertEqual(response.to_dict(), data) + + @requests_mock.Mocker() + def test_create_usage_monitor(self, m): + data = { + "$id": "5e5ea5c16897e", + "$createdAt": "2020-10-15T06:38:00.000+00:00", + "$updatedAt": "2020-10-15T06:38:00.000+00:00", + "name": "Bandwidth spike", + "projectId": "5e5ea5c16897e", + "rules": [], + "type": "usage", + "resourceType": "database", + "resourceId": "main", + "window": 3600.0, + "cooldown": 3600.0, + "enabled": True, + "notify": [], + "escalationId": "5e5ea5c16897e", + "severity": "warning", + "status": "ok", + "alertId": "5e5ea5c16897e", + "interval": 60.0, + "timeout": 10.0, + "url": "https://example.com/health", + "body": "", + "domain": "example.com", + "resolver": "1.1.1.1", + "host": "mail.example.com", + "port": 587.0, + } + headers = {'Content-Type': 'application/json'} + m.request( + 'POST', + requests_mock.ANY, + text=json.dumps(data), + headers=headers, + ) + response = self.monitors.create_usage_monitor( + '', + '', + [], + window=1, + cooldown=1, + enabled=False, + notify=[], + severity='info', + escalation_id='', + ) + request = m.last_request + url = urlsplit(request.url) + self.assertEqual( + unquote(url.path), + '/v1/monitors/usage', + ) + sent = json.loads(request.body or '{}') + self.assertEqual( + sent, + { + 'monitorId': '', + 'name': '', + 'rules': [], + 'window': 1, + 'cooldown': 1, + 'enabled': False, + 'notify': [], + 'severity': 'info', + 'escalationId': '', + }, + ) + self.assertEqual(response.to_dict(), data) + + @requests_mock.Mocker() + def test_update_usage_monitor(self, m): + data = { + "$id": "5e5ea5c16897e", + "$createdAt": "2020-10-15T06:38:00.000+00:00", + "$updatedAt": "2020-10-15T06:38:00.000+00:00", + "name": "Bandwidth spike", + "projectId": "5e5ea5c16897e", + "rules": [], + "type": "usage", + "resourceType": "database", + "resourceId": "main", + "window": 3600.0, + "cooldown": 3600.0, + "enabled": True, + "notify": [], + "escalationId": "5e5ea5c16897e", + "severity": "warning", + "status": "ok", + "alertId": "5e5ea5c16897e", + "interval": 60.0, + "timeout": 10.0, + "url": "https://example.com/health", + "body": "", + "domain": "example.com", + "resolver": "1.1.1.1", + "host": "mail.example.com", + "port": 587.0, + } + headers = {'Content-Type': 'application/json'} + m.request( + 'PATCH', + requests_mock.ANY, + text=json.dumps(data), + headers=headers, + ) + response = self.monitors.update_usage_monitor( + '', + name='', + rules=[], + window=1, + cooldown=1, + enabled=False, + notify=[], + severity='info', + escalation_id='', + ) + request = m.last_request + url = urlsplit(request.url) + self.assertEqual( + unquote(url.path), + '/v1/monitors/usage/', + ) + sent = json.loads(request.body or '{}') + self.assertEqual( + sent, + { + 'name': '', + 'rules': [], + 'window': 1, + 'cooldown': 1, + 'enabled': False, + 'notify': [], + 'severity': 'info', + 'escalationId': '', + }, + ) + self.assertEqual(response.to_dict(), data) + + @requests_mock.Mocker() + def test_get(self, m): + data = { + "$id": "5e5ea5c16897e", + "$createdAt": "2020-10-15T06:38:00.000+00:00", + "$updatedAt": "2020-10-15T06:38:00.000+00:00", + "name": "Bandwidth spike", + "projectId": "5e5ea5c16897e", + "rules": [], + "type": "usage", + "resourceType": "database", + "resourceId": "main", + "window": 3600.0, + "cooldown": 3600.0, + "enabled": True, + "notify": [], + "escalationId": "5e5ea5c16897e", + "severity": "warning", + "status": "ok", + "alertId": "5e5ea5c16897e", + "interval": 60.0, + "timeout": 10.0, + "url": "https://example.com/health", + "body": "", + "domain": "example.com", + "resolver": "1.1.1.1", + "host": "mail.example.com", + "port": 587.0, + } + headers = {'Content-Type': 'application/json'} + m.request( + 'GET', + requests_mock.ANY, + text=json.dumps(data), + headers=headers, + ) + response = self.monitors.get( + '', + ) + request = m.last_request + url = urlsplit(request.url) + self.assertEqual( + unquote(url.path), + '/v1/monitors/', + ) + sent = parse_qs(url.query, keep_blank_values=True) + self.assertEqual(sent, {}) + self.assertEqual(response.to_dict(), data) + + @requests_mock.Mocker() + def test_delete(self, m): + data = '' + headers = {'Content-Type': 'application/json'} + m.request( + 'DELETE', + requests_mock.ANY, + text=json.dumps(data), + headers=headers, + ) + response = self.monitors.delete( + '', + ) + request = m.last_request + url = urlsplit(request.url) + self.assertEqual( + unquote(url.path), + '/v1/monitors/', + ) + sent = json.loads(request.body or '{}') + self.assertEqual(sent, {}) + self.assertEqual(response, data) diff --git a/test/services/test_organization.py b/test/services/test_organization.py index 05b1739e..35f5fcfb 100644 --- a/test/services/test_organization.py +++ b/test/services/test_organization.py @@ -262,6 +262,172 @@ def test_delete(self, m): self.assertEqual(sent, {}) self.assertEqual(response, data) + @requests_mock.Mocker() + def test_list_escalations(self, m): + data = { + "total": 5.0, + "escalations": [], + } + headers = {'Content-Type': 'application/json'} + m.request( + 'GET', + requests_mock.ANY, + text=json.dumps(data), + headers=headers, + ) + response = self.organization.list_escalations( + queries=[], + total=False, + ) + request = m.last_request + url = urlsplit(request.url) + self.assertEqual( + unquote(url.path), + '/v1/organization/escalations', + ) + sent = parse_qs(url.query, keep_blank_values=True) + self.assertEqual( + sent, + { + 'total': ['false'], + }, + ) + self.assertEqual(response.to_dict(), data) + + @requests_mock.Mocker() + def test_create_escalation(self, m): + data = { + "$id": "5e5ea5c16897e", + "$createdAt": "2020-10-15T06:38:00.000+00:00", + "$updatedAt": "2020-10-15T06:38:00.000+00:00", + "name": "Platform", + "steps": [], + "repeat": 2.0, + } + headers = {'Content-Type': 'application/json'} + m.request( + 'POST', + requests_mock.ANY, + text=json.dumps(data), + headers=headers, + ) + response = self.organization.create_escalation( + '', + '', + [], + repeat=1, + ) + request = m.last_request + url = urlsplit(request.url) + self.assertEqual( + unquote(url.path), + '/v1/organization/escalations', + ) + sent = json.loads(request.body or '{}') + self.assertEqual( + sent, + { + 'escalationId': '', + 'name': '', + 'steps': [], + 'repeat': 1, + }, + ) + self.assertEqual(response.to_dict(), data) + + @requests_mock.Mocker() + def test_get_escalation(self, m): + data = { + "$id": "5e5ea5c16897e", + "$createdAt": "2020-10-15T06:38:00.000+00:00", + "$updatedAt": "2020-10-15T06:38:00.000+00:00", + "name": "Platform", + "steps": [], + "repeat": 2.0, + } + headers = {'Content-Type': 'application/json'} + m.request( + 'GET', + requests_mock.ANY, + text=json.dumps(data), + headers=headers, + ) + response = self.organization.get_escalation( + '', + ) + request = m.last_request + url = urlsplit(request.url) + self.assertEqual( + unquote(url.path), + '/v1/organization/escalations/', + ) + sent = parse_qs(url.query, keep_blank_values=True) + self.assertEqual(sent, {}) + self.assertEqual(response.to_dict(), data) + + @requests_mock.Mocker() + def test_update_escalation(self, m): + data = { + "$id": "5e5ea5c16897e", + "$createdAt": "2020-10-15T06:38:00.000+00:00", + "$updatedAt": "2020-10-15T06:38:00.000+00:00", + "name": "Platform", + "steps": [], + "repeat": 2.0, + } + headers = {'Content-Type': 'application/json'} + m.request( + 'PATCH', + requests_mock.ANY, + text=json.dumps(data), + headers=headers, + ) + response = self.organization.update_escalation( + '', + name='', + steps=[], + repeat=1, + ) + request = m.last_request + url = urlsplit(request.url) + self.assertEqual( + unquote(url.path), + '/v1/organization/escalations/', + ) + sent = json.loads(request.body or '{}') + self.assertEqual( + sent, + { + 'name': '', + 'steps': [], + 'repeat': 1, + }, + ) + self.assertEqual(response.to_dict(), data) + + @requests_mock.Mocker() + def test_delete_escalation(self, m): + data = '' + headers = {'Content-Type': 'application/json'} + m.request( + 'DELETE', + requests_mock.ANY, + text=json.dumps(data), + headers=headers, + ) + response = self.organization.delete_escalation( + '', + ) + request = m.last_request + url = urlsplit(request.url) + self.assertEqual( + unquote(url.path), + '/v1/organization/escalations/', + ) + sent = json.loads(request.body or '{}') + self.assertEqual(sent, {}) + self.assertEqual(response, data) + @requests_mock.Mocker() def test_list_installations(self, m): data = {