@ericminassian/platform-core 0.4.0 → 0.5.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.
Files changed (53) hide show
  1. package/dist/api.d.ts +367 -226
  2. package/dist/api.js +148 -92
  3. package/dist/api.js.map +1 -1
  4. package/dist/config.d.ts +0 -2
  5. package/dist/config.js.map +1 -1
  6. package/dist/constants.d.ts +0 -17
  7. package/dist/constants.js +0 -17
  8. package/dist/constants.js.map +1 -1
  9. package/dist/explore.d.ts +367 -0
  10. package/dist/explore.js +440 -0
  11. package/dist/explore.js.map +1 -0
  12. package/dist/index.d.ts +1 -1
  13. package/dist/index.js +1 -1
  14. package/dist/index.js.map +1 -1
  15. package/dist/jobs.d.ts +1 -1
  16. package/dist/jobs.js +1 -1
  17. package/dist/manifest.d.ts +10 -47
  18. package/dist/manifest.js +7 -15
  19. package/dist/manifest.js.map +1 -1
  20. package/dist/naming.d.ts +7 -23
  21. package/dist/naming.js +7 -23
  22. package/dist/naming.js.map +1 -1
  23. package/dist/platform-api.d.ts +3511 -2211
  24. package/dist/platform-api.js +117 -36
  25. package/dist/platform-api.js.map +1 -1
  26. package/dist/runtime-config.d.ts +0 -20
  27. package/dist/runtime-config.js.map +1 -1
  28. package/dist/storage.d.ts +10 -0
  29. package/dist/storage.js +10 -0
  30. package/dist/storage.js.map +1 -1
  31. package/dist/telemetry.d.ts +52 -27
  32. package/dist/telemetry.js +67 -19
  33. package/dist/telemetry.js.map +1 -1
  34. package/dist/web-compute.js +2 -1
  35. package/dist/web-compute.js.map +1 -1
  36. package/package.json +1 -1
  37. package/src/api.ts +176 -110
  38. package/src/config.ts +0 -2
  39. package/src/constants.ts +0 -19
  40. package/src/explore.ts +504 -0
  41. package/src/index.ts +1 -1
  42. package/src/jobs.ts +1 -1
  43. package/src/manifest.ts +15 -48
  44. package/src/naming.ts +7 -25
  45. package/src/platform-api.ts +140 -38
  46. package/src/runtime-config.ts +0 -21
  47. package/src/storage.ts +11 -0
  48. package/src/telemetry.ts +69 -19
  49. package/src/web-compute.ts +3 -1
  50. package/dist/compute.d.ts +0 -52
  51. package/dist/compute.js +0 -65
  52. package/dist/compute.js.map +0 -1
  53. package/src/compute.ts +0 -86
package/src/constants.ts CHANGED
@@ -86,8 +86,6 @@ export const TAGS = {
86
86
  managed: 'platform:managed',
87
87
  app: 'platform:app',
88
88
  stage: 'platform:stage',
89
- /** On resources built per deployment (a service's task definition), so it can be found again. */
90
- deployment: 'platform:deployment',
91
89
  } as const;
92
90
 
93
91
  /** The production stage. Its host has no stage suffix. */
@@ -97,20 +95,3 @@ export const LOCAL_STAGE = 'local';
97
95
 
98
96
  /** Lambda runtime for Web Functions, request-mode servers and worker (Event) Functions. */
99
97
  export const NODE_RUNTIME = 'nodejs24.x';
