@ericminassian/platform-core 0.3.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 (88) hide show
  1. package/dist/api.d.ts +942 -45
  2. package/dist/api.js +372 -13
  3. package/dist/api.js.map +1 -1
  4. package/dist/auth.js +5 -2
  5. package/dist/auth.js.map +1 -1
  6. package/dist/base64url.d.ts +3 -0
  7. package/dist/base64url.js +15 -0
  8. package/dist/base64url.js.map +1 -0
  9. package/dist/bindings.d.ts +62 -12
  10. package/dist/bindings.js +1 -1
  11. package/dist/bindings.js.map +1 -1
  12. package/dist/cloudfront-function.d.ts +5 -1
  13. package/dist/cloudfront-function.js +64 -2
  14. package/dist/cloudfront-function.js.map +1 -1
  15. package/dist/compute.d.ts +52 -0
  16. package/dist/compute.js +65 -0
  17. package/dist/compute.js.map +1 -0
  18. package/dist/config.d.ts +18 -0
  19. package/dist/config.js +9 -0
  20. package/dist/config.js.map +1 -1
  21. package/dist/constants.d.ts +56 -1
  22. package/dist/constants.js +56 -1
  23. package/dist/constants.js.map +1 -1
  24. package/dist/email.d.ts +84 -0
  25. package/dist/email.js +111 -0
  26. package/dist/email.js.map +1 -0
  27. package/dist/fingerprint.d.ts +9 -0
  28. package/dist/fingerprint.js +19 -0
  29. package/dist/fingerprint.js.map +1 -0
  30. package/dist/index.d.ts +6 -0
  31. package/dist/index.js +6 -0
  32. package/dist/index.js.map +1 -1
  33. package/dist/jobs.d.ts +111 -0
  34. package/dist/jobs.js +214 -0
  35. package/dist/jobs.js.map +1 -0
  36. package/dist/manifest.d.ts +270 -29
  37. package/dist/manifest.js +190 -22
  38. package/dist/manifest.js.map +1 -1
  39. package/dist/naming.d.ts +83 -7
  40. package/dist/naming.js +89 -8
  41. package/dist/naming.js.map +1 -1
  42. package/dist/platform-api.d.ts +3733 -1278
  43. package/dist/platform-api.js +120 -8
  44. package/dist/platform-api.js.map +1 -1
  45. package/dist/realtime.d.ts +139 -0
  46. package/dist/realtime.js +201 -0
  47. package/dist/realtime.js.map +1 -0
  48. package/dist/router/decide.d.ts +2 -0
  49. package/dist/router/decide.js +38 -6
  50. package/dist/router.d.ts +35 -13
  51. package/dist/router.js +36 -0
  52. package/dist/router.js.map +1 -1
  53. package/dist/runtime-config.d.ts +57 -0
  54. package/dist/runtime-config.js +12 -0
  55. package/dist/runtime-config.js.map +1 -1
  56. package/dist/storage.d.ts +55 -0
  57. package/dist/storage.js +112 -0
  58. package/dist/storage.js.map +1 -0
  59. package/dist/telemetry.d.ts +124 -19
  60. package/dist/telemetry.js +97 -21
  61. package/dist/telemetry.js.map +1 -1
  62. package/dist/web-compute.d.ts +191 -0
  63. package/dist/web-compute.js +257 -0
  64. package/dist/web-compute.js.map +1 -0
  65. package/package.json +19 -7
  66. package/src/api.ts +445 -15
  67. package/src/auth.ts +6 -2
  68. package/src/base64url.ts +13 -0
  69. package/src/bindings.ts +67 -6
  70. package/src/cloudfront-function.ts +64 -2
  71. package/src/compute.ts +86 -0
  72. package/src/config.ts +31 -1
  73. package/src/constants.ts +64 -1
  74. package/src/email.ts +168 -0
  75. package/src/fingerprint.ts +20 -0
  76. package/src/index.ts +6 -0
  77. package/src/jobs.ts +281 -0
  78. package/src/manifest.ts +415 -45
  79. package/src/naming.ts +93 -9
  80. package/src/platform-api.ts +134 -8
  81. package/src/realtime.ts +298 -0
  82. package/src/router/decide.d.ts +2 -0
  83. package/src/router/decide.js +38 -6
  84. package/src/router.ts +33 -13
  85. package/src/runtime-config.ts +70 -0
  86. package/src/storage.ts +120 -0
  87. package/src/telemetry.ts +104 -21
  88. package/src/web-compute.ts +342 -0
