@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/manifest.ts CHANGED
@@ -1,6 +1,17 @@
1
1
  import { Effect, Schema } from 'effect';
2
+ import { FARGATE_CPUS, type FargateCpu, fargateSizeIssue } from './compute.ts';
2
3
  import { validateCron } from './cron.ts';
3
- import { APP_NAME_PATTERN, ENV_NAME_PATTERN, EVENT_TYPE_PATTERN, RESOURCE_KEY_PATTERN } from './naming.ts';
4
+ import { EMAIL_DEFAULT_DAILY_LIMIT, EMAIL_NAME_MESSAGE, EMAIL_NAME_PATTERN } from './email.ts';
5
+ import { DEFAULT_ATTEMPTS, MAX_ATTEMPTS } from './jobs.ts';
6
+ import {
7
+ APP_NAME_PATTERN,
8
+ ENV_NAME_PATTERN,
9
+ EVENT_TYPE_PATTERN,
10
+ names,
11
+ RESOURCE_KEY_PATTERN,
12
+ } from './naming.ts';
13
+ import { CHANNEL_DECLARATION_PATTERN, CHANNEL_MESSAGE, realtimeIssues } from './realtime.ts';
14
+ import { WEB_COMPUTE_SETTINGS, WEB_REQUEST_MEMORY_MB, type WebComputeSetting } from './web-compute.ts';
4
15
 
5
16
  /**
6
17
  * The app's config file, at the app root. `plat` evaluates it and sends the
@@ -56,29 +67,60 @@ const WebSchema = Schema.Struct({
56
67
  serverRoutes: Schema.Array(Schema.String.check(Schema.isStartingWith('/'))).pipe(orElse(['/api/'])),
57
68
  timeoutSeconds: intBetween(3, 900).pipe(orElse(30)),
58
69
  concurrency: intBetween(1, 128).pipe(orElse(64)),
70
+ compute: Schema.Literals(WEB_COMPUTE_SETTINGS).pipe(orElse('auto')),
71
+ memoryMb: intBetween(128, 10240).pipe(orElse(WEB_REQUEST_MEMORY_MB)),
72
+ maxEnvironments: Schema.optional(intBetween(2, 10000)),
59
73
  }).check(
60
74
  Schema.makeFilter((w) =>
61
75
  w.server || w.static ? undefined : 'web needs a server, a static directory, or both',
62
76
  ),
63
77
  );
64
78
 
79
+ const WORKER_TIMEOUT_SECONDS = 60;
80
+ const WORKER_MEMORY_MB = 512;
81
+ const timeoutSeconds = intBetween(1, 900);
82
+ const memoryMb = intBetween(128, 10240);
83
+
65
84
  const WorkerSchema = Schema.Struct({
66
85
  entry: Schema.String.pipe(orElse('src/worker.ts')),
67
- timeoutSeconds: intBetween(1, 900).pipe(orElse(60)),
68
- memoryMb: intBetween(128, 10240).pipe(orElse(512)),
86
+ timeoutSeconds: timeoutSeconds.pipe(orElse(WORKER_TIMEOUT_SECONDS)),
87
+ memoryMb: memoryMb.pipe(orElse(WORKER_MEMORY_MB)),
69
88
  });
70
89
 
90
+ /** A queue, event or cron handler's own settings; unset ones are the worker's. */
91
+ const HandlerFields = {
92
+ timeoutSeconds: Schema.optional(timeoutSeconds),
93
+ memoryMb: Schema.optional(memoryMb),
94
+ };
95
+ const attempts = intBetween(1, MAX_ATTEMPTS);
96
+ /** An event handler's settings. Unset attempts are `DEFAULT_ATTEMPTS.event`. */
97
+ const HandlerSchema = Schema.Struct({ ...HandlerFields, maxAttempts: Schema.optional(attempts) });
98
+
99
+ const QueueFields = {
100
+ maxAttempts: attempts.pipe(orElse(DEFAULT_ATTEMPTS.queue)),
101
+ concurrency: Schema.optional(intBetween(1, 1000)),
102
+ ...HandlerFields,
103
+ };
104
+
105
+ /** A field that was removed: present at all, it fails with `message`. */
106
+ const removed = (message: string) => Schema.optional(Schema.Unknown.check(Schema.makeFilter(() => message)));
107
+
108
+ // Queues were SQS queues polled by Lambda until 0.4.0; these settings had no meaning after.
71
109
  const QueueSchema = Schema.Struct({
72
- batchSize: intBetween(1, 10).pipe(orElse(10)),
73
- visibilityTimeoutSeconds: Schema.optional(intBetween(0, 43200)),
74
- maxReceiveCount: intBetween(1, 1000).pipe(orElse(5)),
75
- concurrency: Schema.optional(intBetween(2, 1000)),
110
+ ...QueueFields,
111
+ batchSize: removed('removed in 0.4.0: a queue delivers one message per run'),
112
+ visibilityTimeoutSeconds: removed("removed in 0.4.0: a run has its handler's timeoutSeconds"),
113
+ maxReceiveCount: removed('renamed to maxAttempts in 0.4.0'),
76
114
  });
