@ericminassian/platform-core 0.4.0 → 0.4.1
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/dist/api.d.ts +283 -0
- package/dist/api.js +99 -0
- package/dist/api.js.map +1 -1
- package/dist/explore.d.ts +365 -0
- package/dist/explore.js +440 -0
- package/dist/explore.js.map +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/platform-api.d.ts +3718 -1948
- package/dist/platform-api.js +99 -1
- package/dist/platform-api.js.map +1 -1
- package/dist/storage.d.ts +10 -0
- package/dist/storage.js +10 -0
- package/dist/storage.js.map +1 -1
- package/dist/telemetry.d.ts +12 -2
- package/dist/telemetry.js +12 -2
- package/dist/telemetry.js.map +1 -1
- package/package.json +1 -1
- package/src/api.ts +119 -0
- package/src/explore.ts +504 -0
- package/src/index.ts +1 -0
- package/src/platform-api.ts +115 -0
- package/src/storage.ts +11 -0
- package/src/telemetry.ts +12 -2
package/src/explore.ts
ADDED
|
@@ -0,0 +1,504 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The explorer's query model. The control plane answers it (the series
|
|
3
|
+
* endpoint) and evaluates alert rules with it; the console builds charts and
|
|
4
|
+
* alert rules from it; the CLI sends it.
|
|
5
|
+
*
|
|
6
|
+
* Every metric is read from the rollups the telemetry processor writes
|
|
7
|
+
* (`telemetryKeys`), except `realtime` and `service`, which come from
|
|
8
|
+
* CloudWatch on demand and so can't be watched by alert rules.
|
|
9
|
+
*/
|
|
10
|
+
import { Schema } from 'effect';
|
|
11
|
+
|
|
12
|
+
const optional = Schema.optional;
|
|
13
|
+
|
|
14
|
+
// ---------------------------------------------------------------------------
|
|
15
|
+
// Resolution
|
|
16
|
+
// ---------------------------------------------------------------------------
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Bucket sizes a query can ask for. `1m`, `1h` and `1d` are stored; the
|
|
20
|
+
* others are sums of 1-minute rollups (latency histograms add), so they
|
|
21
|
+
* reach back only as far as minute rollups are kept.
|
|
22
|
+
*/
|
|
23
|
+
export const QueryResolution = Schema.Literals(['1m', '5m', '10m', '15m', '30m', '1h', '1d']);
|
|
24
|
+
export type QueryResolution = typeof QueryResolution.Type;
|
|
25
|
+
|
|
26
|
+
export const QUERY_RESOLUTION_MS: Record<QueryResolution, number> = {
|
|
27
|
+
'1m': 60_000,
|
|
28
|
+
'5m': 300_000,
|
|
29
|
+
'10m': 600_000,
|
|
30
|
+
'15m': 900_000,
|
|
31
|
+
'30m': 1_800_000,
|
|
32
|
+
'1h': 3_600_000,
|
|
33
|
+
'1d': 86_400_000,
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
/** About this many buckets per chart when the caller doesn't pick a resolution. */
|
|
37
|
+
export const TARGET_POINTS = 150;
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* The smallest resolution that keeps `from`..`to` near `TARGET_POINTS`
|
|
41
|
+
* buckets, given how far back minute rollups reach (`minuteHorizonMs` before
|
|
42
|
+
* `now`): a range starting before that horizon can't be built from 1-minute
|
|
43
|
+
* rows, so it uses hours (or days past 14 days).
|
|
44
|
+
*/
|
|
45
|
+
export function autoQueryResolution(
|
|
46
|
+
from: number,
|
|
47
|
+
to: number,
|
|
48
|
+
now: number,
|
|
49
|
+
minuteHorizonMs: number,
|
|
50
|
+
): QueryResolution {
|
|
51
|
+
const span = Math.max(to - from, 60_000);
|
|
52
|
+
const minuteOk = from >= now - minuteHorizonMs;
|
|
53
|
+
const ladder: readonly QueryResolution[] = minuteOk
|
|
54
|
+
? ['1m', '5m', '10m', '15m', '30m', '1h', '1d']
|
|
55
|
+
: ['1h', '1d'];
|
|
56
|
+
for (const res of ladder) if (span / QUERY_RESOLUTION_MS[res] <= TARGET_POINTS * 1.5) return res;
|
|
57
|
+
return '1d';
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// ---------------------------------------------------------------------------
|
|
61
|
+
// Queries
|
|
62
|
+
// ---------------------------------------------------------------------------
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* What a query measures:
|
|
66
|
+
* - `requests`: HTTP requests (stage-wide, or of routes)
|
|
67
|
+
* - `latency`: their duration
|
|
68
|
+
* - `cold_starts`: requests served by a fresh server process
|
|
69
|
+
* - `jobs`: queue, event, cron, invoke and service runs
|
|
70
|
+
* - `job_duration`: their duration
|
|
71
|
+
* - `custom`: the app's `Metrics.count`/`value` series
|
|
72
|
+
* - `rate_limit`: `RateLimits` checks
|
|
73
|
+
* - `realtime`: AppSync Events activity (CloudWatch)
|
|
74
|
+
* - `service`: long-running services' CPU and memory (CloudWatch)
|
|
75
|
+
*/
|
|
76
|
+
export const SeriesMetric = Schema.Literals([
|
|
77
|
+
'requests',
|
|
78
|
+
'latency',
|
|
79
|
+
'cold_starts',
|
|
80
|
+
'jobs',
|
|
81
|
+
'job_duration',
|
|
82
|
+
'custom',
|
|
83
|
+
'rate_limit',
|
|
84
|
+
'realtime',
|
|
85
|
+
'service',
|
|
86
|
+
]);
|
|
87
|
+
export type SeriesMetric = typeof SeriesMetric.Type;
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* How each bucket is summarized:
|
|
91
|
+
* - `count`: how many (requests, runs, checks, recorded values)
|
|
92
|
+
* - `rate`: `count` per second
|
|
93
|
+
* - `percent`: the share, 0–100, of the metric's events that match the
|
|
94
|
+
* status or outcome filter, among all of them in the bucket (5xx % of
|
|
95
|
+
* requests, failed % of runs, denied % of checks)
|
|
96
|
+
* - `sum`, `avg`, `max`: of recorded values (custom metrics, realtime, service)
|
|
97
|
+
* - `p50`…`p99`: latency percentiles, from the rollups' fixed-bucket histograms
|
|
98
|
+
* (each is the upper bound of the bucket holding it)
|
|
99
|
+
* - `histogram`: every latency bucket's count, for heatmaps
|
|
100
|
+
*/
|
|
101
|
+
export const SeriesStat = Schema.Literals([
|
|
102
|
+
'count',
|
|
103
|
+
'rate',
|
|
104
|
+
'percent',
|
|
105
|
+
'sum',
|
|
106
|
+
'avg',
|
|
107
|
+
'max',
|
|
108
|
+
'p50',
|
|
109
|
+
'p90',
|
|
110
|
+
'p95',
|
|
111
|
+
'p99',
|
|
112
|
+
'histogram',
|
|
113
|
+
]);
|
|
114
|
+
export type SeriesStat = typeof SeriesStat.Type;
|
|
115
|
+
|
|
116
|
+
export const StatusClass = Schema.Literals(['2xx', '3xx', '4xx', '5xx']);
|
|
117
|
+
export type StatusClass = typeof StatusClass.Type;
|
|
118
|
+
export const STATUS_CLASSES: readonly StatusClass[] = ['2xx', '3xx', '4xx', '5xx'];
|
|
119
|
+
|
|
120
|
+
/** Splits a query into one line per value of this dimension. */
|
|
121
|
+
export const SeriesGroupBy = Schema.Literals(['status', 'route', 'job', 'outcome', 'name']);
|
|
122
|
+
export type SeriesGroupBy = typeof SeriesGroupBy.Type;
|
|
123
|
+
|
|
124
|
+
export const SeriesOutcome = Schema.Literals(['ok', 'error', 'allowed', 'denied']);
|
|
125
|
+
export type SeriesOutcome = typeof SeriesOutcome.Type;
|
|
126
|
+
|
|
127
|
+
const nonEmpty = Schema.String.check(Schema.isNonEmpty());
|
|
128
|
+
|
|
129
|
+
export const SeriesFilter = Schema.Struct({
|
|
130
|
+
/** Routes as rollups key them: `METHOD /pattern`, e.g. `GET /api/items/:id`. */
|
|
131
|
+
routes: optional(Schema.Array(nonEmpty)),
|
|
132
|
+
/** `requests` only. */
|
|
133
|
+
status: optional(Schema.Array(StatusClass)),
|
|
134
|
+
/** Jobs as `kind:name`, e.g. `queue:refresh`, `cron:digest`. */
|
|
135
|
+
jobs: optional(Schema.Array(nonEmpty)),
|
|
136
|
+
/** Custom metric names, rate limit names, or service names. */
|
|
137
|
+
names: optional(Schema.Array(nonEmpty)),
|
|
138
|
+
/** `jobs`: `ok` or `error`; `rate_limit`: `allowed` or `denied`. */
|
|
139
|
+
outcome: optional(SeriesOutcome),
|
|
140
|
+
/** `realtime`: `events`, `publishes`, `subscribes` or `errors`; `service`: `cpu` or `memory`. */
|
|
141
|
+
measure: optional(nonEmpty),
|
|
142
|
+
});
|
|
143
|
+
export type SeriesFilter = typeof SeriesFilter.Type;
|
|
144
|
+
|
|
145
|
+
export const SeriesQuery = Schema.Struct({
|
|
146
|
+
metric: SeriesMetric,
|
|
147
|
+
stat: SeriesStat,
|
|
148
|
+
filter: optional(SeriesFilter),
|
|
149
|
+
groupBy: optional(SeriesGroupBy),
|
|
150
|
+
/** Another stage than the page's. */
|
|
151
|
+
stage: optional(nonEmpty),
|
|
152
|
+
});
|
|
153
|
+
export type SeriesQuery = typeof SeriesQuery.Type;
|
|
154
|
+
|
|
155
|
+
/** The statistics each metric answers; the first is its default. */
|
|
156
|
+
export const METRIC_STATS: Record<SeriesMetric, readonly SeriesStat[]> = {
|
|
157
|
+
requests: ['count', 'rate', 'percent'],
|
|
158
|
+
latency: ['p95', 'p50', 'p90', 'p99', 'histogram'],
|
|
159
|
+
cold_starts: ['count', 'percent'],
|
|
160
|
+
jobs: ['count', 'rate', 'percent'],
|
|
161
|
+
job_duration: ['p95', 'p50', 'p90', 'p99', 'histogram'],
|
|
162
|
+
custom: ['sum', 'avg', 'count', 'max'],
|
|
163
|
+
rate_limit: ['count', 'percent'],
|
|
164
|
+
realtime: ['sum'],
|
|
165
|
+
service: ['avg', 'max'],
|
|
166
|
+
};
|
|
167
|
+
|
|
168
|
+
/** The dimensions each metric can be grouped by. */
|
|
169
|
+
export const METRIC_GROUP_BY: Record<SeriesMetric, readonly SeriesGroupBy[]> = {
|
|
170
|
+
requests: ['status', 'route'],
|
|
171
|
+
latency: ['route'],
|
|
172
|
+
cold_starts: [],
|
|
173
|
+
jobs: ['job', 'outcome'],
|
|
174
|
+
job_duration: ['job'],
|
|
175
|
+
custom: ['name'],
|
|
176
|
+
rate_limit: ['name', 'outcome'],
|
|
177
|
+
realtime: [],
|
|
178
|
+
service: ['name'],
|
|
179
|
+
};
|
|
180
|
+
|
|
181
|
+
/** Metrics alert rules can watch: those read from rollups. */
|
|
182
|
+
export const ALERT_METRICS: readonly SeriesMetric[] = [
|
|
183
|
+
'requests',
|
|
184
|
+
'latency',
|
|
185
|
+
'cold_starts',
|
|
186
|
+
'jobs',
|
|
187
|
+
'job_duration',
|
|
188
|
+
'custom',
|
|
189
|
+
'rate_limit',
|
|
190
|
+
];
|
|
191
|
+
|
|
192
|
+
export const REALTIME_MEASURES = ['events', 'publishes', 'subscribes', 'errors'] as const;
|
|
193
|
+
export const SERVICE_MEASURES = ['cpu', 'memory'] as const;
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* Why a query can't be answered, or undefined when it can. `alert` also
|
|
197
|
+
* refuses what an alert rule can't watch: CloudWatch metrics, histograms,
|
|
198
|
+
* groups, and another stage than the rule's.
|
|
199
|
+
*/
|
|
200
|
+
export function checkSeriesQuery(
|
|
201
|
+
q: SeriesQuery,
|
|
202
|
+
options: { readonly alert?: boolean } = {},
|
|
203
|
+
): string | undefined {
|
|
204
|
+
if (!METRIC_STATS[q.metric].includes(q.stat)) {
|
|
205
|
+
return `${q.metric} answers ${METRIC_STATS[q.metric].join(', ')}, not ${q.stat}`;
|
|
206
|
+
}
|
|
207
|
+
if (q.groupBy && !METRIC_GROUP_BY[q.metric].includes(q.groupBy)) {
|
|
208
|
+
const groups = METRIC_GROUP_BY[q.metric];
|
|
209
|
+
return groups.length
|
|
210
|
+
? `${q.metric} can be grouped by ${groups.join(' or ')}, not ${q.groupBy}`
|
|
211
|
+
: `${q.metric} can't be grouped`;
|
|
212
|
+
}
|
|
213
|
+
const f = q.filter ?? {};
|
|
214
|
+
if (f.status?.length && q.metric !== 'requests') return 'only requests filter by status';
|
|
215
|
+
if (f.routes?.length && q.metric !== 'requests' && q.metric !== 'latency' && q.metric !== 'cold_starts') {
|
|
216
|
+
return 'only requests, latency and cold starts filter by route';
|
|
217
|
+
}
|
|
218
|
+
if (f.jobs?.length && q.metric !== 'jobs' && q.metric !== 'job_duration') return 'only jobs filter by job';
|
|
219
|
+
if (f.outcome) {
|
|
220
|
+
const allowed =
|
|
221
|
+
q.metric === 'jobs' ? ['ok', 'error'] : q.metric === 'rate_limit' ? ['allowed', 'denied'] : [];
|
|
222
|
+
if (!allowed.includes(f.outcome)) {
|
|
223
|
+
return allowed.length
|
|
224
|
+
? `${q.metric} outcomes are ${allowed.join(' or ')}`
|
|
225
|
+
: `${q.metric} doesn't filter by outcome`;
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
if (f.names?.length && q.metric !== 'custom' && q.metric !== 'rate_limit' && q.metric !== 'service') {
|
|
229
|
+
return 'only custom metrics, rate limits and services filter by name';
|
|
230
|
+
}
|
|
231
|
+
if (q.metric === 'custom' && !f.names?.length && q.groupBy !== 'name') {
|
|
232
|
+
return 'a custom metric query names its metric, or groups by name';
|
|
233
|
+
}
|
|
234
|
+
if (q.metric === 'realtime' && !REALTIME_MEASURES.some((m) => m === f.measure)) {
|
|
235
|
+
return `realtime measures one of ${REALTIME_MEASURES.join(', ')}`;
|
|
236
|
+
}
|
|
237
|
+
if (q.metric === 'service' && !SERVICE_MEASURES.some((m) => m === f.measure)) {
|
|
238
|
+
return `service measures ${SERVICE_MEASURES.join(' or ')}`;
|
|
239
|
+
}
|
|
240
|
+
if (q.metric !== 'realtime' && q.metric !== 'service' && f.measure) {
|
|
241
|
+
return 'only realtime and service queries take a measure';
|
|
242
|
+
}
|
|
243
|
+
if (options.alert) {
|
|
244
|
+
if (!ALERT_METRICS.includes(q.metric)) return `alert rules can't watch ${q.metric}`;
|
|
245
|
+
if (q.stat === 'histogram') return 'alert rules watch one number, not a histogram';
|
|
246
|
+
if (q.groupBy) return 'alert rules watch one series; filter instead of grouping';
|
|
247
|
+
if (q.stage) return "an alert rule's query reads the rule's own stage";
|
|
248
|
+
}
|
|
249
|
+
return undefined;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/** The unit a query's values are in (a custom metric's own unit comes with its series). */
|
|
253
|
+
const STAT_UNIT: Record<SeriesStat, string> = {
|
|
254
|
+
count: 'count',
|
|
255
|
+
rate: 'per_second',
|
|
256
|
+
percent: 'percent',
|
|
257
|
+
sum: 'count',
|
|
258
|
+
avg: 'count',
|
|
259
|
+
max: 'count',
|
|
260
|
+
p50: 'ms',
|
|
261
|
+
p90: 'ms',
|
|
262
|
+
p95: 'ms',
|
|
263
|
+
p99: 'ms',
|
|
264
|
+
histogram: 'ms',
|
|
265
|
+
};
|
|
266
|
+
|
|
267
|
+
export function seriesUnit(q: Pick<SeriesQuery, 'metric' | 'stat' | 'filter'>): string {
|
|
268
|
+
const unit = STAT_UNIT[q.stat];
|
|
269
|
+
// Service CPU and memory are percentages of what the task reserved.
|
|
270
|
+
return unit === 'count' && q.metric === 'service' ? 'percent' : unit;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
const METRIC_NOUN: Record<SeriesMetric, string> = {
|
|
274
|
+
requests: 'requests',
|
|
275
|
+
latency: 'latency',
|
|
276
|
+
cold_starts: 'cold starts',
|
|
277
|
+
jobs: 'job runs',
|
|
278
|
+
job_duration: 'job duration',
|
|
279
|
+
custom: 'custom metric',
|
|
280
|
+
rate_limit: 'rate limit checks',
|
|
281
|
+
realtime: 'realtime',
|
|
282
|
+
service: 'service',
|
|
283
|
+
};
|
|
284
|
+
|
|
285
|
+
/**
|
|
286
|
+
* A short label for a query, as charts, alert emails and the CLI show it:
|
|
287
|
+
* `5xx % of requests`, `p95 latency of GET /api/x`, `failed % of job runs`.
|
|
288
|
+
*/
|
|
289
|
+
export function describeQuery(q: SeriesQuery): string {
|
|
290
|
+
const f = q.filter ?? {};
|
|
291
|
+
const noun = METRIC_NOUN[q.metric];
|
|
292
|
+
const scope = [
|
|
293
|
+
f.routes?.length ? (f.routes.length === 1 ? f.routes[0] : `${f.routes.length} routes`) : undefined,
|
|
294
|
+
f.jobs?.length ? (f.jobs.length === 1 ? f.jobs[0] : `${f.jobs.length} jobs`) : undefined,
|
|
295
|
+
].filter(Boolean);
|
|
296
|
+
const of = scope.length ? ` of ${scope.join(', ')}` : '';
|
|
297
|
+
const by = q.groupBy ? ` by ${q.groupBy}` : '';
|
|
298
|
+
const where = q.stage ? ` (${q.stage})` : '';
|
|
299
|
+
const subset = f.status?.length
|
|
300
|
+
? f.status.join('+')
|
|
301
|
+
: f.outcome === 'error'
|
|
302
|
+
? 'failed'
|
|
303
|
+
: f.outcome
|
|
304
|
+
? f.outcome
|
|
305
|
+
: undefined;
|
|
306
|
+
const generic = (): string => {
|
|
307
|
+
if (q.stat === 'percent') return `${subset ?? 'all'} % of ${noun}`;
|
|
308
|
+
if (q.stat === 'rate') return `${subset ? `${subset} ` : ''}${noun} per second`;
|
|
309
|
+
if (q.stat === 'count') return `${subset ? `${subset} ` : ''}${noun}`;
|
|
310
|
+
if (q.stat === 'histogram') return `${noun} distribution`;
|
|
311
|
+
return `${q.stat} ${noun}`;
|
|
312
|
+
};
|
|
313
|
+
let head: string;
|
|
314
|
+
switch (q.metric) {
|
|
315
|
+
case 'custom':
|
|
316
|
+
head = `${q.stat} of ${f.names?.length ? f.names.join(', ') : 'custom metrics'}`;
|
|
317
|
+
break;
|
|
318
|
+
case 'realtime':
|
|
319
|
+
head = `realtime ${f.measure ?? 'events'}`;
|
|
320
|
+
break;
|
|
321
|
+
case 'service':
|
|
322
|
+
head = `${q.stat} ${f.measure ?? 'cpu'}${f.names?.length ? ` of ${f.names.join(', ')}` : ''}`;
|
|
323
|
+
break;
|
|
324
|
+
case 'rate_limit':
|
|
325
|
+
head =
|
|
326
|
+
q.stat === 'percent'
|
|
327
|
+
? `${subset ?? 'denied'} % of rate limit checks`
|
|
328
|
+
: `${subset ? `${subset} ` : ''}rate limit checks`;
|
|
329
|
+
if (f.names?.length) head += ` (${f.names.join(', ')})`;
|
|
330
|
+
break;
|
|
331
|
+
case 'requests':
|
|
332
|
+
case 'latency':
|
|
333
|
+
case 'cold_starts':
|
|
334
|
+
case 'jobs':
|
|
335
|
+
case 'job_duration':
|
|
336
|
+
head = generic();
|
|
337
|
+
break;
|
|
338
|
+
}
|
|
339
|
+
return `${head}${of}${by}${where}`;
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
// ---------------------------------------------------------------------------
|
|
343
|
+
// Charts and filters
|
|
344
|
+
// ---------------------------------------------------------------------------
|
|
345
|
+
|
|
346
|
+
/** A query of an explorer chart, with the id expressions refer to it by (`a`, `b`, …). */
|
|
347
|
+
export const NamedSeriesQuery = Schema.Struct({
|
|
348
|
+
id: Schema.String.check(Schema.isPattern(/^[a-z][a-z0-9]{0,7}$/)),
|
|
349
|
+
...SeriesQuery.fields,
|
|
350
|
+
label: optional(Schema.String),
|
|
351
|
+
/** Charted only through expressions. */
|
|
352
|
+
hidden: optional(Schema.Boolean),
|
|
353
|
+
});
|
|
354
|
+
export type NamedSeriesQuery = typeof NamedSeriesQuery.Type;
|
|
355
|
+
|
|
356
|
+
/** Arithmetic over other queries' values in the same bucket, e.g. `100 * a / b` (evaluated by the console). */
|
|
357
|
+
export const SeriesExpression = Schema.Struct({
|
|
358
|
+
id: Schema.String.check(Schema.isPattern(/^[a-z][a-z0-9]{0,7}$/)),
|
|
359
|
+
expr: Schema.String.check(Schema.isNonEmpty(), Schema.isMaxLength(200)),
|
|
360
|
+
label: optional(Schema.String),
|
|
361
|
+
hidden: optional(Schema.Boolean),
|
|
362
|
+
});
|
|
363
|
+
export type SeriesExpression = typeof SeriesExpression.Type;
|
|
364
|
+
|
|
365
|
+
export const ChartKind = Schema.Literals(['line', 'area', 'bar', 'heatmap']);
|
|
366
|
+
export type ChartKind = typeof ChartKind.Type;
|
|
367
|
+
|
|
368
|
+
export const MetricsView = Schema.Struct({
|
|
369
|
+
kind: Schema.Literal('metrics'),
|
|
370
|
+
queries: Schema.Array(NamedSeriesQuery).check(Schema.isMinLength(1), Schema.isMaxLength(8)),
|
|
371
|
+
expressions: optional(Schema.Array(SeriesExpression).check(Schema.isMaxLength(8))),
|
|
372
|
+
chart: ChartKind,
|
|
373
|
+
scale: optional(Schema.Literals(['linear', 'log'])),
|
|
374
|
+
/** A line drawn across the chart, e.g. an alert threshold. */
|
|
375
|
+
threshold: optional(Schema.Finite),
|
|
376
|
+
});
|
|
377
|
+
export type MetricsView = typeof MetricsView.Type;
|
|
378
|
+
|
|
379
|
+
export const LogLevelName = Schema.Literals(['error', 'warn', 'info', 'debug', 'system']);
|
|
380
|
+
export type LogLevelName = typeof LogLevelName.Type;
|
|
381
|
+
|
|
382
|
+
/**
|
|
383
|
+
* Structured log filters. Any of them makes a search run on Logs Insights
|
|
384
|
+
* (CloudWatch filter patterns can't combine text with JSON fields).
|
|
385
|
+
*/
|
|
386
|
+
export const LogFilters = Schema.Struct({
|
|
387
|
+
levels: optional(Schema.Array(LogLevelName)),
|
|
388
|
+
/** `web`, `worker` or `service:<name>`. */
|
|
389
|
+
streams: optional(Schema.Array(nonEmpty)),
|
|
390
|
+
/** Route patterns (without the method), e.g. `/api/items/:id`. */
|
|
391
|
+
routes: optional(Schema.Array(nonEmpty)),
|
|
392
|
+
status: optional(Schema.Array(StatusClass)),
|
|
393
|
+
/** Deployment ids. */
|
|
394
|
+
revs: optional(Schema.Array(nonEmpty)),
|
|
395
|
+
trace: optional(nonEmpty),
|
|
396
|
+
});
|
|
397
|
+
export type LogFilters = typeof LogFilters.Type;
|
|
398
|
+
|
|
399
|
+
export const TraceFilters = Schema.Struct({
|
|
400
|
+
kind: optional(Schema.Literals(['req', 'job'])),
|
|
401
|
+
/** `METHOD /pattern`. */
|
|
402
|
+
routes: optional(Schema.Array(nonEmpty)),
|
|
403
|
+
/** `kind:name`. */
|
|
404
|
+
jobs: optional(Schema.Array(nonEmpty)),
|
|
405
|
+
/** `error`: 5xx requests and failed jobs; `ok`: the rest. */
|
|
406
|
+
outcome: optional(Schema.Literals(['ok', 'error'])),
|
|
407
|
+
minMs: optional(Schema.Finite),
|
|
408
|
+
/** Only traces whose spans were written (failed, slow or sampled). */
|
|
409
|
+
recorded: optional(Schema.Boolean),
|
|
410
|
+
});
|
|
411
|
+
export type TraceFilters = typeof TraceFilters.Type;
|
|
412
|
+
|
|
413
|
+
// ---------------------------------------------------------------------------
|
|
414
|
+
// Alert rules
|
|
415
|
+
// ---------------------------------------------------------------------------
|
|
416
|
+
|
|
417
|
+
export const AlertState = Schema.Literals(['ok', 'alarm', 'no_data']);
|
|
418
|
+
export type AlertState = typeof AlertState.Type;
|
|
419
|
+
|
|
420
|
+
/** Minutes an alert rule's window can cover. */
|
|
421
|
+
export const ALERT_WINDOWS = [1, 5, 10, 15, 30, 60] as const;
|
|
422
|
+
/** How long the evaluator waits for a minute's telemetry to arrive before reading it. */
|
|
423
|
+
export const ALERT_LAG_MINUTES = 2;
|
|
424
|
+
export const MAX_ALERT_RULES_PER_APP = 25;
|
|
425
|
+
/** How long alert state changes are kept. */
|
|
426
|
+
export const ALERT_HISTORY_DAYS = 90;
|
|
427
|
+
|
|
428
|
+
const name = Schema.Trim.check(Schema.isNonEmpty(), Schema.isMaxLength(80));
|
|
429
|
+
|
|
430
|
+
export const AlertCondition = Schema.Struct({
|
|
431
|
+
op: Schema.Literals(['above', 'below']),
|
|
432
|
+
threshold: Schema.Finite,
|
|
433
|
+
/** The query is summarized over the last this many minutes (sums, shares and histograms of the window). */
|
|
434
|
+
minutes: Schema.Literals(ALERT_WINDOWS),
|
|
435
|
+
});
|
|
436
|
+
export type AlertCondition = typeof AlertCondition.Type;
|
|
437
|
+
|
|
438
|
+
/**
|
|
439
|
+
* A window with no data (no requests behind a percentage or percentile, no
|
|
440
|
+
* values of a custom metric): `ok` and `alarm` treat it as that state,
|
|
441
|
+
* `keep` keeps the current one. Counts are never missing: no events is 0.
|
|
442
|
+
*/
|
|
443
|
+
export const AlertMissingData = Schema.Literals(['ok', 'alarm', 'keep']);
|
|
444
|
+
export type AlertMissingData = typeof AlertMissingData.Type;
|
|
445
|
+
|
|
446
|
+
export const AlertRuleInput = Schema.Struct({
|
|
447
|
+
name,
|
|
448
|
+
stage: nonEmpty,
|
|
449
|
+
query: SeriesQuery,
|
|
450
|
+
condition: AlertCondition,
|
|
451
|
+
missing: AlertMissingData,
|
|
452
|
+
/** Email the platform's alerts topic when the rule fires and when it recovers. */
|
|
453
|
+
notify: Schema.Boolean,
|
|
454
|
+
enabled: Schema.Boolean,
|
|
455
|
+
});
|
|
456
|
+
export type AlertRuleInput = typeof AlertRuleInput.Type;
|
|
457
|
+
|
|
458
|
+
export const AlertRule = Schema.Struct({
|
|
459
|
+
id: Schema.String,
|
|
460
|
+
app: Schema.String,
|
|
461
|
+
...AlertRuleInput.fields,
|
|
462
|
+
state: AlertState,
|
|
463
|
+
/** When `state` last changed. */
|
|
464
|
+
stateSince: optional(Schema.String),
|
|
465
|
+
/** The window's value at the last evaluation (null: no data). */
|
|
466
|
+
value: optional(Schema.NullOr(Schema.Finite)),
|
|
467
|
+
evaluatedAt: optional(Schema.String),
|
|
468
|
+
createdBy: Schema.String,
|
|
469
|
+
createdAt: Schema.String,
|
|
470
|
+
updatedAt: Schema.String,
|
|
471
|
+
});
|
|
472
|
+
export type AlertRule = typeof AlertRule.Type;
|
|
473
|
+
|
|
474
|
+
export const AlertEvent = Schema.Struct({
|
|
475
|
+
ts: Schema.String,
|
|
476
|
+
rule: Schema.String,
|
|
477
|
+
name: Schema.String,
|
|
478
|
+
stage: Schema.String,
|
|
479
|
+
from: AlertState,
|
|
480
|
+
to: AlertState,
|
|
481
|
+
value: Schema.NullOr(Schema.Finite),
|
|
482
|
+
threshold: Schema.Finite,
|
|
483
|
+
});
|
|
484
|
+
export type AlertEvent = typeof AlertEvent.Type;
|
|
485
|
+
|
|
486
|
+
export const AlertHistoryResponse = Schema.Struct({ events: Schema.Array(AlertEvent) });
|
|
487
|
+
export type AlertHistoryResponse = typeof AlertHistoryResponse.Type;
|
|
488
|
+
|
|
489
|
+
export const breaches = (value: number, c: Pick<AlertCondition, 'op' | 'threshold'>): boolean =>
|
|
490
|
+
c.op === 'above' ? value > c.threshold : value < c.threshold;
|
|
491
|
+
|
|
492
|
+
/** The state a rule moves to given its window's value (null: no data). */
|
|
493
|
+
export function nextAlertState(
|
|
494
|
+
current: AlertState,
|
|
495
|
+
value: number | null,
|
|
496
|
+
rule: { readonly condition: AlertCondition; readonly missing: AlertMissingData },
|
|
497
|
+
): AlertState {
|
|
498
|
+
if (value === null) {
|
|
499
|
+
if (rule.missing === 'ok') return 'ok';
|
|
500
|
+
if (rule.missing === 'alarm') return 'alarm';
|
|
501
|
+
return current === 'alarm' || current === 'ok' ? current : 'no_data';
|
|
502
|
+
}
|
|
503
|
+
return breaches(value, rule.condition) ? 'alarm' : 'ok';
|
|
504
|
+
}
|
package/src/index.ts
CHANGED
package/src/platform-api.ts
CHANGED
|
@@ -40,11 +40,16 @@ import {
|
|
|
40
40
|
EdgeFloorResponse,
|
|
41
41
|
EmailStatsResponse,
|
|
42
42
|
ErrorGroup,
|
|
43
|
+
ErrorOccurrencesResponse,
|
|
43
44
|
ErrorStatus,
|
|
45
|
+
InsightsRequest,
|
|
46
|
+
InsightsResponse,
|
|
44
47
|
JobsResponse,
|
|
45
48
|
LimitsResponse,
|
|
49
|
+
LogContextResponse,
|
|
46
50
|
LogLine,
|
|
47
51
|
LogsResponse,
|
|
52
|
+
LogStatsResponse,
|
|
48
53
|
MeResponse,
|
|
49
54
|
MetricsResponse,
|
|
50
55
|
PutSecretRequest,
|
|
@@ -54,6 +59,7 @@ import {
|
|
|
54
59
|
RollbackResponse,
|
|
55
60
|
RouteStats,
|
|
56
61
|
SecretsResponse,
|
|
62
|
+
SeriesResponse,
|
|
57
63
|
ServiceActionResponse,
|
|
58
64
|
ServicesResponse,
|
|
59
65
|
StageDestroyed,
|
|
@@ -63,12 +69,21 @@ import {
|
|
|
63
69
|
StorageResponse,
|
|
64
70
|
SuppressedResponse,
|
|
65
71
|
TraceResponse,
|
|
72
|
+
TracesResponse,
|
|
66
73
|
UpdateAppRequest,
|
|
67
74
|
UpdateErrorRequest,
|
|
68
75
|
UptimePoint,
|
|
69
76
|
UrlResponse,
|
|
70
77
|
} from './api.ts';
|
|
71
78
|
import type { MemberRole } from './config.ts';
|
|
79
|
+
import {
|
|
80
|
+
AlertHistoryResponse,
|
|
81
|
+
AlertRule,
|
|
82
|
+
AlertRuleInput,
|
|
83
|
+
LogFilters,
|
|
84
|
+
SeriesQuery,
|
|
85
|
+
TraceFilters,
|
|
86
|
+
} from './explore.ts';
|
|
72
87
|
|
|
73
88
|
// ---------------------------------------------------------------------------
|
|
74
89
|
// Errors: one class per status, each encoded as `{ error: { code, message } }`
|
|
@@ -445,6 +460,8 @@ export class ObserveApi extends HttpApiGroup.make('observe')
|
|
|
445
460
|
q: Schema.optional(Schema.String),
|
|
446
461
|
/** `web`, `worker` or `service:<name>`. */
|
|
447
462
|
stream: Schema.optional(Schema.String),
|
|
463
|
+
/** Structured filters as JSON (`LogFilters`); any of them runs the search on Logs Insights. */
|
|
464
|
+
f: Schema.optional(Schema.fromJsonString(LogFilters)),
|
|
448
465
|
limit,
|
|
449
466
|
next: Schema.optional(Schema.String),
|
|
450
467
|
},
|
|
@@ -463,6 +480,8 @@ export class ObserveApi extends HttpApiGroup.make('observe')
|
|
|
463
480
|
q: Schema.optional(Schema.String),
|
|
464
481
|
/** `web`, `worker` or `service:<name>`. */
|
|
465
482
|
stream: Schema.optional(Schema.String),
|
|
483
|
+
/** Structured filters as JSON (`LogFilters`), applied to the live lines. */
|
|
484
|
+
f: Schema.optional(Schema.fromJsonString(LogFilters)),
|
|
466
485
|
},
|
|
467
486
|
success: HttpApiSchema.StreamSse({ events: TailEvent, keepAlive: '20 seconds' }),
|
|
468
487
|
error: errors,
|
|
@@ -473,6 +492,101 @@ export class ObserveApi extends HttpApiGroup.make('observe')
|
|
|
473
492
|
success: TraceResponse,
|
|
474
493
|
error: errors,
|
|
475
494
|
}),
|
|
495
|
+
/**
|
|
496
|
+
* The explorer's query (`SeriesQuery`, as JSON in `q`) over the range. `res`
|
|
497
|
+
* may also be `5m`, `10m`, `15m` or `30m` (sums of minute rollups); by
|
|
498
|
+
* default about 150 buckets.
|
|
499
|
+
*/
|
|
500
|
+
HttpApiEndpoint.get('series', '/apps/:app/series', {
|
|
501
|
+
params: app,
|
|
502
|
+
query: { ...rangeQuery, q: Schema.fromJsonString(SeriesQuery) },
|
|
503
|
+
success: SeriesResponse,
|
|
504
|
+
error: errors,
|
|
505
|
+
}),
|
|
506
|
+
/** Requests and jobs that started traces, newest first (Logs Insights over their root lines). */
|
|
507
|
+
HttpApiEndpoint.get('traces', '/apps/:app/traces', {
|
|
508
|
+
params: app,
|
|
509
|
+
query: { ...rangeQuery, f: Schema.optional(Schema.fromJsonString(TraceFilters)), limit },
|
|
510
|
+
success: TracesResponse,
|
|
511
|
+
error: errors,
|
|
512
|
+
}),
|
|
513
|
+
/** Lines per bucket by level and the commonest field values, for the same search as `logs` (Logs Insights). */
|
|
514
|
+
HttpApiEndpoint.get('logStats', '/apps/:app/logs/stats', {
|
|
515
|
+
params: app,
|
|
516
|
+
query: {
|
|
517
|
+
...rangeQuery,
|
|
518
|
+
q: Schema.optional(Schema.String),
|
|
519
|
+
stream: Schema.optional(Schema.String),
|
|
520
|
+
f: Schema.optional(Schema.fromJsonString(LogFilters)),
|
|
521
|
+
},
|
|
522
|
+
success: LogStatsResponse,
|
|
523
|
+
error: errors,
|
|
524
|
+
}),
|
|
525
|
+
/** The lines just before and after one line (`ts`, epoch ms) of one stream. */
|
|
526
|
+
HttpApiEndpoint.get('logContext', '/apps/:app/logs/context', {
|
|
527
|
+
params: app,
|
|
528
|
+
query: {
|
|
529
|
+
...stageQuery,
|
|
530
|
+
stream: Schema.String,
|
|
531
|
+
ts: Schema.String,
|
|
532
|
+
before: limit,
|
|
533
|
+
after: limit,
|
|
534
|
+
},
|
|
535
|
+
success: LogContextResponse,
|
|
536
|
+
error: errors,
|
|
537
|
+
}),
|
|
538
|
+
/** Runs a Logs Insights query on the stage's log groups and waits for it (up to 25 s). */
|
|
539
|
+
HttpApiEndpoint.post('insights', '/apps/:app/insights', {
|
|
540
|
+
params: app,
|
|
541
|
+
payload: InsightsRequest,
|
|
542
|
+
success: InsightsResponse,
|
|
543
|
+
error: errors,
|
|
544
|
+
}),
|
|
545
|
+
/** An error group's events over the range (Logs Insights). */
|
|
546
|
+
HttpApiEndpoint.get('errorOccurrences', '/apps/:app/errors/:fingerprint/occurrences', {
|
|
547
|
+
params: { ...app, fingerprint: Schema.String },
|
|
548
|
+
query: rangeQuery,
|
|
549
|
+
success: ErrorOccurrencesResponse,
|
|
550
|
+
error: errors,
|
|
551
|
+
}),
|
|
552
|
+
)
|
|
553
|
+
.middleware(Authenticated) {}
|
|
554
|
+
|
|
555
|
+
/** Alert rules on an app's stages, evaluated every minute by the control plane. */
|
|
556
|
+
export class AlertsApi extends HttpApiGroup.make('alerts')
|
|
557
|
+
.add(
|
|
558
|
+
/** Every stage's rules, or `?stage=`'s. */
|
|
559
|
+
HttpApiEndpoint.get('list', '/apps/:app/alerts', {
|
|
560
|
+
params: app,
|
|
561
|
+
query: { stage: Schema.optional(Schema.String) },
|
|
562
|
+
success: Schema.Array(AlertRule),
|
|
563
|
+
error: errors,
|
|
564
|
+
}),
|
|
565
|
+
HttpApiEndpoint.post('create', '/apps/:app/alerts', {
|
|
566
|
+
params: app,
|
|
567
|
+
payload: AlertRuleInput,
|
|
568
|
+
success: AlertRule.pipe(HttpApiSchema.status(201)),
|
|
569
|
+
error: errors,
|
|
570
|
+
}),
|
|
571
|
+
/** Replaces the rule's settings; a changed query or condition starts it over in `no_data`. */
|
|
572
|
+
HttpApiEndpoint.put('update', '/apps/:app/alerts/:id', {
|
|
573
|
+
params: { ...app, id: Schema.String },
|
|
574
|
+
payload: AlertRuleInput,
|
|
575
|
+
success: AlertRule,
|
|
576
|
+
error: errors,
|
|
577
|
+
}),
|
|
578
|
+
HttpApiEndpoint.delete('remove', '/apps/:app/alerts/:id', {
|
|
579
|
+
params: { ...app, id: Schema.String },
|
|
580
|
+
success: HttpApiSchema.NoContent,
|
|
581
|
+
error: errors,
|
|
582
|
+
}),
|
|
583
|
+
/** State changes of the app's rules (or `?stage=`'s) in the range, newest first. */
|
|
584
|
+
HttpApiEndpoint.get('history', '/apps/:app/alerts/history', {
|
|
585
|
+
params: app,
|
|
586
|
+
query: { stage: Schema.optional(Schema.String), ...timeQuery },
|
|
587
|
+
success: AlertHistoryResponse,
|
|
588
|
+
error: errors,
|
|
589
|
+
}),
|
|
476
590
|
)
|
|
477
591
|
.middleware(Authenticated) {}
|
|
478
592
|
|
|
@@ -623,6 +737,7 @@ export class PlatformApi extends HttpApi.make('platform')
|
|
|
623
737
|
.add(StagesApi)
|
|
624
738
|
.add(DeploymentsApi)
|
|
625
739
|
.add(ObserveApi)
|
|
740
|
+
.add(AlertsApi)
|
|
626
741
|
.add(ManageApi)
|
|
627
742
|
.add(AdminApi)
|
|
628
743
|
.prefix('/v1')
|