render-lab-tasks-datadog 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (25) hide show
  1. render_lab_tasks_datadog-0.1.0/.gitignore +11 -0
  2. render_lab_tasks_datadog-0.1.0/LICENSE +21 -0
  3. render_lab_tasks_datadog-0.1.0/PKG-INFO +95 -0
  4. render_lab_tasks_datadog-0.1.0/README.md +81 -0
  5. render_lab_tasks_datadog-0.1.0/pyproject.toml +23 -0
  6. render_lab_tasks_datadog-0.1.0/src/render_lab_tasks_datadog/__init__.py +1 -0
  7. render_lab_tasks_datadog-0.1.0/src/render_lab_tasks_datadog/_app.py +3 -0
  8. render_lab_tasks_datadog-0.1.0/src/render_lab_tasks_datadog/await_monitor_recovery.py +20 -0
  9. render_lab_tasks_datadog-0.1.0/src/render_lab_tasks_datadog/cancel_downtime.py +18 -0
  10. render_lab_tasks_datadog-0.1.0/src/render_lab_tasks_datadog/client.py +391 -0
  11. render_lab_tasks_datadog-0.1.0/src/render_lab_tasks_datadog/create_incident.py +18 -0
  12. render_lab_tasks_datadog-0.1.0/src/render_lab_tasks_datadog/create_incident_todo.py +18 -0
  13. render_lab_tasks_datadog-0.1.0/src/render_lab_tasks_datadog/get_incident.py +18 -0
  14. render_lab_tasks_datadog-0.1.0/src/render_lab_tasks_datadog/get_monitor.py +18 -0
  15. render_lab_tasks_datadog-0.1.0/src/render_lab_tasks_datadog/post_event.py +18 -0
  16. render_lab_tasks_datadog-0.1.0/src/render_lab_tasks_datadog/py.typed +0 -0
  17. render_lab_tasks_datadog-0.1.0/src/render_lab_tasks_datadog/retry.py +5 -0
  18. render_lab_tasks_datadog-0.1.0/src/render_lab_tasks_datadog/schedule_downtime.py +18 -0
  19. render_lab_tasks_datadog-0.1.0/src/render_lab_tasks_datadog/search_events.py +18 -0
  20. render_lab_tasks_datadog-0.1.0/src/render_lab_tasks_datadog/search_monitors.py +18 -0
  21. render_lab_tasks_datadog-0.1.0/src/render_lab_tasks_datadog/tasks.py +41 -0
  22. render_lab_tasks_datadog-0.1.0/src/render_lab_tasks_datadog/types.py +162 -0
  23. render_lab_tasks_datadog-0.1.0/src/render_lab_tasks_datadog/update_incident.py +18 -0
  24. render_lab_tasks_datadog-0.1.0/src/render_lab_tasks_datadog/update_incident_todo.py +18 -0
  25. render_lab_tasks_datadog-0.1.0/src/render_lab_tasks_datadog/webhooks.py +31 -0
