@ericminassian/platform-core 0.2.0 → 0.4.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 (89) hide show
  1. package/dist/api.d.ts +1847 -212
  2. package/dist/api.js +694 -1
  3. package/dist/api.js.map +1 -1
  4. package/dist/auth.d.ts +19 -0
  5. package/dist/auth.js +32 -0
  6. package/dist/auth.js.map +1 -1
  7. package/dist/base64url.d.ts +3 -0
  8. package/dist/base64url.js +15 -0
  9. package/dist/base64url.js.map +1 -0
  10. package/dist/bindings.d.ts +69 -13
  11. package/dist/bindings.js +1 -1
  12. package/dist/bindings.js.map +1 -1
  13. package/dist/cloudfront-function.d.ts +5 -1
  14. package/dist/cloudfront-function.js +70 -2
  15. package/dist/cloudfront-function.js.map +1 -1
  16. package/dist/compute.d.ts +52 -0
  17. package/dist/compute.js +65 -0
  18. package/dist/compute.js.map +1 -0
  19. package/dist/config.d.ts +21 -1
  20. package/dist/config.js +16 -0
  21. package/dist/config.js.map +1 -1
  22. package/dist/constants.d.ts +67 -1
  23. package/dist/constants.js +56 -1
  24. package/dist/constants.js.map +1 -1
  25. package/dist/email.d.ts +84 -0
  26. package/dist/email.js +111 -0
  27. package/dist/email.js.map +1 -0
  28. package/dist/fingerprint.d.ts +9 -0
  29. package/dist/fingerprint.js +19 -0
  30. package/dist/fingerprint.js.map +1 -0
  31. package/dist/index.d.ts +6 -0
  32. package/dist/index.js +6 -0
  33. package/dist/index.js.map +1 -1
  34. package/dist/jobs.d.ts +111 -0
  35. package/dist/jobs.js +214 -0
  36. package/dist/jobs.js.map +1 -0
  37. package/dist/manifest.d.ts +357 -112
  38. package/dist/manifest.js +270 -72
  39. package/dist/manifest.js.map +1 -1
  40. package/dist/naming.d.ts +93 -6
  41. package/dist/naming.js +98 -6
  42. package/dist/naming.js.map +1 -1
  43. package/dist/platform-api.d.ts +7792 -0
  44. package/dist/platform-api.js +455 -0
  45. package/dist/platform-api.js.map +1 -0
  46. package/dist/realtime.d.ts +139 -0
  47. package/dist/realtime.js +201 -0
  48. package/dist/realtime.js.map +1 -0
  49. package/dist/router/decide.d.ts +7 -1
  50. package/dist/router/decide.js +42 -5
  51. package/dist/router.d.ts +35 -13
  52. package/dist/router.js +36 -0
  53. package/dist/router.js.map +1 -1
  54. package/dist/runtime-config.d.ts +57 -0
  55. package/dist/runtime-config.js +12 -0
  56. package/dist/runtime-config.js.map +1 -1
  57. package/dist/storage.d.ts +55 -0
  58. package/dist/storage.js +112 -0
  59. package/dist/storage.js.map +1 -0
  60. package/dist/telemetry.d.ts +350 -83
  61. package/dist/telemetry.js +188 -15
  62. package/dist/telemetry.js.map +1 -1
  63. package/dist/web-compute.d.ts +191 -0
  64. package/dist/web-compute.js +257 -0
  65. package/dist/web-compute.js.map +1 -0
  66. package/package.json +28 -8
  67. package/src/api.ts +864 -238
  68. package/src/auth.ts +37 -0
  69. package/src/base64url.ts +13 -0
  70. package/src/bindings.ts +74 -7
  71. package/src/cloudfront-function.ts +70 -2
  72. package/src/compute.ts +86 -0
  73. package/src/config.ts +34 -2
  74. package/src/constants.ts +76 -1
  75. package/src/email.ts +168 -0
  76. package/src/fingerprint.ts +20 -0
  77. package/src/index.ts +6 -0
  78. package/src/jobs.ts +281 -0
  79. package/src/manifest.ts +542 -114
  80. package/src/naming.ts +103 -8
  81. package/src/platform-api.ts +630 -0
  82. package/src/realtime.ts +298 -0
  83. package/src/router/decide.d.ts +7 -1
  84. package/src/router/decide.js +42 -5
  85. package/src/router.ts +33 -13
  86. package/src/runtime-config.ts +70 -0
  87. package/src/storage.ts +120 -0
  88. package/src/telemetry.ts +198 -93
  89. package/src/web-compute.ts +342 -0
