sandcovery 0.7.0 → 0.9.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.
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- export { t as Sandcovery } from "./src-gAv6vIvE.mjs";
1
+ export { t as Sandcovery } from "./src-DjOLw-ft.mjs";
@@ -1,6 +1,5 @@
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";
1
+ import { C as SandboxId, Ct as Number$1, Fa as isSuccess, Kt as fromJsonString, Mt as Struct, Ra as try_, Ut as decodeUnknownOption, Wt as decodeUnknownSync, Xa as exists, Za as filter, _o as some, ao as getOrElse, at as increment, ct as update, ho as none, io as fromUndefinedOr, jt as String, lo as isNone, mo as match, no as fromNullOr, nt as get, oo as getOrNull, ot as make, po as map, st as set, t as Sandcovery, tt as decrement, uo as isSome, vo as toArray } from "./src-DjOLw-ft.mjs";
2
+ import { C as clamp, _ as servedOrSpawned, b as KUBERNETES_GATEWAY_COMMAND, f as writePrivateFile, g as servedAt, h as isTerminal, i as launchedRelay, m as READY, n as savedSandboxes, o as DESTROY_TIMEOUT_MS, s as createdSandbox, t as runningSandbox, u as stopSignalOf, v as socketOf, w as noop, x as KUBERNETES_PORT, y as KUBERNETES_COMMAND } from "./saved-sandboxes-BMjkAVGx.mjs";
4
3
  import os from "node:os";
5
4
  import { spawn } from "node:child_process";
6
5
  import net from "node:net";
@@ -14,7 +13,6 @@ const IDLE_WATCHER_ENV = "__SANDCOVERY_KUBECTL_IDLE";
14
13
  const IDLE_SOCKET_NAME = "kubectl-idle";
15
14
  const IDLE_MS = 9e5;
16
15
  const HEARTBEAT_MS = 6e4;
17
- const DESTROY_TIMEOUT_MS = 3e4;
18
16
  const REFUSED_STATUSES = /* @__PURE__ */ new Set([
19
17
  400,
20
18
  401,
@@ -24,17 +22,29 @@ const REFUSED_STATUSES = /* @__PURE__ */ new Set([
24
22
  410,
25
23
  422
26
24
  ]);
25
+ const ClusterLine = Struct({
26
+ expires_at: String,
27
+ key: String,
28
+ sandbox: String
29
+ });
30
+ const trackedOf = ({ expires_at, key, sandbox }) => ({
31
+ expiresAt: Date.parse(expires_at),
32
+ key,
33
+ sandbox
34
+ });
35
+ const UNWATCHED$1 = {
36
+ cluster: none(),
37
+ destroying: none(),
38
+ due: 0,
39
+ holders: 0
40
+ };
27
41
  const decodeWatcher = decodeUnknownSync(fromJsonString(Struct({
28
42
  idleMs: Number$1,
29
43
  socketPath: String
30
44
  })));
31
45
  const decodeHold = decodeUnknownOption(fromJsonString(Struct({ origin: String })));
32
46
  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
- })));
47
+ const decodeCluster = decodeUnknownOption(fromJsonString(ClusterLine));
38
48
  const ended = async ({ cluster, origin }) => {
39
49
  try {
40
50
  await new Sandcovery({
@@ -48,74 +58,96 @@ const ended = async ({ cluster, origin }) => {
48
58
  }
49
59
  };
50
60
  const destroyed = async ({ entry, origin, settle }) => {
51
- const { cluster } = entry;
52
- if (cluster !== null && await ended({
53
- cluster,
61
+ const { cluster } = get(entry);
62
+ if (isSome(cluster) && await ended({
63
+ cluster: cluster.value,
54
64
  origin
55
- })) {
56
- if (entry.cluster?.sandbox === cluster.sandbox) entry.cluster = null;
57
- } else entry.due = Date.now() + HEARTBEAT_MS;
58
- entry.destroying = null;
65
+ })) update(entry, (watching) => ({
66
+ ...watching,
67
+ cluster: watching.cluster.pipe(filter(({ sandbox }) => sandbox !== cluster.value.sandbox)),
68
+ destroying: none()
69
+ }));
70
+ else update(entry, (watching) => ({
71
+ ...watching,
72
+ destroying: none(),
73
+ due: Date.now() + HEARTBEAT_MS
74
+ }));
59
75
  settle();
60
76
  };
61
77
  const watchIdle = async (config) => {
62
78
  const { idleMs, socketPath } = decodeWatcher(config);
63
79
  const watched = /* @__PURE__ */ new Map();
64
80
  const listener = net.createServer();
65
- const state = {
66
- connections: 0,
67
- timer: null
68
- };
81
+ const connections = make(0);
82
+ const timer = make(null);
69
83
  const check = () => {
70
84
  const now = Date.now();
71
- if (state.timer !== null) clearTimeout(state.timer);
85
+ const waiting = get(timer);
86
+ if (waiting !== null) clearTimeout(waiting);
72
87
  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
88
+ const current = get(entry);
89
+ const live = {
90
+ ...current,
91
+ cluster: current.cluster.pipe(filter(({ expiresAt }) => now < expiresAt))
92
+ };
93
+ set(entry, live);
94
+ if (isSome(live.cluster) && live.holders === 0 && isNone(live.destroying) && now >= live.due) set(entry, {
95
+ ...live,
96
+ destroying: some(destroyed({
97
+ entry,
98
+ origin,
99
+ settle: check
100
+ }))
78
101
  });
79
- if (entry.cluster === null && entry.holders === 0 && entry.destroying === null) watched.delete(origin);
102
+ const settled = get(entry);
103
+ if (isNone(settled.cluster) && settled.holders === 0 && isNone(settled.destroying)) watched.delete(origin);
80
104
  }
81
- if (state.connections === 0 && watched.size === 0) {
105
+ if (get(connections) === 0 && watched.size === 0) {
82
106
  listener.close();
83
107
  return;
84
108
  }
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));
109
+ const next = Math.min(now + HEARTBEAT_MS, ...[...watched.values()].flatMap((entry) => {
110
+ const { cluster, destroying, due, holders } = get(entry);
111
+ const dueAt = holders === 0 ? match(destroying, {
112
+ onNone: () => [due],
113
+ onSome: () => []
114
+ }) : [];
115
+ return toArray(cluster).flatMap(({ expiresAt }) => [expiresAt, ...dueAt]);
116
+ }));
117
+ set(timer, setTimeout(check, clamp(next - now, 0, HEARTBEAT_MS)));
87
118
  };
88
119
  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;
120
+ const entry = watched.get(origin) ?? make({
121
+ ...UNWATCHED$1,
122
+ due: Date.now() + idleMs
123
+ });
124
+ update(entry, (watching) => ({
125
+ ...watching,
126
+ holders: watching.holders + 1
127
+ }));
96
128
  watched.set(origin, entry);
97
- await entry.destroying;
129
+ await getOrNull(get(entry).destroying);
98
130
  connection.write(READY);
99
131
  return entry;
100
132
  };
101
133
  listener.on("connection", (connection) => {
102
- const hold = { entry: null };
134
+ const hold = make(null);
103
135
  const lines = readline.createInterface({ input: connection });
104
- state.connections += 1;
136
+ increment(connections);
105
137
  connection.on("error", noop);
106
138
  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)));