@@ -5,21 +5,34 @@
5
5
  // when inlined.
6
6
  //
7
7
  // rec: route record from the KeyValueStore (see RouteRecord in router.ts)
8
- // o - Web Function endpoint domain (server), optional
8
+ // o - the server's domain, optional: a Web Function endpoint, or a function URL when c is 'r'
9
+ // (request mode). Which one only changes how the CloudFront Function calls it (OAC, or
10
+ // the origin secret k in a header); `plat dev` runs the server itself.
9
11
  // s - static key prefix in the sites bucket, e.g. "foo/prod/d01j..." , optional
10
12
  // r - server route prefixes when both o and s exist, e.g. ["/api/"]
11
13
  // spa - 1 to serve index.html for unknown non-file paths
12
- // returns { t: 'server' } | { t: 'static', key: '/<prefix>/<path>' } | { t: 'health' } | { t: 'notfound' }
13
- // health - the router answers /__platform/health itself (HealthResponse with rec.d as the
14
- // revision): a stage without a server has nothing else to report what it serves.
14
+ // rt - realtime: { n: channel namespace, m: 'p' | 's' }, optional
15
+ // p - public store names, optional
16
+ // returns { t: 'server' } | { t: 'static', key: '/<prefix>/<path>' } | { t: 'health' } | { t: 'realtime' }
17
+ // | { t: 'storage', key: '/<app>/<stage>/<store>/<key>' } | { t: 'notfound' }
18
+ // health - the router answers /__platform/health itself (HealthResponse with rec.d as the
19
+ // revision): a stage without a server has nothing else to report what it serves.
20
+ // realtime - /__platform/realtime is the router's own: it answers the browser's config, or passes
21
+ // a WebSocket to AppSync. Other /__platform/realtime/* paths (the token) are the server's.
22
+ // storage - /__platform/storage/<store>/<key> of a public store, served from the storage bucket
23
+ // (whose origin path adds `_public`); every other path below /__platform/storage/ is
24
+ // not found, so it never reaches the server. The key stays percent-encoded, as S3
25
+ // decodes it, and keys with `.` or `..` segments (also encoded) are refused.
15
26
 