package/src/telemetry.ts CHANGED
@@ -4,105 +4,204 @@
4
4
  * filter forwards the interesting kinds to the telemetry processor, which
5
5
  * aggregates rollups into the telemetry table. Logs Insights covers the rest
6
6
  * (search, traces) on demand. No CloudWatch custom metrics are ever created.
7
+ *
8
+ * CloudWatch Logs bills every byte ingested, so lines leave out what a reader
9
+ * can tell without it (a `path` equal to its `route`, a first `attempt`), and
10
+ * most requests and jobs fold their spans into a count (`traceSampled`).
7
11
  */
12
+ import { Schema } from 'effect';
13
+ import { fingerprint, fnv1a } from './fingerprint.ts';
8
14
 
9
- export type TelemetryKind = 'req' | 'err' | 'job' | 'span' | 'log' | 'metric' | 'env';
15
+ export const TelemetryKind = Schema.Literals(['req', 'err', 'job', 'span', 'log', 'metric', 'limit', 'env']);
16
+ export type TelemetryKind = typeof TelemetryKind.Type;
10
17
 
11
- interface Base {
18
+ const base = {
12
19
  /** Marker so the subscription filter only matches platform lines. */
13
- _p: 1;
14
- t: TelemetryKind;
20
+ _p: Schema.Literal(1),
15
21
  /** Epoch milliseconds. */
16
- ts: number;
17
- app: string;
18
- stage: string;
22
+ ts: Schema.Finite,
23
+ app: Schema.String,
24
+ stage: Schema.String,
19
25
  /** Deployment id. */
20
- rev: string;
21
- trace?: string;
22
- span?: string;
23
- parent?: string;
24
- }
26
+ rev: Schema.String,
27
+ trace: Schema.optional(Schema.String),
28
+ span: Schema.optional(Schema.String),
29
+ parent: Schema.optional(Schema.String),
30
+ };
31
+
32
+ /**
33
+ * On a `req` or `job` line: the spans it made (SDK calls, `fetch`es, `traced`
34
+ * units) that weren't written as `span` lines, how many and their total ms.
35
+ * Absent when every span was written. See `TRACE_SAMPLE_RATE`.
36
+ */
37
+ const unwrittenSpans = {
38
+ calls: Schema.optional(Schema.Finite),
39
+ callMs: Schema.optional(Schema.Finite),
40
+ };
25
41
 
26
- export interface RequestEvent extends Base {
27
- t: 'req';
28
- method: string;
29
- /** Route pattern when known (`/api/todos/:id`), else the raw path. */
30
- route: string;
31
- path: string;
32
- status: number;
42
+ export const RequestEvent = Schema.Struct({
43
+ ...base,
44
+ t: Schema.Literal('req'),
45
+ method: Schema.String,
46
+ /** Route pattern when known (`/api/todos/:id`), else the raw path with ids as `:id`. */
47
+ route: Schema.String,
48
+ /** The raw path, when it isn't `route`. */
49
+ path: Schema.optional(Schema.String),
50
+ status: Schema.Finite,
33
51
  /** Duration in ms. */
34
- dur: number;
35
- bytes?: number;
36
- country?: string;
52
+ dur: Schema.Finite,
53
+ bytes: Schema.optional(Schema.Finite),
54
+ country: Schema.optional(Schema.String),
37
55
  /** Hashed user id when signed in. */
38
- user?: string;
39
- cold?: boolean;
40
- }
56
+ user: Schema.optional(Schema.String),
57
+ cold: Schema.optional(Schema.Boolean),
58
+ ...unwrittenSpans,
59
+ });
60
+ export type RequestEvent = typeof RequestEvent.Type;
41
61
 
42
- export interface ErrorEvent extends Base {
43
- t: 'err';
44
- source: 'http' | 'job' | 'unhandled' | 'log';
45
- name: string;
46
- message: string;
47
- stack?: string;
48
- route?: string;
49
- job?: string;
50
- fingerprint: string;
51
- }
62
+ export const ErrorEvent = Schema.Struct({
63
+ ...base,
64
+ t: Schema.Literal('err'),
65
+ /** `service`: a long-running service's `run` failed (it is rerun after a backoff). */
66
+ source: Schema.Literals(['http', 'job', 'unhandled', 'log', 'service']),
67
+ name: Schema.String,
68
+ message: Schema.String,
69
+ stack: Schema.optional(Schema.String),
70
+ route: Schema.optional(Schema.String),
71
+ job: Schema.optional(Schema.String),
72
+ fingerprint: Schema.String,
73
+ });
74
+ export type ErrorEvent = typeof ErrorEvent.Type;
52
75
 
