ai-sdk-sandbox-gce 0.3.2 → 0.3.4

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.
@@ -17,5 +17,10 @@
17
17
  export const AGENT_TOKEN_HEADER = 'x-ai-sdk-sandbox-agent-token';
18
18
  /** The instance metadata key the agent reads its token from, when its environment has none. */
19
19
  export const AGENT_TOKEN_METADATA_KEY = 'ai-sdk-sandbox-agent-token';
20
+ /**
21
+ * The instance metadata key of a machine booted ahead of a sandbox: the minutes after its boot its
22
+ * agent powers it off unless configured meanwhile. Never without it.
23
+ */
24
+ export const IDLE_POWER_OFF_METADATA_KEY = 'ai-sdk-sandbox-idle-poweroff-minutes';
20
25
  /** The port the agent listens on, in its machine. */
21
26
  export const DEFAULT_AGENT_PORT = 8100;
@@ -5,10 +5,14 @@ export interface Instance {
5
5
  /** `PROVISIONING`, `STAGING`, `RUNNING`, `STOPPING`, `TERMINATED`, `SUSPENDING`, `SUSPENDED`… */
6
6
  status: string;
7
7
  labels?: Record<string, string>;
8
+ /** What the labels are changed with: Compute Engine refuses a change made on older ones. */
9
+ labelFingerprint?: string;
8
10
  networkInterfaces?: {
9
11
  networkIP?: string;
10
12
  }[];
11
13
  metadata?: InstanceMetadata;
14
+ /** When the instance was made: an RFC 3339 timestamp. */
15
+ creationTimestamp?: string;
12
16
  }
13
17
  /** The metadata of an instance: its `fingerprint` must be given back to change it. */