139
+ const holding = get(hold);
140
+ if (holding !== null) {
141
+ const entry = await holding;
142
+ const cluster = decodeCluster(line).pipe(map(trackedOf), filter(({ expiresAt }) => !Number.isNaN(expiresAt)));
114
143
  if (isNone(cluster)) {
115
144
  connection.destroy();
116
145
  return;
117
146
  }
118
- entry.cluster = cluster.value;
147
+ update(entry, (watching) => ({
148
+ ...watching,
149
+ cluster
150
+ }));
119
151
  return;
120
152
  }
121
153
  const asked = decodeHold(line);
@@ -123,16 +155,17 @@ const watchIdle = async (config) => {
123
155
  connection.destroy();
124
156
  return;
125
157
  }
126
- hold.entry = held(connection, asked.value.origin);
158
+ set(hold, held(connection, asked.value.origin));
127
159
  };
128
160
  const released = async () => {
129
- const entry = await hold.entry;
130
- state.connections -= 1;
161
+ const entry = await get(hold);
162
+ decrement(connections);
131
163
  lines.close();
132
- if (entry !== null) {
133
- entry.holders -= 1;
134
- entry.due = Date.now() + idleMs;
135
- }
164
+ if (entry !== null) update(entry, (watching) => ({
165
+ ...watching,
166
+ due: Date.now() + idleMs,
167
+ holders: watching.holders - 1
168
+ }));
136
169
  check();
137
170
  };
138
171
  lines.on("line", (line) => {
@@ -144,7 +177,7 @@ const watchIdle = async (config) => {
144
177
  });
145
178
  const serving = await servedAt(listener, socketPath);
146
179
  process.stdout.write(READY);
147
- if (serving) state.timer = setTimeout(check, HEARTBEAT_MS);
180
+ if (serving) set(timer, setTimeout(check, HEARTBEAT_MS));
148
181
  };
149
182
  const holdCluster = async ({ entry, folder, origin }) => {
150
183
  const socketPath = socketOf({
@@ -157,11 +190,11 @@ const holdCluster = async ({ entry, folder, origin }) => {
157
190
  await once(connection, "connect");
158
191
  return connection;
159
192
  },
160
- entry,
161
193
  env: { [IDLE_WATCHER_ENV]: JSON.stringify({
162
194
  idleMs: IDLE_MS,
163
195
  socketPath
164
- }) }
196
+ }) },
197
+ entry
165
198
  });
166
199
  socket.on("error", noop);
167
200
  const { promise: ready, reject, resolve } = Promise.withResolvers();