16
27
  export function decide(rec, uri) {
17
- if (!rec || (!rec.o && !rec.s)) return { t: 'notfound' };
28
+ if (!rec || (!rec.o && !rec.s && !rec.p)) return { t: 'notfound' };
18
29
  if (uri.indexOf('/__platform/') === 0) {
30
+ if (uri.indexOf('/__platform/storage/') === 0) return storage(rec, uri.substring(20));
31
+ if (uri === '/__platform/realtime' && rec.rt) return { t: 'realtime' };
19
32
  if (rec.o) return { t: 'server' };
20
33
  return uri === '/__platform/health' ? { t: 'health' } : { t: 'notfound' };
21
34
  }
22
- if (!rec.s) return { t: 'server' };
35
+ if (!rec.s) return rec.o ? { t: 'server' } : { t: 'notfound' };
23
36
  if (rec.o) {
24
37
  var routes = rec.r || [];
25
38
  for (var i = 0; i < routes.length; i++) {
@@ -35,3 +48,22 @@ export function decide(rec, uri) {
35
48
  var dir = uri.charAt(uri.length - 1) === '/' ? uri : uri + '/';
36
49
  return { t: 'static', key: '/' + rec.s + dir + 'index.html' };
37
50
  }
51
+
52
+ function storage(rec, rest) {
53
+ var slash = rest.indexOf('/');
54
+ if (slash <= 0) return { t: 'notfound' };
55
+ var store = rest.substring(0, slash);
56
+ var key = rest.substring(slash + 1);
57
+ if (!rec.p || rec.p.indexOf(store) === -1 || !servableKey(key)) return { t: 'notfound' };
58
+ return { t: 'storage', key: '/' + rec.app + '/' + rec.stage + '/' + store + '/' + key };
59
+ }
60
+
61
+ // isServableKey in storage.ts. S3 decodes the key once, so an encoded dot or slash counts as one.
62
+ function servableKey(key) {
63
+ if (!key) return false;
64
+ var parts = key.replace(/%2e/gi, '.').replace(/%2f/gi, '/').split('/');
65
+ for (var i = 0; i < parts.length; i++) {
66
+ if (parts[i] === '.' || parts[i] === '..') return false;
67
+ }
68
+ return true;
69
+ }
package/src/router.ts CHANGED
@@ -1,24 +1,44 @@
1
+ import { Schema } from 'effect';
2
+
1
3
  export type { RouteDecision } from './router/decide.js';
2
4
  export { decide } from './router/decide.js';
3
5
 
4
6
  /**
5
- * Value stored in the CloudFront KeyValueStore under the public hostname.
6
- * Keys are short because KVS values are capped at 1 KB.
7
+ * Value stored in the CloudFront KeyValueStore under the public hostname, and
8
+ * kept with each deployment for rollbacks. Keys are short because KVS values
9
+ * are capped at 1 KB.
7
10
  */
8
- export interface RouteRecord {
9
- v: 1;
10
- app: string;
11
- stage: string;
11
+ export const RouteRecordSchema = Schema.Struct({
12
+ v: Schema.Literal(1),
13
+ app: Schema.String,
14
+ stage: Schema.String,
12
15
  /** Deployment id currently live. */
13
- d: string;
14
- /** Web Function endpoint domain. */
15
- o?: string;
16
+ d: Schema.String,
17
+ /** The server's domain: a Web Function endpoint's, or with `c` a function URL's. */
18
+ o: Schema.optional(Schema.String),
19
+ /**
20
+ * `r`: `o` is a request-mode server (a function URL, `WebCompute`
21
+ * `request`), which the router calls without OAC, sending `k` in
22
+ * `ORIGIN_HEADER`. Absent: a Web Function endpoint, called with OAC.
23
+ */
24
+ c: Schema.optional(Schema.Literal('r')),
25
+ /** The request-mode server's `originSecret`. */
26
+ k: Schema.optional(Schema.String),
16
27
  /** Static prefix in the sites bucket (no leading slash). */
17
- s?: string;
28
+ s: Schema.optional(Schema.String),
18
29
  /** Server route prefixes (only meaningful when both `o` and `s` exist). */
19
- r?: readonly string[];
20
- spa?: 0 | 1;
21
- }
30
+ r: Schema.optional(Schema.Array(Schema.String)),
31
+ spa: Schema.optional(Schema.Literals([0, 1])),
32
+ /**
33
+ * Realtime (`plat.config.ts` `realtime`): the stage's channel namespace and
34
+ * who subscribes (`p` public with the API key, `s` signed-in with a token).
35
+ * The router answers `REALTIME_PATH` only for records that have it.
36
+ */
37
+ rt: Schema.optional(Schema.Struct({ n: Schema.String, m: Schema.Literals(['p', 's']) })),
38
+ /** Public stores, which the router serves from the storage bucket at `STORAGE_PATH`. */
39
+ p: Schema.optional(Schema.Array(Schema.String)),
40
+ });
41
+ export type RouteRecord = typeof RouteRecordSchema.Type;
22
42
 
23
43
  export function encodeRouteRecord(rec: RouteRecord): string {
24
44
  const json = JSON.stringify(rec);
@@ -1,3 +1,5 @@
1
+ import { APPSYNC_PUBLISH_PATH, APPSYNC_REALTIME_PATH } from './realtime.ts';
2
+
1
3
  /**
2
4
  * What the foundation produced: shared resources every stage deploy needs.
3
5
  * Stored as JSON in SSM at `platformNames.runtimeConfigParameter` by the
@@ -26,6 +28,8 @@ export interface PlatformRuntimeConfig {
26
28
  kvsArn?: string;
27
29
  /** The router distribution; Web Function resource policies trust only this. */
28
30
  distributionArn?: string;
31
+ /** The edge floor's alarm and trigger; absent without `limits.edgeFloorAt`. */
32
+ edgeFloor?: EdgeFloorRuntimeConfig;
29
33
  /** Shared Cognito user pool for app end users. */
30
34
  userPoolId?: string;
31
35
  /** Hosted login origin, e.g. `https://login.platform.ericminassian.com`. */
@@ -36,6 +40,72 @@ export interface PlatformRuntimeConfig {
36
40
  alertsTopicArn?: string;
37
41
  /** Telemetry processor (account-level log subscription target). */
38
42
  telemetryFunctionArn?: string;
43
+ /** The AppSync Event API stages' channel namespaces live in (absent on platforms that predate it). */
44
+ realtime?: RealtimeRuntimeConfig;
45
+ /** The SES domain every stage sends from (absent on platforms that predate email). */
46
+ email?: EmailRuntimeConfig;
47
+ /** Container compute, ECS on Fargate (absent on platforms that predate it). */
48
+ containers?: ContainersRuntimeConfig;
49
+ }
50
+
51
+ /**
52
+ * Where containers run. Tasks get a public IPv4 address in a public subnet
53
+ * (there is no NAT gateway) and accept no inbound traffic.
54
+ */
55
+ export interface ContainersRuntimeConfig {
56
+ /** ECS cluster name. */
57
+ cluster: string;
58
+ subnets: string[];
59
+ securityGroups: string[];
60
+ /** ECR repository name. */
61
+ repository: string;
62
+ /** `<account>.dkr.ecr.<region>.amazonaws.com/<repository>`. */
63
+ repositoryUri: string;
64
+ /** Pulls images and writes container logs. */
65
+ executionRoleArn: string;
66
+ /** Assumed by EventBridge Scheduler to scale a stage's services (preview stop schedules). */
67
+ schedulerRoleArn: string;
68
+ }
69
+
70
+ /**
71
+ * The edge floor (`limits.edgeFloorAt`): a CloudWatch alarm on the router
72
+ * distribution's requests per minute, and an EventBridge rule that invokes
73
+ * the control plane's worker when it goes off. The web ACL itself belongs to
74
+ * the control plane, which creates it only while the floor is on.
75
+ */
76
+ export interface EdgeFloorRuntimeConfig {
77
+ alarmArn: string;
78
+ /** The rule's ARN, which the worker's resource policy names. */
79
+ ruleArn: string;
80
+ }
81
+
82
+ export interface EmailRuntimeConfig {
83
+ /** Verified domain identity: `mail.<zone>` (`mail.localhost` in the emulator). */
84
+ domain: string;
85
+ identityArn: string;
86
+ }
87
+
88
+ export interface RealtimeRuntimeConfig {
89
+ apiId: string;
90
+ /** HTTP domain (`<id>.appsync-api.<region>.amazonaws.com`; `127.0.0.1:<port>` in the emulator). */
91
+ httpDomain: string;
92
+ /** Realtime (WebSocket) domain. */
93
+ realtimeDomain: string;
94
+ }
95
+
96
+ /**
97
+ * Where to publish and connect. AWS serves TLS; the emulator serves plain
98
+ * HTTP and WebSocket on local ports.
99
+ */
100
+ export function realtimeEndpoints(
101
+ cfg: Pick<PlatformRuntimeConfig, 'target'>,
102
+ rt: RealtimeRuntimeConfig,
103
+ ): { publishUrl: string; websocketUrl: string } {
104
+ const tls = cfg.target === 'aws';
105
+ return {
106
+ publishUrl: `${tls ? 'https' : 'http'}://${rt.httpDomain}${APPSYNC_PUBLISH_PATH}`,
107
+ websocketUrl: `${tls ? 'wss' : 'ws'}://${rt.realtimeDomain}${APPSYNC_REALTIME_PATH}`,
108
+ };
39
109
  }
40
110
 
41
111
  export function cognitoIssuer(region: string, userPoolId: string): string {
package/src/storage.ts ADDED
@@ -0,0 +1,120 @@
1
+ /**
2
+ * File stores (`storage` in `plat.config.ts`). Every stage's stores share the
3
+ * platform's storage bucket:
4
+ *
5
+ * - a private store is `<app>/<stage>/<store>/` (`names.storagePrefix`);
6
+ * browsers reach its files only through presigned URLs;
7
+ * - a public store is `_public/<app>/<stage>/<store>/`, which the edge serves
8
+ * at `/__platform/storage/<store>/<key>` on the app's own host. The router
9
+ * distribution may read `_public/*` and nothing else, so a routing mistake
10
+ * can't expose a private store. `_` can't start an app name, so no app's
11
+ * prefix collides with it.
12
+ *
13
+ * Isomorphic: the SDK, its browser client, the CLI and the engine share it.
14
+ */
15
+
16
+ /** Where the edge serves public stores on every app host: `/__platform/storage/<store>/<key>`. */
17
+ export const STORAGE_PATH = '/__platform/storage/';
18
+
19
+ /** Top-level prefix of public stores in the storage bucket. */
20
+ export const PUBLIC_STORAGE_ROOT = '_public/';
21
+
22
+ /**
23
+ * Headers the edge adds to every public-store response (the router
24
+ * distribution's response headers policy; `plat dev` sends the same).
25
+ * `script-src 'none'` keeps an uploaded HTML or SVG file from running script
26
+ * on the app's origin, where its session cookie lives (`sandbox` would also
27
+ * stop PDFs from opening in Chrome).
28
+ */
29
+ export const STORAGE_RESPONSE_HEADERS = {
30
+ 'x-content-type-options': 'nosniff',
31
+ 'content-security-policy': "script-src 'none'",
32
+ } as const;
33
+
34
+ /**
35
+ * The router's `x-platform-host` for a public store's file, in place of the
36
+ * host. CloudFront's cache key is the rewritten URI plus that header, not the
37
+ * behavior or origin, and an app's server could be asked for the same path
38
+ * (`/<app>/<stage>/<store>/<key>`) on the app's host: with the host in both,
39
+ * its response would be served for the file, and the file for that path. No
40
+ * routed host has this value.
41
+ */
42
+ export const STORAGE_CACHE_HOST = '__storage';
43
+
44
+ /** `Cache-Control` the edge adds to a public file that carries none: browsers revalidate it. */
45
+ export const STORAGE_DEFAULT_CACHE_CONTROL = 'no-cache';
46
+
47
+ /**
48
+ * Whether the edge serves `key` (as it appears in a URL path, so still
49
+ * percent-encoded): not empty, and without `.` or `..` segments. S3 decodes
50
+ * the key once, so `%2e` counts as a dot and `%2f` as a slash. The router
51
+ * inlines the same check (`router/decide.js`).
52
+ */
53
+ export function isServableKey(key: string): boolean {
54
+ if (!key) return false;
55
+ return key
56
+ .replace(/%2e/gi, '.')
57
+ .replace(/%2f/gi, '/')
58
+ .split('/')
59
+ .every((part) => part !== '.' && part !== '..');
60
+ }
61
+
62
+ /**
63
+ * The path the edge serves a public store's file at, with each key segment
64
+ * percent-encoded: `storagePath('snapshots', 'fires/today 1.json')` →
65
+ * `/__platform/storage/snapshots/fires/today%201.json`.
66
+ */
67
+ export function storagePath(store: string, key: string): string {
68
+ const k = key.replace(/^\/+/, '');
69
+ const path = k.split('/').map(encodeURIComponent).join('/');
70
+ if (!isServableKey(path)) throw new Error(`Storage key "${key}" can't be served from the edge`);
71
+ return `${STORAGE_PATH}${store}/${path}`;
72
+ }
73
+
74
+ /** Content types by file extension: static files, and store files put without one. */
75
+ const CONTENT_TYPES: Record<string, string> = {
76
+ html: 'text/html; charset=utf-8',
77
+ htm: 'text/html; charset=utf-8',
78
+ css: 'text/css; charset=utf-8',
79
+ js: 'text/javascript; charset=utf-8',
80
+ mjs: 'text/javascript; charset=utf-8',
81
+ cjs: 'text/javascript; charset=utf-8',
82
+ map: 'application/json; charset=utf-8',
83
+ json: 'application/json; charset=utf-8',
84
+ geojson: 'application/geo+json',
85
+ ndjson: 'application/x-ndjson',
86
+ webmanifest: 'application/manifest+json',
87
+ txt: 'text/plain; charset=utf-8',
88
+ csv: 'text/csv; charset=utf-8',
89
+ md: 'text/markdown; charset=utf-8',
90
+ xml: 'application/xml; charset=utf-8',
91
+ svg: 'image/svg+xml',
92
+ png: 'image/png',
93
+ jpg: 'image/jpeg',
94
+ jpeg: 'image/jpeg',
95
+ gif: 'image/gif',
96
+ webp: 'image/webp',
97
+ avif: 'image/avif',
98
+ ico: 'image/x-icon',
99
+ woff: 'font/woff',
100
+ woff2: 'font/woff2',
101
+ ttf: 'font/ttf',
102
+ otf: 'font/otf',
103
+ wasm: 'application/wasm',
104
+ pdf: 'application/pdf',
105
+ zip: 'application/zip',
106
+ gz: 'application/gzip',
107
+ mp4: 'video/mp4',
108
+ webm: 'video/webm',
109
+ mp3: 'audio/mpeg',
110
+ wav: 'audio/wav',
111
+ };
112
+
113
+ /** The content type for a file name (or key), `application/octet-stream` when the extension is unknown. */
114
+ export function contentTypeFor(path: string): string {
115
+ const file = path.slice(path.lastIndexOf('/') + 1);
116
+ const dot = file.lastIndexOf('.');
117
+ return (
118
+ (dot === -1 ? undefined : CONTENT_TYPES[file.slice(dot + 1).toLowerCase()]) ?? 'application/octet-stream'
119
+ );
120
+ }
package/src/telemetry.ts CHANGED
@@ -4,10 +4,15 @@
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
  */
8
12
  import { Schema } from 'effect';
13
+ import { fingerprint, fnv1a } from './fingerprint.ts';
9
14
 
10
- export const TelemetryKind = Schema.Literals(['req', 'err', 'job', 'span', 'log', 'metric', 'env']);
15
+ export const TelemetryKind = Schema.Literals(['req', 'err', 'job', 'span', 'log', 'metric', 'limit', 'env']);
11
16
  export type TelemetryKind = typeof TelemetryKind.Type;
12
17
 
13
18
  const base = {
@@ -24,13 +29,24 @@ const base = {
24
29
  parent: Schema.optional(Schema.String),
25
30
  };
26
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
+ };
41
+
27
42
  export const RequestEvent = Schema.Struct({
28
43
  ...base,
29
44
  t: Schema.Literal('req'),
30
45
  method: Schema.String,
31
- /** Route pattern when known (`/api/todos/:id`), else the raw path. */
46
+ /** Route pattern when known (`/api/todos/:id`), else the raw path with ids as `:id`. */
32
47
  route: Schema.String,
33
- path: Schema.String,
48
+ /** The raw path, when it isn't `route`. */
49
+ path: Schema.optional(Schema.String),
34
50
  status: Schema.Finite,
35
51
  /** Duration in ms. */
36
52
  dur: Schema.Finite,
@@ -39,13 +55,15 @@ export const RequestEvent = Schema.Struct({
39
55
  /** Hashed user id when signed in. */
40
56
  user: Schema.optional(Schema.String),
41
57
  cold: Schema.optional(Schema.Boolean),
58
+ ...unwrittenSpans,
42
59
  });
43
60
  export type RequestEvent = typeof RequestEvent.Type;
44
61
 
45
62
  export const ErrorEvent = Schema.Struct({
46
63
  ...base,
47
64
  t: Schema.Literal('err'),
48
- source: Schema.Literals(['http', 'job', 'unhandled', 'log']),
65
+ /** `service`: a long-running service's `run` failed (it is rerun after a backoff). */
66
+ source: Schema.Literals(['http', 'job', 'unhandled', 'log', 'service']),
49
67
  name: Schema.String,
50
68
  message: Schema.String,
51
69
  stack: Schema.optional(Schema.String),
@@ -55,17 +73,30 @@ export const ErrorEvent = Schema.Struct({
55
73
  });
56
74
  export type ErrorEvent = typeof ErrorEvent.Type;
57
75
 
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
+ */
58
81
  export const JobEvent = Schema.Struct({
59
82
  ...base,
60
83
  t: Schema.Literal('job'),
61
- kind: Schema.Literals(['queue', 'event', 'cron', 'invoke']),
84
+ kind: Schema.Literals(['queue', 'event', 'cron', 'invoke', 'service']),
62
85
  name: Schema.String,
63
86
  status: Schema.Literals(['ok', 'error']),
64
87
  dur: Schema.Finite,
88
+ /** A queue message's, event's or cron run's attempt, when it isn't the first. */
65
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,
66
93
  });
67
94
  export type JobEvent = typeof JobEvent.Type;
68
95
 
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
+ */
69
100
  export const SpanEvent = Schema.Struct({
70
101
  ...base,
71
102
  t: Schema.Literal('span'),
@@ -100,11 +131,31 @@ export const MetricEvent = Schema.Struct({
100
131
  });
101
132
  export type MetricEvent = typeof MetricEvent.Type;
102
133
 
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). */
103
145
  export const EnvEvent = Schema.Struct({
104
146
  ...base,
105
147
  t: Schema.Literal('env'),
106
148
  event: Schema.Literals(['start', 'stop']),
107
- runtime: Schema.Literals(['web', 'worker']),
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),
108
159
  initMs: Schema.optional(Schema.Finite),
109
160
  });
110
161
  export type EnvEvent = typeof EnvEvent.Type;
@@ -117,13 +168,40 @@ export const TelemetryEvent = Schema.Union([
117
168
  SpanEvent,
118
169
  LogEvent,
119
170
  MetricEvent,
171
+ LimitEvent,
120
172
  EnvEvent,
121
173
  ]);
122
174
  export type TelemetryEvent = typeof TelemetryEvent.Type;
123
175
 
124
176
  /** Account-level subscription filter: only aggregate-worthy kinds reach the processor. */
125
177
  export const TELEMETRY_FILTER_PATTERN =
126
- '{ ($._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
+ }
127
205
 
128
206
  export function isTelemetryEvent(v: unknown): v is TelemetryEvent {
129
207
  return (
@@ -181,20 +259,32 @@ export function bucketStart(ts: number, res: Resolution): number {
181
259
  * resolution; `sk` starts with the bucket time so a Query with `BETWEEN`
182
260
  * returns a time range.
183
261
  *
184
- * - `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
185
266
  * - `r#<app>#<stage>#<res>` sk `<iso>#<route>` per-route HTTP (same fields, plus method)
186
- * - `j#<app>#<stage>#<res>` sk `<iso>#<kind>:<name>` jobs: ok, error, lat[]
187
- * - `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
188
271
  * - `e#<app>#<stage>` sk `<fingerprint>` error groups: count, firstSeen, lastSeen, sample, status
189
- * - `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)
190
274
  */
191
275
  export const telemetryKeys = {
192
276
  stage: (app: string, stage: string, res: Resolution) => `m#${app}#${stage}#${res}`,
193
277
  route: (app: string, stage: string, res: Resolution) => `r#${app}#${stage}#${res}`,
194
278
  job: (app: string, stage: string, res: Resolution) => `j#${app}#${stage}#${res}`,
195
279
  metric: (app: string, stage: string, res: Resolution) => `c#${app}#${stage}#${res}`,
280
+ limit: (app: string, stage: string, res: Resolution) => `l#${app}#${stage}#${res}`,
196
281
  errors: (app: string, stage: string) => `e#${app}#${stage}`,
197
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}`,
198
288
  time: (ts: number) => new Date(ts).toISOString(),
199
289
  } as const;
200
290
 
@@ -202,9 +292,10 @@ export const telemetryKeys = {
202
292
  // Error fingerprinting (Sentry-style grouping)
203
293
  // ---------------------------------------------------------------------------
204
294
 
205
- /** 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. */
206
296
  export function normalizeErrorMessage(message: string): string {
207
297
  return message
298
+ .replace(/\barn:aws[\w-]*:[^\s"'`,()]+/g, '<arn>')
208
299
  .replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi, '<uuid>')
209
300
  .replace(/\b[0-9a-f]{16,}\b/gi, '<hex>')
210
301
  .replace(/(["'`]).*?\1/g, '<str>')
@@ -224,15 +315,7 @@ export function topFrame(stack: string | undefined): string {
224
315
  return '';
225
316
  }
226
317
 
227
- /** Stable short hash (FNV-1a 32-bit, hex) — no crypto dependency so the SDK stays tiny. */
228
- export function fingerprint(parts: readonly string[]): string {
229
- let h = 0x811c9dc5;
230
- for (const ch of parts.join('|')) {
231
- h ^= ch.codePointAt(0)!;
232
- h = Math.imul(h, 0x01000193) >>> 0;
233
- }
234
- return h.toString(16).padStart(8, '0');
235
- }
318
+ export { fingerprint } from './fingerprint.ts';
236
319
 
237
320
  export function errorFingerprint(name: string, message: string, stack?: string): string {
238
321
  return fingerprint([name, normalizeErrorMessage(message), topFrame(stack)]);