@ericminassian/platform-engine 0.3.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.
Files changed (94) hide show
  1. package/dist/clients.d.ts +8 -0
  2. package/dist/clients.js +22 -1
  3. package/dist/clients.js.map +1 -1
  4. package/dist/compat.d.ts +21 -9
  5. package/dist/compat.js +27 -7
  6. package/dist/compat.js.map +1 -1
  7. package/dist/drivers/appsync.d.ts +49 -0
  8. package/dist/drivers/appsync.js +155 -0
  9. package/dist/drivers/appsync.js.map +1 -0
  10. package/dist/drivers/ecr.d.ts +109 -0
  11. package/dist/drivers/ecr.js +303 -0
  12. package/dist/drivers/ecr.js.map +1 -0
  13. package/dist/drivers/ecs.d.ts +163 -0
  14. package/dist/drivers/ecs.js +447 -0
  15. package/dist/drivers/ecs.js.map +1 -0
  16. package/dist/drivers/events.d.ts +10 -0
  17. package/dist/drivers/events.js +13 -1
  18. package/dist/drivers/events.js.map +1 -1
  19. package/dist/drivers/index.d.ts +5 -0
  20. package/dist/drivers/index.js +5 -0
  21. package/dist/drivers/index.js.map +1 -1
  22. package/dist/drivers/kvs.d.ts +3 -0
  23. package/dist/drivers/kvs.js +14 -7
  24. package/dist/drivers/kvs.js.map +1 -1
  25. package/dist/drivers/lambda.d.ts +22 -0
  26. package/dist/drivers/lambda.js +74 -3
  27. package/dist/drivers/lambda.js.map +1 -1
  28. package/dist/drivers/request-function.d.ts +60 -0
  29. package/dist/drivers/request-function.js +167 -0
  30. package/dist/drivers/request-function.js.map +1 -0
  31. package/dist/drivers/s3.d.ts +5 -0
  32. package/dist/drivers/s3.js +26 -0
  33. package/dist/drivers/s3.js.map +1 -1
  34. package/dist/drivers/scheduler.d.ts +24 -0
  35. package/dist/drivers/scheduler.js +60 -5
  36. package/dist/drivers/scheduler.js.map +1 -1
  37. package/dist/drivers/ses.d.ts +77 -0
  38. package/dist/drivers/ses.js +181 -0
  39. package/dist/drivers/ses.js.map +1 -0
  40. package/dist/drivers/sqs.d.ts +11 -0
  41. package/dist/drivers/sqs.js +67 -1
  42. package/dist/drivers/sqs.js.map +1 -1
  43. package/dist/drivers/web-function.d.ts +11 -3
  44. package/dist/drivers/web-function.js +22 -5
  45. package/dist/drivers/web-function.js.map +1 -1
  46. package/dist/emulator.js.map +1 -1
  47. package/dist/images.d.ts +104 -0
  48. package/dist/images.js +182 -0
  49. package/dist/images.js.map +1 -0
  50. package/dist/index.d.ts +130 -6
  51. package/dist/index.js +11 -2
  52. package/dist/index.js.map +1 -1
  53. package/dist/local.js +222 -7
  54. package/dist/local.js.map +1 -1
  55. package/dist/policy.d.ts +47 -4
  56. package/dist/policy.js +365 -13
  57. package/dist/policy.js.map +1 -1
  58. package/dist/services.d.ts +155 -0
  59. package/dist/services.js +464 -0
  60. package/dist/services.js.map +1 -0
  61. package/dist/stage.d.ts +33 -8
  62. package/dist/stage.js +598 -124
  63. package/dist/stage.js.map +1 -1
  64. package/dist/static.d.ts +1 -1
  65. package/dist/static.js +2 -36
  66. package/dist/static.js.map +1 -1
  67. package/dist/util.d.ts +22 -0
  68. package/dist/util.js +18 -2
  69. package/dist/util.js.map +1 -1
  70. package/package.json +20 -14
  71. package/src/clients.ts +25 -1
  72. package/src/compat.ts +34 -11
  73. package/src/drivers/appsync.ts +220 -0
  74. package/src/drivers/ecr.ts +457 -0
  75. package/src/drivers/ecs.ts +661 -0
  76. package/src/drivers/events.ts +29 -2
  77. package/src/drivers/index.ts +5 -0
  78. package/src/drivers/kvs.ts +21 -12
  79. package/src/drivers/lambda.ts +103 -2
  80. package/src/drivers/request-function.ts +295 -0
  81. package/src/drivers/s3.ts +38 -0
  82. package/src/drivers/scheduler.ts +88 -5
  83. package/src/drivers/ses.ts +267 -0
  84. package/src/drivers/sqs.ts +95 -0
  85. package/src/drivers/web-function.ts +29 -9
  86. package/src/emulator.ts +3 -3
  87. package/src/images.ts +254 -0
  88. package/src/index.ts +129 -7
  89. package/src/local.ts +251 -7
  90. package/src/policy.ts +446 -24
  91. package/src/services.ts +663 -0
  92. package/src/stage.ts +753 -139
  93. package/src/static.ts +2 -37
  94. package/src/util.ts +38 -4