53
- export interface JobEvent extends Base {
54
- t: 'job';
55
- kind: 'queue' | 'event' | 'cron' | 'invoke';
56
- name: string;
57
- status: 'ok' | 'error';
58
- dur: number;
59
- attempt?: number;
60
- }
76
+ /**
77
+ * One unit of work. `service` jobs come from long-running services: `<service>`
78
+ * is a run of the service that ended (it is rerun; `dur` is how long it ran),
79
+ * `<service>/<unit>` a unit of work it marked with `traced`.
80
+ */
81
+ export const JobEvent = Schema.Struct({
82
+ ...base,
83
+ t: Schema.Literal('job'),
84
+ kind: Schema.Literals(['queue', 'event', 'cron', 'invoke', 'service']),
85
+ name: Schema.String,
86
+ status: Schema.Literals(['ok', 'error']),
87
+ dur: Schema.Finite,
88
+ /** A queue message's, event's or cron run's attempt, when it isn't the first. */
89
+ attempt: Schema.optional(Schema.Finite),
90
+ /** What happens after a failed run: tried again later, or moved to the dead-letter queue. */
91
+ next: Schema.optional(Schema.Literals(['retry', 'dead'])),
92
+ ...unwrittenSpans,
93
+ });
94
+ export type JobEvent = typeof JobEvent.Type;
61
95
 
62
- export interface SpanEvent extends Base {
63
- t: 'span';
96
+ /**
97
+ * A call a request or job made, written only when its request or job keeps its
98
+ * spans (`TRACE_SAMPLE_RATE`); `parent` is that request's or job's `span`.
99
+ */
100
+ export const SpanEvent = Schema.Struct({
101
+ ...base,
102
+ t: Schema.Literal('span'),
64
103
  /** `db.get`, `db.query`, `queue.send`, `events.publish`, `storage.put`, `fetch`, ... */
65
- op: string;
66
- name?: string;
67
- dur: number;
68
- status: 'ok' | 'error';
104
+ op: Schema.String,
105
+ name: Schema.optional(Schema.String),
106
+ dur: Schema.Finite,
107
+ status: Schema.Literals(['ok', 'error']),
69
108
  /** Start offset relative to the trace root, ms. */
70
- start?: number;
71
- }
109
+ start: Schema.optional(Schema.Finite),
110
+ });
111
+ export type SpanEvent = typeof SpanEvent.Type;
72
112
 
73
- export interface LogEvent extends Base {
74
- t: 'log';
75
- level: 'debug' | 'info' | 'warn' | 'error';
76
- msg: string;
77
- [field: string]: unknown;
78
- }
113
+ /** A log line; any other fields are the structured fields it was logged with. */
114
+ export const LogEvent = Schema.StructWithRest(
115
+ Schema.Struct({
116
+ ...base,
117
+ t: Schema.Literal('log'),
118
+ level: Schema.Literals(['debug', 'info', 'warn', 'error']),
119
+ msg: Schema.String,
120
+ }),
121
+ [Schema.Record(Schema.String, Schema.Unknown)],
122
+ );
123
+ export type LogEvent = typeof LogEvent.Type;
79
124
 
80
- export interface MetricEvent extends Base {
81
- t: 'metric';
82
- name: string;
83
- value: number;
84
- unit?: string;
85
- }
125
+ export const MetricEvent = Schema.Struct({
126
+ ...base,
127
+ t: Schema.Literal('metric'),
128
+ name: Schema.String,
129
+ value: Schema.Finite,
130
+ unit: Schema.optional(Schema.String),
131
+ });
132
+ export type MetricEvent = typeof MetricEvent.Type;
86
133
 
