@ericminassian/platform-core 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/dist/api.d.ts +367 -226
  2. package/dist/api.js +148 -92
  3. package/dist/api.js.map +1 -1
  4. package/dist/config.d.ts +0 -2
  5. package/dist/config.js.map +1 -1
  6. package/dist/constants.d.ts +0 -17
  7. package/dist/constants.js +0 -17
  8. package/dist/constants.js.map +1 -1
  9. package/dist/explore.d.ts +367 -0
  10. package/dist/explore.js +440 -0
  11. package/dist/explore.js.map +1 -0
  12. package/dist/index.d.ts +1 -1
  13. package/dist/index.js +1 -1
  14. package/dist/index.js.map +1 -1
  15. package/dist/jobs.d.ts +1 -1
  16. package/dist/jobs.js +1 -1
  17. package/dist/manifest.d.ts +10 -47
  18. package/dist/manifest.js +7 -15
  19. package/dist/manifest.js.map +1 -1
  20. package/dist/naming.d.ts +7 -23
  21. package/dist/naming.js +7 -23
  22. package/dist/naming.js.map +1 -1
  23. package/dist/platform-api.d.ts +3511 -2211
  24. package/dist/platform-api.js +117 -36
  25. package/dist/platform-api.js.map +1 -1
  26. package/dist/runtime-config.d.ts +0 -20
  27. package/dist/runtime-config.js.map +1 -1
  28. package/dist/storage.d.ts +10 -0
  29. package/dist/storage.js +10 -0
  30. package/dist/storage.js.map +1 -1
  31. package/dist/telemetry.d.ts +52 -27
  32. package/dist/telemetry.js +67 -19
  33. package/dist/telemetry.js.map +1 -1
  34. package/dist/web-compute.js +2 -1
  35. package/dist/web-compute.js.map +1 -1
  36. package/package.json +1 -1
  37. package/src/api.ts +176 -110
  38. package/src/config.ts +0 -2
  39. package/src/constants.ts +0 -19
  40. package/src/explore.ts +504 -0
  41. package/src/index.ts +1 -1
  42. package/src/jobs.ts +1 -1
  43. package/src/manifest.ts +15 -48
  44. package/src/naming.ts +7 -25
  45. package/src/platform-api.ts +140 -38
  46. package/src/runtime-config.ts +0 -21
  47. package/src/storage.ts +11 -0
  48. package/src/telemetry.ts +69 -19
  49. package/src/web-compute.ts +3 -1
  50. package/dist/compute.d.ts +0 -52
  51. package/dist/compute.js +0 -65
  52. package/dist/compute.js.map +0 -1
  53. package/src/compute.ts +0 -86
