sandcovery 0.6.2 → 0.7.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.
@@ -0,0 +1,438 @@
1
+ import { _ as KUBERNETES_COMMAND, a as savedSandboxes, b as writePrivateFile, c as launchedRelay, d as servedAt, f as servedOrSpawned, g as v7, h as noop, i as saveSandbox, l as READY, m as clamp, p as socketOf, r as runningSandbox, u as isTerminal, v as KUBERNETES_GATEWAY_COMMAND, y as KUBERNETES_PORT } from "./tool-B8KvfvY5.mjs";
2
+ import { Bs as isSome, Cn as decodeUnknownSync, Hs as map, Ks as some, Ms as fromNullOr, Os as exists, Ps as fromUndefinedOr, Sn as decodeUnknownOption, Us as match, Ws as none, cn as String, ks as filter, ln as Struct, ps as try_, rn as Number$1, us as isSuccess, wn as fromJsonString, zs as isNone } from "./x-account-BSasf-z-.mjs";
3
+ import { t as Sandcovery } from "./src-gAv6vIvE.mjs";
4
+ import os from "node:os";
5
+ import { spawn } from "node:child_process";
6
+ import net from "node:net";
7
+ import fs from "node:fs";
8
+ import path from "node:path";
9
+ import readline from "node:readline";
10
+ import { once } from "node:events";
11
+ import { setTimeout as setTimeout$1 } from "node:timers/promises";
12
+ // src/cli/kubectl-idle.ts
13
+ const IDLE_WATCHER_ENV = "__SANDCOVERY_KUBECTL_IDLE";
14
+ const IDLE_SOCKET_NAME = "kubectl-idle";
15
+ const IDLE_MS = 9e5;
16
+ const HEARTBEAT_MS = 6e4;
17
+ const DESTROY_TIMEOUT_MS = 3e4;
18
+ const REFUSED_STATUSES = /* @__PURE__ */ new Set([
19
+ 400,
20
+ 401,
21
+ 403,
22
+ 404,
23
+ 409,
24
+ 410,
25
+ 422
26
+ ]);
27
+ const decodeWatcher = decodeUnknownSync(fromJsonString(Struct({
28
+ idleMs: Number$1,
29
+ socketPath: String
30
+ })));
31
+ const decodeHold = decodeUnknownOption(fromJsonString(Struct({ origin: String })));
32
+ const decodeAnswered = decodeUnknownOption(Struct({ cause: Struct({ status: Number$1 }) }));
33
+ const decodeCluster = decodeUnknownOption(fromJsonString(Struct({
34
+ expires_at: String,
35
+ key: String,
36
+ sandbox: String
37
+ })));
38
+ const ended = async ({ cluster, origin }) => {
39
+ try {
40
+ await new Sandcovery({
41
+ apiKey: cluster.key,
42
+ baseUrl: origin
43
+ }).sandboxes.destroy(cluster.sandbox, { signal: AbortSignal.timeout(DESTROY_TIMEOUT_MS) });
44
+ return true;
45
+ } catch (error) {
46
+ if (!(error instanceof Error)) throw error;
47
+ return isTerminal(error) || exists(decodeAnswered(error), ({ cause }) => REFUSED_STATUSES.has(cause.status));
48
+ }
49
+ };
50
+ const destroyed = async ({ entry, origin, settle }) => {
51
+ const { cluster } = entry;
52
+ if (cluster !== null && await ended({
53
+ cluster,
54
+ origin
55
+ })) {
56
+ if (entry.cluster?.sandbox === cluster.sandbox) entry.cluster = null;
57
+ } else entry.due = Date.now() + HEARTBEAT_MS;
58
+ entry.destroying = null;
59
+ settle();
60
+ };
61
+ const watchIdle = async (config) => {
62
+ const { idleMs, socketPath } = decodeWatcher(config);
63
+ const watched = /* @__PURE__ */ new Map();
64
+ const listener = net.createServer();
65
+ const state = {
66
+ connections: 0,
67
+ timer: null
68
+ };
69
+ const check = () => {
70
+ const now = Date.now();
71
+ if (state.timer !== null) clearTimeout(state.timer);
72
+ for (const [origin, entry] of watched) {
73
+ if (entry.cluster !== null && now >= entry.cluster.expiresAt) entry.cluster = null;
74
+ if (entry.cluster !== null && entry.holders === 0 && entry.destroying === null && now >= entry.due) entry.destroying = destroyed({
75
+ entry,
76
+ origin,
77
+ settle: check
78
+ });
79
+ if (entry.cluster === null && entry.holders === 0 && entry.destroying === null) watched.delete(origin);
80
+ }
81
+ if (state.connections === 0 && watched.size === 0) {
82
+ listener.close();
83
+ return;
84
+ }
85
+ const next = Math.min(now + HEARTBEAT_MS, ...[...watched.values()].flatMap(({ cluster, destroying, due, holders }) => cluster === null ? [] : [cluster.expiresAt, ...holders === 0 && destroying === null ? [due] : []]));
86
+ state.timer = setTimeout(check, clamp(next - now, 0, HEARTBEAT_MS));
87
+ };
88
+ const held = async (connection, origin) => {
89
+ const entry = watched.get(origin) ?? {
90
+ cluster: null,
91
+ destroying: null,
92
+ due: Date.now() + idleMs,
93
+ holders: 0
94
+ };
95
+ entry.holders += 1;
96
+ watched.set(origin, entry);
97
+ await entry.destroying;
98
+ connection.write(READY);
99
+ return entry;
100
+ };
101
+ listener.on("connection", (connection) => {
102
+ const hold = { entry: null };
103
+ const lines = readline.createInterface({ input: connection });
104
+ state.connections += 1;
105
+ connection.on("error", noop);
106
+ const received = async (line) => {
107
+ if (hold.entry !== null) {
108
+ const entry = await hold.entry;
109
+ const cluster = decodeCluster(line).pipe(map(({ expires_at, key, sandbox }) => ({
110
+ expiresAt: Date.parse(expires_at),
111
+ key,
112
+ sandbox
113
+ })), filter(({ expiresAt }) => !Number.isNaN(expiresAt)));
114
+ if (isNone(cluster)) {
115
+ connection.destroy();
116
+ return;
117
+ }
118
+ entry.cluster = cluster.value;
119
+ return;
120
+ }
121
+ const asked = decodeHold(line);
122
+ if (isNone(asked)) {
123
+ connection.destroy();
124
+ return;
125
+ }
126
+ hold.entry = held(connection, asked.value.origin);
127
+ };
128
+ const released = async () => {
129
+ const entry = await hold.entry;
130
+ state.connections -= 1;
131
+ lines.close();
132
+ if (entry !== null) {
133
+ entry.holders -= 1;
134
+ entry.due = Date.now() + idleMs;
135
+ }
136
+ check();
137
+ };
138
+ lines.on("line", (line) => {
139
+ received(line);
140
+ });
141
+ connection.once("close", () => {
142
+ released();
143
+ });
144
+ });
145
+ const serving = await servedAt(listener, socketPath);
146
+ process.stdout.write(READY);
147
+ if (serving) state.timer = setTimeout(check, HEARTBEAT_MS);
148
+ };
149
+ const holdCluster = async ({ entry, folder, origin }) => {
150
+ const socketPath = socketOf({
151
+ folder,
152
+ name: IDLE_SOCKET_NAME
153
+ });
154
+ const socket = await servedOrSpawned({
155
+ attempt: async () => {
156
+ const connection = net.connect(socketPath);
157
+ await once(connection, "connect");
158
+ return connection;
159
+ },
160
+ entry,
161
+ env: { [IDLE_WATCHER_ENV]: JSON.stringify({
162
+ idleMs: IDLE_MS,
163
+ socketPath
164
+ }) }
165
+ });
166
+ socket.on("error", noop);
167
+ const { promise: ready, reject, resolve } = Promise.withResolvers();
168
+ socket.once("data", () => {
169
+ resolve(null);
170
+ });
171
+ socket.once("close", () => {
172
+ reject(/* @__PURE__ */ new Error("The idle watcher stopped before it answered."));
173
+ });
174
+ socket.write(`${JSON.stringify({ origin })}\n`);
175
+ try {
176
+ await ready;
177
+ } catch (error) {
178
+ socket.destroy();
179
+ throw error;
180
+ }
181
+ return {
182
+ attach: (cluster) => {
183
+ socket.write(`${JSON.stringify(cluster)}\n`);
184
+ },
185
+ release: () => {
186
+ socket.end();
187
+ socket.unref();
188
+ }
189
+ };
190
+ };
191
+ // src/cli/commands/kubectl.ts
192
+ const SANDBOXES_FILE = "kubectl.json";
193
+ const KUBECONFIG_FOLDER = "kubeconfig";
194
+ const CONTEXT_NAME = "sandcovery";
195
+ const SLUGS = ["freestyle/2x4", "boxd/2x8"];
196
+ const START_TIMEOUT_SECONDS = 300;
197
+ const ANSWER_WAIT_MS = 12e4;
198
+ const ANSWER_POLL_MS = 1e3;
199
+ const ANSWER_REQUEST_MS = 1e4;
200
+ const UNWATCHED = "Can't stop the cluster after 15 idle minutes, so it runs until its TTL.";
201
+ const KUBECTL = process.platform === "win32" ? "kubectl.exe" : "kubectl";
202
+ const LOCAL_COMMANDS = /* @__PURE__ */ new Set([
203
+ "completion",
204
+ "config",
205
+ "help",
206
+ "kustomize",
207
+ "options",
208
+ "plugin"
209
+ ]);
210
+ const HELP_FLAGS = /* @__PURE__ */ new Set(["--help", "-h"]);
211
+ const CLIENT_FLAGS = /* @__PURE__ */ new Set(["--client", "--client=true"]);
212
+ const GLOBAL_VALUE_FLAGS = /* @__PURE__ */ new Set([
213
+ "--as",
214
+ "--as-group",
215
+ "--as-uid",
216
+ "--cache-dir",
217
+ "--certificate-authority",
218
+ "--client-certificate",
219
+ "--client-key",
220
+ "--cluster",
221
+ "--context",
222
+ "--kubeconfig",
223
+ "--log-flush-frequency",
224
+ "--namespace",
225
+ "--password",
226
+ "--profile",
227
+ "--profile-output",
228
+ "--request-timeout",
229
+ "--server",
230
+ "--tls-server-name",
231
+ "--token",
232
+ "--user",
233
+ "--username",
234
+ "--v",
235
+ "--vmodule",
236
+ "-n",
237
+ "-s",
238
+ "-v"
239
+ ]);
240
+ const READY_STATUSES = /* @__PURE__ */ new Set([200, 401]);
241
+ const FORWARDED_SIGNALS = /* @__PURE__ */ new Map([
242
+ [129, "SIGHUP"],
243
+ [130, "SIGINT"],
244
+ [143, "SIGTERM"]
245
+ ]);
246
+ const answers = async ({ deadline, tool, url }) => {
247
+ try {
248
+ const response = await fetch(url, {
249
+ redirect: "manual",
250
+ signal: AbortSignal.any([tool.signal, AbortSignal.timeout(ANSWER_REQUEST_MS)])
251
+ });
252
+ await response.body?.cancel();
253
+ if (READY_STATUSES.has(response.status)) return true;
254
+ } catch (error) {
255
+ if (tool.signal.aborted) throw error;
256
+ }
257
+ if (Date.now() + ANSWER_POLL_MS > deadline) return false;
258
+ await setTimeout$1(ANSWER_POLL_MS, null, { signal: tool.signal });
259
+ return await answers({
260
+ deadline,
261
+ tool,
262
+ url
263
+ });
264
+ };
265
+ const startCluster = async ({ kubeconfig, tool }) => {
266
+ const file = path.join(tool.folder, SANDBOXES_FILE);
267
+ const saved = fromUndefinedOr(savedSandboxes(file)[tool.origin]);
268
+ const running = await runningSandbox({
269
+ id: saved,
270
+ tool
271
+ });
272
+ if (isSome(running) && fs.existsSync(kubeconfig)) return running.value;
273
+ if (isSome(running)) await tool.client.sandboxes.destroy(running.value.id, { signal: tool.signal });
274
+ const sandbox = await tool.client.sandboxes.create({
275
+ disk_mib: null,
276
+ egress: null,
277
+ env: null,
278
+ gpu: null,
279
+ idle_timeout_seconds: null,
280
+ image: null,
281
+ os: null,
282
+ ports: [KUBERNETES_PORT],
283
+ provider: null,
284
+ region: null,
285
+ slug: null,
286
+ slugs: SLUGS,
287
+ snapshot_id: null,
288
+ ttl_seconds: null
289
+ }, {
290
+ idempotencyKey: v7(),
291
+ signal: tool.signal
292
+ });
293
+ const provider = sandbox.provider ?? "its provider";
294
+ try {
295
+ const start = await tool.client.sandboxes.exec(sandbox.id, {
296
+ command: KUBERNETES_COMMAND,
297
+ cwd: null,
298
+ env: null,
299
+ timeout_seconds: START_TIMEOUT_SECONDS
300
+ }, { signal: tool.signal });
301
+ const token = start.stdout.trim();
302
+ if (start.exit_code !== 0 || token === "" || token.includes("\n") || token.includes(" ")) throw new Error(`Can't run kubectl. Kubernetes didn't start in sandbox ${sandbox.id} on ${provider}, so Sandcovery destroyed it.`, { cause: start });
303
+ const gateway = await launchedRelay({
304
+ command: KUBERNETES_GATEWAY_COMMAND,
305
+ id: sandbox.id,
306
+ tool
307
+ });
308
+ if (gateway.code !== 0) throw new Error(`Can't run kubectl. The Sandcovery relay for the Kubernetes API didn't start in sandbox ${sandbox.id} on ${provider}, so Sandcovery destroyed it.`, { cause: gateway });
309
+ const preview = await tool.client.sandboxes.portPreview(sandbox.id, KUBERNETES_PORT, { signal: tool.signal });
310
+ const server = preview.url.endsWith("/") ? preview.url.slice(0, -1) : preview.url;
311
+ if (!await answers({
312
+ deadline: Date.now() + ANSWER_WAIT_MS,
313
+ tool,
314
+ url: `${server}/version`
315
+ })) throw new Error(`Can't run kubectl. The cluster in sandbox ${sandbox.id} on ${provider} didn't answer at ${server} within 2 minutes, so Sandcovery destroyed it.`);
316
+ writePrivateFile({
317
+ file: kubeconfig,
318
+ text: `${JSON.stringify({
319
+ apiVersion: "v1",
320
+ clusters: [{
321
+ cluster: { server },
322
+ name: CONTEXT_NAME
323
+ }],
324
+ contexts: [{
325
+ context: {
326
+ cluster: CONTEXT_NAME,
327
+ user: CONTEXT_NAME
328
+ },
329
+ name: CONTEXT_NAME
330
+ }],
331
+ "current-context": CONTEXT_NAME,
332
+ kind: "Config",
333
+ users: [{
334
+ name: CONTEXT_NAME,
335
+ user: { token }
336
+ }]
337
+ }, null, 2)}\n`
338
+ });
339
+ } catch (error) {
340
+ if (!tool.signal.aborted) await tool.client.sandboxes.destroy(sandbox.id, { signal: tool.signal });
341
+ throw error;
342
+ }
343
+ saveSandbox({
344
+ file,
345
+ id: sandbox.id,
346
+ origin: tool.origin
347
+ });
348
+ return sandbox;
349
+ };
350
+ const held = async (tool) => {
351
+ const { entry } = tool;
352
+ if (isNone(entry)) return none();
353
+ try {
354
+ return some(await holdCluster({
355
+ entry: entry.value,
356
+ folder: tool.folder,
357
+ origin: tool.origin
358
+ }));
359
+ } catch (error) {
360
+ if (!(error instanceof Error)) throw error;
361
+ tool.io.stderr.write(`${UNWATCHED} ${error.message}\n`);
362
+ return none();
363
+ }
364
+ };
365
+ const ran = async ({ kubeconfig, kubectl, tool }) => {
366
+ const { promise, reject, resolve } = Promise.withResolvers();
367
+ const child = spawn(kubectl, tool.args, {
368
+ env: {
369
+ ...process.env,
370
+ KUBECONFIG: kubeconfig
371
+ },
372
+ stdio: "inherit"
373
+ });
374
+ const forwarding = new AbortController();
375
+ child.once("error", reject);
376
+ child.once("close", (code, signal) => {
377
+ const signalled = match(fromNullOr(signal), {
378
+ onNone: () => 0,
379
+ onSome: (name) => os.constants.signals[name]
380
+ });
381
+ resolve(code ?? 128 + signalled);
382
+ });
383
+ tool.signal.addEventListener("abort", () => {
384
+ child.kill(FORWARDED_SIGNALS.get(tool.signal.reason) ?? "SIGTERM");
385
+ }, {
386
+ once: true,
387
+ signal: forwarding.signal
388
+ });
389
+ try {
390
+ return await promise;
391
+ } finally {
392
+ forwarding.abort();
393
+ }
394
+ };
395
+ const onPath = (name) => fromUndefinedOr((process.env.PATH ?? "").split(path.delimiter).flatMap((folder) => path.isAbsolute(folder) ? [path.join(folder, name)] : []).find((file) => {
396
+ const found = try_(() => {
397
+ fs.accessSync(file, fs.constants.X_OK);
398
+ return fs.statSync(file).isFile();
399
+ });
400
+ return isSuccess(found) && found.success;
401
+ }));
402
+ const kubectlRun = async (tool) => {
403
+ const kubectl = onPath(KUBECTL);
404
+ if (isNone(kubectl)) throw new Error("Can't run kubectl. It isn't on PATH.");
405
+ if (process.argv.slice(1, 2).some((own) => fs.realpathSync(kubectl.value) === fs.realpathSync(own))) throw new Error(`Can't run kubectl. ${kubectl.value} on PATH is sandcovery-kubectl itself.`);
406
+ const kubeconfig = path.join(tool.folder, KUBECONFIG_FOLDER, encodeURIComponent(tool.origin));
407
+ const end = tool.args.indexOf("--");
408
+ const words = end === -1 ? tool.args : tool.args.slice(0, end);
409
+ if (match(fromUndefinedOr(words.find((word, index) => !word.startsWith("-") && !GLOBAL_VALUE_FLAGS.has(words[index - 1] ?? ""))), {
410
+ onNone: () => true,
411
+ onSome: (command) => LOCAL_COMMANDS.has(command) || command === "version" && words.some((word) => CLIENT_FLAGS.has(word))
412
+ }) || words.some((word) => HELP_FLAGS.has(word))) return await ran({
413
+ kubeconfig,
414
+ kubectl: kubectl.value,
415
+ tool
416
+ });
417
+ const hold = await held(tool);
418
+ try {
419
+ const sandbox = await startCluster({
420
+ kubeconfig,
421
+ tool
422
+ });
423
+ const { key } = tool;
424
+ if (isSome(hold) && isSome(key)) hold.value.attach({
425
+ expires_at: sandbox.expires_at,
426
+ key: key.value,
427
+ sandbox: sandbox.id
428
+ });
429
+ return await ran({
430
+ kubeconfig,
431
+ kubectl: kubectl.value,
432
+ tool
433
+ });
434
+ } finally {
435
+ if (isSome(hold)) hold.value.release();
436
+ }
437
+ };
438
+ export { watchIdle as a, IDLE_WATCHER_ENV as i, kubectlRun as n, onPath as r, answers as t };