87
- export interface EnvEvent extends Base {
88
- t: 'env';
89
- event: 'start' | 'stop';
90
- runtime: 'web' | 'worker';
91
- initMs?: number;
92
- }
134
+ /** One `RateLimits` check, and whether the limit let it through. */
135
+ export const LimitEvent = Schema.Struct({
136
+ ...base,
137
+ t: Schema.Literal('limit'),
138
+ /** The limit's name (`signups`). Its key (whom it counts) is never sent: it can be a client address. */
139
+ name: Schema.String,
140
+ ok: Schema.Boolean,
141
+ });
142
+ export type LimitEvent = typeof LimitEvent.Type;
143
+
144
+ /** A runtime process starting or stopping (`service`: a container of a long-running service). */
145
+ export const EnvEvent = Schema.Struct({
146
+ ...base,
147
+ t: Schema.Literal('env'),
148
+ event: Schema.Literals(['start', 'stop']),
149
+ runtime: Schema.Literals(['web', 'worker', 'service']),
150
+ /**
151
+ * How a deployed server runs (`runtime: 'web'`): `request`, a function per
152
+ * request, or `instance`, a Web Function environment. Absent under `plat dev`.
153
+ */
154
+ compute: Schema.optional(Schema.Literals(['request', 'instance'])),
155
+ /** The service's name (`runtime: 'service'`). */
156
+ name: Schema.optional(Schema.String),
157
+ /** Why it stopped, e.g. `SIGTERM`. */
158
+ reason: Schema.optional(Schema.String),
159
+ initMs: Schema.optional(Schema.Finite),
160
+ });
161
+ export type EnvEvent = typeof EnvEvent.Type;
93
162
 
94
- export type TelemetryEvent =
95
- | RequestEvent
96
- | ErrorEvent
97
- | JobEvent
98
- | SpanEvent
99
- | LogEvent
100
- | MetricEvent
101
- | EnvEvent;
163
+ /** One telemetry line, as the SDK writes it and the telemetry processor reads it. */
164
+ export const TelemetryEvent = Schema.Union([
165
+ RequestEvent,
166
+ ErrorEvent,
167
+ JobEvent,
168
+ SpanEvent,
169
+ LogEvent,
170
+ MetricEvent,
171
+ LimitEvent,
172
+ EnvEvent,
173
+ ]);
174
+ export type TelemetryEvent = typeof TelemetryEvent.Type;
102
175
 
103
176
  /** Account-level subscription filter: only aggregate-worthy kinds reach the processor. */
104
177
  export const TELEMETRY_FILTER_PATTERN =
105
- '{ ($._p = 1) && (($.t = "req") || ($.t = "err") || ($.t = "job") || ($.t = "metric") || ($.t = "env")) }';
178
+ '{ ($._p = 1) && (($.t = "req") || ($.t = "err") || ($.t = "job") || ($.t = "metric") || ($.t = "limit") || ($.t = "env")) }';
179
+
180
+ // ---------------------------------------------------------------------------
181
+ // Span sampling
182
+ // ---------------------------------------------------------------------------
183
+
184
+ /**
185
+ * A request or job writes its spans when it fails (a 5xx, a failed job, or an
186
+ * `err` line while it runs), takes `SLOW_TRACE_MS` or longer, or its trace is
187
+ * in this share of traces (`traceSampled`). The rest write only their own
188
+ * line, with the spans counted on it (`calls`, `callMs`).
189
+ */
190
+ export const TRACE_SAMPLE_RATE = 1 / 20;
191
+
192
+ /** A request or job that takes this long (ms) or longer writes its spans. */
193
+ export const SLOW_TRACE_MS = 1_000;
194
+
195
+ /**
196
+ * Whether `trace` is one of the sampled traces. It depends on the trace id
197
+ * alone, so every hop of a trace (server → queue → worker) makes the same
198
+ * choice. Any string works: a client can send its own `x-platform-trace`.
199
+ */
200
+ export function traceSampled(trace: string): boolean {
201
+ // Comparing the hash with a threshold (not `% 20`) keeps a trace sampled at
202
+ // one rate sampled at any higher rate.
203
+ return fnv1a(trace) < TRACE_SAMPLE_RATE * 2 ** 32;
204
+ }
106
205
 