package/src/images.ts ADDED
@@ -0,0 +1,254 @@
1
+ /**
2
+ * OCI image assembly without Docker: a layer is a deterministic tarball of
3
+ * files, an image is a base image's layers plus that layer, described by a
4
+ * config and a manifest. Pure functions; the registry calls live in
5
+ * `drivers/ecr.ts`.
6
+ *
7
+ * Determinism matters: the same files on the same base give byte-identical
8
+ * blobs, so redeploying unchanged code pushes nothing new and the image
9
+ * digest says whether a build changed.
10
+ */
11
+
12
+ import { createHash } from 'node:crypto';
13
+ import { gzipSync } from 'fflate';
14
+
15
+ export const MEDIA_TYPES = {
16
+ ociManifest: 'application/vnd.oci.image.manifest.v1+json',
17
+ ociIndex: 'application/vnd.oci.image.index.v1+json',
18
+ ociConfig: 'application/vnd.oci.image.config.v1+json',
19
+ ociLayerGzip: 'application/vnd.oci.image.layer.v1.tar+gzip',
20
+ dockerManifest: 'application/vnd.docker.distribution.manifest.v2+json',
21
+ dockerManifestList: 'application/vnd.docker.distribution.manifest.list.v2+json',
22
+ } as const;
23
+
24
+ /** Single-platform manifest types a base image may have. */
25
+ export const IMAGE_MANIFEST_TYPES: readonly string[] = [MEDIA_TYPES.ociManifest, MEDIA_TYPES.dockerManifest];
26
+
27
+ export interface Descriptor {
28
+ mediaType: string;
29
+ digest: string;
30
+ size: number;
31
+ annotations?: Record<string, string>;
32
+ }
33
+
34
+ export interface ImageManifest {
35
+ schemaVersion: 2;
36
+ mediaType?: string;
37
+ config: Descriptor;
38
+ layers: Descriptor[];
39
+ annotations?: Record<string, string>;
40
+ }
41
+
42
+ /** The parts of an OCI image config the platform reads or writes; the rest passes through. */
43
+ export interface ImageConfig {
44
+ architecture: string;
45
+ os: string;
46
+ created?: string;
47
+ config?: {
48
+ Env?: string[];
49
+ Entrypoint?: string[] | null;
50
+ Cmd?: string[] | null;
51
+ WorkingDir?: string;
52
+ User?: string;
53
+ [key: string]: unknown;
54
+ };
55
+ rootfs: { type: 'layers'; diff_ids: string[] };
56
+ history?: Array<{ created?: string; created_by?: string; comment?: string; empty_layer?: boolean }>;
57
+ [key: string]: unknown;
58
+ }
59
+
60
+ export interface ImageFile {
61
+ /** Absolute path inside the image (`/app/index.mjs`). */
62
+ path: string;
63
+ content: Uint8Array;
64
+ /** Default 0o644. */
65
+ mode?: number;
66
+ }
67
+
68
+ export interface Layer {
69
+ /** The gzipped tarball as pushed. */
70
+ blob: Uint8Array;
71
+ /** sha256 of `blob`: the layer's digest in the manifest. */
72
+ digest: string;
73
+ /** sha256 of the uncompressed tarball: the layer's entry in the config's `rootfs.diff_ids`. */
74
+ diffId: string;
75
+ size: number;
76
+ }
77
+
78
+ export function sha256Digest(bytes: Uint8Array): string {
79
+ return `sha256:${createHash('sha256').update(bytes).digest('hex')}`;
80
+ }
81
+
82
+ /**
83
+ * A ustar archive of `files` plus an entry for every parent directory,
84
+ * sorted by path, owned by root with mtime 0, so equal input gives equal
85
+ * bytes.
86
+ */
87
+ export function tarFiles(files: readonly ImageFile[]): Uint8Array {
88
+ const entries = new Map<string, { type: 'dir' } | { type: 'file'; content: Uint8Array; mode: number }>();
89
+ for (const f of files) {
90
+ const rel = normalizePath(f.path);
91
+ const parts = rel.split('/');
92
+ for (let i = 1; i < parts.length; i++) entries.set(`${parts.slice(0, i).join('/')}/`, { type: 'dir' });
93
+ if (entries.has(rel)) throw new Error(`duplicate file in layer: ${f.path}`);
94
+ entries.set(rel, { type: 'file', content: f.content, mode: f.mode ?? 0o644 });
95
+ }
96
+ const blocks: Uint8Array[] = [];
97
+ for (const name of [...entries.keys()].toSorted()) {
98
+ const e = entries.get(name)!;
99
+ if (e.type === 'dir') {
100
+ blocks.push(tarHeader({ name, mode: 0o755, size: 0, type: '5' }));
101
+ } else {
102
+ blocks.push(tarHeader({ name, mode: e.mode, size: e.content.length, type: '0' }), e.content);
103
+ const pad = (512 - (e.content.length % 512)) % 512;
104
+ if (pad) blocks.push(new Uint8Array(pad));
105
+ }
106
+ }
107
+ blocks.push(new Uint8Array(1024));
108
+ return concat(blocks);
109
+ }
110
+
111
+ /** A gzipped layer of `files` with its digests. */
112
+ export function buildLayer(files: readonly ImageFile[]): Layer {
113
+ const tar = tarFiles(files);
114
+ // mtime 0 keeps the gzip header (and so the digest) stable.
115
+ const blob = gzipSync(tar, { level: 9, mtime: 0 });
116
+ return { blob, digest: sha256Digest(blob), diffId: sha256Digest(tar), size: blob.length };
117
+ }
118
+
119
+ export interface ImageConfigSpec {
120
+ entrypoint: string[];
121
+ /** Replaces the base image's Cmd; none when omitted (the base's would be appended to the entrypoint). */
122
+ cmd?: string[];
123
+ /** Merged over the base image's environment. */
124
+ env?: Record<string, string>;
125
+ workingDir?: string;
126
+ user?: string;
127
+ /** History line for the added layer. */
128
+ createdBy?: string;
129
+ }
130
+
131
+ /** The base image's config with `layer` on top and the process settings of `spec`. */
132
+ export function imageConfig(base: ImageConfig, layer: Layer, spec: ImageConfigSpec): ImageConfig {
133
+ const env = new Map<string, string>();
134
+ for (const kv of base.config?.Env ?? []) {
135
+ const i = kv.indexOf('=');
136
+ env.set(i === -1 ? kv : kv.slice(0, i), i === -1 ? '' : kv.slice(i + 1));
137
+ }
138
+ for (const [k, v] of Object.entries(spec.env ?? {})) env.set(k, v);
139
+ const { Cmd: _cmd, ...baseProcess } = base.config ?? {};
140
+ return {
141
+ ...base,
142
+ config: {
143
+ ...baseProcess,
144
+ Env: [...env].map(([k, v]) => `${k}=${v}`),
145
+ Entrypoint: spec.entrypoint,
146
+ ...(spec.cmd ? { Cmd: spec.cmd } : {}),
147
+ ...(spec.workingDir ? { WorkingDir: spec.workingDir } : {}),
148
+ ...(spec.user ? { User: spec.user } : {}),
149
+ },
150
+ rootfs: { type: 'layers', diff_ids: [...base.rootfs.diff_ids, layer.diffId] },
151
+ history: [
152
+ ...(base.history ?? []),
153
+ { ...(base.created ? { created: base.created } : {}), created_by: spec.createdBy ?? 'platform' },
154
+ ],
155
+ };
156
+ }
157
+
158
+ /** An OCI image manifest (serialized: its bytes are what the digest covers). */
159
+ export function imageManifest(
160
+ config: { digest: string; size: number },
161
+ layers: readonly Descriptor[],
162
+ ): string {
163
+ const manifest: ImageManifest = {
164
+ schemaVersion: 2,
165
+ mediaType: MEDIA_TYPES.ociManifest,
166
+ config: { mediaType: MEDIA_TYPES.ociConfig, digest: config.digest, size: config.size },
167
+ layers: layers.map((l) => ({ mediaType: l.mediaType, digest: l.digest, size: l.size })),
168
+ };
169
+ return JSON.stringify(manifest);
170
+ }
171
+
172
+ export function layerDescriptor(layer: Layer): Descriptor {
173
+ return { mediaType: MEDIA_TYPES.ociLayerGzip, digest: layer.digest, size: layer.size };
174
+ }
175
+
176
+ /** Parse a registry manifest, refusing multi-platform indexes (a base must be pinned to one platform). */
177
+ export function parseImageManifest(raw: string, fallbackMediaType?: string): ImageManifest {
178
+ const m = JSON.parse(raw) as Partial<ImageManifest> & { manifests?: unknown };
179
+ const mediaType = m.mediaType ?? fallbackMediaType;
180
+ if (m.manifests || mediaType === MEDIA_TYPES.ociIndex || mediaType === MEDIA_TYPES.dockerManifestList) {
181
+ throw new Error('expected a single-platform image manifest, got a multi-platform index');
182
+ }
183
+ if (m.schemaVersion !== 2 || !m.config?.digest || !Array.isArray(m.layers)) {
184
+ throw new Error('not an image manifest (schema version 2 with a config and layers)');
185
+ }
186
+ return m as ImageManifest;
187
+ }
188
+
189
+ function normalizePath(path: string): string {
190
+ const rel = path.replace(/^\/+/, '');
191
+ if (!rel || rel.endsWith('/') || rel.split('/').some((p) => p === '' || p === '.' || p === '..')) {
192
+ throw new Error(`invalid file path in layer: ${path}`);
193
+ }
194
+ return rel;
195
+ }
196
+
197
+ const encoder = new TextEncoder();
198
+
199
+ function tarHeader(e: { name: string; mode: number; size: number; type: '0' | '5' }): Uint8Array {
200
+ const h = new Uint8Array(512);
201
+ const [prefix, name] = splitName(e.name);
202
+ writeString(h, 0, 100, name);
203
+ writeOctal(h, 100, 8, e.mode);
204
+ writeOctal(h, 108, 8, 0); // uid
205
+ writeOctal(h, 116, 8, 0); // gid
206
+ writeOctal(h, 124, 12, e.size);
207
+ writeOctal(h, 136, 12, 0); // mtime
208
+ h.fill(0x20, 148, 156); // checksum is computed with its own field as spaces
209
+ h[156] = e.type.charCodeAt(0);
210
+ writeString(h, 257, 6, 'ustar');
211
+ writeString(h, 263, 2, '00');
212
+ writeString(h, 265, 32, 'root');
213
+ writeString(h, 297, 32, 'root');
214
+ writeString(h, 345, 155, prefix);
215
+ const sum = h.reduce((a, b) => a + b, 0);
216
+ writeString(h, 148, 8, `${sum.toString(8).padStart(6, '0')}\0 `);
217
+ return h;
218
+ }
219
+
220
+ /** ustar keeps names ≤ 100 bytes, or a ≤ 155-byte prefix plus a ≤ 100-byte name split at a `/`. */
221
+ function splitName(path: string): [string, string] {
222
+ const bytes = encoder.encode(path);
223
+ if (bytes.length <= 100) return ['', path];
224
+ // A directory entry's trailing slash stays with the name part.
225
+ for (let i = path.length - 2; i > 0; i--) {
226
+ if (path[i] !== '/') continue;
227
+ const prefix = path.slice(0, i);
228
+ const name = path.slice(i + 1);
229
+ if (encoder.encode(prefix).length <= 155 && encoder.encode(name).length <= 100) return [prefix, name];
230
+ }
231
+ throw new Error(`path too long for a ustar layer: ${path}`);
232
+ }
233
+
234
+ function writeString(h: Uint8Array, offset: number, length: number, value: string): void {
235
+ const bytes = encoder.encode(value);
236
+ if (bytes.length > length) throw new Error(`tar header field too long: ${value}`);
237
+ h.set(bytes, offset);
238
+ }
239
+
240
+ function writeOctal(h: Uint8Array, offset: number, length: number, value: number): void {
241
+ const digits = value.toString(8);
242
+ if (digits.length > length - 1) throw new Error(`tar header value too large: ${value}`);
243
+ writeString(h, offset, length, `${digits.padStart(length - 1, '0')}\0`);
244
+ }
245
+
246
+ function concat(parts: readonly Uint8Array[]): Uint8Array {
247
+ const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
248
+ let at = 0;
249
+ for (const p of parts) {
250
+ out.set(p, at);
251
+ at += p.length;
252
+ }
253
+ return out;
254
+ }
package/src/index.ts CHANGED
@@ -18,19 +18,25 @@ import { GetCallerIdentityCommand } from '@aws-sdk/client-sts';
18
18
  import type {
19
19
  Bindings,
20
20
  PlatformRuntimeConfig,
21
+ RealtimeEdgeEntry,
21
22
  ResolvedManifest,
22
23
  RouteRecord,
24
+ WebCompute,
23
25
  } from '@ericminassian/platform-core';