14
18
  export interface InstanceMetadata {
@@ -52,7 +56,7 @@ export declare class ComputeApi {
52
56
  getInstance(name: string): Promise<Instance | undefined>;
53
57
  /** The instances of the zone whose label `key` is `value`, every page of them. */
54
58
  listInstances(key: string, value: string): Promise<Instance[]>;
55
- insertInstance(body: Record<string, unknown>): Promise<void>;
59
+ insertInstance(body: Record<string, unknown>, { wait }?: ChangeOptions): Promise<void>;
56
60
  startInstance(name: string, { wait }?: ChangeOptions): Promise<void>;
57
61
  resumeInstance(name: string): Promise<void>;
58
62
  stopInstance(name: string, { wait }?: ChangeOptions): Promise<void>;
@@ -63,6 +67,11 @@ export declare class ComputeApi {
63
67
  * read with `fingerprint`.
64
68
  */
65
69
  setMetadata(name: string, metadata: InstanceMetadata): Promise<void>;
70
+ /**
71
+ * Replaces the labels of the instance `name`. Refused with a 412 when they changed since they were
72
+ * read with `fingerprint`: of two changes made on the same labels, one only goes through.
73
+ */
74
+ setLabels(name: string, labels: Record<string, string>, fingerprint: string | undefined): Promise<void>;
66
75
  /** Deletes the instance `name` and its disks set to go with it. Nothing when there is none. */
67
76
  deleteInstance(name: string, { wait }?: ChangeOptions): Promise<void>;
68
77
  /**
@@ -33,8 +33,8 @@ export class ComputeApi {
33
33
  } while (pageToken !== undefined);
34
34
  return instances;
35
35
  }
36
- async insertInstance(body) {
37
- await this.change('POST', this.zonal('instances'), { body });
36
+ async insertInstance(body, { wait = true } = {}) {
37
+ await this.change('POST', this.zonal('instances'), { body, wait });
38
38
  }
39
39
  async startInstance(name, { wait = true } = {}) {
40
40
  await this.change('POST', this.zonal(`instances/${name}/start`), { wait });
@@ -56,6 +56,15 @@ export class ComputeApi {
56
56
  async setMetadata(name, metadata) {
57
57
  await this.change('POST', this.zonal(`instances/${name}/setMetadata`), { body: metadata });
58
58
  }
59
+ /**
60
+ * Replaces the labels of the instance `name`. Refused with a 412 when they changed since they were
61
+ * read with `fingerprint`: of two changes made on the same labels, one only goes through.
62
+ */
63
+ async setLabels(name, labels, fingerprint) {
64
+ await this.change('POST', this.zonal(`instances/${name}/setLabels`), {
65
+ body: { labels, labelFingerprint: fingerprint },
66
+ });
67
+ }
59
68
  /** Deletes the instance `name` and its disks set to go with it. Nothing when there is none. */
60
69
  async deleteInstance(name, { wait = true } = {}) {
61
70
  await this.change('DELETE', this.zonal(`instances/${name}`), { ignore: [404], wait });
@@ -119,6 +119,56 @@ function reconcileEveryMs(value) {
119
119
  }
120
120
  return minutes === 0 ? undefined : minutes * 60_000;
121
121
  }
122
+ /**
123
+ * What `SANDBOX_PROFILE` sets the defaults of: `cost`, nothing running but the sandboxes, each
124
+ * booted on demand; `fast`, a machine of the warm pool always booted and the proxy always on, for a
125
+ * sandbox in seconds at a fixed cost.
126
+ */
127
+ const PROFILES = {
128
+ cost: { warmPool: 0, proxyAlwaysOn: false },
129
+ fast: { warmPool: 1, proxyAlwaysOn: true },
130
+ };
131
+ /** `SANDBOX_PROFILE`, `cost` or `fast`: `cost` when unset. */
132
+ function profile(value) {
133
+ const text = nonEmpty(value) ?? 'cost';
134
+ if (text !== 'cost' && text !== 'fast') {
135
+ throw new Error(`SANDBOX_PROFILE: \`${text}\` is neither \`cost\` nor \`fast\`.`);
136
+ }
137
+ return PROFILES[text];
138
+ }
139
+ /** `SANDBOX_WARM_POOL`, a whole number of machines: `fallback` when unset. */
140
+ function warmPool(value, fallback) {
141
+ const text = nonEmpty(value);
142
+ if (text === undefined)
143
+ return fallback;
144
+ const parsed = Number(text);
145
+ if (!Number.isInteger(parsed) || parsed < 0) {
146
+ throw new Error(`SANDBOX_WARM_POOL: \`${text}\` is not a whole number of machines.`);
147
+ }
148
+ return parsed;
149
+ }
150
+ /** A variable that is `true` or `false`: `fallback` when unset. */
151
+ function flag(name, value, fallback) {
152
+ const text = nonEmpty(value);
153
+ if (text === undefined)
154
+ return fallback;
155
+ if (text !== 'true' && text !== 'false') {
156
+ throw new Error(`${name}: \`${text}\` is neither \`true\` nor \`false\`.`);
157
+ }
158
+ return text === 'true';
159
+ }
160
+ /** The settings `SANDBOX_PROFILE` gives the defaults of, with a word on the cost of a warm pool. */
161
+ function speedSettings(env, logger) {
162
+ const defaults = profile(env['SANDBOX_PROFILE']);
163
+ const pool = warmPool(env['SANDBOX_WARM_POOL'], defaults.warmPool);
164
+ if (pool > 0) {
165
+ logger.info(`SANDBOX_WARM_POOL=${pool}: ${pool === 1 ? 'a machine is' : `${pool} machines are`} kept booted from each template in use, billed all the time.`);
166
+ }
167
+ return {
168
+ warmPool: pool,
169
+ proxyAlwaysOn: flag('SANDBOX_PROXY_ALWAYS_ON', env['SANDBOX_PROXY_ALWAYS_ON'], defaults.proxyAlwaysOn),
170
+ };
171
+ }
122
172
  /** The secret the agents' tokens are derived from. */
123
173
  function agentSecret(env) {
124
174
  const secret = required(env, 'SANDBOX_AGENT_SECRET', 'the secret the tokens of the sandboxes’ agents are derived from, 32 characters at least');
@@ -183,6 +233,7 @@ export async function sandboxesConfig(env, logger) {
183
233
  maxRunning: maxRunning(env['SANDBOX_MAX_RUNNING']),
184
234
  reconcileEveryMs: reconcileEveryMs(env['SANDBOX_RECONCILE_MINUTES']),
185
235
  proxyInstance: nonEmpty(env['SANDBOX_PROXY_INSTANCE']),
236
+ ...speedSettings(env, logger),
186
237
  serviceToken: serviceToken(env, logger),
187
238
  };
188
239
  }
@@ -29,8 +29,13 @@ export const ROUTES = [
29
29
  body: { status: 'ok', protocol: PROTOCOL_VERSION, version: PACKAGE_VERSION },
30
30
  })),
31
31
  // Beyond `ai-sdk-sandbox-cloud-run`'s API: boots what a sandbox will need, ahead of it.
32
- route('POST', /^\/v1\/prepare$/, async ({ sandboxes }) => {
33
- await sandboxes.prepare();
32
+ route('POST', /^\/v1\/prepare$/, async ({ sandboxes, request }) => {
33
+ // An earlier client sends no body: the proxy only.
34
+ const body = await readJson(request);
35
+ await sandboxes.prepare({
36
+ template: optionalString(body, 'template'),
37
+ image: optionalString(body, 'image'),
38
+ });
34
39
  return NO_CONTENT;
35
40
  }),
36
41
  route('POST', /^\/v1\/sandboxes$/, async ({ sandboxes, request }) => {
@@ -76,26 +76,39 @@ export interface SandboxesOptions {
76
76
  * one at once. Never without it.
77
77
  */
78
78
  reconcileEveryMs?: number;
79
+ /**
80
+ * How many machines are kept booted from each template in use, for the next creations from it to
81
+ * take at once rather than boot one: billed while they run, all the time, and deleted once they
82
+ * waited a day. Created in the request of a creation, never waited for. None without it.
83
+ */
84
+ warmPool?: number;
85
+ /**
86
+ * Never stops the proxy's machine of {@link proxyInstance} once no sandbox runs: a sandbox never
87
+ * waits for it to boot, and it is billed all the time. Stopped when idle without it.
88
+ */
89
+ proxyAlwaysOn?: boolean;
79
90
  }
80
91
  /** The image a sandbox gets when its caller names none. */
81
92
  export declare const DEFAULT_IMAGE = "default";
82
93
  /**
83
- * The sandboxes, each a Compute Engine machine of its own, named after it. The service keeps nothing
84
- * of them: what a machine is, Compute Engine says; what it may reach and its credentials, the egress
85
- * proxy holds; its processes, its agent runs. Any instance of the service, on any Cloud Run instance,
86
- * serves any sandbox.
94
+ * The sandboxes, each a Compute Engine machine of its own, named after it, or labelled with its
95
+ * name when taken from the warm pool. The service keeps nothing of them: what a machine is, Compute
96
+ * Engine says; what it may reach and its credentials, the egress proxy holds; its processes, its
97
+ * agent runs. Any instance of the service, on any Cloud Run instance, serves any sandbox.
87
98
  */
88
99
  export declare class Sandboxes {
89
100
  private readonly options;
90
101
  private readonly endpoints;
102
+ private readonly machines;
91
103
  private readonly bases;
92
104
  private nextReconcile;
93
105
  constructor(options: SandboxesOptions);
94
106
  /** The agent of the running sandbox `name`. */
95
107
  agent(name: string): Promise<AgentClient>;
96
108
  /**
97
- * Creates the sandbox `name` on the image `image`, from its template `template` when given.
98
- * Never resumes one.
109
+ * Creates the sandbox `name` on the image `image`, from its template `template` when given: on a
110
+ * machine of the warm pool booted from it when one runs, a new machine otherwise. Never resumes
111
+ * one.
99
112
  */
100
113
  create(name: string, { template, image, ...network }: SandboxNetwork & {
101
114
  image?: string;
@@ -147,11 +160,74 @@ export declare class Sandboxes {
147
160
  templateExists(id: string, image?: string): Promise<boolean>;
148
161
  deleteTemplate(id: string, image?: string): Promise<void>;
149
162
  /**
150
- * Starts the proxy's machine when the service drives it and it is stopped, without waiting for it
151
- * to boot: a sandbox created soon after finds it up, rather than waiting for it. Nothing else:
152
- * the proxy stops with the next sandbox that stops, or by itself when none comes.
163
+ * Boots what a sandbox likely to come soon will need, without waiting for it: the proxy's machine
164
+ * when the service drives it and it is stopped, and, given the `template` the sandbox will be made
165
+ * from, a machine of the warm pool booted from it when its pool holds none, whatever
166
+ * `SANDBOX_WARM_POOL`. The creation that follows takes it, rather than boot one. Nothing when the
167
+ * template does not exist yet: building it is the creation's. The proxy stops with the next
168
+ * sandbox that stops, or by itself when none comes; the machine is deleted by the next creation or
169
+ * preparation that meets it unused after {@link PREPARED_WAIT_MS}.
170
+ */
171
+ prepare({ template, image, }?: {
172
+ template?: string;
173
+ image?: string;
174
+ }): Promise<void>;
175
+ /**
176
+ * Starts the proxy's machine when the service drives it and it is stopped, not waiting for it to
177
+ * boot. One on its way down, the last sandbox just gone, is let stop first, within
178
+ * `startTimeoutMs`: Compute Engine starts no machine that is stopping.
179
+ */
180
+ private prepareProxy;
181
+ /**
182
+ * Boots a machine of the warm pool from the template `id` of `image` when it exists and its pool
183
+ * holds none usable, the machines no longer usable deleted meanwhile. One at a time: a
184
+ * preparation that finds another one made meanwhile deletes its own.
185
+ */
186
+ private prepareMachine;
187
+ /**
188
+ * Creates a machine of the warm pool labelled prepared, without waiting for it, then deletes it
189
+ * when another usable one of the template shows up meanwhile: of two preparations at once, the
190
+ * one that sees the other's machine gives way, so that one at most is left, none at worst.
191
+ */
192
+ private addPrepared;
193
+ /** Waits for every change of the pool, logging those that failed rather than failing. */
194
+ private settled;
195
+ /** The machines of the service's warm pool, taken or not. */
196
+ private poolMachines;
197
+ /**
198
+ * Whether the machine `machine` of the warm pool may be taken, of the template `templateLabel`
199
+ * when given: not retired, running or booting, and not waiting for too long, a prepared one
200
+ * {@link PREPARED_WAIT_MS}, any other {@link POOL_WAIT_MS}.
201
+ */
202
+ private usable;
203
+ /**
204
+ * Takes for the sandbox `name` a machine of the warm pool of its template, `sourceImage`, and sees
205
+ * to the pool: the template's machines missing created, and any machine no longer running (a Spot
206
+ * machine taken back, one at its run limit) or waiting for more than a day deleted, whatever its
207
+ * template. `upkeep` does so without waiting for Compute Engine, never failing: the caller awaits
208
+ * it before answering. A machine of the pool never ran an agent, as fresh as one made from the
209
+ * template; once taken, it never goes back to the pool.
210
+ */
211
+ private fromPool;
212
+ /**
213
+ * Takes the machine `machine` of the warm pool for the sandbox `name`, by its labels: of two
214
+ * creations taking it at once, Compute Engine lets one change them only. The machine as it is
215
+ * then, running or still booting, `undefined` when another creation took it, or it no longer
216
+ * runs. Fails when Compute Engine refuses the change for another reason.
153
217
  */
154
- prepare(): Promise<void>;
218
+ private take;
219
+ /**
220
+ * Deletes the machine `machine` of the warm pool, once labelled retired: a creation that read it
221
+ * before can no longer take it, nor this one take it from under a creation that did.
222
+ */
223
+ private retire;
224
+ /**
225
+ * Creates a machine of the warm pool booted from `template`, prepared for a sandbox likely to
226
+ * come when told so, without waiting for it. Answers its name.
227
+ */
228
+ private addToPool;
229
+ /** What the machines of the warm pool are named after: the service's prefix, then `pool-`. */
230
+ private get poolPrefix();
155
231
  /**
156
232
  * Starts the proxy's machine when the service drives it and it is stopped, and waits until the
157
233
  * proxy answers. Stopping, it is first let stop: its registrations go with it, and the sandboxes
@@ -160,7 +236,13 @@ export declare class Sandboxes {
160
236
  private proxyUp;
161
237
  /** Starts a {@link reconcile} without waiting for it, once per period at most. */
162
238
  private reconcileInBackground;
163
- /** Stops the proxy's machine, when the service drives it, once no sandbox runs. */
239
+ /**
240
+ * Stops the proxy's machine, when the service drives it and does not keep it running, once no
241
+ * sandbox runs, nor a prepared machine waits for one: a sandbox is about to take it, which would
242
+ * then wait for the proxy to boot again. The other machines of the warm pool need no proxy until
243
+ * taken; once the prepared one is taken or gone, the next stop applies the rule, and the proxy's
244
+ * own idle exit bounds it meanwhile.
245
+ */
164
246
  private proxyDownWhenIdle;
165
247
  /** Refuses one more running sandbox beyond {@link SandboxesOptions.maxRunning}. */
166
248
  private assertRoom;
@@ -181,22 +263,61 @@ export declare class Sandboxes {
181
263
  */
182
264
  private leftRunning;
183
265
  /**
184
- * Whether no instance is named `instance`, once the one going away is gone: a machine stopping
185
- * may be on its way to deletion, which takes some 50 s after the sandbox's own.
266
+ * The machine `instance` once it runs: a machine of the warm pool taken while it boots, which
267
+ * Compute Engine says is `RUNNING` some seconds later. As it is when it is not on its way.
268
+ */
269
+ private booted;
270
+ /**
271
+ * Whether no instance is named after the sandbox `name`, nor holds it under its label, once those
272
+ * going away are gone: a machine stopping may be on its way to deletion, which takes some 50 s
273
+ * after the sandbox's own.
186
274
  */
187
275
  private nameIsFree;
188
- /** Creates the machine `instance`, a standard one when the zone has no Spot capacity left. */
276
+ /** Creates the machine named after the sandbox `name`, and answers its name. */
277
+ private insertSandbox;
278
+ /**
279
+ * Makes the new machine `made` the sandbox `name`'s, and ready: taken from the warm pool as it
280
+ * is, or created under its name and read. Deleted when another machine holds the name too, or
281
+ * anything fails: half-made, it would block a retry under the same name, and cost.
282
+ */
283
+ private settle;
284
+ /**
285
+ * Whether the machine `instance` is the only one holding the sandbox `name`: two creations of the
286
+ * same name, one on a machine of the warm pool, are not stopped by Compute Engine as two machines
287
+ * of the same name are. The one that finds the other's loses; both may.
288
+ */
289
+ private soleHolder;
290
+ /** The machines holding the sandbox `name` under its label: taken from the warm pool. */
291
+ private labelled;
292
+ /**
293
+ * Creates the machine `instance`, a standard one when the zone has no Spot capacity left: of the
294
+ * sandbox it is named after, or of the warm pool with its `labels`. Not waited for with `wait`
295
+ * false: a missing capacity then goes unseen, and the machine is not made.
296
+ */
189
297
  private insert;
190
298
  /** Starts the stopped machine `instance`, as a standard one when the zone has no Spot capacity. */
191
299
  private start;
192
300
  /** The run limit of the machines, which Compute Engine enforces by stopping them. */
193
301
  private runLimit;
194
302
  private mayFallBack;
195
- /** The instance of the sandbox `name`: `undefined` when there is none, or one not the service's. */
303
+ /**
304
+ * The instance of the sandbox `name`: `undefined` when there is none, or one not the service's.
305
+ * The one named after it, or else the one holding it under its label, taken from the warm pool;
306
+ * the one found last tried first.
307
+ */
196
308
  private instanceOf;
309
+ /** The sandbox the machine `instance` holds: its label's, or the one it is named after. */
310
+ private sandboxOf;
311
+ /** Whether `instance` is a sandbox's machine of the service, holding `name`. */
312
+ private holds;
313
+ /**
314
+ * Deletes the machine `instance` of the sandbox `name`, the proxy made to forget it first, and
315
+ * returns once it left `RUNNING`. Only the proxy's registration without `instance`.
316
+ */
317
+ private removeMachine;
197
318
  /**
198
- * Makes the running machine of `name` ready for commands: registered with the egress proxy
199
- * under its address, its agent answering and configured.
319
+ * Makes the running machine `instance` of `name` ready for commands: registered with the egress
320
+ * proxy under its address, its agent answering and configured.
200
321
  */
201
322
  private ready;
202
323
  private waitForAgent;
@@ -217,4 +338,6 @@ export declare class Sandboxes {
217
338
  */
218
339
  private namespace;
219
340
  private instanceBody;
341
+ /** How a machine runs: Spot when the service's are, unless `standard`, its run limit either way. */
342
+ private scheduling;
220
343
  }