107
206
  export function isTelemetryEvent(v: unknown): v is TelemetryEvent {
108
207
  return (
@@ -143,7 +242,8 @@ export function percentile(hist: readonly number[], p: number): number | null {
143
242
  // Rollups (telemetry table layout)
144
243
  // ---------------------------------------------------------------------------
145
244
 
146
- export type Resolution = '1m' | '1h' | '1d';
245
+ export const Resolution = Schema.Literals(['1m', '1h', '1d']);
246
+ export type Resolution = typeof Resolution.Type;
147
247
 
148
248
  export const RESOLUTION_MS: Record<Resolution, number> = { '1m': 60_000, '1h': 3_600_000, '1d': 86_400_000 };
149
249
 
@@ -159,20 +259,32 @@ export function bucketStart(ts: number, res: Resolution): number {
159
259
  * resolution; `sk` starts with the bucket time so a Query with `BETWEEN`
160
260
  * returns a time range.
161
261
  *
162
- * - `m#<app>#<stage>#<res>` sk `<iso>` whole-stage HTTP: req, s2xx, s3xx, s4xx, s5xx, lat[], cold
262
+ * - `m#<app>#<stage>#<res>` sk `<iso>` whole-stage HTTP: req, s2xx, s3xx, s4xx, s5xx, lat[], cold,
263
+ * dur (ms handling them, summed), and process starts:
264
+ * webStarts (webInits of them reported webInitMs, summed),
265
+ * workerStarts, serviceStarts
163
266
  * - `r#<app>#<stage>#<res>` sk `<iso>#<route>` per-route HTTP (same fields, plus method)
164
- * - `j#<app>#<stage>#<res>` sk `<iso>#<kind>:<name>` jobs: ok, error, lat[]
165
- * - `c#<app>#<stage>#<res>` sk `<iso>#<metric>` custom metrics: count, sum, min, max
267
+ * - `j#<app>#<stage>#<res>` sk `<iso>#<kind>:<name>` jobs: ok, error, lat[]; `service:<name>` rows also
268
+ * count `starts` (containers of that service starting)
269
+ * - `c#<app>#<stage>#<res>` sk `<iso>#<metric>` custom metrics: count, sum (and the unit)
270
+ * - `l#<app>#<stage>#<res>` sk `<iso>#<limit>` rate limit checks: allowed, denied
166
271
  * - `e#<app>#<stage>` sk `<fingerprint>` error groups: count, firstSeen, lastSeen, sample, status
167
- * - `u#<app>#<stage>` sk `<iso>` uptime checks: ok, status, ms
272
+ * - `u#<app>#<stage>` sk `<iso>` uptime: ok, source (`traffic`: req, s5xx; `check`, or none on
273
+ * rows before traffic counted: status, ms)
168
274
  */
169
275
  export const telemetryKeys = {
170
276
  stage: (app: string, stage: string, res: Resolution) => `m#${app}#${stage}#${res}`,
171
277
  route: (app: string, stage: string, res: Resolution) => `r#${app}#${stage}#${res}`,
172
278
  job: (app: string, stage: string, res: Resolution) => `j#${app}#${stage}#${res}`,
173
279
  metric: (app: string, stage: string, res: Resolution) => `c#${app}#${stage}#${res}`,
280
+ limit: (app: string, stage: string, res: Resolution) => `l#${app}#${stage}#${res}`,
174
281
  errors: (app: string, stage: string) => `e#${app}#${stage}`,
175
282
  uptime: (app: string, stage: string) => `u#${app}#${stage}`,
283
+ /**
284
+ * Email usage: sk `YYYY-MM-DD` (UTC), `n` recipients sent. The SDK writes it
285
+ * with the stage role, whose IAM grant covers only this partition.
286
+ */
287
+ email: (app: string, stage: string) => `mail#${app}#${stage}`,
176
288
  time: (ts: number) => new Date(ts).toISOString(),
177
289
  } as const;
178
290
 
@@ -180,9 +292,10 @@ export const telemetryKeys = {
180
292
  // Error fingerprinting (Sentry-style grouping)
181
293
  // ---------------------------------------------------------------------------
182
294
 
183
- /** Normalize volatile parts (ids, numbers, quoted values) so similar errors group together. */
295
+ /** Normalize volatile parts (ARNs, ids, numbers, quoted values) so similar errors group together. */
184
296
  export function normalizeErrorMessage(message: string): string {
185
297
  return message
298
+ .replace(/\barn:aws[\w-]*:[^\s"'`,()]+/g, '<arn>')
186
299
  .replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi, '<uuid>')
187
300
  .replace(/\b[0-9a-f]{16,}\b/gi, '<hex>')
188
301
  .replace(/(["'`]).*?\1/g, '<str>')
@@ -202,15 +315,7 @@ export function topFrame(stack: string | undefined): string {
202
315
  return '';
203
316
  }
204
317
 
205
- /** Stable short hash (FNV-1a 32-bit, hex) — no crypto dependency so the SDK stays tiny. */
206
- export function fingerprint(parts: readonly string[]): string {
207
- let h = 0x811c9dc5;
208
- for (const ch of parts.join('|')) {
209
- h ^= ch.codePointAt(0)!;
210
- h = Math.imul(h, 0x01000193) >>> 0;
211
- }
212
- return h.toString(16).padStart(8, '0');
213
- }
318
+ export { fingerprint } from './fingerprint.ts';
214
319
 
215
320
  export function errorFingerprint(name: string, message: string, stack?: string): string {
216
321
  return fingerprint([name, normalizeErrorMessage(message), topFrame(stack)]);