@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.
- package/dist/api.d.ts +1847 -212
- package/dist/api.js +694 -1
- package/dist/api.js.map +1 -1
- package/dist/auth.d.ts +19 -0
- package/dist/auth.js +32 -0
- 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 +69 -13
- 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 +70 -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 +21 -1
- package/dist/config.js +16 -0
- package/dist/config.js.map +1 -1
- package/dist/constants.d.ts +67 -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/fingerprint.d.ts +9 -0
- package/dist/fingerprint.js +19 -0
- package/dist/fingerprint.js.map +1 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +6 -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 +357 -112
- package/dist/manifest.js +270 -72
- package/dist/manifest.js.map +1 -1
- package/dist/naming.d.ts +93 -6
- package/dist/naming.js +98 -6
- package/dist/naming.js.map +1 -1
- package/dist/platform-api.d.ts +7792 -0
- package/dist/platform-api.js +455 -0
- package/dist/platform-api.js.map +1 -0
- 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 +7 -1
- package/dist/router/decide.js +42 -5
- 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 +55 -0
- package/dist/storage.js +112 -0
- package/dist/storage.js.map +1 -0
- package/dist/telemetry.d.ts +350 -83
- package/dist/telemetry.js +188 -15
- 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 +28 -8
- package/src/api.ts +864 -238
- package/src/auth.ts +37 -0
- package/src/base64url.ts +13 -0
- package/src/bindings.ts +74 -7
- package/src/cloudfront-function.ts +70 -2
- package/src/compute.ts +86 -0
- package/src/config.ts +34 -2
- package/src/constants.ts +76 -1
- package/src/email.ts +168 -0
- package/src/fingerprint.ts +20 -0
- package/src/index.ts +6 -0
- package/src/jobs.ts +281 -0
- package/src/manifest.ts +542 -114
- package/src/naming.ts +103 -8
- package/src/platform-api.ts +630 -0
- package/src/realtime.ts +298 -0
- package/src/router/decide.d.ts +7 -1
- package/src/router/decide.js +42 -5
- package/src/router.ts +33 -13
- package/src/runtime-config.ts +70 -0
- package/src/storage.ts +120 -0
- package/src/telemetry.ts +198 -93
- package/src/web-compute.ts +342 -0
package/src/auth.ts
CHANGED
|
@@ -21,6 +21,43 @@ export const AUTH_COOKIES = {
|
|
|
21
21
|
|
|
22
22
|
export const AUTH_SCOPES = ['openid', 'email', 'profile'] as const;
|
|
23
23
|
|
|
24
|
+
/**
|
|
25
|
+
* Backslashes, spaces, and ASCII control characters (`<= ' '` covers C0 and space).
|
|
26
|
+
* All of them are ASCII, so checking UTF-16 code units one by one is exact.
|
|
27
|
+
*/
|
|
28
|
+
const unsafeInRedirect = (c: string) => c === '\\' || c <= ' ' || c === '\u007f';
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Only same-origin absolute paths are allowed as post-login destinations.
|
|
32
|
+
* Browsers drop tabs and newlines from URLs (`/\t/evil.com` becomes
|
|
33
|
+
* `//evil.com`), so control characters and spaces are refused too.
|
|
34
|
+
*/
|
|
35
|
+
export function safeRedirect(target: string | null | undefined): string {
|
|
36
|
+
if (!target?.startsWith('/') || target.startsWith('//') || target.split('').some(unsafeInRedirect))
|
|
37
|
+
return '/';
|
|
38
|
+
return target;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Path that starts sign-in and returns to `redirect` afterwards. */
|
|
42
|
+
export function loginPath(redirect = '/'): string {
|
|
43
|
+
return `${AUTH_ROUTES.login}?redirect=${encodeURIComponent(safeRedirect(redirect))}`;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Path that signs out and then goes to `redirect`. */
|
|
47
|
+
export function logoutPath(redirect = '/'): string {
|
|
48
|
+
return `${AUTH_ROUTES.logout}?redirect=${encodeURIComponent(safeRedirect(redirect))}`;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Body of every platform 401 (the `auth.required` gate and the SDK's
|
|
53
|
+
* `Unauthorized` error), so clients decode one shape.
|
|
54
|
+
*/
|
|
55
|
+
export const UNAUTHORIZED_BODY = {
|
|
56
|
+
_tag: 'Unauthorized',
|
|
57
|
+
message: 'Sign in required',
|
|
58
|
+
loginUrl: AUTH_ROUTES.login,
|
|
59
|
+
} as const;
|
|
60
|
+
|
|
24
61
|
/** The user object apps see. */
|
|
25
62
|
export interface PlatformUser {
|
|
26
63
|
/** Stable user id (Cognito `sub`). Same across all platform apps. */
|
package/src/base64url.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/** Unpadded base64url (RFC 4648 §5), without Node's Buffer so it runs anywhere. */
|
|
2
|
+
export function base64url(bytes: Uint8Array): string {
|
|
3
|
+
let bin = '';
|
|
4
|
+
for (const b of bytes) bin += String.fromCharCode(b);
|
|
5
|
+
return btoa(bin).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export function fromBase64url(s: string): Uint8Array<ArrayBuffer> {
|
|
9
|
+
const bin = atob(s.replace(/-/g, '+').replace(/_/g, '/'));
|
|
10
|
+
const out = new Uint8Array(bin.length);
|
|
11
|
+
for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
|
|
12
|
+
return out;
|
|
13
|
+
}
|
package/src/bindings.ts
CHANGED
|
@@ -7,7 +7,8 @@
|
|
|
7
7
|
export const BINDINGS_ENV = 'PLATFORM_BINDINGS';
|
|
8
8
|
|
|
9
9
|
export interface Bindings {
|
|
10
|
-
|
|
10
|
+
/** 2 since jobs were pushed (SDK 0.4.0): `queues` gave way to `jobs`. */
|
|
11
|
+
v: 2;
|
|
11
12
|
app: string;
|
|
12
13
|
stage: string;
|
|
13
14
|
/** Public hostname, e.g. `foo.ericminassian.com` or `foo.localhost:3000`. */
|
|
@@ -17,16 +18,46 @@ export interface Bindings {
|
|
|
17
18
|
/** Deployment id currently running. */
|
|
18
19
|
revision: string;
|
|
19
20
|
region: string;
|
|
21
|
+
/** Account id, so the SDK can build ARNs from the names below. */
|
|
22
|
+
account: string;
|
|
20
23
|
/** DynamoDB table backing `db` (present when `db: true`). */
|
|
21
24
|
table?: string;
|
|
22
|
-
|
|
25
|
+
/** Queues, events and crons (present when the stage has a worker). */
|
|
26
|
+
jobs?: JobBindings;
|
|
23
27
|
bus?: { name: string; arn: string };
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
secrets: { path: string; sharedPath: string; names: string[] };
|
|
28
|
+
storage?: StorageBindings;
|
|
29
|
+
secrets: { path: string; sharedPath: string; names: readonly string[] };
|
|
27
30
|
auth?: AuthBindings;
|
|
28
|
-
|
|
31
|
+
realtime?: RealtimeBindings;
|
|
32
|
+
email?: EmailBindings;
|
|
33
|
+
/** Worker function name: direct `invoke` jobs, and every handler not in `jobs.fns`. */
|
|
29
34
|
worker?: string;
|
|
35
|
+
/**
|
|
36
|
+
* The stage's secret (32 random bytes, base64url), kept in SSM at
|
|
37
|
+
* `names.stageKeyParameter`. The SDK derives a key per purpose from it, e.g.
|
|
38
|
+
* to seal `db` query cursors. Absent on stages deployed before it existed.
|
|
39
|
+
*/
|
|
40
|
+
stageKey?: string;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Where jobs go and how often they're tried. Handlers are keyed `kind:name`
|
|
45
|
+
* (`handlerKey`); only what differs from the default is listed, since Lambda
|
|
46
|
+
* caps a function's environment at 4 KB.
|
|
47
|
+
*/
|
|
48
|
+
export interface JobBindings {
|
|
49
|
+
/** Declared queues. */
|
|
50
|
+
queues: readonly string[];
|
|
51
|
+
/** Handlers that run in a function of their own, by key: its name. The rest run on `worker`. */
|
|
52
|
+
fns: Record<string, string>;
|
|
53
|
+
/** Handlers whose attempts aren't their kind's `DEFAULT_ATTEMPTS`, by key. */
|
|
54
|
+
attempts: Record<string, number>;
|
|
55
|
+
/** The stage's dead-letter queue's URL (`names.deadLetters`). */
|
|
56
|
+
dead: string;
|
|
57
|
+
/** The stage's schedule group, where retries and delayed sends are one-shot schedules. */
|
|
58
|
+
group: string;
|
|
59
|
+
/** The role Scheduler invokes them as: the stage's own. */
|
|
60
|
+
role: string;
|
|
30
61
|
}
|
|
31
62
|
|
|
32
63
|
export interface AuthBindings {
|
|
@@ -43,6 +74,42 @@ export interface AuthBindings {
|
|
|
43
74
|
required: boolean;
|
|
44
75
|
}
|
|
45
76
|
|
|
77
|
+
/** The shared storage bucket: a private store is `prefix + <name>/`, a public one `publicPrefix + <name>/`. */
|
|
78
|
+
export interface StorageBindings {
|
|
79
|
+
bucket: string;
|
|
80
|
+
prefix: string;
|
|
81
|
+
/** Every store's name. */
|
|
82
|
+
stores: readonly string[];
|
|
83
|
+
/** The stores the edge serves at `STORAGE_PATH` (absent on stages deployed before there were any). */
|
|
84
|
+
public?: readonly string[];
|
|
85
|
+
publicPrefix?: string;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export interface RealtimeBindings {
|
|
89
|
+
/** The stage's channel namespace. */
|
|
90
|
+
namespace: string;
|
|
91
|
+
/** AppSync's HTTP publish endpoint (`https://<domain>/event`; `http://127.0.0.1:<port>/event` locally). */
|
|
92
|
+
publishUrl: string;
|
|
93
|
+
subscribe: 'public' | 'signed-in';
|
|
94
|
+
/** Declared channel patterns (`board`, `boards/*`): the SDK publishes only to these. */
|
|
95
|
+
channels: readonly string[];
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export interface EmailBindings {
|
|
99
|
+
/** `ses` when deployed; `local` under `plat dev` / `plat test`, where the CLI captures mail and nothing is sent. */
|
|
100
|
+
mode: 'ses' | 'local';
|
|
101
|
+
/** The stage's address, e.g. `todo@mail.platform.ericminassian.com`. */
|
|
102
|
+
from: string;
|
|
103
|
+
/** Display name (`email.name`). */
|
|
104
|
+
name?: string;
|
|
105
|
+
/** SES tenant and configuration set (both `names.emailTenant`). */
|
|
106
|
+
tenant: string;
|
|
107
|
+
/** Recipients per UTC day. */
|
|
108
|
+
dailyLimit: number;
|
|
109
|
+
/** Table holding the stage's usage rows (the platform's telemetry table; `telemetryKeys.email`). */
|
|
110
|
+
usageTable: string;
|
|
111
|
+
}
|
|
112
|
+
|
|
46
113
|
export function encodeBindings(b: Bindings): string {
|
|
47
114
|
return JSON.stringify(b);
|
|
48
115
|
}
|
|
@@ -54,6 +121,6 @@ export function decodeBindings(raw: string | undefined): Bindings {
|
|
|
54
121
|
);
|
|
55
122
|
}
|
|
56
123
|
const b = JSON.parse(raw) as Bindings;
|
|
57
|
-
if (b.v !==
|
|
124
|
+
if (b.v !== 2) throw new Error(`Unsupported ${BINDINGS_ENV} version ${String((b as { v?: unknown }).v)}`);
|
|
58
125
|
return b;
|
|
59
126
|
}
|
|
@@ -1,11 +1,17 @@
|
|
|
1
1
|
import { readFileSync } from 'node:fs';
|
|
2
|
-
import { HOST_HEADER } from './constants.ts';
|
|
2
|
+
import { HOST_HEADER, ORIGIN_HEADER } from './constants.ts';
|
|
3
|
+
import { APPSYNC_REALTIME_PATH, REALTIME_KVS_KEY } from './realtime.ts';
|
|
4
|
+
import { PUBLIC_STORAGE_ROOT, STORAGE_CACHE_HOST, STORAGE_PATH } from './storage.ts';
|
|
3
5
|
|
|
4
6
|
/**
|
|
5
7
|
* Builds the CloudFront Function (JavaScript runtime 2.0) that routes every
|
|
6
8
|
* request on `*.<domain>`: look up the host in the KeyValueStore, then either
|
|
7
9
|
* rewrite the URI into the sites bucket (the distribution's default S3 origin)
|
|
8
|
-
* or switch the origin to the stage's Lambda Web Function with OAC
|
|
10
|
+
* or switch the origin to the stage's server: a Lambda Web Function with OAC
|
|
11
|
+
* signing, or a request-mode function URL with the stage's origin secret.
|
|
12
|
+
* `REALTIME_PATH` is answered here (the browser's config) or passed to the
|
|
13
|
+
* AppSync realtime endpoint (a WebSocket). The `STORAGE_PATH` behavior runs
|
|
14
|
+
* it too: a public store's file is rewritten into that behavior's origin.
|
|
9
15
|
*/
|
|
10
16
|
export function buildRouterFunctionCode(opts: { kvsId: string; originReadTimeoutSeconds?: number }): string {
|
|
11
17
|
const decideSrc = readFileSync(new URL('./router/decide.js', import.meta.url), 'utf8')
|
|
@@ -18,6 +24,41 @@ const kvs = cf.kvs(${JSON.stringify(opts.kvsId)});
|
|
|
18
24
|
|
|
19
25
|
${decideSrc}
|
|
20
26
|
|
|
27
|
+
function health(rec) {
|
|
28
|
+
var body = JSON.stringify({ ok: true, app: rec.app, stage: rec.stage, revision: rec.d });
|
|
29
|
+
return { statusCode: 200, statusDescription: 'OK', headers: { 'content-type': { value: 'application/json' }, 'cache-control': { value: 'no-store' } }, body: body };
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function json(body) {
|
|
33
|
+
return { statusCode: 200, statusDescription: 'OK', headers: { 'content-type': { value: 'application/json' }, 'cache-control': { value: 'no-store' } }, body: JSON.stringify(body) };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
async function realtime(req, rec) {
|
|
37
|
+
var raw;
|
|
38
|
+
try { raw = await kvs.get(${JSON.stringify(REALTIME_KVS_KEY)}); } catch (e) { return notFound(); }
|
|
39
|
+
var rt;
|
|
40
|
+
try { rt = JSON.parse(raw); } catch (e) { return notFound(); }
|
|
41
|
+
// CloudFront drops Upgrade and Connection before functions run; a WebSocket
|
|
42
|
+
// handshake still carries Sec-WebSocket-Key.
|
|
43
|
+
if (req.headers['sec-websocket-key']) {
|
|
44
|
+
req.uri = ${JSON.stringify(APPSYNC_REALTIME_PATH)};
|
|
45
|
+
req.querystring = {};
|
|
46
|
+
req.cookies = {};
|
|
47
|
+
delete req.headers['authorization'];
|
|
48
|
+
// AppSync authenticates the subprotocol header, not a signature: no OAC.
|
|
49
|
+
cf.updateRequestOrigin({
|
|
50
|
+
domainName: rt.o,
|
|
51
|
+
originAccessControlConfig: { enabled: false },
|
|
52
|
+
customOriginConfig: { port: 443, protocol: 'https', sslProtocols: ['TLSv1.2'] },
|
|
53
|
+
timeouts: { readTimeout: ${readTimeout} }
|
|
54
|
+
});
|
|
55
|
+
return req;
|
|
56
|
+
}
|
|
57
|
+
var cfg = { v: 1, host: rt.h, namespace: rec.rt.n, subscribe: rec.rt.m === 's' ? 'signed-in' : 'public' };
|
|
58
|
+
if (rec.rt.m !== 's') cfg.apiKey = rt.k;
|
|
59
|
+
return json(cfg);
|
|
60
|
+
}
|
|
61
|
+
|
|
21
62
|
function notFound() {
|
|
22
63
|
return { statusCode: 404, statusDescription: 'Not Found', headers: { 'content-type': { value: 'text/plain' }, 'cache-control': { value: 'no-store' } }, body: 'Nothing is deployed here.' };
|
|
23
64
|
}
|
|
@@ -32,6 +73,8 @@ async function handler(event) {
|
|
|
32
73
|
try { rec = JSON.parse(raw); } catch (e) { return notFound(); }
|
|
33
74
|
var d = decide(rec, req.uri);
|
|
34
75
|
if (d.t === 'notfound') return notFound();
|
|
76
|
+
if (d.t === 'health') return health(rec);
|
|
77
|
+
if (d.t === 'realtime') return await realtime(req, rec);
|
|
35
78
|
req.headers[${JSON.stringify(HOST_HEADER)}] = { value: host };
|
|
36
79
|
if (d.t === 'static') {
|
|
37
80
|
req.uri = d.key;
|
|
@@ -39,6 +82,31 @@ async function handler(event) {
|
|
|
39
82
|
delete req.headers['authorization'];
|
|
40
83
|
return req;
|
|
41
84
|
}
|
|
85
|
+
// Only on the ${STORAGE_PATH}* behavior, whose origin is the storage bucket under ${PUBLIC_STORAGE_ROOT}.
|
|
86
|
+
// Its own cache key (STORAGE_CACHE_HOST in core). No query string: the OAC-signed request would
|
|
87
|
+
// pass S3's response-* overrides through.
|
|
88
|
+
if (d.t === 'storage') {
|
|
89
|
+
req.headers[${JSON.stringify(HOST_HEADER)}] = { value: ${JSON.stringify(STORAGE_CACHE_HOST)} };
|
|
90
|
+
req.uri = d.key;
|
|
91
|
+
req.querystring = {};
|
|
92
|
+
req.cookies = {};
|
|
93
|
+
delete req.headers['authorization'];
|
|
94
|
+
return req;
|
|
95
|
+
}
|
|
96
|
+
// A viewer's copy of the origin header never reaches a server.
|
|
97
|
+
delete req.headers[${JSON.stringify(ORIGIN_HEADER)}];
|
|
98
|
+
if (rec.c === 'r') {
|
|
99
|
+
// Request mode: a function URL, which anyone may call, so the server only answers requests
|
|
100
|
+
// carrying the stage's secret. OAC would make clients hash POST bodies (x-amz-content-sha256).
|
|
101
|
+
cf.updateRequestOrigin({
|
|
102
|
+
domainName: rec.o,
|
|
103
|
+
originAccessControlConfig: { enabled: false },
|
|
104
|
+
customOriginConfig: { port: 443, protocol: 'https', sslProtocols: ['TLSv1.2'] },
|
|
105
|
+
customHeaders: { ${JSON.stringify(ORIGIN_HEADER)}: rec.k },
|
|
106
|
+
timeouts: { readTimeout: ${readTimeout} }
|
|
107
|
+
});
|
|
108
|
+
return req;
|
|
109
|
+
}
|
|
42
110
|
cf.updateRequestOrigin({
|
|
43
111
|
domainName: rec.o,
|
|
44
112
|
originAccessControlConfig: { enabled: true, signingBehavior: 'always-amz-auth', signingProtocol: 'sigv4', originType: 'lambda' },
|
package/src/compute.ts
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Container compute (ECS on Fargate): the sizes a container may have and
|
|
3
|
+
* what one costs while it runs. Shared by the manifest schema, the engine,
|
|
4
|
+
* the console's cost page and `plat deploy`.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
/** vCPUs a Fargate task may have (the platform caps it at 4). */
|
|
8
|
+
export const FARGATE_CPUS = [0.25, 0.5, 1, 2, 4] as const;
|
|
9
|
+
export type FargateCpu = (typeof FARGATE_CPUS)[number];
|
|
10
|
+
|
|
11
|
+
/** Memory (MB) Fargate allows for each vCPU size. */
|
|
12
|
+
export function fargateMemoryOptions(cpu: FargateCpu): number[] {
|
|
13
|
+
if (cpu === 0.25) return [512, 1024, 2048];
|
|
14
|
+
const [from, to] = MEMORY_RANGES[cpu];
|
|
15
|
+
return Array.from({ length: (to - from) / 1024 + 1 }, (_, i) => from + i * 1024);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** Above 0.25 vCPU, memory goes from..to in steps of 1024 MB. */
|
|
19
|
+
const MEMORY_RANGES: Record<Exclude<FargateCpu, 0.25>, readonly [number, number]> = {
|
|
20
|
+
0.5: [1024, 4096],
|
|
21
|
+
1: [2048, 8192],
|
|
22
|
+
2: [4096, 16384],
|
|
23
|
+
4: [8192, 30720],
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
/** Why `cpu`/`memoryMb` isn't a size Fargate runs, or null when it is. */
|
|
27
|
+
export function fargateSizeIssue(cpu: number, memoryMb: number): string | null {
|
|
28
|
+
if (!(FARGATE_CPUS as readonly number[]).includes(cpu)) {
|
|
29
|
+
return `cpu must be one of ${FARGATE_CPUS.join(', ')}`;
|
|
30
|
+
}
|
|
31
|
+
const options = fargateMemoryOptions(cpu as FargateCpu);
|
|
32
|
+
if (options.includes(memoryMb)) return null;
|
|
33
|
+
const allowed =
|
|
34
|
+
cpu === 0.25 ? options.join(', ') : `${options[0]}-${options[options.length - 1]} in steps of 1024`;
|
|
35
|
+
return `memoryMb ${memoryMb} doesn't fit ${cpu} vCPU: use ${allowed}`;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** ECS task-definition units: 1024 per vCPU. */
|
|
39
|
+
export function fargateCpuUnits(cpu: number): number {
|
|
40
|
+
return Math.round(cpu * 1024);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Prices behind the estimates: us-east-1, Linux on ARM (Graviton), checked
|
|
45
|
+
* 2026-11-15. Spot prices move with supply and demand, so Spot estimates are
|
|
46
|
+
* approximate. Every task gets a public IPv4 address (there is no NAT), which
|
|
47
|
+
* AWS bills by the hour whatever the capacity.
|
|
48
|
+
*/
|
|
49
|
+
export const CONTAINER_PRICES_USD = {
|
|
50
|
+
onDemand: { vcpuHour: 0.03238, gbHour: 0.00356 },
|
|
51
|
+
spot: { vcpuHour: 0.00995, gbHour: 0.00109 },
|
|
52
|
+
publicIpv4Hour: 0.005,
|
|
53
|
+
} as const;
|
|
54
|
+
|
|
55
|
+
/** Hours AWS bills a month of always-on capacity for. */
|
|
56
|
+
export const HOURS_PER_MONTH = 730;
|
|
57
|
+
|
|
58
|
+
export interface ContainerCostEstimate {
|
|
59
|
+
/** vCPU and memory, per month. */
|
|
60
|
+
computeUsd: number;
|
|
61
|
+
/** The task's public IPv4 address, per month. */
|
|
62
|
+
publicIpv4Usd: number;
|
|
63
|
+
totalUsd: number;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** What one container of this size costs a month if it runs all the time. */
|
|
67
|
+
export function estimateContainerCost(size: {
|
|
68
|
+
cpu: number;
|
|
69
|
+
memoryMb: number;
|
|
70
|
+
spot: boolean;
|
|
71
|
+
}): ContainerCostEstimate {
|
|
72
|
+
const price = size.spot ? CONTAINER_PRICES_USD.spot : CONTAINER_PRICES_USD.onDemand;
|
|
73
|
+
const hourly = size.cpu * price.vcpuHour + (size.memoryMb / 1024) * price.gbHour;
|
|
74
|
+
const computeUsd = round2(hourly * HOURS_PER_MONTH);
|
|
75
|
+
const publicIpv4Usd = round2(CONTAINER_PRICES_USD.publicIpv4Hour * HOURS_PER_MONTH);
|
|
76
|
+
return { computeUsd, publicIpv4Usd, totalUsd: round2(computeUsd + publicIpv4Usd) };
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** `0.25 vCPU · 512 MB · Spot`. */
|
|
80
|
+
export function describeContainerSize(size: { cpu: number; memoryMb: number; spot: boolean }): string {
|
|
81
|
+
return `${size.cpu} vCPU · ${size.memoryMb} MB · ${size.spot ? 'Spot' : 'on-demand'}`;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function round2(n: number): number {
|
|
85
|
+
return Math.round(n * 100) / 100;
|
|
86
|
+
}
|
package/src/config.ts
CHANGED
|
@@ -3,7 +3,9 @@
|
|
|
3
3
|
* member allowlist. Members are GitHub usernames; inviting someone is a PR
|
|
4
4
|
* plus a platform deploy. No emails or account ids here (the repo is public).
|
|
5
5
|
*/
|
|
6
|
-
|
|
6
|
+
import { Schema } from 'effect';
|
|
7
|
+
export const MemberRole = Schema.Literals(['admin', 'member']);
|
|
8
|
+
export type MemberRole = typeof MemberRole.Type;
|
|
7
9
|
|
|
8
10
|
export interface Member {
|
|
9
11
|
github: string;
|
|
@@ -32,11 +34,41 @@ export interface PlatformConfig {
|
|
|
32
34
|
reservedAppNames: string[];
|
|
33
35
|
/** Preview stages untouched for this long are destroyed by the reaper. */
|
|
34
36
|
previewTtlDays: number;
|
|
35
|
-
limits: {
|
|
37
|
+
limits: {
|
|
38
|
+
appsPerMember: number;
|
|
39
|
+
stagesPerApp: number;
|
|
40
|
+
/** Highest `email.dailyLimit` an app may declare (recipients per UTC day). */
|
|
41
|
+
emailsPerDay: number;
|
|
42
|
+
/**
|
|
43
|
+
* The edge floor's limit for every app: requests one client (IP address)
|
|
44
|
+
* may send one host per minute before the edge answers 429 for a while.
|
|
45
|
+
* Enforced only while the floor is on (`edgeFloorAt`); apps set finer
|
|
46
|
+
* limits with `RateLimits`.
|
|
47
|
+
*/
|
|
48
|
+
edgeRequestsPerMinute?: number;
|
|
49
|
+
/**
|
|
50
|
+
* Requests per minute across the whole edge, every app together, that
|
|
51
|
+
* turn the floor on: the control plane attaches an AWS WAF web ACL with
|
|
52
|
+
* the `edgeRequestsPerMinute` rule, and removes it after an hour under
|
|
53
|
+
* this rate. Set both or neither; without them there is no floor.
|
|
54
|
+
*/
|
|
55
|
+
edgeFloorAt?: number;
|
|
56
|
+
/** Long-running services one stage's plat.config.ts may declare: the one resource billed while idle. */
|
|
57
|
+
servicesPerApp: number;
|
|
58
|
+
};
|
|
36
59
|
telemetry: { logRetentionDays: { prod: number; other: number } };
|
|
37
60
|
}
|
|
38
61
|
|
|
39
62
|
export function definePlatformConfig(config: PlatformConfig): PlatformConfig {
|
|
63
|
+
const { edgeRequestsPerMinute: perClient, edgeFloorAt: at } = config.limits;
|
|
64
|
+
// WAF's rate-based rules count from 10 requests.
|
|
65
|
+
if (perClient !== undefined && (!Number.isSafeInteger(perClient) || perClient < 10))
|
|
66
|
+
throw new Error(`limits.edgeRequestsPerMinute must be an integer of at least 10, not ${perClient}`);
|
|
67
|
+
if (at !== undefined && (!Number.isSafeInteger(at) || at < 1))
|
|
68
|
+
throw new Error(`limits.edgeFloorAt must be a positive integer, not ${at}`);
|
|
69
|
+
// One without the other is a floor that never turns on, or one with no limit to enforce.
|
|
70
|
+
if ((perClient === undefined) !== (at === undefined))
|
|
71
|
+
throw new Error('limits.edgeRequestsPerMinute and limits.edgeFloorAt are set together, or neither');
|
|
40
72
|
const seen = new Set<string>();
|
|
41
73
|
for (const m of config.members) {
|
|
42
74
|
const key = m.github.toLowerCase();
|
package/src/constants.ts
CHANGED
|
@@ -20,16 +20,74 @@ export const PLATFORM_DEFAULTS = {
|
|
|
20
20
|
export const PLATFORM_PATH_PREFIX = '/__platform/';
|
|
21
21
|
export const HEALTH_PATH = '/__platform/health';
|
|
22
22
|
|
|
23
|
+
/**
|
|
24
|
+
* Body served at `HEALTH_PATH`: by the SDK when the stage has a server, else
|
|
25
|
+
* by the edge router from its route record. `revision` is the deployment id,
|
|
26
|
+
* so a poller can tell which deployment answered.
|
|
27
|
+
*/
|
|
28
|
+
export interface HealthResponse {
|
|
29
|
+
ok: true;
|
|
30
|
+
app: string;
|
|
31
|
+
stage: string;
|
|
32
|
+
revision: string;
|
|
33
|
+
}
|
|
34
|
+
|
|
23
35
|
/** Header the router sets so apps (and the cache key) see the public host. */
|
|
24
36
|
export const HOST_HEADER = 'x-platform-host';
|
|
25
37
|
/** Trace propagation header (W3C traceparent is also honored). */
|
|
26
38
|
export const TRACE_HEADER = 'x-platform-trace';
|
|
27
39
|
|
|
40
|
+
/**
|
|
41
|
+
* The secret the router sends a request-mode server (a function URL anyone
|
|
42
|
+
* can call) with each request: the stage's `originSecret`. The SDK answers
|
|
43
|
+
* 403 to a request without it before any app code runs.
|
|
44
|
+
*/
|
|
45
|
+
export const ORIGIN_HEADER = 'x-platform-origin';
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* The client's `ip:port` as the edge saw the connection; IPv6 is unbracketed
|
|
49
|
+
* (`2001:db8::7:51234`). CloudFront sets it and replaces any copy a client
|
|
50
|
+
* sends (so does `plat dev`), and servers only take requests from the edge
|
|
51
|
+
* (Web Function endpoints signed ones, request-mode servers those carrying
|
|
52
|
+
* `ORIGIN_HEADER`), so apps can trust it.
|
|
53
|
+
*/
|
|
54
|
+
export const VIEWER_ADDRESS_HEADER = 'cloudfront-viewer-address';
|
|
55
|
+
/** The client's country (ISO 3166-1 alpha-2), from the edge; absent locally. */
|
|
56
|
+
export const VIEWER_COUNTRY_HEADER = 'cloudfront-viewer-country';
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Partition-key prefix of the SDK's rate-limit counters in a stage's table
|
|
60
|
+
* (`_rl#<limit>#<key>`). Collection names start with a letter, so no
|
|
61
|
+
* document shares it; the data browser leaves these items out.
|
|
62
|
+
*/
|
|
63
|
+
export const RATE_LIMIT_PK_PREFIX = '_rl#';
|
|
64
|
+
|
|
65
|
+
/** How long the edge's request floor asks a client over it to wait: WAF counts the last minute. */
|
|
66
|
+
export const EDGE_RETRY_AFTER_SECONDS = 60;
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* The control plane worker's invoke job that the edge floor's alarm runs when
|
|
70
|
+
* it goes off (an EventBridge rule in the foundation stack): it turns the floor on.
|
|
71
|
+
*/
|
|
72
|
+
export const EDGE_FLOOR_JOB = 'edge-floor';
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* The body of the edge floor's 429 (`limits.edgeRequestsPerMinute`): the SDK's
|
|
76
|
+
* `RateLimited`, so a generated web client decodes it like an app's own 429.
|
|
77
|
+
*/
|
|
78
|
+
export const EDGE_RATE_LIMITED_BODY = {
|
|
79
|
+
_tag: 'RateLimited',
|
|
80
|
+
message: `Too many requests. Try again in ${EDGE_RETRY_AFTER_SECONDS} seconds.`,
|
|
81
|
+
retryAfter: EDGE_RETRY_AFTER_SECONDS,
|
|
82
|
+
} as const;
|
|
83
|
+
|
|
28
84
|
/** Tags on every AWS resource the engine creates. */
|
|
29
85
|
export const TAGS = {
|
|
30
86
|
managed: 'platform:managed',
|
|
31
87
|
app: 'platform:app',
|
|
32
88
|
stage: 'platform:stage',
|
|
89
|
+
/** On resources built per deployment (a service's task definition), so it can be found again. */
|
|
90
|
+
deployment: 'platform:deployment',
|
|
33
91
|
} as const;
|
|
34
92
|
|
|
35
93
|
/** The production stage. Its host has no stage suffix. */
|
|
@@ -37,5 +95,22 @@ export const PROD_STAGE = 'prod';
|
|
|
37
95
|
/** Stage name used by `plat dev` against the AWS Emulator. */
|
|
38
96
|
export const LOCAL_STAGE = 'local';
|
|
39
97
|
|
|
40
|
-
/** Lambda runtime for
|
|
98
|
+
/** Lambda runtime for Web Functions, request-mode servers and worker (Event) Functions. */
|
|
41
99
|
export const NODE_RUNTIME = 'nodejs24.x';
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Base of every container image the platform builds: Node.js 24 on Debian
|
|
103
|
+
* slim, linux/arm64, pinned to one image manifest (not the multi-platform
|
|
104
|
+
* index). The engine copies it from ECR Public into the platform's
|
|
105
|
+
* repository the first time a deploy needs it, so bumping it is a deliberate
|
|
106
|
+
* change: look up the arm64 entry of the tag's index and update both fields.
|
|
107
|
+
*/
|
|
108
|
+
export const CONTAINER_BASE_IMAGE = {
|
|
109
|
+
registry: 'public.ecr.aws',
|
|
110
|
+
repository: 'docker/library/node',
|
|
111
|
+
tag: '24-slim',
|
|
112
|
+
digest: 'sha256:5f8fabfed57b75127de2f584593d67a9e8c90e6b0f65652871f9ef0f759c0299',
|
|
113
|
+
} as const;
|
|
114
|
+
|
|
115
|
+
/** Environment variable naming the service a container runs (`ais`). */
|
|
116
|
+
export const SERVICE_ENV = 'PLATFORM_SERVICE';
|