@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.
- package/dist/api.d.ts +1225 -45
- package/dist/api.js +471 -13
- package/dist/api.js.map +1 -1
- package/dist/auth.js +5 -2
- package/dist/auth.js.map +1 -1
- package/dist/base64url.d.ts +3 -0
- package/dist/base64url.js +15 -0
- package/dist/base64url.js.map +1 -0
- package/dist/bindings.d.ts +62 -12
- package/dist/bindings.js +1 -1
- package/dist/bindings.js.map +1 -1
- package/dist/cloudfront-function.d.ts +5 -1
- package/dist/cloudfront-function.js +64 -2
- package/dist/cloudfront-function.js.map +1 -1
- package/dist/compute.d.ts +52 -0
- package/dist/compute.js +65 -0
- package/dist/compute.js.map +1 -0
- package/dist/config.d.ts +18 -0
- package/dist/config.js +9 -0
- package/dist/config.js.map +1 -1
- package/dist/constants.d.ts +56 -1
- package/dist/constants.js +56 -1
- package/dist/constants.js.map +1 -1
- package/dist/email.d.ts +84 -0
- package/dist/email.js +111 -0
- package/dist/email.js.map +1 -0
- package/dist/explore.d.ts +365 -0
- package/dist/explore.js +440 -0
- package/dist/explore.js.map +1 -0
- package/dist/fingerprint.d.ts +9 -0
- package/dist/fingerprint.js +19 -0
- package/dist/fingerprint.js.map +1 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +7 -0
- package/dist/index.js.map +1 -1
- package/dist/jobs.d.ts +111 -0
- package/dist/jobs.js +214 -0
- package/dist/jobs.js.map +1 -0
- package/dist/manifest.d.ts +270 -29
- package/dist/manifest.js +190 -22
- package/dist/manifest.js.map +1 -1
- package/dist/naming.d.ts +83 -7
- package/dist/naming.js +89 -8
- package/dist/naming.js.map +1 -1
- package/dist/platform-api.d.ts +5897 -1672
- package/dist/platform-api.js +218 -8
- package/dist/platform-api.js.map +1 -1
- package/dist/realtime.d.ts +139 -0
- package/dist/realtime.js +201 -0
- package/dist/realtime.js.map +1 -0
- package/dist/router/decide.d.ts +2 -0
- package/dist/router/decide.js +38 -6
- package/dist/router.d.ts +35 -13
- package/dist/router.js +36 -0
- package/dist/router.js.map +1 -1
- package/dist/runtime-config.d.ts +57 -0
- package/dist/runtime-config.js +12 -0
- package/dist/runtime-config.js.map +1 -1
- package/dist/storage.d.ts +65 -0
- package/dist/storage.js +122 -0
- package/dist/storage.js.map +1 -0
- package/dist/telemetry.d.ts +135 -20
- package/dist/telemetry.js +108 -22
- package/dist/telemetry.js.map +1 -1
- package/dist/web-compute.d.ts +191 -0
- package/dist/web-compute.js +257 -0
- package/dist/web-compute.js.map +1 -0
- package/package.json +19 -7
- package/src/api.ts +564 -15
- package/src/auth.ts +6 -2
- package/src/base64url.ts +13 -0
- package/src/bindings.ts +67 -6
- package/src/cloudfront-function.ts +64 -2
- package/src/compute.ts +86 -0
- package/src/config.ts +31 -1
- package/src/constants.ts +64 -1
- package/src/email.ts +168 -0
- package/src/explore.ts +504 -0
- package/src/fingerprint.ts +20 -0
- package/src/index.ts +7 -0
- package/src/jobs.ts +281 -0
- package/src/manifest.ts +415 -45
- package/src/naming.ts +93 -9
- package/src/platform-api.ts +249 -8
- package/src/realtime.ts +298 -0
- package/src/router/decide.d.ts +2 -0
- package/src/router/decide.js +38 -6
- package/src/router.ts +33 -13
- package/src/runtime-config.ts +70 -0
- package/src/storage.ts +131 -0
- package/src/telemetry.ts +115 -22
- package/src/web-compute.ts +342 -0
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
|
|
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
|
-
|
|
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,42 @@ 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
|
-
*
|
|
185
|
-
*
|
|
186
|
-
*
|
|
187
|
-
*
|
|
262
|
+
* Every rollup family is written at `1m`, `1h` and `1d` (`RESOLUTION_TTL_DAYS`).
|
|
263
|
+
* Route, job, custom metric and rate limit rows have had minute buckets only
|
|
264
|
+
* since November 2026; before, they started at `1h`.
|
|
265
|
+
*
|
|
266
|
+
* - `m#<app>#<stage>#<res>` sk `<iso>` whole-stage HTTP: req, s2xx, s3xx, s4xx, s5xx, lat[], cold,
|
|
267
|
+
* dur (ms handling them, summed), and process starts:
|
|
268
|
+
* webStarts (webInits of them reported webInitMs, summed),
|
|
269
|
+
* workerStarts, serviceStarts
|
|
270
|
+
* - `r#<app>#<stage>#<res>` sk `<iso>#<METHOD> <route>` per-route HTTP: req, s2xx, s3xx, s4xx, s5xx, lat[],
|
|
271
|
+
* cold, method, route. Rows from before November 2026 have no
|
|
272
|
+
* s2xx, s3xx or cold: their req − s4xx − s5xx were 2xx
|
|
273
|
+
* - `j#<app>#<stage>#<res>` sk `<iso>#<kind>:<name>` jobs: ok, error, lat[]; `service:<name>` rows also
|
|
274
|
+
* count `starts` (containers of that service starting)
|
|
275
|
+
* - `c#<app>#<stage>#<res>` sk `<iso>#<metric>` custom metrics: count, sum, max (and the unit); rows from
|
|
276
|
+
* before November 2026 have no max
|
|
277
|
+
* - `l#<app>#<stage>#<res>` sk `<iso>#<limit>` rate limit checks: allowed, denied
|
|
188
278
|
* - `e#<app>#<stage>` sk `<fingerprint>` error groups: count, firstSeen, lastSeen, sample, status
|
|
189
|
-
* - `u#<app>#<stage>` sk `<iso>` uptime
|
|
279
|
+
* - `u#<app>#<stage>` sk `<iso>` uptime: ok, source (`traffic`: req, s5xx; `check`, or none on
|
|
280
|
+
* rows before traffic counted: status, ms)
|
|
281
|
+
* - `a#<app>#<stage>` sk `<iso>#<ruleId>` alert rule state changes (`AlertEvent` fields but `ts`),
|
|
282
|
+
* kept `ALERT_HISTORY_DAYS`
|
|
190
283
|
*/
|
|
191
284
|
export const telemetryKeys = {
|
|
192
285
|
stage: (app: string, stage: string, res: Resolution) => `m#${app}#${stage}#${res}`,
|
|
193
286
|
route: (app: string, stage: string, res: Resolution) => `r#${app}#${stage}#${res}`,
|
|
194
287
|
job: (app: string, stage: string, res: Resolution) => `j#${app}#${stage}#${res}`,
|
|
195
288
|
metric: (app: string, stage: string, res: Resolution) => `c#${app}#${stage}#${res}`,
|
|
289
|
+
limit: (app: string, stage: string, res: Resolution) => `l#${app}#${stage}#${res}`,
|
|
196
290
|
errors: (app: string, stage: string) => `e#${app}#${stage}`,
|
|
197
291
|
uptime: (app: string, stage: string) => `u#${app}#${stage}`,
|
|
292
|
+
alerts: (app: string, stage: string) => `a#${app}#${stage}`,
|
|
293
|
+
/**
|
|
294
|
+
* Email usage: sk `YYYY-MM-DD` (UTC), `n` recipients sent. The SDK writes it
|
|
295
|
+
* with the stage role, whose IAM grant covers only this partition.
|
|
296
|
+
*/
|
|
297
|
+
email: (app: string, stage: string) => `mail#${app}#${stage}`,
|
|
198
298
|
time: (ts: number) => new Date(ts).toISOString(),
|
|
199
299
|
} as const;
|
|
200
300
|
|
|
@@ -202,9 +302,10 @@ export const telemetryKeys = {
|
|
|
202
302
|
// Error fingerprinting (Sentry-style grouping)
|
|
203
303
|
// ---------------------------------------------------------------------------
|
|
204
304
|
|
|
205
|
-
/** Normalize volatile parts (ids, numbers, quoted values) so similar errors group together. */
|
|
305
|
+
/** Normalize volatile parts (ARNs, ids, numbers, quoted values) so similar errors group together. */
|
|
206
306
|
export function normalizeErrorMessage(message: string): string {
|
|
207
307
|
return message
|
|
308
|
+
.replace(/\barn:aws[\w-]*:[^\s"'`,()]+/g, '<arn>')
|
|
208
309
|
.replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi, '<uuid>')
|
|
209
310
|
.replace(/\b[0-9a-f]{16,}\b/gi, '<hex>')
|
|
210
311
|
.replace(/(["'`]).*?\1/g, '<str>')
|
|
@@ -224,15 +325,7 @@ export function topFrame(stack: string | undefined): string {
|
|
|
224
325
|
return '';
|
|
225
326
|
}
|
|
226
327
|
|
|
227
|
-
|
|
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
|
-
}
|
|
328
|
+
export { fingerprint } from './fingerprint.ts';
|
|
236
329
|
|
|
237
330
|
export function errorFingerprint(name: string, message: string, stack?: string): string {
|
|
238
331
|
return fingerprint([name, normalizeErrorMessage(message), topFrame(stack)]);
|
|
@@ -0,0 +1,342 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* How a stage's server runs, and what each way costs. Shared by the manifest
|
|
3
|
+
* schema, the engine, the router, the SDK and the control plane's daily
|
|
4
|
+
* chooser.
|
|
5
|
+
*
|
|
6
|
+
* - `request`: a regular Lambda function (arm64) behind a function URL. Each
|
|
7
|
+
* request is an invocation, billed by the millisecond (a cold start's INIT
|
|
8
|
+
* too) and by the request, from the account's monthly free tier first.
|
|
9
|
+
* Nothing is billed while no request runs.
|
|
10
|
+
* - `instance`: a Lambda Web Function. An environment serves many requests at
|
|
11
|
+
* once and is billed for the memory it uses for as long as it lives (until
|
|
12
|
+
* about five minutes after its last request), plus vCPU while it works.
|
|
13
|
+
*
|
|
14
|
+
* Request mode costs less until a stage is busy about a quarter of the time,
|
|
15
|
+
* so quiet stages run it and the chooser moves a busy prod stage to instance
|
|
16
|
+
* mode (and back) by `simulateWebCompute`.
|
|
17
|
+
*/
|
|
18
|
+
import { base64url, fromBase64url } from './base64url.ts';
|
|
19
|
+
import { HOURS_PER_MONTH } from './compute.ts';
|
|
20
|
+
import { PROD_STAGE } from './constants.ts';
|
|
21
|
+
|
|
22
|
+
export const WEB_COMPUTE = ['request', 'instance'] as const;
|
|
23
|
+
export type WebCompute = (typeof WEB_COMPUTE)[number];
|
|
24
|
+
|
|
25
|
+
/** `web.compute` in plat.config.ts. */
|
|
26
|
+
export const WEB_COMPUTE_SETTINGS = ['auto', ...WEB_COMPUTE] as const;
|
|
27
|
+
export type WebComputeSetting = (typeof WEB_COMPUTE_SETTINGS)[number];
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Memory of a request-mode server unless `web.memoryMb` says otherwise, from
|
|
31
|
+
* the template app's server bundle (2.1 MB, measured 2026-11-16). INIT took
|
|
32
|
+
* 460–650 ms at 512, 1024 and 1769 MB alike, but Lambda gives the handler CPU
|
|
33
|
+
* in proportion to memory: the first request after INIT took ~115 ms at
|
|
34
|
+
* 512 MB, ~60 ms at 1024 and ~40 ms at 1769, and warm requests 12–148 ms at
|
|
35
|
+
* 512 against 5–11 ms at the other two. So 1024 MB answers faster than 512 and
|
|
36
|
+
* costs less per warm request (the shorter time more than pays for the
|
|
37
|
+
* doubled rate); 1769 MB only costs more. Each environment used ~140 MB.
|
|
38
|
+
*/
|
|
39
|
+
export const WEB_REQUEST_MEMORY_MB = 1024;
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Most environments a Web Function endpoint runs at once. Lambda keeps
|
|
43
|
+
* spare, billed environments next to busy ones (CI bursts ran 9–25), so this
|
|
44
|
+
* also caps that headroom. Prod takes `web.maxEnvironments`.
|
|
45
|
+
*/
|
|
46
|
+
export const WEB_MAX_ENVIRONMENTS = { preview: 2, prod: 10 } as const;
|
|
47
|
+
|
|
48
|
+
/** The first `@ericminassian/platform` whose server bundle also runs as a request-mode handler. */
|
|
49
|
+
export const REQUEST_MODE_MIN_SDK = '0.4.0';
|
|
50
|
+
|
|
51
|
+
/** Whether a bundle built with this SDK version can run in request mode. */
|
|
52
|
+
export function supportsRequestMode(sdk: string | undefined): boolean {
|
|
53
|
+
const v = sdk ? /^(\d+)\.(\d+)\.(\d+)(-.+)?$/.exec(sdk.trim()) : null;
|
|
54
|
+
if (!v) return false;
|
|
55
|
+
const min = REQUEST_MODE_MIN_SDK.split('.').map(Number);
|
|
56
|
+
const got = [Number(v[1]), Number(v[2]), Number(v[3])];
|
|
57
|
+
for (let i = 0; i < 3; i++) if (got[i] !== min[i]) return got[i]! > min[i]!;
|
|
58
|
+
// A prerelease of the minimum predates it.
|
|
59
|
+
return v[4] === undefined;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* The account Lambda concurrency `auto` needs before it runs request mode.
|
|
64
|
+
* Request-mode servers share the account's concurrency with every worker; a
|
|
65
|
+
* new account's limit is 10, which one burst of browser tests on a preview
|
|
66
|
+
* can exceed, and Lambda answers throttled requests with errors. Web
|
|
67
|
+
* Functions scale on their own quota. AWS keeps 100 unreserved at the usual
|
|
68
|
+
* 1,000.
|
|
69
|
+
*/
|
|
70
|
+
export const REQUEST_MODE_MIN_ACCOUNT_CONCURRENCY = 100;
|
|
71
|
+
|
|
72
|
+
/** Why `auto` keeps a server off request mode on this account, or undefined when it needn't. */
|
|
73
|
+
export function requestModeBlocked(accountConcurrency: number | undefined): string | undefined {
|
|
74
|
+
if (accountConcurrency === undefined || accountConcurrency >= REQUEST_MODE_MIN_ACCOUNT_CONCURRENCY)
|
|
75
|
+
return undefined;
|
|
76
|
+
return (
|
|
77
|
+
`the account's Lambda concurrency limit is ${accountConcurrency}, and request mode needs ` +
|
|
78
|
+
`${REQUEST_MODE_MIN_ACCOUNT_CONCURRENCY} (raise "Concurrent executions" in Service Quotas)`
|
|
79
|
+
);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* The mode a deploy runs the server in. `auto` runs request mode everywhere
|
|
84
|
+
* but prod, where a stage keeps the mode it has (the chooser changes it) and
|
|
85
|
+
* starts in request mode. A bundle built with an SDK older than
|
|
86
|
+
* `REQUEST_MODE_MIN_SDK` only runs as a Web Function, and so does `auto` on an
|
|
87
|
+
* account without the Lambda concurrency request mode needs
|
|
88
|
+
* (`requestModeBlocked`); `note` then says why.
|
|
89
|
+
*/
|
|
90
|
+
export function webComputeFor(input: {
|
|
91
|
+
setting: WebComputeSetting;
|
|
92
|
+
stage: string;
|
|
93
|
+
/** The mode the stage's server runs in now, if it has one. */
|
|
94
|
+
current?: WebCompute | undefined;
|
|
95
|
+
/** The deployment's `@ericminassian/platform` version. */
|
|
96
|
+
sdk?: string | undefined;
|
|
97
|
+
/** The account's Lambda concurrency limit, when known. */
|
|
98
|
+
accountConcurrency?: number | undefined;
|
|
99
|
+
}): { compute: WebCompute; note?: string } | { error: string } {
|
|
100
|
+
const capable = supportsRequestMode(input.sdk);
|
|
101
|
+
if (input.setting === 'instance') return { compute: 'instance' };
|
|
102
|
+
const blocked = requestModeBlocked(input.accountConcurrency);
|
|
103
|
+
if (input.setting === 'request') {
|
|
104
|
+
if (!capable)
|
|
105
|
+
return {
|
|
106
|
+
error: `web.compute is 'request', but this build's @ericminassian/platform is ${input.sdk ?? 'unknown'}: request mode needs ${REQUEST_MODE_MIN_SDK} or later`,
|
|
107
|
+
};
|
|
108
|
+
// Asked for by name: it runs, with the warning.
|
|
109
|
+
return blocked
|
|
110
|
+
? { compute: 'request', note: `request mode can be throttled: ${blocked}` }
|
|
111
|
+
: { compute: 'request' };
|
|
112
|
+
}
|
|
113
|
+
if (!capable) return { compute: 'instance' };
|
|
114
|
+
const wanted = input.stage === PROD_STAGE ? (input.current ?? 'request') : 'request';
|
|
115
|
+
if (wanted === 'request' && blocked) return { compute: 'instance', note: `instance mode: ${blocked}` };
|
|
116
|
+
return { compute: wanted };
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** `maxEnvironments` of a stage's Web Function endpoints. */
|
|
120
|
+
export function webMaxEnvironments(web: { maxEnvironments?: number | undefined }, stage: string): number {
|
|
121
|
+
return stage === PROD_STAGE
|
|
122
|
+
? (web.maxEnvironments ?? WEB_MAX_ENVIRONMENTS.prod)
|
|
123
|
+
: WEB_MAX_ENVIRONMENTS.preview;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// ---------------------------------------------------------------------------
|
|
127
|
+
// The origin secret
|
|
128
|
+
|
|
129
|
+
const ORIGIN_SECRET_INFO = 'platform:origin:v1';
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* What the router sends a stage's request-mode server in `ORIGIN_HEADER`:
|
|
133
|
+
* HKDF of the stage key, so the engine (which writes it into the route) and
|
|
134
|
+
* the SDK (which checks it) agree without storing another secret.
|
|
135
|
+
*/
|
|
136
|
+
export async function originSecret(stageKey: string): Promise<string> {
|
|
137
|
+
const raw = await crypto.subtle.importKey('raw', fromBase64url(stageKey), 'HKDF', false, ['deriveBits']);
|
|
138
|
+
const bits = await crypto.subtle.deriveBits(
|
|
139
|
+
{
|
|
140
|
+
name: 'HKDF',
|
|
141
|
+
hash: 'SHA-256',
|
|
142
|
+
salt: new Uint8Array(0),
|
|
143
|
+
info: new TextEncoder().encode(ORIGIN_SECRET_INFO),
|
|
144
|
+
},
|
|
145
|
+
raw,
|
|
146
|
+
256,
|
|
147
|
+
);
|
|
148
|
+
return base64url(new Uint8Array(bits));
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
// ---------------------------------------------------------------------------
|
|
152
|
+
// Cost
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* Prices behind the estimates, us-east-1, checked 2026-11-16. Request mode is
|
|
156
|
+
* Lambda on arm64; its INIT is billed like duration. Web Functions bill the
|
|
157
|
+
* memory an environment uses (not what it may use) for its whole life, vCPU
|
|
158
|
+
* per second it works, and requests. Neither estimate subtracts the free
|
|
159
|
+
* tier: the account's workers draw on it too.
|
|
160
|
+
*/
|
|
161
|
+
export const WEB_COMPUTE_PRICES_USD = {
|
|
162
|
+
request: { gbSecond: 0.0000133334, perMillionRequests: 0.2 },
|
|
163
|
+
instance: { gbSecond: 0.000003667, vcpuSecond: 0.0000277, perMillionRequests: 0.3 },
|
|
164
|
+
} as const;
|
|
165
|
+
|
|
166
|
+
/** How long a Web Function environment lives after its last request (measured: ~290 s). */
|
|
167
|
+
export const INSTANCE_IDLE_SECONDS = 290;
|
|
168
|
+
/**
|
|
169
|
+
* How long Lambda keeps an idle request-mode environment for the next
|
|
170
|
+
* request. Undocumented; observed to be several minutes, so the simulation
|
|
171
|
+
* assumes the short end.
|
|
172
|
+
*/
|
|
173
|
+
export const REQUEST_IDLE_MINUTES = 5;
|
|
174
|
+
/** A Web Function environment's memory when CloudWatch has none for the stage (measured: ~250 MB). */
|
|
175
|
+
export const INSTANCE_DEFAULT_MEMORY_MB = 256;
|
|
176
|
+
/**
|
|
177
|
+
* A cold start's INIT when the stage reported none (`env` lines' `initMs`,
|
|
178
|
+
* which came within ~30 ms of Lambda's own figure). Measured: 460–650 ms for
|
|
179
|
+
* the template app's server.
|
|
180
|
+
*/
|
|
181
|
+
export const DEFAULT_INIT_MS = 550;
|
|
182
|
+
|
|
183
|
+
/** One minute of a stage's requests (the telemetry's whole-stage minute rollup). */
|
|
184
|
+
export interface MinuteTraffic {
|
|
185
|
+
/** Start of the minute, epoch ms. */
|
|
186
|
+
ts: number;
|
|
187
|
+
req: number;
|
|
188
|
+
/** Time spent handling them, summed (ms). */
|
|
189
|
+
durMs: number;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
export interface WebComputeSimulationInput {
|
|
193
|
+
/** Minutes with requests in `from`..`to` (the others had none). */
|
|
194
|
+
minutes: readonly MinuteTraffic[];
|
|
195
|
+
from: number;
|
|
196
|
+
to: number;
|
|
197
|
+
/** `web.memoryMb`. */
|
|
198
|
+
requestMemoryMb: number;
|
|
199
|
+
/** What a Web Function environment uses. */
|
|
200
|
+
instanceMemoryMb: number;
|
|
201
|
+
/** `web.concurrency`: requests one Web Function environment serves at once. */
|
|
202
|
+
maxConcurrencyPerEnvironment: number;
|
|
203
|
+
/** A cold start's INIT, ms. */
|
|
204
|
+
initMs: number;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
export interface WebComputeEstimate {
|
|
208
|
+
/** A month of this traffic in request mode. */
|
|
209
|
+
request: { monthlyUsd: number; coldStartsPerMonth: number };
|
|
210
|
+
/** A month of this traffic in instance mode. */
|
|
211
|
+
instance: { monthlyUsd: number; environmentHoursPerMonth: number };
|
|
212
|
+
requestsPerMonth: number;
|
|
213
|
+
/** Days of traffic the month is extrapolated from. */
|
|
214
|
+
days: number;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
const MINUTE = 60_000;
|
|
218
|
+
/** Environment lifetimes are tracked in slots of this many seconds. */
|
|
219
|
+
const SLOT_SECONDS = 10;
|
|
220
|
+
|
|
221
|
+
/**
|
|
222
|
+
* Both modes' monthly cost for the traffic in `minutes`, extrapolated from
|
|
223
|
+
* `from`..`to`. Minute data only has averages, so a minute's concurrency is
|
|
224
|
+
* its handling time over 60 s:
|
|
225
|
+
*
|
|
226
|
+
* - request: handling time × memory, cold starts × INIT × memory, requests.
|
|
227
|
+
* A minute needs as many environments as its concurrency (at least one);
|
|
228
|
+
* environments idle longer than `REQUEST_IDLE_MINUTES` are gone.
|
|
229
|
+
* - instance: environments alive from each busy minute until
|
|
230
|
+
* `INSTANCE_IDLE_SECONDS` after it, as many as its concurrency over
|
|
231
|
+
* `maxConcurrencyPerEnvironment` (at least one), × memory; vCPU for the
|
|
232
|
+
* time an environment has a request in flight; requests.
|
|
233
|
+
*
|
|
234
|
+
* Overlapping requests are what instance mode bills once and request mode
|
|
235
|
+
* bills each, so a stage busy enough to keep requests overlapping is the one
|
|
236
|
+
* that moves to instance mode.
|
|
237
|
+
*/
|
|
238
|
+
export function simulateWebCompute(input: WebComputeSimulationInput): WebComputeEstimate {
|
|
239
|
+
const span = Math.max(input.to - input.from, MINUTE);
|
|
240
|
+
const perMonth = (HOURS_PER_MONTH * 3_600_000) / span;
|
|
241
|
+
const minutes = input.minutes
|
|
242
|
+
.filter((m) => m.req > 0 && m.ts >= input.from && m.ts < input.to)
|
|
243
|
+
.toSorted((a, b) => a.ts - b.ts);
|
|
244
|
+
const prices = WEB_COMPUTE_PRICES_USD;
|
|
245
|
+
|
|
246
|
+
let requests = 0;
|
|
247
|
+
let durationSeconds = 0;
|
|
248
|
+
let coldStarts = 0;
|
|
249
|
+
let warm = 0;
|
|
250
|
+
let lastBusy = Number.NEGATIVE_INFINITY;
|
|
251
|
+
let vcpuSeconds = 0;
|
|
252
|
+
const alive = new Map<number, number>();
|
|
253
|
+
const lifeSlots = Math.ceil((60 + INSTANCE_IDLE_SECONDS) / SLOT_SECONDS);
|
|
254
|
+
for (const m of minutes) {
|
|
255
|
+
requests += m.req;
|
|
256
|
+
durationSeconds += m.durMs / 1000;
|
|
257
|
+
const concurrency = m.durMs / MINUTE;
|
|
258
|
+
|
|
259
|
+
if (m.ts - lastBusy > REQUEST_IDLE_MINUTES * MINUTE) warm = 0;
|
|
260
|
+
const needed = Math.max(1, Math.ceil(concurrency));
|
|
261
|
+
if (needed > warm) {
|
|
262
|
+
coldStarts += needed - warm;
|
|
263
|
+
warm = needed;
|
|
264
|
+
}
|
|
265
|
+
lastBusy = m.ts;
|
|
266
|
+
|
|
267
|
+
const environments = Math.max(1, Math.ceil(concurrency / input.maxConcurrencyPerEnvironment));
|
|
268
|
+
const first = Math.floor(m.ts / 1000 / SLOT_SECONDS);
|
|
269
|
+
for (let s = first; s < first + lifeSlots; s++) alive.set(s, Math.max(alive.get(s) ?? 0, environments));
|
|
270
|
+
// vCPU bills the seconds an environment has a request in flight, once however many overlap.
|
|
271
|
+
// With requests arriving at random, that share of the minute is 1 - e^(-concurrency).
|
|
272
|
+
vcpuSeconds += 60 * environments * (1 - Math.exp(-concurrency / environments));
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
const requestGb = input.requestMemoryMb / 1024;
|
|
276
|
+
const requestUsd =
|
|
277
|
+
(durationSeconds + (coldStarts * input.initMs) / 1000) * requestGb * prices.request.gbSecond +
|
|
278
|
+
(requests * prices.request.perMillionRequests) / 1e6;
|
|
279
|
+
|
|
280
|
+
let environmentSeconds = 0;
|
|
281
|
+
for (const n of alive.values()) environmentSeconds += n * SLOT_SECONDS;
|
|
282
|
+
const instanceUsd =
|
|
283
|
+
environmentSeconds * (input.instanceMemoryMb / 1024) * prices.instance.gbSecond +
|
|
284
|
+
vcpuSeconds * prices.instance.vcpuSecond +
|
|
285
|
+
(requests * prices.instance.perMillionRequests) / 1e6;
|
|
286
|
+
|
|
287
|
+
return {
|
|
288
|
+
request: {
|
|
289
|
+
monthlyUsd: round4(requestUsd * perMonth),
|
|
290
|
+
coldStartsPerMonth: Math.round(coldStarts * perMonth),
|
|
291
|
+
},
|
|
292
|
+
instance: {
|
|
293
|
+
monthlyUsd: round4(instanceUsd * perMonth),
|
|
294
|
+
environmentHoursPerMonth: Math.round(((environmentSeconds * perMonth) / 3600) * 10) / 10,
|
|
295
|
+
},
|
|
296
|
+
requestsPerMonth: Math.round(requests * perMonth),
|
|
297
|
+
days: Math.round((span / 86_400_000) * 100) / 100,
|
|
298
|
+
};
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
// ---------------------------------------------------------------------------
|
|
302
|
+
// Switching
|
|
303
|
+
|
|
304
|
+
/** The other mode must cost this much less (a share of the current one's cost), this many days running. */
|
|
305
|
+
export const COMPUTE_SWITCH_RULE = { cheaperBy: 0.25, days: 3 } as const;
|
|
306
|
+
|
|
307
|
+
/** Days in a row the other mode was cheaper enough, kept on the stage. */
|
|
308
|
+
export interface ComputeStreak {
|
|
309
|
+
to: WebCompute;
|
|
310
|
+
days: number;
|
|
311
|
+
/** The last day it was (UTC, `YYYY-MM-DD`). */
|
|
312
|
+
day: string;
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
/**
|
|
316
|
+
* Today's step of the switching rule: the streak to keep, and the mode to
|
|
317
|
+
* switch to once the other mode has been `COMPUTE_SWITCH_RULE.cheaperBy`
|
|
318
|
+
* cheaper `COMPUTE_SWITCH_RULE.days` days running. A second run on the same
|
|
319
|
+
* day changes nothing; a day the other mode wasn't cheaper enough, or a day
|
|
320
|
+
* without a run, starts the count over.
|
|
321
|
+
*/
|
|
322
|
+
export function nextComputeStreak(input: {
|
|
323
|
+
current: WebCompute;
|
|
324
|
+
estimate: Pick<WebComputeEstimate, 'request' | 'instance'>;
|
|
325
|
+
streak?: ComputeStreak | undefined;
|
|
326
|
+
/** Today, UTC `YYYY-MM-DD`. */
|
|
327
|
+
day: string;
|
|
328
|
+
}): { streak?: ComputeStreak; switchTo?: WebCompute } {
|
|
329
|
+
const other: WebCompute = input.current === 'request' ? 'instance' : 'request';
|
|
330
|
+
const current = input.estimate[input.current].monthlyUsd;
|
|
331
|
+
const cheaper = input.estimate[other].monthlyUsd <= current * (1 - COMPUTE_SWITCH_RULE.cheaperBy);
|
|
332
|
+
if (!cheaper || current <= 0) return {};
|
|
333
|
+
const prev = input.streak?.to === other ? input.streak : undefined;
|
|
334
|
+
const days = prev?.day === input.day ? prev.days : prev?.day === previousDay(input.day) ? prev.days + 1 : 1;
|
|
335
|
+
if (days >= COMPUTE_SWITCH_RULE.days) return { switchTo: other };
|
|
336
|
+
return { streak: { to: other, days, day: input.day } };
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
const previousDay = (day: string) =>
|
|
340
|
+
new Date(Date.parse(`${day}T00:00:00Z`) - 86_400_000).toISOString().slice(0, 10);
|
|
341
|
+
|
|
342
|
+
const round4 = (n: number) => Math.round(n * 10_000) / 10_000;
|