@@ -238,11 +271,6 @@ const GLOBAL_VALUE_FLAGS = /* @__PURE__ */ new Set([
238
271
  "-v"
239
272
  ]);
240
273
  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
274
  const answers = async ({ deadline, tool, url }) => {
247
275
  try {
248
276
  const response = await fetch(url, {
@@ -263,32 +291,36 @@ const answers = async ({ deadline, tool, url }) => {
263
291
  });
264
292
  };
265
293
  const startCluster = async ({ kubeconfig, tool }) => {
266
- const file = path.join(tool.folder, SANDBOXES_FILE);
267
- const saved = fromUndefinedOr(savedSandboxes(file)[tool.origin]);
294
+ const state = {
295
+ file: path.join(tool.folder, SANDBOXES_FILE),
296
+ schema: SandboxId
297
+ };
298
+ const saved = fromUndefinedOr(savedSandboxes(state)[tool.origin]);
268
299
  const running = await runningSandbox({
269
300
  id: saved,
270
301
  tool
271
302
  });
272
303
  if (isSome(running) && fs.existsSync(kubeconfig)) return running.value;
273
304
  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
305
+ const sandbox = await createdSandbox({
306
+ request: {
307
+ api_key_id: null,
308
+ disk_mib: null,
309
+ egress: null,
310
+ env: null,
311
+ gpu: null,
312
+ idle_timeout_seconds: null,
313
+ image: null,
314
+ os: null,
315
+ ports: [KUBERNETES_PORT],
316
+ provider: null,
317
+ region: null,
318
+ slug: null,
319
+ slugs: SLUGS,
320
+ snapshot_id: null,
321
+ ttl_seconds: null
322
+ },
323
+ tool
292
324
  });
293
325
  const provider = sandbox.provider ?? "its provider";
294
326
  try {
@@ -310,8 +342,8 @@ const startCluster = async ({ kubeconfig, tool }) => {
310
342
  const server = preview.url.endsWith("/") ? preview.url.slice(0, -1) : preview.url;
311
343
  if (!await answers({
312
344
  deadline: Date.now() + ANSWER_WAIT_MS,
313
- tool,
314
- url: `${server}/version`
345
+ url: `${server}/version`,
346
+ tool
315
347
  })) 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
348
  writePrivateFile({
317
349
  file: kubeconfig,
@@ -337,13 +369,15 @@ const startCluster = async ({ kubeconfig, tool }) => {
337
369
  }, null, 2)}\n`
338
370
  });
339
371
  } catch (error) {
340
- if (!tool.signal.aborted) await tool.client.sandboxes.destroy(sandbox.id, { signal: tool.signal });
372
+ await tool.client.sandboxes.destroy(sandbox.id, { signal: AbortSignal.timeout(DESTROY_TIMEOUT_MS) });
341
373
  throw error;
342
374
  }
343
- saveSandbox({
344
- file,
345
- id: sandbox.id,
346
- origin: tool.origin
375
+ writePrivateFile({
376
+ file: state.file,
377
+ text: `${JSON.stringify({
378
+ ...savedSandboxes(state),
379
+ [tool.origin]: sandbox.id
380
+ }, null, 2)}\n`
347
381
  });
348
382
  return sandbox;
349
383
  };
@@ -381,7 +415,7 @@ const ran = async ({ kubeconfig, kubectl, tool }) => {
381
415
  resolve(code ?? 128 + signalled);
382
416
  });
383
417
  tool.signal.addEventListener("abort", () => {
384
- child.kill(FORWARDED_SIGNALS.get(tool.signal.reason) ?? "SIGTERM");
418
+ child.kill(getOrElse(stopSignalOf(tool.signal), () => "SIGTERM"));
385
419
  }, {
386
420
  once: true,
387
421
  signal: forwarding.signal
@@ -408,11 +442,11 @@ const kubectlRun = async (tool) => {
408
442
  const words = end === -1 ? tool.args : tool.args.slice(0, end);
409
443
  if (match(fromUndefinedOr(words.find((word, index) => !word.startsWith("-") && !GLOBAL_VALUE_FLAGS.has(words[index - 1] ?? ""))), {
410
444
  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({
445
+ onSome: (command) => LOCAL_COMMANDS.has(command) || command === "version" && !CLIENT_FLAGS.isDisjointFrom(new Set(words))
446
+ }) || !HELP_FLAGS.isDisjointFrom(new Set(words))) return await ran({
413
447
  kubeconfig,
414
- kubectl: kubectl.value,
415
- tool
448
+ tool,
449
+ kubectl: kubectl.value
416
450
  });
417
451
  const hold = await held(tool);
418
452
  try {
@@ -428,8 +462,8 @@ const kubectlRun = async (tool) => {
428
462
  });
429
463
  return await ran({
430
464
  kubeconfig,
431
- kubectl: kubectl.value,
432
- tool
465
+ tool,
466
+ kubectl: kubectl.value
433
467
  });
434
468
  } finally {
435
469
  if (isSome(hold)) hold.value.release();