77
115
 
78
- const CronSchema = Schema.Union([
79
- Schema.String,
80
- Schema.Struct({ schedule: Schema.String, timezone: Schema.optional(Schema.String) }),
81
- ]).check(
116
+ const CronScheduleSchema = Schema.Struct({
117
+ schedule: Schema.String,
118
+ timezone: Schema.optional(Schema.String),
119
+ maxAttempts: Schema.optional(attempts),
120
+ ...HandlerFields,
121
+ });
122
+
123
+ const CronSchema = Schema.Union([Schema.String, CronScheduleSchema]).check(
82
124
  Schema.makeFilter((cron) => validateCron(typeof cron === 'string' ? cron : cron.schedule) ?? undefined),
83
125
  );
84
126
 
@@ -87,6 +129,41 @@ const AuthSchema = Schema.Union([
87
129
  Schema.Struct({ required: Schema.Boolean.pipe(orElse(false)) }),
88
130
  ]);
89
131
 
132
+ const StoreSchema = Schema.Struct({
133
+ public: Schema.Boolean.pipe(orElse(false)),
134
+ expireAfterDays: Schema.optional(intBetween(1, 3650)),
135
+ });
136
+ const ServiceSchema = Schema.Struct({
137
+ entry: Schema.String,
138
+ cpu: Schema.Literals(FARGATE_CPUS).pipe(orElse(0.25)),
139
+ memoryMb: Schema.Int.pipe(orElse(512)),
140
+ spot: Schema.Boolean.pipe(orElse(true)),
141
+ previewMinutes: intBetween(0, 1440).pipe(orElse(30)),
142
+ }).check(
143
+ Schema.makeFilter((s) => {
144
+ const issue = fargateSizeIssue(s.cpu, s.memoryMb);
145
+ return issue ? [{ path: ['memoryMb'], issue }] : undefined;
146
+ }),
147
+ );
148
+
149
+ const RealtimeSubscribeSchema = Schema.Literals(['public', 'signed-in']);
150
+
151
+ const EmailSchema = Schema.Union([
152
+ Schema.Boolean,
153
+ Schema.Struct({
154
+ name: Schema.optional(
155
+ Schema.String.check(Schema.isPattern(EMAIL_NAME_PATTERN, { message: EMAIL_NAME_MESSAGE })),
156
+ ),
157
+ // The platform's ceiling (`limits.emailsPerDay`) is checked when a deployment is created.
158
+ dailyLimit: Schema.optional(intBetween(1, 1_000_000)),
159
+ }),
160
+ ]);
161
+
162
+ const RealtimeSchema = Schema.Struct({
163
+ subscribe: RealtimeSubscribeSchema.pipe(orElse('public')),
164
+ channels: recordOf(CHANNEL_DECLARATION_PATTERN, Schema.Struct({}), CHANNEL_MESSAGE),
165
+ });
166
+
90
167
  export const ManifestSchema = Schema.Struct({
91
168
  // Reserved names are enforced when an app is registered (API), not here:
92
169
  // the control plane itself is the app named `platform`.
@@ -101,14 +178,32 @@ export const ManifestSchema = Schema.Struct({
101
178
  queues: recordOf(RESOURCE_KEY_PATTERN, QueueSchema, RESOURCE_KEY_MESSAGE).pipe(orElse({})),
102
179
  // The array form predates typed event payloads; deployments recorded
103
180
  // before then still store it.
104
- events: Schema.Union([Schema.Array(eventType), recordOf(EVENT_TYPE_PATTERN, Schema.Struct({}))]).pipe(
181
+ events: Schema.Union([Schema.Array(eventType), recordOf(EVENT_TYPE_PATTERN, HandlerSchema)]).pipe(
105
182
  orElse([]),
106
183
  ),
107
184
  crons: recordOf(RESOURCE_KEY_PATTERN, CronSchema, RESOURCE_KEY_MESSAGE).pipe(orElse({})),
108
- storage: Schema.Array(resourceKey).pipe(orElse([])),
185
+ // The array form (every store private, kept forever) is still accepted.
186
+ storage: Schema.Union([
187
+ Schema.Array(resourceKey),
188
+ recordOf(RESOURCE_KEY_PATTERN, StoreSchema, RESOURCE_KEY_MESSAGE),
189
+ ]).pipe(orElse([])),
109
190
  secrets: Schema.Array(envName).pipe(orElse([])),
110
191
  env: recordOf(ENV_NAME_PATTERN, Schema.String).pipe(orElse({})),
111
- });
192
+ realtime: Schema.optional(RealtimeSchema),
193
+ email: EmailSchema.pipe(orElse(false)),
194
+ services: recordOf(RESOURCE_KEY_PATTERN, ServiceSchema, RESOURCE_KEY_MESSAGE).pipe(orElse({})),
195
+ }).check(
196
+ Schema.makeFilter((m) => {
197
+ if (!m.realtime) return undefined;
198
+ const issues = realtimeIssues({
199
+ subscribe: m.realtime.subscribe,
200
+ channels: Object.keys(m.realtime.channels),
201
+ auth: m.auth !== false,
202
+ server: Boolean(m.web?.server),
203
+ });
204
+ return issues.map((i) => ({ path: ['realtime', ...i.path], issue: i.message }));
205
+ }),
206
+ );
112
207
 
113
208
  /** The evaluated config as JSON: what the CLI sends and deployments store. */
114
209
  export type ManifestInput = typeof ManifestSchema.Encoded;
@@ -145,36 +240,163 @@ export interface WebConfig {
145
240
  serverRoutes?: readonly string[];
146
241
  /** 3-900. Default 30. */
147
242
  timeoutSeconds?: number;
148
- /** Max concurrent requests per Web Function environment, 1-128. Default 64. */
243
+ /** Max concurrent requests per Web Function environment (instance mode), 1-128. Default 64. */
149
244
  concurrency?: number;
245
+ /**
246
+ * How the server runs. `request`: one invocation per request, billed by the
247
+ * millisecond and nothing while idle. `instance`: a Web Function, whose
248
+ * environments serve many requests at once and are billed for their memory
249
+ * while they live (until about five minutes after the last request).
250
+ * `auto` (default): previews run `request`; prod starts on `request` and
251
+ * moves to whichever mode its traffic makes cheaper, checked daily.
252
+ */
253
+ compute?: WebComputeSetting;
254
+ /** Memory of the server in request mode, 128-10240 MB (CPU grows with it). Default 1024. */
255
+ memoryMb?: number;
256
+ /** Most environments prod's Web Function (instance mode) runs at once, 2-10000. Default 10; previews 2. */
257
+ maxEnvironments?: number;
150
258
  }
151
259
 
152
260
  export interface WorkerConfig {
153
261
  /** Module whose default export is `defineWorker(...)`. Default `src/worker.ts`. */
154
262
  entry?: string;
155
- /** 1-900. Default 60. */
263
+ /** 1-900. Default 60. Handlers can set their own (`HandlerConfig`). */
156
264
  timeoutSeconds?: number;
157
- /** 128-10240. Default 512. */
265
+ /** 128-10240. Default 512. Handlers can set their own (`HandlerConfig`). */
158
266
  memoryMb?: number;
159
267
  }
160
268
 
161
- /** Declare one with `queue<Body>({ ... })` to type what is sent and received. */
162
- export interface QueueConfig<Body = unknown> extends Payload<Body> {
163
- /** Messages per worker invocation, 1-10. Default 10. */
164
- batchSize?: number;
165
- /** Defaults to 6x the worker timeout, as AWS recommends for Lambda consumers. */
166
- visibilityTimeoutSeconds?: number;
167
- /** Deliveries before a message moves to the dead-letter queue, 1-1000. Default 5. */
168
- maxReceiveCount?: number;
169
- /** Max concurrent worker invocations draining this queue, 2-1000. */
269
+ /**
270
+ * A queue, event or cron handler's own Lambda settings, for handlers whose
271
+ * needs differ from the rest (a big parse, a long idle wait). A handler that
272
+ * sets either runs in a function of its own, from the same worker bundle;
273
+ * the one it doesn't set is the worker's.
274
+ */
275
+ export interface HandlerConfig {
276
+ /** 1-900. Default: the worker's `timeoutSeconds`. */
277
+ timeoutSeconds?: number;
278
+ /** 128-10240. Default: the worker's `memoryMb`. */
279
+ memoryMb?: number;
280
+ }
281
+
282
+ /** How often a failed run is tried again, for every kind of handler. */
283
+ export interface RetryConfig {
284
+ /**
285
+ * Runs before the job goes to the stage's dead-letter queue, 1-100: the
286
+ * first, then retries 1, 2, 4 … minutes apart (at most an hour). Default 5
287
+ * for queues, 3 for events and crons.
288
+ */
289
+ maxAttempts?: number;
290
+ }
291
+
292
+ /**
293
+ * Declare one with `queue<Body>({ ... })` to type what is sent and received.
294
+ * Each message is one run of its handler, at least once and in no set order.
295
+ */
296
+ export interface QueueConfig<Body = unknown> extends Payload<Body>, HandlerConfig, RetryConfig {
297
+ /**
298
+ * At most this many runs at once, 1-1000. Setting it runs the handler in a
299
+ * function of its own with that much reserved Lambda concurrency; messages
300
+ * past it wait (up to six hours) instead of failing.
301
+ */
170
302
  concurrency?: number;
171
303
  }
172
304
 
305
+ /** Event handler options. */
306
+ export type EventOptions = HandlerConfig & RetryConfig;
307
+
173
308
  /** Declare one with `event<Detail>()` to type what is published and handled. */
174
- export type EventConfig<Detail = unknown> = Payload<Detail>;
309
+ export type EventConfig<Detail = unknown> = Payload<Detail> & EventOptions;
310
+
311
+ /**
312
+ * 5-field cron in UTC (`0 3 * * *`) or `rate(5 minutes)`; the object form adds
313
+ * a timezone or the handler's own settings.
314
+ */
315
+ export type CronConfig = string | CronSchedule;
316
+
317
+ export interface CronSchedule extends HandlerConfig, RetryConfig {
318
+ schedule: string;
319
+ /** IANA name, e.g. `America/Los_Angeles`. Default UTC. */
320
+ timezone?: string;
321
+ }
322
+
323
+ /** Declare one with `channel<Event>()` to type what is published and received. */
324
+ export type ChannelConfig<Event = unknown> = Payload<Event>;
325
+
326
+ /** A file store. `{}` is a private store whose files are kept until deleted. */
327
+ export interface StoreConfig {
328
+ /**
329
+ * Serve the store's files from the edge at `/__platform/storage/<store>/<key>`
330
+ * on the app's host, to anyone with the URL (`auth.required` doesn't cover
331
+ * it), with no server in the path. Files are cached as their `cacheControl`
332
+ * says; without one, browsers revalidate on each use. Default `false`.
333
+ */
334
+ public?: boolean;
335
+ /** Delete files not written for this many days, 1-3650. Checked daily. Default: kept until deleted. */
336
+ expireAfterDays?: number;
337
+ }
338
+
339
+ /**
340
+ * A long-running process: it holds connections open (WebSocket or
341
+ * server-sent-event sources) and writes what it receives to the db, storage,
342
+ * queues or realtime. One instance per stage, restarted when it crashes and
343
+ * replaced on each deploy. Unlike everything else it is billed while it runs:
344
+ * about $6 a month at the default size on Spot.
345
+ */
346
+ export interface ServiceConfig {
347
+ /** Module whose default export is `defineService(...)` from `@ericminassian/platform`. */
348
+ entry: string;
349
+ /** vCPUs: 0.25 (default), 0.5, 1, 2 or 4. */
350
+ cpu?: FargateCpu;
351
+ /**
352
+ * Memory in MB, one of the sizes Fargate pairs with `cpu`: 512, 1024 or
353
+ * 2048 for 0.25 vCPU; 1024-4096 for 0.5; 2048-8192 for 1; 4096-16384 for 2;
354
+ * 8192-30720 for 4 (steps of 1024). Default 512.
355
+ */
356
+ memoryMb?: number;
357
+ /**
358
+ * Run on Fargate Spot, about 70% cheaper. AWS may reclaim it with two
359
+ * minutes' notice (the service gets SIGTERM) and the platform starts a
360
+ * replacement. Default `true`.
361
+ */
362
+ spot?: boolean;
363
+ /** Minutes a preview stage runs it after each deploy before stopping it; 0 means never. Default 30. */
364
+ previewMinutes?: number;
365
+ }
366
+
367
+ /**
368
+ * Live updates pushed to browsers. The server and worker publish; browsers
369
+ * subscribe (they never publish). Events aren't stored: a browser that was
370
+ * away re-reads what it shows after reconnecting.
371
+ */
372
+ export interface RealtimeConfig {
373
+ /**
374
+ * Who may subscribe: anyone (`public`, the default), or signed-in users of
375
+ * this app (`signed-in`, needs `auth` and `web.server`).
376
+ */
377
+ subscribe?: 'public' | 'signed-in';
378
+ /**
379
+ * Channels and their event types: `board: channel<BoardEvent>()`, or
380
+ * `'boards/*': channel<BoardEvent>()` for every channel below `boards/`.
381
+ * Names are 1-4 segments of a-z, 0-9 and hyphens. `'user/*'` channels
382
+ * (`user/<user id>/...`) are private to that user (`signed-in` only).
383
+ */
384
+ channels: { readonly [pattern: string]: ChannelConfig };
385
+ }
175
386
 
176
- /** 5-field cron in UTC (`0 3 * * *`) or `rate(5 minutes)`. */
177
- export type CronConfig = string | { schedule: string; timezone?: string };
387
+ /**
388
+ * Transactional email, sent from `<app>@mail.<platform zone>` (previews from
389
+ * `<app>--<stage>@…`). Replies need `replyTo`: the sending address takes no mail.
390
+ */
391
+ export interface EmailConfig {
392
+ /** Display name recipients see, e.g. `Todo` → `"Todo" <todo@mail…>`. */
393
+ name?: string;
394
+ /**
395
+ * Recipients per UTC day (default 200), up to the platform's
396
+ * `limits.emailsPerDay`. Previews and `plat dev` get at most 50.
397
+ */
398
+ dailyLimit?: number;
399
+ }
178
400
 
179
401
  export interface AppConfig {
180
402
  /** 3-30 chars of a-z, 0-9 and single hyphens; also the app's host name. */
@@ -193,12 +415,23 @@ export interface AppConfig {
193
415
  events?: readonly string[] | { readonly [type: string]: EventConfig };
194
416
  /** Scheduled jobs. Each needs a handler in the worker. */
195
417
  crons?: { readonly [name: string]: CronConfig };
196
- /** Named file stores. */
197
- storage?: readonly string[];
418
+ /**
419
+ * Named file stores: `{ uploads: {}, snapshots: { public: true, expireAfterDays: 7 } }`.
420
+ * A list of names (`['uploads']`) declares private stores. Keys are 1-20
421
+ * chars of a-z, 0-9 and hyphens. A store can't switch between public and
422
+ * private once it has files: declare a new one instead.
423
+ */
424
+ storage?: readonly string[] | { readonly [name: string]: StoreConfig };
198
425
  /** Secret names like `STRIPE_KEY`; values are set with `plat secrets set`. */
199
426
  secrets?: readonly string[];
200
427
  /** Plain, non-secret configuration exposed as environment variables. */
201
428
  env?: { readonly [name: string]: string };
429
+ /** Live updates pushed to browsers on typed channels. */
430
+ realtime?: RealtimeConfig;
431
+ /** Send email with the SDK's `Email` service: `true`, or `{ name, dailyLimit }`. */
432
+ email?: boolean | EmailConfig;
433
+ /** Long-running processes, e.g. stream ingest. Keys are 1-20 chars of a-z, 0-9 and hyphens. */
434
+ services?: { readonly [name: string]: ServiceConfig };
202
435
  }
203
436
 
204
437
  /**
@@ -225,13 +458,18 @@ export function defineApp<const T extends AppConfig>(config: T & Exact<T, AppCon
225
458
  return config;
226
459
  }
227
460
 
228
- /** A queue whose messages are `Body`: `queues: { emails: queue<EmailJob>({ batchSize: 5 }) }`. */
461
+ /** A queue whose messages are `Body`: `queues: { emails: queue<EmailJob>({ maxAttempts: 3 }) }`. */
229
462
  export function queue<Body>(options: QueueConfig = {}): QueueConfig<Body> {
230
463
  return options as QueueConfig<Body>;
231
464
  }
232
465
 
233
466
  /** An event subscription whose detail is `Detail`: `events: { 'todo.created': event<TodoCreated>() }`. */
234
- export function event<Detail>(): EventConfig<Detail> {
467
+ export function event<Detail>(options: EventOptions = {}): EventConfig<Detail> {
468
+ return options;
469
+ }
470
+
471
+ /** A realtime channel whose events are `Event`: `realtime: { channels: { board: channel<BoardEvent>() } }`. */
472
+ export function channel<Event>(): ChannelConfig<Event> {
235
473
  return {};
236
474
  }
237
475
 
@@ -250,18 +488,36 @@ export const ResolvedManifest = Schema.Struct({
250
488
  worker: Schema.optional(WorkerSchema),
251
489
  auth: Schema.Struct({ enabled: Schema.Boolean, required: Schema.Boolean }),
252
490
  db: Schema.Boolean,
253
- queues: Schema.Record(
254
- Schema.String,
255
- Schema.Struct({ ...QueueSchema.fields, visibilityTimeoutSeconds: Schema.Finite }),
256
- ),
491
+ queues: Schema.Record(Schema.String, Schema.Struct(QueueFields)),
257
492
  events: Schema.Array(Schema.String),
258
- crons: Schema.Record(
259
- Schema.String,
260
- Schema.Struct({ schedule: Schema.String, timezone: Schema.optional(Schema.String) }),
261
- ),
493
+ /**
494
+ * Each event handler's own settings, by type. Absent from deployments
495
+ * recorded before handlers had any. A field of its own, so clients that
496
+ * know only `events` keep decoding manifests.
497
+ */
498
+ eventOptions: Schema.Record(Schema.String, HandlerSchema).pipe(orElse({})),
499
+ crons: Schema.Record(Schema.String, CronScheduleSchema),
500
+ /** Every store's name. */
262
501
  storage: Schema.Array(Schema.String),
502
+ /**
503
+ * Each store's options, by name. Absent from deployments recorded before
504
+ * stores had any: those stores are private and kept until deleted. A field
505
+ * of its own, so clients that know only `storage` keep decoding manifests.
506
+ */
507
+ storageOptions: Schema.Record(
508
+ Schema.String,
509
+ Schema.Struct({ public: Schema.Boolean, expireAfterDays: Schema.optional(Schema.Finite) }),
510
+ ).pipe(orElse({})),
263
511
  secrets: Schema.Array(Schema.String),
264
512
  env: Schema.Record(Schema.String, Schema.String),
513
+ /** Present when the stage has a channel namespace. `channels` are the declared patterns. */
514
+ realtime: Schema.optional(
515
+ Schema.Struct({ subscribe: RealtimeSubscribeSchema, channels: Schema.Array(Schema.String) }),
516
+ ),
517
+ /** Present when the stage sends email. `dailyLimit` is the declared one (prod's). */
518
+ email: Schema.optional(Schema.Struct({ name: Schema.optional(Schema.String), dailyLimit: Schema.Finite })),
519
+ /** Long-running services, with defaults applied. */
520
+ services: Schema.Record(Schema.String, ServiceSchema).pipe(orElse({})),
265
521
  });
266
522
  export type ResolvedManifest = typeof ResolvedManifest.Type;
267
523
 
@@ -293,7 +549,10 @@ export function parseManifest(input: unknown): ResolvedManifest {
293
549
  }
294
550
 
295
551
  export function resolveManifest(m: Manifest): ResolvedManifest {
296
- const events = Array.isArray(m.events) ? m.events : Object.keys(m.events);
552
+ const eventOptions: ResolvedManifest['eventOptions'] = isEventList(m.events)
553
+ ? Object.fromEntries(m.events.map((type) => [type, {}]))
554
+ : m.events;
555
+ const events = Object.keys(eventOptions);
297
556
  const needsWorker =
298
557
  Object.keys(m.queues).length > 0 || events.length > 0 || Object.keys(m.crons).length > 0;
299
558
  const worker = m.worker ?? (needsWorker ? Schema.decodeUnknownSync(WorkerSchema)({}) : undefined);
@@ -301,15 +560,31 @@ export function resolveManifest(m: Manifest): ResolvedManifest {
301
560
  typeof m.auth === 'boolean'
302
561
  ? { enabled: m.auth, required: false }
303
562
  : { enabled: true, required: m.auth.required };
563
+ // Validation refused the removed queue settings, so only the current ones remain.
304
564
  const queues: ResolvedManifest['queues'] = Object.fromEntries(
305
565
  Object.entries(m.queues).map(([key, q]) => [
306
566
  key,
307
- { ...q, visibilityTimeoutSeconds: q.visibilityTimeoutSeconds ?? (worker?.timeoutSeconds ?? 60) * 6 },
567
+ {
568
+ maxAttempts: q.maxAttempts,
569
+ ...(q.concurrency !== undefined ? { concurrency: q.concurrency } : {}),
570
+ ...(q.timeoutSeconds !== undefined ? { timeoutSeconds: q.timeoutSeconds } : {}),
571
+ ...(q.memoryMb !== undefined ? { memoryMb: q.memoryMb } : {}),
572
+ },
308
573
  ]),
309
574
  );
575
+ const email: ResolvedManifest['email'] =
576
+ m.email === false
577
+ ? undefined
578
+ : {
579
+ ...(m.email !== true && m.email.name ? { name: m.email.name } : {}),
580
+ dailyLimit: (m.email !== true && m.email.dailyLimit) || EMAIL_DEFAULT_DAILY_LIMIT,
581
+ };
310
582
  const crons: ResolvedManifest['crons'] = Object.fromEntries(
311
583
  Object.entries(m.crons).map(([key, c]) => [key, typeof c === 'string' ? { schedule: c } : c]),
312
584
  );
585
+ const stores: Record<string, typeof StoreSchema.Type> = isStoreList(m.storage)
586
+ ? Object.fromEntries(m.storage.map((name) => [name, { public: false }]))
587
+ : m.storage;
313
588
  return {
314
589
  name: m.name,
315
590
  ...(m.description ? { description: m.description } : {}),
@@ -318,10 +593,105 @@ export function resolveManifest(m: Manifest): ResolvedManifest {
318
593
  auth,
319
594
  db: m.db,
320
595
  queues,
321
- events: [...new Set(events)],
596
+ events,
597
+ eventOptions,
322
598
  crons,
323
- storage: [...new Set(m.storage)],
599
+ storage: Object.keys(stores),
600
+ storageOptions: stores,
324
601
  secrets: [...new Set(m.secrets)],
325
602
  env: m.env,
603
+ ...(m.realtime
604
+ ? { realtime: { subscribe: m.realtime.subscribe, channels: Object.keys(m.realtime.channels) } }
605
+ : {}),
606
+ ...(email ? { email } : {}),
607
+ services: m.services,
326
608
  };
327
609
  }
610
+
611
+ const isStoreList = (storage: Manifest['storage']): storage is readonly string[] => Array.isArray(storage);
612
+ const isEventList = (events: Manifest['events']): events is readonly string[] => Array.isArray(events);
613
+
614
+ /** The stores the edge serves (`public: true`). */
615
+ export function publicStores(m: Pick<ResolvedManifest, 'storage' | 'storageOptions'>): string[] {
616
+ return m.storage.filter((name) => m.storageOptions[name]?.public === true);
617
+ }
618
+
619
+ // ---------------------------------------------------------------------------
620
+ // Worker functions
621
+
622
+ const HANDLER_KINDS = ['queue', 'event', 'cron'] as const;
623
+ export type HandlerKind = (typeof HANDLER_KINDS)[number];
624
+
625
+ /** A queue, event or cron handler and the settings it runs with. */
626
+ export interface HandlerSettings {
627
+ kind: HandlerKind;
628
+ /** The queue or cron key, or the event type. */
629
+ name: string;
630
+ timeoutSeconds: number;
631
+ memoryMb: number;
632
+ /** Runs before its job is dead-lettered. */
633
+ maxAttempts: number;
634
+ /** Reserved concurrency of its function (queues that set `concurrency`). */
635
+ concurrency?: number;
636
+ /**
637
+ * It sets its own memory, timeout or (a queue) concurrency, so it runs in a
638
+ * function of its own (`names.handlerFunction`).
639
+ */
640
+ own: boolean;
641
+ }
642
+
643
+ type WorkerManifest = Pick<ResolvedManifest, 'worker' | 'queues' | 'eventOptions' | 'crons'>;
644
+
645
+ /** Each kind's handlers, by name, with what they set. */
646
+ const declaredHandlers = (
647
+ m: WorkerManifest,
648
+ ): Record<
649
+ HandlerKind,
650
+ { readonly [name: string]: HandlerConfig & { maxAttempts?: number; concurrency?: number } }
651
+ > => ({
652
+ queue: m.queues,
653
+ event: m.eventOptions,
654
+ cron: m.crons,
655
+ });
656
+
657
+ /** A handler's settings: its own, and the worker's for any it doesn't set. */
658
+ export function handlerSettings(m: WorkerManifest, kind: HandlerKind, name: string): HandlerSettings {
659
+ const own = declaredHandlers(m)[kind][name] ?? {};
660
+ // Reserved concurrency is per function, so a queue that caps it needs one to itself.
661
+ const concurrency = kind === 'queue' ? own.concurrency : undefined;
662
+ return {
663
+ kind,
664
+ name,
665
+ timeoutSeconds: own.timeoutSeconds ?? m.worker?.timeoutSeconds ?? WORKER_TIMEOUT_SECONDS,
666
+ memoryMb: own.memoryMb ?? m.worker?.memoryMb ?? WORKER_MEMORY_MB,
667
+ maxAttempts: own.maxAttempts ?? DEFAULT_ATTEMPTS[kind],
668
+ ...(concurrency !== undefined ? { concurrency } : {}),
669
+ own: own.timeoutSeconds !== undefined || own.memoryMb !== undefined || concurrency !== undefined,
670
+ };
671
+ }
672
+
673
+ /** Every queue, event and cron handler with its settings. */
674
+ export function workerHandlers(m: WorkerManifest): HandlerSettings[] {
675
+ const declared = declaredHandlers(m);
676
+ return HANDLER_KINDS.flatMap((kind) =>
677
+ Object.keys(declared[kind]).map((name) => handlerSettings(m, kind, name)),
678
+ );
679
+ }
680
+
681
+ /** The handlers that run in functions of their own. The worker's function runs the rest. */
682
+ export function ownFunctionHandlers(m: WorkerManifest): HandlerSettings[] {
683
+ return workerHandlers(m).filter((h) => h.own);
684
+ }
685
+
686
+ /** The Lambda function a handler runs in: its own, or the worker's. */
687
+ export function handlerFunctionName(
688
+ app: string,
689
+ stage: string,
690
+ m: WorkerManifest,
691
+ kind: HandlerKind,
692
+ name: string,
693
+ ): string {
694
+ return handlerSettings(m, kind, name).own
695
+ ? names.handlerFunction(app, stage, kind, name)
696
+ : names.workerFunction(app, stage);
697
+ }