@ericminassian/platform-core 0.3.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.
Files changed (92) hide show
  1. package/dist/api.d.ts +1225 -45
  2. package/dist/api.js +471 -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/explore.d.ts +365 -0
  28. package/dist/explore.js +440 -0
  29. package/dist/explore.js.map +1 -0
  30. package/dist/fingerprint.d.ts +9 -0
  31. package/dist/fingerprint.js +19 -0
  32. package/dist/fingerprint.js.map +1 -0
  33. package/dist/index.d.ts +7 -0
  34. package/dist/index.js +7 -0
  35. package/dist/index.js.map +1 -1
  36. package/dist/jobs.d.ts +111 -0
  37. package/dist/jobs.js +214 -0
  38. package/dist/jobs.js.map +1 -0
  39. package/dist/manifest.d.ts +270 -29
  40. package/dist/manifest.js +190 -22
  41. package/dist/manifest.js.map +1 -1
  42. package/dist/naming.d.ts +83 -7
  43. package/dist/naming.js +89 -8
  44. package/dist/naming.js.map +1 -1
  45. package/dist/platform-api.d.ts +5897 -1672
  46. package/dist/platform-api.js +218 -8
  47. package/dist/platform-api.js.map +1 -1
  48. package/dist/realtime.d.ts +139 -0
  49. package/dist/realtime.js +201 -0
  50. package/dist/realtime.js.map +1 -0
  51. package/dist/router/decide.d.ts +2 -0
  52. package/dist/router/decide.js +38 -6
  53. package/dist/router.d.ts +35 -13
  54. package/dist/router.js +36 -0
  55. package/dist/router.js.map +1 -1
  56. package/dist/runtime-config.d.ts +57 -0
  57. package/dist/runtime-config.js +12 -0
  58. package/dist/runtime-config.js.map +1 -1
  59. package/dist/storage.d.ts +65 -0
  60. package/dist/storage.js +122 -0
  61. package/dist/storage.js.map +1 -0
  62. package/dist/telemetry.d.ts +135 -20
  63. package/dist/telemetry.js +108 -22
  64. package/dist/telemetry.js.map +1 -1
  65. package/dist/web-compute.d.ts +191 -0
  66. package/dist/web-compute.js +257 -0
  67. package/dist/web-compute.js.map +1 -0
  68. package/package.json +19 -7
  69. package/src/api.ts +564 -15
  70. package/src/auth.ts +6 -2
  71. package/src/base64url.ts +13 -0
  72. package/src/bindings.ts +67 -6
  73. package/src/cloudfront-function.ts +64 -2
  74. package/src/compute.ts +86 -0
  75. package/src/config.ts +31 -1
  76. package/src/constants.ts +64 -1
  77. package/src/email.ts +168 -0
  78. package/src/explore.ts +504 -0
  79. package/src/fingerprint.ts +20 -0
  80. package/src/index.ts +7 -0
  81. package/src/jobs.ts +281 -0
  82. package/src/manifest.ts +415 -45
  83. package/src/naming.ts +93 -9
  84. package/src/platform-api.ts +249 -8
  85. package/src/realtime.ts +298 -0
  86. package/src/router/decide.d.ts +2 -0
  87. package/src/router/decide.js +38 -6
  88. package/src/router.ts +33 -13
  89. package/src/runtime-config.ts +70 -0
  90. package/src/storage.ts +131 -0
  91. package/src/telemetry.ts +115 -22
  92. package/src/web-compute.ts +342 -0