100
-
101
- /**
102
- * Base of every container image the platform builds: Node.js 24 on Debian
103
- * slim, linux/arm64, pinned to one image manifest (not the multi-platform
104
- * index). The engine copies it from ECR Public into the platform's
105
- * repository the first time a deploy needs it, so bumping it is a deliberate
106
- * change: look up the arm64 entry of the tag's index and update both fields.
107
- */
108
- export const CONTAINER_BASE_IMAGE = {
109
- registry: 'public.ecr.aws',
110
- repository: 'docker/library/node',
111
- tag: '24-slim',
112
- digest: 'sha256:5f8fabfed57b75127de2f584593d67a9e8c90e6b0f65652871f9ef0f759c0299',
113
- } as const;
114
-
115
- /** Environment variable naming the service a container runs (`ais`). */
116
- export const SERVICE_ENV = 'PLATFORM_SERVICE';
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`, which comes from CloudWatch on
8
+ * demand and so can't be watched by alert rules. Neither can
9
+ * `page_views` and `edge_requests`: the router's access log they come from
10
+ * arrives up to an hour late.
11
+ */
12
+ import { Schema } from 'effect';
13
+
14
+ const optional = Schema.optional;
15
+
16
+ // ---------------------------------------------------------------------------
17
+ // Resolution
18
+ // ---------------------------------------------------------------------------
19
+
20
+ /**
21
+ * Bucket sizes a query can ask for. `1m`, `1h` and `1d` are stored; the
22
+ * others are sums of 1-minute rollups (latency histograms add), so they
23
+ * reach back only as far as minute rollups are kept.
24
+ */
25
+ export const QueryResolution = Schema.Literals(['1m', '5m', '10m', '15m', '30m', '1h', '1d']);
26
+ export type QueryResolution = typeof QueryResolution.Type;
27
+
28
+ export const QUERY_RESOLUTION_MS: Record<QueryResolution, number> = {
29
+ '1m': 60_000,
30
+ '5m': 300_000,
31
+ '10m': 600_000,
32
+ '15m': 900_000,
33
+ '30m': 1_800_000,
34
+ '1h': 3_600_000,
35
+ '1d': 86_400_000,
36
+ };
37
+
38
+ /** About this many buckets per chart when the caller doesn't pick a resolution. */
39
+ export const TARGET_POINTS = 150;
40
+
41
+ /**
42
+ * The smallest resolution that keeps `from`..`to` near `TARGET_POINTS`
43
+ * buckets, given how far back minute rollups reach (`minuteHorizonMs` before
44
+ * `now`): a range starting before that horizon can't be built from 1-minute
45
+ * rows, so it uses hours (or days past 14 days).
46
+ */
47
+ export function autoQueryResolution(
48
+ from: number,
49
+ to: number,
50
+ now: number,
51
+ minuteHorizonMs: number,
52
+ ): QueryResolution {
53
+ const span = Math.max(to - from, 60_000);
54
+ const minuteOk = from >= now - minuteHorizonMs;
55
+ const ladder: readonly QueryResolution[] = minuteOk
56
+ ? ['1m', '5m', '10m', '15m', '30m', '1h', '1d']
57
+ : ['1h', '1d'];
58
+ for (const res of ladder) if (span / QUERY_RESOLUTION_MS[res] <= TARGET_POINTS * 1.5) return res;
59
+ return '1d';
60
+ }
61
+
62
+ // ---------------------------------------------------------------------------
63
+ // Queries
64
+ // ---------------------------------------------------------------------------
65
+
66
+ /**
67
+ * What a query measures:
68
+ * - `requests`: HTTP requests (stage-wide, or of routes) the stage's server handled
69
+ * - `page_views`: pages the router served for the stage's host (`isPageView`)
70
+ * - `edge_requests`: every request the router served for it: files, server, stores
71
+ * - `latency`: their duration
72
+ * - `cold_starts`: requests served by a fresh server process
73
+ * - `jobs`: queue, event, cron and invoke runs
74
+ * - `job_duration`: their duration
75
+ * - `custom`: the app's `Metrics.count`/`value` series
76
+ * - `rate_limit`: `RateLimits` checks
77
+ * - `realtime`: AppSync Events activity (CloudWatch)
78
+ */
79
+ export const SeriesMetric = Schema.Literals([
80
+ 'requests',
81
+ 'page_views',
82
+ 'edge_requests',
83
+ 'latency',
84
+ 'cold_starts',
85
+ 'jobs',
86
+ 'job_duration',
87
+ 'custom',
88
+ 'rate_limit',
89
+ 'realtime',
90
+ ]);
91
+ export type SeriesMetric = typeof SeriesMetric.Type;
92
+
93
+ /**
94
+ * How each bucket is summarized:
95
+ * - `count`: how many (requests, runs, checks, recorded values)
96
+ * - `rate`: `count` per second
97
+ * - `percent`: the share, 0–100, of the metric's events that match the
98
+ * status or outcome filter, among all of them in the bucket (5xx % of
99
+ * requests, failed % of runs, denied % of checks)
100
+ * - `sum`, `avg`, `max`: of recorded values (custom metrics, realtime)
101
+ * - `p50`…`p99`: latency percentiles, from the rollups' fixed-bucket histograms
102
+ * (each is the upper bound of the bucket holding it)
103
+ * - `histogram`: every latency bucket's count, for heatmaps
104
+ */
105
+ export const SeriesStat = Schema.Literals([
106
+ 'count',
107
+ 'rate',
108
+ 'percent',
109
+ 'sum',
110
+ 'avg',
111
+ 'max',
112
+ 'p50',
113
+ 'p90',
114
+ 'p95',
115
+ 'p99',
116
+ 'histogram',
117
+ ]);
118
+ export type SeriesStat = typeof SeriesStat.Type;
119
+
120
+ export const StatusClass = Schema.Literals(['2xx', '3xx', '4xx', '5xx']);
121
+ export type StatusClass = typeof StatusClass.Type;
122
+ export const STATUS_CLASSES: readonly StatusClass[] = ['2xx', '3xx', '4xx', '5xx'];
123
+
124
+ /** Splits a query into one line per value of this dimension. */
125
+ export const SeriesGroupBy = Schema.Literals(['status', 'route', 'job', 'outcome', 'name']);
126
+ export type SeriesGroupBy = typeof SeriesGroupBy.Type;
127
+
128
+ export const SeriesOutcome = Schema.Literals(['ok', 'error', 'allowed', 'denied']);
129
+ export type SeriesOutcome = typeof SeriesOutcome.Type;
130
+
131
+ const nonEmpty = Schema.String.check(Schema.isNonEmpty());
132
+
133
+ export const SeriesFilter = Schema.Struct({
134
+ /** Routes as rollups key them: `METHOD /pattern`, e.g. `GET /api/items/:id`. */
135
+ routes: optional(Schema.Array(nonEmpty)),
136
+ /** `requests` and `edge_requests` only. */
137
+ status: optional(Schema.Array(StatusClass)),
138
+ /** Jobs as `kind:name`, e.g. `queue:refresh`, `cron:digest`. */
139
+ jobs: optional(Schema.Array(nonEmpty)),
140
+ /** Custom metric names or rate limit names. */
141
+ names: optional(Schema.Array(nonEmpty)),
142
+ /** `jobs`: `ok` or `error`; `rate_limit`: `allowed` or `denied`. */
143
+ outcome: optional(SeriesOutcome),
144
+ /** `realtime`: `events`, `publishes`, `subscribes` or `errors`. */
145
+ measure: optional(nonEmpty),
146
+ });
147
+ export type SeriesFilter = typeof SeriesFilter.Type;
148
+
149
+ export const SeriesQuery = Schema.Struct({
150
+ metric: SeriesMetric,
151
+ stat: SeriesStat,
152
+ filter: optional(SeriesFilter),
153
+ groupBy: optional(SeriesGroupBy),
154
+ /** Another stage than the page's. */
155
+ stage: optional(nonEmpty),
156
+ });
157
+ export type SeriesQuery = typeof SeriesQuery.Type;
158
+
159
+ /** The statistics each metric answers; the first is its default. */
160
+ export const METRIC_STATS: Record<SeriesMetric, readonly SeriesStat[]> = {
161
+ requests: ['count', 'rate', 'percent'],
162
+ page_views: ['count', 'rate'],
163
+ edge_requests: ['count', 'rate', 'percent'],
164
+ latency: ['p95', 'p50', 'p90', 'p99', 'histogram'],
165
+ cold_starts: ['count', 'percent'],
166
+ jobs: ['count', 'rate', 'percent'],
167
+ job_duration: ['p95', 'p50', 'p90', 'p99', 'histogram'],
168
+ custom: ['sum', 'avg', 'count', 'max'],
169
+ rate_limit: ['count', 'percent'],
170
+ realtime: ['sum'],
171
+ };
172
+
173
+ /** The dimensions each metric can be grouped by. */
174
+ export const METRIC_GROUP_BY: Record<SeriesMetric, readonly SeriesGroupBy[]> = {
175
+ requests: ['status', 'route'],
176
+ page_views: [],
177
+ edge_requests: ['status'],
178
+ latency: ['route'],
179
+ cold_starts: [],
180
+ jobs: ['job', 'outcome'],
181
+ job_duration: ['job'],
182
+ custom: ['name'],
183
+ rate_limit: ['name', 'outcome'],
184
+ realtime: [],
185
+ };
186
+
187
+ /** Metrics alert rules can watch: those read from rollups written as their events happen. */
188
+ export const ALERT_METRICS: readonly SeriesMetric[] = [
189
+ 'requests',
190
+ 'latency',
191
+ 'cold_starts',
192
+ 'jobs',
193
+ 'job_duration',
194
+ 'custom',
195
+ 'rate_limit',
196
+ ];
197
+
198
+ export const REALTIME_MEASURES = ['events', 'publishes', 'subscribes', 'errors'] as const;
199
+
200
+ /**
201
+ * Why a query can't be answered, or undefined when it can. `alert` also
202
+ * refuses what an alert rule can't watch: CloudWatch metrics, histograms,
203
+ * groups, and another stage than the rule's.
204
+ */
205
+ export function checkSeriesQuery(
206
+ q: SeriesQuery,
207
+ options: { readonly alert?: boolean } = {},
208
+ ): string | undefined {
209
+ if (!METRIC_STATS[q.metric].includes(q.stat)) {
210
+ return `${q.metric} answers ${METRIC_STATS[q.metric].join(', ')}, not ${q.stat}`;
211
+ }
212
+ if (q.groupBy && !METRIC_GROUP_BY[q.metric].includes(q.groupBy)) {
213
+ const groups = METRIC_GROUP_BY[q.metric];
214
+ return groups.length
215
+ ? `${q.metric} can be grouped by ${groups.join(' or ')}, not ${q.groupBy}`
216
+ : `${q.metric} can't be grouped`;
217
+ }
218
+ const f = q.filter ?? {};
219
+ if (f.status?.length && q.metric !== 'requests' && q.metric !== 'edge_requests') {
220
+ return 'only requests and edge requests filter by status';
221
+ }
222
+ if (f.routes?.length && q.metric !== 'requests' && q.metric !== 'latency' && q.metric !== 'cold_starts') {
223
+ return 'only requests, latency and cold starts filter by route';
224
+ }
225
+ if (f.jobs?.length && q.metric !== 'jobs' && q.metric !== 'job_duration') return 'only jobs filter by job';
226
+ if (f.outcome) {
227
+ const allowed =
228
+ q.metric === 'jobs' ? ['ok', 'error'] : q.metric === 'rate_limit' ? ['allowed', 'denied'] : [];
229
+ if (!allowed.includes(f.outcome)) {
230
+ return allowed.length
231
+ ? `${q.metric} outcomes are ${allowed.join(' or ')}`
232
+ : `${q.metric} doesn't filter by outcome`;
233
+ }
234
+ }
235
+ if (f.names?.length && q.metric !== 'custom' && q.metric !== 'rate_limit') {
236
+ return 'only custom metrics and rate limits filter by name';
237
+ }
238
+ if (q.metric === 'custom' && !f.names?.length && q.groupBy !== 'name') {
239
+ return 'a custom metric query names its metric, or groups by name';
240
+ }
241
+ if (q.metric === 'realtime' && !REALTIME_MEASURES.some((m) => m === f.measure)) {
242
+ return `realtime measures one of ${REALTIME_MEASURES.join(', ')}`;
243
+ }
244
+ if (q.metric !== 'realtime' && f.measure) return 'only realtime queries take a measure';
245
+ if (options.alert) {
246
+ if (!ALERT_METRICS.includes(q.metric)) return `alert rules can't watch ${q.metric}`;
247
+ if (q.stat === 'histogram') return 'alert rules watch one number, not a histogram';
248
+ if (q.groupBy) return 'alert rules watch one series; filter instead of grouping';
249
+ if (q.stage) return "an alert rule's query reads the rule's own stage";
250
+ }
251
+ return undefined;
252
+ }
253
+
254
+ /** The unit a query's values are in (a custom metric's own unit comes with its series). */
255
+ const STAT_UNIT: Record<SeriesStat, string> = {
256
+ count: 'count',
257
+ rate: 'per_second',
258
+ percent: 'percent',
259
+ sum: 'count',
260
+ avg: 'count',
261
+ max: 'count',
262
+ p50: 'ms',
263
+ p90: 'ms',
264
+ p95: 'ms',
265
+ p99: 'ms',
266
+ histogram: 'ms',
267
+ };
268
+
269
+ export function seriesUnit(q: Pick<SeriesQuery, 'metric' | 'stat' | 'filter'>): string {
270
+ return STAT_UNIT[q.stat];
271
+ }
272
+
273
+ const METRIC_NOUN: Record<SeriesMetric, string> = {
274
+ requests: 'requests',
275
+ page_views: 'page views',
276
+ edge_requests: 'edge requests',
277
+ latency: 'latency',
278
+ cold_starts: 'cold starts',
279
+ jobs: 'job runs',
280
+ job_duration: 'job duration',
281
+ custom: 'custom metric',
282
+ rate_limit: 'rate limit checks',
283
+ realtime: 'realtime',
284
+ };
285
+
286
+ /**
287
+ * A short label for a query, as charts, alert emails and the CLI show it:
288
+ * `5xx % of requests`, `p95 latency of GET /api/x`, `failed % of job runs`.
289
+ */
290
+ export function describeQuery(q: SeriesQuery): string {
291
+ const f = q.filter ?? {};
292
+ const noun = METRIC_NOUN[q.metric];
293
+ const scope = [
294
+ f.routes?.length ? (f.routes.length === 1 ? f.routes[0] : `${f.routes.length} routes`) : undefined,
295
+ f.jobs?.length ? (f.jobs.length === 1 ? f.jobs[0] : `${f.jobs.length} jobs`) : undefined,
296
+ ].filter(Boolean);
297
+ const of = scope.length ? ` of ${scope.join(', ')}` : '';
298
+ const by = q.groupBy ? ` by ${q.groupBy}` : '';
299
+ const where = q.stage ? ` (${q.stage})` : '';
300
+ const subset = f.status?.length
301
+ ? f.status.join('+')
302
+ : f.outcome === 'error'
303
+ ? 'failed'
304
+ : f.outcome
305
+ ? f.outcome
306
+ : undefined;
307
+ const generic = (): string => {
308
+ if (q.stat === 'percent') return `${subset ?? 'all'} % of ${noun}`;
309
+ if (q.stat === 'rate') return `${subset ? `${subset} ` : ''}${noun} per second`;
310
+ if (q.stat === 'count') return `${subset ? `${subset} ` : ''}${noun}`;
311
+ if (q.stat === 'histogram') return `${noun} distribution`;
312
+ return `${q.stat} ${noun}`;
313
+ };
314
+ let head: string;
315
+ switch (q.metric) {
316
+ case 'custom':
317
+ head = `${q.stat} of ${f.names?.length ? f.names.join(', ') : 'custom metrics'}`;
318
+ break;
319
+ case 'realtime':
320
+ head = `realtime ${f.measure ?? 'events'}`;
321
+ break;
322
+ case 'rate_limit':
323
+ head =
324
+ q.stat === 'percent'
325
+ ? `${subset ?? 'denied'} % of rate limit checks`
326
+ : `${subset ? `${subset} ` : ''}rate limit checks`;
327
+ if (f.names?.length) head += ` (${f.names.join(', ')})`;
328
+ break;
329
+ case 'requests':
330
+ case 'page_views':
331
+ case 'edge_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` or `worker`. */
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
@@ -1,11 +1,11 @@
1
1
  export * from './api.ts';
2
2
  export * from './auth.ts';
3
3
  export * from './bindings.ts';
4
- export * from './compute.ts';
5
4
  export * from './config.ts';
6
5
  export * from './constants.ts';
7
6
  export * from './cron.ts';
8
7
  export * from './email.ts';
8
+ export * from './explore.ts';
9
9
  export * from './ids.ts';
10
10
  export * from './jobs.ts';
11
11
  export * from './manifest.ts';
package/src/jobs.ts CHANGED
@@ -70,7 +70,7 @@ export const handlerKey = (kind: HandlerKind, name: string): string => `${kind}:
70
70
  /**
71
71
  * Name of the one-shot schedule for a retry or delayed send (≤ 64 chars of
72
72
  * Scheduler's alphabet). It leads with `_`, which no cron key (a cron's own
73
- * schedule) or service stop schedule (`<key>--stop`) starts with, then the
73
+ * schedule) starts with, then the
74
74
  * kind and queue or cron key, so the console can count what's waiting per
75
75
  * queue with a name prefix. Event types can be long and contain `:`, so they
76
76
  * are hashed.
package/src/manifest.ts CHANGED
@@ -1,5 +1,4 @@
1
1
  import { Effect, Schema } from 'effect';
2
- import { FARGATE_CPUS, type FargateCpu, fargateSizeIssue } from './compute.ts';
3
2
  import { validateCron } from './cron.ts';
4
3
  import { EMAIL_DEFAULT_DAILY_LIMIT, EMAIL_NAME_MESSAGE, EMAIL_NAME_PATTERN } from './email.ts';
5
4
  import { DEFAULT_ATTEMPTS, MAX_ATTEMPTS } from './jobs.ts';
@@ -133,19 +132,6 @@ const StoreSchema = Schema.Struct({
133
132
  public: Schema.Boolean.pipe(orElse(false)),
134
133
  expireAfterDays: Schema.optional(intBetween(1, 3650)),
135
134
  });
136
- const ServiceSchema = Schema.Struct({
137
- entry: Schema.String,
138
- cpu: Schema.Literals(FARGATE_CPUS).pipe(orElse(0.25)),
139
- memoryMb: Schema.Int.pipe(orElse(512)),
140
- spot: Schema.Boolean.pipe(orElse(true)),
141
- previewMinutes: intBetween(0, 1440).pipe(orElse(30)),
142
- }).check(
143
- Schema.makeFilter((s) => {
144
- const issue = fargateSizeIssue(s.cpu, s.memoryMb);
145
- return issue ? [{ path: ['memoryMb'], issue }] : undefined;
146
- }),
147
- );
148
-
149
135
  const RealtimeSubscribeSchema = Schema.Literals(['public', 'signed-in']);
150
136
 
151
137
  const EmailSchema = Schema.Union([
@@ -171,6 +157,7 @@ export const ManifestSchema = Schema.Struct({
171
157
  Schema.isPattern(APP_NAME_PATTERN, { message: 'must be 3-30 chars of a-z, 0-9, single hyphens' }),
172
158
  ),
173
159
  description: Schema.optional(Schema.String.check(Schema.isMaxLength(200))),
160
+ listed: Schema.Boolean.pipe(orElse(true)),
174
161
  web: Schema.optional(WebSchema),
175
162
  worker: Schema.optional(WorkerSchema),
176
163
  auth: AuthSchema.pipe(orElse(false)),
@@ -191,7 +178,11 @@ export const ManifestSchema = Schema.Struct({
191
178
  env: recordOf(ENV_NAME_PATTERN, Schema.String).pipe(orElse({})),
192
179
  realtime: Schema.optional(RealtimeSchema),
193
180
  email: EmailSchema.pipe(orElse(false)),
194
- services: recordOf(RESOURCE_KEY_PATTERN, ServiceSchema, RESOURCE_KEY_MESSAGE).pipe(orElse({})),
181
+ // Long-running services ran on Fargate until 0.5.0. Each paid for its vCPU, memory and public
182
+ // IPv4 address all month, the only part of an app billed while idle.
183
+ services: removed(
184
+ 'removed in 0.5.0: hold a connection from a cron instead, listening for a while each run',
185
+ ),
195
186
  }).check(
196
187
  Schema.makeFilter((m) => {
197
188
  if (!m.realtime) return undefined;
@@ -336,34 +327,6 @@ export interface StoreConfig {
336
327
  expireAfterDays?: number;
337
328
  }
338
329
 
339
- /**
340
- * A long-running process: it holds connections open (WebSocket or
341
- * server-sent-event sources) and writes what it receives to the db, storage,
342
- * queues or realtime. One instance per stage, restarted when it crashes and
343
- * replaced on each deploy. Unlike everything else it is billed while it runs:
344
- * about $6 a month at the default size on Spot.
345
- */
346
- export interface ServiceConfig {
347
- /** Module whose default export is `defineService(...)` from `@ericminassian/platform`. */
348
- entry: string;
349
- /** vCPUs: 0.25 (default), 0.5, 1, 2 or 4. */
350
- cpu?: FargateCpu;
351
- /**
352
- * Memory in MB, one of the sizes Fargate pairs with `cpu`: 512, 1024 or
353
- * 2048 for 0.25 vCPU; 1024-4096 for 0.5; 2048-8192 for 1; 4096-16384 for 2;
354
- * 8192-30720 for 4 (steps of 1024). Default 512.
355
- */
356
- memoryMb?: number;
357
- /**
358
- * Run on Fargate Spot, about 70% cheaper. AWS may reclaim it with two
359
- * minutes' notice (the service gets SIGTERM) and the platform starts a
360
- * replacement. Default `true`.
361
- */
362
- spot?: boolean;
363
- /** Minutes a preview stage runs it after each deploy before stopping it; 0 means never. Default 30. */
364
- previewMinutes?: number;
365
- }
366
-
367
330
  /**
368
331
  * Live updates pushed to browsers. The server and worker publish; browsers
369
332
  * subscribe (they never publish). Events aren't stored: a browser that was
@@ -401,7 +364,13 @@ export interface EmailConfig {
401
364
  export interface AppConfig {
402
365
  /** 3-30 chars of a-z, 0-9 and single hyphens; also the app's host name. */
403
366
  name: string;
367
+ /** One line, up to 200 chars. The public directory shows it next to the app. */
404
368
  description?: string;
369
+ /**
370
+ * Whether the platform's public directory (`GET /v1/public/apps`) lists the
371
+ * prod stage, with its page views. Default true; `false` keeps the app out.
372
+ */
373
+ listed?: boolean;
405
374
  web?: WebConfig;
406
375
  /** Present automatically when any queue, event or cron exists. */
407
376
  worker?: WorkerConfig;
@@ -430,8 +399,6 @@ export interface AppConfig {
430
399
  realtime?: RealtimeConfig;
431
400
  /** Send email with the SDK's `Email` service: `true`, or `{ name, dailyLimit }`. */
432
401
  email?: boolean | EmailConfig;
433
- /** Long-running processes, e.g. stream ingest. Keys are 1-20 chars of a-z, 0-9 and hyphens. */
434
- services?: { readonly [name: string]: ServiceConfig };
435
402
  }
436
403
 
437
404
  /**
@@ -483,6 +450,8 @@ export function channel<Event>(): ChannelConfig<Event> {
483
450
  export const ResolvedManifest = Schema.Struct({
484
451
  name: Schema.String,
485
452
  description: Schema.optional(Schema.String),
453
+ /** Listed in the public directory (prod only). Deployments recorded before it existed were. */
454
+ listed: Schema.Boolean.pipe(orElse(true)),
486
455
  web: Schema.optional(WebSchema),
487
456
  /** Present when any queue, event subscription or cron exists. */
488
457
  worker: Schema.optional(WorkerSchema),
@@ -516,8 +485,6 @@ export const ResolvedManifest = Schema.Struct({
516
485
  ),
517
486
  /** Present when the stage sends email. `dailyLimit` is the declared one (prod's). */
518
487
  email: Schema.optional(Schema.Struct({ name: Schema.optional(Schema.String), dailyLimit: Schema.Finite })),
519
- /** Long-running services, with defaults applied. */
520
- services: Schema.Record(Schema.String, ServiceSchema).pipe(orElse({})),
521
488
  });
522
489
  export type ResolvedManifest = typeof ResolvedManifest.Type;
523
490
 
@@ -588,6 +555,7 @@ export function resolveManifest(m: Manifest): ResolvedManifest {
588
555
  return {
589
556
  name: m.name,
590
557
  ...(m.description ? { description: m.description } : {}),
558
+ listed: m.listed,
591
559
  ...(m.web ? { web: m.web } : {}),
592
560
  ...(worker ? { worker } : {}),
593
561
  auth,
@@ -604,7 +572,6 @@ export function resolveManifest(m: Manifest): ResolvedManifest {
604
572
  ? { realtime: { subscribe: m.realtime.subscribe, channels: Object.keys(m.realtime.channels) } }
605
573
  : {}),
606
574
  ...(email ? { email } : {}),
607
- services: m.services,
608
575
  };
609
576
  }
610
577