24
26
  import { createClients } from './clients.ts';
27
+ import { ensureRealtimePlatform } from './drivers/appsync.ts';
25
28
  import { putObject } from './drivers/s3.ts';
26
29
  import { ensureLocal } from './local.ts';
27
- import { deployStage, destroyStage, listStageResources, rollbackStage } from './stage.ts';
30
+ import { controlService, describeServices } from './services.ts';
31
+ import { deployStage, destroyStage, expireStorage, listStageResources, rollbackStage } from './stage.ts';
28
32
  import type { EngineContext } from './util.ts';
29
33
 
30
34
  export type { AwsClients } from './clients.ts';
31
35
  export * from './drivers/index.ts';
32
36
  export * from './emulator.ts';
37
+ export * as images from './images.ts';
33
38
  export * as policies from './policy.ts';
39
+ export { ServiceNotFoundError } from './services.ts';
34
40
  export { hostFor } from './stage.ts';
35
41
  export { cacheControlFor, contentTypeFor } from './static.ts';
36
42
  export type { EngineContext, PolicyDocument, PolicyStatement } from './util.ts';
@@ -67,14 +73,31 @@ export interface DeployStageInput {
67
73
  stage: string;
68
74
  deploymentId: string;
69
75
  platform: PlatformRuntimeConfig;
70
- /** Uploaded build artifacts (zips) in the artifacts bucket. */
71
- artifacts: { server?: S3Location; worker?: S3Location; static?: S3Location };
76
+ /**
77
+ * Uploaded build artifacts (zips) in the artifacts bucket. `services` is
78
+ * `services.zip`: `<service>/index.mjs` (+ `.map`) for each declared service.
79
+ */
80
+ artifacts: { server?: S3Location; worker?: S3Location; static?: S3Location; services?: S3Location };
72
81
  /**
73
82
  * `function`: create/update the Lambda Web Function + route record (AWS).
74
83
  * `external`: skip both; `plat dev` runs the server process itself because
75
84
  * the emulator does not serve Web Function endpoints yet.
76
85
  */
77
86
  webMode?: 'function' | 'external';
87
+ /**
88
+ * How the server runs with `webMode: 'function'` (core `webComputeFor`
89
+ * decides it): `instance`, a Lambda Web Function (the default), or
90
+ * `request`, a Lambda function per request behind function URLs. A deploy
91
+ * builds only this one; the stage keeps the other mode's (it costs nothing
92
+ * idle) until the manifest drops `web.server` or the stage is destroyed.
93
+ */
94
+ webCompute?: WebCompute;
95
+ /**
96
+ * `ecs`: build each service's image and run it on ECS (AWS; the default).
97
+ * `external`: skip images and ECS; `plat dev` runs services as local
98
+ * processes. Their log groups are created either way.
99
+ */
100
+ servicesMode?: 'ecs' | 'external';
78
101
  /** Use this role instead of creating the per-stage role (the control plane runs privileged). */
79
102
  roleArn?: string;
80
103
  /** Extra environment variables for web + worker (merged over manifest `env`). */
@@ -83,7 +106,7 @@ export interface DeployStageInput {
83
106
  }
84
107
 
85
108
  export interface ResourceRef {
86
- /** `role`, `table`, `queue`, `bus`, `rule`, `schedule-group`, `schedule`, `log-group`, `web-function`, `function`, `esm`, `user-pool-client`, `route`, `static` */
109
+ /** `role`, `table`, `queue`, `bus`, `rule`, `schedule-group`, `schedule`, `log-group`, `web-function`, `function` (worker, a handler's own, or the request-mode server), `esm`, `user-pool-client`, `channel-namespace`, `email-tenant`, `configuration-set`, `route`, `static`, `image`, `task-definition`, `ecs-service` */
87
110
  type: string;
88
111
  name: string;
89
112
  arn?: string;
@@ -94,19 +117,86 @@ export interface DeployStageResult {
94
117
  host: string;
95
118
  url: string;
96
119
  route?: RouteRecord;
120
+ /** How the server runs, when the stage has one. */
121
+ compute?: WebCompute;
122
+ /** The server in instance mode. */
97
123
  webFunction?: { name: string; endpointDomain: string; revisionId: string };
124
+ /** The server in request mode: the version this deploy published, behind `urlDomain`. */
125
+ requestFunction?: { name: string; urlDomain: string; version: string };
98
126
  workerFunction?: { name: string; arn: string };
127
+ /** Services the deploy rolled out (`servicesMode: 'ecs'`). */
128
+ services?: DeployedService[];
99
129
  resources: ResourceRef[];
100
130
  }
101
131
 
132
+ export interface DeployedService {
133
+ /** The key in plat.config.ts (`ais`). */
134
+ name: string;
135
+ /** `<repositoryUri>@sha256:…`. */
136
+ image: string;
137
+ taskDefinitionArn: string;
138
+ /** 1 running, 0 when a preview doesn't run it. */
139
+ desired: number;
140
+ /** A preview's stop schedule. */
141
+ stopsAt?: string;
142
+ }
143
+
102
144
  export interface RollbackStageInput {
103
145
  app: string;
104
146
  stage: string;
105
147
  platform: PlatformRuntimeConfig;
106
- /** Route record of the deployment to go back to. The engine picks the endpoint (`o`) itself. */
148
+ /**
149
+ * Route record of the deployment to go back to, in its compute mode. The
150
+ * engine picks the endpoint or function URL (`o`) itself.
151
+ */
107
152
  route: RouteRecord;
108
- /** That deployment's Web Function revision. */
153
+ /** That deployment's Web Function revision (instance mode). */
109
154
  revisionId?: string;
155
+ /** That deployment's function version (request mode). */
156
+ version?: string;
157
+ /**
158
+ * Services that deployment declared. Each one the stage still runs is
159
+ * pointed back at that deployment's build; the rollback is refused if a
160
+ * build was cleaned up since.
161
+ */
162
+ services?: readonly string[];
163
+ }
164
+
165
+ export interface StageServicesInput {
166
+ app: string;
167
+ stage: string;
168
+ platform: PlatformRuntimeConfig;
169
+ }
170
+
171
+ /** One service as ECS reports it right now. */
172
+ export interface ServiceRuntimeState {
173
+ name: string;
174
+ desired: number;
175
+ running: number;
176
+ pending: number;
177
+ /** The newest ECS deployment's rollout (`COMPLETED`, `IN_PROGRESS`, `FAILED`). */
178
+ rollout?: 'completed' | 'in_progress' | 'failed';
179
+ /** Deployment whose build the newest ECS deployment runs (its task definition's tag). */
180
+ deploymentId?: string;
181
+ /** When the current task started. */
182
+ startedAt?: string;
183
+ /** When a stop schedule scales it to zero. */
184
+ stopsAt?: string;
185
+ /** The task that stopped most recently. */
186
+ lastStop?: { at: string; reason: string; exitCode?: number };
187
+ /** Recent ECS service events, newest first (at most 10). */
188
+ events: Array<{ at: string; message: string }>;
189
+ }
190
+
191
+ export interface ControlServiceInput extends StageServicesInput {
192
+ name: string;
193
+ /**
194
+ * `start`: desired 1, stopping again after `minutes` when given (replacing
195
+ * any stop schedule). `stop`: desired 0 (and no stop schedule). `restart`:
196
+ * a fresh task on the same build.
197
+ */
198
+ action: 'start' | 'stop' | 'restart';
199
+ minutes?: number;
110
200
  }
111
201
 
112
202
  export interface DestroyStageInput {
@@ -117,6 +207,16 @@ export interface DestroyStageInput {
117
207
  keepData?: boolean;
118
208
  }
119
209
 
210
+ export interface ExpireStorageInput {
211
+ app: string;
212
+ stage: string;
213
+ platform: PlatformRuntimeConfig;
214
+ /** The live deployment's: its stores' `expireAfterDays` and where their files are. */
215
+ manifest: Pick<ResolvedManifest, 'storage' | 'storageOptions'>;
216
+ /** Default: the current time. */
217
+ now?: Date;
218
+ }
219
+
120
220
  export interface Engine {
121
221
  readonly region: string;
122
222
  readonly target: 'aws' | 'emulator';
@@ -125,10 +225,27 @@ export interface Engine {
125
225
  /** Returns the route record it wrote. */
126
226
  rollbackStage(input: RollbackStageInput): Promise<RouteRecord>;
127
227
  destroyStage(input: DestroyStageInput): Promise<void>;
228
+ /**
229
+ * Delete the files of the stage's stores that set `expireAfterDays` and
230
+ * weren't written for that many days. Answers how many, by store. The
231
+ * control plane runs it daily for every live stage.
232
+ */
233
+ expireStorage(input: ExpireStorageInput): Promise<Record<string, number>>;
128
234
  /** Everything the engine owns for a stage (found by name + tags). */
129
235
  listStageResources(app: string, stage: string): Promise<ResourceRef[]>;
130
236
  /** Upload a local file/buffer into the artifacts bucket (used by `plat dev`). */
131
237
  putArtifact(platform: PlatformRuntimeConfig, key: string, body: Uint8Array): Promise<S3Location>;
238
+ /**
239
+ * Keep realtime usable platform-wide: the public subscribe key exists and is far from expiry,
240
+ * and the router's realtime entry is current (written only when the platform has a route
241
+ * store). Returns that entry, or undefined when the platform has no realtime API. The control
242
+ * plane runs it nightly; `plat dev` serves the entry from its local router.
243
+ */
244
+ ensureRealtimePlatform(platform: PlatformRuntimeConfig): Promise<RealtimeEdgeEntry | undefined>;
245
+ /** The stage's long-running services as ECS runs them now (none without container compute). */
246
+ describeServices(input: StageServicesInput): Promise<ServiceRuntimeState[]>;
247
+ /** Start, stop or restart one of the stage's services. */
248
+ controlService(input: ControlServiceInput): Promise<{ desired: number; stopsAt?: string }>;
132
249
  }
133
250
 
134
251
  export function createEngine(opts: EngineOptions): Engine {
@@ -140,8 +257,12 @@ export function createEngine(opts: EngineOptions): Engine {
140
257
  deployStage: (input) => deployStage(ctx, input),
141
258
  rollbackStage: (input) => rollbackStage(ctx, input),
142
259
  destroyStage: (input) => destroyStage(ctx, input),
260
+ expireStorage: (input) => expireStorage(ctx, input),
143
261
  listStageResources: (app, stage) => listStageResources(ctx, app, stage),
144
262
  putArtifact: (platform, key, body) => putObject(ctx, { bucket: platform.artifactsBucket, key, body }),
263
+ ensureRealtimePlatform: (platform) => ensureRealtimePlatform(ctx, platform),
264
+ describeServices: (input) => describeServices(ctx, input),
265
+ controlService: (input) => controlService(ctx, input),
145
266
  };
146
267
  contexts.set(engine, ctx);
147
268
  return engine;
@@ -174,7 +295,8 @@ function createContext(opts: EngineOptions): EngineContext {
174
295
 
175
296
  /**
176
297
  * Shared resources `plat dev` needs inside a fresh emulator (buckets, tables,
177
- * user pool) and the matching runtime config (`target: 'emulator'`).
298
+ * user pool, realtime API, mail domain) and the matching runtime config
299
+ * (`target: 'emulator'`).
178
300
  */
179
301
  export async function ensureLocalPlatform(
180
302
  engine: Engine,