package/src/jobs.ts ADDED
@@ -0,0 +1,281 @@
1
+ /**
2
+ * Jobs: queue messages, events and cron runs. They are pushed, never polled:
3
+ * a queue send is an async Lambda invoke of the function its handler runs in,
4
+ * events arrive from EventBridge and crons from EventBridge Scheduler, and a
5
+ * failed run is retried through a one-shot Scheduler schedule. A stage with
6
+ * jobs costs nothing until one runs (an SQS queue with a Lambda event source
7
+ * mapping costs ~$0.26 a month in empty polls).
8
+ *
9
+ * After its last attempt a job goes to the stage's dead-letter queue, an SQS
10
+ * queue nothing polls. Four writers share it: the SDK (a handler that failed
11
+ * every attempt, `DeadLetter`), Lambda's on-failure destination (a crash or
12
+ * timeout retried twice, or an event older than six hours), Scheduler's
13
+ * dead-letter queue (a retry or cron it couldn't deliver) and EventBridge's (an
14
+ * event it couldn't deliver). `readDeadLetter` reads all four.
15
+ */
16
+ import { fingerprint } from './fingerprint.ts';
17
+ import type { HandlerKind } from './manifest.ts';
18
+
19
+ /** Marker on every job payload the platform sends to a worker function. */
20
+ export const JOB_MARKER = 'job';
21
+
22
+ /** What a worker function receives for a queue message, a retry, or a delayed send. */
23
+ export interface JobPayload {
24
+ __platform: typeof JOB_MARKER;
25
+ kind: HandlerKind;
26
+ /** Queue or cron key, or event type. */
27
+ name: string;
28
+ /** Stable across retries: the message's id, the event's id, or the cron run's. */
29
+ id: string;
30
+ /** Which delivery this is, from 1. */
31
+ attempt: number;
32
+ /** Epoch ms when the message was sent, the event published or the cron fired. */
33
+ sentAt: number;
34
+ /** A queue message's body. */
35
+ body?: unknown;
36
+ /** An event's detail. */
37
+ detail?: unknown;
38
+ trace?: string;
39
+ }
40
+
41
+ /**
42
+ * The largest job payload, in bytes of JSON. Retries and delayed sends go
43
+ * through a Scheduler schedule, whose input is capped at 256 KB, and a dead
44
+ * letter wraps the payload with its error, so this leaves room for both.
45
+ */
46
+ export const JOB_PAYLOAD_MAX_BYTES = 240 * 1024;
47
+
48
+ /** Attempts per kind when a handler sets none. Lambda retried events and crons twice before. */
49
+ export const DEFAULT_ATTEMPTS: Readonly<Record<HandlerKind, number>> = { queue: 5, event: 3, cron: 3 };
50
+ export const MAX_ATTEMPTS = 100;
51
+
52
+ /** The longest delay `send` takes: a one-shot schedule can be any time ahead, a year is plenty. */
53
+ export const MAX_JOB_DELAY_SECONDS = 365 * 86_400;
54
+
55
+ /**
56
+ * Scheduler fires a one-shot schedule within about a minute of its time, and
57
+ * refuses times in the past, so a delayed send or retry is scheduled at least
58
+ * this far ahead.
59
+ */
60
+ export const MIN_SCHEDULE_LEAD_SECONDS = 60;
61
+
62
+ /** Seconds before attempt `failed + 1`: 1, 2, 4 … minutes, at most an hour. */
63
+ export function retryDelaySeconds(failed: number): number {
64
+ return Math.min(60 * 2 ** Math.max(0, failed - 1), 3600);
65
+ }
66
+
67
+ /** `kind:name`, the key bindings use for a handler. */
68
+ export const handlerKey = (kind: HandlerKind, name: string): string => `${kind}:${name}`;
69
+
70
+ /**
71
+ * Name of the one-shot schedule for a retry or delayed send (≤ 64 chars of
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
74
+ * kind and queue or cron key, so the console can count what's waiting per
75
+ * queue with a name prefix. Event types can be long and contain `:`, so they
76
+ * are hashed.
77
+ */
78
+ export function jobScheduleName(kind: HandlerKind, name: string, id: string): string {
79
+ return `${jobSchedulePrefix(kind, name)}${id}`.slice(0, 64);
80
+ }
81
+
82
+ export function jobSchedulePrefix(kind: HandlerKind, name: string): string {
83
+ if (kind === 'queue') return `_q-${name}-`;
84
+ if (kind === 'cron') return `_c-${name}-`;
85
+ return `_e-${fingerprint([name])}-`;
86
+ }
87
+
88
+ export const isJobSchedule = (name: string): boolean => name.startsWith('_');
89
+
90
+ /** One-shot schedule expression for `at` (UTC, whole seconds). */
91
+ export function atExpression(at: Date): string {
92
+ return `at(${at.toISOString().slice(0, 19)})`;
93
+ }
94
+
95
+ /** What the SDK writes to the dead-letter queue when a handler failed its last attempt. */
96
+ export interface DeadLetter {
97
+ v: 1;
98
+ job: JobPayload;
99
+ /** Epoch ms. */
100
+ failedAt: number;
101
+ error: { name: string; message: string };
102
+ }
103
+
104
+ /** A dead-letter queue message, whoever wrote it, in the terms the console shows. */
105
+ export interface DeadLetterView {
106
+ /** `invoke` is a direct `invokeJob` call that crashed or timed out. */
107
+ kind: HandlerKind | 'invoke';
108
+ name: string;
109
+ /** Deliveries made, when known. */
110
+ attempts: number | null;
111
+ error: { name: string; message: string };
112
+ /** Epoch ms. */
113
+ failedAt: number | null;
114
+ /** Who gave up: the SDK, Lambda (crash, timeout, too old), Scheduler or EventBridge (couldn't deliver). */
115
+ source: 'sdk' | 'lambda' | 'scheduler' | 'eventbridge';
116
+ /** What redriving sends, to the function the job's handler runs in now. */
117
+ redrive: JobPayload | { __platform: 'invoke'; name: string; payload: unknown; trace?: string };
118
+ }
119
+
120
+ /** SQS message attributes as the SDK returns them. */
121
+ type Attributes = Record<string, { StringValue?: string } | undefined>;
122
+
123
+ const isObject = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null;
124
+
125
+ /**
126
+ * Normalizes anything a worker function can receive into the job it stands
127
+ * for: a job payload as is, an EventBridge event, or a cron firing. `id` is
128
+ * used when the input carries none (a cron firing). Undefined for anything
129
+ * else, such as a direct `invoke`.
130
+ */
131
+ export function toJob(input: unknown, id: string, now: number): JobPayload | undefined {
132
+ if (!isObject(input)) return undefined;
133
+ if (input.__platform === JOB_MARKER && typeof input.kind === 'string' && typeof input.name === 'string') {
134
+ return input as unknown as JobPayload;
135
+ }
136
+ if (input.__platform === 'cron' && typeof input.name === 'string') {
137
+ return {
138
+ __platform: JOB_MARKER,
139
+ kind: 'cron',
140
+ name: input.name,
141
+ id,
142
+ attempt: 1,
143
+ sentAt: now,
144
+ ...(typeof input.trace === 'string' ? { trace: input.trace } : {}),
145
+ };
146
+ }
147
+ if (typeof input['detail-type'] === 'string') {
148
+ // The SDK publishes `{ data, trace }` as an event's detail; events from elsewhere are bare.
149
+ const detail = input.detail;
150
+ const envelope = isObject(detail) && 'data' in detail ? detail : undefined;
151
+ return {
152
+ __platform: JOB_MARKER,
153
+ kind: 'event',
154
+ name: input['detail-type'],
155
+ id: typeof input.id === 'string' ? input.id : id,
156
+ attempt: 1,
157
+ sentAt: typeof input.time === 'string' ? Date.parse(input.time) || now : now,
158
+ detail: envelope ? envelope.data : detail,
159
+ ...(envelope && typeof envelope.trace === 'string' ? { trace: envelope.trace } : {}),
160
+ };
161
+ }
162
+ return undefined;
163
+ }
164
+
165
+ /** Reads a dead-letter queue message; null for one the platform didn't write. */
166
+ export function readDeadLetter(body: string, attributes: Attributes = {}): DeadLetterView | null {
167
+ let parsed: unknown;
168
+ try {
169
+ parsed = JSON.parse(body);
170
+ } catch {
171
+ return null;
172
+ }
173
+ if (!isObject(parsed)) return null;
174
+ const attr = (name: string) => attributes[name]?.StringValue;
175
+
176
+ // The SDK's own.
177
+ if (parsed.v === 1 && isObject(parsed.job) && isObject(parsed.error)) {
178
+ const d = parsed as unknown as DeadLetter;
179
+ return {
180
+ kind: d.job.kind,
181
+ name: d.job.name,
182
+ attempts: d.job.attempt,
183
+ error: d.error,
184
+ failedAt: d.failedAt,
185
+ source: 'sdk',
186
+ redrive: { ...d.job, attempt: 1 },
187
+ };
188
+ }
189
+
190
+ // Lambda's on-failure destination record.
191
+ if (isObject(parsed.requestContext) && 'requestPayload' in parsed) {
192
+ const ctx = parsed.requestContext;
193
+ const response = isObject(parsed.responsePayload) ? parsed.responsePayload : {};
194
+ const condition = typeof ctx.condition === 'string' ? ctx.condition : 'RetriesExhausted';
195
+ const error = {
196
+ name:
197
+ typeof response.errorType === 'string'
198
+ ? response.errorType
199
+ : condition === 'EventAgeExceeded'
200
+ ? 'EventAgeExceeded'
201
+ : 'FunctionError',
202
+ message:
203
+ typeof response.errorMessage === 'string'
204
+ ? response.errorMessage
205
+ : condition === 'EventAgeExceeded'
206
+ ? 'the event waited longer than six hours (throttled)'
207
+ : condition,
208
+ };
209
+ const failedAt = typeof parsed.timestamp === 'string' ? Date.parse(parsed.timestamp) || null : null;
210
+ const attempts = typeof ctx.approximateInvokeCount === 'number' ? ctx.approximateInvokeCount : null;
211
+ return fromPayload(parsed.requestPayload, error, failedAt, 'lambda', attempts);
212
+ }
213
+
214
+ // Scheduler (a retry, delayed send or cron it couldn't deliver) and EventBridge (an event it
215
+ // couldn't deliver) put the input they meant to deliver in the body and the error in attributes.
216
+ const error = {
217
+ name: attr('ERROR_CODE') ?? 'DeliveryFailed',
218
+ message: attr('ERROR_MESSAGE') ?? 'the target could not be invoked',
219
+ };
220
+ const source = attr('RULE_ARN') ? 'eventbridge' : 'scheduler';
221
+ return fromPayload(parsed, error, null, source, null);
222
+ }
223
+
224
+ function fromPayload(
225
+ payload: unknown,
226
+ error: DeadLetterView['error'],
227
+ failedAt: number | null,
228
+ source: DeadLetterView['source'],
229
+ attempts: number | null,
230
+ ): DeadLetterView | null {
231
+ const job = toJob(payload, `r${fingerprint([JSON.stringify(payload ?? null)])}`, failedAt ?? Date.now());
232
+ if (job) {
233
+ return {
234
+ kind: job.kind,
235
+ name: job.name,
236
+ attempts: attempts ?? job.attempt,
237
+ error,
238
+ failedAt,
239
+ source,
240
+ redrive: { ...job, attempt: 1 },
241
+ };
242
+ }
243
+ if (isObject(payload) && payload.__platform === 'invoke' && typeof payload.name === 'string') {
244
+ return {
245
+ kind: 'invoke',
246
+ name: payload.name,
247
+ attempts,
248
+ error,
249
+ failedAt,
250
+ source,
251
+ redrive: {
252
+ __platform: 'invoke',
253
+ name: payload.name,
254
+ payload: payload.payload,
255
+ ...(typeof payload.trace === 'string' ? { trace: payload.trace } : {}),
256
+ },
257
+ };
258
+ }
259
+ return null;
260
+ }
261
+
262
+ /**
263
+ * The oldest `@ericminassian/platform` whose bundles this platform deploys:
264
+ * jobs became pushed (bindings v2) in 0.4.0, and an older worker can't read
265
+ * them.
266
+ */
267
+ export const MIN_SDK_VERSION = '0.4.0';
268
+
269
+ /** Whether bundles built with SDK `version` can be deployed (undefined: a CLI older than 0.4.0 sent none). */
270
+ export function sdkSupported(version: string | undefined): boolean {
271
+ if (!version) return false;
272
+ const parse = (v: string) =>
273
+ v
274
+ .split('-')[0]!
275
+ .split('.')
276
+ .map((n) => Number(n));
277
+ const [a, b] = [parse(version), parse(MIN_SDK_VERSION)];
278
+ if (a.length !== 3 || a.some((n) => !Number.isInteger(n))) return false;
279
+ for (let i = 0; i < 3; i++) if (a[i] !== b[i]) return a[i]! > b[i]!;
280
+ return true;
281
+ }