package/src/naming.ts CHANGED
@@ -141,21 +141,6 @@ export const names = {
141
141
  fit(`${app}--${stage}--${eventType.replace(/[^A-Za-z0-9._-]/g, '_')}`, 64),
142
142
  scheduleGroup: (app: string, stage: string) => `${app}--${stage}`,
143
143
  schedule: (cronKey: string) => cronKey,
144
- /**
145
- * A long-running service's ECS service and task definition family (ECS
146
- * names are their own namespace, so `worker` can't clash with the Lambda).
147
- */
148
- service: (app: string, stage: string, key: string) => `${app}--${stage}--${key}`,
149
- serviceLogGroup: (app: string, stage: string, key: string) =>
150
- `/platform/apps/${app}/${stage}/services/${key}`,
151
- /** Tag of a service's image for one deployment in the container repository (≤ 103 of ECR's 128 chars). */
152
- serviceImageTag: (app: string, stage: string, key: string, deploymentId: string) =>
153
- `${app}--${stage}--${key}--${deploymentId}`,
154
- /**
155
- * One-shot schedule, in the stage's schedule group, that stops a preview's
156
- * service. Cron keys can't contain `--`, so it never clashes with a cron.
157
- */
158
- serviceStopSchedule: (key: string) => `${key}--stop`,
159
144
  userPoolClient: (app: string, stage: string) => `${app}--${stage}`,
160
145
  /** SES tenant and its configuration set (≤ 64 chars each; the base is ≤ 52). */
161
146
  emailTenant: (app: string, stage: string) => `${app}--${stage}`,
@@ -203,16 +188,6 @@ export const platformNames = {
203
188
  realtimeApi: 'platform-realtime',
204
189
  /** Its Lambda authorizer (signed-in subscribe tokens). */
205
190
  realtimeAuthorizer: 'platform-realtime-authorizer',
206
- /** ECS cluster every stage's containers run in (long-running services). */
207
- containerCluster: 'platform',
208
- /** VPC and security group containers run in: public subnets, no NAT, egress only. */
209
- containerNetwork: 'platform-containers',
210
- /** ECR repository of every container image the platform builds; tags name app, stage and deployment. */
211
- containerRepository: 'platform-containers',
212
- /** Role ECS uses to pull images and ship container logs (the app's code runs as its stage role). */
213
- containerExecutionRole: 'platform-container-execution',
214
- /** Role EventBridge Scheduler uses to scale containers (a preview's stop schedule). */
215
- containerSchedulerRole: 'platform-container-scheduler',
216
191
  /** Description of the API's subscribe-only key for `public` stages (how the control plane finds it). */
217
192
  realtimePublicKey: 'platform-public-subscribe',
218
193
  /** The control plane's own app name (services/control-plane/plat.config.ts), stage prod. */
@@ -234,6 +209,13 @@ export const platformNames = {
234
209
  * floor on, and the EventBridge rule that tells the control plane when it goes off.
235
210
  */
236
211
  edgeFloorAlarm: 'platform-edge-floor',
212
+ /**
213
+ * The router's access log (CloudFront standard logging, `EDGE_LOG_FIELDS`): its log group, and
214
+ * the name of the delivery source, destination, resource policy and subscription filter that
215
+ * feed it to the telemetry processor.
216
+ */
217
+ edgeLogGroup: '/platform/edge',
218
+ edgeLogDelivery: 'platform-edge',
237
219
  runtimeConfigParameter: '/platform/config/runtime',
238
220
  sessionKeyParameter: '/platform/config/session-key',
239
221
  githubAppParameterPrefix: '/platform/config/github-app/',
@@ -40,35 +40,49 @@ import {
40
40
  EdgeFloorResponse,
41
41
  EmailStatsResponse,
42
42
  ErrorGroup,
43
+ ErrorOccurrencesResponse,
43
44
  ErrorStatus,
45
+ InsightsRequest,
46
+ InsightsResponse,
44
47
  JobsResponse,
45
48
  LimitsResponse,
49
+ LogContextResponse,
46
50
  LogLine,
47
51
  LogsResponse,
52
+ LogStatsResponse,
48
53
  MeResponse,
49
54
  MetricsResponse,
55
+ PublicAppsResponse,
50
56
  PutSecretRequest,
51
57
  QueueStats,
52
58
  RealtimeStatsResponse,
59
+ type RepoVisibility,
53
60
  RollbackRequest,
54
61
  RollbackResponse,
55
62
  RouteStats,
56
63
  SecretsResponse,
57
- ServiceActionResponse,
58
- ServicesResponse,
64
+ SeriesResponse,
59
65
  StageDestroyed,
60
66
  StageDestroying,
61
67
  StageRecord,
62
- StartServiceRequest,
63
68
  StorageResponse,
64
69
  SuppressedResponse,
65
70
  TraceResponse,
71
+ TracesResponse,
66
72
  UpdateAppRequest,
67
73
  UpdateErrorRequest,
68
74
  UptimePoint,
69
75
  UrlResponse,
70
76
  } from './api.ts';
71
77
  import type { MemberRole } from './config.ts';
78
+ import {
79
+ AlertHistoryResponse,
80
+ AlertRule,
81
+ AlertRuleInput,
82
+ LogFilters,
83
+ SeriesQuery,
84
+ TraceFilters,
85
+ } from './explore.ts';
72
86
 
73
87
  // ---------------------------------------------------------------------------
74
88
  // Errors: one class per status, each encoded as `{ error: { code, message } }`
@@ -126,7 +140,7 @@ export class NotFound extends Schema.TaggedError<NotFound, { readonly brand: uni
126
140
 
127
141
  /**
128
142
  * 409: `exists`, `dns_conflict`, `has_stages`, `already_started`, `rollback_failed`,
129
- * `redrive_failed`, `discard_failed`, `paused_by_aws`, `service_action_failed`.
143
+ * `redrive_failed`, `discard_failed`, `paused_by_aws`.
130
144
  */
131
145
  export class Conflict extends Schema.TaggedError<Conflict, { readonly brand: unique symbol }>()(
132
146
  'Conflict',
@@ -198,6 +212,8 @@ export interface CiPrincipal {
198
212
  readonly sha?: string | undefined;
199
213
  readonly actor?: string | undefined;
200
214
  readonly runId?: string | undefined;
215
+ /** The repository's visibility when the token was minted. */
216
+ readonly repositoryVisibility?: RepoVisibility | undefined;
201
217
  }
202
218
 
203
219
  export type Principal = MemberPrincipal | CiPrincipal;
@@ -258,6 +274,23 @@ export class SessionApi extends HttpApiGroup.make('session').add(
258
274
  HttpApiEndpoint.get('me', '/me', { success: MeResponse, error: errors }).middleware(Authenticated),
259
275
  ) {}
260
276
 
277
+ /**
278
+ * What anyone may read, without signing in: the public directory. Pages on
279
+ * any site may fetch it from the browser (`Access-Control-Allow-Origin: *`;
280
+ * it carries no credentials), and the router caches it
281
+ * (`PUBLIC_CACHE_CONTROL`), so readers rarely wake the control plane.
282
+ */
283
+ export class PublicApi extends HttpApiGroup.make('public').add(
284
+ HttpApiEndpoint.get('apps', '/public/apps', { success: PublicAppsResponse, error: errors }),
285
+ ) {}
286
+
287
+ /**
288
+ * How long browsers and the router keep the public directory: a page that
289
+ * fetches it live is a few minutes behind at most, and the control plane
290
+ * answers each edge location at most every five minutes.
291
+ */
292
+ export const PUBLIC_CACHE_CONTROL = 'public, max-age=60, s-maxage=300';
293
+
261
294
  export class AppsApi extends HttpApiGroup.make('apps')
262
295
  .add(
263
296
  HttpApiEndpoint.get('list', '/apps', { success: Schema.Array(AppSummary), error: errors }),
@@ -405,13 +438,6 @@ export class ObserveApi extends HttpApiGroup.make('observe')
405
438
  success: LimitsResponse,
406
439
  error: errors,
407
440
  }),
408
- /** The stage's long-running services: ECS state, CPU and memory, starts and failed runs. */
409
- HttpApiEndpoint.get('services', '/apps/:app/services', {
410
- params: app,
411
- query: rangeQuery,
412
- success: ServicesResponse,
413
- error: errors,
414
- }),
415
441
  HttpApiEndpoint.get('errors', '/apps/:app/errors', {
416
442
  params: app,
417
443
  query: { ...stageQuery, status: Schema.optional(ErrorStatus) },
@@ -443,8 +469,10 @@ export class ObserveApi extends HttpApiGroup.make('observe')
443
469
  query: {
444
470
  ...rangeQuery,
445
471
  q: Schema.optional(Schema.String),
446
- /** `web`, `worker` or `service:<name>`. */
472
+ /** `web` or `worker`. */
447
473
  stream: Schema.optional(Schema.String),
474
+ /** Structured filters as JSON (`LogFilters`); any of them runs the search on Logs Insights. */
475
+ f: Schema.optional(Schema.fromJsonString(LogFilters)),
448
476
  limit,
449
477
  next: Schema.optional(Schema.String),
450
478
  },
@@ -461,8 +489,10 @@ export class ObserveApi extends HttpApiGroup.make('observe')
461
489
  query: {
462
490
  ...stageQuery,
463
491
  q: Schema.optional(Schema.String),
464
- /** `web`, `worker` or `service:<name>`. */
492
+ /** `web` or `worker`. */
465
493
  stream: Schema.optional(Schema.String),
494
+ /** Structured filters as JSON (`LogFilters`), applied to the live lines. */
495
+ f: Schema.optional(Schema.fromJsonString(LogFilters)),
466
496
  },
467
497
  success: HttpApiSchema.StreamSse({ events: TailEvent, keepAlive: '20 seconds' }),
468
498
  error: errors,
@@ -473,6 +503,101 @@ export class ObserveApi extends HttpApiGroup.make('observe')
473
503
  success: TraceResponse,
474
504
  error: errors,
475
505
  }),
506
+ /**
507
+ * The explorer's query (`SeriesQuery`, as JSON in `q`) over the range. `res`
508
+ * may also be `5m`, `10m`, `15m` or `30m` (sums of minute rollups); by
509
+ * default about 150 buckets.
510
+ */
511
+ HttpApiEndpoint.get('series', '/apps/:app/series', {
512
+ params: app,
513
+ query: { ...rangeQuery, q: Schema.fromJsonString(SeriesQuery) },
514
+ success: SeriesResponse,
515
+ error: errors,
516
+ }),
517
+ /** Requests and jobs that started traces, newest first (Logs Insights over their root lines). */
518
+ HttpApiEndpoint.get('traces', '/apps/:app/traces', {
519
+ params: app,
520
+ query: { ...rangeQuery, f: Schema.optional(Schema.fromJsonString(TraceFilters)), limit },
521
+ success: TracesResponse,
522
+ error: errors,
523
+ }),
524
+ /** Lines per bucket by level and the commonest field values, for the same search as `logs` (Logs Insights). */
525
+ HttpApiEndpoint.get('logStats', '/apps/:app/logs/stats', {
526
+ params: app,
527
+ query: {
528
+ ...rangeQuery,
529
+ q: Schema.optional(Schema.String),
530
+ stream: Schema.optional(Schema.String),
531
+ f: Schema.optional(Schema.fromJsonString(LogFilters)),
532
+ },
533
+ success: LogStatsResponse,
534
+ error: errors,
535
+ }),
536
+ /** The lines just before and after one line (`ts`, epoch ms) of one stream. */
537
+ HttpApiEndpoint.get('logContext', '/apps/:app/logs/context', {
538
+ params: app,
539
+ query: {
540
+ ...stageQuery,
541
+ stream: Schema.String,
542
+ ts: Schema.String,
543
+ before: limit,
544
+ after: limit,
545
+ },
546
+ success: LogContextResponse,
547
+ error: errors,
548
+ }),
549
+ /** Runs a Logs Insights query on the stage's log groups and waits for it (up to 25 s). */
550
+ HttpApiEndpoint.post('insights', '/apps/:app/insights', {
551
+ params: app,
552
+ payload: InsightsRequest,
553
+ success: InsightsResponse,
554
+ error: errors,
555
+ }),
556
+ /** An error group's events over the range (Logs Insights). */
557
+ HttpApiEndpoint.get('errorOccurrences', '/apps/:app/errors/:fingerprint/occurrences', {
558
+ params: { ...app, fingerprint: Schema.String },
559
+ query: rangeQuery,
560
+ success: ErrorOccurrencesResponse,
561
+ error: errors,
562
+ }),
563
+ )
564
+ .middleware(Authenticated) {}
565
+
566
+ /** Alert rules on an app's stages, evaluated every minute by the control plane. */
567
+ export class AlertsApi extends HttpApiGroup.make('alerts')
568
+ .add(
569
+ /** Every stage's rules, or `?stage=`'s. */
570
+ HttpApiEndpoint.get('list', '/apps/:app/alerts', {
571
+ params: app,
572
+ query: { stage: Schema.optional(Schema.String) },
573
+ success: Schema.Array(AlertRule),
574
+ error: errors,
575
+ }),
576
+ HttpApiEndpoint.post('create', '/apps/:app/alerts', {
577
+ params: app,
578
+ payload: AlertRuleInput,
579
+ success: AlertRule.pipe(HttpApiSchema.status(201)),
580
+ error: errors,
581
+ }),
582
+ /** Replaces the rule's settings; a changed query or condition starts it over in `no_data`. */
583
+ HttpApiEndpoint.put('update', '/apps/:app/alerts/:id', {
584
+ params: { ...app, id: Schema.String },
585
+ payload: AlertRuleInput,
586
+ success: AlertRule,
587
+ error: errors,
588
+ }),
589
+ HttpApiEndpoint.delete('remove', '/apps/:app/alerts/:id', {
590
+ params: { ...app, id: Schema.String },
591
+ success: HttpApiSchema.NoContent,
592
+ error: errors,
593
+ }),
594
+ /** State changes of the app's rules (or `?stage=`'s) in the range, newest first. */
595
+ HttpApiEndpoint.get('history', '/apps/:app/alerts/history', {
596
+ params: app,
597
+ query: { stage: Schema.optional(Schema.String), ...timeQuery },
598
+ success: AlertHistoryResponse,
599
+ error: errors,
600
+ }),
476
601
  )
477
602
  .middleware(Authenticated) {}
478
603
 
@@ -562,31 +687,6 @@ export class ManageApi extends HttpApiGroup.make('manage')
562
687
  success: EmailSending,
563
688
  error: errors,
564
689
  }),
565
- /** Replaces the service's task with a fresh one on the same build. */
566
- HttpApiEndpoint.post('restartService', '/apps/:app/services/:name/restart', {
567
- params: { ...app, name: Schema.String },
568
- query: stageQuery,
569
- success: ServiceActionResponse.pipe(HttpApiSchema.status(202)),
570
- error: errors,
571
- }),
572
- /**
573
- * Runs it (desired 1). It stops again after `minutes` when given; on
574
- * previews always, by default after its `previewMinutes` (30 when that is 0).
575
- */
576
- HttpApiEndpoint.post('startService', '/apps/:app/services/:name/start', {
577
- params: { ...app, name: Schema.String },
578
- query: stageQuery,
579
- payload: StartServiceRequest,
580
- success: ServiceActionResponse.pipe(HttpApiSchema.status(202)),
581
- error: errors,
582
- }),
583
- /** Scales it to zero until it is started again or the stage is redeployed. */
584
- HttpApiEndpoint.post('stopService', '/apps/:app/services/:name/stop', {
585
- params: { ...app, name: Schema.String },
586
- query: stageQuery,
587
- success: ServiceActionResponse.pipe(HttpApiSchema.status(202)),
588
- error: errors,
589
- }),
590
690
  /** Runs dead letters again from their first attempt, on the function their handler runs in now. */
591
691
  HttpApiEndpoint.post('redrive', '/apps/:app/dead-letters/redrive', {
592
692
  params: app,
@@ -619,10 +719,12 @@ export class AdminApi extends HttpApiGroup.make('admin')
619
719
 
620
720
  export class PlatformApi extends HttpApi.make('platform')
621
721
  .add(SessionApi)
722
+ .add(PublicApi)
622
723
  .add(AppsApi)
623
724
  .add(StagesApi)
624
725
  .add(DeploymentsApi)
625
726
  .add(ObserveApi)
727
+ .add(AlertsApi)
626
728
  .add(ManageApi)
627
729
  .add(AdminApi)
628
730
  .prefix('/v1')
@@ -44,27 +44,6 @@ export interface PlatformRuntimeConfig {
44
44
  realtime?: RealtimeRuntimeConfig;
45
45
  /** The SES domain every stage sends from (absent on platforms that predate email). */
46
46
  email?: EmailRuntimeConfig;
47
- /** Container compute, ECS on Fargate (absent on platforms that predate it). */
48
- containers?: ContainersRuntimeConfig;
49
- }
50
-
51
- /**
52
- * Where containers run. Tasks get a public IPv4 address in a public subnet
53
- * (there is no NAT gateway) and accept no inbound traffic.
54
- */
55
- export interface ContainersRuntimeConfig {
56
- /** ECS cluster name. */
57
- cluster: string;
58
- subnets: string[];
59
- securityGroups: string[];
60
- /** ECR repository name. */
61
- repository: string;
62
- /** `<account>.dkr.ecr.<region>.amazonaws.com/<repository>`. */
63
- repositoryUri: string;
64
- /** Pulls images and writes container logs. */
65
- executionRoleArn: string;
66
- /** Assumed by EventBridge Scheduler to scale a stage's services (preview stop schedules). */
67
- schedulerRoleArn: string;
68
47
  }
69
48
 
70
49
  /**
package/src/storage.ts CHANGED
@@ -44,6 +44,17 @@ export const STORAGE_CACHE_HOST = '__storage';
44
44
  /** `Cache-Control` the edge adds to a public file that carries none: browsers revalidate it. */
45
45
  export const STORAGE_DEFAULT_CACHE_CONTROL = 'no-cache';
46
46
 
47
+ /**
48
+ * `plat dev` only: where its router relays browser uploads to the AWS Emulator,
49
+ * with the presigned URL in `?to=`. The emulator refuses a presigned request
50
+ * that carries an `Origin` header (`InvalidAccessKeyId`), which every browser
51
+ * upload sends and S3 accepts; the router forwards the PUT without it. The SDK
52
+ * returns relay URLs when `DEV_UPLOAD_RELAY_ENV` is set, which only `plat dev`
53
+ * does (`plat test` and deployed stages get the presigned URL itself).
54
+ */
55
+ export const DEV_UPLOAD_PATH = '/__plat_dev/upload';
56
+ export const DEV_UPLOAD_RELAY_ENV = 'PLATFORM_DEV_UPLOAD_RELAY';
57
+
47
58
  /**
48
59
  * Whether the edge serves `key` (as it appears in a URL path, so still
49
60
  * percent-encoded): not empty, and without `.` or `..` segments. S3 decodes
package/src/telemetry.ts CHANGED
@@ -62,8 +62,7 @@ export type RequestEvent = typeof RequestEvent.Type;
62
62
  export const ErrorEvent = Schema.Struct({
63
63
  ...base,
64
64
  t: Schema.Literal('err'),
65
- /** `service`: a long-running service's `run` failed (it is rerun after a backoff). */
66
- source: Schema.Literals(['http', 'job', 'unhandled', 'log', 'service']),
65
+ source: Schema.Literals(['http', 'job', 'unhandled', 'log']),
67
66
  name: Schema.String,
68
67
  message: Schema.String,
69
68
  stack: Schema.optional(Schema.String),
@@ -73,15 +72,11 @@ export const ErrorEvent = Schema.Struct({
73
72
  });
74
73
  export type ErrorEvent = typeof ErrorEvent.Type;
75
74
 
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
- */
75
+ /** One unit of work. */
81
76
  export const JobEvent = Schema.Struct({
82
77
  ...base,
83
78
  t: Schema.Literal('job'),
84
- kind: Schema.Literals(['queue', 'event', 'cron', 'invoke', 'service']),
79
+ kind: Schema.Literals(['queue', 'event', 'cron', 'invoke']),
85
80
  name: Schema.String,
86
81
  status: Schema.Literals(['ok', 'error']),
87
82
  dur: Schema.Finite,
@@ -141,21 +136,17 @@ export const LimitEvent = Schema.Struct({
141
136
  });
142
137
  export type LimitEvent = typeof LimitEvent.Type;
143
138
 
144
- /** A runtime process starting or stopping (`service`: a container of a long-running service). */
139
+ /** A runtime process starting or stopping. */
145
140
  export const EnvEvent = Schema.Struct({
146
141
  ...base,
147
142
  t: Schema.Literal('env'),
148
143
  event: Schema.Literals(['start', 'stop']),
149
- runtime: Schema.Literals(['web', 'worker', 'service']),
144
+ runtime: Schema.Literals(['web', 'worker']),
150
145
  /**
151
146
  * How a deployed server runs (`runtime: 'web'`): `request`, a function per
152
147
  * request, or `instance`, a Web Function environment. Absent under `plat dev`.
153
148
  */
154
149
  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),
159
150
  initMs: Schema.optional(Schema.Finite),
160
151
  });
161
152
  export type EnvEvent = typeof EnvEvent.Type;
@@ -259,18 +250,31 @@ export function bucketStart(ts: number, res: Resolution): number {
259
250
  * resolution; `sk` starts with the bucket time so a Query with `BETWEEN`
260
251
  * returns a time range.
261
252
  *
253
+ * Every rollup family is written at `1m`, `1h` and `1d` (`RESOLUTION_TTL_DAYS`).
254
+ * Route, job, custom metric and rate limit rows have had minute buckets only
255
+ * since November 2026; before, they started at `1h`.
256
+ *
262
257
  * - `m#<app>#<stage>#<res>` sk `<iso>` whole-stage HTTP: req, s2xx, s3xx, s4xx, s5xx, lat[], cold,
263
258
  * dur (ms handling them, summed), and process starts:
264
259
  * webStarts (webInits of them reported webInitMs, summed),
265
- * workerStarts, serviceStarts
266
- * - `r#<app>#<stage>#<res>` sk `<iso>#<route>` per-route HTTP (same fields, plus method)
267
- * - `j#<app>#<stage>#<res>` sk `<iso>#<kind>:<name>` jobs: ok, error, lat[]; `service:<name>` rows also
268
- * count `starts` (containers of that service starting)
269
- * - `c#<app>#<stage>#<res>` sk `<iso>#<metric>` custom metrics: count, sum (and the unit)
260
+ * workerStarts
261
+ * - `r#<app>#<stage>#<res>` sk `<iso>#<METHOD> <route>` per-route HTTP: req, s2xx, s3xx, s4xx, s5xx, lat[],
262
+ * cold, method, route. Rows from before November 2026 have no
263
+ * s2xx, s3xx or cold: their req − s4xx − s5xx were 2xx
264
+ * - `j#<app>#<stage>#<res>` sk `<iso>#<kind>:<name>` jobs: ok, error, lat[]
265
+ * - `c#<app>#<stage>#<res>` sk `<iso>#<metric>` custom metrics: count, sum, max (and the unit); rows from
266
+ * before November 2026 have no max
270
267
  * - `l#<app>#<stage>#<res>` sk `<iso>#<limit>` rate limit checks: allowed, denied
268
+ * - `v#<app>#<stage>#<res>` sk `<iso>` edge traffic from the router's access log, every
269
+ * request to the stage's host (files, server,
270
+ * stores) but health checks: req, s2xx, s3xx,
271
+ * s4xx, s5xx, and pages (`isPageView`). Since
272
+ * November 2026; written up to an hour late
271
273
  * - `e#<app>#<stage>` sk `<fingerprint>` error groups: count, firstSeen, lastSeen, sample, status
272
274
  * - `u#<app>#<stage>` sk `<iso>` uptime: ok, source (`traffic`: req, s5xx; `check`, or none on
273
275
  * rows before traffic counted: status, ms)
276
+ * - `a#<app>#<stage>` sk `<iso>#<ruleId>` alert rule state changes (`AlertEvent` fields but `ts`),
277
+ * kept `ALERT_HISTORY_DAYS`
274
278
  */
275
279
  export const telemetryKeys = {
276
280
  stage: (app: string, stage: string, res: Resolution) => `m#${app}#${stage}#${res}`,
@@ -278,8 +282,10 @@ export const telemetryKeys = {
278
282
  job: (app: string, stage: string, res: Resolution) => `j#${app}#${stage}#${res}`,
279
283
  metric: (app: string, stage: string, res: Resolution) => `c#${app}#${stage}#${res}`,
280
284
  limit: (app: string, stage: string, res: Resolution) => `l#${app}#${stage}#${res}`,
285
+ edge: (app: string, stage: string, res: Resolution) => `v#${app}#${stage}#${res}`,
281
286
  errors: (app: string, stage: string) => `e#${app}#${stage}`,
282
287
  uptime: (app: string, stage: string) => `u#${app}#${stage}`,
288
+ alerts: (app: string, stage: string) => `a#${app}#${stage}`,
283
289
  /**
284
290
  * Email usage: sk `YYYY-MM-DD` (UTC), `n` recipients sent. The SDK writes it
285
291
  * with the stage role, whose IAM grant covers only this partition.
@@ -288,6 +294,50 @@ export const telemetryKeys = {
288
294
  time: (ts: number) => new Date(ts).toISOString(),
289
295
  } as const;
290
296
 
297
+ // ---------------------------------------------------------------------------
298
+ // Edge traffic (the router's access log)
299
+ // ---------------------------------------------------------------------------
300
+
301
+ /**
302
+ * The fields the router's access log carries (CloudFront standard logging,
303
+ * delivered to `platformNames.edgeLogGroup` as one JSON object per request,
304
+ * every value a string). Enough to count requests and page views per host;
305
+ * never the client's address. Each field costs bytes ingested, but CloudFront
306
+ * includes 750 bytes of log delivery per request, which these stay well under.
307
+ */
308
+ export const EDGE_LOG_FIELDS = [
309
+ 'timestamp(ms)',
310
+ 'x-host-header',
311
+ 'cs-method',
312
+ 'cs-uri-stem',
313
+ 'sc-status',
314
+ 'sc-content-type',
315
+ ] as const;
316
+
317
+ /** One access log record, as `EDGE_LOG_FIELDS` deliver it. */
318
+ export const EdgeLogRecord = Schema.Struct({
319
+ 'timestamp(ms)': Schema.String,
320
+ 'x-host-header': Schema.String,
321
+ 'cs-method': Schema.String,
322
+ 'cs-uri-stem': Schema.String,
323
+ 'sc-status': Schema.String,
324
+ 'sc-content-type': Schema.optional(Schema.String),
325
+ });
326
+ export type EdgeLogRecord = typeof EdgeLogRecord.Type;
327
+
328
+ /**
329
+ * Whether a request loaded a page: a GET answered with an HTML document, or
330
+ * a 304 for a path that names no file (a page the browser had cached, whose
331
+ * revalidation carries no content type). Assets, API calls and errors aren't.
332
+ */
333
+ export function isPageView(method: string, uri: string, status: number, contentType: string | undefined) {
334
+ if (method !== 'GET') return false;
335
+ if (status >= 200 && status < 300) return (contentType ?? '').toLowerCase().startsWith('text/html');
336
+ if (status !== 304) return false;
337
+ const last = uri.slice(uri.lastIndexOf('/') + 1);
338
+ return !last.includes('.') || last.endsWith('.html');
339
+ }
340
+
291
341
  // ---------------------------------------------------------------------------
292
342
  // Error fingerprinting (Sentry-style grouping)
293
343
  // ---------------------------------------------------------------------------
@@ -16,9 +16,11 @@
16
16
  * mode (and back) by `simulateWebCompute`.
17
17
  */
18
18
  import { base64url, fromBase64url } from './base64url.ts';
19
- import { HOURS_PER_MONTH } from './compute.ts';
20
19
  import { PROD_STAGE } from './constants.ts';
21
20
 
21
+ /** Hours AWS bills a month of always-on capacity for. */
22
+ const HOURS_PER_MONTH = 730;
23
+
22
24
  export const WEB_COMPUTE = ['request', 'instance'] as const;
23
25
  export type WebCompute = (typeof WEB_COMPUTE)[number];
24
26
 
package/dist/compute.d.ts DELETED
@@ -1,52 +0,0 @@
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
- /** vCPUs a Fargate task may have (the platform caps it at 4). */
7
- export declare const FARGATE_CPUS: readonly [0.25, 0.5, 1, 2, 4];
8
- export type FargateCpu = (typeof FARGATE_CPUS)[number];
9
- /** Memory (MB) Fargate allows for each vCPU size. */
10
- export declare function fargateMemoryOptions(cpu: FargateCpu): number[];
11
- /** Why `cpu`/`memoryMb` isn't a size Fargate runs, or null when it is. */
12
- export declare function fargateSizeIssue(cpu: number, memoryMb: number): string | null;
13
- /** ECS task-definition units: 1024 per vCPU. */
14
- export declare function fargateCpuUnits(cpu: number): number;
15
- /**
16
- * Prices behind the estimates: us-east-1, Linux on ARM (Graviton), checked
17
- * 2026-11-15. Spot prices move with supply and demand, so Spot estimates are
18
- * approximate. Every task gets a public IPv4 address (there is no NAT), which
19
- * AWS bills by the hour whatever the capacity.
20
- */
21
- export declare const CONTAINER_PRICES_USD: {
22
- readonly onDemand: {
23
- readonly vcpuHour: 0.03238;
24
- readonly gbHour: 0.00356;
25
- };
26
- readonly spot: {
27
- readonly vcpuHour: 0.00995;
28
- readonly gbHour: 0.00109;
29
- };
30
- readonly publicIpv4Hour: 0.005;
31
- };
32
- /** Hours AWS bills a month of always-on capacity for. */
33
- export declare const HOURS_PER_MONTH = 730;
34
- export interface ContainerCostEstimate {
35
- /** vCPU and memory, per month. */
36
- computeUsd: number;
37
- /** The task's public IPv4 address, per month. */
38
- publicIpv4Usd: number;
39
- totalUsd: number;
40
- }
41
- /** What one container of this size costs a month if it runs all the time. */
42
- export declare function estimateContainerCost(size: {
43
- cpu: number;
44
- memoryMb: number;
45
- spot: boolean;
46
- }): ContainerCostEstimate;
47
- /** `0.25 vCPU · 512 MB · Spot`. */
48
- export declare function describeContainerSize(size: {
49
- cpu: number;
50
- memoryMb: number;
51
- spot: boolean;
52
- }): string;
package/dist/compute.js DELETED
@@ -1,65 +0,0 @@
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
- /** vCPUs a Fargate task may have (the platform caps it at 4). */
7
- export const FARGATE_CPUS = [0.25, 0.5, 1, 2, 4];
8
- /** Memory (MB) Fargate allows for each vCPU size. */
9
- export function fargateMemoryOptions(cpu) {
10
- if (cpu === 0.25)
11
- return [512, 1024, 2048];
12
- const [from, to] = MEMORY_RANGES[cpu];
13
- return Array.from({ length: (to - from) / 1024 + 1 }, (_, i) => from + i * 1024);
14
- }
15
- /** Above 0.25 vCPU, memory goes from..to in steps of 1024 MB. */
16
- const MEMORY_RANGES = {
17
- 0.5: [1024, 4096],
18
- 1: [2048, 8192],
19
- 2: [4096, 16384],
20
- 4: [8192, 30720],
21
- };
22
- /** Why `cpu`/`memoryMb` isn't a size Fargate runs, or null when it is. */
23
- export function fargateSizeIssue(cpu, memoryMb) {
24
- if (!FARGATE_CPUS.includes(cpu)) {
25
- return `cpu must be one of ${FARGATE_CPUS.join(', ')}`;
26
- }
27
- const options = fargateMemoryOptions(cpu);
28
- if (options.includes(memoryMb))
29
- return null;
30
- const allowed = cpu === 0.25 ? options.join(', ') : `${options[0]}-${options[options.length - 1]} in steps of 1024`;
31
- return `memoryMb ${memoryMb} doesn't fit ${cpu} vCPU: use ${allowed}`;
32
- }
33
- /** ECS task-definition units: 1024 per vCPU. */
34
- export function fargateCpuUnits(cpu) {
35
- return Math.round(cpu * 1024);
36
- }
37
- /**
38
- * Prices behind the estimates: us-east-1, Linux on ARM (Graviton), checked
39
- * 2026-11-15. Spot prices move with supply and demand, so Spot estimates are
40
- * approximate. Every task gets a public IPv4 address (there is no NAT), which
41
- * AWS bills by the hour whatever the capacity.
42
- */
43
- export const CONTAINER_PRICES_USD = {
44
- onDemand: { vcpuHour: 0.03238, gbHour: 0.00356 },
45
- spot: { vcpuHour: 0.00995, gbHour: 0.00109 },
46
- publicIpv4Hour: 0.005,
47
- };
48
- /** Hours AWS bills a month of always-on capacity for. */
49
- export const HOURS_PER_MONTH = 730;
50
- /** What one container of this size costs a month if it runs all the time. */
51
- export function estimateContainerCost(size) {
52
- const price = size.spot ? CONTAINER_PRICES_USD.spot : CONTAINER_PRICES_USD.onDemand;
53
- const hourly = size.cpu * price.vcpuHour + (size.memoryMb / 1024) * price.gbHour;
54
- const computeUsd = round2(hourly * HOURS_PER_MONTH);
55
- const publicIpv4Usd = round2(CONTAINER_PRICES_USD.publicIpv4Hour * HOURS_PER_MONTH);
56
- return { computeUsd, publicIpv4Usd, totalUsd: round2(computeUsd + publicIpv4Usd) };
57
- }
58
- /** `0.25 vCPU · 512 MB · Spot`. */
59
- export function describeContainerSize(size) {
60
- return `${size.cpu} vCPU · ${size.memoryMb} MB · ${size.spot ? 'Spot' : 'on-demand'}`;
61
- }
62
- function round2(n) {
63
- return Math.round(n * 100) / 100;
64
- }
65
- //# sourceMappingURL=compute.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"compute.js","sourceRoot":"","sources":["../src/compute.ts"],"names":[],"mappings":"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"}