@rawdash/connector-datadog 0.15.0 → 0.18.0
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.
- package/LICENSE +202 -0
- package/dist/index.d.ts +138 -1
- package/dist/index.js +6 -3
- package/dist/index.js.map +1 -1
- package/package.json +14 -13
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/dist/index.d.ts
CHANGED
|
@@ -52,6 +52,143 @@ declare const datadogCredentials: {
|
|
|
52
52
|
};
|
|
53
53
|
};
|
|
54
54
|
type DatadogCredentials = typeof datadogCredentials;
|
|
55
|
+
declare const datadogResources: {
|
|
56
|
+
readonly datadog_monitor: {
|
|
57
|
+
readonly shape: "entity";
|
|
58
|
+
readonly description: "Datadog monitors with name, type, current status (OK / Alert / Warn / No Data), priority, and tags.";
|
|
59
|
+
readonly endpoint: "GET /api/v1/monitor/search";
|
|
60
|
+
readonly responses: {
|
|
61
|
+
readonly monitors: z.ZodObject<{
|
|
62
|
+
monitors: z.ZodArray<z.ZodObject<{
|
|
63
|
+
id: z.ZodNumber;
|
|
64
|
+
name: z.ZodString;
|
|
65
|
+
type: z.ZodString;
|
|
66
|
+
status: z.ZodEnum<{
|
|
67
|
+
OK: "OK";
|
|
68
|
+
Alert: "Alert";
|
|
69
|
+
Warn: "Warn";
|
|
70
|
+
"No Data": "No Data";
|
|
71
|
+
Ignored: "Ignored";
|
|
72
|
+
}>;
|
|
73
|
+
priority: z.ZodNullable<z.ZodNumber>;
|
|
74
|
+
tags: z.ZodArray<z.ZodString>;
|
|
75
|
+
overall_state_modified: z.ZodOptional<z.ZodNullable<z.ZodISODateTime>>;
|
|
76
|
+
created: z.ZodISODateTime;
|
|
77
|
+
modified: z.ZodISODateTime;
|
|
78
|
+
}, z.core.$strip>>;
|
|
79
|
+
metadata: z.ZodObject<{
|
|
80
|
+
page: z.ZodNumber;
|
|
81
|
+
page_count: z.ZodNumber;
|
|
82
|
+
per_page: z.ZodNumber;
|
|
83
|
+
total_count: z.ZodNumber;
|
|
84
|
+
}, z.core.$strip>;
|
|
85
|
+
}, z.core.$strip>;
|
|
86
|
+
};
|
|
87
|
+
};
|
|
88
|
+
readonly datadog_monitor_event: {
|
|
89
|
+
readonly shape: "event";
|
|
90
|
+
readonly description: "Monitor state-transition events, emitted whenever a monitor's status changes from its previously-stored value.";
|
|
91
|
+
readonly notes: "Derived by diffing each monitor's current status against the last-synced status, so it depends on the monitors phase running and on prior monitor state being stored.";
|
|
92
|
+
};
|
|
93
|
+
readonly datadog_incident: {
|
|
94
|
+
readonly shape: "entity";
|
|
95
|
+
readonly description: "Datadog incidents with title, severity, state, and created / resolved timestamps.";
|
|
96
|
+
readonly endpoint: "GET /api/v2/incidents";
|
|
97
|
+
readonly responses: {
|
|
98
|
+
readonly incidents: z.ZodObject<{
|
|
99
|
+
data: z.ZodArray<z.ZodObject<{
|
|
100
|
+
id: z.ZodString;
|
|
101
|
+
type: z.ZodLiteral<"incidents">;
|
|
102
|
+
attributes: z.ZodObject<{
|
|
103
|
+
title: z.ZodString;
|
|
104
|
+
severity: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
105
|
+
state: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
106
|
+
customer_impact_scope: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
107
|
+
created: z.ZodISODateTime;
|
|
108
|
+
modified: z.ZodOptional<z.ZodNullable<z.ZodISODateTime>>;
|
|
109
|
+
resolved: z.ZodOptional<z.ZodNullable<z.ZodISODateTime>>;
|
|
110
|
+
}, z.core.$strip>;
|
|
111
|
+
}, z.core.$strip>>;
|
|
112
|
+
meta: z.ZodOptional<z.ZodObject<{
|
|
113
|
+
pagination: z.ZodOptional<z.ZodObject<{
|
|
114
|
+
next_offset: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
115
|
+
offset: z.ZodOptional<z.ZodNumber>;
|
|
116
|
+
size: z.ZodOptional<z.ZodNumber>;
|
|
117
|
+
}, z.core.$strip>>;
|
|
118
|
+
}, z.core.$strip>>;
|
|
119
|
+
}, z.core.$strip>;
|
|
120
|
+
};
|
|
121
|
+
};
|
|
122
|
+
readonly datadog_slo: {
|
|
123
|
+
readonly shape: "entity";
|
|
124
|
+
readonly description: "Service Level Objectives with type, thresholds, primary target, and latest SLI value.";
|
|
125
|
+
readonly endpoint: "GET /api/v1/slo";
|
|
126
|
+
readonly responses: {
|
|
127
|
+
readonly slos: z.ZodObject<{
|
|
128
|
+
data: z.ZodArray<z.ZodObject<{
|
|
129
|
+
id: z.ZodString;
|
|
130
|
+
name: z.ZodString;
|
|
131
|
+
type: z.ZodString;
|
|
132
|
+
thresholds: z.ZodArray<z.ZodObject<{
|
|
133
|
+
timeframe: z.ZodString;
|
|
134
|
+
target: z.ZodNumber;
|
|
135
|
+
warning: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
136
|
+
}, z.core.$strip>>;
|
|
137
|
+
overall_status: z.ZodOptional<z.ZodNullable<z.ZodArray<z.ZodObject<{
|
|
138
|
+
sli_value: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
139
|
+
indexed_at: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
140
|
+
}, z.core.$strip>>>>;
|
|
141
|
+
created_at: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
142
|
+
modified_at: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
143
|
+
}, z.core.$strip>>;
|
|
144
|
+
}, z.core.$strip>;
|
|
145
|
+
};
|
|
146
|
+
};
|
|
147
|
+
readonly datadog_slo_sli: {
|
|
148
|
+
readonly shape: "metric";
|
|
149
|
+
readonly description: "SLI value samples per SLO, one per overall_status snapshot reported by Datadog.";
|
|
150
|
+
readonly unit: "percent";
|
|
151
|
+
readonly dimensions: [{
|
|
152
|
+
readonly name: "sloId";
|
|
153
|
+
readonly description: "Datadog SLO id.";
|
|
154
|
+
}, {
|
|
155
|
+
readonly name: "sloType";
|
|
156
|
+
readonly description: "SLO type (metric, monitor, etc.).";
|
|
157
|
+
}];
|
|
158
|
+
};
|
|
159
|
+
readonly datadog_metric: {
|
|
160
|
+
readonly shape: "metric";
|
|
161
|
+
readonly dynamic: true;
|
|
162
|
+
readonly description: "User-declared metric timeseries samples, stored as `datadog_metric.<query name>`, from the Datadog Metrics Query API.";
|
|
163
|
+
readonly endpoint: "POST /api/v2/query/timeseries";
|
|
164
|
+
readonly dimensions: [{
|
|
165
|
+
readonly name: "queryName";
|
|
166
|
+
readonly description: "The user-declared query name.";
|
|
167
|
+
}, {
|
|
168
|
+
readonly name: "query";
|
|
169
|
+
readonly description: "The Datadog metrics query string.";
|
|
170
|
+
}, {
|
|
171
|
+
readonly name: "tags";
|
|
172
|
+
readonly description: "Comma-joined group tags for the series, or `*` when the series is ungrouped.";
|
|
173
|
+
}];
|
|
174
|
+
readonly responses: {
|
|
175
|
+
readonly metric_queries: z.ZodObject<{
|
|
176
|
+
data: z.ZodObject<{
|
|
177
|
+
type: z.ZodLiteral<"timeseries_response">;
|
|
178
|
+
attributes: z.ZodObject<{
|
|
179
|
+
series: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
180
|
+
group_tags: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
181
|
+
query_index: z.ZodOptional<z.ZodNumber>;
|
|
182
|
+
}, z.core.$strip>>>;
|
|
183
|
+
times: z.ZodOptional<z.ZodArray<z.ZodNumber>>;
|
|
184
|
+
values: z.ZodOptional<z.ZodArray<z.ZodArray<z.ZodNumber>>>;
|
|
185
|
+
}, z.core.$strip>;
|
|
186
|
+
}, z.core.$strip>;
|
|
187
|
+
}, z.core.$strip>;
|
|
188
|
+
};
|
|
189
|
+
};
|
|
190
|
+
};
|
|
191
|
+
declare const id = "datadog";
|
|
55
192
|
declare class DatadogConnector extends BaseConnector<DatadogSettings, DatadogCredentials> {
|
|
56
193
|
static readonly id = "datadog";
|
|
57
194
|
static readonly resources: {
|
|
@@ -311,4 +448,4 @@ declare class DatadogConnector extends BaseConnector<DatadogSettings, DatadogCre
|
|
|
311
448
|
sync(options: SyncOptions, storage: StorageHandle, signal?: AbortSignal): Promise<SyncResult>;
|
|
312
449
|
}
|
|
313
450
|
|
|
314
|
-
export { DatadogConnector, type DatadogResource, type DatadogSettings, configFields, DatadogConnector as default, doc };
|
|
451
|
+
export { DatadogConnector, type DatadogResource, type DatadogSettings, configFields, DatadogConnector as default, doc, id, datadogResources as resources };
|
package/dist/index.js
CHANGED
|
@@ -329,8 +329,9 @@ var datadogResources = defineResources({
|
|
|
329
329
|
responses: { metric_queries: timeseriesResponseSchema }
|
|
330
330
|
}
|
|
331
331
|
});
|
|
332
|
+
var id = "datadog";
|
|
332
333
|
var DatadogConnector = class _DatadogConnector extends BaseConnector {
|
|
333
|
-
static id =
|
|
334
|
+
static id = id;
|
|
334
335
|
static resources = datadogResources;
|
|
335
336
|
static schemas = schemasFromResources(datadogResources);
|
|
336
337
|
static create(input, ctx) {
|
|
@@ -346,7 +347,7 @@ var DatadogConnector = class _DatadogConnector extends BaseConnector {
|
|
|
346
347
|
ctx
|
|
347
348
|
);
|
|
348
349
|
}
|
|
349
|
-
id =
|
|
350
|
+
id = id;
|
|
350
351
|
credentials = datadogCredentials;
|
|
351
352
|
get apiHost() {
|
|
352
353
|
return `api.${(this.settings.site ?? DEFAULT_SITE).toLowerCase()}`;
|
|
@@ -836,6 +837,8 @@ export {
|
|
|
836
837
|
DatadogConnector,
|
|
837
838
|
configFields,
|
|
838
839
|
index_default as default,
|
|
839
|
-
doc
|
|
840
|
+
doc,
|
|
841
|
+
id,
|
|
842
|
+
datadogResources as resources
|
|
840
843
|
};
|
|
841
844
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../connector-shared/src/errors.ts","../../../connector-shared/src/retry.ts","../../../connector-shared/src/version.ts","../../../connector-shared/src/request.ts","../../../connector-shared/src/rate-limit.ts","../../../connector-shared/src/sanitize.ts","../../../connector-shared/src/epoch.ts","../../../connector-shared/src/pagination.ts","../../../connector-shared/src/logger.ts","../src/datadog.ts","../src/index.ts"],"sourcesContent":["import type { HttpResponse } from './types';\n\nexport type HttpErrorKind =\n | 'transient'\n | 'rate_limit'\n | 'auth'\n | 'upstream_bug'\n | 'client_bug';\n\nexport abstract class HttpClientError extends Error {\n abstract readonly kind: HttpErrorKind;\n readonly response?: HttpResponse;\n\n constructor(message: string, response?: HttpResponse) {\n super(message);\n this.name = new.target.name;\n this.response = response;\n }\n}\n\nexport class TransientError extends HttpClientError {\n readonly kind = 'transient' as const;\n}\n\nexport class RateLimitError extends HttpClientError {\n readonly kind = 'rate_limit' as const;\n readonly retryAfter?: Date;\n\n constructor(message: string, response?: HttpResponse, retryAfter?: Date) {\n super(message, response);\n this.retryAfter = retryAfter;\n }\n}\n\nexport class AuthError extends HttpClientError {\n readonly kind = 'auth' as const;\n}\n\nexport class UpstreamBugError extends HttpClientError {\n readonly kind = 'upstream_bug' as const;\n}\n\nexport class ClientBugError extends HttpClientError {\n readonly kind = 'client_bug' as const;\n}\n\nexport function classifyStatus(status: number): HttpErrorKind {\n if (status === 429) {\n return 'rate_limit';\n }\n if (status === 401 || status === 403) {\n return 'auth';\n }\n if (status === 408) {\n return 'transient';\n }\n if (status >= 500) {\n return 'upstream_bug';\n }\n if (status >= 400) {\n return 'client_bug';\n }\n return 'client_bug';\n}\n\nexport function errorForStatus(\n message: string,\n response: HttpResponse,\n retryAfter?: Date,\n): HttpClientError {\n const kind = classifyStatus(response.status);\n switch (kind) {\n case 'rate_limit':\n return new RateLimitError(message, response, retryAfter);\n case 'auth':\n return new AuthError(message, response);\n case 'transient':\n return new TransientError(message, response);\n case 'upstream_bug':\n return new UpstreamBugError(message, response);\n case 'client_bug':\n return new ClientBugError(message, response);\n }\n}\n","import { HttpClientError, RateLimitError, TransientError } from './errors';\n\nexport interface RetryPolicy {\n maxAttempts?: number;\n initialDelayMs?: number;\n maxDelayMs?: number;\n retryOn?: (status: number | null, err?: Error) => boolean;\n}\n\nexport const defaultRetryOn = (status: number | null, err?: Error): boolean => {\n if (err instanceof RateLimitError) {\n return true;\n }\n if (err instanceof TransientError) {\n return true;\n }\n if (status === null) {\n return err instanceof Error && !(err instanceof HttpClientError);\n }\n if (status === 408 || status === 429) {\n return true;\n }\n if (status >= 500) {\n return true;\n }\n return false;\n};\n\nexport function backoffDelayMs(\n attempt: number,\n policy: Required<Pick<RetryPolicy, 'initialDelayMs' | 'maxDelayMs'>>,\n): number {\n const base = policy.initialDelayMs * 2 ** attempt;\n const jitter = base * 0.25 * Math.random();\n return Math.min(base + jitter, policy.maxDelayMs);\n}\n\nexport function parseRetryAfter(\n headerValue: string | null,\n now: Date = new Date(),\n): Date | undefined {\n if (!headerValue) {\n return undefined;\n }\n const trimmed = headerValue.trim();\n if (/^\\d+$/.test(trimmed)) {\n return new Date(now.getTime() + Number(trimmed) * 1000);\n }\n const parsed = Date.parse(trimmed);\n if (Number.isNaN(parsed)) {\n return undefined;\n }\n return new Date(parsed);\n}\n\nexport function sleep(ms: number, signal?: AbortSignal): Promise<void> {\n if (signal?.aborted) {\n return Promise.reject(signal.reason ?? new Error('Aborted'));\n }\n return new Promise<void>((resolve, reject) => {\n const onAbort = () => {\n clearTimeout(timer);\n reject(signal!.reason ?? new Error('Aborted'));\n };\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n}\n","export const HTTP_CLIENT_VERSION = '0.0.0';\n\nexport const DEFAULT_USER_AGENT = `rawdash-connector/${HTTP_CLIENT_VERSION} (+https://rawdash.dev)`;\n\nexport function connectorUserAgent(connectorId: string): string {\n return `rawdash-connector-${connectorId}/${HTTP_CLIENT_VERSION} (+https://rawdash.dev)`;\n}\n","import {\n AuthError,\n ClientBugError,\n HttpClientError,\n RateLimitError,\n TransientError,\n UpstreamBugError,\n errorForStatus,\n} from './errors';\nimport { defaultRetryOn, parseRetryAfter, sleep } from './retry';\nimport type { FetchLike, HttpMethod, HttpRequest, HttpResponse } from './types';\nimport { DEFAULT_USER_AGENT } from './version';\n\nconst DEFAULT_TIMEOUT_MS = 10_000;\nconst DEFAULT_MAX_ATTEMPTS = 3;\nconst DEFAULT_INITIAL_DELAY_MS = 1000;\nconst DEFAULT_MAX_DELAY_MS = 60_000;\nconst OBSERVER_TIMEOUT_MS = 250;\n\nexport interface RequestObservation {\n url: string;\n method: HttpMethod;\n status: number;\n resource: string;\n requestId: string;\n body: unknown;\n}\n\nexport type RequestObserver = (\n event: RequestObservation,\n) => void | Promise<void>;\n\nexport interface RequestOptions {\n fetch?: FetchLike;\n observer?: RequestObserver;\n resource: string;\n requestId?: string;\n}\n\nasync function notifyObserver(\n observer: RequestObserver,\n event: RequestObservation,\n): Promise<void> {\n let result: void | Promise<void>;\n try {\n result = observer(event);\n } catch (err) {\n console.warn('[connector-shared] request observer threw:', err);\n return;\n }\n if (!(result instanceof Promise)) {\n return;\n }\n const guarded = result.catch((err) => {\n console.warn('[connector-shared] request observer rejected:', err);\n });\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeout = new Promise<void>((resolve) => {\n timer = setTimeout(resolve, OBSERVER_TIMEOUT_MS);\n });\n try {\n await Promise.race([guarded, timeout]);\n } finally {\n if (timer) {\n clearTimeout(timer);\n }\n }\n}\n\nfunction newRequestId(): string {\n const c = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto;\n if (c?.randomUUID) {\n return c.randomUUID();\n }\n return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;\n}\n\nfunction mergeHeaders(\n defaults: Record<string, string>,\n overrides: Record<string, string> | undefined,\n): Record<string, string> {\n const merged: Record<string, string> = {};\n for (const [k, v] of Object.entries(defaults)) {\n merged[k.toLowerCase()] = v;\n }\n if (overrides) {\n for (const [k, v] of Object.entries(overrides)) {\n merged[k.toLowerCase()] = v;\n }\n }\n return merged;\n}\n\nfunction linkTimeoutSignal(\n parent: AbortSignal | undefined,\n timeoutMs: number,\n): { signal: AbortSignal; cancel: () => void } {\n const controller = new AbortController();\n const onParentAbort = () => {\n controller.abort(parent?.reason);\n };\n if (parent) {\n if (parent.aborted) {\n controller.abort(parent.reason);\n } else {\n parent.addEventListener('abort', onParentAbort, { once: true });\n }\n }\n const timer = setTimeout(() => {\n controller.abort(new Error(`Request timed out after ${timeoutMs}ms`));\n }, timeoutMs);\n return {\n signal: controller.signal,\n cancel: () => {\n clearTimeout(timer);\n if (parent) {\n parent.removeEventListener('abort', onParentAbort);\n }\n },\n };\n}\n\nasync function readBody(res: Response, parseJson: boolean): Promise<unknown> {\n if (res.status === 204 || res.status === 205) {\n return null;\n }\n const contentType = res.headers.get('content-type') ?? '';\n if (parseJson && contentType.includes('application/json')) {\n const text = await res.text();\n if (text.length === 0) {\n return null;\n }\n return JSON.parse(text);\n }\n return res.text();\n}\n\nexport async function request<T = unknown>(\n req: HttpRequest,\n options: RequestOptions,\n): Promise<HttpResponse<T>> {\n const fetchImpl: FetchLike = options.fetch ?? (globalThis.fetch as FetchLike);\n const retry = req.retry ?? {};\n const maxAttempts = retry.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;\n const initialDelayMs = retry.initialDelayMs ?? DEFAULT_INITIAL_DELAY_MS;\n const maxDelayMs = retry.maxDelayMs ?? DEFAULT_MAX_DELAY_MS;\n const retryOn = retry.retryOn ?? defaultRetryOn;\n const timeoutMs = req.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const parseJson = req.parseJson ?? true;\n\n const headers = mergeHeaders(\n {\n 'User-Agent': DEFAULT_USER_AGENT,\n Accept: 'application/json',\n },\n req.headers,\n );\n\n let lastErr: Error | undefined;\n\n for (let attempt = 0; attempt < maxAttempts; attempt++) {\n req.signal?.throwIfAborted();\n\n const { signal, cancel } = linkTimeoutSignal(req.signal, timeoutMs);\n let res: Response;\n try {\n res = await fetchImpl(req.url, {\n method: req.method ?? 'GET',\n headers,\n body: req.body as RequestInit['body'],\n signal,\n });\n } catch (err) {\n cancel();\n if (req.signal?.aborted) {\n throw req.signal.reason ?? err;\n }\n const error = err instanceof Error ? err : new Error(String(err));\n lastErr = error;\n if (attempt < maxAttempts - 1 && retryOn(null, error)) {\n const delay = computeDelay(attempt, initialDelayMs, maxDelayMs);\n await sleep(delay, req.signal);\n continue;\n }\n throw new TransientError(error.message);\n }\n cancel();\n\n const body = await readBody(res, parseJson);\n const httpResponse: HttpResponse<T> = {\n status: res.status,\n headers: res.headers,\n body: body as T,\n };\n if (req.rateLimit) {\n const state = req.rateLimit.parse(res.headers);\n if (state) {\n httpResponse.rateLimitState = state;\n }\n }\n\n if (options.observer) {\n await notifyObserver(options.observer, {\n url: req.url,\n method: req.method ?? 'GET',\n status: res.status,\n resource: options.resource,\n requestId: options.requestId ?? newRequestId(),\n body,\n });\n }\n\n if (res.ok) {\n return httpResponse;\n }\n\n const retryAfter = parseRetryAfter(res.headers.get('retry-after'));\n const message = `HTTP ${res.status} ${res.statusText} for ${req.method ?? 'GET'} ${req.url}`;\n const err = errorForStatus(message, httpResponse, retryAfter);\n\n if (\n attempt < maxAttempts - 1 &&\n retryOn(res.status, err) &&\n !(err instanceof AuthError) &&\n !(err instanceof ClientBugError)\n ) {\n lastErr = err;\n let delay = computeDelay(attempt, initialDelayMs, maxDelayMs);\n if (err instanceof RateLimitError && retryAfter) {\n const wait = retryAfter.getTime() - Date.now();\n if (wait > 0) {\n delay = Math.min(wait, maxDelayMs);\n }\n }\n await sleep(delay, req.signal);\n continue;\n }\n\n throw err;\n }\n\n throw lastErr ?? new UpstreamBugError('Exhausted retry attempts');\n}\n\nfunction computeDelay(\n attempt: number,\n initialDelayMs: number,\n maxDelayMs: number,\n): number {\n const base = initialDelayMs * 2 ** attempt;\n const jitter = base * 0.25 * Math.random();\n return Math.min(base + jitter, maxDelayMs);\n}\n\nexport { HttpClientError };\n","export interface RateLimitState {\n remaining: number;\n resetAt: Date;\n}\n\nexport interface RateLimitPolicy {\n parse(headers: Headers): RateLimitState | null;\n}\n\nexport interface StandardRateLimitPolicyConfig {\n remainingHeader: string;\n resetHeader: string;\n resetUnit: 's' | 'ms';\n resetFallbackMs?: number;\n}\n\nexport function standardRateLimitPolicy(\n config: StandardRateLimitPolicyConfig,\n): RateLimitPolicy {\n const { remainingHeader, resetHeader, resetUnit, resetFallbackMs } = config;\n const multiplier = resetUnit === 's' ? 1000 : 1;\n return {\n parse(h) {\n const remainingRaw = h.get(remainingHeader);\n if (remainingRaw === null || remainingRaw.trim() === '') {\n return null;\n }\n const remaining = Number(remainingRaw);\n if (!Number.isFinite(remaining)) {\n return null;\n }\n const resetRaw = h.get(resetHeader);\n if (resetRaw === null) {\n if (resetFallbackMs === undefined) {\n return null;\n }\n return {\n remaining,\n resetAt: new Date(Date.now() + resetFallbackMs),\n };\n }\n if (resetRaw.trim() === '') {\n return null;\n }\n const reset = Number(resetRaw);\n if (!Number.isFinite(reset) || reset < 0) {\n return null;\n }\n const resetMs = reset * multiplier;\n if (!Number.isFinite(resetMs)) {\n return null;\n }\n return { remaining, resetAt: new Date(resetMs) };\n },\n };\n}\n","export interface SanitizeAllowedUrlOptions {\n url: string | null;\n host: string;\n pathname: string;\n protocol?: 'https:' | 'http:';\n}\n\nexport function sanitizeAllowedUrl(\n options: SanitizeAllowedUrlOptions,\n): string | null {\n const { url, host, pathname, protocol = 'https:' } = options;\n if (url === null) {\n return null;\n }\n try {\n const u = new URL(url);\n if (u.protocol !== protocol || u.host !== host || u.pathname !== pathname) {\n return null;\n }\n return u.toString();\n } catch {\n return null;\n }\n}\n","export type EpochUnit = 'ms' | 's' | 'iso';\n\nexport function parseEpoch(\n value: number | string | null | undefined,\n unit: EpochUnit,\n): number | null {\n if (value === null || value === undefined) {\n return null;\n }\n if (unit === 'iso') {\n if (typeof value !== 'string') {\n return null;\n }\n const ms = new Date(value).getTime();\n return Number.isFinite(ms) ? ms : null;\n }\n if (typeof value === 'string' && value.trim() === '') {\n return null;\n }\n const n = typeof value === 'number' ? value : Number(value);\n if (!Number.isFinite(n)) {\n return null;\n }\n const result = unit === 's' ? n * 1000 : n;\n return Number.isFinite(result) ? result : null;\n}\n","import { request } from './request';\nimport type { HttpRequest } from './types';\n\nexport function parseLinkHeader(header: string | null): Record<string, string> {\n if (!header) {\n return {};\n }\n const result: Record<string, string> = {};\n for (const part of header.split(',')) {\n const match = part.match(/<([^>]+)>\\s*;\\s*rel=\"([^\"]+)\"/);\n if (match) {\n result[match[2]!] = match[1]!;\n }\n }\n return result;\n}\n\nexport async function* paginateLink<T>(\n initial: HttpRequest,\n parse: (body: unknown) => T[],\n options: { resource: string },\n): AsyncIterable<T> {\n let next: string | null = initial.url;\n while (next) {\n const res: Awaited<ReturnType<typeof request>> = await request(\n {\n ...initial,\n url: next,\n },\n { resource: options.resource },\n );\n for (const item of parse(res.body)) {\n yield item;\n }\n const links = parseLinkHeader(res.headers.get('link'));\n next = links['next'] ?? null;\n }\n}\n\nexport async function* paginateCursor<T>(\n initial: HttpRequest,\n parse: (body: unknown) => { items: T[]; nextCursor: string | null },\n buildNext: (req: HttpRequest, cursor: string) => HttpRequest,\n options: { resource: string },\n): AsyncIterable<T> {\n let req: HttpRequest = initial;\n while (true) {\n const res = await request(req, { resource: options.resource });\n const { items, nextCursor } = parse(res.body);\n for (const item of items) {\n yield item;\n }\n if (!nextCursor) {\n return;\n }\n req = buildNext(req, nextCursor);\n }\n}\n\nexport async function* paginatePage<T>(\n initial: HttpRequest,\n parse: (body: unknown) => { items: T[]; hasMore: boolean },\n buildPage: (req: HttpRequest, page: number) => HttpRequest,\n options: { resource: string },\n): AsyncIterable<T> {\n let page = 1;\n while (true) {\n const req = page === 1 ? initial : buildPage(initial, page);\n const res = await request(req, { resource: options.resource });\n const { items, hasMore } = parse(res.body);\n for (const item of items) {\n yield item;\n }\n if (!hasMore || items.length === 0) {\n return;\n }\n page++;\n }\n}\n","export type LogFields = Record<string, unknown>;\n\nexport interface ConnectorLogger {\n info(event: string, fields?: LogFields): void;\n warn(event: string, fields?: LogFields): void;\n}\n\nexport interface ConnectorLoggerOptions {\n scope: string;\n}\n\nconst MAX_VALUE_LEN = 120;\n\nfunction truncate(s: string, max = MAX_VALUE_LEN): string {\n if (s.length <= max) {\n return s;\n }\n return `${s.slice(0, max - 1)}…`;\n}\n\nfunction formatValue(value: unknown): string {\n if (value === null) {\n return 'null';\n }\n if (value === undefined) {\n return '';\n }\n if (typeof value === 'number' || typeof value === 'boolean') {\n return String(value);\n }\n if (typeof value === 'string') {\n const t = truncate(value);\n if (/[\\s\"=]/.test(t)) {\n return JSON.stringify(t);\n }\n return t;\n }\n if (typeof value === 'bigint') {\n return value.toString();\n }\n let json: string | undefined;\n try {\n json = JSON.stringify(value);\n } catch {\n json = undefined;\n }\n return truncate(json ?? String(value));\n}\n\nexport function formatLogFields(fields?: LogFields): string {\n if (!fields) {\n return '';\n }\n const parts: string[] = [];\n for (const [k, v] of Object.entries(fields)) {\n if (v === undefined) {\n continue;\n }\n parts.push(`${k}=${formatValue(v)}`);\n }\n return parts.length > 0 ? ` ${parts.join(' ')}` : '';\n}\n\nexport function formatLogLine(\n scope: string,\n event: string,\n fields?: LogFields,\n): string {\n return `[${scope}] ${event}${formatLogFields(fields)}`;\n}\n\nexport function createDefaultConnectorLogger(\n opts: ConnectorLoggerOptions,\n): ConnectorLogger {\n return {\n info(event, fields) {\n console.info(formatLogLine(opts.scope, event, fields));\n },\n warn(event, fields) {\n console.warn(formatLogLine(opts.scope, event, fields));\n },\n };\n}\n\nconst NOOP_LOGGER: ConnectorLogger = {\n info() {},\n warn() {},\n};\n\nexport function noopConnectorLogger(): ConnectorLogger {\n return NOOP_LOGGER;\n}\n","import {\n type HttpResponse,\n connectorUserAgent,\n parseEpoch,\n sanitizeAllowedUrl,\n standardRateLimitPolicy,\n} from '@rawdash/connector-shared';\nimport {\n BaseConnector,\n type ChunkedSyncCursor,\n type ConnectorContext,\n type ConnectorDoc,\n type CredentialsSchema,\n type Entity,\n type JSONValue,\n type StorageHandle,\n type SyncOptions,\n type SyncResult,\n defineConfigFields,\n defineConnectorDoc,\n defineResources,\n makeChunkedCursorGuard,\n paginateChunked,\n schemasFromResources,\n selectActivePhases,\n} from '@rawdash/core';\nimport { z } from 'zod';\n\n// ---------------------------------------------------------------------------\n// configFields\n// ---------------------------------------------------------------------------\n\nconst metricQuerySchema = z.object({\n name: z\n .string()\n .min(1)\n .regex(/^[a-zA-Z0-9_]+$/, {\n message: 'Metric name must be alphanumeric / underscore',\n }),\n query: z.string().min(1),\n interval: z\n .enum(['5m', '15m', '1h', '1d'])\n .optional()\n .describe('Aggregation interval - defaults to 1h.'),\n});\n\nconst datadogSiteSchema = z\n .string()\n .trim()\n .min(1)\n .toLowerCase()\n .regex(/^(?:[a-z0-9-]+\\.)*(?:datadoghq\\.com|datadoghq\\.eu|ddog-gov\\.com)$/, {\n message:\n 'Site must be a Datadog hostname (e.g. datadoghq.com, datadoghq.eu, us3.datadoghq.com)',\n });\n\nexport const configFields = defineConfigFields(\n z.object({\n apiKey: z.object({ $secret: z.string().min(1) }).meta({\n label: 'API Key',\n description:\n 'Datadog API key. Create at Datadog → Organization Settings → API Keys.',\n placeholder: 'dd_api_key',\n secret: true,\n }),\n appKey: z.object({ $secret: z.string().min(1) }).meta({\n label: 'Application Key',\n description:\n 'Datadog Application key. Create at Datadog → Organization Settings → Application Keys. Used in tandem with the API key to authenticate REST calls.',\n placeholder: 'dd_app_key',\n secret: true,\n }),\n site: datadogSiteSchema.optional().meta({\n label: 'Site',\n description:\n 'Datadog site host (e.g. `datadoghq.com`, `datadoghq.eu`, `us3.datadoghq.com`). Defaults to `datadoghq.com`.',\n placeholder: 'datadoghq.com',\n }),\n metricQueries: z.array(metricQuerySchema).nonempty().optional().meta({\n label: 'Metric queries (optional)',\n description:\n 'User-declared metric timeseries queries. Each entry produces `datadog_metric` samples named `<name>` from the Datadog Metrics Query API.',\n }),\n resources: z\n .array(\n z.enum([\n 'monitors',\n 'monitor_events',\n 'incidents',\n 'slos',\n 'metric_queries',\n ]),\n )\n .nonempty()\n .optional()\n .meta({\n label: 'Resources',\n description:\n \"Which Datadog resources to sync. Omit to sync all of them. 'monitor_events' depends on 'monitors' being fetched - enabling it without 'monitors' still runs the monitors query but skips writing monitor entities.\",\n }),\n metricsLookbackHours: z.number().int().positive().max(168).optional().meta({\n label: 'Metrics lookback (hours)',\n description:\n 'Window of metric samples to pull on each sync, in hours. Defaults to 24.',\n placeholder: '24',\n }),\n }),\n);\n\nexport const doc: ConnectorDoc = defineConnectorDoc({\n displayName: 'Datadog',\n category: 'infrastructure',\n brandColor: '#632CA6',\n tagline:\n 'Sync monitor health, monitor state-change events, incidents, SLOs, and user-declared metric queries from a Datadog org.',\n vendor: {\n name: 'Datadog',\n apiDocs: 'https://docs.datadoghq.com/api/latest/',\n website: 'https://www.datadoghq.com',\n },\n auth: {\n summary:\n 'A Datadog API key and Application key are required, scoped to the org and site you want to read from. Both are stored as secrets.',\n setup: [\n 'Open Datadog → Organization Settings → API Keys and create (or copy) an API key.',\n 'Open Datadog → Organization Settings → Application Keys and create an Application key with read access to monitors, incidents, SLOs, and metrics.',\n 'Store both as secrets and reference them from the connector config as `apiKey: secret(\"DD_API_KEY\")` and `appKey: secret(\"DD_APP_KEY\")`.',\n 'Set `site` to your Datadog site host (e.g. `datadoghq.com`, `datadoghq.eu`, `us3.datadoghq.com`); it defaults to `datadoghq.com`.',\n ],\n },\n rateLimit:\n 'Datadog returns X-RateLimit-Remaining / X-RateLimit-Reset headers (reset in seconds) on the v2 endpoints, wired through the standard rate-limit policy so the host scheduler backs off on near-empty windows.',\n limitations: [\n 'Logs and RUM session data are out of scope (high volume, low dashboard signal).',\n 'Synthetic monitor results are out of scope.',\n 'Monitor entities are not cleared on a full sync - the monitor_events diff depends on the prior status being stored.',\n 'Pagination URLs are pinned to the configured `api.<site>` host.',\n ],\n});\n\nexport type DatadogResource =\n | 'monitors'\n | 'monitor_events'\n | 'incidents'\n | 'slos'\n | 'metric_queries';\n\nexport interface DatadogMetricQuery {\n name: string;\n query: string;\n interval?: '5m' | '15m' | '1h' | '1d';\n}\n\nexport interface DatadogSettings {\n site?: string;\n metricQueries?: readonly DatadogMetricQuery[];\n resources?: readonly DatadogResource[];\n metricsLookbackHours?: number;\n}\n\nconst datadogCredentials = {\n apiKey: {\n description: 'Datadog API key',\n auth: 'required' as const,\n },\n appKey: {\n description: 'Datadog Application key',\n auth: 'required' as const,\n },\n} satisfies CredentialsSchema;\n\ntype DatadogCredentials = typeof datadogCredentials;\n\n// ---------------------------------------------------------------------------\n// Sync phases + cursor\n// ---------------------------------------------------------------------------\n\n// Datadog exposes `X-RateLimit-Remaining` / `X-RateLimit-Reset` on the v2\n// endpoints (Reset is seconds-until). We treat reset as a relative-seconds\n// value; standardRateLimitPolicy with `resetUnit: 's'` and the right header\n// names parses it as the \"remaining\" budget — close enough for the host\n// scheduler to back off on near-empty windows.\nconst datadogRateLimit = standardRateLimitPolicy({\n remainingHeader: 'x-ratelimit-remaining',\n resetHeader: 'x-ratelimit-reset',\n resetUnit: 's',\n});\n\nconst PHASE_ORDER = ['monitors', 'incidents', 'slos', 'metrics'] as const;\n\ntype DatadogPhase = (typeof PHASE_ORDER)[number];\n\ntype DatadogSyncCursor = ChunkedSyncCursor<DatadogPhase, string>;\n\nconst isDatadogSyncCursor = makeChunkedCursorGuard(PHASE_ORDER);\n\n// ---------------------------------------------------------------------------\n// Datadog API types\n// ---------------------------------------------------------------------------\n\ntype DatadogMonitorStatus = 'OK' | 'Alert' | 'Warn' | 'No Data' | 'Ignored';\n\ninterface DatadogMonitor {\n id: number;\n name: string;\n type: string;\n status: DatadogMonitorStatus;\n priority: number | null;\n tags: string[];\n overall_state_modified?: string | null;\n created: string;\n modified: string;\n}\n\ninterface DatadogMonitorSearchResponse {\n monitors: DatadogMonitor[];\n metadata: {\n page: number;\n page_count: number;\n per_page: number;\n total_count: number;\n };\n}\n\ninterface DatadogIncident {\n id: string;\n type: 'incidents';\n attributes: {\n title: string;\n severity?: string | null;\n state?: string | null;\n customer_impact_scope?: string | null;\n created: string;\n modified?: string | null;\n resolved?: string | null;\n };\n}\n\ninterface DatadogIncidentsResponse {\n data: DatadogIncident[];\n meta?: {\n pagination?: {\n next_offset?: number | null;\n offset?: number;\n size?: number;\n };\n };\n}\n\ninterface DatadogSloThreshold {\n timeframe: string;\n target: number;\n warning?: number | null;\n}\n\ninterface DatadogSloStatus {\n sli_value?: number | null;\n indexed_at?: number | null;\n}\n\ninterface DatadogSlo {\n id: string;\n name: string;\n type: string;\n thresholds: DatadogSloThreshold[];\n overall_status?: DatadogSloStatus[] | null;\n created_at?: number | null;\n modified_at?: number | null;\n}\n\ninterface DatadogSlosResponse {\n data: DatadogSlo[];\n}\n\ninterface DatadogTimeseriesResponse {\n data: {\n type: 'timeseries_response';\n attributes: {\n series?: Array<{\n group_tags?: string[];\n query_index?: number;\n unit?: Array<{ name?: string } | null> | null;\n }>;\n times?: number[];\n values?: number[][];\n };\n };\n}\n\ninterface MonitorsBatchItem {\n monitor: DatadogMonitor;\n}\n\ninterface MetricsBatchItem {\n queryName: string;\n query: string;\n response: DatadogTimeseriesResponse;\n}\n\n// ---------------------------------------------------------------------------\n// Schemas — describe the per-resource API response shape consumed by request()\n// ---------------------------------------------------------------------------\n\nconst idString = z.string().min(1);\n\nconst monitorSchema = z.object({\n id: z.number().int().nonnegative(),\n name: z.string(),\n type: z.string(),\n status: z.enum(['OK', 'Alert', 'Warn', 'No Data', 'Ignored']),\n priority: z.number().int().nullable(),\n tags: z.array(z.string()),\n overall_state_modified: z.iso.datetime().nullable().optional(),\n created: z.iso.datetime(),\n modified: z.iso.datetime(),\n});\n\nconst monitorSearchResponseSchema = z.object({\n monitors: z.array(monitorSchema),\n metadata: z.object({\n page: z.number().int().nonnegative(),\n page_count: z.number().int().nonnegative(),\n per_page: z.number().int().positive(),\n total_count: z.number().int().nonnegative(),\n }),\n});\n\nconst incidentSchema = z.object({\n id: idString,\n type: z.literal('incidents'),\n attributes: z.object({\n title: z.string(),\n severity: z.string().nullable().optional(),\n state: z.string().nullable().optional(),\n customer_impact_scope: z.string().nullable().optional(),\n created: z.iso.datetime(),\n modified: z.iso.datetime().nullable().optional(),\n resolved: z.iso.datetime().nullable().optional(),\n }),\n});\n\nconst incidentsResponseSchema = z.object({\n data: z.array(incidentSchema),\n meta: z\n .object({\n pagination: z\n .object({\n next_offset: z.number().int().nullable().optional(),\n offset: z.number().int().optional(),\n size: z.number().int().optional(),\n })\n .optional(),\n })\n .optional(),\n});\n\nconst sloSchema = z.object({\n id: idString,\n name: z.string(),\n type: z.string(),\n thresholds: z.array(\n z.object({\n timeframe: z.string(),\n target: z.number(),\n warning: z.number().nullable().optional(),\n }),\n ),\n overall_status: z\n .array(\n z.object({\n sli_value: z.number().nullable().optional(),\n indexed_at: z.number().nullable().optional(),\n }),\n )\n .nullable()\n .optional(),\n created_at: z.number().nullable().optional(),\n modified_at: z.number().nullable().optional(),\n});\n\nconst slosResponseSchema = z.object({\n data: z.array(sloSchema),\n});\n\nconst timeseriesResponseSchema = z.object({\n data: z.object({\n type: z.literal('timeseries_response'),\n attributes: z.object({\n series: z\n .array(\n z.object({\n group_tags: z.array(z.string()).optional(),\n query_index: z.number().int().optional(),\n }),\n )\n .optional(),\n times: z.array(z.number()).optional(),\n values: z.array(z.array(z.number())).optional(),\n }),\n }),\n});\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\nconst DEFAULT_SITE = 'datadoghq.com';\nconst MONITORS_PAGE_SIZE = 100;\nconst INCIDENTS_PAGE_SIZE = 50;\nconst DEFAULT_METRICS_LOOKBACK_HOURS = 24;\nconst INTERVAL_MS: Record<\n NonNullable<DatadogMetricQuery['interval']>,\n number\n> = {\n '5m': 5 * 60 * 1000,\n '15m': 15 * 60 * 1000,\n '1h': 60 * 60 * 1000,\n '1d': 24 * 60 * 60 * 1000,\n};\nconst DEFAULT_INTERVAL_MS = INTERVAL_MS['1h'];\n\n// ---------------------------------------------------------------------------\n// Resource definitions\n// ---------------------------------------------------------------------------\n\nconst datadogResources = defineResources({\n datadog_monitor: {\n shape: 'entity',\n description:\n 'Datadog monitors with name, type, current status (OK / Alert / Warn / No Data), priority, and tags.',\n endpoint: 'GET /api/v1/monitor/search',\n responses: { monitors: monitorSearchResponseSchema },\n },\n datadog_monitor_event: {\n shape: 'event',\n description:\n \"Monitor state-transition events, emitted whenever a monitor's status changes from its previously-stored value.\",\n notes:\n \"Derived by diffing each monitor's current status against the last-synced status, so it depends on the monitors phase running and on prior monitor state being stored.\",\n },\n datadog_incident: {\n shape: 'entity',\n description:\n 'Datadog incidents with title, severity, state, and created / resolved timestamps.',\n endpoint: 'GET /api/v2/incidents',\n responses: { incidents: incidentsResponseSchema },\n },\n datadog_slo: {\n shape: 'entity',\n description:\n 'Service Level Objectives with type, thresholds, primary target, and latest SLI value.',\n endpoint: 'GET /api/v1/slo',\n responses: { slos: slosResponseSchema },\n },\n datadog_slo_sli: {\n shape: 'metric',\n description:\n 'SLI value samples per SLO, one per overall_status snapshot reported by Datadog.',\n unit: 'percent',\n dimensions: [\n { name: 'sloId', description: 'Datadog SLO id.' },\n { name: 'sloType', description: 'SLO type (metric, monitor, etc.).' },\n ],\n },\n datadog_metric: {\n shape: 'metric',\n dynamic: true,\n description:\n 'User-declared metric timeseries samples, stored as `datadog_metric.<query name>`, from the Datadog Metrics Query API.',\n endpoint: 'POST /api/v2/query/timeseries',\n dimensions: [\n { name: 'queryName', description: 'The user-declared query name.' },\n { name: 'query', description: 'The Datadog metrics query string.' },\n {\n name: 'tags',\n description:\n 'Comma-joined group tags for the series, or `*` when the series is ungrouped.',\n },\n ],\n responses: { metric_queries: timeseriesResponseSchema },\n },\n});\n\n// ---------------------------------------------------------------------------\n// DatadogConnector\n// ---------------------------------------------------------------------------\n\nexport class DatadogConnector extends BaseConnector<\n DatadogSettings,\n DatadogCredentials\n> {\n static readonly id = 'datadog';\n\n static readonly resources = datadogResources;\n\n static readonly schemas = schemasFromResources(datadogResources);\n\n static create(input: unknown, ctx?: ConnectorContext): DatadogConnector {\n const parsed = configFields.parse(input);\n return new DatadogConnector(\n {\n site: parsed.site,\n metricQueries: parsed.metricQueries,\n resources: parsed.resources,\n metricsLookbackHours: parsed.metricsLookbackHours,\n },\n { apiKey: parsed.apiKey, appKey: parsed.appKey },\n ctx,\n );\n }\n\n readonly id = 'datadog';\n override readonly credentials = datadogCredentials;\n\n private get apiHost(): string {\n return `api.${(this.settings.site ?? DEFAULT_SITE).toLowerCase()}`;\n }\n\n private get apiBase(): string {\n return `https://${this.apiHost}`;\n }\n\n private buildHeaders(): Record<string, string> {\n return {\n 'DD-API-KEY': this.creds.apiKey,\n 'DD-APPLICATION-KEY': this.creds.appKey,\n 'User-Agent': connectorUserAgent('datadog'),\n };\n }\n\n private fetch<T>(\n url: string,\n resource: string,\n signal?: AbortSignal,\n ): Promise<HttpResponse<T>> {\n return this.get<T>(url, {\n resource,\n headers: this.buildHeaders(),\n signal,\n rateLimit: datadogRateLimit,\n });\n }\n\n private postJson<T>(\n url: string,\n body: unknown,\n resource: string,\n signal?: AbortSignal,\n ): Promise<HttpResponse<T>> {\n return this.post<T>(url, {\n resource,\n headers: {\n ...this.buildHeaders(),\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(body),\n signal,\n rateLimit: datadogRateLimit,\n });\n }\n\n // -------------------------------------------------------------------------\n // Resource enablement\n // -------------------------------------------------------------------------\n\n private activePhases(): DatadogPhase[] {\n return selectActivePhases<DatadogResource, DatadogPhase>(\n (r) => {\n switch (r) {\n case 'monitors':\n case 'monitor_events':\n return 'monitors';\n case 'incidents':\n return 'incidents';\n case 'slos':\n return 'slos';\n case 'metric_queries':\n return 'metrics';\n }\n },\n PHASE_ORDER,\n this.settings.resources,\n );\n }\n\n // -------------------------------------------------------------------------\n // URL building + sanitization\n // -------------------------------------------------------------------------\n\n private allowedPagePath(phase: DatadogPhase): string {\n switch (phase) {\n case 'monitors':\n return '/api/v1/monitor/search';\n case 'incidents':\n return '/api/v2/incidents';\n case 'slos':\n return '/api/v1/slo';\n case 'metrics':\n return '/api/v2/query/timeseries';\n }\n }\n\n private sanitizePageUrl(\n phase: DatadogPhase,\n pageUrl: string | null,\n ): string | null {\n return sanitizeAllowedUrl({\n url: pageUrl,\n host: this.apiHost,\n pathname: this.allowedPagePath(phase),\n });\n }\n\n private resolveCursor(cursor: unknown): DatadogSyncCursor | undefined {\n if (!isDatadogSyncCursor(cursor)) {\n return undefined;\n }\n return {\n phase: cursor.phase,\n page: this.sanitizePageUrl(cursor.phase, cursor.page),\n };\n }\n\n private buildInitialMonitorsUrl(): string {\n const u = new URL(`${this.apiBase}/api/v1/monitor/search`);\n u.searchParams.set('per_page', String(MONITORS_PAGE_SIZE));\n u.searchParams.set('page', '0');\n u.searchParams.set('sort', 'status,desc');\n return u.toString();\n }\n\n private buildNextMonitorsUrl(currentUrl: string, nextPage: number): string {\n const u = new URL(currentUrl);\n u.searchParams.set('page', String(nextPage));\n return u.toString();\n }\n\n private buildInitialIncidentsUrl(options: SyncOptions): string {\n const u = new URL(`${this.apiBase}/api/v2/incidents`);\n u.searchParams.set('page[size]', String(INCIDENTS_PAGE_SIZE));\n u.searchParams.set('page[offset]', '0');\n u.searchParams.set('include', '');\n if (options.since) {\n u.searchParams.set('filter[created.from]', options.since);\n }\n return u.toString();\n }\n\n private buildNextIncidentsUrl(\n currentUrl: string,\n nextOffset: number,\n ): string {\n const u = new URL(currentUrl);\n u.searchParams.set('page[offset]', String(nextOffset));\n return u.toString();\n }\n\n private buildSlosUrl(): string {\n const u = new URL(`${this.apiBase}/api/v1/slo`);\n u.searchParams.set('limit', '1000');\n u.searchParams.set('offset', '0');\n return u.toString();\n }\n\n private buildMetricsUrl(): string {\n return `${this.apiBase}/api/v2/query/timeseries`;\n }\n\n // -------------------------------------------------------------------------\n // Fetchers\n // -------------------------------------------------------------------------\n\n private async fetchMonitorsPage(\n page: string | null,\n signal: AbortSignal | undefined,\n ): Promise<{ items: MonitorsBatchItem[]; next: string | null }> {\n const url = page ?? this.buildInitialMonitorsUrl();\n const res = await this.fetch<DatadogMonitorSearchResponse>(\n url,\n 'monitors',\n signal,\n );\n const meta = res.body.metadata;\n const currentPage = meta.page;\n const totalPages = meta.page_count;\n const hasNext = currentPage + 1 < totalPages;\n const next = hasNext\n ? this.sanitizePageUrl(\n 'monitors',\n this.buildNextMonitorsUrl(url, currentPage + 1),\n )\n : null;\n return {\n items: res.body.monitors.map((m) => ({ monitor: m })),\n next,\n };\n }\n\n private async fetchIncidentsPage(\n page: string | null,\n options: SyncOptions,\n signal: AbortSignal | undefined,\n ): Promise<{ items: DatadogIncident[]; next: string | null }> {\n const url = page ?? this.buildInitialIncidentsUrl(options);\n const res = await this.fetch<DatadogIncidentsResponse>(\n url,\n 'incidents',\n signal,\n );\n const nextOffset = res.body.meta?.pagination?.next_offset ?? null;\n const incidents = res.body.data;\n const cutoff = options.since\n ? (parseEpoch(options.since, 'iso') ?? null)\n : null;\n const filtered =\n cutoff !== null\n ? incidents.filter((inc) => {\n const ts = parseEpoch(inc.attributes.created, 'iso');\n return ts === null || ts >= cutoff;\n })\n : incidents;\n const lastIncident = incidents.at(-1);\n const lastTs = lastIncident\n ? parseEpoch(lastIncident.attributes.created, 'iso')\n : null;\n const cutoffReached = cutoff !== null && lastTs !== null && lastTs < cutoff;\n const next =\n !cutoffReached && nextOffset !== null\n ? this.sanitizePageUrl(\n 'incidents',\n this.buildNextIncidentsUrl(url, nextOffset),\n )\n : null;\n return { items: filtered, next };\n }\n\n private async fetchSlos(\n signal: AbortSignal | undefined,\n ): Promise<{ items: DatadogSlo[]; next: string | null }> {\n const res = await this.fetch<DatadogSlosResponse>(\n this.buildSlosUrl(),\n 'slos',\n signal,\n );\n return { items: res.body.data, next: null };\n }\n\n private async fetchMetrics(\n options: SyncOptions,\n signal: AbortSignal | undefined,\n ): Promise<{ items: MetricsBatchItem[]; next: string | null }> {\n const queries = this.settings.metricQueries ?? [];\n if (queries.length === 0) {\n return { items: [], next: null };\n }\n const lookbackHours =\n this.settings.metricsLookbackHours ?? DEFAULT_METRICS_LOOKBACK_HOURS;\n const now = Date.now();\n const sinceMs = options.since ? parseEpoch(options.since, 'iso') : null;\n const fromMs =\n sinceMs !== null ? sinceMs : now - lookbackHours * 60 * 60 * 1000;\n const items: MetricsBatchItem[] = [];\n for (const q of queries) {\n signal?.throwIfAborted();\n const intervalMs = q.interval\n ? INTERVAL_MS[q.interval]\n : DEFAULT_INTERVAL_MS;\n const body = {\n data: {\n type: 'timeseries_request',\n attributes: {\n from: fromMs,\n to: now,\n interval: intervalMs,\n queries: [\n {\n name: 'a',\n data_source: 'metrics',\n query: q.query,\n },\n ],\n formulas: [{ formula: 'a' }],\n },\n },\n };\n const res = await this.postJson<DatadogTimeseriesResponse>(\n this.buildMetricsUrl(),\n body,\n 'metric_queries',\n signal,\n );\n items.push({\n queryName: q.name,\n query: q.query,\n response: res.body,\n });\n }\n return { items, next: null };\n }\n\n // -------------------------------------------------------------------------\n // Writers\n // -------------------------------------------------------------------------\n\n private async writeMonitorsBatch(\n storage: StorageHandle,\n items: MonitorsBatchItem[],\n ): Promise<void> {\n const writeEntities = this.isResourceEnabled('monitors');\n const writeEvents = this.isResourceEnabled('monitor_events');\n\n for (const item of items) {\n const m = item.monitor;\n const createdMs = parseEpoch(m.created, 'iso');\n const modifiedMs = parseEpoch(m.modified, 'iso');\n const stateModifiedMs =\n m.overall_state_modified !== undefined &&\n m.overall_state_modified !== null\n ? parseEpoch(m.overall_state_modified, 'iso')\n : null;\n if (createdMs === null || modifiedMs === null) {\n console.warn(\n `[connector-datadog] skipping monitor ${m.id} with unparseable created/modified timestamps`,\n );\n continue;\n }\n const updatedMs = Math.max(modifiedMs, stateModifiedMs ?? 0);\n\n const attributes: Record<string, JSONValue> = {\n monitorId: m.id,\n name: m.name,\n monitorType: m.type,\n status: m.status,\n priority: m.priority,\n tags: m.tags,\n createdAt: createdMs,\n modifiedAt: modifiedMs,\n stateModifiedAt: stateModifiedMs,\n };\n\n if (writeEvents) {\n const prior = await storage.getEntity('datadog_monitor', String(m.id));\n const priorStatus =\n prior !== null &&\n typeof prior.attributes === 'object' &&\n prior.attributes !== null\n ? (prior.attributes as { status?: string }).status\n : undefined;\n if (\n priorStatus !== m.status &&\n stateModifiedMs !== null &&\n Number.isFinite(stateModifiedMs)\n ) {\n await storage.event({\n name: 'datadog_monitor_event',\n start_ts: stateModifiedMs,\n end_ts: null,\n attributes: {\n monitorId: m.id,\n name: m.name,\n monitorType: m.type,\n fromStatus: priorStatus ?? null,\n toStatus: m.status,\n priority: m.priority,\n tags: m.tags,\n },\n });\n }\n }\n\n if (writeEntities) {\n await storage.entity({\n type: 'datadog_monitor',\n id: String(m.id),\n attributes,\n updated_at: updatedMs,\n });\n } else if (writeEvents) {\n // We still upsert to keep the comparison baseline fresh even when the\n // host hasn't asked for the monitor entity itself — the next sync's\n // monitor_event diff depends on a stored prior state.\n await storage.entity({\n type: 'datadog_monitor',\n id: String(m.id),\n attributes,\n updated_at: updatedMs,\n });\n }\n }\n }\n\n private async writeIncidents(\n storage: StorageHandle,\n incidents: DatadogIncident[],\n ): Promise<void> {\n for (const inc of incidents) {\n const createdMs = parseEpoch(inc.attributes.created, 'iso');\n if (createdMs === null) {\n console.warn(\n `[connector-datadog] skipping incident ${inc.id} with unparseable created timestamp`,\n );\n continue;\n }\n const modifiedMs = inc.attributes.modified\n ? parseEpoch(inc.attributes.modified, 'iso')\n : null;\n const resolvedMs = inc.attributes.resolved\n ? parseEpoch(inc.attributes.resolved, 'iso')\n : null;\n await storage.entity({\n type: 'datadog_incident',\n id: inc.id,\n attributes: {\n incidentId: inc.id,\n title: inc.attributes.title,\n severity: inc.attributes.severity ?? null,\n state: inc.attributes.state ?? null,\n customerImpactScope: inc.attributes.customer_impact_scope ?? null,\n createdAt: createdMs,\n modifiedAt: modifiedMs,\n resolvedAt: resolvedMs,\n },\n updated_at: Math.max(createdMs, modifiedMs ?? 0, resolvedMs ?? 0),\n });\n }\n }\n\n private async writeSlos(\n storage: StorageHandle,\n slos: DatadogSlo[],\n ): Promise<void> {\n const sliSamples: Array<{\n name: string;\n ts: number;\n value: number;\n attributes: Record<string, string | number>;\n }> = [];\n const entities: Entity[] = [];\n for (const s of slos) {\n const createdMs =\n s.created_at !== null && s.created_at !== undefined\n ? parseEpoch(s.created_at, 's')\n : null;\n const modifiedMs =\n s.modified_at !== null && s.modified_at !== undefined\n ? parseEpoch(s.modified_at, 's')\n : null;\n const targets = s.thresholds.map((t) => ({\n timeframe: t.timeframe,\n target: t.target,\n }));\n const primaryTarget = s.thresholds[0]?.target ?? null;\n const latestStatus = (s.overall_status ?? []).find(\n (st) => st.sli_value !== null && st.sli_value !== undefined,\n );\n const latestSli = latestStatus?.sli_value ?? null;\n entities.push({\n type: 'datadog_slo',\n id: s.id,\n attributes: {\n sloId: s.id,\n name: s.name,\n sloType: s.type,\n thresholds: targets as unknown as JSONValue,\n target: primaryTarget,\n latestSliValue: latestSli,\n createdAt: createdMs,\n modifiedAt: modifiedMs,\n },\n updated_at: modifiedMs ?? createdMs ?? Date.now(),\n });\n\n for (const status of s.overall_status ?? []) {\n const ts =\n status.indexed_at !== null && status.indexed_at !== undefined\n ? parseEpoch(status.indexed_at, 's')\n : null;\n const value = status.sli_value;\n if (\n ts === null ||\n value === null ||\n value === undefined ||\n !Number.isFinite(value)\n ) {\n continue;\n }\n sliSamples.push({\n name: 'datadog_slo_sli',\n ts,\n value,\n attributes: { sloId: s.id, sloType: s.type },\n });\n }\n }\n for (const entity of entities) {\n await storage.entity(entity);\n }\n if (sliSamples.length > 0) {\n await storage.metrics(sliSamples, { names: ['datadog_slo_sli'] });\n }\n }\n\n private async writeMetrics(\n storage: StorageHandle,\n items: MetricsBatchItem[],\n ): Promise<void> {\n if (items.length === 0) {\n return;\n }\n const samplesByName: Map<\n string,\n Array<{\n name: string;\n ts: number;\n value: number;\n attributes: Record<string, string | number>;\n }>\n > = new Map();\n for (const item of items) {\n const attrs = item.response.data.attributes;\n const times = attrs.times ?? [];\n const series = attrs.series ?? [];\n const values = attrs.values ?? [];\n for (let s = 0; s < series.length; s++) {\n const seriesValues = values[s];\n if (!seriesValues) {\n continue;\n }\n const tagsArr = series[s]?.group_tags ?? [];\n const tagsStr = tagsArr.length > 0 ? tagsArr.join(',') : '*';\n for (let t = 0; t < times.length; t++) {\n const rawTs = times[t];\n const rawValue = seriesValues[t];\n if (rawTs === undefined || rawValue === undefined) {\n continue;\n }\n const ts = parseEpoch(rawTs, 'ms');\n if (ts === null || !Number.isFinite(rawValue)) {\n continue;\n }\n const name = `datadog_metric.${item.queryName}`;\n let bucket = samplesByName.get(name);\n if (!bucket) {\n bucket = [];\n samplesByName.set(name, bucket);\n }\n bucket.push({\n name,\n ts,\n value: rawValue,\n attributes: {\n queryName: item.queryName,\n query: item.query,\n tags: tagsStr,\n },\n });\n }\n }\n }\n for (const [name, samples] of samplesByName) {\n await storage.metrics(samples, { names: [name] });\n }\n }\n\n // -------------------------------------------------------------------------\n // sync\n // -------------------------------------------------------------------------\n\n async sync(\n options: SyncOptions,\n storage: StorageHandle,\n signal?: AbortSignal,\n ): Promise<SyncResult> {\n const cursor = this.resolveCursor(options.cursor);\n const isFull = options.mode === 'full';\n const phases = this.activePhases();\n\n return paginateChunked<DatadogPhase, string>({\n phases,\n cursor,\n signal,\n logger: this.logger,\n fetchPage: async (phase, page, sig) => {\n switch (phase) {\n case 'monitors':\n return this.fetchMonitorsPage(page, sig);\n case 'incidents':\n return this.fetchIncidentsPage(page, options, sig);\n case 'slos':\n return this.fetchSlos(sig);\n case 'metrics':\n return this.fetchMetrics(options, sig);\n }\n },\n writeBatch: async (phase, items, page) => {\n if (isFull && page === null) {\n switch (phase) {\n case 'monitors':\n if (this.isResourceEnabled('monitor_events')) {\n await storage.events([], { names: ['datadog_monitor_event'] });\n }\n // Monitor entities are intentionally NOT cleared on a full\n // sync — `writeMonitorsBatch` reads the prior status off the\n // existing entity to derive monitor_events. Wiping it here\n // would forget every state we'd seen on the previous run.\n break;\n case 'incidents':\n await storage.entities([], { types: ['datadog_incident'] });\n break;\n case 'slos':\n await storage.entities([], { types: ['datadog_slo'] });\n await storage.metrics([], { names: ['datadog_slo_sli'] });\n break;\n case 'metrics':\n for (const q of this.settings.metricQueries ?? []) {\n await storage.metrics([], {\n names: [`datadog_metric.${q.name}`],\n });\n }\n break;\n }\n }\n switch (phase) {\n case 'monitors':\n return this.writeMonitorsBatch(\n storage,\n items as MonitorsBatchItem[],\n );\n case 'incidents':\n return this.writeIncidents(storage, items as DatadogIncident[]);\n case 'slos':\n return this.writeSlos(storage, items as DatadogSlo[]);\n case 'metrics':\n return this.writeMetrics(storage, items as MetricsBatchItem[]);\n }\n },\n });\n }\n}\n","import { DatadogConnector } from './datadog';\n\nexport { configFields, doc, DatadogConnector } from './datadog';\nexport type { DatadogResource, DatadogSettings } from './datadog';\nexport default DatadogConnector;\n"],"mappings":";AEAO,IAAM,sBAAsB;AAE5B,IAAM,qBAAqB,qBAAqB,mBAAmB;AAEnE,SAAS,mBAAmB,aAA6B;AAC9D,SAAO,qBAAqB,WAAW,IAAI,mBAAmB;AAChE;AEUO,SAAS,wBACd,QACiB;AACjB,QAAM,EAAE,iBAAiB,aAAa,WAAW,gBAAgB,IAAI;AACrE,QAAM,aAAa,cAAc,MAAM,MAAO;AAC9C,SAAO;IACL,MAAM,GAAG;AACP,YAAM,eAAe,EAAE,IAAI,eAAe;AAC1C,UAAI,iBAAiB,QAAQ,aAAa,KAAK,MAAM,IAAI;AACvD,eA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;AAAA,YACF,KAAK;AACH,oBAAM,QAAQ,SAAS,CAAC,GAAG,EAAE,OAAO,CAAC,aAAa,EAAE,CAAC;AACrD,oBAAM,QAAQ,QAAQ,CAAC,GAAG,EAAE,OAAO,CAAC,iBAAiB,EAAE,CAAC;AACxD;AAAA,YACF,KAAK;AACH,yBAAW,KAAK,KAAK,SAAS,iBAAiB,CAAC,GAAG;AACjD,sBAAM,QAAQ,QAAQ,CAAC,GAAG;AAAA,kBACxB,OAAO,CAAC,kBAAkB,EAAE,IAAI,EAAE;AAAA,gBACpC,CAAC;AAAA,cACH;AACA;AAAA,UACJ;AAAA,QACF;AACA,gBAAQ,OAAO;AAAA,UACb,KAAK;AACH,mBAAO,KAAK;AAAA,cACV;AAAA,cACA;AAAA,YACF;AAAA,UACF,KAAK;AACH,mBAAO,KAAK,eAAe,SAAS,KAA0B;AAAA,UAChE,KAAK;AACH,mBAAO,KAAK,UAAU,SAAS,KAAqB;AAAA,UACtD,KAAK;AACH,mBAAO,KAAK,aAAa,SAAS,KAA2B;AAAA,QACjE;AAAA,MACF;AAAA,IACF,CAAC;AAAA,EACH;AACF;;;AC9mCA,IAAO,gBAAQ;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../../connector-shared/src/errors.ts","../../../connector-shared/src/retry.ts","../../../connector-shared/src/version.ts","../../../connector-shared/src/request.ts","../../../connector-shared/src/rate-limit.ts","../../../connector-shared/src/sanitize.ts","../../../connector-shared/src/epoch.ts","../../../connector-shared/src/pagination.ts","../../../connector-shared/src/logger.ts","../src/datadog.ts","../src/index.ts"],"sourcesContent":["import type { HttpResponse } from './types';\n\nexport type HttpErrorKind =\n | 'transient'\n | 'rate_limit'\n | 'auth'\n | 'upstream_bug'\n | 'client_bug';\n\nexport abstract class HttpClientError extends Error {\n abstract readonly kind: HttpErrorKind;\n readonly response?: HttpResponse;\n\n constructor(message: string, response?: HttpResponse) {\n super(message);\n this.name = new.target.name;\n this.response = response;\n }\n}\n\nexport class TransientError extends HttpClientError {\n readonly kind = 'transient' as const;\n}\n\nexport class RateLimitError extends HttpClientError {\n readonly kind = 'rate_limit' as const;\n readonly retryAfter?: Date;\n\n constructor(message: string, response?: HttpResponse, retryAfter?: Date) {\n super(message, response);\n this.retryAfter = retryAfter;\n }\n}\n\nexport class AuthError extends HttpClientError {\n readonly kind = 'auth' as const;\n}\n\nexport class UpstreamBugError extends HttpClientError {\n readonly kind = 'upstream_bug' as const;\n}\n\nexport class ClientBugError extends HttpClientError {\n readonly kind = 'client_bug' as const;\n}\n\nexport function classifyStatus(status: number): HttpErrorKind {\n if (status === 429) {\n return 'rate_limit';\n }\n if (status === 401 || status === 403) {\n return 'auth';\n }\n if (status === 408) {\n return 'transient';\n }\n if (status >= 500) {\n return 'upstream_bug';\n }\n if (status >= 400) {\n return 'client_bug';\n }\n return 'client_bug';\n}\n\nexport function errorForStatus(\n message: string,\n response: HttpResponse,\n retryAfter?: Date,\n): HttpClientError {\n const kind = classifyStatus(response.status);\n switch (kind) {\n case 'rate_limit':\n return new RateLimitError(message, response, retryAfter);\n case 'auth':\n return new AuthError(message, response);\n case 'transient':\n return new TransientError(message, response);\n case 'upstream_bug':\n return new UpstreamBugError(message, response);\n case 'client_bug':\n return new ClientBugError(message, response);\n }\n}\n","import { HttpClientError, RateLimitError, TransientError } from './errors';\n\nexport interface RetryPolicy {\n maxAttempts?: number;\n initialDelayMs?: number;\n maxDelayMs?: number;\n retryOn?: (status: number | null, err?: Error) => boolean;\n}\n\nexport const defaultRetryOn = (status: number | null, err?: Error): boolean => {\n if (err instanceof RateLimitError) {\n return true;\n }\n if (err instanceof TransientError) {\n return true;\n }\n if (status === null) {\n return err instanceof Error && !(err instanceof HttpClientError);\n }\n if (status === 408 || status === 429) {\n return true;\n }\n if (status >= 500) {\n return true;\n }\n return false;\n};\n\nexport function backoffDelayMs(\n attempt: number,\n policy: Required<Pick<RetryPolicy, 'initialDelayMs' | 'maxDelayMs'>>,\n): number {\n const base = policy.initialDelayMs * 2 ** attempt;\n const jitter = base * 0.25 * Math.random();\n return Math.min(base + jitter, policy.maxDelayMs);\n}\n\nexport function parseRetryAfter(\n headerValue: string | null,\n now: Date = new Date(),\n): Date | undefined {\n if (!headerValue) {\n return undefined;\n }\n const trimmed = headerValue.trim();\n if (/^\\d+$/.test(trimmed)) {\n return new Date(now.getTime() + Number(trimmed) * 1000);\n }\n const parsed = Date.parse(trimmed);\n if (Number.isNaN(parsed)) {\n return undefined;\n }\n return new Date(parsed);\n}\n\nexport function sleep(ms: number, signal?: AbortSignal): Promise<void> {\n if (signal?.aborted) {\n return Promise.reject(signal.reason ?? new Error('Aborted'));\n }\n return new Promise<void>((resolve, reject) => {\n const onAbort = () => {\n clearTimeout(timer);\n reject(signal!.reason ?? new Error('Aborted'));\n };\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n}\n","export const HTTP_CLIENT_VERSION = '0.0.0';\n\nexport const DEFAULT_USER_AGENT = `rawdash-connector/${HTTP_CLIENT_VERSION} (+https://rawdash.dev)`;\n\nexport function connectorUserAgent(connectorId: string): string {\n return `rawdash-connector-${connectorId}/${HTTP_CLIENT_VERSION} (+https://rawdash.dev)`;\n}\n","import {\n AuthError,\n ClientBugError,\n HttpClientError,\n RateLimitError,\n TransientError,\n UpstreamBugError,\n errorForStatus,\n} from './errors';\nimport { defaultRetryOn, parseRetryAfter, sleep } from './retry';\nimport type { FetchLike, HttpMethod, HttpRequest, HttpResponse } from './types';\nimport { DEFAULT_USER_AGENT } from './version';\n\nconst DEFAULT_TIMEOUT_MS = 10_000;\nconst DEFAULT_MAX_ATTEMPTS = 3;\nconst DEFAULT_INITIAL_DELAY_MS = 1000;\nconst DEFAULT_MAX_DELAY_MS = 60_000;\nconst OBSERVER_TIMEOUT_MS = 250;\n\nexport interface RequestObservation {\n url: string;\n method: HttpMethod;\n status: number;\n resource: string;\n requestId: string;\n body: unknown;\n}\n\nexport type RequestObserver = (\n event: RequestObservation,\n) => void | Promise<void>;\n\nexport interface RequestOptions {\n fetch?: FetchLike;\n observer?: RequestObserver;\n resource: string;\n requestId?: string;\n}\n\nasync function notifyObserver(\n observer: RequestObserver,\n event: RequestObservation,\n): Promise<void> {\n let result: void | Promise<void>;\n try {\n result = observer(event);\n } catch (err) {\n console.warn('[connector-shared] request observer threw:', err);\n return;\n }\n if (!(result instanceof Promise)) {\n return;\n }\n const guarded = result.catch((err) => {\n console.warn('[connector-shared] request observer rejected:', err);\n });\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeout = new Promise<void>((resolve) => {\n timer = setTimeout(resolve, OBSERVER_TIMEOUT_MS);\n });\n try {\n await Promise.race([guarded, timeout]);\n } finally {\n if (timer) {\n clearTimeout(timer);\n }\n }\n}\n\nfunction newRequestId(): string {\n const c = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto;\n if (c?.randomUUID) {\n return c.randomUUID();\n }\n return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;\n}\n\nfunction mergeHeaders(\n defaults: Record<string, string>,\n overrides: Record<string, string> | undefined,\n): Record<string, string> {\n const merged: Record<string, string> = {};\n for (const [k, v] of Object.entries(defaults)) {\n merged[k.toLowerCase()] = v;\n }\n if (overrides) {\n for (const [k, v] of Object.entries(overrides)) {\n merged[k.toLowerCase()] = v;\n }\n }\n return merged;\n}\n\nfunction linkTimeoutSignal(\n parent: AbortSignal | undefined,\n timeoutMs: number,\n): { signal: AbortSignal; cancel: () => void } {\n const controller = new AbortController();\n const onParentAbort = () => {\n controller.abort(parent?.reason);\n };\n if (parent) {\n if (parent.aborted) {\n controller.abort(parent.reason);\n } else {\n parent.addEventListener('abort', onParentAbort, { once: true });\n }\n }\n const timer = setTimeout(() => {\n controller.abort(new Error(`Request timed out after ${timeoutMs}ms`));\n }, timeoutMs);\n return {\n signal: controller.signal,\n cancel: () => {\n clearTimeout(timer);\n if (parent) {\n parent.removeEventListener('abort', onParentAbort);\n }\n },\n };\n}\n\nasync function readBody(res: Response, parseJson: boolean): Promise<unknown> {\n if (res.status === 204 || res.status === 205) {\n return null;\n }\n const contentType = res.headers.get('content-type') ?? '';\n if (parseJson && contentType.includes('application/json')) {\n const text = await res.text();\n if (text.length === 0) {\n return null;\n }\n return JSON.parse(text);\n }\n return res.text();\n}\n\nexport async function request<T = unknown>(\n req: HttpRequest,\n options: RequestOptions,\n): Promise<HttpResponse<T>> {\n const fetchImpl: FetchLike = options.fetch ?? (globalThis.fetch as FetchLike);\n const retry = req.retry ?? {};\n const maxAttempts = retry.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;\n const initialDelayMs = retry.initialDelayMs ?? DEFAULT_INITIAL_DELAY_MS;\n const maxDelayMs = retry.maxDelayMs ?? DEFAULT_MAX_DELAY_MS;\n const retryOn = retry.retryOn ?? defaultRetryOn;\n const timeoutMs = req.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const parseJson = req.parseJson ?? true;\n\n const headers = mergeHeaders(\n {\n 'User-Agent': DEFAULT_USER_AGENT,\n Accept: 'application/json',\n },\n req.headers,\n );\n\n let lastErr: Error | undefined;\n\n for (let attempt = 0; attempt < maxAttempts; attempt++) {\n req.signal?.throwIfAborted();\n\n const { signal, cancel } = linkTimeoutSignal(req.signal, timeoutMs);\n let res: Response;\n try {\n res = await fetchImpl(req.url, {\n method: req.method ?? 'GET',\n headers,\n body: req.body as RequestInit['body'],\n signal,\n });\n } catch (err) {\n cancel();\n if (req.signal?.aborted) {\n throw req.signal.reason ?? err;\n }\n const error = err instanceof Error ? err : new Error(String(err));\n lastErr = error;\n if (attempt < maxAttempts - 1 && retryOn(null, error)) {\n const delay = computeDelay(attempt, initialDelayMs, maxDelayMs);\n await sleep(delay, req.signal);\n continue;\n }\n throw new TransientError(error.message);\n }\n cancel();\n\n const body = await readBody(res, parseJson);\n const httpResponse: HttpResponse<T> = {\n status: res.status,\n headers: res.headers,\n body: body as T,\n };\n if (req.rateLimit) {\n const state = req.rateLimit.parse(res.headers);\n if (state) {\n httpResponse.rateLimitState = state;\n }\n }\n\n if (options.observer) {\n await notifyObserver(options.observer, {\n url: req.url,\n method: req.method ?? 'GET',\n status: res.status,\n resource: options.resource,\n requestId: options.requestId ?? newRequestId(),\n body,\n });\n }\n\n if (res.ok) {\n return httpResponse;\n }\n\n const retryAfter = parseRetryAfter(res.headers.get('retry-after'));\n const message = `HTTP ${res.status} ${res.statusText} for ${req.method ?? 'GET'} ${req.url}`;\n const err = errorForStatus(message, httpResponse, retryAfter);\n\n if (\n attempt < maxAttempts - 1 &&\n retryOn(res.status, err) &&\n !(err instanceof AuthError) &&\n !(err instanceof ClientBugError)\n ) {\n lastErr = err;\n let delay = computeDelay(attempt, initialDelayMs, maxDelayMs);\n if (err instanceof RateLimitError && retryAfter) {\n const wait = retryAfter.getTime() - Date.now();\n if (wait > 0) {\n delay = Math.min(wait, maxDelayMs);\n }\n }\n await sleep(delay, req.signal);\n continue;\n }\n\n throw err;\n }\n\n throw lastErr ?? new UpstreamBugError('Exhausted retry attempts');\n}\n\nfunction computeDelay(\n attempt: number,\n initialDelayMs: number,\n maxDelayMs: number,\n): number {\n const base = initialDelayMs * 2 ** attempt;\n const jitter = base * 0.25 * Math.random();\n return Math.min(base + jitter, maxDelayMs);\n}\n\nexport { HttpClientError };\n","export interface RateLimitState {\n remaining: number;\n resetAt: Date;\n}\n\nexport interface RateLimitPolicy {\n parse(headers: Headers): RateLimitState | null;\n}\n\nexport interface StandardRateLimitPolicyConfig {\n remainingHeader: string;\n resetHeader: string;\n resetUnit: 's' | 'ms';\n resetFallbackMs?: number;\n}\n\nexport function standardRateLimitPolicy(\n config: StandardRateLimitPolicyConfig,\n): RateLimitPolicy {\n const { remainingHeader, resetHeader, resetUnit, resetFallbackMs } = config;\n const multiplier = resetUnit === 's' ? 1000 : 1;\n return {\n parse(h) {\n const remainingRaw = h.get(remainingHeader);\n if (remainingRaw === null || remainingRaw.trim() === '') {\n return null;\n }\n const remaining = Number(remainingRaw);\n if (!Number.isFinite(remaining)) {\n return null;\n }\n const resetRaw = h.get(resetHeader);\n if (resetRaw === null) {\n if (resetFallbackMs === undefined) {\n return null;\n }\n return {\n remaining,\n resetAt: new Date(Date.now() + resetFallbackMs),\n };\n }\n if (resetRaw.trim() === '') {\n return null;\n }\n const reset = Number(resetRaw);\n if (!Number.isFinite(reset) || reset < 0) {\n return null;\n }\n const resetMs = reset * multiplier;\n if (!Number.isFinite(resetMs)) {\n return null;\n }\n return { remaining, resetAt: new Date(resetMs) };\n },\n };\n}\n","export interface SanitizeAllowedUrlOptions {\n url: string | null;\n host: string;\n pathname: string;\n protocol?: 'https:' | 'http:';\n}\n\nexport function sanitizeAllowedUrl(\n options: SanitizeAllowedUrlOptions,\n): string | null {\n const { url, host, pathname, protocol = 'https:' } = options;\n if (url === null) {\n return null;\n }\n try {\n const u = new URL(url);\n if (u.protocol !== protocol || u.host !== host || u.pathname !== pathname) {\n return null;\n }\n return u.toString();\n } catch {\n return null;\n }\n}\n","export type EpochUnit = 'ms' | 's' | 'iso';\n\nexport function parseEpoch(\n value: number | string | null | undefined,\n unit: EpochUnit,\n): number | null {\n if (value === null || value === undefined) {\n return null;\n }\n if (unit === 'iso') {\n if (typeof value !== 'string') {\n return null;\n }\n const ms = new Date(value).getTime();\n return Number.isFinite(ms) ? ms : null;\n }\n if (typeof value === 'string' && value.trim() === '') {\n return null;\n }\n const n = typeof value === 'number' ? value : Number(value);\n if (!Number.isFinite(n)) {\n return null;\n }\n const result = unit === 's' ? n * 1000 : n;\n return Number.isFinite(result) ? result : null;\n}\n","import { request } from './request';\nimport type { HttpRequest } from './types';\n\nexport function parseLinkHeader(header: string | null): Record<string, string> {\n if (!header) {\n return {};\n }\n const result: Record<string, string> = {};\n for (const part of header.split(',')) {\n const match = part.match(/<([^>]+)>\\s*;\\s*rel=\"([^\"]+)\"/);\n if (match) {\n result[match[2]!] = match[1]!;\n }\n }\n return result;\n}\n\nexport async function* paginateLink<T>(\n initial: HttpRequest,\n parse: (body: unknown) => T[],\n options: { resource: string },\n): AsyncIterable<T> {\n let next: string | null = initial.url;\n while (next) {\n const res: Awaited<ReturnType<typeof request>> = await request(\n {\n ...initial,\n url: next,\n },\n { resource: options.resource },\n );\n for (const item of parse(res.body)) {\n yield item;\n }\n const links = parseLinkHeader(res.headers.get('link'));\n next = links['next'] ?? null;\n }\n}\n\nexport async function* paginateCursor<T>(\n initial: HttpRequest,\n parse: (body: unknown) => { items: T[]; nextCursor: string | null },\n buildNext: (req: HttpRequest, cursor: string) => HttpRequest,\n options: { resource: string },\n): AsyncIterable<T> {\n let req: HttpRequest = initial;\n while (true) {\n const res = await request(req, { resource: options.resource });\n const { items, nextCursor } = parse(res.body);\n for (const item of items) {\n yield item;\n }\n if (!nextCursor) {\n return;\n }\n req = buildNext(req, nextCursor);\n }\n}\n\nexport async function* paginatePage<T>(\n initial: HttpRequest,\n parse: (body: unknown) => { items: T[]; hasMore: boolean },\n buildPage: (req: HttpRequest, page: number) => HttpRequest,\n options: { resource: string },\n): AsyncIterable<T> {\n let page = 1;\n while (true) {\n const req = page === 1 ? initial : buildPage(initial, page);\n const res = await request(req, { resource: options.resource });\n const { items, hasMore } = parse(res.body);\n for (const item of items) {\n yield item;\n }\n if (!hasMore || items.length === 0) {\n return;\n }\n page++;\n }\n}\n","export type LogFields = Record<string, unknown>;\n\nexport interface ConnectorLogger {\n info(event: string, fields?: LogFields): void;\n warn(event: string, fields?: LogFields): void;\n}\n\nexport interface ConnectorLoggerOptions {\n scope: string;\n}\n\nconst MAX_VALUE_LEN = 120;\n\nfunction truncate(s: string, max = MAX_VALUE_LEN): string {\n if (s.length <= max) {\n return s;\n }\n return `${s.slice(0, max - 1)}…`;\n}\n\nfunction formatValue(value: unknown): string {\n if (value === null) {\n return 'null';\n }\n if (value === undefined) {\n return '';\n }\n if (typeof value === 'number' || typeof value === 'boolean') {\n return String(value);\n }\n if (typeof value === 'string') {\n const t = truncate(value);\n if (/[\\s\"=]/.test(t)) {\n return JSON.stringify(t);\n }\n return t;\n }\n if (typeof value === 'bigint') {\n return value.toString();\n }\n let json: string | undefined;\n try {\n json = JSON.stringify(value);\n } catch {\n json = undefined;\n }\n return truncate(json ?? String(value));\n}\n\nexport function formatLogFields(fields?: LogFields): string {\n if (!fields) {\n return '';\n }\n const parts: string[] = [];\n for (const [k, v] of Object.entries(fields)) {\n if (v === undefined) {\n continue;\n }\n parts.push(`${k}=${formatValue(v)}`);\n }\n return parts.length > 0 ? ` ${parts.join(' ')}` : '';\n}\n\nexport function formatLogLine(\n scope: string,\n event: string,\n fields?: LogFields,\n): string {\n return `[${scope}] ${event}${formatLogFields(fields)}`;\n}\n\nexport function createDefaultConnectorLogger(\n opts: ConnectorLoggerOptions,\n): ConnectorLogger {\n return {\n info(event, fields) {\n console.info(formatLogLine(opts.scope, event, fields));\n },\n warn(event, fields) {\n console.warn(formatLogLine(opts.scope, event, fields));\n },\n };\n}\n\nconst NOOP_LOGGER: ConnectorLogger = {\n info() {},\n warn() {},\n};\n\nexport function noopConnectorLogger(): ConnectorLogger {\n return NOOP_LOGGER;\n}\n","import {\n type HttpResponse,\n connectorUserAgent,\n parseEpoch,\n sanitizeAllowedUrl,\n standardRateLimitPolicy,\n} from '@rawdash/connector-shared';\nimport {\n BaseConnector,\n type ChunkedSyncCursor,\n type ConnectorContext,\n type ConnectorDoc,\n type CredentialsSchema,\n type Entity,\n type JSONValue,\n type StorageHandle,\n type SyncOptions,\n type SyncResult,\n defineConfigFields,\n defineConnectorDoc,\n defineResources,\n makeChunkedCursorGuard,\n paginateChunked,\n schemasFromResources,\n selectActivePhases,\n} from '@rawdash/core';\nimport { z } from 'zod';\n\n// ---------------------------------------------------------------------------\n// configFields\n// ---------------------------------------------------------------------------\n\nconst metricQuerySchema = z.object({\n name: z\n .string()\n .min(1)\n .regex(/^[a-zA-Z0-9_]+$/, {\n message: 'Metric name must be alphanumeric / underscore',\n }),\n query: z.string().min(1),\n interval: z\n .enum(['5m', '15m', '1h', '1d'])\n .optional()\n .describe('Aggregation interval - defaults to 1h.'),\n});\n\nconst datadogSiteSchema = z\n .string()\n .trim()\n .min(1)\n .toLowerCase()\n .regex(/^(?:[a-z0-9-]+\\.)*(?:datadoghq\\.com|datadoghq\\.eu|ddog-gov\\.com)$/, {\n message:\n 'Site must be a Datadog hostname (e.g. datadoghq.com, datadoghq.eu, us3.datadoghq.com)',\n });\n\nexport const configFields = defineConfigFields(\n z.object({\n apiKey: z.object({ $secret: z.string().min(1) }).meta({\n label: 'API Key',\n description:\n 'Datadog API key. Create at Datadog → Organization Settings → API Keys.',\n placeholder: 'dd_api_key',\n secret: true,\n }),\n appKey: z.object({ $secret: z.string().min(1) }).meta({\n label: 'Application Key',\n description:\n 'Datadog Application key. Create at Datadog → Organization Settings → Application Keys. Used in tandem with the API key to authenticate REST calls.',\n placeholder: 'dd_app_key',\n secret: true,\n }),\n site: datadogSiteSchema.optional().meta({\n label: 'Site',\n description:\n 'Datadog site host (e.g. `datadoghq.com`, `datadoghq.eu`, `us3.datadoghq.com`). Defaults to `datadoghq.com`.',\n placeholder: 'datadoghq.com',\n }),\n metricQueries: z.array(metricQuerySchema).nonempty().optional().meta({\n label: 'Metric queries (optional)',\n description:\n 'User-declared metric timeseries queries. Each entry produces `datadog_metric` samples named `<name>` from the Datadog Metrics Query API.',\n }),\n resources: z\n .array(\n z.enum([\n 'monitors',\n 'monitor_events',\n 'incidents',\n 'slos',\n 'metric_queries',\n ]),\n )\n .nonempty()\n .optional()\n .meta({\n label: 'Resources',\n description:\n \"Which Datadog resources to sync. Omit to sync all of them. 'monitor_events' depends on 'monitors' being fetched - enabling it without 'monitors' still runs the monitors query but skips writing monitor entities.\",\n }),\n metricsLookbackHours: z.number().int().positive().max(168).optional().meta({\n label: 'Metrics lookback (hours)',\n description:\n 'Window of metric samples to pull on each sync, in hours. Defaults to 24.',\n placeholder: '24',\n }),\n }),\n);\n\nexport const doc: ConnectorDoc = defineConnectorDoc({\n displayName: 'Datadog',\n category: 'infrastructure',\n brandColor: '#632CA6',\n tagline:\n 'Sync monitor health, monitor state-change events, incidents, SLOs, and user-declared metric queries from a Datadog org.',\n vendor: {\n name: 'Datadog',\n apiDocs: 'https://docs.datadoghq.com/api/latest/',\n website: 'https://www.datadoghq.com',\n },\n auth: {\n summary:\n 'A Datadog API key and Application key are required, scoped to the org and site you want to read from. Both are stored as secrets.',\n setup: [\n 'Open Datadog → Organization Settings → API Keys and create (or copy) an API key.',\n 'Open Datadog → Organization Settings → Application Keys and create an Application key with read access to monitors, incidents, SLOs, and metrics.',\n 'Store both as secrets and reference them from the connector config as `apiKey: secret(\"DD_API_KEY\")` and `appKey: secret(\"DD_APP_KEY\")`.',\n 'Set `site` to your Datadog site host (e.g. `datadoghq.com`, `datadoghq.eu`, `us3.datadoghq.com`); it defaults to `datadoghq.com`.',\n ],\n },\n rateLimit:\n 'Datadog returns X-RateLimit-Remaining / X-RateLimit-Reset headers (reset in seconds) on the v2 endpoints, wired through the standard rate-limit policy so the host scheduler backs off on near-empty windows.',\n limitations: [\n 'Logs and RUM session data are out of scope (high volume, low dashboard signal).',\n 'Synthetic monitor results are out of scope.',\n 'Monitor entities are not cleared on a full sync - the monitor_events diff depends on the prior status being stored.',\n 'Pagination URLs are pinned to the configured `api.<site>` host.',\n ],\n});\n\nexport type DatadogResource =\n | 'monitors'\n | 'monitor_events'\n | 'incidents'\n | 'slos'\n | 'metric_queries';\n\nexport interface DatadogMetricQuery {\n name: string;\n query: string;\n interval?: '5m' | '15m' | '1h' | '1d';\n}\n\nexport interface DatadogSettings {\n site?: string;\n metricQueries?: readonly DatadogMetricQuery[];\n resources?: readonly DatadogResource[];\n metricsLookbackHours?: number;\n}\n\nconst datadogCredentials = {\n apiKey: {\n description: 'Datadog API key',\n auth: 'required' as const,\n },\n appKey: {\n description: 'Datadog Application key',\n auth: 'required' as const,\n },\n} satisfies CredentialsSchema;\n\ntype DatadogCredentials = typeof datadogCredentials;\n\n// ---------------------------------------------------------------------------\n// Sync phases + cursor\n// ---------------------------------------------------------------------------\n\n// Datadog exposes `X-RateLimit-Remaining` / `X-RateLimit-Reset` on the v2\n// endpoints (Reset is seconds-until). We treat reset as a relative-seconds\n// value; standardRateLimitPolicy with `resetUnit: 's'` and the right header\n// names parses it as the \"remaining\" budget — close enough for the host\n// scheduler to back off on near-empty windows.\nconst datadogRateLimit = standardRateLimitPolicy({\n remainingHeader: 'x-ratelimit-remaining',\n resetHeader: 'x-ratelimit-reset',\n resetUnit: 's',\n});\n\nconst PHASE_ORDER = ['monitors', 'incidents', 'slos', 'metrics'] as const;\n\ntype DatadogPhase = (typeof PHASE_ORDER)[number];\n\ntype DatadogSyncCursor = ChunkedSyncCursor<DatadogPhase, string>;\n\nconst isDatadogSyncCursor = makeChunkedCursorGuard(PHASE_ORDER);\n\n// ---------------------------------------------------------------------------\n// Datadog API types\n// ---------------------------------------------------------------------------\n\ntype DatadogMonitorStatus = 'OK' | 'Alert' | 'Warn' | 'No Data' | 'Ignored';\n\ninterface DatadogMonitor {\n id: number;\n name: string;\n type: string;\n status: DatadogMonitorStatus;\n priority: number | null;\n tags: string[];\n overall_state_modified?: string | null;\n created: string;\n modified: string;\n}\n\ninterface DatadogMonitorSearchResponse {\n monitors: DatadogMonitor[];\n metadata: {\n page: number;\n page_count: number;\n per_page: number;\n total_count: number;\n };\n}\n\ninterface DatadogIncident {\n id: string;\n type: 'incidents';\n attributes: {\n title: string;\n severity?: string | null;\n state?: string | null;\n customer_impact_scope?: string | null;\n created: string;\n modified?: string | null;\n resolved?: string | null;\n };\n}\n\ninterface DatadogIncidentsResponse {\n data: DatadogIncident[];\n meta?: {\n pagination?: {\n next_offset?: number | null;\n offset?: number;\n size?: number;\n };\n };\n}\n\ninterface DatadogSloThreshold {\n timeframe: string;\n target: number;\n warning?: number | null;\n}\n\ninterface DatadogSloStatus {\n sli_value?: number | null;\n indexed_at?: number | null;\n}\n\ninterface DatadogSlo {\n id: string;\n name: string;\n type: string;\n thresholds: DatadogSloThreshold[];\n overall_status?: DatadogSloStatus[] | null;\n created_at?: number | null;\n modified_at?: number | null;\n}\n\ninterface DatadogSlosResponse {\n data: DatadogSlo[];\n}\n\ninterface DatadogTimeseriesResponse {\n data: {\n type: 'timeseries_response';\n attributes: {\n series?: Array<{\n group_tags?: string[];\n query_index?: number;\n unit?: Array<{ name?: string } | null> | null;\n }>;\n times?: number[];\n values?: number[][];\n };\n };\n}\n\ninterface MonitorsBatchItem {\n monitor: DatadogMonitor;\n}\n\ninterface MetricsBatchItem {\n queryName: string;\n query: string;\n response: DatadogTimeseriesResponse;\n}\n\n// ---------------------------------------------------------------------------\n// Schemas — describe the per-resource API response shape consumed by request()\n// ---------------------------------------------------------------------------\n\nconst idString = z.string().min(1);\n\nconst monitorSchema = z.object({\n id: z.number().int().nonnegative(),\n name: z.string(),\n type: z.string(),\n status: z.enum(['OK', 'Alert', 'Warn', 'No Data', 'Ignored']),\n priority: z.number().int().nullable(),\n tags: z.array(z.string()),\n overall_state_modified: z.iso.datetime().nullable().optional(),\n created: z.iso.datetime(),\n modified: z.iso.datetime(),\n});\n\nconst monitorSearchResponseSchema = z.object({\n monitors: z.array(monitorSchema),\n metadata: z.object({\n page: z.number().int().nonnegative(),\n page_count: z.number().int().nonnegative(),\n per_page: z.number().int().positive(),\n total_count: z.number().int().nonnegative(),\n }),\n});\n\nconst incidentSchema = z.object({\n id: idString,\n type: z.literal('incidents'),\n attributes: z.object({\n title: z.string(),\n severity: z.string().nullable().optional(),\n state: z.string().nullable().optional(),\n customer_impact_scope: z.string().nullable().optional(),\n created: z.iso.datetime(),\n modified: z.iso.datetime().nullable().optional(),\n resolved: z.iso.datetime().nullable().optional(),\n }),\n});\n\nconst incidentsResponseSchema = z.object({\n data: z.array(incidentSchema),\n meta: z\n .object({\n pagination: z\n .object({\n next_offset: z.number().int().nullable().optional(),\n offset: z.number().int().optional(),\n size: z.number().int().optional(),\n })\n .optional(),\n })\n .optional(),\n});\n\nconst sloSchema = z.object({\n id: idString,\n name: z.string(),\n type: z.string(),\n thresholds: z.array(\n z.object({\n timeframe: z.string(),\n target: z.number(),\n warning: z.number().nullable().optional(),\n }),\n ),\n overall_status: z\n .array(\n z.object({\n sli_value: z.number().nullable().optional(),\n indexed_at: z.number().nullable().optional(),\n }),\n )\n .nullable()\n .optional(),\n created_at: z.number().nullable().optional(),\n modified_at: z.number().nullable().optional(),\n});\n\nconst slosResponseSchema = z.object({\n data: z.array(sloSchema),\n});\n\nconst timeseriesResponseSchema = z.object({\n data: z.object({\n type: z.literal('timeseries_response'),\n attributes: z.object({\n series: z\n .array(\n z.object({\n group_tags: z.array(z.string()).optional(),\n query_index: z.number().int().optional(),\n }),\n )\n .optional(),\n times: z.array(z.number()).optional(),\n values: z.array(z.array(z.number())).optional(),\n }),\n }),\n});\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\nconst DEFAULT_SITE = 'datadoghq.com';\nconst MONITORS_PAGE_SIZE = 100;\nconst INCIDENTS_PAGE_SIZE = 50;\nconst DEFAULT_METRICS_LOOKBACK_HOURS = 24;\nconst INTERVAL_MS: Record<\n NonNullable<DatadogMetricQuery['interval']>,\n number\n> = {\n '5m': 5 * 60 * 1000,\n '15m': 15 * 60 * 1000,\n '1h': 60 * 60 * 1000,\n '1d': 24 * 60 * 60 * 1000,\n};\nconst DEFAULT_INTERVAL_MS = INTERVAL_MS['1h'];\n\n// ---------------------------------------------------------------------------\n// Resource definitions\n// ---------------------------------------------------------------------------\n\nexport const datadogResources = defineResources({\n datadog_monitor: {\n shape: 'entity',\n description:\n 'Datadog monitors with name, type, current status (OK / Alert / Warn / No Data), priority, and tags.',\n endpoint: 'GET /api/v1/monitor/search',\n responses: { monitors: monitorSearchResponseSchema },\n },\n datadog_monitor_event: {\n shape: 'event',\n description:\n \"Monitor state-transition events, emitted whenever a monitor's status changes from its previously-stored value.\",\n notes:\n \"Derived by diffing each monitor's current status against the last-synced status, so it depends on the monitors phase running and on prior monitor state being stored.\",\n },\n datadog_incident: {\n shape: 'entity',\n description:\n 'Datadog incidents with title, severity, state, and created / resolved timestamps.',\n endpoint: 'GET /api/v2/incidents',\n responses: { incidents: incidentsResponseSchema },\n },\n datadog_slo: {\n shape: 'entity',\n description:\n 'Service Level Objectives with type, thresholds, primary target, and latest SLI value.',\n endpoint: 'GET /api/v1/slo',\n responses: { slos: slosResponseSchema },\n },\n datadog_slo_sli: {\n shape: 'metric',\n description:\n 'SLI value samples per SLO, one per overall_status snapshot reported by Datadog.',\n unit: 'percent',\n dimensions: [\n { name: 'sloId', description: 'Datadog SLO id.' },\n { name: 'sloType', description: 'SLO type (metric, monitor, etc.).' },\n ],\n },\n datadog_metric: {\n shape: 'metric',\n dynamic: true,\n description:\n 'User-declared metric timeseries samples, stored as `datadog_metric.<query name>`, from the Datadog Metrics Query API.',\n endpoint: 'POST /api/v2/query/timeseries',\n dimensions: [\n { name: 'queryName', description: 'The user-declared query name.' },\n { name: 'query', description: 'The Datadog metrics query string.' },\n {\n name: 'tags',\n description:\n 'Comma-joined group tags for the series, or `*` when the series is ungrouped.',\n },\n ],\n responses: { metric_queries: timeseriesResponseSchema },\n },\n});\n\n// ---------------------------------------------------------------------------\n// DatadogConnector\n// ---------------------------------------------------------------------------\n\nexport const id = 'datadog';\n\nexport class DatadogConnector extends BaseConnector<\n DatadogSettings,\n DatadogCredentials\n> {\n static readonly id = id;\n\n static readonly resources = datadogResources;\n\n static readonly schemas = schemasFromResources(datadogResources);\n\n static create(input: unknown, ctx?: ConnectorContext): DatadogConnector {\n const parsed = configFields.parse(input);\n return new DatadogConnector(\n {\n site: parsed.site,\n metricQueries: parsed.metricQueries,\n resources: parsed.resources,\n metricsLookbackHours: parsed.metricsLookbackHours,\n },\n { apiKey: parsed.apiKey, appKey: parsed.appKey },\n ctx,\n );\n }\n\n readonly id = id;\n override readonly credentials = datadogCredentials;\n\n private get apiHost(): string {\n return `api.${(this.settings.site ?? DEFAULT_SITE).toLowerCase()}`;\n }\n\n private get apiBase(): string {\n return `https://${this.apiHost}`;\n }\n\n private buildHeaders(): Record<string, string> {\n return {\n 'DD-API-KEY': this.creds.apiKey,\n 'DD-APPLICATION-KEY': this.creds.appKey,\n 'User-Agent': connectorUserAgent('datadog'),\n };\n }\n\n private fetch<T>(\n url: string,\n resource: string,\n signal?: AbortSignal,\n ): Promise<HttpResponse<T>> {\n return this.get<T>(url, {\n resource,\n headers: this.buildHeaders(),\n signal,\n rateLimit: datadogRateLimit,\n });\n }\n\n private postJson<T>(\n url: string,\n body: unknown,\n resource: string,\n signal?: AbortSignal,\n ): Promise<HttpResponse<T>> {\n return this.post<T>(url, {\n resource,\n headers: {\n ...this.buildHeaders(),\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(body),\n signal,\n rateLimit: datadogRateLimit,\n });\n }\n\n // -------------------------------------------------------------------------\n // Resource enablement\n // -------------------------------------------------------------------------\n\n private activePhases(): DatadogPhase[] {\n return selectActivePhases<DatadogResource, DatadogPhase>(\n (r) => {\n switch (r) {\n case 'monitors':\n case 'monitor_events':\n return 'monitors';\n case 'incidents':\n return 'incidents';\n case 'slos':\n return 'slos';\n case 'metric_queries':\n return 'metrics';\n }\n },\n PHASE_ORDER,\n this.settings.resources,\n );\n }\n\n // -------------------------------------------------------------------------\n // URL building + sanitization\n // -------------------------------------------------------------------------\n\n private allowedPagePath(phase: DatadogPhase): string {\n switch (phase) {\n case 'monitors':\n return '/api/v1/monitor/search';\n case 'incidents':\n return '/api/v2/incidents';\n case 'slos':\n return '/api/v1/slo';\n case 'metrics':\n return '/api/v2/query/timeseries';\n }\n }\n\n private sanitizePageUrl(\n phase: DatadogPhase,\n pageUrl: string | null,\n ): string | null {\n return sanitizeAllowedUrl({\n url: pageUrl,\n host: this.apiHost,\n pathname: this.allowedPagePath(phase),\n });\n }\n\n private resolveCursor(cursor: unknown): DatadogSyncCursor | undefined {\n if (!isDatadogSyncCursor(cursor)) {\n return undefined;\n }\n return {\n phase: cursor.phase,\n page: this.sanitizePageUrl(cursor.phase, cursor.page),\n };\n }\n\n private buildInitialMonitorsUrl(): string {\n const u = new URL(`${this.apiBase}/api/v1/monitor/search`);\n u.searchParams.set('per_page', String(MONITORS_PAGE_SIZE));\n u.searchParams.set('page', '0');\n u.searchParams.set('sort', 'status,desc');\n return u.toString();\n }\n\n private buildNextMonitorsUrl(currentUrl: string, nextPage: number): string {\n const u = new URL(currentUrl);\n u.searchParams.set('page', String(nextPage));\n return u.toString();\n }\n\n private buildInitialIncidentsUrl(options: SyncOptions): string {\n const u = new URL(`${this.apiBase}/api/v2/incidents`);\n u.searchParams.set('page[size]', String(INCIDENTS_PAGE_SIZE));\n u.searchParams.set('page[offset]', '0');\n u.searchParams.set('include', '');\n if (options.since) {\n u.searchParams.set('filter[created.from]', options.since);\n }\n return u.toString();\n }\n\n private buildNextIncidentsUrl(\n currentUrl: string,\n nextOffset: number,\n ): string {\n const u = new URL(currentUrl);\n u.searchParams.set('page[offset]', String(nextOffset));\n return u.toString();\n }\n\n private buildSlosUrl(): string {\n const u = new URL(`${this.apiBase}/api/v1/slo`);\n u.searchParams.set('limit', '1000');\n u.searchParams.set('offset', '0');\n return u.toString();\n }\n\n private buildMetricsUrl(): string {\n return `${this.apiBase}/api/v2/query/timeseries`;\n }\n\n // -------------------------------------------------------------------------\n // Fetchers\n // -------------------------------------------------------------------------\n\n private async fetchMonitorsPage(\n page: string | null,\n signal: AbortSignal | undefined,\n ): Promise<{ items: MonitorsBatchItem[]; next: string | null }> {\n const url = page ?? this.buildInitialMonitorsUrl();\n const res = await this.fetch<DatadogMonitorSearchResponse>(\n url,\n 'monitors',\n signal,\n );\n const meta = res.body.metadata;\n const currentPage = meta.page;\n const totalPages = meta.page_count;\n const hasNext = currentPage + 1 < totalPages;\n const next = hasNext\n ? this.sanitizePageUrl(\n 'monitors',\n this.buildNextMonitorsUrl(url, currentPage + 1),\n )\n : null;\n return {\n items: res.body.monitors.map((m) => ({ monitor: m })),\n next,\n };\n }\n\n private async fetchIncidentsPage(\n page: string | null,\n options: SyncOptions,\n signal: AbortSignal | undefined,\n ): Promise<{ items: DatadogIncident[]; next: string | null }> {\n const url = page ?? this.buildInitialIncidentsUrl(options);\n const res = await this.fetch<DatadogIncidentsResponse>(\n url,\n 'incidents',\n signal,\n );\n const nextOffset = res.body.meta?.pagination?.next_offset ?? null;\n const incidents = res.body.data;\n const cutoff = options.since\n ? (parseEpoch(options.since, 'iso') ?? null)\n : null;\n const filtered =\n cutoff !== null\n ? incidents.filter((inc) => {\n const ts = parseEpoch(inc.attributes.created, 'iso');\n return ts === null || ts >= cutoff;\n })\n : incidents;\n const lastIncident = incidents.at(-1);\n const lastTs = lastIncident\n ? parseEpoch(lastIncident.attributes.created, 'iso')\n : null;\n const cutoffReached = cutoff !== null && lastTs !== null && lastTs < cutoff;\n const next =\n !cutoffReached && nextOffset !== null\n ? this.sanitizePageUrl(\n 'incidents',\n this.buildNextIncidentsUrl(url, nextOffset),\n )\n : null;\n return { items: filtered, next };\n }\n\n private async fetchSlos(\n signal: AbortSignal | undefined,\n ): Promise<{ items: DatadogSlo[]; next: string | null }> {\n const res = await this.fetch<DatadogSlosResponse>(\n this.buildSlosUrl(),\n 'slos',\n signal,\n );\n return { items: res.body.data, next: null };\n }\n\n private async fetchMetrics(\n options: SyncOptions,\n signal: AbortSignal | undefined,\n ): Promise<{ items: MetricsBatchItem[]; next: string | null }> {\n const queries = this.settings.metricQueries ?? [];\n if (queries.length === 0) {\n return { items: [], next: null };\n }\n const lookbackHours =\n this.settings.metricsLookbackHours ?? DEFAULT_METRICS_LOOKBACK_HOURS;\n const now = Date.now();\n const sinceMs = options.since ? parseEpoch(options.since, 'iso') : null;\n const fromMs =\n sinceMs !== null ? sinceMs : now - lookbackHours * 60 * 60 * 1000;\n const items: MetricsBatchItem[] = [];\n for (const q of queries) {\n signal?.throwIfAborted();\n const intervalMs = q.interval\n ? INTERVAL_MS[q.interval]\n : DEFAULT_INTERVAL_MS;\n const body = {\n data: {\n type: 'timeseries_request',\n attributes: {\n from: fromMs,\n to: now,\n interval: intervalMs,\n queries: [\n {\n name: 'a',\n data_source: 'metrics',\n query: q.query,\n },\n ],\n formulas: [{ formula: 'a' }],\n },\n },\n };\n const res = await this.postJson<DatadogTimeseriesResponse>(\n this.buildMetricsUrl(),\n body,\n 'metric_queries',\n signal,\n );\n items.push({\n queryName: q.name,\n query: q.query,\n response: res.body,\n });\n }\n return { items, next: null };\n }\n\n // -------------------------------------------------------------------------\n // Writers\n // -------------------------------------------------------------------------\n\n private async writeMonitorsBatch(\n storage: StorageHandle,\n items: MonitorsBatchItem[],\n ): Promise<void> {\n const writeEntities = this.isResourceEnabled('monitors');\n const writeEvents = this.isResourceEnabled('monitor_events');\n\n for (const item of items) {\n const m = item.monitor;\n const createdMs = parseEpoch(m.created, 'iso');\n const modifiedMs = parseEpoch(m.modified, 'iso');\n const stateModifiedMs =\n m.overall_state_modified !== undefined &&\n m.overall_state_modified !== null\n ? parseEpoch(m.overall_state_modified, 'iso')\n : null;\n if (createdMs === null || modifiedMs === null) {\n console.warn(\n `[connector-datadog] skipping monitor ${m.id} with unparseable created/modified timestamps`,\n );\n continue;\n }\n const updatedMs = Math.max(modifiedMs, stateModifiedMs ?? 0);\n\n const attributes: Record<string, JSONValue> = {\n monitorId: m.id,\n name: m.name,\n monitorType: m.type,\n status: m.status,\n priority: m.priority,\n tags: m.tags,\n createdAt: createdMs,\n modifiedAt: modifiedMs,\n stateModifiedAt: stateModifiedMs,\n };\n\n if (writeEvents) {\n const prior = await storage.getEntity('datadog_monitor', String(m.id));\n const priorStatus =\n prior !== null &&\n typeof prior.attributes === 'object' &&\n prior.attributes !== null\n ? (prior.attributes as { status?: string }).status\n : undefined;\n if (\n priorStatus !== m.status &&\n stateModifiedMs !== null &&\n Number.isFinite(stateModifiedMs)\n ) {\n await storage.event({\n name: 'datadog_monitor_event',\n start_ts: stateModifiedMs,\n end_ts: null,\n attributes: {\n monitorId: m.id,\n name: m.name,\n monitorType: m.type,\n fromStatus: priorStatus ?? null,\n toStatus: m.status,\n priority: m.priority,\n tags: m.tags,\n },\n });\n }\n }\n\n if (writeEntities) {\n await storage.entity({\n type: 'datadog_monitor',\n id: String(m.id),\n attributes,\n updated_at: updatedMs,\n });\n } else if (writeEvents) {\n // We still upsert to keep the comparison baseline fresh even when the\n // host hasn't asked for the monitor entity itself — the next sync's\n // monitor_event diff depends on a stored prior state.\n await storage.entity({\n type: 'datadog_monitor',\n id: String(m.id),\n attributes,\n updated_at: updatedMs,\n });\n }\n }\n }\n\n private async writeIncidents(\n storage: StorageHandle,\n incidents: DatadogIncident[],\n ): Promise<void> {\n for (const inc of incidents) {\n const createdMs = parseEpoch(inc.attributes.created, 'iso');\n if (createdMs === null) {\n console.warn(\n `[connector-datadog] skipping incident ${inc.id} with unparseable created timestamp`,\n );\n continue;\n }\n const modifiedMs = inc.attributes.modified\n ? parseEpoch(inc.attributes.modified, 'iso')\n : null;\n const resolvedMs = inc.attributes.resolved\n ? parseEpoch(inc.attributes.resolved, 'iso')\n : null;\n await storage.entity({\n type: 'datadog_incident',\n id: inc.id,\n attributes: {\n incidentId: inc.id,\n title: inc.attributes.title,\n severity: inc.attributes.severity ?? null,\n state: inc.attributes.state ?? null,\n customerImpactScope: inc.attributes.customer_impact_scope ?? null,\n createdAt: createdMs,\n modifiedAt: modifiedMs,\n resolvedAt: resolvedMs,\n },\n updated_at: Math.max(createdMs, modifiedMs ?? 0, resolvedMs ?? 0),\n });\n }\n }\n\n private async writeSlos(\n storage: StorageHandle,\n slos: DatadogSlo[],\n ): Promise<void> {\n const sliSamples: Array<{\n name: string;\n ts: number;\n value: number;\n attributes: Record<string, string | number>;\n }> = [];\n const entities: Entity[] = [];\n for (const s of slos) {\n const createdMs =\n s.created_at !== null && s.created_at !== undefined\n ? parseEpoch(s.created_at, 's')\n : null;\n const modifiedMs =\n s.modified_at !== null && s.modified_at !== undefined\n ? parseEpoch(s.modified_at, 's')\n : null;\n const targets = s.thresholds.map((t) => ({\n timeframe: t.timeframe,\n target: t.target,\n }));\n const primaryTarget = s.thresholds[0]?.target ?? null;\n const latestStatus = (s.overall_status ?? []).find(\n (st) => st.sli_value !== null && st.sli_value !== undefined,\n );\n const latestSli = latestStatus?.sli_value ?? null;\n entities.push({\n type: 'datadog_slo',\n id: s.id,\n attributes: {\n sloId: s.id,\n name: s.name,\n sloType: s.type,\n thresholds: targets as unknown as JSONValue,\n target: primaryTarget,\n latestSliValue: latestSli,\n createdAt: createdMs,\n modifiedAt: modifiedMs,\n },\n updated_at: modifiedMs ?? createdMs ?? Date.now(),\n });\n\n for (const status of s.overall_status ?? []) {\n const ts =\n status.indexed_at !== null && status.indexed_at !== undefined\n ? parseEpoch(status.indexed_at, 's')\n : null;\n const value = status.sli_value;\n if (\n ts === null ||\n value === null ||\n value === undefined ||\n !Number.isFinite(value)\n ) {\n continue;\n }\n sliSamples.push({\n name: 'datadog_slo_sli',\n ts,\n value,\n attributes: { sloId: s.id, sloType: s.type },\n });\n }\n }\n for (const entity of entities) {\n await storage.entity(entity);\n }\n if (sliSamples.length > 0) {\n await storage.metrics(sliSamples, { names: ['datadog_slo_sli'] });\n }\n }\n\n private async writeMetrics(\n storage: StorageHandle,\n items: MetricsBatchItem[],\n ): Promise<void> {\n if (items.length === 0) {\n return;\n }\n const samplesByName: Map<\n string,\n Array<{\n name: string;\n ts: number;\n value: number;\n attributes: Record<string, string | number>;\n }>\n > = new Map();\n for (const item of items) {\n const attrs = item.response.data.attributes;\n const times = attrs.times ?? [];\n const series = attrs.series ?? [];\n const values = attrs.values ?? [];\n for (let s = 0; s < series.length; s++) {\n const seriesValues = values[s];\n if (!seriesValues) {\n continue;\n }\n const tagsArr = series[s]?.group_tags ?? [];\n const tagsStr = tagsArr.length > 0 ? tagsArr.join(',') : '*';\n for (let t = 0; t < times.length; t++) {\n const rawTs = times[t];\n const rawValue = seriesValues[t];\n if (rawTs === undefined || rawValue === undefined) {\n continue;\n }\n const ts = parseEpoch(rawTs, 'ms');\n if (ts === null || !Number.isFinite(rawValue)) {\n continue;\n }\n const name = `datadog_metric.${item.queryName}`;\n let bucket = samplesByName.get(name);\n if (!bucket) {\n bucket = [];\n samplesByName.set(name, bucket);\n }\n bucket.push({\n name,\n ts,\n value: rawValue,\n attributes: {\n queryName: item.queryName,\n query: item.query,\n tags: tagsStr,\n },\n });\n }\n }\n }\n for (const [name, samples] of samplesByName) {\n await storage.metrics(samples, { names: [name] });\n }\n }\n\n // -------------------------------------------------------------------------\n // sync\n // -------------------------------------------------------------------------\n\n async sync(\n options: SyncOptions,\n storage: StorageHandle,\n signal?: AbortSignal,\n ): Promise<SyncResult> {\n const cursor = this.resolveCursor(options.cursor);\n const isFull = options.mode === 'full';\n const phases = this.activePhases();\n\n return paginateChunked<DatadogPhase, string>({\n phases,\n cursor,\n signal,\n logger: this.logger,\n fetchPage: async (phase, page, sig) => {\n switch (phase) {\n case 'monitors':\n return this.fetchMonitorsPage(page, sig);\n case 'incidents':\n return this.fetchIncidentsPage(page, options, sig);\n case 'slos':\n return this.fetchSlos(sig);\n case 'metrics':\n return this.fetchMetrics(options, sig);\n }\n },\n writeBatch: async (phase, items, page) => {\n if (isFull && page === null) {\n switch (phase) {\n case 'monitors':\n if (this.isResourceEnabled('monitor_events')) {\n await storage.events([], { names: ['datadog_monitor_event'] });\n }\n // Monitor entities are intentionally NOT cleared on a full\n // sync — `writeMonitorsBatch` reads the prior status off the\n // existing entity to derive monitor_events. Wiping it here\n // would forget every state we'd seen on the previous run.\n break;\n case 'incidents':\n await storage.entities([], { types: ['datadog_incident'] });\n break;\n case 'slos':\n await storage.entities([], { types: ['datadog_slo'] });\n await storage.metrics([], { names: ['datadog_slo_sli'] });\n break;\n case 'metrics':\n for (const q of this.settings.metricQueries ?? []) {\n await storage.metrics([], {\n names: [`datadog_metric.${q.name}`],\n });\n }\n break;\n }\n }\n switch (phase) {\n case 'monitors':\n return this.writeMonitorsBatch(\n storage,\n items as MonitorsBatchItem[],\n );\n case 'incidents':\n return this.writeIncidents(storage, items as DatadogIncident[]);\n case 'slos':\n return this.writeSlos(storage, items as DatadogSlo[]);\n case 'metrics':\n return this.writeMetrics(storage, items as MetricsBatchItem[]);\n }\n },\n });\n }\n}\n","import { DatadogConnector } from './datadog';\n\nexport {\n configFields,\n doc,\n DatadogConnector,\n id,\n datadogResources as resources,\n} from './datadog';\nexport type { DatadogResource, DatadogSettings } from './datadog';\nexport default DatadogConnector;\n"],"mappings":";AEAO,IAAM,sBAAsB;AAE5B,IAAM,qBAAqB,qBAAqB,mBAAmB;AAEnE,SAAS,mBAAmB,aAA6B;AAC9D,SAAO,qBAAqB,WAAW,IAAI,mBAAmB;AAChE;AEUO,SAAS,wBACd,QACiB;AACjB,QAAM,EAAE,iBAAiB,aAAa,WAAW,gBAAgB,IAAI;AACrE,QAAM,aAAa,cAAc,MAAM,MAAO;AAC9C,SAAO;IACL,MAAM,GAAG;AACP,YAAM,eAAe,EAAE,IAAI,eAAe;AAC1C,UAAI,iBAAiB,QAAQ,aAAa,KAAK,MAAM,IAAI;AACvD,eAAO;MACT;AACA,YAAM,YAAY,OAAO,YAAY;AACrC,UAAI,CAAC,OAAO,SAAS,SAAS,GAAG;AAC/B,eAAO;MACT;AACA,YAAM,WAAW,EAAE,IAAI,WAAW;AAClC,UAAI,aAAa,MAAM;AACrB,YAAI,oBAAoB,QAAW;AACjC,iBAAO;QACT;AACA,eAAO;UACL;UACA,SAAS,IAAI,KAAK,KAAK,IAAI,IAAI,eAAe;QAChD;MACF;AACA,UAAI,SAAS,KAAK,MAAM,IAAI;AAC1B,eAAO;MACT;AACA,YAAM,QAAQ,OAAO,QAAQ;AAC7B,UAAI,CAAC,OAAO,SAAS,KAAK,KAAK,QAAQ,GAAG;AACxC,eAAO;MACT;AACA,YAAM,UAAU,QAAQ;AACxB,UAAI,CAAC,OAAO,SAAS,OAAO,GAAG;AAC7B,eAAO;MACT;AACA,aAAO,EAAE,WAAW,SAAS,IAAI,KAAK,OAAO,EAAE;IACjD;EACF;AACF;AChDO,SAAS,mBACd,SACe;AACf,QA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ACtD,KAAK;AACH,mBAAO,KAAK,aAAa,SAAS,KAA2B;AAAA,QACjE;AAAA,MACF;AAAA,IACF,CAAC;AAAA,EACH;AACF;;;AC1mCA,IAAO,gBAAQ;","names":[]}
|
package/package.json
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rawdash/connector-datadog",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.18.0",
|
|
4
4
|
"description": "Rawdash connector for Datadog — metric queries, monitors, incidents, and SLOs",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"type": "module",
|
|
7
|
+
"sideEffects": false,
|
|
7
8
|
"repository": {
|
|
8
9
|
"type": "git",
|
|
9
10
|
"url": "https://github.com/rawdash/rawdash.git",
|
|
@@ -21,22 +22,22 @@
|
|
|
21
22
|
"import": "./dist/index.js"
|
|
22
23
|
}
|
|
23
24
|
},
|
|
24
|
-
"scripts": {
|
|
25
|
-
"build": "tsup",
|
|
26
|
-
"typecheck": "tsc --noEmit",
|
|
27
|
-
"lint": "eslint src",
|
|
28
|
-
"test": "vitest run"
|
|
29
|
-
},
|
|
30
25
|
"dependencies": {
|
|
31
|
-
"
|
|
32
|
-
"
|
|
26
|
+
"zod": "^4.4.3",
|
|
27
|
+
"@rawdash/core": "0.18.0"
|
|
33
28
|
},
|
|
34
29
|
"devDependencies": {
|
|
35
|
-
"@rawdash/connector-shared": "workspace:*",
|
|
36
|
-
"@rawdash/connector-test-utils": "workspace:*",
|
|
37
30
|
"fast-check": "^4.8.0",
|
|
38
31
|
"tsup": "^8.0.0",
|
|
39
32
|
"typescript": "^5.7.2",
|
|
40
|
-
"vitest": "^4.1.4"
|
|
33
|
+
"vitest": "^4.1.4",
|
|
34
|
+
"@rawdash/connector-shared": "0.3.0",
|
|
35
|
+
"@rawdash/connector-test-utils": "0.0.5"
|
|
36
|
+
},
|
|
37
|
+
"scripts": {
|
|
38
|
+
"build": "tsup",
|
|
39
|
+
"typecheck": "tsc --noEmit",
|
|
40
|
+
"lint": "eslint src",
|
|
41
|
+
"test": "vitest run"
|
|
41
42
|
}
|
|
42
|
-
}
|
|
43
|
+
}
|