@@ -0,0 +1,11 @@
1
+ .venv/
2
+ __pycache__/
3
+ *.py[cod]
4
+ .pytest_cache/
5
+ .mypy_cache/
6
+ .ruff_cache/
7
+ dist/
8
+ *.egg-info/
9
+ .env
10
+ .env.*
11
+ !.env.example
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Render Lab
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,95 @@
1
+ Metadata-Version: 2.5
2
+ Name: render-lab-tasks-datadog
3
+ Version: 0.1.0
4
+ Summary: datadog tasks for Render Workflows
5
+ Project-URL: Repository, https://github.com/render-lab/render-tasks-python
6
+ License-Expression: MIT
7
+ License-File: LICENSE
8
+ Requires-Python: >=3.12
9
+ Requires-Dist: httpx<0.29,>=0.28
10
+ Requires-Dist: render-lab-tasks-core<0.2,>=0.1.1
11
+ Requires-Dist: render-lab-triggers<0.2,>=0.1.0
12
+ Requires-Dist: render==1.0.1
13
+ Description-Content-Type: text/markdown
14
+
15
+ # render-lab-tasks-datadog
16
+
17
+ Unreleased Python port: **12 registered tasks** from
18
+ [render-lab/render-tasks](https://github.com/render-lab/render-tasks/tree/45f9c2d44bd28e01ae9813e0d2ff56ee6c533816/packages/tasks-datadog).
19
+ Python 3.12+, Render SDK 1.0.1. Requires core 0.1.1 or later.
20
+
21
+ From the repository root:
22
+
23
+ ```sh
24
+ uv sync --all-packages --locked
25
+ ```
26
+
27
+ Import `render_lab_tasks_datadog.tasks` to register tasks. The package root is inert.
28
+ Compose the exported `app` with `Workflows.from_workflows`; call tasks through
29
+ `ctx.run`. Every operation also exports `*_impl(ctx, input, *, deps=None)` for
30
+ injection. `Client(http, env)` accepts a caller-owned HTTPX client, and
31
+ `Deps(datadog=client)` injects it. Default dependencies open and close the HTTP
32
+ client per invocation; credentials are read lazily at use. No HTTP retries or
33
+ background vendor polling occur; `retry.py` owns the durable retry policies.
34
+
35
+ ## Task surface
36
+
37
+ | Registered task | Python export |
38
+ | --- | --- |
39
+ | `datadog.awaitMonitorRecovery` | `await_monitor_recovery` |
40
+ | `datadog.cancelDowntime` | `cancel_downtime` |
41
+ | `datadog.createIncident` | `create_incident` |
42
+ | `datadog.createIncidentTodo` | `create_incident_todo` |
43
+ | `datadog.getIncident` | `get_incident` |
44
+ | `datadog.getMonitor` | `get_monitor` |
45
+ | `datadog.postEvent` | `post_event` |
46
+ | `datadog.scheduleDowntime` | `schedule_downtime` |
47
+ | `datadog.searchEvents` | `search_events` |
48
+ | `datadog.searchMonitors` | `search_monitors` |
49
+ | `datadog.updateIncident` | `update_incident` |
50
+ | `datadog.updateIncidentTodo` | `update_incident_todo` |
51
+
52
+ Typed JSON inputs and results are in `types.py`. Task names and JSON field names
53
+ match the pinned source; Python function names use snake_case.
54
+
55
+ ## Environment
56
+
57
+ | Variable | Requirement |
58
+ | --- | --- |
59
+ | `DD_API_KEY` | Required for all API calls. |
60
+ | `DD_APP_KEY` | Required for all API calls, including event intake. |
61
+ | `DD_SITE` | Optional; datadoghq.com by default; choose the account region. |
62
+
63
+ ## Behavior and limits
64
+
65
+ Create-incident, create-todo, schedule-downtime, and event-ingestion tasks disable retries. Cancellation treats 404 as success. Recovery polling distinguishes OK, pending alert states, and Unknown. Incident/todo permissions, the event-intake host, regional routing, and terminal-state behavior need live checks.
66
+
67
+ ## Verification
68
+
69
+ All registered tasks have hermetic contract fixtures executed independently against
70
+ the pinned TS implementation. SDK-backed tasks also have explicit HTTP request
71
+ fixtures. See `tests/test_batch3_contracts.py` and `tests/test_batch3_edges.py`.
72
+ These are not live vendor results.
73
+
74
+ Vendor webhooks subpaths and other registration-free TS exports are outside this
75
+ batch unless explicitly listed above. Full registered-task coverage does not
76
+ imply all supporting exports are ported.
77
+
78
+ Pending scopes, test resources, replay, and hosted checks are in the
79
+ [live-testing backlog](https://github.com/render-lab/render-tasks-python/issues/1)
80
+ and [verification tracker](../../docs/verification-tracker.md).
81
+
82
+ ## Webhook adapter
83
+
84
+ `render_lab_tasks_datadog.webhooks.datadog_shared_secret_adapter(on_event, ...)` returns a
85
+ registration-free adapter for `render_lab_triggers`. The callback receives the
86
+ verified event and returns `{"task": "namespace.task", "args": [event]}` or `None`.
87
+ The signing credential `DATADOG_WEBHOOK_SECRET` is read inside verification unless
88
+ provided explicitly. Importing this module does not register tasks. Signature
89
+ checks use the raw body; live delivery remains in the testing backlog.
90
+
91
+ ## Installation
92
+
93
+ ```sh
94
+ pip install render-lab-tasks-datadog==0.1.0
95
+ ```
@@ -0,0 +1,81 @@
1
+ # render-lab-tasks-datadog
2
+
3
+ Unreleased Python port: **12 registered tasks** from
4
+ [render-lab/render-tasks](https://github.com/render-lab/render-tasks/tree/45f9c2d44bd28e01ae9813e0d2ff56ee6c533816/packages/tasks-datadog).
5
+ Python 3.12+, Render SDK 1.0.1. Requires core 0.1.1 or later.
6
+
7
+ From the repository root:
8
+
9
+ ```sh
10
+ uv sync --all-packages --locked
11
+ ```
12
+
13
+ Import `render_lab_tasks_datadog.tasks` to register tasks. The package root is inert.
14
+ Compose the exported `app` with `Workflows.from_workflows`; call tasks through
15
+ `ctx.run`. Every operation also exports `*_impl(ctx, input, *, deps=None)` for
16
+ injection. `Client(http, env)` accepts a caller-owned HTTPX client, and
17
+ `Deps(datadog=client)` injects it. Default dependencies open and close the HTTP
18
+ client per invocation; credentials are read lazily at use. No HTTP retries or
19
+ background vendor polling occur; `retry.py` owns the durable retry policies.
20
+
21
+ ## Task surface
22
+
23
+ | Registered task | Python export |
24
+ | --- | --- |
25
+ | `datadog.awaitMonitorRecovery` | `await_monitor_recovery` |
26
+ | `datadog.cancelDowntime` | `cancel_downtime` |
27
+ | `datadog.createIncident` | `create_incident` |
28
+ | `datadog.createIncidentTodo` | `create_incident_todo` |
29
+ | `datadog.getIncident` | `get_incident` |
30
+ | `datadog.getMonitor` | `get_monitor` |
31
+ | `datadog.postEvent` | `post_event` |
32
+ | `datadog.scheduleDowntime` | `schedule_downtime` |
33
+ | `datadog.searchEvents` | `search_events` |
34
+ | `datadog.searchMonitors` | `search_monitors` |
35
+ | `datadog.updateIncident` | `update_incident` |
36
+ | `datadog.updateIncidentTodo` | `update_incident_todo` |
37
+
38
+ Typed JSON inputs and results are in `types.py`. Task names and JSON field names
39
+ match the pinned source; Python function names use snake_case.
40
+
41
+ ## Environment
42
+
43
+ | Variable | Requirement |
44
+ | --- | --- |
45
+ | `DD_API_KEY` | Required for all API calls. |
46
+ | `DD_APP_KEY` | Required for all API calls, including event intake. |
47
+ | `DD_SITE` | Optional; datadoghq.com by default; choose the account region. |
48
+
49
+ ## Behavior and limits
50
+
51
+ Create-incident, create-todo, schedule-downtime, and event-ingestion tasks disable retries. Cancellation treats 404 as success. Recovery polling distinguishes OK, pending alert states, and Unknown. Incident/todo permissions, the event-intake host, regional routing, and terminal-state behavior need live checks.
52
+
53
+ ## Verification
54
+
55
+ All registered tasks have hermetic contract fixtures executed independently against
56
+ the pinned TS implementation. SDK-backed tasks also have explicit HTTP request
57
+ fixtures. See `tests/test_batch3_contracts.py` and `tests/test_batch3_edges.py`.
58
+ These are not live vendor results.
59
+
60
+ Vendor webhooks subpaths and other registration-free TS exports are outside this
61
+ batch unless explicitly listed above. Full registered-task coverage does not
62
+ imply all supporting exports are ported.
63
+
64
+ Pending scopes, test resources, replay, and hosted checks are in the
65
+ [live-testing backlog](https://github.com/render-lab/render-tasks-python/issues/1)
66
+ and [verification tracker](../../docs/verification-tracker.md).
67
+
68
+ ## Webhook adapter
69
+
70
+ `render_lab_tasks_datadog.webhooks.datadog_shared_secret_adapter(on_event, ...)` returns a
71
+ registration-free adapter for `render_lab_triggers`. The callback receives the
72
+ verified event and returns `{"task": "namespace.task", "args": [event]}` or `None`.
73
+ The signing credential `DATADOG_WEBHOOK_SECRET` is read inside verification unless
74
+ provided explicitly. Importing this module does not register tasks. Signature
75
+ checks use the raw body; live delivery remains in the testing backlog.
76
+
77
+ ## Installation
78
+
79
+ ```sh
80
+ pip install render-lab-tasks-datadog==0.1.0
81
+ ```
@@ -0,0 +1,23 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.27,<2"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "render-lab-tasks-datadog"
7
+ version = "0.1.0"
8
+ description = "datadog tasks for Render Workflows"
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ requires-python = ">=3.12"
13
+ dependencies = ["render-lab-triggers>=0.1.0,<0.2", "render==1.0.1", "httpx>=0.28,<0.29", "render-lab-tasks-core>=0.1.1,<0.2"]
14
+
15
+ [project.urls]
16
+ Repository = "https://github.com/render-lab/render-tasks-python"
17
+
18
+ [tool.uv.sources]
19
+ render-lab-triggers = { workspace = true }
20
+ render-lab-tasks-core = { workspace = true }
21
+
22
+ [tool.hatch.build.targets.wheel]
23
+ packages = ["src/render_lab_tasks_datadog"]
@@ -0,0 +1 @@
1
+ """Import .tasks explicitly to register durable tasks."""
@@ -0,0 +1,3 @@
1
+ from render import Workflows
2
+
3
+ app = Workflows()
@@ -0,0 +1,20 @@
1
+ from render import TaskContext
2
+
3
+ from ._app import app
4
+ from .client import Deps, dependencies
5
+ from .retry import DATADOG_AWAIT_RETRY
6
+ from .types import AwaitMonitorRecoveryInput, AwaitMonitorRecoveryResult
7
+
8
+
9
+ async def await_monitor_recovery_impl(
10
+ ctx: TaskContext, input: AwaitMonitorRecoveryInput, *, deps: Deps | None = None
11
+ ) -> AwaitMonitorRecoveryResult:
12
+ async with dependencies(deps) as resolved:
13
+ return await resolved.datadog.await_monitor_recovery(input)
14
+
15
+
16
+ @app.task(name="datadog.awaitMonitorRecovery", retry=DATADOG_AWAIT_RETRY)
17
+ async def await_monitor_recovery(
18
+ ctx: TaskContext, input: AwaitMonitorRecoveryInput
19
+ ) -> AwaitMonitorRecoveryResult:
20
+ return await await_monitor_recovery_impl(ctx, input)
@@ -0,0 +1,18 @@
1
+ from render import TaskContext
2
+
3
+ from ._app import app
4
+ from .client import Deps, dependencies
5
+ from .retry import DATADOG_RETRY
6
+ from .types import CancelDowntimeInput, CancelDowntimeResult
7
+
8
+
9
+ async def cancel_downtime_impl(
10
+ ctx: TaskContext, input: CancelDowntimeInput, *, deps: Deps | None = None
11
+ ) -> CancelDowntimeResult:
12
+ async with dependencies(deps) as resolved:
13
+ return await resolved.datadog.cancel_downtime(input)
14
+
15
+
16
+ @app.task(name="datadog.cancelDowntime", retry=DATADOG_RETRY)
17
+ async def cancel_downtime(ctx: TaskContext, input: CancelDowntimeInput) -> CancelDowntimeResult:
18
+ return await cancel_downtime_impl(ctx, input)
@@ -0,0 +1,391 @@
1
+ """Injected vendor interface and one-attempt async HTTP adapter."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ import os
7
+ from collections.abc import AsyncIterator, Mapping
8
+ from contextlib import asynccontextmanager
9
+ from dataclasses import dataclass
10
+ from datetime import UTC, datetime
11
+ from typing import Any, Protocol
12
+
13
+ import httpx
14
+ from render_lab_tasks_core.http import (
15
+ ApiError,
16
+ HttpClient,
17
+ enc,
18
+ js_string,
19
+ nullish,
20
+ pick,
21
+ query,
22
+ required,
23
+ )
24
+
25
+ from . import types as t
26
+
27
+
28
+ def obj(value: Any) -> dict[str, Any]:
29
+ return value if isinstance(value, dict) else {}
30
+
31
+
32
+ def array(value: Any) -> list[Any]:
33
+ return value if isinstance(value, list) else []
34
+
35
+
36
+ def numeric(value: Any) -> bool:
37
+ return isinstance(value, (int, float)) and not isinstance(value, bool)
38
+
39
+
40
+ def remap(input: Mapping[str, Any], names: Mapping[str, str]) -> dict[str, Any]:
41
+ return {v: input[k] for k, v in names.items() if k in input}
42
+
43
+
44
+ def qs(values: Mapping[str, Any]) -> str:
45
+ return "?" + query(values) if values else ""
46
+
47
+
48
+ def validate_limit(input: Mapping[str, Any], key: str, task: str) -> None:
49
+ if key not in input:
50
+ return
51
+ n = input[key]
52
+ if not numeric(n) or not math.isfinite(n) or not 1 <= n <= 100 or int(n) != n:
53
+ raise ValueError(f"{task} {key} must be an integer from 1 through 100.")
54
+
55
+
56
+ def monitor(value: Any) -> t.MonitorDTO:
57
+ row = obj(value)
58
+ try:
59
+ id = float(nullish(row.get("id"), 0))
60
+ except (ValueError, TypeError):
61
+ id = 0
62
+ if not math.isfinite(id):
63
+ id = 0
64
+ state = nullish(row.get("overall_state"), row.get("status"))
65
+ if state not in ("Alert", "Warn", "No Data", "OK", "Unknown"):
66
+ state = "Unknown"
67
+ return {
68
+ "id": id,
69
+ "name": nullish(row.get("name"), ""),
70
+ "type": nullish(row.get("type"), ""),
71
+ "overallState": state,
72
+ "message": nullish(row.get("message"), ""),
73
+ "query": nullish(row.get("query"), ""),
74
+ "tags": array(row.get("tags")),
75
+ }
76
+
77
+
78
+ def incident_fields(input: Mapping[str, Any]) -> dict[str, Any]:
79
+ attrs = remap(input, {"title": "title", "customerImpactScope": "customer_impact_scope"})
80
+ fields = {
81
+ v: {"type": "dropdown", "value": input[k]}
82
+ for k, v in {"severity": "severity", "status": "state"}.items()
83
+ if k in input
84
+ }
85
+ if fields:
86
+ attrs["fields"] = fields
87
+ return attrs
88
+
89
+
90
+ def incident(value: Any) -> t.IncidentDTO:
91
+ row = obj(value)
92
+ attrs = obj(row.get("attributes"))
93
+ fields = obj(attrs.get("fields"))
94
+ status = nullish(
95
+ obj(fields.get("state")).get("value"), nullish(attrs.get("state"), attrs.get("status"))
96
+ )
97
+ if status not in ("active", "stable", "resolved", "unknown"):
98
+ status = "unknown"
99
+ return {
100
+ "id": nullish(row.get("id"), ""),
101
+ "title": nullish(attrs.get("title"), ""),
102
+ "customerImpactScope": attrs.get("customer_impact_scope"),
103
+ "severity": nullish(obj(fields.get("severity")).get("value"), attrs.get("severity")),
104
+ "status": status,
105
+ "createdAt": nullish(attrs.get("created"), attrs.get("created_at")),
106
+ "modifiedAt": nullish(attrs.get("modified"), attrs.get("modified_at")),
107
+ }
108
+
109
+
110
+ def todo_fields(input: Mapping[str, Any]) -> dict[str, Any]:
111
+ return remap(
112
+ input,
113
+ {
114
+ "content": "content",
115
+ "completed": "completed",
116
+ "dueDate": "due_date",
117
+ "assignees": "assignees",
118
+ },
119
+ )
120
+
121
+
122
+ def todo(value: Any, incident_id: str) -> t.IncidentTodoDTO:
123
+ row = obj(value)
124
+ attrs = obj(row.get("attributes"))
125
+ return {
126
+ "id": nullish(row.get("id"), ""),
127
+ "incidentId": incident_id,
128
+ "content": nullish(attrs.get("content"), ""),
129
+ "completed": attrs.get("completed") is True,
130
+ "dueDate": attrs.get("due_date"),
131
+ "assignees": array(attrs.get("assignees")),
132
+ }
133
+
134
+
135
+ def downtime(value: Any) -> t.DowntimeDTO:
136
+ row = obj(value)
137
+ attrs = obj(row.get("attributes"))
138
+ schedule = obj(attrs.get("schedule"))
139
+ id = obj(attrs.get("monitor_identifier")).get("monitor_id")
140
+ scope = attrs.get("scope")
141
+ return {
142
+ "id": nullish(row.get("id"), ""),
143
+ "scope": " ".join(scope) if isinstance(scope, list) else nullish(scope, ""),
144
+ "monitorId": id if numeric(id) else None,
145
+ "status": nullish(attrs.get("status"), nullish(attrs.get("state"), "")),
146
+ "start": schedule.get("start"),
147
+ "end": schedule.get("end"),
148
+ "message": attrs.get("message"),
149
+ }
150
+
151
+
152
+ def timestamp(value: Any) -> str | None:
153
+ if isinstance(value, str):
154
+ return value
155
+ if numeric(value) and math.isfinite(value):
156
+ try:
157
+ return (
158
+ datetime.fromtimestamp(value / 1000, UTC)
159
+ .isoformat(timespec="milliseconds")
160
+ .replace("+00:00", "Z")
161
+ )
162
+ except (ValueError, OverflowError, OSError):
163
+ return None
164
+ return None
165
+
166
+
167
+ def event(value: Any) -> t.EventDTO:
168
+ row = obj(value)
169
+ attrs = obj(row.get("attributes"))
170
+ inner = obj(attrs.get("attributes"))
171
+ return {
172
+ "id": nullish(row.get("id"), ""),
173
+ "title": nullish(inner.get("title"), nullish(attrs.get("title"), "")),
174
+ "text": nullish(
175
+ inner.get("message"), nullish(attrs.get("message"), nullish(attrs.get("text"), ""))
176
+ ),
177
+ "timestamp": timestamp(nullish(attrs.get("timestamp"), inner.get("timestamp"))),
178
+ "tags": array(attrs.get("tags")),
179
+ "url": nullish(inner.get("url"), attrs.get("url")),
180
+ "alertType": nullish(inner.get("status"), attrs.get("status")),
181
+ }
182
+
183
+
184
+ class Port(Protocol):
185
+ async def await_monitor_recovery(
186
+ self, input: t.AwaitMonitorRecoveryInput
187
+ ) -> t.AwaitMonitorRecoveryResult: ...
188
+ async def cancel_downtime(self, input: t.CancelDowntimeInput) -> t.CancelDowntimeResult: ...
189
+ async def create_incident(self, input: t.CreateIncidentInput) -> t.IncidentDTO: ...
190
+ async def create_incident_todo(self, input: t.CreateIncidentTodoInput) -> t.IncidentTodoDTO: ...
191
+ async def get_incident(self, input: t.GetIncidentInput) -> t.IncidentDTO: ...
192
+ async def get_monitor(self, input: t.GetMonitorInput) -> t.MonitorDTO: ...
193
+ async def post_event(self, input: t.PostEventInput) -> t.EventDTO: ...
194
+ async def schedule_downtime(self, input: t.ScheduleDowntimeInput) -> t.DowntimeDTO: ...
195
+ async def search_events(self, input: t.SearchEventsInput) -> t.EventPage: ...
196
+ async def search_monitors(self, input: t.SearchMonitorsInput) -> list[t.MonitorDTO]: ...
197
+ async def update_incident(self, input: t.UpdateIncidentInput) -> t.IncidentDTO: ...
198
+ async def update_incident_todo(self, input: t.UpdateIncidentTodoInput) -> t.IncidentTodoDTO: ...
199
+
200
+
201
+ @dataclass(frozen=True)
202
+ class Deps:
203
+ datadog: Port
204
+
205
+
206
+ class Client:
207
+ def __init__(self, http: httpx.AsyncClient, env: Mapping[str, str] | None = None) -> None:
208
+ self.env = os.environ if env is None else env
209
+
210
+ def auth() -> dict[str, str]:
211
+ return {
212
+ "DD-API-KEY": required(self.env, "DD_API_KEY"),
213
+ "DD-APPLICATION-KEY": required(self.env, "DD_APP_KEY"),
214
+ }
215
+
216
+ self.api = HttpClient(
217
+ http,
218
+ lambda: "https://api." + self.env.get("DD_SITE", "datadoghq.com"),
219
+ auth=auth,
220
+ label="Datadog API",
221
+ )
222
+ self.intake = HttpClient(
223
+ http,
224
+ lambda: "https://event-management-intake." + self.env.get("DD_SITE", "datadoghq.com"),
225
+ auth=auth,
226
+ label="Datadog Events API",
227
+ )
228
+
229
+ async def search_monitors(self, input: t.SearchMonitorsInput) -> list[t.MonitorDTO]:
230
+ validate_limit(input, "perPage", "searchMonitors")
231
+ data = obj(
232
+ await self.api.call(
233
+ "/api/v1/monitor/search"
234
+ + qs(remap(input, {"query": "query", "page": "page", "perPage": "per_page"}))
235
+ )
236
+ )
237
+ return [monitor(row) for row in array(data.get("monitors"))]
238
+
239
+ async def get_monitor(self, input: t.GetMonitorInput) -> t.MonitorDTO:
240
+ return monitor(await self.api.call("/api/v1/monitor/" + enc(input["monitorId"])))
241
+
242
+ async def await_monitor_recovery(
243
+ self, input: t.AwaitMonitorRecoveryInput
244
+ ) -> t.AwaitMonitorRecoveryResult:
245
+ row = await self.get_monitor(input)
246
+ id = js_string(input["monitorId"])
247
+ if row["overallState"] == "OK":
248
+ return {"monitorId": input["monitorId"], "state": "OK", "recovered": True}
249
+ if row["overallState"] == "Unknown":
250
+ raise RuntimeError(f"Datadog monitor {id}: monitor state is unknown.")
251
+ raise RuntimeError(f"Datadog monitor {id} still not recovered.")
252
+
253
+ async def create_incident(self, input: t.CreateIncidentInput) -> t.IncidentDTO:
254
+ row = obj(
255
+ await self.api.call(
256
+ "/api/v2/incidents",
257
+ method="POST",
258
+ body={"data": {"type": "incidents", "attributes": incident_fields(input)}},
259
+ )
260
+ )
261
+ return incident(row.get("data"))
262
+
263
+ async def get_incident(self, input: t.GetIncidentInput) -> t.IncidentDTO:
264
+ row = obj(await self.api.call("/api/v2/incidents/" + enc(input["incidentId"])))
265
+ return incident(row.get("data"))
266
+
267
+ async def update_incident(self, input: t.UpdateIncidentInput) -> t.IncidentDTO:
268
+ fields = incident_fields(input)
269
+ if not fields:
270
+ raise ValueError("updateIncident requires at least one mutable field.")
271
+ row = obj(
272
+ await self.api.call(
273
+ "/api/v2/incidents/" + enc(input["incidentId"]),
274
+ method="PATCH",
275
+ body={
276
+ "data": {"id": input["incidentId"], "type": "incidents", "attributes": fields}
277
+ },
278
+ )
279
+ )
280
+ return incident(row.get("data"))
281
+
282
+ async def create_incident_todo(self, input: t.CreateIncidentTodoInput) -> t.IncidentTodoDTO:
283
+ row = obj(
284
+ await self.api.call(
285
+ "/api/v2/incidents/" + enc(input["incidentId"]) + "/relationships/todos",
286
+ method="POST",
287
+ body={"data": {"type": "incident_todos", "attributes": todo_fields(input)}},
288
+ )
289
+ )
290
+ return todo(row.get("data"), input["incidentId"])
291
+
292
+ async def update_incident_todo(self, input: t.UpdateIncidentTodoInput) -> t.IncidentTodoDTO:
293
+ fields = todo_fields(input)
294
+ if not fields:
295
+ raise ValueError("updateIncidentTodo requires at least one mutable field.")
296
+ row = obj(
297
+ await self.api.call(
298
+ "/api/v2/incidents/"
299
+ + enc(input["incidentId"])
300
+ + "/relationships/todos/"
301
+ + enc(input["todoId"]),
302
+ method="PATCH",
303
+ body={
304
+ "data": {"id": input["todoId"], "type": "incident_todos", "attributes": fields}
305
+ },
306
+ )
307
+ )
308
+ return todo(row.get("data"), input["incidentId"])
309
+
310
+ async def schedule_downtime(self, input: t.ScheduleDowntimeInput) -> t.DowntimeDTO:
311
+ fields = remap(
312
+ input, {"scope": "scope", "message": "message", "timezone": "display_timezone"}
313
+ )
314
+ if "monitorId" in input:
315
+ fields["monitor_identifier"] = {"monitor_id": input["monitorId"]}
316
+ schedule = pick(input, "start", "end")
317
+ if schedule:
318
+ fields["schedule"] = schedule
319
+ row = obj(
320
+ await self.api.call(
321
+ "/api/v2/downtime",
322
+ method="POST",
323
+ body={"data": {"type": "downtime", "attributes": fields}},
324
+ )
325
+ )
326
+ return downtime(row.get("data"))
327
+
328
+ async def cancel_downtime(self, input: t.CancelDowntimeInput) -> t.CancelDowntimeResult:
329
+ try:
330
+ await self.api.call(
331
+ "/api/v2/downtime/" + enc(input["downtimeId"]),
332
+ method="DELETE",
333
+ response_type="text",
334
+ )
335
+ except ApiError as error:
336
+ if error.status != 404:
337
+ raise
338
+ return {"downtimeId": input["downtimeId"], "canceled": True}
339
+
340
+ async def post_event(self, input: t.PostEventInput) -> t.EventDTO:
341
+ details: dict[str, Any] = {"status": input.get("alertType", "info")}
342
+ if "aggregationKey" in input:
343
+ details["aggregation_key"] = input["aggregationKey"]
344
+ attrs = {
345
+ "title": input["title"],
346
+ "category": "alert",
347
+ "message": input["text"],
348
+ "attributes": details,
349
+ **pick(input, "tags"),
350
+ }
351
+ row = obj(
352
+ await self.intake.call(
353
+ "/api/v2/events",
354
+ method="POST",
355
+ body={"data": {"type": "event", "attributes": attrs}},
356
+ )
357
+ )
358
+ result = event(row.get("data"))
359
+ result["title"] = result["title"] or input["title"]
360
+ result["text"] = result["text"] or input["text"]
361
+ result["tags"] = result["tags"] or input.get("tags", [])
362
+ result["alertType"] = nullish(result["alertType"], input.get("alertType"))
363
+ return result
364
+
365
+ async def search_events(self, input: t.SearchEventsInput) -> t.EventPage:
366
+ validate_limit(input, "limit", "searchEvents")
367
+ body: dict[str, Any] = {"filter": pick(input, "query", "from", "to"), "sort": "-timestamp"}
368
+ page = pick(input, "limit", "cursor")
369
+ if page:
370
+ body["page"] = page
371
+ row = obj(await self.api.call("/api/v2/events/search", method="POST", body=body))
372
+ return {
373
+ "events": [event(r) for r in array(row.get("data"))],
374
+ "nextCursor": obj(obj(row.get("meta")).get("page")).get("after"),
375
+ }
376
+
377
+
378
+ @asynccontextmanager
379
+ async def dependencies(deps: Deps | None) -> AsyncIterator[Deps]:
380
+ if deps is not None:
381
+ yield deps
382
+ else:
383
+ async with httpx.AsyncClient(
384
+ timeout=30, transport=httpx.AsyncHTTPTransport(retries=0)
385
+ ) as http:
386
+ yield Deps(datadog=Client(http))
387
+
388
+
389
+ DatadogPort = Port
390
+ DatadogClient = Client
391
+ DatadogDeps = Deps
@@ -0,0 +1,18 @@
1
+ from render import TaskContext
2
+
3
+ from ._app import app
4
+ from .client import Deps, dependencies
5
+ from .retry import DATADOG_NO_RETRY
6
+ from .types import CreateIncidentInput, IncidentDTO
7
+
8
+
9
+ async def create_incident_impl(
10
+ ctx: TaskContext, input: CreateIncidentInput, *, deps: Deps | None = None
11
+ ) -> IncidentDTO:
12
+ async with dependencies(deps) as resolved:
13
+ return await resolved.datadog.create_incident(input)
14
+
15
+
16
+ @app.task(name="datadog.createIncident", retry=DATADOG_NO_RETRY)
17
+ async def create_incident(ctx: TaskContext, input: CreateIncidentInput) -> IncidentDTO:
18
+ return await create_incident_impl(ctx, input)
@@ -0,0 +1,18 @@
1
+ from render import TaskContext
2
+
3
+ from ._app import app
4
+ from .client import Deps, dependencies
5
+ from .retry import DATADOG_NO_RETRY
6
+ from .types import CreateIncidentTodoInput, IncidentTodoDTO
7
+
8
+
9
+ async def create_incident_todo_impl(
10
+ ctx: TaskContext, input: CreateIncidentTodoInput, *, deps: Deps | None = None
11
+ ) -> IncidentTodoDTO:
12
+ async with dependencies(deps) as resolved:
13
+ return await resolved.datadog.create_incident_todo(input)
14
+
15
+
16
+ @app.task(name="datadog.createIncidentTodo", retry=DATADOG_NO_RETRY)
17
+ async def create_incident_todo(ctx: TaskContext, input: CreateIncidentTodoInput) -> IncidentTodoDTO:
18
+ return await create_incident_todo_impl(ctx, input)
@@ -0,0 +1,18 @@
1
+ from render import TaskContext
2
+
3
+ from ._app import app
4
+ from .client import Deps, dependencies
5
+ from .retry import DATADOG_RETRY
6
+ from .types import GetIncidentInput, IncidentDTO
7
+
8
+
9
+ async def get_incident_impl(
10
+ ctx: TaskContext, input: GetIncidentInput, *, deps: Deps | None = None
11
+ ) -> IncidentDTO:
12
+ async with dependencies(deps) as resolved:
13
+ return await resolved.datadog.get_incident(input)
14
+
15
+
16
+ @app.task(name="datadog.getIncident", retry=DATADOG_RETRY)
17
+ async def get_incident(ctx: TaskContext, input: GetIncidentInput) -> IncidentDTO:
18
+ return await get_incident_impl(ctx, input)
@@ -0,0 +1,18 @@
1
+ from render import TaskContext
2
+
3
+ from ._app import app
4
+ from .client import Deps, dependencies
5
+ from .retry import DATADOG_RETRY
6
+ from .types import GetMonitorInput, MonitorDTO
7
+
8
+
9
+ async def get_monitor_impl(
10
+ ctx: TaskContext, input: GetMonitorInput, *, deps: Deps | None = None
11
+ ) -> MonitorDTO:
12
+ async with dependencies(deps) as resolved:
13
+ return await resolved.datadog.get_monitor(input)
14
+
15
+
16
+ @app.task(name="datadog.getMonitor", retry=DATADOG_RETRY)
17
+ async def get_monitor(ctx: TaskContext, input: GetMonitorInput) -> MonitorDTO:
18
+ return await get_monitor_impl(ctx, input)
@@ -0,0 +1,18 @@
1
+ from render import TaskContext
2
+
3
+ from ._app import app
4
+ from .client import Deps, dependencies
5
+ from .retry import DATADOG_NO_RETRY
6
+ from .types import EventDTO, PostEventInput
7
+
8
+
9
+ async def post_event_impl(
10
+ ctx: TaskContext, input: PostEventInput, *, deps: Deps | None = None
11
+ ) -> EventDTO:
12
+ async with dependencies(deps) as resolved:
13
+ return await resolved.datadog.post_event(input)
14
+
15
+
16
+ @app.task(name="datadog.postEvent", retry=DATADOG_NO_RETRY)
17
+ async def post_event(ctx: TaskContext, input: PostEventInput) -> EventDTO:
18
+ return await post_event_impl(ctx, input)
@@ -0,0 +1,5 @@
1
+ from render import Retry
2
+
3
+ DATADOG_AWAIT_RETRY = Retry(max_retries=240, wait_duration_ms=15000, backoff_scaling=1)
4
+ DATADOG_RETRY = Retry(max_retries=3, wait_duration_ms=1000, backoff_scaling=2)
5
+ DATADOG_NO_RETRY = Retry(max_retries=0, wait_duration_ms=1000, backoff_scaling=1)
@@ -0,0 +1,18 @@
1
+ from render import TaskContext
2
+
3
+ from ._app import app
4
+ from .client import Deps, dependencies
5
+ from .retry import DATADOG_NO_RETRY
6
+ from .types import DowntimeDTO, ScheduleDowntimeInput
7
+
8
+
9
+ async def schedule_downtime_impl(
10
+ ctx: TaskContext, input: ScheduleDowntimeInput, *, deps: Deps | None = None
11
+ ) -> DowntimeDTO:
12
+ async with dependencies(deps) as resolved:
13
+ return await resolved.datadog.schedule_downtime(input)
14
+
15
+
16
+ @app.task(name="datadog.scheduleDowntime", retry=DATADOG_NO_RETRY)
17
+ async def schedule_downtime(ctx: TaskContext, input: ScheduleDowntimeInput) -> DowntimeDTO:
18
+ return await schedule_downtime_impl(ctx, input)
@@ -0,0 +1,18 @@
1
+ from render import TaskContext
2
+
3
+ from ._app import app
4
+ from .client import Deps, dependencies
5
+ from .retry import DATADOG_RETRY
6
+ from .types import EventPage, SearchEventsInput
7
+
8
+
9
+ async def search_events_impl(
10
+ ctx: TaskContext, input: SearchEventsInput, *, deps: Deps | None = None
11
+ ) -> EventPage:
12
+ async with dependencies(deps) as resolved:
13
+ return await resolved.datadog.search_events(input)
14
+
15
+
16
+ @app.task(name="datadog.searchEvents", retry=DATADOG_RETRY)
17
+ async def search_events(ctx: TaskContext, input: SearchEventsInput) -> EventPage:
18
+ return await search_events_impl(ctx, input)
@@ -0,0 +1,18 @@
1
+ from render import TaskContext
2
+
3
+ from ._app import app
4
+ from .client import Deps, dependencies
5
+ from .retry import DATADOG_RETRY
6
+ from .types import MonitorDTO, SearchMonitorsInput
7
+
8
+
9
+ async def search_monitors_impl(
10
+ ctx: TaskContext, input: SearchMonitorsInput, *, deps: Deps | None = None
11
+ ) -> list[MonitorDTO]:
12
+ async with dependencies(deps) as resolved:
13
+ return await resolved.datadog.search_monitors(input)
14
+
15
+
16
+ @app.task(name="datadog.searchMonitors", retry=DATADOG_RETRY)
17
+ async def search_monitors(ctx: TaskContext, input: SearchMonitorsInput) -> list[MonitorDTO]:
18
+ return await search_monitors_impl(ctx, input)
@@ -0,0 +1,41 @@
1
+ from ._app import app
2
+ from .await_monitor_recovery import await_monitor_recovery, await_monitor_recovery_impl
3
+ from .cancel_downtime import cancel_downtime, cancel_downtime_impl
4
+ from .create_incident import create_incident, create_incident_impl
5
+ from .create_incident_todo import create_incident_todo, create_incident_todo_impl
6
+ from .get_incident import get_incident, get_incident_impl
7
+ from .get_monitor import get_monitor, get_monitor_impl
8
+ from .post_event import post_event, post_event_impl
9
+ from .schedule_downtime import schedule_downtime, schedule_downtime_impl
10
+ from .search_events import search_events, search_events_impl
11
+ from .search_monitors import search_monitors, search_monitors_impl
12
+ from .update_incident import update_incident, update_incident_impl
13
+ from .update_incident_todo import update_incident_todo, update_incident_todo_impl
14
+
15
+ __all__ = [
16
+ "app",
17
+ "await_monitor_recovery",
18
+ "await_monitor_recovery_impl",
19
+ "cancel_downtime",
20
+ "cancel_downtime_impl",
21
+ "create_incident",
22
+ "create_incident_impl",
23
+ "create_incident_todo",
24
+ "create_incident_todo_impl",
25
+ "get_incident",
26
+ "get_incident_impl",
27
+ "get_monitor",
28
+ "get_monitor_impl",
29
+ "post_event",
30
+ "post_event_impl",
31
+ "schedule_downtime",
32
+ "schedule_downtime_impl",
33
+ "search_events",
34
+ "search_events_impl",
35
+ "search_monitors",
36
+ "search_monitors_impl",
37
+ "update_incident",
38
+ "update_incident_impl",
39
+ "update_incident_todo",
40
+ "update_incident_todo_impl",
41
+ ]
@@ -0,0 +1,162 @@
1
+ """JSON contracts ported from the pinned TypeScript pack."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Literal, NotRequired, TypedDict
6
+
7
+ type JsonValue = str | float | bool | None | list[JsonValue] | dict[str, JsonValue]
8
+
9
+ type MonitorState = (
10
+ Literal["Alert"] | Literal["Warn"] | Literal["No Data"] | Literal["OK"] | Literal["Unknown"]
11
+ )
12
+
13
+
14
+ class MonitorDTO(TypedDict):
15
+ id: float
16
+ name: str
17
+ type: str
18
+ overallState: MonitorState
19
+ message: str
20
+ query: str
21
+ tags: list[str]
22
+
23
+
24
+ class SearchMonitorsInput(TypedDict):
25
+ query: NotRequired[str]
26
+ page: NotRequired[float]
27
+ perPage: NotRequired[float]
28
+
29
+
30
+ class GetMonitorInput(TypedDict):
31
+ monitorId: float
32
+
33
+
34
+ class AwaitMonitorRecoveryInput(TypedDict):
35
+ monitorId: float
36
+
37
+
38
+ class AwaitMonitorRecoveryResult(TypedDict):
39
+ monitorId: float
40
+ state: Literal["OK"]
41
+ recovered: Literal[True]
42
+
43
+
44
+ type IncidentStatus = (
45
+ Literal["active"] | Literal["stable"] | Literal["resolved"] | Literal["unknown"]
46
+ )
47
+
48
+
49
+ class IncidentDTO(TypedDict):
50
+ id: str
51
+ title: str
52
+ customerImpactScope: str | None
53
+ severity: str | None
54
+ status: IncidentStatus
55
+ createdAt: str | None
56
+ modifiedAt: str | None
57
+
58
+
59
+ class CreateIncidentInput(TypedDict):
60
+ title: str
61
+ customerImpactScope: NotRequired[str]
62
+ severity: NotRequired[str]
63
+
64
+
65
+ class GetIncidentInput(TypedDict):
66
+ incidentId: str
67
+
68
+
69
+ class UpdateIncidentInput(TypedDict):
70
+ incidentId: str
71
+ title: NotRequired[str]
72
+ customerImpactScope: NotRequired[str]
73
+ severity: NotRequired[str]
74
+ status: NotRequired[Literal["active", "stable", "resolved"]]
75
+
76
+
77
+ class IncidentTodoDTO(TypedDict):
78
+ id: str
79
+ incidentId: str
80
+ content: str
81
+ completed: bool
82
+ dueDate: str | None
83
+ assignees: list[str]
84
+
85
+
86
+ class CreateIncidentTodoInput(TypedDict):
87
+ incidentId: str
88
+ content: str
89
+ dueDate: NotRequired[str]
90
+ assignees: NotRequired[list[str]]
91
+
92
+
93
+ class UpdateIncidentTodoInput(TypedDict):
94
+ incidentId: str
95
+ todoId: str
96
+ content: NotRequired[str]
97
+ completed: NotRequired[bool]
98
+ dueDate: NotRequired[str | None]
99
+ assignees: NotRequired[list[str]]
100
+
101
+
102
+ class DowntimeDTO(TypedDict):
103
+ id: str
104
+ scope: str
105
+ monitorId: float | None
106
+ status: str
107
+ start: str | None
108
+ end: str | None
109
+ message: str | None
110
+
111
+
112
+ class ScheduleDowntimeInput(TypedDict):
113
+ scope: str
114
+ monitorId: NotRequired[float]
115
+ start: NotRequired[str]
116
+ end: NotRequired[str]
117
+ message: NotRequired[str]
118
+ timezone: NotRequired[str]
119
+
120
+
121
+ class CancelDowntimeInput(TypedDict):
122
+ downtimeId: str
123
+
124
+
125
+ class CancelDowntimeResult(TypedDict):
126
+ downtimeId: str
127
+ canceled: Literal[True]
128
+
129
+
130
+ class EventDTO(TypedDict):
131
+ id: str
132
+ title: str
133
+ text: str
134
+ timestamp: str | None
135
+ tags: list[str]
136
+ url: str | None
137
+ alertType: str | None
138
+
139
+
140
+ class PostEventInput(TypedDict):
141
+ title: str
142
+ text: str
143
+ tags: NotRequired[list[str]]
144
+ alertType: NotRequired[str]
145
+ aggregationKey: NotRequired[str]
146
+
147
+
148
+ SearchEventsInput = TypedDict(
149
+ "SearchEventsInput",
150
+ {
151
+ "query": NotRequired[str],
152
+ "from": NotRequired[str],
153
+ "to": NotRequired[str],
154
+ "limit": NotRequired[float],
155
+ "cursor": NotRequired[str],
156
+ },
157
+ )
158
+
159
+
160
+ class EventPage(TypedDict):
161
+ events: list[EventDTO]
162
+ nextCursor: str | None
@@ -0,0 +1,18 @@
1
+ from render import TaskContext
2
+
3
+ from ._app import app
4
+ from .client import Deps, dependencies
5
+ from .retry import DATADOG_RETRY
6
+ from .types import IncidentDTO, UpdateIncidentInput
7
+
8
+
9
+ async def update_incident_impl(
10
+ ctx: TaskContext, input: UpdateIncidentInput, *, deps: Deps | None = None
11
+ ) -> IncidentDTO:
12
+ async with dependencies(deps) as resolved:
13
+ return await resolved.datadog.update_incident(input)
14
+
15
+
16
+ @app.task(name="datadog.updateIncident", retry=DATADOG_RETRY)
17
+ async def update_incident(ctx: TaskContext, input: UpdateIncidentInput) -> IncidentDTO:
18
+ return await update_incident_impl(ctx, input)
@@ -0,0 +1,18 @@
1
+ from render import TaskContext
2
+
3
+ from ._app import app
4
+ from .client import Deps, dependencies
5
+ from .retry import DATADOG_RETRY
6
+ from .types import IncidentTodoDTO, UpdateIncidentTodoInput
7
+
8
+
9
+ async def update_incident_todo_impl(
10
+ ctx: TaskContext, input: UpdateIncidentTodoInput, *, deps: Deps | None = None
11
+ ) -> IncidentTodoDTO:
12
+ async with dependencies(deps) as resolved:
13
+ return await resolved.datadog.update_incident_todo(input)
14
+
15
+
16
+ @app.task(name="datadog.updateIncidentTodo", retry=DATADOG_RETRY)
17
+ async def update_incident_todo(ctx: TaskContext, input: UpdateIncidentTodoInput) -> IncidentTodoDTO:
18
+ return await update_incident_todo_impl(ctx, input)
@@ -0,0 +1,31 @@
1
+ """Registration-free datadog webhook verification and event mapping."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from collections.abc import Callable
7
+
8
+ from render_lab_tasks_core.signatures import safe_equal
9
+ from render_lab_triggers.types import Adapter, Json, WebhookContext, WebhookDispatch, WebhookRequest
10
+
11
+ type OnEvent = Callable[[dict[str, Json]], WebhookDispatch | None]
12
+
13
+
14
+ def verify_datadog_shared_secret(secret: str, token: str | None) -> bool:
15
+ return bool(token) and safe_equal(token, secret)
16
+
17
+
18
+ def datadog_shared_secret_adapter(
19
+ on_event: OnEvent, *, secret: str | None = None, header_name: str = "x-render-webhook-secret"
20
+ ) -> Adapter:
21
+ def verify(req: WebhookRequest) -> bool:
22
+ key = secret if secret is not None else os.getenv("DATADOG_WEBHOOK_SECRET")
23
+ return bool(key) and (
24
+ verify_datadog_shared_secret(key or "", req["headers"].get(header_name.lower()))
25
+ )
26
+
27
+ def map_event(ctx: WebhookContext) -> WebhookDispatch | None:
28
+ payload = ctx["body"] if ctx["body"] is not None else {}
29
+ return on_event({"payload": payload})
30
+
31
+ return Adapter(verify, map_event)