@beachside/upstash-box 0.0.0 → 0.20.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/README.md +28 -2
- package/dist/adapter.d.ts +258 -0
- package/dist/exec.d.ts +10 -0
- package/dist/files-shell.d.ts +15 -0
- package/dist/files.d.ts +52 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +2415 -0
- package/dist/process.d.ts +7 -0
- package/dist/regular.d.ts +14 -0
- package/dist/snapshots.d.ts +543 -0
- package/dist/transport.d.ts +15 -0
- package/package.json +38 -7
package/dist/index.js
ADDED
|
@@ -0,0 +1,2415 @@
|
|
|
1
|
+
// src/index.ts
|
|
2
|
+
import { bindAdapter } from "@beachside/adapter";
|
|
3
|
+
|
|
4
|
+
// src/adapter.ts
|
|
5
|
+
import { createHash as createHash2 } from "node:crypto";
|
|
6
|
+
import { z as z7 } from "zod";
|
|
7
|
+
import {
|
|
8
|
+
AdapterCheckpointError as AdapterCheckpointError3,
|
|
9
|
+
AdapterError as AdapterError8,
|
|
10
|
+
AllowNetworkSetting,
|
|
11
|
+
DEFAULT_LIFETIME_SECONDS,
|
|
12
|
+
listedLabels,
|
|
13
|
+
listedTime as listedTime2,
|
|
14
|
+
validateResourceReference as validateResourceReference2,
|
|
15
|
+
ResourceMinimums,
|
|
16
|
+
allowlistConfig,
|
|
17
|
+
allowlistFromCanonical,
|
|
18
|
+
assertResourceScope as assertResourceScope2,
|
|
19
|
+
defineAdapter,
|
|
20
|
+
networkPolicyName,
|
|
21
|
+
parseEgressAllowlist,
|
|
22
|
+
sandboxReference,
|
|
23
|
+
smallestSize,
|
|
24
|
+
throwAllowlistError,
|
|
25
|
+
unknownSandboxFacts
|
|
26
|
+
} from "@beachside/adapter";
|
|
27
|
+
|
|
28
|
+
// src/exec.ts
|
|
29
|
+
import WebSocket from "ws";
|
|
30
|
+
import { AdapterError as AdapterError2 } from "@beachside/adapter";
|
|
31
|
+
import { z as z2 } from "zod";
|
|
32
|
+
|
|
33
|
+
// src/transport.ts
|
|
34
|
+
import { AdapterError } from "@beachside/adapter";
|
|
35
|
+
import { z } from "zod";
|
|
36
|
+
var ORIGIN = "https://us-east-1.box.upstash.com";
|
|
37
|
+
var RANGE_BYTES = 8 * 1024 * 1024;
|
|
38
|
+
var JSON_BYTES = 12 * 1024 * 1024;
|
|
39
|
+
function nativeCode(status) {
|
|
40
|
+
switch (status) {
|
|
41
|
+
case 400:
|
|
42
|
+
case 422:
|
|
43
|
+
return "INVALID_ARGUMENT";
|
|
44
|
+
case 401:
|
|
45
|
+
return "UNAUTHENTICATED";
|
|
46
|
+
case 403:
|
|
47
|
+
return "FORBIDDEN";
|
|
48
|
+
case 404:
|
|
49
|
+
return "NOT_FOUND";
|
|
50
|
+
case 409:
|
|
51
|
+
return "CONFLICT";
|
|
52
|
+
case 429:
|
|
53
|
+
return "RATE_LIMIT";
|
|
54
|
+
default:
|
|
55
|
+
return "UNAVAILABLE";
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
class BoxHttpError extends AdapterError {
|
|
60
|
+
status;
|
|
61
|
+
constructor(status) {
|
|
62
|
+
super(nativeCode(status), `Upstash Box returned HTTP ${status}`);
|
|
63
|
+
this.status = status;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
function definitiveRefusal(error) {
|
|
67
|
+
return error instanceof BoxHttpError && [400, 401, 403, 404, 422, 429].includes(error.status);
|
|
68
|
+
}
|
|
69
|
+
var Base64 = z.base64();
|
|
70
|
+
function decodeBytes(value, max) {
|
|
71
|
+
const encodedLimit = Math.ceil(max / 3) * 4;
|
|
72
|
+
if (value.length > encodedLimit || !Base64.safeParse(value).success)
|
|
73
|
+
throw new AdapterError("UNAVAILABLE", "Upstash Box returned invalid or oversized base64");
|
|
74
|
+
const bytes = Buffer.from(value, "base64");
|
|
75
|
+
if (bytes.length > max || bytes.toString("base64") !== value)
|
|
76
|
+
throw new AdapterError("UNAVAILABLE", "Upstash Box returned invalid or oversized base64");
|
|
77
|
+
return bytes;
|
|
78
|
+
}
|
|
79
|
+
function createTransport(origin, apiKey, fetcher) {
|
|
80
|
+
async function request(path, signal, method = "GET", body) {
|
|
81
|
+
const response = await fetcher(origin + path, {
|
|
82
|
+
method,
|
|
83
|
+
signal,
|
|
84
|
+
redirect: "error",
|
|
85
|
+
headers: { "X-Box-Api-Key": apiKey, ...body && { "Content-Type": "application/json" } },
|
|
86
|
+
body: body && JSON.stringify(body)
|
|
87
|
+
});
|
|
88
|
+
if (!response.ok) {
|
|
89
|
+
await response.body?.cancel().catch(() => {
|
|
90
|
+
return;
|
|
91
|
+
});
|
|
92
|
+
throw new BoxHttpError(response.status);
|
|
93
|
+
}
|
|
94
|
+
return response;
|
|
95
|
+
}
|
|
96
|
+
async function json(path, signal, method, body) {
|
|
97
|
+
const response = await request(path, signal, method, body);
|
|
98
|
+
if (!response.body)
|
|
99
|
+
throw new AdapterError("UNAVAILABLE", "Upstash Box returned no JSON");
|
|
100
|
+
const chunks = [];
|
|
101
|
+
let bytes = 0;
|
|
102
|
+
const reader = response.body.getReader();
|
|
103
|
+
try {
|
|
104
|
+
for (;; ) {
|
|
105
|
+
const chunk = await reader.read();
|
|
106
|
+
if (chunk.done)
|
|
107
|
+
break;
|
|
108
|
+
bytes += chunk.value.byteLength;
|
|
109
|
+
if (bytes > JSON_BYTES) {
|
|
110
|
+
await reader.cancel().catch(() => {
|
|
111
|
+
return;
|
|
112
|
+
});
|
|
113
|
+
throw new AdapterError("UNAVAILABLE", "Upstash Box returned oversized JSON");
|
|
114
|
+
}
|
|
115
|
+
chunks.push(chunk.value);
|
|
116
|
+
}
|
|
117
|
+
} finally {
|
|
118
|
+
reader.releaseLock();
|
|
119
|
+
}
|
|
120
|
+
try {
|
|
121
|
+
const value = JSON.parse(Buffer.concat(chunks, bytes).toString("utf8"));
|
|
122
|
+
return value;
|
|
123
|
+
} catch {
|
|
124
|
+
throw new AdapterError("UNAVAILABLE", "Upstash Box returned invalid JSON");
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
async function empty(path, signal, method, body) {
|
|
128
|
+
const response = await request(path, signal, method, body);
|
|
129
|
+
await response.body?.cancel().catch(() => {
|
|
130
|
+
return;
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
return { json, empty };
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// src/exec.ts
|
|
137
|
+
var MAX_OUTPUT_BYTES = 1024 * 1024;
|
|
138
|
+
var CHUNK_BYTES = 64 * 1024;
|
|
139
|
+
var FRAME_BYTES = 2 * 1024 * 1024;
|
|
140
|
+
var ServerFrame = z2.discriminatedUnion("type", [
|
|
141
|
+
z2.object({ type: z2.literal("started"), pid: z2.number().int().positive() }),
|
|
142
|
+
z2.object({ type: z2.literal("stdout"), data: z2.string() }),
|
|
143
|
+
z2.object({ type: z2.literal("stderr"), data: z2.string() }),
|
|
144
|
+
z2.object({ type: z2.literal("exit"), code: z2.number().int().safe() }),
|
|
145
|
+
z2.object({ type: z2.literal("error") })
|
|
146
|
+
]);
|
|
147
|
+
|
|
148
|
+
class ExecLoss extends Error {
|
|
149
|
+
output;
|
|
150
|
+
constructor(output) {
|
|
151
|
+
super("Upstash Box did not confirm command completion");
|
|
152
|
+
this.output = output;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
function createExec(origin, apiKey) {
|
|
156
|
+
const sockets = new Set;
|
|
157
|
+
const url = origin.replace(/^https:/, "wss:").replace(/^http:/, "ws:");
|
|
158
|
+
function close() {
|
|
159
|
+
for (const socket of sockets)
|
|
160
|
+
socket.terminate();
|
|
161
|
+
}
|
|
162
|
+
function exec(input, signal) {
|
|
163
|
+
return new Promise((resolve, reject) => {
|
|
164
|
+
if (signal.aborted) {
|
|
165
|
+
reject(new AdapterError2("TIMEOUT", "Upstash Box command was not started"));
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
const path = `/v2/box/${encodeURIComponent(input.sandbox.id)}/exec-session`;
|
|
169
|
+
const socket = new WebSocket(url + path, {
|
|
170
|
+
headers: { "X-Box-Api-Key": apiKey },
|
|
171
|
+
followRedirects: false,
|
|
172
|
+
maxPayload: FRAME_BYTES,
|
|
173
|
+
perMessageDeflate: false
|
|
174
|
+
});
|
|
175
|
+
sockets.add(socket);
|
|
176
|
+
const stdout = [];
|
|
177
|
+
const stderr = [];
|
|
178
|
+
let sent = false;
|
|
179
|
+
let started = false;
|
|
180
|
+
let settled = false;
|
|
181
|
+
let captured = 0;
|
|
182
|
+
let truncated = false;
|
|
183
|
+
const max = input.maxOutputBytes;
|
|
184
|
+
function result(exitCode) {
|
|
185
|
+
return {
|
|
186
|
+
exitCode,
|
|
187
|
+
stdout: Buffer.concat(stdout),
|
|
188
|
+
stderr: Buffer.concat(stderr),
|
|
189
|
+
truncated
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
function finish(value) {
|
|
193
|
+
if (settled)
|
|
194
|
+
return;
|
|
195
|
+
settled = true;
|
|
196
|
+
clearTimeout(timer);
|
|
197
|
+
signal.removeEventListener("abort", stop);
|
|
198
|
+
if (value instanceof Error)
|
|
199
|
+
reject(value);
|
|
200
|
+
else
|
|
201
|
+
resolve(value);
|
|
202
|
+
if (socket.readyState === WebSocket.OPEN)
|
|
203
|
+
socket.close();
|
|
204
|
+
else if (socket.readyState === WebSocket.CONNECTING)
|
|
205
|
+
socket.terminate();
|
|
206
|
+
}
|
|
207
|
+
function loss() {
|
|
208
|
+
finish(sent ? new ExecLoss(result(null)) : new AdapterError2("UNAVAILABLE", "Upstash Box could not start a live session"));
|
|
209
|
+
}
|
|
210
|
+
function stop() {
|
|
211
|
+
if (sent && socket.readyState === WebSocket.OPEN) {
|
|
212
|
+
socket.send(JSON.stringify({ type: "terminate" }), () => {
|
|
213
|
+
return;
|
|
214
|
+
});
|
|
215
|
+
}
|
|
216
|
+
loss();
|
|
217
|
+
}
|
|
218
|
+
function send(frame, callback) {
|
|
219
|
+
socket.send(JSON.stringify(frame), (error) => {
|
|
220
|
+
if (error)
|
|
221
|
+
loss();
|
|
222
|
+
else if (!settled)
|
|
223
|
+
callback?.();
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
let offset = 0;
|
|
227
|
+
function sendInput() {
|
|
228
|
+
const bytes = input.stdin;
|
|
229
|
+
if (!bytes || offset === bytes.length) {
|
|
230
|
+
send({ type: "stdin_close" });
|
|
231
|
+
return;
|
|
232
|
+
}
|
|
233
|
+
const chunk = bytes.subarray(offset, offset + CHUNK_BYTES);
|
|
234
|
+
offset += chunk.length;
|
|
235
|
+
send({ type: "stdin", data: Buffer.from(chunk).toString("base64") }, sendInput);
|
|
236
|
+
}
|
|
237
|
+
const timer = setTimeout(stop, Math.min(input.deadlineSeconds * 1000, 2147483647));
|
|
238
|
+
signal.addEventListener("abort", stop, { once: true });
|
|
239
|
+
socket.once("close", () => {
|
|
240
|
+
sockets.delete(socket);
|
|
241
|
+
loss();
|
|
242
|
+
});
|
|
243
|
+
socket.on("error", loss);
|
|
244
|
+
socket.once("unexpected-response", (_request, response) => {
|
|
245
|
+
response.resume();
|
|
246
|
+
finish(new BoxHttpError(response.statusCode ?? 500));
|
|
247
|
+
});
|
|
248
|
+
socket.once("open", () => {
|
|
249
|
+
const command = input.command.kind === "argv" ? { argv: input.command.argv } : { cmd: input.command.script };
|
|
250
|
+
const cwd = input.cwd ?? "/workspace/home";
|
|
251
|
+
sent = true;
|
|
252
|
+
send({
|
|
253
|
+
type: "start",
|
|
254
|
+
...command,
|
|
255
|
+
cwd: cwd.startsWith("/") ? cwd : `/workspace/home/${cwd}`,
|
|
256
|
+
env: input.env && Object.entries(input.env).map(([key, value]) => `${key}=${value}`)
|
|
257
|
+
});
|
|
258
|
+
});
|
|
259
|
+
socket.on("message", (raw, binary) => {
|
|
260
|
+
if (settled)
|
|
261
|
+
return;
|
|
262
|
+
try {
|
|
263
|
+
if (binary || !Buffer.isBuffer(raw))
|
|
264
|
+
return loss();
|
|
265
|
+
const frame = ServerFrame.parse(JSON.parse(raw.toString("utf8")));
|
|
266
|
+
switch (frame.type) {
|
|
267
|
+
case "started":
|
|
268
|
+
if (started)
|
|
269
|
+
return loss();
|
|
270
|
+
started = true;
|
|
271
|
+
sendInput();
|
|
272
|
+
break;
|
|
273
|
+
case "stdout":
|
|
274
|
+
case "stderr": {
|
|
275
|
+
if (!started)
|
|
276
|
+
return loss();
|
|
277
|
+
const bytes = decodeBytes(frame.data, FRAME_BYTES);
|
|
278
|
+
const keep = Math.min(bytes.length, max - captured);
|
|
279
|
+
if (keep > 0) {
|
|
280
|
+
const stream = frame.type === "stdout" ? stdout : stderr;
|
|
281
|
+
stream.push(Buffer.from(bytes.subarray(0, keep)));
|
|
282
|
+
captured += keep;
|
|
283
|
+
}
|
|
284
|
+
truncated ||= keep < bytes.length;
|
|
285
|
+
break;
|
|
286
|
+
}
|
|
287
|
+
case "exit":
|
|
288
|
+
if (!started)
|
|
289
|
+
return loss();
|
|
290
|
+
finish(result(frame.code));
|
|
291
|
+
break;
|
|
292
|
+
case "error":
|
|
293
|
+
loss();
|
|
294
|
+
break;
|
|
295
|
+
}
|
|
296
|
+
} catch {
|
|
297
|
+
loss();
|
|
298
|
+
}
|
|
299
|
+
});
|
|
300
|
+
});
|
|
301
|
+
}
|
|
302
|
+
return { exec, close };
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
// src/files.ts
|
|
306
|
+
import {
|
|
307
|
+
AdapterError as AdapterError4,
|
|
308
|
+
AdapterFilesystemError as AdapterFilesystemError2,
|
|
309
|
+
MAX_DIRECTORY_ENTRIES,
|
|
310
|
+
MAX_DIRECTORY_NAME_BYTES
|
|
311
|
+
} from "@beachside/adapter";
|
|
312
|
+
import { z as z3 } from "zod";
|
|
313
|
+
|
|
314
|
+
// src/files-shell.ts
|
|
315
|
+
import {
|
|
316
|
+
AdapterError as AdapterError3,
|
|
317
|
+
AdapterFilesystemError
|
|
318
|
+
} from "@beachside/adapter";
|
|
319
|
+
var MAKE_STAGE = 'mkdir -m 700 -- "$1"';
|
|
320
|
+
var REMOVE_STAGE = 'rm -rf -- "$1"';
|
|
321
|
+
var APPEND_STAGE = 'cat -- "$1/chunk" >> "$1/data"';
|
|
322
|
+
var COPY_STAGE = 'cp -P -- "$1" "$2/data" && [ ! -L "$2/data" ] && [ -f "$2/data" ]';
|
|
323
|
+
var LINK_STAGE = `
|
|
324
|
+
if ln -T -- "$1/data" "$2"; then exit 0; fi
|
|
325
|
+
if [ -e "$2" ] || [ -L "$2" ]; then exit 73; fi
|
|
326
|
+
exit 74
|
|
327
|
+
`;
|
|
328
|
+
var REMOVE_EMPTY_DIRECTORY = 'rmdir -- "$1"';
|
|
329
|
+
async function guest(run, sandbox, script, args, signal) {
|
|
330
|
+
signal.throwIfAborted();
|
|
331
|
+
return (await run({
|
|
332
|
+
sandbox,
|
|
333
|
+
command: { kind: "argv", argv: ["/bin/sh", "-c", script, "beachside", ...args] },
|
|
334
|
+
deadlineSeconds: 30,
|
|
335
|
+
maxOutputBytes: 1024
|
|
336
|
+
}, signal)).exitCode;
|
|
337
|
+
}
|
|
338
|
+
async function stagedFile(run, input, ctx, fill, publish) {
|
|
339
|
+
const parent = input.destination.slice(0, input.destination.lastIndexOf("/") + 1);
|
|
340
|
+
const stage = `${parent}.beachside-${crypto.randomUUID()}`;
|
|
341
|
+
ctx.signal.throwIfAborted();
|
|
342
|
+
ctx.retain?.({ temporaryPaths: [stage] });
|
|
343
|
+
let stageExit;
|
|
344
|
+
try {
|
|
345
|
+
stageExit = await guest(run, input.sandbox, MAKE_STAGE, [stage], ctx.signal);
|
|
346
|
+
} catch (error) {
|
|
347
|
+
if (error instanceof AdapterError3) {
|
|
348
|
+
ctx.retain?.({ temporaryPaths: [] });
|
|
349
|
+
throw error;
|
|
350
|
+
}
|
|
351
|
+
stageExit = null;
|
|
352
|
+
}
|
|
353
|
+
if (stageExit === null)
|
|
354
|
+
throw new AdapterFilesystemError("UNAVAILABLE", "Upstash Box did not acknowledge staging creation", {
|
|
355
|
+
effect: "none",
|
|
356
|
+
source: input.source,
|
|
357
|
+
destination: input.destination,
|
|
358
|
+
temporaryPaths: [stage]
|
|
359
|
+
});
|
|
360
|
+
if (stageExit !== 0) {
|
|
361
|
+
ctx.retain?.({ temporaryPaths: [] });
|
|
362
|
+
throw new AdapterError3("UNAVAILABLE", "Upstash Box could not create staging");
|
|
363
|
+
}
|
|
364
|
+
let publishing = false;
|
|
365
|
+
let published = false;
|
|
366
|
+
let failed = false;
|
|
367
|
+
let failure;
|
|
368
|
+
try {
|
|
369
|
+
await fill(stage);
|
|
370
|
+
ctx.signal.throwIfAborted();
|
|
371
|
+
publishing = true;
|
|
372
|
+
await publish(stage);
|
|
373
|
+
published = true;
|
|
374
|
+
ctx.retain?.({ effect: "applied" });
|
|
375
|
+
} catch (error) {
|
|
376
|
+
failure = error;
|
|
377
|
+
failed = true;
|
|
378
|
+
}
|
|
379
|
+
const uncertainPublish = failed && publishing && !(failure instanceof AdapterError3);
|
|
380
|
+
let removed = false;
|
|
381
|
+
if (!uncertainPublish) {
|
|
382
|
+
try {
|
|
383
|
+
removed = await guest(run, input.sandbox, REMOVE_STAGE, [stage], AbortSignal.timeout(5000)) === 0;
|
|
384
|
+
} catch {}
|
|
385
|
+
}
|
|
386
|
+
if (removed) {
|
|
387
|
+
ctx.retain?.({ temporaryPaths: [] });
|
|
388
|
+
if (failed)
|
|
389
|
+
throw failure;
|
|
390
|
+
return;
|
|
391
|
+
}
|
|
392
|
+
const confirmedFailure = failure instanceof AdapterError3 ? failure : undefined;
|
|
393
|
+
const code = confirmedFailure?.code ?? "UNAVAILABLE";
|
|
394
|
+
const message = confirmedFailure ? confirmedFailure.message : published ? "Upstash Box published the file but did not confirm staging cleanup" : "Upstash Box could not confirm the filesystem operation";
|
|
395
|
+
throw new AdapterFilesystemError(code, message, {
|
|
396
|
+
effect: published ? "applied" : uncertainPublish ? "unknown" : "none",
|
|
397
|
+
source: input.source,
|
|
398
|
+
destination: input.destination,
|
|
399
|
+
temporaryPaths: [stage]
|
|
400
|
+
});
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
// src/files.ts
|
|
404
|
+
var MAX_FILE_BYTES = 1024 * 1024;
|
|
405
|
+
var StageName = /^\.beachside-[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
|
|
406
|
+
var NativeStat = z3.object({
|
|
407
|
+
type: z3.enum(["file", "directory", "symlink", "other"]),
|
|
408
|
+
size: z3.number().int().nonnegative().safe().optional(),
|
|
409
|
+
mod_time: z3.iso.datetime({ offset: true }).optional(),
|
|
410
|
+
version: z3.string().min(1).optional()
|
|
411
|
+
});
|
|
412
|
+
var NativeName = z3.string().min(1).max(4096).refine((name) => name !== "." && name !== ".." && !name.includes("/") && !name.includes("\x00"));
|
|
413
|
+
var NativeDirectory = z3.object({
|
|
414
|
+
files: z3.array(z3.object({ name: NativeName })).nullable()
|
|
415
|
+
});
|
|
416
|
+
var Content = z3.object({ content: z3.string() });
|
|
417
|
+
function boxPath(id) {
|
|
418
|
+
return `/v2/box/${encodeURIComponent(id)}`;
|
|
419
|
+
}
|
|
420
|
+
function portableType(type) {
|
|
421
|
+
return type === "other" ? "unknown" : type;
|
|
422
|
+
}
|
|
423
|
+
function missing(error) {
|
|
424
|
+
return error instanceof BoxHttpError && error.status === 404;
|
|
425
|
+
}
|
|
426
|
+
function boxFiles(transport, run, identify, guardGuest) {
|
|
427
|
+
const query = ({ sandbox, path }) => ({
|
|
428
|
+
prefix: `${boxPath(identify(sandbox))}/files`,
|
|
429
|
+
path: encodeURIComponent(path)
|
|
430
|
+
});
|
|
431
|
+
async function guestRejection(sandbox, ctx) {
|
|
432
|
+
try {
|
|
433
|
+
await guardGuest?.(sandbox, ctx.signal);
|
|
434
|
+
} catch (error) {
|
|
435
|
+
return error instanceof AdapterError4 ? ctx.reject(error.code, error.message) : ctx.reject("UNAVAILABLE", "Upstash Box guest readiness could not be checked");
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
async function nativeStat(input, signal, follow) {
|
|
439
|
+
const { prefix, path } = query(input);
|
|
440
|
+
const result = NativeStat.safeParse(await transport.json(`${prefix}/stat?path=${path}${follow ? "&follow=true" : ""}`, signal));
|
|
441
|
+
if (!result.success)
|
|
442
|
+
throw new AdapterError4("UNAVAILABLE", "Upstash Box returned invalid file metadata");
|
|
443
|
+
return result.data;
|
|
444
|
+
}
|
|
445
|
+
async function maybeStat(input, signal, follow = false) {
|
|
446
|
+
try {
|
|
447
|
+
return await nativeStat(input, signal, follow);
|
|
448
|
+
} catch (error) {
|
|
449
|
+
if (error instanceof Error && missing(error))
|
|
450
|
+
return null;
|
|
451
|
+
throw error;
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
async function requireDestinationParent(input, signal) {
|
|
455
|
+
const path = input.path.slice(0, input.path.lastIndexOf("/")) || "/";
|
|
456
|
+
const parent = await nativeStat({ sandbox: input.sandbox, path }, signal, true);
|
|
457
|
+
if (parent.type !== "directory")
|
|
458
|
+
throw new AdapterError4("NOT_FOUND", "The destination parent is not a directory");
|
|
459
|
+
}
|
|
460
|
+
async function regular(input, signal) {
|
|
461
|
+
const file = await nativeStat(input, signal, true);
|
|
462
|
+
if (file.type !== "file")
|
|
463
|
+
throw new AdapterError4("INVALID_ARGUMENT", "The path is not a regular file");
|
|
464
|
+
if (file.size === undefined || file.version === undefined)
|
|
465
|
+
throw new AdapterError4("UNAVAILABLE", "Upstash Box did not report file size and version");
|
|
466
|
+
return { size: file.size, version: file.version };
|
|
467
|
+
}
|
|
468
|
+
async function range(input, offset, length, signal) {
|
|
469
|
+
const { prefix, path } = query(input);
|
|
470
|
+
const result = Content.safeParse(await transport.json(`${prefix}/read?path=${path}&encoding=base64&offset=${offset}&length=${length}`, signal));
|
|
471
|
+
if (!result.success)
|
|
472
|
+
throw new AdapterError4("UNAVAILABLE", "Upstash Box returned invalid file data");
|
|
473
|
+
const bytes = decodeBytes(result.data.content, length);
|
|
474
|
+
if (bytes.length !== length)
|
|
475
|
+
throw new AdapterError4("CONFLICT", "Upstash Box file changed during reading");
|
|
476
|
+
return bytes;
|
|
477
|
+
}
|
|
478
|
+
async function verify(input, file, signal) {
|
|
479
|
+
const latest = await regular(input, signal);
|
|
480
|
+
if (latest.version !== file.version || latest.size !== file.size)
|
|
481
|
+
throw new AdapterError4("CONFLICT", "Upstash Box file changed during reading");
|
|
482
|
+
}
|
|
483
|
+
async function list(input, { signal }) {
|
|
484
|
+
await guardGuest?.(input.sandbox, signal);
|
|
485
|
+
const { prefix, path } = query(input);
|
|
486
|
+
const directory = await nativeStat(input, signal, true);
|
|
487
|
+
if (directory.type !== "directory")
|
|
488
|
+
throw new AdapterError4("INVALID_ARGUMENT", "The path is not a directory");
|
|
489
|
+
const result = NativeDirectory.safeParse(await transport.json(`${prefix}/list?folder=${path}`, signal));
|
|
490
|
+
if (!result.success)
|
|
491
|
+
throw new AdapterError4("UNAVAILABLE", "Upstash Box returned invalid directory data");
|
|
492
|
+
const names = (result.data.files ?? []).map(({ name }) => name).sort();
|
|
493
|
+
if (names.length > MAX_DIRECTORY_ENTRIES || names.reduce((total, name) => total + Buffer.byteLength(name), 0) > MAX_DIRECTORY_NAME_BYTES)
|
|
494
|
+
throw new AdapterError4("CAPACITY", "Upstash Box directory exceeds the listing bound");
|
|
495
|
+
if (new Set(names).size !== names.length)
|
|
496
|
+
throw new AdapterError4("UNAVAILABLE", "Upstash Box returned duplicate directory entries");
|
|
497
|
+
const entries = [];
|
|
498
|
+
const parent = input.path.endsWith("/") ? input.path : `${input.path}/`;
|
|
499
|
+
for (let index = 0;index < names.length; index += 16) {
|
|
500
|
+
const batch = names.slice(index, index + 16);
|
|
501
|
+
entries.push(...await Promise.all(batch.map(async (name) => {
|
|
502
|
+
const item = await maybeStat({ sandbox: input.sandbox, path: parent + name }, signal);
|
|
503
|
+
return { name, type: item ? portableType(item.type) : "unknown" };
|
|
504
|
+
})));
|
|
505
|
+
}
|
|
506
|
+
return entries;
|
|
507
|
+
}
|
|
508
|
+
async function writeNative(input, bytes, signal) {
|
|
509
|
+
await transport.empty(`${boxPath(identify(input.sandbox))}/files/write`, signal, "POST", {
|
|
510
|
+
path: input.path,
|
|
511
|
+
encoding: "base64",
|
|
512
|
+
content: Buffer.from(bytes).toString("base64")
|
|
513
|
+
});
|
|
514
|
+
}
|
|
515
|
+
async function rename(sandbox, from, to, signal) {
|
|
516
|
+
await transport.empty(`${boxPath(identify(sandbox))}/files/rename`, signal, "POST", {
|
|
517
|
+
from,
|
|
518
|
+
to
|
|
519
|
+
});
|
|
520
|
+
}
|
|
521
|
+
async function publish(sandbox, stage, destination, overwrite, signal) {
|
|
522
|
+
if (overwrite) {
|
|
523
|
+
try {
|
|
524
|
+
await rename(sandbox, `${stage}/data`, destination, signal);
|
|
525
|
+
} catch (error) {
|
|
526
|
+
if (definitiveRefusal(error))
|
|
527
|
+
throw error;
|
|
528
|
+
throw new Error("Upstash Box did not acknowledge file publication");
|
|
529
|
+
}
|
|
530
|
+
return;
|
|
531
|
+
}
|
|
532
|
+
const exit = await guest(run, sandbox, LINK_STAGE, [stage, destination], signal);
|
|
533
|
+
if (exit === 73)
|
|
534
|
+
throw new AdapterError4("CONFLICT", "Upstash Box file already exists");
|
|
535
|
+
if (exit === 74)
|
|
536
|
+
throw new AdapterError4("UNSUPPORTED", "Upstash Box could not publish with exclusive hard linking");
|
|
537
|
+
if (exit !== 0)
|
|
538
|
+
throw new Error("Upstash Box did not acknowledge exclusive file publication");
|
|
539
|
+
}
|
|
540
|
+
async function writeStream(input, ctx) {
|
|
541
|
+
identify(input.sandbox);
|
|
542
|
+
if (input.path === "/" || input.path.endsWith("/"))
|
|
543
|
+
throw new AdapterError4("INVALID_ARGUMENT", "A file write requires a filename");
|
|
544
|
+
await requireDestinationParent(input, ctx.signal);
|
|
545
|
+
let bytesWritten = 0;
|
|
546
|
+
await stagedFile(run, { sandbox: input.sandbox, destination: input.path }, ctx, async (stage) => {
|
|
547
|
+
const data = { sandbox: input.sandbox, path: `${stage}/data` };
|
|
548
|
+
const chunk = { sandbox: input.sandbox, path: `${stage}/chunk` };
|
|
549
|
+
await writeNative(data, new Uint8Array, ctx.signal);
|
|
550
|
+
const buffer = new Uint8Array(MAX_FILE_BYTES);
|
|
551
|
+
let buffered = 0;
|
|
552
|
+
async function flush() {
|
|
553
|
+
await writeNative(chunk, buffer.subarray(0, buffered), ctx.signal);
|
|
554
|
+
if (await guest(run, input.sandbox, APPEND_STAGE, [stage], ctx.signal) !== 0)
|
|
555
|
+
throw new AdapterError4("UNAVAILABLE", "Upstash Box did not confirm the staged file chunk");
|
|
556
|
+
bytesWritten += buffered;
|
|
557
|
+
buffered = 0;
|
|
558
|
+
ctx.retain?.({ bytesTransferred: bytesWritten });
|
|
559
|
+
}
|
|
560
|
+
for await (const bytes of input.bytes) {
|
|
561
|
+
for (let offset = 0;offset < bytes.length; ) {
|
|
562
|
+
const count = Math.min(bytes.length - offset, buffer.length - buffered);
|
|
563
|
+
buffer.set(bytes.subarray(offset, offset + count), buffered);
|
|
564
|
+
buffered += count;
|
|
565
|
+
offset += count;
|
|
566
|
+
if (buffered === buffer.length)
|
|
567
|
+
await flush();
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
if (buffered)
|
|
571
|
+
await flush();
|
|
572
|
+
const staged = await nativeStat(data, ctx.signal, false);
|
|
573
|
+
if (staged.type !== "file" || staged.size !== bytesWritten)
|
|
574
|
+
throw new AdapterError4("UNAVAILABLE", "Upstash Box staged file length differs from the input");
|
|
575
|
+
}, (stage) => publish(input.sandbox, stage, input.path, input.overwrite, ctx.signal));
|
|
576
|
+
return { bytesWritten };
|
|
577
|
+
}
|
|
578
|
+
return {
|
|
579
|
+
maxBytes: MAX_FILE_BYTES,
|
|
580
|
+
async read(input, { signal }) {
|
|
581
|
+
await guardGuest?.(input.sandbox, signal);
|
|
582
|
+
const file = await regular(input, signal);
|
|
583
|
+
const length = Math.min(file.size, (input.maxBytes ?? MAX_FILE_BYTES) + 1, MAX_FILE_BYTES + 1);
|
|
584
|
+
const bytes = length === 0 ? new Uint8Array : await range(input, 0, length, signal);
|
|
585
|
+
await verify(input, file, signal);
|
|
586
|
+
return bytes;
|
|
587
|
+
},
|
|
588
|
+
async readStream(input, { signal }) {
|
|
589
|
+
await guardGuest?.(input.sandbox, signal);
|
|
590
|
+
const controller = new AbortController;
|
|
591
|
+
const active = AbortSignal.any([signal, controller.signal]);
|
|
592
|
+
const file = await regular(input, active);
|
|
593
|
+
let offset = 0;
|
|
594
|
+
return new ReadableStream({
|
|
595
|
+
async pull(stream) {
|
|
596
|
+
if (offset === file.size) {
|
|
597
|
+
await verify(input, file, active);
|
|
598
|
+
stream.close();
|
|
599
|
+
return;
|
|
600
|
+
}
|
|
601
|
+
const length = Math.min(RANGE_BYTES, file.size - offset);
|
|
602
|
+
const bytes = await range(input, offset, length, active);
|
|
603
|
+
offset += bytes.length;
|
|
604
|
+
stream.enqueue(bytes);
|
|
605
|
+
},
|
|
606
|
+
cancel() {
|
|
607
|
+
controller.abort();
|
|
608
|
+
}
|
|
609
|
+
}, { highWaterMark: 0 });
|
|
610
|
+
},
|
|
611
|
+
list,
|
|
612
|
+
async readDirectory(input, ctx) {
|
|
613
|
+
return {
|
|
614
|
+
entries: await list(input, ctx),
|
|
615
|
+
completeness: "complete",
|
|
616
|
+
observedAt: new Date().toISOString()
|
|
617
|
+
};
|
|
618
|
+
},
|
|
619
|
+
async stat(input, { signal }) {
|
|
620
|
+
await guardGuest?.(input.sandbox, signal);
|
|
621
|
+
const file = await nativeStat(input, signal, input.followSymlinks);
|
|
622
|
+
return {
|
|
623
|
+
type: portableType(file.type),
|
|
624
|
+
...file.size !== undefined && { sizeBytes: file.size },
|
|
625
|
+
...file.mod_time && { modifiedAt: file.mod_time }
|
|
626
|
+
};
|
|
627
|
+
},
|
|
628
|
+
async exists(input, { signal }) {
|
|
629
|
+
await guardGuest?.(input.sandbox, signal);
|
|
630
|
+
return await maybeStat(input, signal) !== null;
|
|
631
|
+
},
|
|
632
|
+
makeDirectory: {
|
|
633
|
+
async prepare(input, { signal }) {
|
|
634
|
+
await guardGuest?.(input.sandbox, signal);
|
|
635
|
+
const existing = await maybeStat(input, signal, true);
|
|
636
|
+
if (existing && existing.type !== "directory")
|
|
637
|
+
throw new AdapterError4("INVALID_ARGUMENT", "The directory path is occupied by a non-directory entry");
|
|
638
|
+
return input;
|
|
639
|
+
},
|
|
640
|
+
async submit(input, ctx) {
|
|
641
|
+
const { sandbox, path, recursive } = input;
|
|
642
|
+
const id = identify(sandbox);
|
|
643
|
+
const rejected = await guestRejection(sandbox, ctx);
|
|
644
|
+
if (rejected)
|
|
645
|
+
return rejected;
|
|
646
|
+
try {
|
|
647
|
+
await transport.empty(`${boxPath(id)}/files/mkdir`, ctx.signal, "POST", {
|
|
648
|
+
path,
|
|
649
|
+
parents: recursive
|
|
650
|
+
});
|
|
651
|
+
} catch (error) {
|
|
652
|
+
if (!(error instanceof BoxHttpError) || ![400, 404, 409, 422].includes(error.status)) {
|
|
653
|
+
if (definitiveRefusal(error))
|
|
654
|
+
return ctx.reject(error.code, error.message);
|
|
655
|
+
return ctx.unknown("Upstash Box did not acknowledge directory creation");
|
|
656
|
+
}
|
|
657
|
+
const existing = await maybeStat(input, ctx.signal, true).catch(() => null);
|
|
658
|
+
if (existing?.type !== "directory")
|
|
659
|
+
return ctx.reject(error.code, error.message);
|
|
660
|
+
}
|
|
661
|
+
return { acknowledged: true };
|
|
662
|
+
}
|
|
663
|
+
},
|
|
664
|
+
async remove(input, ctx) {
|
|
665
|
+
const { sandbox, path, recursive } = input;
|
|
666
|
+
const id = identify(sandbox);
|
|
667
|
+
if (path === "/")
|
|
668
|
+
return ctx.reject("INVALID_ARGUMENT", "Cannot remove the filesystem root");
|
|
669
|
+
const rejected = await guestRejection(sandbox, ctx);
|
|
670
|
+
if (rejected)
|
|
671
|
+
return rejected;
|
|
672
|
+
try {
|
|
673
|
+
const file = await maybeStat(input, ctx.signal);
|
|
674
|
+
if (!file)
|
|
675
|
+
return { acknowledged: true };
|
|
676
|
+
if (!recursive && file.type === "directory") {
|
|
677
|
+
const exit = await guest(run, sandbox, REMOVE_EMPTY_DIRECTORY, [path], ctx.signal);
|
|
678
|
+
if (exit === null)
|
|
679
|
+
return ctx.unknown("Upstash Box did not acknowledge directory removal");
|
|
680
|
+
if (exit !== 0 && await maybeStat(input, ctx.signal))
|
|
681
|
+
return ctx.reject("CONFLICT", "Upstash Box could not remove the directory without recursion");
|
|
682
|
+
} else {
|
|
683
|
+
await transport.empty(`${boxPath(id)}/files/remove`, ctx.signal, "POST", {
|
|
684
|
+
path,
|
|
685
|
+
recursive
|
|
686
|
+
});
|
|
687
|
+
}
|
|
688
|
+
} catch (error) {
|
|
689
|
+
if (definitiveRefusal(error) && error.status !== 404)
|
|
690
|
+
return ctx.reject(error.code, error.message);
|
|
691
|
+
if (!(error instanceof Error && missing(error)))
|
|
692
|
+
return ctx.unknown("Upstash Box did not acknowledge file removal");
|
|
693
|
+
}
|
|
694
|
+
return { acknowledged: true };
|
|
695
|
+
},
|
|
696
|
+
async write(input, ctx) {
|
|
697
|
+
identify(input.sandbox);
|
|
698
|
+
if (input.path === "/" || input.path.endsWith("/"))
|
|
699
|
+
return ctx.reject("INVALID_ARGUMENT", "A file write requires a filename");
|
|
700
|
+
if (input.bytes.byteLength > MAX_FILE_BYTES)
|
|
701
|
+
return ctx.reject("CAPACITY", "Upstash Box write exceeds the buffered limit");
|
|
702
|
+
const rejected = await guestRejection(input.sandbox, ctx);
|
|
703
|
+
if (rejected)
|
|
704
|
+
return rejected;
|
|
705
|
+
try {
|
|
706
|
+
if (input.overwrite) {
|
|
707
|
+
await requireDestinationParent(input, ctx.signal);
|
|
708
|
+
await writeNative(input, input.bytes, ctx.signal);
|
|
709
|
+
} else {
|
|
710
|
+
const bytes = input.bytes;
|
|
711
|
+
await writeStream({
|
|
712
|
+
...input,
|
|
713
|
+
bytes: async function* () {
|
|
714
|
+
yield bytes;
|
|
715
|
+
}()
|
|
716
|
+
}, {
|
|
717
|
+
signal: ctx.signal,
|
|
718
|
+
deadline: Date.now() + 30000
|
|
719
|
+
});
|
|
720
|
+
}
|
|
721
|
+
return { bytesWritten: input.bytes.byteLength };
|
|
722
|
+
} catch (error) {
|
|
723
|
+
if (error instanceof AdapterFilesystemError2) {
|
|
724
|
+
if (error.details.effect === "applied")
|
|
725
|
+
return { bytesWritten: input.bytes.byteLength };
|
|
726
|
+
const path = error.details.temporaryPaths?.[0];
|
|
727
|
+
const stage = path?.slice(path.lastIndexOf("/") + 1);
|
|
728
|
+
if (stage && StageName.test(stage))
|
|
729
|
+
return ctx.unknown(`Upstash Box could not confirm the file write; staging directory ${stage} may remain beside the destination`);
|
|
730
|
+
}
|
|
731
|
+
if (definitiveRefusal(error) || error instanceof AdapterError4 && !(error instanceof AdapterFilesystemError2) && [
|
|
732
|
+
"INVALID_ARGUMENT",
|
|
733
|
+
"NOT_FOUND",
|
|
734
|
+
"CONFLICT",
|
|
735
|
+
"UNSUPPORTED",
|
|
736
|
+
"UNAUTHENTICATED",
|
|
737
|
+
"FORBIDDEN"
|
|
738
|
+
].includes(error.code))
|
|
739
|
+
return ctx.reject(error.code, error.message);
|
|
740
|
+
return ctx.unknown("Upstash Box could not confirm the file write");
|
|
741
|
+
}
|
|
742
|
+
},
|
|
743
|
+
async writeStream(input, ctx) {
|
|
744
|
+
await guardGuest?.(input.sandbox, ctx.signal);
|
|
745
|
+
return writeStream(input, ctx);
|
|
746
|
+
},
|
|
747
|
+
async copy(input, ctx) {
|
|
748
|
+
await guardGuest?.(input.sandbox, ctx.signal);
|
|
749
|
+
const source = await nativeStat({ sandbox: input.sandbox, path: input.source }, ctx.signal, false);
|
|
750
|
+
if (source.type !== "file")
|
|
751
|
+
throw new AdapterError4("INVALID_ARGUMENT", "Only regular files can be copied");
|
|
752
|
+
await requireDestinationParent({ sandbox: input.sandbox, path: input.destination }, ctx.signal);
|
|
753
|
+
await stagedFile(run, input, ctx, async (stage) => {
|
|
754
|
+
const exit = await guest(run, input.sandbox, COPY_STAGE, [input.source, stage], ctx.signal);
|
|
755
|
+
if (exit !== 0)
|
|
756
|
+
throw new AdapterError4("CONFLICT", "Upstash Box could not copy the regular source file");
|
|
757
|
+
}, (stage) => publish(input.sandbox, stage, input.destination, input.overwrite, ctx.signal));
|
|
758
|
+
return { acknowledged: true };
|
|
759
|
+
},
|
|
760
|
+
async move(input, ctx) {
|
|
761
|
+
identify(input.sandbox);
|
|
762
|
+
if (!input.overwrite)
|
|
763
|
+
throw new AdapterError4("UNSUPPORTED", "Upstash Box has no atomic no-clobber rename");
|
|
764
|
+
await guardGuest?.(input.sandbox, ctx.signal);
|
|
765
|
+
try {
|
|
766
|
+
await rename(input.sandbox, input.source, input.destination, ctx.signal);
|
|
767
|
+
} catch (error) {
|
|
768
|
+
if (definitiveRefusal(error))
|
|
769
|
+
throw error;
|
|
770
|
+
throw new AdapterFilesystemError2("UNAVAILABLE", "Upstash Box did not acknowledge the rename", {
|
|
771
|
+
effect: "unknown",
|
|
772
|
+
source: input.source,
|
|
773
|
+
destination: input.destination
|
|
774
|
+
});
|
|
775
|
+
}
|
|
776
|
+
return { acknowledged: true };
|
|
777
|
+
}
|
|
778
|
+
};
|
|
779
|
+
}
|
|
780
|
+
|
|
781
|
+
// src/process.ts
|
|
782
|
+
import { Socket } from "node:net";
|
|
783
|
+
import { setImmediate as yieldOutput } from "node:timers/promises";
|
|
784
|
+
import WebSocket2 from "ws";
|
|
785
|
+
import { z as z4 } from "zod";
|
|
786
|
+
import {
|
|
787
|
+
AdapterError as AdapterError5
|
|
788
|
+
} from "@beachside/adapter";
|
|
789
|
+
var FRAME_BYTES2 = 2 * 1024 * 1024;
|
|
790
|
+
var PENDING_BYTES = 2 * FRAME_BYTES2;
|
|
791
|
+
var DELIVERY_BYTES = 16384;
|
|
792
|
+
var INPUT_BYTES = 65536;
|
|
793
|
+
var OUTGOING_BYTES = 262144;
|
|
794
|
+
var Frame = z4.discriminatedUnion("type", [
|
|
795
|
+
z4.object({ type: z4.literal("started"), pid: z4.number().int().positive() }),
|
|
796
|
+
z4.object({ type: z4.literal("stdout"), data: z4.string() }),
|
|
797
|
+
z4.object({ type: z4.literal("stderr"), data: z4.string() }),
|
|
798
|
+
z4.object({ type: z4.literal("exit"), code: z4.number().int().safe() }),
|
|
799
|
+
z4.object({ type: z4.literal("error") })
|
|
800
|
+
]);
|
|
801
|
+
var NativeSocket = z4.object({ _socket: z4.instanceof(Socket) });
|
|
802
|
+
function deferred() {
|
|
803
|
+
let resolve;
|
|
804
|
+
let reject;
|
|
805
|
+
const promise = new Promise((accept, fail) => {
|
|
806
|
+
resolve = accept;
|
|
807
|
+
reject = fail;
|
|
808
|
+
});
|
|
809
|
+
promise.catch(() => {
|
|
810
|
+
return;
|
|
811
|
+
});
|
|
812
|
+
return { promise, resolve, reject };
|
|
813
|
+
}
|
|
814
|
+
function createProcesses(origin, apiKey) {
|
|
815
|
+
const sessions = new Set;
|
|
816
|
+
const url = origin.replace(/^http/, "ws");
|
|
817
|
+
async function start(input, ctx) {
|
|
818
|
+
const setup = { deadline: ctx.deadline, signal: ctx.signal };
|
|
819
|
+
const remaining = setup.deadline - Date.now();
|
|
820
|
+
const byteOutput = input.output?.format === "bytes";
|
|
821
|
+
let onBytes = ctx.onOutputBytes;
|
|
822
|
+
let onText = ctx.onOutput;
|
|
823
|
+
const captureLimit = input.capture?.maxBytes;
|
|
824
|
+
if (byteOutput && !onBytes)
|
|
825
|
+
throw new AdapterError5("UNSUPPORTED", "Upstash Box byte output needs a byte consumer");
|
|
826
|
+
if (captureLimit !== undefined && (!Number.isSafeInteger(captureLimit) || captureLimit < 0 || captureLimit > MAX_OUTPUT_BYTES))
|
|
827
|
+
throw new AdapterError5("CAPACITY", "Upstash Box process capture is outside its byte limit");
|
|
828
|
+
if (setup.signal.aborted || remaining <= 0)
|
|
829
|
+
throw new AdapterError5("TIMEOUT", "Upstash Box process start expired before dispatch");
|
|
830
|
+
const path = `/v2/box/${encodeURIComponent(input.sandbox.id)}/exec-session`;
|
|
831
|
+
const socket = new WebSocket2(url + path, {
|
|
832
|
+
headers: { "X-Box-Api-Key": apiKey },
|
|
833
|
+
followRedirects: false,
|
|
834
|
+
maxPayload: FRAME_BYTES2,
|
|
835
|
+
perMessageDeflate: false,
|
|
836
|
+
allowSynchronousEvents: false
|
|
837
|
+
});
|
|
838
|
+
const started = deferred();
|
|
839
|
+
const exited = deferred();
|
|
840
|
+
const output = deferred();
|
|
841
|
+
const capture = captureLimit === undefined ? undefined : deferred();
|
|
842
|
+
let captured = capture && {
|
|
843
|
+
stdout: Buffer.alloc(captureLimit ?? 0),
|
|
844
|
+
stderr: Buffer.alloc(captureLimit ?? 0)
|
|
845
|
+
};
|
|
846
|
+
const lengths = { stdout: 0, stderr: 0 };
|
|
847
|
+
const decoders = { stdout: new TextDecoder, stderr: new TextDecoder };
|
|
848
|
+
const queue = [];
|
|
849
|
+
let pendingBytes = 0;
|
|
850
|
+
let delivering = false;
|
|
851
|
+
let observing = true;
|
|
852
|
+
let truncated = false;
|
|
853
|
+
let dispatched = false;
|
|
854
|
+
let acknowledged = false;
|
|
855
|
+
let observedAt = new Date().toISOString();
|
|
856
|
+
let finished = false;
|
|
857
|
+
let detached = false;
|
|
858
|
+
let confirmedExit;
|
|
859
|
+
let inputClosed = !input.terminal && input.stdin !== "pipe";
|
|
860
|
+
let inputInFlight = false;
|
|
861
|
+
let inputUncertain = false;
|
|
862
|
+
function stopOutput(error) {
|
|
863
|
+
if (!observing)
|
|
864
|
+
return;
|
|
865
|
+
observing = false;
|
|
866
|
+
onBytes = undefined;
|
|
867
|
+
onText = undefined;
|
|
868
|
+
queue.length = 0;
|
|
869
|
+
pendingBytes = 0;
|
|
870
|
+
socket.resume();
|
|
871
|
+
output.reject(error);
|
|
872
|
+
}
|
|
873
|
+
function stopStartWait() {
|
|
874
|
+
clearTimeout(timer);
|
|
875
|
+
setup.signal.removeEventListener("abort", cancelStart);
|
|
876
|
+
}
|
|
877
|
+
function failed(error) {
|
|
878
|
+
if (finished)
|
|
879
|
+
return;
|
|
880
|
+
finished = true;
|
|
881
|
+
stopStartWait();
|
|
882
|
+
started.reject(error);
|
|
883
|
+
exited.reject(error);
|
|
884
|
+
capture?.reject(error);
|
|
885
|
+
stopOutput(error);
|
|
886
|
+
socket.terminate();
|
|
887
|
+
}
|
|
888
|
+
function abandon(error) {
|
|
889
|
+
if (detached)
|
|
890
|
+
return;
|
|
891
|
+
detached = true;
|
|
892
|
+
stopStartWait();
|
|
893
|
+
stopOutput(error);
|
|
894
|
+
started.reject(error);
|
|
895
|
+
exited.reject(error);
|
|
896
|
+
capture?.reject(error);
|
|
897
|
+
captured = undefined;
|
|
898
|
+
if (!dispatched)
|
|
899
|
+
failed(error);
|
|
900
|
+
else if (!finished) {
|
|
901
|
+
const connection = NativeSocket.safeParse(socket);
|
|
902
|
+
if (connection.success)
|
|
903
|
+
connection.data._socket.unref();
|
|
904
|
+
}
|
|
905
|
+
}
|
|
906
|
+
function detach() {
|
|
907
|
+
abandon(new AdapterError5("UNAVAILABLE", "Upstash Box process was detached"));
|
|
908
|
+
}
|
|
909
|
+
function cancelStart() {
|
|
910
|
+
abandon(new AdapterError5("TIMEOUT", "Upstash Box did not acknowledge process start in time"));
|
|
911
|
+
}
|
|
912
|
+
function checkControl(context) {
|
|
913
|
+
if (context.signal.aborted || context.deadline <= Date.now())
|
|
914
|
+
throw new AdapterError5("TIMEOUT", "Upstash Box process input or control expired");
|
|
915
|
+
if (finished || detached || socket.readyState !== WebSocket2.OPEN)
|
|
916
|
+
throw new AdapterError5("UNAVAILABLE", "Upstash Box process connection is closed");
|
|
917
|
+
if (socket.bufferedAmount > OUTGOING_BYTES)
|
|
918
|
+
throw new AdapterError5("CAPACITY", "Upstash Box process send buffer is full");
|
|
919
|
+
}
|
|
920
|
+
async function send(frame, context) {
|
|
921
|
+
checkControl(context);
|
|
922
|
+
return new Promise((resolve, reject) => {
|
|
923
|
+
const complete = (error) => {
|
|
924
|
+
clearTimeout(timeout);
|
|
925
|
+
context.signal.removeEventListener("abort", abort);
|
|
926
|
+
if (error)
|
|
927
|
+
reject(error);
|
|
928
|
+
else
|
|
929
|
+
resolve();
|
|
930
|
+
};
|
|
931
|
+
const abort = () => complete(new AdapterError5("TIMEOUT", "Upstash Box process send was not confirmed"));
|
|
932
|
+
const timeout = setTimeout(abort, Math.max(0, context.deadline - Date.now()));
|
|
933
|
+
context.signal.addEventListener("abort", abort, { once: true });
|
|
934
|
+
const failedSend = () => new AdapterError5("UNAVAILABLE", "Upstash Box process send failed");
|
|
935
|
+
try {
|
|
936
|
+
socket.send(JSON.stringify(frame), (error) => complete(error ? failedSend() : undefined));
|
|
937
|
+
} catch {
|
|
938
|
+
complete(failedSend());
|
|
939
|
+
}
|
|
940
|
+
});
|
|
941
|
+
}
|
|
942
|
+
function checkInput(context) {
|
|
943
|
+
checkControl(context);
|
|
944
|
+
if (inputClosed || inputUncertain)
|
|
945
|
+
throw new AdapterError5("CONFLICT", "Upstash Box process input is closed or uncertain");
|
|
946
|
+
if (inputInFlight)
|
|
947
|
+
throw new AdapterError5("CAPACITY", "Upstash Box process already has input pending");
|
|
948
|
+
}
|
|
949
|
+
async function sendInput(frame, context) {
|
|
950
|
+
checkInput(context);
|
|
951
|
+
inputInFlight = true;
|
|
952
|
+
try {
|
|
953
|
+
await send(frame, context);
|
|
954
|
+
if (frame.type === "stdin_close")
|
|
955
|
+
inputClosed = true;
|
|
956
|
+
} catch (error) {
|
|
957
|
+
inputUncertain = true;
|
|
958
|
+
throw error;
|
|
959
|
+
} finally {
|
|
960
|
+
inputInFlight = false;
|
|
961
|
+
}
|
|
962
|
+
}
|
|
963
|
+
const handle = {
|
|
964
|
+
get confirmedExit() {
|
|
965
|
+
return confirmedExit;
|
|
966
|
+
},
|
|
967
|
+
outputDone: output.promise,
|
|
968
|
+
capture: capture?.promise,
|
|
969
|
+
wait: () => exited.promise,
|
|
970
|
+
async status() {
|
|
971
|
+
if (confirmedExit)
|
|
972
|
+
return { state: "exited", exit: confirmedExit, observedAt };
|
|
973
|
+
return {
|
|
974
|
+
state: acknowledged && !finished && !detached && socket.readyState === WebSocket2.OPEN ? "running" : "unknown",
|
|
975
|
+
observedAt
|
|
976
|
+
};
|
|
977
|
+
},
|
|
978
|
+
async detach() {
|
|
979
|
+
detach();
|
|
980
|
+
},
|
|
981
|
+
async detachOutput() {
|
|
982
|
+
stopOutput(new AdapterError5("UNAVAILABLE", "Upstash Box process output was detached"));
|
|
983
|
+
},
|
|
984
|
+
async signal(signal, context) {
|
|
985
|
+
if (signal !== "SIGTERM" && signal !== "SIGKILL")
|
|
986
|
+
throw new AdapterError5("INVALID_ARGUMENT", "Invalid Upstash Box process signal");
|
|
987
|
+
if (confirmedExit)
|
|
988
|
+
return { status: "not-found" };
|
|
989
|
+
await send({ type: "signal", signal: signal === "SIGTERM" ? "TERM" : "KILL" }, context);
|
|
990
|
+
return { status: "requested" };
|
|
991
|
+
},
|
|
992
|
+
...!inputClosed && {
|
|
993
|
+
async write(bytes, context) {
|
|
994
|
+
if (bytes.length > INPUT_BYTES)
|
|
995
|
+
throw new AdapterError5("CAPACITY", "Upstash Box process write exceeds 64 KiB");
|
|
996
|
+
if (!bytes.length) {
|
|
997
|
+
checkInput(context);
|
|
998
|
+
return;
|
|
999
|
+
}
|
|
1000
|
+
await sendInput({ type: "stdin", data: Buffer.from(bytes).toString("base64") }, context);
|
|
1001
|
+
}
|
|
1002
|
+
},
|
|
1003
|
+
...!input.terminal && !inputClosed && {
|
|
1004
|
+
async closeStdin(context) {
|
|
1005
|
+
if (!inputClosed)
|
|
1006
|
+
await sendInput({ type: "stdin_close" }, context);
|
|
1007
|
+
}
|
|
1008
|
+
},
|
|
1009
|
+
...input.terminal && {
|
|
1010
|
+
async resize({ rows, columns }, context) {
|
|
1011
|
+
await send({ type: "resize", rows, cols: columns }, context);
|
|
1012
|
+
}
|
|
1013
|
+
}
|
|
1014
|
+
};
|
|
1015
|
+
async function deliver() {
|
|
1016
|
+
if (delivering || !observing)
|
|
1017
|
+
return;
|
|
1018
|
+
delivering = true;
|
|
1019
|
+
try {
|
|
1020
|
+
while (observing && queue.length) {
|
|
1021
|
+
const next = queue[0];
|
|
1022
|
+
for (let offset = 0;observing && offset < next.bytes.length; offset += DELIVERY_BYTES) {
|
|
1023
|
+
const bytes = next.bytes.subarray(offset, offset + DELIVERY_BYTES);
|
|
1024
|
+
if (byteOutput && onBytes)
|
|
1025
|
+
onBytes({ stream: next.stream, bytes: Uint8Array.from(bytes) });
|
|
1026
|
+
else {
|
|
1027
|
+
const value = decoders[next.stream].decode(bytes, { stream: true });
|
|
1028
|
+
if (value)
|
|
1029
|
+
onText?.({ stream: next.stream, text: value });
|
|
1030
|
+
}
|
|
1031
|
+
await yieldOutput();
|
|
1032
|
+
}
|
|
1033
|
+
if (!observing)
|
|
1034
|
+
return;
|
|
1035
|
+
queue.shift();
|
|
1036
|
+
pendingBytes -= next.bytes.length;
|
|
1037
|
+
if (socket.isPaused && pendingBytes < FRAME_BYTES2)
|
|
1038
|
+
socket.resume();
|
|
1039
|
+
}
|
|
1040
|
+
if (confirmedExit && observing) {
|
|
1041
|
+
if (!byteOutput)
|
|
1042
|
+
for (const stream of ["stdout", "stderr"]) {
|
|
1043
|
+
const text = decoders[stream].decode();
|
|
1044
|
+
if (text)
|
|
1045
|
+
onText?.({ stream, text });
|
|
1046
|
+
}
|
|
1047
|
+
observing = false;
|
|
1048
|
+
onBytes = undefined;
|
|
1049
|
+
onText = undefined;
|
|
1050
|
+
output.resolve();
|
|
1051
|
+
}
|
|
1052
|
+
} catch (error) {
|
|
1053
|
+
stopOutput(error instanceof Error ? error : new AdapterError5("UNAVAILABLE", "Upstash Box output consumer failed"));
|
|
1054
|
+
} finally {
|
|
1055
|
+
delivering = false;
|
|
1056
|
+
}
|
|
1057
|
+
}
|
|
1058
|
+
function receive(stream, data) {
|
|
1059
|
+
if (!acknowledged)
|
|
1060
|
+
throw new AdapterError5("UNAVAILABLE", "Upstash Box output preceded start");
|
|
1061
|
+
if (!observing && !captured)
|
|
1062
|
+
return;
|
|
1063
|
+
const bytes = decodeBytes(data, FRAME_BYTES2);
|
|
1064
|
+
const channel = input.terminal ? "stdout" : stream;
|
|
1065
|
+
if (captured && captureLimit !== undefined) {
|
|
1066
|
+
const count = Math.min(bytes.length, captureLimit - lengths.stdout - lengths.stderr);
|
|
1067
|
+
bytes.copy(captured[channel], lengths[channel], 0, count);
|
|
1068
|
+
lengths[channel] += count;
|
|
1069
|
+
truncated ||= count < bytes.length;
|
|
1070
|
+
}
|
|
1071
|
+
if (!observing || !bytes.length)
|
|
1072
|
+
return;
|
|
1073
|
+
if (pendingBytes + bytes.length > PENDING_BYTES || queue.length >= 256) {
|
|
1074
|
+
stopOutput(new AdapterError5("CAPACITY", "Upstash Box process output buffer is full"));
|
|
1075
|
+
return;
|
|
1076
|
+
}
|
|
1077
|
+
queue.push({ stream: channel, bytes });
|
|
1078
|
+
pendingBytes += bytes.length;
|
|
1079
|
+
if (pendingBytes >= FRAME_BYTES2)
|
|
1080
|
+
socket.pause();
|
|
1081
|
+
deliver();
|
|
1082
|
+
}
|
|
1083
|
+
function confirmExit(code) {
|
|
1084
|
+
if (!acknowledged)
|
|
1085
|
+
throw new AdapterError5("UNAVAILABLE", "Upstash Box exit preceded start");
|
|
1086
|
+
finished = true;
|
|
1087
|
+
stopStartWait();
|
|
1088
|
+
if (detached) {
|
|
1089
|
+
socket.close();
|
|
1090
|
+
return;
|
|
1091
|
+
}
|
|
1092
|
+
confirmedExit = { exitCode: code };
|
|
1093
|
+
observedAt = new Date().toISOString();
|
|
1094
|
+
started.resolve(handle);
|
|
1095
|
+
exited.resolve(confirmedExit);
|
|
1096
|
+
if (captured)
|
|
1097
|
+
capture?.resolve({
|
|
1098
|
+
exitCode: code,
|
|
1099
|
+
stdout: captured.stdout.subarray(0, lengths.stdout),
|
|
1100
|
+
stderr: captured.stderr.subarray(0, lengths.stderr),
|
|
1101
|
+
truncated
|
|
1102
|
+
});
|
|
1103
|
+
socket.resume();
|
|
1104
|
+
socket.close();
|
|
1105
|
+
deliver();
|
|
1106
|
+
}
|
|
1107
|
+
const timer = setTimeout(cancelStart, remaining);
|
|
1108
|
+
setup.signal.addEventListener("abort", cancelStart, { once: true });
|
|
1109
|
+
sessions.add(detach);
|
|
1110
|
+
socket.once("close", () => {
|
|
1111
|
+
sessions.delete(detach);
|
|
1112
|
+
failed(new AdapterError5("UNAVAILABLE", "Upstash Box process closed without exit evidence"));
|
|
1113
|
+
});
|
|
1114
|
+
socket.on("error", () => failed(new AdapterError5("UNAVAILABLE", "Upstash Box process connection failed")));
|
|
1115
|
+
socket.once("unexpected-response", (_request, response) => {
|
|
1116
|
+
response.resume();
|
|
1117
|
+
failed(new BoxHttpError(response.statusCode ?? 500));
|
|
1118
|
+
});
|
|
1119
|
+
socket.once("open", () => {
|
|
1120
|
+
if (finished)
|
|
1121
|
+
return;
|
|
1122
|
+
const cwd = input.cwd ?? "/workspace/home";
|
|
1123
|
+
const command = input.command.kind === "argv" ? { argv: input.command.argv } : { cmd: input.command.script };
|
|
1124
|
+
const frame = {
|
|
1125
|
+
type: "start",
|
|
1126
|
+
...command,
|
|
1127
|
+
cwd: cwd.startsWith("/") ? cwd : `/workspace/home/${cwd}`,
|
|
1128
|
+
env: input.env && Object.entries(input.env).map(([key, value]) => `${key}=${value}`),
|
|
1129
|
+
...input.terminal && {
|
|
1130
|
+
tty: true,
|
|
1131
|
+
rows: input.terminal.rows,
|
|
1132
|
+
cols: input.terminal.columns
|
|
1133
|
+
}
|
|
1134
|
+
};
|
|
1135
|
+
dispatched = true;
|
|
1136
|
+
socket.send(JSON.stringify(frame), (error) => {
|
|
1137
|
+
if (error)
|
|
1138
|
+
failed(new AdapterError5("UNAVAILABLE", "Upstash Box process start send failed"));
|
|
1139
|
+
});
|
|
1140
|
+
});
|
|
1141
|
+
socket.on("message", (raw, binary) => {
|
|
1142
|
+
if (finished)
|
|
1143
|
+
return;
|
|
1144
|
+
try {
|
|
1145
|
+
if (binary || !Buffer.isBuffer(raw))
|
|
1146
|
+
throw new Error("Invalid Upstash Box process frame");
|
|
1147
|
+
const frame = Frame.parse(JSON.parse(raw.toString("utf8")));
|
|
1148
|
+
if (detached && frame.type !== "started" && frame.type !== "exit")
|
|
1149
|
+
return;
|
|
1150
|
+
switch (frame.type) {
|
|
1151
|
+
case "started": {
|
|
1152
|
+
if (acknowledged)
|
|
1153
|
+
throw new Error("Duplicate Upstash Box process start");
|
|
1154
|
+
acknowledged = true;
|
|
1155
|
+
observedAt = new Date().toISOString();
|
|
1156
|
+
if (detached) {
|
|
1157
|
+
if (inputClosed)
|
|
1158
|
+
socket.send(JSON.stringify({ type: "stdin_close" }), () => {
|
|
1159
|
+
return;
|
|
1160
|
+
});
|
|
1161
|
+
break;
|
|
1162
|
+
}
|
|
1163
|
+
const ready = () => {
|
|
1164
|
+
stopStartWait();
|
|
1165
|
+
started.resolve(handle);
|
|
1166
|
+
};
|
|
1167
|
+
if (inputClosed)
|
|
1168
|
+
send({ type: "stdin_close" }, setup).then(ready, (error) => {
|
|
1169
|
+
if (!detached)
|
|
1170
|
+
failed(error);
|
|
1171
|
+
});
|
|
1172
|
+
else
|
|
1173
|
+
ready();
|
|
1174
|
+
break;
|
|
1175
|
+
}
|
|
1176
|
+
case "stdout":
|
|
1177
|
+
case "stderr":
|
|
1178
|
+
receive(frame.type, frame.data);
|
|
1179
|
+
observedAt = new Date().toISOString();
|
|
1180
|
+
break;
|
|
1181
|
+
case "exit":
|
|
1182
|
+
confirmExit(frame.code);
|
|
1183
|
+
break;
|
|
1184
|
+
case "error":
|
|
1185
|
+
failed(new AdapterError5("UNAVAILABLE", "Upstash Box process reported an error"));
|
|
1186
|
+
break;
|
|
1187
|
+
}
|
|
1188
|
+
} catch {
|
|
1189
|
+
if (!detached)
|
|
1190
|
+
failed(new AdapterError5("UNAVAILABLE", "Upstash Box returned an invalid process frame"));
|
|
1191
|
+
}
|
|
1192
|
+
});
|
|
1193
|
+
return started.promise;
|
|
1194
|
+
}
|
|
1195
|
+
return {
|
|
1196
|
+
processes: {
|
|
1197
|
+
supports: {
|
|
1198
|
+
status: true,
|
|
1199
|
+
sustainedOutput: true,
|
|
1200
|
+
binaryOutput: true,
|
|
1201
|
+
signals: ["SIGTERM", "SIGKILL"],
|
|
1202
|
+
terminal: true,
|
|
1203
|
+
stdin: "bytes",
|
|
1204
|
+
execCapture: "bytes"
|
|
1205
|
+
},
|
|
1206
|
+
start
|
|
1207
|
+
},
|
|
1208
|
+
close() {
|
|
1209
|
+
for (const detach of sessions)
|
|
1210
|
+
detach();
|
|
1211
|
+
}
|
|
1212
|
+
};
|
|
1213
|
+
}
|
|
1214
|
+
|
|
1215
|
+
// src/snapshots.ts
|
|
1216
|
+
import { createHash } from "node:crypto";
|
|
1217
|
+
import {
|
|
1218
|
+
AdapterCheckpointError,
|
|
1219
|
+
AdapterError as AdapterError6,
|
|
1220
|
+
Preserve,
|
|
1221
|
+
assertResourceScope,
|
|
1222
|
+
listedTime,
|
|
1223
|
+
resolveSnapshot,
|
|
1224
|
+
validateResourceReference
|
|
1225
|
+
} from "@beachside/adapter";
|
|
1226
|
+
import { z as z5 } from "zod";
|
|
1227
|
+
var PROVIDER = "upstash-box";
|
|
1228
|
+
var POLL_MS = 2000;
|
|
1229
|
+
var Id = z5.string().regex(/^[a-zA-Z0-9_-]{1,128}$/);
|
|
1230
|
+
var SourceClass = z5.enum(["ephemeral", "regular"]);
|
|
1231
|
+
var SourceState = z5.enum(["running", "stopped"]);
|
|
1232
|
+
var Consistency = z5.enum(["unknown", "caller-quiesced"]);
|
|
1233
|
+
var Name = z5.string().regex(/^beachside-[0-9a-f]{24}$/);
|
|
1234
|
+
var NativeSnapshot = z5.object({
|
|
1235
|
+
id: Id,
|
|
1236
|
+
box_id: Id,
|
|
1237
|
+
name: z5.string().min(1).max(512),
|
|
1238
|
+
status: z5.enum(["creating", "ready", "error", "deleted"]),
|
|
1239
|
+
created_at: z5.number().int().positive().max(253402300799)
|
|
1240
|
+
});
|
|
1241
|
+
var SnapshotIdentity = NativeSnapshot.pick({ id: true, box_id: true, name: true });
|
|
1242
|
+
var SnapshotList = z5.object({
|
|
1243
|
+
snapshots: z5.array(NativeSnapshot).nullable().transform((entries) => entries ?? [])
|
|
1244
|
+
});
|
|
1245
|
+
var SnapshotHistory = z5.strictObject({
|
|
1246
|
+
sourceId: Id,
|
|
1247
|
+
sourceClass: SourceClass,
|
|
1248
|
+
consistency: Consistency
|
|
1249
|
+
});
|
|
1250
|
+
var CaptureToken = SnapshotHistory.extend({
|
|
1251
|
+
id: Id.optional(),
|
|
1252
|
+
name: Name,
|
|
1253
|
+
sourceState: SourceState
|
|
1254
|
+
});
|
|
1255
|
+
var profile = {
|
|
1256
|
+
id: "upstash-filesystem",
|
|
1257
|
+
preserve: Preserve.FILESYSTEM,
|
|
1258
|
+
sourceStates: SourceState.options,
|
|
1259
|
+
interruption: "stop",
|
|
1260
|
+
sourceAfter: "unchanged",
|
|
1261
|
+
connections: "unknown",
|
|
1262
|
+
consistency: "unknown",
|
|
1263
|
+
restoreExecution: "fresh",
|
|
1264
|
+
mountHandling: "none"
|
|
1265
|
+
};
|
|
1266
|
+
var capture = {
|
|
1267
|
+
preserve: profile.preserve,
|
|
1268
|
+
interruption: profile.interruption,
|
|
1269
|
+
restoreExecution: profile.restoreExecution
|
|
1270
|
+
};
|
|
1271
|
+
var profileSupport = {
|
|
1272
|
+
status: "supported",
|
|
1273
|
+
value: { profiles: [profile], defaultProfileId: profile.id }
|
|
1274
|
+
};
|
|
1275
|
+
var noVolumes = { status: "unsupported", reason: "Upstash Box has no native volumes" };
|
|
1276
|
+
function captureName(submission) {
|
|
1277
|
+
return `beachside-${createHash("sha256").update(submission).digest("hex").slice(0, 24)}`;
|
|
1278
|
+
}
|
|
1279
|
+
function snapshotsPath(source) {
|
|
1280
|
+
return `${boxPath(source)}/snapshots`;
|
|
1281
|
+
}
|
|
1282
|
+
function snapshotHooks(options) {
|
|
1283
|
+
const { transport, scope, boxKind, readSandbox, restoreCapabilities } = options;
|
|
1284
|
+
const restore = restoreCapabilities.status === "supported" ? restoreCapabilities.value : {
|
|
1285
|
+
networkPolicies: [],
|
|
1286
|
+
resources: false,
|
|
1287
|
+
mounts: false,
|
|
1288
|
+
independentLifecycle: false
|
|
1289
|
+
};
|
|
1290
|
+
function checkReference(reference) {
|
|
1291
|
+
assertResourceScope(reference, { provider: PROVIDER, scope });
|
|
1292
|
+
const id = Id.safeParse(reference.nativeId);
|
|
1293
|
+
if (reference.kind !== "snapshot" || !id.success)
|
|
1294
|
+
throw new AdapterError6("INVALID_ARGUMENT", "Invalid Upstash Box snapshot reference");
|
|
1295
|
+
return id.data;
|
|
1296
|
+
}
|
|
1297
|
+
async function read(source, signal) {
|
|
1298
|
+
const response = SnapshotList.safeParse(await transport.json(snapshotsPath(source), signal));
|
|
1299
|
+
if (!response.success || response.data.snapshots.some((entry) => entry.box_id !== source))
|
|
1300
|
+
throw new AdapterError6("UNAVAILABLE", "Upstash Box returned invalid snapshot inventory");
|
|
1301
|
+
return response.data.snapshots;
|
|
1302
|
+
}
|
|
1303
|
+
function referenceFor(id, token) {
|
|
1304
|
+
const { sourceId, sourceClass, consistency } = token;
|
|
1305
|
+
return validateResourceReference({
|
|
1306
|
+
version: 1,
|
|
1307
|
+
kind: "snapshot",
|
|
1308
|
+
provider: PROVIDER,
|
|
1309
|
+
scope,
|
|
1310
|
+
nativeId: id,
|
|
1311
|
+
ownership: "verified-created",
|
|
1312
|
+
history: { sourceId, sourceClass, consistency }
|
|
1313
|
+
});
|
|
1314
|
+
}
|
|
1315
|
+
function info(reference, history, native) {
|
|
1316
|
+
const state = native?.status;
|
|
1317
|
+
return {
|
|
1318
|
+
reference,
|
|
1319
|
+
preserve: Preserve.FILESYSTEM,
|
|
1320
|
+
restoreExecution: "fresh",
|
|
1321
|
+
consistency: history.consistency,
|
|
1322
|
+
source: { id: history.sourceId, class: history.sourceClass },
|
|
1323
|
+
state: state === "creating" || state === "ready" ? state : "unknown",
|
|
1324
|
+
createdAt: native ? listedTime(native.created_at * 1000) : null,
|
|
1325
|
+
expiration: "unknown",
|
|
1326
|
+
excludedPaths: null,
|
|
1327
|
+
mounts: [],
|
|
1328
|
+
mountHandling: "none",
|
|
1329
|
+
restore: {
|
|
1330
|
+
networkPolicies: restore.networkPolicies,
|
|
1331
|
+
resources: restore.resources,
|
|
1332
|
+
mounts: restore.mounts,
|
|
1333
|
+
independentLifecycle: restore.independentLifecycle
|
|
1334
|
+
},
|
|
1335
|
+
dependencies: [],
|
|
1336
|
+
nativeDependencies: null,
|
|
1337
|
+
labels: null
|
|
1338
|
+
};
|
|
1339
|
+
}
|
|
1340
|
+
function unknownCapture(token, native) {
|
|
1341
|
+
const id = native?.id ?? token.id;
|
|
1342
|
+
return {
|
|
1343
|
+
kind: "snapshot_capture",
|
|
1344
|
+
status: native?.status === "ready" ? "partial" : "unknown",
|
|
1345
|
+
snapshot: id ? referenceFor(id, token) : undefined,
|
|
1346
|
+
capture: native?.status === "ready" ? capture : undefined
|
|
1347
|
+
};
|
|
1348
|
+
}
|
|
1349
|
+
async function sourceObservation(sandbox, ctx) {
|
|
1350
|
+
try {
|
|
1351
|
+
const source = await readSandbox(sandbox, ctx);
|
|
1352
|
+
return source.id === sandbox.id ? source.state : "unknown";
|
|
1353
|
+
} catch {
|
|
1354
|
+
return "unknown";
|
|
1355
|
+
}
|
|
1356
|
+
}
|
|
1357
|
+
async function captured(token, native, sandbox, ctx) {
|
|
1358
|
+
const state = await sourceObservation(sandbox, ctx);
|
|
1359
|
+
const snapshot = info(referenceFor(native.id, token), token, native);
|
|
1360
|
+
const source = { state, connections: "unknown", observedAt: new Date().toISOString() };
|
|
1361
|
+
if (state !== token.sourceState)
|
|
1362
|
+
return {
|
|
1363
|
+
success: false,
|
|
1364
|
+
outcome: {
|
|
1365
|
+
kind: "snapshot_capture",
|
|
1366
|
+
status: "partial",
|
|
1367
|
+
snapshot: referenceFor(native.id, token),
|
|
1368
|
+
capture,
|
|
1369
|
+
source
|
|
1370
|
+
}
|
|
1371
|
+
};
|
|
1372
|
+
return {
|
|
1373
|
+
success: true,
|
|
1374
|
+
value: { snapshot, capture, source, retainedResources: [snapshot.reference] }
|
|
1375
|
+
};
|
|
1376
|
+
}
|
|
1377
|
+
return {
|
|
1378
|
+
snapshotProfiles: async () => profileSupport,
|
|
1379
|
+
resourceCapabilities: async () => ({
|
|
1380
|
+
restore: restoreCapabilities,
|
|
1381
|
+
volumes: noVolumes,
|
|
1382
|
+
mounts: noVolumes
|
|
1383
|
+
}),
|
|
1384
|
+
snapshotCapture: {
|
|
1385
|
+
recovery: { version: 1, token: CaptureToken },
|
|
1386
|
+
async prepare(input, ctx) {
|
|
1387
|
+
const source = await readSandbox(input.sandbox, ctx);
|
|
1388
|
+
const plan = resolveSnapshot(profileSupport, input.request, source.state);
|
|
1389
|
+
if (source.id !== input.sandbox.id)
|
|
1390
|
+
throw new AdapterError6("CONFLICT", "Upstash Box returned a different snapshot source");
|
|
1391
|
+
if (plan.status !== "supported")
|
|
1392
|
+
throw new AdapterError6("UNSUPPORTED", plan.reason);
|
|
1393
|
+
if (input.request.retention?.cleanupAfterSeconds !== undefined)
|
|
1394
|
+
throw new AdapterError6("UNSUPPORTED", "Upstash Box does not schedule snapshot cleanup");
|
|
1395
|
+
return {
|
|
1396
|
+
...input,
|
|
1397
|
+
expectation: { profile: plan.value.profile, sourceState: plan.value.sourceState }
|
|
1398
|
+
};
|
|
1399
|
+
},
|
|
1400
|
+
async submit(input, ctx) {
|
|
1401
|
+
const sourceState = SourceState.safeParse(input.expectation?.sourceState);
|
|
1402
|
+
const id = Id.safeParse(input.sandbox.id);
|
|
1403
|
+
if (!sourceState.success || !id.success)
|
|
1404
|
+
return ctx.reject("INVALID_ARGUMENT", "Upstash Box snapshot source is unconfirmed");
|
|
1405
|
+
const token = {
|
|
1406
|
+
sourceId: id.data,
|
|
1407
|
+
sourceClass: boxKind,
|
|
1408
|
+
sourceState: sourceState.data,
|
|
1409
|
+
consistency: input.request.consistency ?? "unknown",
|
|
1410
|
+
name: captureName(ctx.submissionId)
|
|
1411
|
+
};
|
|
1412
|
+
await ctx.checkpoint(token);
|
|
1413
|
+
let response;
|
|
1414
|
+
try {
|
|
1415
|
+
response = await transport.json(snapshotsPath(token.sourceId), ctx.signal, "POST", {
|
|
1416
|
+
name: token.name
|
|
1417
|
+
});
|
|
1418
|
+
} catch (error) {
|
|
1419
|
+
if (definitiveRefusal(error))
|
|
1420
|
+
return ctx.reject(error.code, error.message);
|
|
1421
|
+
return ctx.pending(token, { pollAfterMs: POLL_MS });
|
|
1422
|
+
}
|
|
1423
|
+
const identity = SnapshotIdentity.safeParse(response);
|
|
1424
|
+
if (!identity.success || identity.data.name !== token.name || identity.data.box_id !== token.sourceId)
|
|
1425
|
+
return ctx.pending(token, { pollAfterMs: POLL_MS });
|
|
1426
|
+
const acknowledged = { ...token, id: identity.data.id };
|
|
1427
|
+
const native = NativeSnapshot.safeParse(response);
|
|
1428
|
+
try {
|
|
1429
|
+
await ctx.checkpoint(acknowledged);
|
|
1430
|
+
} catch (error) {
|
|
1431
|
+
if (error instanceof AdapterCheckpointError)
|
|
1432
|
+
error.outcome = unknownCapture(acknowledged, native.success ? native.data : undefined);
|
|
1433
|
+
throw error;
|
|
1434
|
+
}
|
|
1435
|
+
if (!native.success || native.data.status === "creating")
|
|
1436
|
+
return ctx.pending(acknowledged, { pollAfterMs: POLL_MS });
|
|
1437
|
+
if (native.data.status !== "ready")
|
|
1438
|
+
return ctx.unknown("Upstash Box did not complete snapshot capture", unknownCapture(acknowledged, native.data));
|
|
1439
|
+
const result = await captured(acknowledged, native.data, input.sandbox, {
|
|
1440
|
+
signal: ctx.signal,
|
|
1441
|
+
deadline: Date.now() + 30000
|
|
1442
|
+
});
|
|
1443
|
+
return result.success ? result.value : ctx.unknown("Snapshot is ready but source state is unconfirmed", result.outcome);
|
|
1444
|
+
},
|
|
1445
|
+
async observe(attempt, ctx) {
|
|
1446
|
+
const parsed = CaptureToken.safeParse(attempt.token);
|
|
1447
|
+
if (!parsed.success || parsed.data.sourceId !== attempt.sandbox?.id || parsed.data.name !== captureName(attempt.submissionId))
|
|
1448
|
+
return null;
|
|
1449
|
+
const token = parsed.data;
|
|
1450
|
+
let snapshots;
|
|
1451
|
+
try {
|
|
1452
|
+
snapshots = await read(token.sourceId, ctx.signal);
|
|
1453
|
+
} catch {
|
|
1454
|
+
return ctx.unknown("Upstash Box snapshot state could not be observed", unknownCapture(token));
|
|
1455
|
+
}
|
|
1456
|
+
const matching = snapshots.filter((entry) => entry.name === token.name && (!token.id || token.id === entry.id));
|
|
1457
|
+
if (matching.length > 1)
|
|
1458
|
+
return ctx.unknown("Upstash Box returned ambiguous snapshot identity", unknownCapture(token));
|
|
1459
|
+
const snapshot = matching[0];
|
|
1460
|
+
if (!snapshot)
|
|
1461
|
+
return ctx.unknown("Upstash Box did not return the submitted snapshot", unknownCapture(token));
|
|
1462
|
+
if (snapshot.status === "creating")
|
|
1463
|
+
return ctx.pending({ ...token, id: snapshot.id }, { pollAfterMs: POLL_MS });
|
|
1464
|
+
if (snapshot.status !== "ready")
|
|
1465
|
+
return ctx.unknown("Upstash Box did not complete snapshot capture", unknownCapture(token, snapshot));
|
|
1466
|
+
const result = await captured(token, snapshot, attempt.sandbox, ctx);
|
|
1467
|
+
return result.success ? result.value : ctx.unknown("Snapshot is ready but source state is unconfirmed", result.outcome);
|
|
1468
|
+
}
|
|
1469
|
+
},
|
|
1470
|
+
async snapshotInspect(reference, ctx) {
|
|
1471
|
+
const id = checkReference(reference);
|
|
1472
|
+
const history = SnapshotHistory.safeParse(reference.history);
|
|
1473
|
+
if (!history.success)
|
|
1474
|
+
throw new AdapterError6("UNSUPPORTED", "Upstash requires the source Box ID to inspect a snapshot");
|
|
1475
|
+
const snapshots = await read(history.data.sourceId, ctx.signal);
|
|
1476
|
+
const snapshot = snapshots.find((entry) => entry.id === id && entry.status !== "deleted");
|
|
1477
|
+
if (!snapshot)
|
|
1478
|
+
throw new AdapterError6("NOT_FOUND", "Upstash Box snapshot is unavailable");
|
|
1479
|
+
return info(reference, history.data, snapshot);
|
|
1480
|
+
},
|
|
1481
|
+
snapshotDelete: {
|
|
1482
|
+
async prepare(reference) {
|
|
1483
|
+
checkReference(reference);
|
|
1484
|
+
return reference;
|
|
1485
|
+
},
|
|
1486
|
+
async submit(reference, ctx) {
|
|
1487
|
+
const id = checkReference(reference);
|
|
1488
|
+
let response;
|
|
1489
|
+
try {
|
|
1490
|
+
response = await transport.json("/v2/box/snapshots", ctx.signal, "DELETE", { ids: [id] });
|
|
1491
|
+
} catch (error) {
|
|
1492
|
+
if (definitiveRefusal(error))
|
|
1493
|
+
return ctx.reject(error.code, error.message);
|
|
1494
|
+
return ctx.unknown("Upstash Box snapshot deletion could not be confirmed");
|
|
1495
|
+
}
|
|
1496
|
+
const result = z5.object({ deleted: z5.literal(1) }).safeParse(response);
|
|
1497
|
+
return result.success ? { deleted: true, reference } : ctx.unknown("Upstash Box did not confirm deleting the exact snapshot");
|
|
1498
|
+
}
|
|
1499
|
+
}
|
|
1500
|
+
};
|
|
1501
|
+
}
|
|
1502
|
+
|
|
1503
|
+
// src/regular.ts
|
|
1504
|
+
import {
|
|
1505
|
+
AdapterCheckpointError as AdapterCheckpointError2,
|
|
1506
|
+
AdapterError as AdapterError7,
|
|
1507
|
+
Preserve as Preserve2,
|
|
1508
|
+
PreviewResult
|
|
1509
|
+
} from "@beachside/adapter";
|
|
1510
|
+
import { z as z6 } from "zod";
|
|
1511
|
+
var Preview = z6.object({
|
|
1512
|
+
url: z6.url(),
|
|
1513
|
+
port: z6.number().int(),
|
|
1514
|
+
token: z6.string().min(1).optional()
|
|
1515
|
+
});
|
|
1516
|
+
var PreviewList = z6.object({
|
|
1517
|
+
previews: z6.array(Preview.extend({ bearer_token: z6.boolean(), basic_auth: z6.boolean() }))
|
|
1518
|
+
});
|
|
1519
|
+
function regularHooks(options) {
|
|
1520
|
+
const { transport, identify, inspect, keepAlive, access } = options;
|
|
1521
|
+
const preview = async ({ sandbox, port }, ctx) => {
|
|
1522
|
+
const id = identify(sandbox);
|
|
1523
|
+
const { info: box } = await inspect(sandbox, ctx);
|
|
1524
|
+
if (box.state !== "running")
|
|
1525
|
+
throw new AdapterError7("CONFLICT", "Resume the Upstash Box before publishing a preview");
|
|
1526
|
+
const path = `${boxPath(id)}/preview`;
|
|
1527
|
+
const host = `${id.toLowerCase()}-${port}.preview.box.upstash.com`;
|
|
1528
|
+
const current = PreviewList.safeParse(await transport.json(path, ctx.signal));
|
|
1529
|
+
if (!current.success)
|
|
1530
|
+
throw new AdapterError7("UNAVAILABLE", "Upstash Box preview list is invalid");
|
|
1531
|
+
const existing = current.data.previews.find((entry) => entry.port === port);
|
|
1532
|
+
if (existing) {
|
|
1533
|
+
if (existing.basic_auth || existing.bearer_token !== (access === "protected"))
|
|
1534
|
+
throw new AdapterError7("CONFLICT", "Upstash Box port already has a different preview access mode");
|
|
1535
|
+
if (new URL(existing.url).hostname !== host)
|
|
1536
|
+
throw new AdapterError7("UNAVAILABLE", "Upstash Box returned a mismatched preview");
|
|
1537
|
+
if (access === "public")
|
|
1538
|
+
return PreviewResult.parse({ access, url: existing.url });
|
|
1539
|
+
}
|
|
1540
|
+
const parsed = Preview.safeParse(await transport.json(path, ctx.signal, "POST", {
|
|
1541
|
+
port,
|
|
1542
|
+
bearer_token: access === "protected",
|
|
1543
|
+
basic_auth: false
|
|
1544
|
+
}));
|
|
1545
|
+
if (!parsed.success || parsed.data.port !== port || new URL(parsed.data.url).hostname !== host)
|
|
1546
|
+
throw new AdapterError7("UNAVAILABLE", "Upstash Box returned a mismatched preview");
|
|
1547
|
+
const { url, token } = parsed.data;
|
|
1548
|
+
const result = PreviewResult.safeParse(access === "protected" ? { access, url, headers: token ? { Authorization: `Bearer ${token}` } : {} } : token ? undefined : { access, url });
|
|
1549
|
+
if (!result.success)
|
|
1550
|
+
throw new AdapterError7("UNAVAILABLE", "Upstash Box did not confirm the configured preview access");
|
|
1551
|
+
return result.data;
|
|
1552
|
+
};
|
|
1553
|
+
if (keepAlive)
|
|
1554
|
+
return { preview };
|
|
1555
|
+
const LifecycleAck = z6.strictObject({ id: z6.string().min(1).max(128) });
|
|
1556
|
+
const recovery = { version: 1, token: LifecycleAck };
|
|
1557
|
+
const suspendFacts = {
|
|
1558
|
+
preserve: Preserve2.FILESYSTEM,
|
|
1559
|
+
processes: "terminated",
|
|
1560
|
+
connections: "dropped"
|
|
1561
|
+
};
|
|
1562
|
+
const resumeFacts = { execution: "fresh", connections: "dropped" };
|
|
1563
|
+
function pausePartial(reference) {
|
|
1564
|
+
return {
|
|
1565
|
+
kind: "sandbox_suspend",
|
|
1566
|
+
status: "partial",
|
|
1567
|
+
reference,
|
|
1568
|
+
acknowledged: true,
|
|
1569
|
+
...suspendFacts,
|
|
1570
|
+
observation: null
|
|
1571
|
+
};
|
|
1572
|
+
}
|
|
1573
|
+
function resumePartial(reference) {
|
|
1574
|
+
return {
|
|
1575
|
+
kind: "sandbox_resume",
|
|
1576
|
+
status: "partial",
|
|
1577
|
+
reference,
|
|
1578
|
+
acknowledged: true,
|
|
1579
|
+
...resumeFacts,
|
|
1580
|
+
observation: null
|
|
1581
|
+
};
|
|
1582
|
+
}
|
|
1583
|
+
async function observed(attempt, ctx) {
|
|
1584
|
+
const token = LifecycleAck.safeParse(attempt.token);
|
|
1585
|
+
const box = attempt.sandbox;
|
|
1586
|
+
if (!token.success || !box?.reference || token.data.id !== box.id)
|
|
1587
|
+
return null;
|
|
1588
|
+
const { info } = await inspect(box, ctx).catch(() => ({ info: null }));
|
|
1589
|
+
return { token: token.data, reference: box.reference, info };
|
|
1590
|
+
}
|
|
1591
|
+
async function canChangeState(box, ctx) {
|
|
1592
|
+
if (!box)
|
|
1593
|
+
return null;
|
|
1594
|
+
const current = await inspect(box, ctx).catch(() => null);
|
|
1595
|
+
if (!current)
|
|
1596
|
+
return { status: "unknown", reason: "Upstash Box state could not be verified" };
|
|
1597
|
+
if (current.keepAlive)
|
|
1598
|
+
return {
|
|
1599
|
+
status: "unsupported",
|
|
1600
|
+
reason: "Upstash keep-alive boxes cannot pause or resume"
|
|
1601
|
+
};
|
|
1602
|
+
return null;
|
|
1603
|
+
}
|
|
1604
|
+
async function assertTransition(box, desired, ctx) {
|
|
1605
|
+
const { info, keepAlive: active } = await inspect(box, ctx);
|
|
1606
|
+
if (active)
|
|
1607
|
+
throw new AdapterError7("UNSUPPORTED", "Upstash keep-alive boxes cannot pause or resume");
|
|
1608
|
+
if (info.state !== desired)
|
|
1609
|
+
throw new AdapterError7("CONFLICT", `Upstash Box must be ${desired} for this operation`);
|
|
1610
|
+
}
|
|
1611
|
+
const suspend = {
|
|
1612
|
+
recovery,
|
|
1613
|
+
async prepare(input, ctx) {
|
|
1614
|
+
await assertTransition(input.sandbox, "running", ctx);
|
|
1615
|
+
return { ...input, intent: { action: "suspend", preserve: Preserve2.FILESYSTEM } };
|
|
1616
|
+
},
|
|
1617
|
+
async submit(input, ctx) {
|
|
1618
|
+
const id = identify(input.sandbox);
|
|
1619
|
+
try {
|
|
1620
|
+
await assertTransition(input.sandbox, "running", {
|
|
1621
|
+
signal: ctx.signal,
|
|
1622
|
+
deadline: Date.now() + 30000
|
|
1623
|
+
});
|
|
1624
|
+
} catch (error) {
|
|
1625
|
+
if (error instanceof AdapterError7)
|
|
1626
|
+
return ctx.reject(error.code, error.message);
|
|
1627
|
+
return ctx.reject("UNAVAILABLE", "Upstash Box state could not be verified before dispatch");
|
|
1628
|
+
}
|
|
1629
|
+
try {
|
|
1630
|
+
await transport.empty(`${boxPath(id)}/pause`, ctx.signal, "POST");
|
|
1631
|
+
} catch (error) {
|
|
1632
|
+
if (definitiveRefusal(error))
|
|
1633
|
+
return ctx.reject(error.code, error.message);
|
|
1634
|
+
return ctx.unknown("Upstash Box pause was not acknowledged");
|
|
1635
|
+
}
|
|
1636
|
+
const token = { id };
|
|
1637
|
+
try {
|
|
1638
|
+
await ctx.checkpoint(token);
|
|
1639
|
+
} catch (error) {
|
|
1640
|
+
if (error instanceof AdapterCheckpointError2)
|
|
1641
|
+
error.outcome = pausePartial(input.sandbox.reference);
|
|
1642
|
+
throw error;
|
|
1643
|
+
}
|
|
1644
|
+
return observePause({ ...ctx, sandbox: input.sandbox, token }, {
|
|
1645
|
+
signal: ctx.signal,
|
|
1646
|
+
deadline: Date.now() + 30000,
|
|
1647
|
+
pending: ctx.pending,
|
|
1648
|
+
unknown: ctx.unknown
|
|
1649
|
+
});
|
|
1650
|
+
},
|
|
1651
|
+
observe: observePause
|
|
1652
|
+
};
|
|
1653
|
+
async function observePause(attempt, ctx) {
|
|
1654
|
+
const current = await observed(attempt, ctx);
|
|
1655
|
+
if (!current)
|
|
1656
|
+
return ctx.unknown("Upstash Box pause acknowledgement is unavailable");
|
|
1657
|
+
const { token, reference, info } = current;
|
|
1658
|
+
if (info?.state === "stopped")
|
|
1659
|
+
return { reference, ...suspendFacts, observation: info };
|
|
1660
|
+
if (info?.state === "running")
|
|
1661
|
+
return ctx.pending(token, { pollAfterMs: 1000 });
|
|
1662
|
+
return ctx.unknown("Upstash Box acknowledged pause but stopped state was not observed", pausePartial(reference));
|
|
1663
|
+
}
|
|
1664
|
+
const resume = {
|
|
1665
|
+
recovery,
|
|
1666
|
+
async prepare(input, ctx) {
|
|
1667
|
+
await assertTransition(input.sandbox, "stopped", ctx);
|
|
1668
|
+
return { ...input, intent: { action: "resume" } };
|
|
1669
|
+
},
|
|
1670
|
+
async submit(input, ctx) {
|
|
1671
|
+
const id = identify(input.sandbox);
|
|
1672
|
+
try {
|
|
1673
|
+
await assertTransition(input.sandbox, "stopped", {
|
|
1674
|
+
signal: ctx.signal,
|
|
1675
|
+
deadline: Date.now() + 30000
|
|
1676
|
+
});
|
|
1677
|
+
} catch (error) {
|
|
1678
|
+
if (error instanceof AdapterError7)
|
|
1679
|
+
return ctx.reject(error.code, error.message);
|
|
1680
|
+
return ctx.reject("UNAVAILABLE", "Upstash Box state could not be verified before dispatch");
|
|
1681
|
+
}
|
|
1682
|
+
try {
|
|
1683
|
+
await transport.empty(`${boxPath(id)}/resume`, ctx.signal, "POST");
|
|
1684
|
+
} catch (error) {
|
|
1685
|
+
if (definitiveRefusal(error))
|
|
1686
|
+
return ctx.reject(error.code, error.message);
|
|
1687
|
+
return ctx.unknown("Upstash Box resume was not acknowledged");
|
|
1688
|
+
}
|
|
1689
|
+
const token = { id };
|
|
1690
|
+
try {
|
|
1691
|
+
await ctx.checkpoint(token);
|
|
1692
|
+
} catch (error) {
|
|
1693
|
+
if (error instanceof AdapterCheckpointError2)
|
|
1694
|
+
error.outcome = resumePartial(input.sandbox.reference);
|
|
1695
|
+
throw error;
|
|
1696
|
+
}
|
|
1697
|
+
return observeResume({ ...ctx, sandbox: input.sandbox, token }, {
|
|
1698
|
+
signal: ctx.signal,
|
|
1699
|
+
deadline: Date.now() + 30000,
|
|
1700
|
+
pending: ctx.pending,
|
|
1701
|
+
unknown: ctx.unknown
|
|
1702
|
+
});
|
|
1703
|
+
},
|
|
1704
|
+
observe: observeResume
|
|
1705
|
+
};
|
|
1706
|
+
async function observeResume(attempt, ctx) {
|
|
1707
|
+
const current = await observed(attempt, ctx);
|
|
1708
|
+
if (!current)
|
|
1709
|
+
return ctx.unknown("Upstash Box resume acknowledgement is unavailable");
|
|
1710
|
+
const { token, reference, info } = current;
|
|
1711
|
+
if (info?.state === "running")
|
|
1712
|
+
return { reference, ...resumeFacts, executionIdentity: info.execution, observation: info };
|
|
1713
|
+
if (info?.state === "stopped")
|
|
1714
|
+
return ctx.pending(token, { pollAfterMs: 1000 });
|
|
1715
|
+
return ctx.unknown("Upstash Box acknowledged resume but running state was not observed", resumePartial(reference));
|
|
1716
|
+
}
|
|
1717
|
+
return {
|
|
1718
|
+
preview,
|
|
1719
|
+
suspend,
|
|
1720
|
+
resume,
|
|
1721
|
+
async suspensionCapabilities({ sandbox }, ctx) {
|
|
1722
|
+
return await canChangeState(sandbox, ctx) ?? { status: "supported", value: suspendFacts };
|
|
1723
|
+
},
|
|
1724
|
+
async resumeCapabilities({ sandbox }, ctx) {
|
|
1725
|
+
return await canChangeState(sandbox, ctx) ?? {
|
|
1726
|
+
status: "supported",
|
|
1727
|
+
value: { sourceStates: ["stopped"], setsSessionTimeout: false }
|
|
1728
|
+
};
|
|
1729
|
+
}
|
|
1730
|
+
};
|
|
1731
|
+
}
|
|
1732
|
+
|
|
1733
|
+
// src/adapter.ts
|
|
1734
|
+
var PROVIDER2 = "upstash-box";
|
|
1735
|
+
var REGION = "us-east-1";
|
|
1736
|
+
var IMAGE = "node";
|
|
1737
|
+
var LIFETIME = { minSeconds: 1, maxSeconds: 259200 };
|
|
1738
|
+
var Runtime = z7.enum([
|
|
1739
|
+
"node",
|
|
1740
|
+
"python",
|
|
1741
|
+
"golang",
|
|
1742
|
+
"ruby",
|
|
1743
|
+
"rust",
|
|
1744
|
+
"node-alpine",
|
|
1745
|
+
"python-alpine",
|
|
1746
|
+
"golang-alpine",
|
|
1747
|
+
"ruby-alpine",
|
|
1748
|
+
"rust-alpine"
|
|
1749
|
+
]);
|
|
1750
|
+
var BoxKind = z7.enum(["ephemeral", "regular"]);
|
|
1751
|
+
var RESERVED_ENV = new Set([
|
|
1752
|
+
"PATH",
|
|
1753
|
+
"HOME",
|
|
1754
|
+
"LD_PRELOAD",
|
|
1755
|
+
"LD_LIBRARY_PATH",
|
|
1756
|
+
"NODE_OPTIONS",
|
|
1757
|
+
"UPSTASH_BOX_ID",
|
|
1758
|
+
"UPSTASH_BOX_NAME",
|
|
1759
|
+
"UPSTASH_BOX_AGENT",
|
|
1760
|
+
"UPSTASH_BOX_RUNTIME"
|
|
1761
|
+
]);
|
|
1762
|
+
var SIZES = [
|
|
1763
|
+
{ name: "small", vcpus: 2, memoryMiB: 4096 },
|
|
1764
|
+
{ name: "medium", vcpus: 4, memoryMiB: 8192 },
|
|
1765
|
+
{ name: "large", vcpus: 8, memoryMiB: 16384 }
|
|
1766
|
+
];
|
|
1767
|
+
var Size = z7.enum(["small", "medium", "large"]);
|
|
1768
|
+
var Setup = z7.strictObject({
|
|
1769
|
+
image: Runtime.default(IMAGE),
|
|
1770
|
+
boxKind: BoxKind.default("ephemeral"),
|
|
1771
|
+
keepAlive: z7.boolean().default(false),
|
|
1772
|
+
preview: z7.strictObject({ access: z7.enum(["protected", "public"]).default("protected") }).optional(),
|
|
1773
|
+
network: z7.union([z7.enum(["internet", "blocked"]), AllowNetworkSetting]).default("internet"),
|
|
1774
|
+
resources: ResourceMinimums.optional(),
|
|
1775
|
+
lifecycle: z7.strictObject({
|
|
1776
|
+
lifetimeSeconds: z7.number().int().min(LIFETIME.minSeconds).max(LIFETIME.maxSeconds).optional()
|
|
1777
|
+
}).default({})
|
|
1778
|
+
});
|
|
1779
|
+
var Credentials = z7.strictObject({
|
|
1780
|
+
apiKey: z7.string().regex(/^[!-~]+$/).max(1024)
|
|
1781
|
+
});
|
|
1782
|
+
var Id2 = z7.string().regex(/^[a-zA-Z0-9_-]{1,128}$/);
|
|
1783
|
+
var NativeLabel = z7.string().regex(/^[a-zA-Z0-9._:-]{1,20}$/);
|
|
1784
|
+
var CorrelationPrefix = "bs:";
|
|
1785
|
+
var Policy = z7.object({
|
|
1786
|
+
mode: z7.enum(["allow-all", "deny-all", "custom"]),
|
|
1787
|
+
allowed_domains: z7.array(z7.string()).max(256).optional(),
|
|
1788
|
+
allowed_cidrs: z7.array(z7.string()).max(256).optional(),
|
|
1789
|
+
denied_cidrs: z7.array(z7.string()).max(256).optional()
|
|
1790
|
+
});
|
|
1791
|
+
var Detail = z7.object({
|
|
1792
|
+
id: Id2,
|
|
1793
|
+
ephemeral: z7.boolean().optional(),
|
|
1794
|
+
keep_alive: z7.boolean().optional(),
|
|
1795
|
+
created_at: z7.number().int().positive().safe().optional(),
|
|
1796
|
+
status: z7.enum(["creating", "idle", "running", "paused", "error", "deleted"]),
|
|
1797
|
+
runtime: z7.string().optional(),
|
|
1798
|
+
size: Size.optional(),
|
|
1799
|
+
labels: z7.array(NativeLabel).max(5).optional(),
|
|
1800
|
+
expires_at: z7.number().int().positive().max(8640000000000).optional().catch(undefined),
|
|
1801
|
+
network_policy: Policy.optional()
|
|
1802
|
+
});
|
|
1803
|
+
var ListEntry = z7.object({
|
|
1804
|
+
id: Id2,
|
|
1805
|
+
ephemeral: Detail.shape.ephemeral.catch(undefined),
|
|
1806
|
+
keep_alive: Detail.shape.keep_alive.catch(undefined),
|
|
1807
|
+
created_at: Detail.shape.created_at.catch(undefined),
|
|
1808
|
+
status: Detail.shape.status.optional().catch(undefined),
|
|
1809
|
+
labels: Detail.shape.labels.catch(undefined),
|
|
1810
|
+
expires_at: Detail.shape.expires_at
|
|
1811
|
+
});
|
|
1812
|
+
var Preparation = z7.strictObject({
|
|
1813
|
+
size: Size,
|
|
1814
|
+
ttl: z7.number().int().min(LIFETIME.minSeconds).max(LIFETIME.maxSeconds).optional(),
|
|
1815
|
+
runtime: Runtime,
|
|
1816
|
+
env_vars: z7.record(z7.string(), z7.string()).optional(),
|
|
1817
|
+
snapshot_id: Id2.optional(),
|
|
1818
|
+
network_policy: Policy,
|
|
1819
|
+
labels: z7.array(NativeLabel).max(4)
|
|
1820
|
+
});
|
|
1821
|
+
var CreateToken = z7.strictObject({
|
|
1822
|
+
id: Id2,
|
|
1823
|
+
size: Size,
|
|
1824
|
+
labels: z7.array(NativeLabel).max(4),
|
|
1825
|
+
policy: z7.string().regex(/^[a-f0-9]{64}$/),
|
|
1826
|
+
ttl: Preparation.shape.ttl,
|
|
1827
|
+
expiryAcknowledged: z7.literal(true).optional(),
|
|
1828
|
+
runtime: Runtime,
|
|
1829
|
+
boxKind: BoxKind,
|
|
1830
|
+
keepAlive: z7.boolean(),
|
|
1831
|
+
restore: z7.boolean().optional()
|
|
1832
|
+
});
|
|
1833
|
+
var DestroyToken = z7.strictObject({ id: Id2, acknowledged: z7.boolean() });
|
|
1834
|
+
function marker(submissionId, kind) {
|
|
1835
|
+
const prefix = kind ? `${CorrelationPrefix}${kind === "ephemeral" ? "e" : "r"}:` : CorrelationPrefix;
|
|
1836
|
+
return prefix + createHash2("sha256").update(submissionId).digest("base64url").slice(0, 20 - prefix.length);
|
|
1837
|
+
}
|
|
1838
|
+
function nativeKind(box) {
|
|
1839
|
+
if (box.ephemeral !== undefined)
|
|
1840
|
+
return box.ephemeral ? "ephemeral" : "regular";
|
|
1841
|
+
if (box.expires_at !== undefined)
|
|
1842
|
+
return "ephemeral";
|
|
1843
|
+
const candidate = box.labels?.find((label) => /^bs:[er]:[A-Za-z0-9_-]{15}$/.test(label));
|
|
1844
|
+
if (candidate)
|
|
1845
|
+
return candidate.startsWith("bs:e:") ? "ephemeral" : "regular";
|
|
1846
|
+
if (box.keep_alive === true)
|
|
1847
|
+
return "regular";
|
|
1848
|
+
return;
|
|
1849
|
+
}
|
|
1850
|
+
var CreationReceipt = z7.object({ submission: z7.string().min(1).max(128) });
|
|
1851
|
+
function hasClassEvidence(box, ref, kind) {
|
|
1852
|
+
if (box.ephemeral !== undefined)
|
|
1853
|
+
return nativeKind(box) === kind;
|
|
1854
|
+
if (ref.ownership === "borrowed")
|
|
1855
|
+
return nativeKind(box) === kind;
|
|
1856
|
+
if (ref.ownership !== "verified-created" || !ref.receipt || !box.labels)
|
|
1857
|
+
return false;
|
|
1858
|
+
try {
|
|
1859
|
+
const receipt = CreationReceipt.safeParse(JSON.parse(ref.receipt));
|
|
1860
|
+
return receipt.success && (box.labels.includes(marker(receipt.data.submission, kind)) || kind === "ephemeral" && box.labels.includes(marker(receipt.data.submission)));
|
|
1861
|
+
} catch {
|
|
1862
|
+
return false;
|
|
1863
|
+
}
|
|
1864
|
+
}
|
|
1865
|
+
function nativeLabels(labels) {
|
|
1866
|
+
const result = Object.entries(labels ?? {}).map(([key, value]) => {
|
|
1867
|
+
const label = `${key}:${value}`;
|
|
1868
|
+
if (!key || key.includes(":") || label.startsWith(CorrelationPrefix) || !NativeLabel.safeParse(label).success)
|
|
1869
|
+
throw new AdapterError8("UNSUPPORTED", "Upstash Box labels must fit its 20-character key:value format");
|
|
1870
|
+
return label;
|
|
1871
|
+
});
|
|
1872
|
+
if (result.length > 4)
|
|
1873
|
+
throw new AdapterError8("UNSUPPORTED", "Upstash Box supports at most four user labels");
|
|
1874
|
+
return result;
|
|
1875
|
+
}
|
|
1876
|
+
function ipv4Range(cidr) {
|
|
1877
|
+
const [address = "", bits = "32"] = cidr.split("/");
|
|
1878
|
+
const start = address.split(".").reduce((value, octet) => value * 256 + Number(octet), 0);
|
|
1879
|
+
return { start, end: start + 2 ** (32 - Number(bits)) - 1 };
|
|
1880
|
+
}
|
|
1881
|
+
var PRIVATE_RANGES = ["10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16"].map(ipv4Range);
|
|
1882
|
+
function rejectPrivateRanges(cidrs) {
|
|
1883
|
+
for (const cidr of cidrs) {
|
|
1884
|
+
const range = ipv4Range(cidr);
|
|
1885
|
+
if (PRIVATE_RANGES.some((blocked) => range.start <= blocked.end && blocked.start <= range.end))
|
|
1886
|
+
throw new AdapterError8("UNSUPPORTED", `Upstash Box cannot allow private IPv4 range ${cidr}`);
|
|
1887
|
+
}
|
|
1888
|
+
}
|
|
1889
|
+
function policyDigest(policy = { mode: "allow-all" }) {
|
|
1890
|
+
const entries = [...policy.allowed_domains ?? [], ...policy.allowed_cidrs ?? []];
|
|
1891
|
+
if (policy.denied_cidrs?.length || policy.mode === "custom" !== entries.length > 0)
|
|
1892
|
+
throw new AdapterError8("CONFLICT", "Upstash Box returned an unexpected network policy");
|
|
1893
|
+
const domains = policy.allowed_domains ?? [];
|
|
1894
|
+
const ranges = policy.allowed_cidrs ?? [];
|
|
1895
|
+
if (domains.some((entry) => parseEgressAllowlist([entry]).hosts.length === 0) || ranges.some((entry) => parseEgressAllowlist([entry]).cidrs.length === 0))
|
|
1896
|
+
throw new AdapterError8("CONFLICT", "Upstash Box returned a misplaced network entry");
|
|
1897
|
+
const canonical = entries.length ? parseEgressAllowlist(entries).canonical : "";
|
|
1898
|
+
return createHash2("sha256").update(JSON.stringify([policy.mode, canonical])).digest("hex");
|
|
1899
|
+
}
|
|
1900
|
+
function hasRequestedExpiry(detail, token, submissionId) {
|
|
1901
|
+
return token.ttl !== undefined && detail.created_at !== undefined && detail.expires_at !== undefined && detail.expires_at - detail.created_at === token.ttl && nativeKind(detail) === "ephemeral" && detail.labels?.includes(marker(submissionId, token.boxKind)) === true;
|
|
1902
|
+
}
|
|
1903
|
+
function ready(detail, token, submissionId) {
|
|
1904
|
+
return nativeKind(detail) === token.boxKind && (detail.status === "idle" || detail.status === "running") && detail.runtime === token.runtime && detail.size === token.size && (token.boxKind === "regular" || hasRequestedExpiry(detail, token, submissionId) && (detail.expires_at ?? 0) * 1000 > Date.now()) && Boolean(detail.keep_alive) === token.keepAlive && detail.labels?.includes(marker(submissionId, token.boxKind)) && token.labels.every((label) => detail.labels?.includes(label)) && token.policy === policyDigest(detail.network_policy);
|
|
1905
|
+
}
|
|
1906
|
+
function sandboxState(status) {
|
|
1907
|
+
const state = {
|
|
1908
|
+
idle: "running",
|
|
1909
|
+
running: "running",
|
|
1910
|
+
paused: "stopped",
|
|
1911
|
+
deleted: "destroyed",
|
|
1912
|
+
creating: "creating",
|
|
1913
|
+
error: "unknown"
|
|
1914
|
+
};
|
|
1915
|
+
return status === undefined ? "unknown" : state[status];
|
|
1916
|
+
}
|
|
1917
|
+
function sandboxInfo(detail, reference) {
|
|
1918
|
+
const size = SIZES.find((entry) => entry.name === detail.size);
|
|
1919
|
+
return {
|
|
1920
|
+
...unknownSandboxFacts(),
|
|
1921
|
+
reference,
|
|
1922
|
+
state: sandboxState(detail.status),
|
|
1923
|
+
nativeState: detail.status,
|
|
1924
|
+
observedAt: new Date().toISOString(),
|
|
1925
|
+
...nativeKind(detail) === "regular" && { expires: { status: "none" } },
|
|
1926
|
+
...detail.expires_at && {
|
|
1927
|
+
expires: {
|
|
1928
|
+
status: "known",
|
|
1929
|
+
action: "destroy",
|
|
1930
|
+
scope: "sandbox",
|
|
1931
|
+
at: new Date(detail.expires_at * 1000).toISOString()
|
|
1932
|
+
}
|
|
1933
|
+
},
|
|
1934
|
+
...size && {
|
|
1935
|
+
resources: {
|
|
1936
|
+
status: "known",
|
|
1937
|
+
value: { vcpus: size.vcpus, memoryMiB: size.memoryMiB }
|
|
1938
|
+
}
|
|
1939
|
+
}
|
|
1940
|
+
};
|
|
1941
|
+
}
|
|
1942
|
+
function createUpstashBoxAdapter(options = {}) {
|
|
1943
|
+
return defineUpstashBoxAdapter(ORIGIN, options);
|
|
1944
|
+
}
|
|
1945
|
+
function defineUpstashBoxAdapter(origin, options) {
|
|
1946
|
+
return defineAdapter({
|
|
1947
|
+
name: PROVIDER2,
|
|
1948
|
+
displayName: "Upstash Box",
|
|
1949
|
+
config: Setup,
|
|
1950
|
+
credentials: Credentials,
|
|
1951
|
+
setup: {
|
|
1952
|
+
credentials: {
|
|
1953
|
+
apiKey: {
|
|
1954
|
+
env: "UPSTASH_BOX_API_KEY",
|
|
1955
|
+
description: "A Box API key from the Upstash Console.",
|
|
1956
|
+
url: "https://console.upstash.com/"
|
|
1957
|
+
}
|
|
1958
|
+
},
|
|
1959
|
+
config: {
|
|
1960
|
+
image: { env: "UPSTASH_BOX_IMAGE", choices: Runtime.options },
|
|
1961
|
+
boxKind: { env: "UPSTASH_BOX_KIND", choices: BoxKind.options },
|
|
1962
|
+
network: { env: "UPSTASH_BOX_NETWORK", choices: ["internet"] }
|
|
1963
|
+
},
|
|
1964
|
+
docs: "https://beachside.run/docs/providers/upstash-box/"
|
|
1965
|
+
},
|
|
1966
|
+
async connect({ config, credentials, host }) {
|
|
1967
|
+
const ephemeral = config.boxKind === "ephemeral";
|
|
1968
|
+
if (ephemeral && (config.keepAlive || config.preview))
|
|
1969
|
+
throw new AdapterError8("UNSUPPORTED", "Upstash Box keep-alive and previews require a regular box");
|
|
1970
|
+
if (!ephemeral && config.lifecycle.lifetimeSeconds !== undefined)
|
|
1971
|
+
throw new AdapterError8("UNSUPPORTED", "Upstash regular boxes have no native lifetime");
|
|
1972
|
+
if (config.network === "blocked")
|
|
1973
|
+
throw new AdapterError8("UNSUPPORTED", "Upstash Box deny-all failed live egress verification");
|
|
1974
|
+
const size = smallestSize("Upstash Box", SIZES, config.resources ?? {});
|
|
1975
|
+
const parsedAllow = allowlistConfig("Upstash Box", config.network);
|
|
1976
|
+
throwAllowlistError(parsedAllow);
|
|
1977
|
+
const allowlist = parsedAllow.allowlist && allowlistFromCanonical(parsedAllow.allowlist);
|
|
1978
|
+
if (allowlist)
|
|
1979
|
+
rejectPrivateRanges(allowlist.cidrs);
|
|
1980
|
+
const defaultPolicy = networkPolicyName(config.network);
|
|
1981
|
+
const policies = allowlist ? ["allow"] : ["internet"];
|
|
1982
|
+
const scope = {
|
|
1983
|
+
authority: { kind: "service", id: origin },
|
|
1984
|
+
partition: { region: REGION }
|
|
1985
|
+
};
|
|
1986
|
+
const transport = createTransport(origin, credentials.apiKey, options.fetch ?? globalThis.fetch);
|
|
1987
|
+
const live = createExec(origin, credentials.apiKey);
|
|
1988
|
+
host.onClose(live.close);
|
|
1989
|
+
const processes = createProcesses(origin, credentials.apiKey);
|
|
1990
|
+
host.onClose(processes.close);
|
|
1991
|
+
await transport.empty(`/v2/box?label=${encodeURIComponent(marker(crypto.randomUUID()))}`, host.signal, "GET");
|
|
1992
|
+
function locator(box) {
|
|
1993
|
+
const id = Id2.safeParse(box.id);
|
|
1994
|
+
if (!id.success)
|
|
1995
|
+
throw new AdapterError8("INVALID_ARGUMENT", "Invalid Upstash Box ID");
|
|
1996
|
+
if (box.reference) {
|
|
1997
|
+
assertResourceScope2(box.reference, { provider: PROVIDER2, scope });
|
|
1998
|
+
if (box.reference.nativeId !== id.data)
|
|
1999
|
+
throw new AdapterError8("CONFLICT", "Upstash Box ID differs from the saved reference");
|
|
2000
|
+
}
|
|
2001
|
+
return id.data;
|
|
2002
|
+
}
|
|
2003
|
+
async function detail(id, signal) {
|
|
2004
|
+
const raw = await transport.json(boxPath(id), signal);
|
|
2005
|
+
const result = Detail.safeParse(raw);
|
|
2006
|
+
if (!result.success)
|
|
2007
|
+
throw new AdapterError8("UNAVAILABLE", "Upstash Box detail is invalid");
|
|
2008
|
+
if (result.data.id !== id)
|
|
2009
|
+
throw new AdapterError8("CONFLICT", "Upstash Box returned a different ID");
|
|
2010
|
+
return result.data;
|
|
2011
|
+
}
|
|
2012
|
+
function reference(id, attempt) {
|
|
2013
|
+
return sandboxReference(PROVIDER2, scope, id, {
|
|
2014
|
+
operation: attempt.operationId,
|
|
2015
|
+
submission: attempt.submissionId
|
|
2016
|
+
});
|
|
2017
|
+
}
|
|
2018
|
+
function partial(ref, acknowledged, restore) {
|
|
2019
|
+
if (restore)
|
|
2020
|
+
return { kind: "snapshot_restore", status: "unknown", sandbox: ref, mounts: [] };
|
|
2021
|
+
return {
|
|
2022
|
+
kind: "create",
|
|
2023
|
+
status: "partial",
|
|
2024
|
+
sandbox: ref,
|
|
2025
|
+
setup: {
|
|
2026
|
+
expiry: acknowledged ? "acknowledged" : "unconfirmed",
|
|
2027
|
+
readiness: "unconfirmed"
|
|
2028
|
+
}
|
|
2029
|
+
};
|
|
2030
|
+
}
|
|
2031
|
+
async function deleted(id, acknowledged, signal) {
|
|
2032
|
+
try {
|
|
2033
|
+
return (await detail(id, signal)).status === "deleted";
|
|
2034
|
+
} catch (error) {
|
|
2035
|
+
return acknowledged && error instanceof BoxHttpError && error.status === 404;
|
|
2036
|
+
}
|
|
2037
|
+
}
|
|
2038
|
+
function prepare(input, snapshotId, selectedSize = size.name) {
|
|
2039
|
+
const runtime = Runtime.safeParse(input.image.value);
|
|
2040
|
+
if (input.image.kind !== "prepared" || !runtime.success || input.region !== undefined && input.region !== REGION || input.requirements || input.mounts?.length)
|
|
2041
|
+
throw new AdapterError8("UNSUPPORTED", "Upstash Box requires a prepared runtime in us-east-1 without mounts or state requirements");
|
|
2042
|
+
if (!ephemeral && input.lifetimeSeconds !== undefined)
|
|
2043
|
+
throw new AdapterError8("UNSUPPORTED", "Upstash regular boxes have no native lifetime");
|
|
2044
|
+
const reserved = Object.keys(input.env ?? {}).find((key) => RESERVED_ENV.has(key));
|
|
2045
|
+
if (reserved)
|
|
2046
|
+
throw new AdapterError8("UNSUPPORTED", `Upstash Box reserves environment variable ${reserved}`);
|
|
2047
|
+
if (!policies.includes(input.networkPolicy))
|
|
2048
|
+
throw new AdapterError8("UNSUPPORTED", "Unsupported Upstash Box network policy");
|
|
2049
|
+
const network_policy = input.networkPolicy === "allow" && allowlist ? {
|
|
2050
|
+
mode: "custom",
|
|
2051
|
+
allowed_domains: [...allowlist.hosts],
|
|
2052
|
+
allowed_cidrs: [...allowlist.cidrs]
|
|
2053
|
+
} : { mode: "allow-all" };
|
|
2054
|
+
return {
|
|
2055
|
+
size: selectedSize,
|
|
2056
|
+
ttl: ephemeral ? input.lifetimeSeconds ?? config.lifecycle.lifetimeSeconds ?? DEFAULT_LIFETIME_SECONDS : undefined,
|
|
2057
|
+
runtime: runtime.data,
|
|
2058
|
+
env_vars: input.env,
|
|
2059
|
+
network_policy,
|
|
2060
|
+
labels: nativeLabels(input.labels),
|
|
2061
|
+
snapshot_id: snapshotId
|
|
2062
|
+
};
|
|
2063
|
+
}
|
|
2064
|
+
async function submitAllocation(prepared, ctx) {
|
|
2065
|
+
let raw;
|
|
2066
|
+
try {
|
|
2067
|
+
raw = await transport.json(prepared.snapshot_id ? "/v2/box/from-snapshot" : "/v2/box", ctx.signal, "POST", {
|
|
2068
|
+
...prepared,
|
|
2069
|
+
...ephemeral ? { ephemeral: true } : config.keepAlive ? { keep_alive: true } : {},
|
|
2070
|
+
labels: [...prepared.labels, marker(ctx.submissionId, config.boxKind)]
|
|
2071
|
+
});
|
|
2072
|
+
} catch (error) {
|
|
2073
|
+
if (definitiveRefusal(error))
|
|
2074
|
+
return ctx.reject(error.code, error.message);
|
|
2075
|
+
return ctx.unknown("Upstash Box did not confirm allocation");
|
|
2076
|
+
}
|
|
2077
|
+
const parsed = z7.object({ id: Id2 }).safeParse(raw);
|
|
2078
|
+
if (!parsed.success)
|
|
2079
|
+
return ctx.unknown("Upstash Box returned no usable allocation ID");
|
|
2080
|
+
const { id } = parsed.data;
|
|
2081
|
+
const ref = reference(id, ctx);
|
|
2082
|
+
const token = {
|
|
2083
|
+
id,
|
|
2084
|
+
size: prepared.size,
|
|
2085
|
+
labels: prepared.labels,
|
|
2086
|
+
policy: policyDigest(prepared.network_policy),
|
|
2087
|
+
runtime: prepared.runtime,
|
|
2088
|
+
boxKind: config.boxKind,
|
|
2089
|
+
keepAlive: config.keepAlive,
|
|
2090
|
+
...prepared.snapshot_id && { restore: true },
|
|
2091
|
+
...prepared.ttl !== undefined && { ttl: prepared.ttl }
|
|
2092
|
+
};
|
|
2093
|
+
const native = Detail.safeParse(raw);
|
|
2094
|
+
const hasExpiry = native.success && hasRequestedExpiry(native.data, token, ctx.submissionId);
|
|
2095
|
+
if (hasExpiry)
|
|
2096
|
+
token.expiryAcknowledged = true;
|
|
2097
|
+
try {
|
|
2098
|
+
await ctx.checkpoint(token);
|
|
2099
|
+
} catch (error) {
|
|
2100
|
+
if (error instanceof AdapterCheckpointError3)
|
|
2101
|
+
error.outcome = partial(ref, hasExpiry, !!token.restore);
|
|
2102
|
+
throw error;
|
|
2103
|
+
}
|
|
2104
|
+
try {
|
|
2105
|
+
if (native.success && ready(native.data, token, ctx.submissionId))
|
|
2106
|
+
return { id, reference: ref, state: "running" };
|
|
2107
|
+
} catch {}
|
|
2108
|
+
return observeAllocation({
|
|
2109
|
+
operationId: ctx.operationId,
|
|
2110
|
+
submissionId: ctx.submissionId,
|
|
2111
|
+
sandbox: undefined,
|
|
2112
|
+
token
|
|
2113
|
+
}, {
|
|
2114
|
+
signal: ctx.signal,
|
|
2115
|
+
deadline: Date.now() + 30000,
|
|
2116
|
+
pending: ctx.pending,
|
|
2117
|
+
unknown: ctx.unknown
|
|
2118
|
+
});
|
|
2119
|
+
}
|
|
2120
|
+
async function observeAllocation(attempt, ctx) {
|
|
2121
|
+
const token = attempt.token;
|
|
2122
|
+
if (!token)
|
|
2123
|
+
return ctx.unknown("Upstash Box allocation did not return an ID");
|
|
2124
|
+
const ref = reference(token.id, attempt);
|
|
2125
|
+
let hasExpiry = token.expiryAcknowledged === true;
|
|
2126
|
+
try {
|
|
2127
|
+
const box = await detail(token.id, ctx.signal);
|
|
2128
|
+
hasExpiry ||= hasRequestedExpiry(box, token, attempt.submissionId);
|
|
2129
|
+
if (ready(box, token, attempt.submissionId))
|
|
2130
|
+
return { id: token.id, reference: ref, state: "running" };
|
|
2131
|
+
if (box.status === "creating") {
|
|
2132
|
+
return ctx.pending(hasExpiry ? { ...token, expiryAcknowledged: true } : token, {
|
|
2133
|
+
pollAfterMs: 2000
|
|
2134
|
+
});
|
|
2135
|
+
}
|
|
2136
|
+
return ctx.unknown("Upstash Box setup could not be confirmed", partial(ref, hasExpiry, !!token.restore));
|
|
2137
|
+
} catch {
|
|
2138
|
+
return ctx.unknown("Upstash Box setup could not be observed", partial(ref, hasExpiry, !!token.restore));
|
|
2139
|
+
}
|
|
2140
|
+
}
|
|
2141
|
+
function prepareRestore(input) {
|
|
2142
|
+
assertResourceScope2(input.snapshot, { provider: PROVIDER2, scope });
|
|
2143
|
+
if (input.snapshot.kind !== "snapshot")
|
|
2144
|
+
throw new AdapterError8("INVALID_ARGUMENT", "Upstash Box requires a snapshot reference");
|
|
2145
|
+
const resources = input.request.resources;
|
|
2146
|
+
if (resources?.diskMiB)
|
|
2147
|
+
throw new AdapterError8("UNSUPPORTED", "Upstash Box cannot select snapshot restore disk size");
|
|
2148
|
+
const requested = smallestSize("Upstash Box", SIZES, {
|
|
2149
|
+
vcpus: Math.max(config.resources?.vcpus ?? 0, resources?.vcpu ?? 0),
|
|
2150
|
+
memoryMiB: Math.max(config.resources?.memoryMiB ?? 0, resources?.memoryMiB ?? 0)
|
|
2151
|
+
});
|
|
2152
|
+
return prepare({
|
|
2153
|
+
image: { kind: "prepared", value: config.image },
|
|
2154
|
+
networkPolicy: input.request.networkPolicy,
|
|
2155
|
+
labels: input.request.labels,
|
|
2156
|
+
env: input.request.env,
|
|
2157
|
+
lifetimeSeconds: input.request.lifetimeSeconds,
|
|
2158
|
+
mounts: input.request.mounts
|
|
2159
|
+
}, Id2.parse(input.snapshot.nativeId), requested.name);
|
|
2160
|
+
}
|
|
2161
|
+
async function list(input, ctx) {
|
|
2162
|
+
const cursor = input.cursor === undefined ? undefined : Id2.safeParse(input.cursor);
|
|
2163
|
+
if (cursor && !cursor.success)
|
|
2164
|
+
throw new AdapterError8("INVALID_ARGUMENT", "Invalid Upstash Box cursor");
|
|
2165
|
+
const rows = z7.array(z7.unknown()).safeParse(await transport.json("/v2/box", ctx.signal));
|
|
2166
|
+
if (!rows.success)
|
|
2167
|
+
throw new AdapterError8("UNAVAILABLE", "Upstash Box list is invalid");
|
|
2168
|
+
const candidates = rows.data.flatMap((raw) => {
|
|
2169
|
+
const box = ListEntry.safeParse(raw);
|
|
2170
|
+
return box.success && (!cursor || box.data.id > cursor.data) ? [{ ...box.data, validDetail: Detail.safeParse(raw).success }] : [];
|
|
2171
|
+
});
|
|
2172
|
+
candidates.sort((left, right) => left.id < right.id ? -1 : left.id === right.id ? 0 : 1);
|
|
2173
|
+
const page = candidates.slice(0, input.limit);
|
|
2174
|
+
return { page, nextCursor: candidates.length > page.length ? page.at(-1)?.id : undefined };
|
|
2175
|
+
}
|
|
2176
|
+
async function requireRunningGuest(box, signal) {
|
|
2177
|
+
const { status } = await detail(locator(box), signal);
|
|
2178
|
+
if (status === "deleted")
|
|
2179
|
+
throw new AdapterError8("NOT_FOUND", "Upstash Box was deleted");
|
|
2180
|
+
if (status === "paused")
|
|
2181
|
+
throw new AdapterError8("CONFLICT", "Resume the Upstash Box before accessing its guest");
|
|
2182
|
+
if (status !== "idle" && status !== "running")
|
|
2183
|
+
throw new AdapterError8("UNAVAILABLE", "Upstash Box guest readiness could not be confirmed");
|
|
2184
|
+
}
|
|
2185
|
+
const guardGuest = ephemeral ? undefined : requireRunningGuest;
|
|
2186
|
+
const files = boxFiles(transport, live.exec, locator, guardGuest);
|
|
2187
|
+
const restoreCapabilities = {
|
|
2188
|
+
status: "supported",
|
|
2189
|
+
value: {
|
|
2190
|
+
networkPolicies: policies,
|
|
2191
|
+
resources: true,
|
|
2192
|
+
mounts: false,
|
|
2193
|
+
independentLifecycle: true
|
|
2194
|
+
}
|
|
2195
|
+
};
|
|
2196
|
+
const snapshots = snapshotHooks({
|
|
2197
|
+
transport,
|
|
2198
|
+
scope,
|
|
2199
|
+
boxKind: config.boxKind,
|
|
2200
|
+
restoreCapabilities,
|
|
2201
|
+
async readSandbox(box, ctx) {
|
|
2202
|
+
const native = await detail(locator(box), ctx.signal);
|
|
2203
|
+
if (box.reference ? !hasClassEvidence(native, box.reference, config.boxKind) : nativeKind(native) !== config.boxKind)
|
|
2204
|
+
throw new AdapterError8("CONFLICT", "Could not confirm the Upstash Box kind");
|
|
2205
|
+
return { id: native.id, state: sandboxInfo(native, box.reference ?? null).state };
|
|
2206
|
+
}
|
|
2207
|
+
});
|
|
2208
|
+
const snapshotRestore = {
|
|
2209
|
+
recovery: { version: 1, token: CreateToken },
|
|
2210
|
+
options: { env: true, labels: true, lifetime: ephemeral ? LIFETIME : undefined },
|
|
2211
|
+
async prepare(input, ctx) {
|
|
2212
|
+
prepareRestore(input);
|
|
2213
|
+
const snapshot = await snapshots.snapshotInspect(input.snapshot, ctx);
|
|
2214
|
+
if (snapshot.state !== "ready")
|
|
2215
|
+
throw new AdapterError8("CONFLICT", "Upstash Box snapshot is not ready");
|
|
2216
|
+
return input;
|
|
2217
|
+
},
|
|
2218
|
+
async submit(input, ctx) {
|
|
2219
|
+
return submitAllocation(prepareRestore(input), ctx);
|
|
2220
|
+
},
|
|
2221
|
+
async observe(attempt, ctx) {
|
|
2222
|
+
const token = CreateToken.safeParse(attempt.token);
|
|
2223
|
+
return observeAllocation({ ...attempt, sandbox: undefined, token: token.success ? token.data : undefined }, ctx);
|
|
2224
|
+
}
|
|
2225
|
+
};
|
|
2226
|
+
return {
|
|
2227
|
+
scope,
|
|
2228
|
+
defaultImage: { kind: "prepared", value: config.image },
|
|
2229
|
+
defaultNetworkPolicy: defaultPolicy,
|
|
2230
|
+
...snapshots,
|
|
2231
|
+
snapshotRestore,
|
|
2232
|
+
ssh: {
|
|
2233
|
+
supports: {
|
|
2234
|
+
auth: "password",
|
|
2235
|
+
publicKey: "unused",
|
|
2236
|
+
scope: "account",
|
|
2237
|
+
hostKeys: false,
|
|
2238
|
+
expires: false,
|
|
2239
|
+
proxy: "none"
|
|
2240
|
+
},
|
|
2241
|
+
async target(input, ctx) {
|
|
2242
|
+
const id = locator(input.sandbox);
|
|
2243
|
+
const { status } = await detail(id, ctx.signal);
|
|
2244
|
+
if (status === "deleted")
|
|
2245
|
+
throw new AdapterError8("NOT_FOUND", "Upstash Box was deleted");
|
|
2246
|
+
if (status === "paused")
|
|
2247
|
+
throw new AdapterError8("CONFLICT", "Resume the Upstash Box before opening SSH");
|
|
2248
|
+
if (status !== "idle" && status !== "running")
|
|
2249
|
+
throw new AdapterError8("UNAVAILABLE", "Upstash Box is not running yet");
|
|
2250
|
+
return {
|
|
2251
|
+
host: new URL(origin).hostname,
|
|
2252
|
+
port: 22,
|
|
2253
|
+
username: id,
|
|
2254
|
+
auth: { method: "password", password: credentials.apiKey }
|
|
2255
|
+
};
|
|
2256
|
+
}
|
|
2257
|
+
},
|
|
2258
|
+
processes: {
|
|
2259
|
+
...processes.processes,
|
|
2260
|
+
async start(input, ctx) {
|
|
2261
|
+
locator(input.sandbox);
|
|
2262
|
+
if (guardGuest)
|
|
2263
|
+
await guardGuest(input.sandbox, ctx.signal);
|
|
2264
|
+
return processes.processes.start(input, ctx);
|
|
2265
|
+
}
|
|
2266
|
+
},
|
|
2267
|
+
...!ephemeral && regularHooks({
|
|
2268
|
+
transport,
|
|
2269
|
+
identify: locator,
|
|
2270
|
+
keepAlive: config.keepAlive,
|
|
2271
|
+
access: config.preview?.access ?? "protected",
|
|
2272
|
+
async inspect(box, ctx) {
|
|
2273
|
+
const native = await detail(locator(box), ctx.signal);
|
|
2274
|
+
if (native.status === "deleted")
|
|
2275
|
+
throw new AdapterError8("NOT_FOUND", "Upstash Box was deleted");
|
|
2276
|
+
if (box.reference ? !hasClassEvidence(native, box.reference, "regular") : nativeKind(native) !== "regular")
|
|
2277
|
+
throw new AdapterError8("CONFLICT", "Could not confirm the saved Upstash Box is regular");
|
|
2278
|
+
return {
|
|
2279
|
+
info: sandboxInfo(native, box.reference ?? null),
|
|
2280
|
+
keepAlive: native.keep_alive === true
|
|
2281
|
+
};
|
|
2282
|
+
}
|
|
2283
|
+
}),
|
|
2284
|
+
supports: {
|
|
2285
|
+
images: ["prepared"],
|
|
2286
|
+
network: policies,
|
|
2287
|
+
lifetime: ephemeral ? LIFETIME : undefined,
|
|
2288
|
+
createEnv: true,
|
|
2289
|
+
exec: { commands: ["argv", "shell"], maxOutputBytes: MAX_OUTPUT_BYTES },
|
|
2290
|
+
fileWrite: { overwrite: true, noClobber: true }
|
|
2291
|
+
},
|
|
2292
|
+
create: {
|
|
2293
|
+
recovery: { version: 1, token: CreateToken },
|
|
2294
|
+
async prepare(input) {
|
|
2295
|
+
return prepare(input);
|
|
2296
|
+
},
|
|
2297
|
+
submit: submitAllocation,
|
|
2298
|
+
observe: observeAllocation
|
|
2299
|
+
},
|
|
2300
|
+
async inventory(input, ctx) {
|
|
2301
|
+
const { page, nextCursor } = await list(input, ctx);
|
|
2302
|
+
return {
|
|
2303
|
+
items: page.map((box) => ({
|
|
2304
|
+
id: box.id,
|
|
2305
|
+
state: box.status === "deleted" ? "destroyed" : box.status === "running" || box.status === "idle" ? "running" : "unknown"
|
|
2306
|
+
})),
|
|
2307
|
+
nextCursor
|
|
2308
|
+
};
|
|
2309
|
+
},
|
|
2310
|
+
async sandboxList(input, ctx) {
|
|
2311
|
+
const { page, nextCursor } = await list(input, ctx);
|
|
2312
|
+
return {
|
|
2313
|
+
coverage: "provider-scope",
|
|
2314
|
+
nextCursor,
|
|
2315
|
+
items: page.map((box) => ({
|
|
2316
|
+
id: box.id,
|
|
2317
|
+
state: sandboxState(box.status),
|
|
2318
|
+
reference: box.validDetail && box.status !== "deleted" && nativeKind(box) === config.boxKind ? validateResourceReference2({
|
|
2319
|
+
version: 1,
|
|
2320
|
+
kind: "sandbox",
|
|
2321
|
+
provider: PROVIDER2,
|
|
2322
|
+
scope,
|
|
2323
|
+
nativeId: box.id,
|
|
2324
|
+
ownership: "borrowed"
|
|
2325
|
+
}) : null,
|
|
2326
|
+
labels: box.labels ? listedLabels(Object.fromEntries(box.labels.flatMap((label) => {
|
|
2327
|
+
const separator = label.indexOf(":");
|
|
2328
|
+
return separator > 0 ? [[label.slice(0, separator), label.slice(separator + 1)]] : [];
|
|
2329
|
+
})), (key) => key === "bs") : null,
|
|
2330
|
+
createdAt: box.created_at === undefined ? null : listedTime2(box.created_at * 1000)
|
|
2331
|
+
}))
|
|
2332
|
+
};
|
|
2333
|
+
},
|
|
2334
|
+
destroy: {
|
|
2335
|
+
recovery: { version: 1, token: DestroyToken },
|
|
2336
|
+
async prepare(box, ctx) {
|
|
2337
|
+
const id = locator(box);
|
|
2338
|
+
await detail(id, ctx.signal);
|
|
2339
|
+
return box;
|
|
2340
|
+
},
|
|
2341
|
+
async submit(box, ctx) {
|
|
2342
|
+
const id = locator(box);
|
|
2343
|
+
const token = { id, acknowledged: false };
|
|
2344
|
+
await ctx.checkpoint(token);
|
|
2345
|
+
try {
|
|
2346
|
+
await transport.empty(boxPath(id), ctx.signal, "DELETE");
|
|
2347
|
+
} catch (error) {
|
|
2348
|
+
if (definitiveRefusal(error))
|
|
2349
|
+
return ctx.reject(error.code, error.message);
|
|
2350
|
+
return ctx.unknown("Upstash Box did not acknowledge deletion");
|
|
2351
|
+
}
|
|
2352
|
+
await ctx.checkpoint({ id, acknowledged: true });
|
|
2353
|
+
if (await deleted(id, true, ctx.signal))
|
|
2354
|
+
return { computeStopped: true, retainedResources: [] };
|
|
2355
|
+
return ctx.unknown("Upstash Box acknowledged deletion but termination was not observed");
|
|
2356
|
+
},
|
|
2357
|
+
async observe(attempt, ctx) {
|
|
2358
|
+
const token = DestroyToken.safeParse(attempt.token);
|
|
2359
|
+
if (!token.success || token.data.id !== attempt.sandbox?.id)
|
|
2360
|
+
return null;
|
|
2361
|
+
if (await deleted(token.data.id, token.data.acknowledged, ctx.signal))
|
|
2362
|
+
return { computeStopped: true, retainedResources: [] };
|
|
2363
|
+
return ctx.unknown(token.data.acknowledged ? "Upstash Box acknowledged deletion but termination was not observed" : "Upstash Box termination could not be confirmed");
|
|
2364
|
+
}
|
|
2365
|
+
},
|
|
2366
|
+
async reopen(ref, ctx) {
|
|
2367
|
+
const id = locator({ id: ref.nativeId, reference: ref });
|
|
2368
|
+
const box = await detail(id, ctx.signal);
|
|
2369
|
+
if (box.status === "deleted")
|
|
2370
|
+
throw new AdapterError8("NOT_FOUND", "Upstash Box was deleted");
|
|
2371
|
+
if (!hasClassEvidence(box, ref, config.boxKind))
|
|
2372
|
+
throw new AdapterError8("CONFLICT", "Could not confirm the saved Upstash Box kind");
|
|
2373
|
+
return sandboxInfo(box, ref);
|
|
2374
|
+
},
|
|
2375
|
+
async inspect(box, ctx) {
|
|
2376
|
+
const id = locator(box);
|
|
2377
|
+
try {
|
|
2378
|
+
return { id, ...sandboxInfo(await detail(id, ctx.signal), box.reference ?? null) };
|
|
2379
|
+
} catch (error) {
|
|
2380
|
+
if (error instanceof BoxHttpError && error.status === 404)
|
|
2381
|
+
return null;
|
|
2382
|
+
throw error;
|
|
2383
|
+
}
|
|
2384
|
+
},
|
|
2385
|
+
exec: Object.assign(async (input, ctx) => {
|
|
2386
|
+
locator(input.sandbox);
|
|
2387
|
+
try {
|
|
2388
|
+
if (guardGuest)
|
|
2389
|
+
await guardGuest(input.sandbox, ctx.signal);
|
|
2390
|
+
return await live.exec(input, ctx.signal);
|
|
2391
|
+
} catch (error) {
|
|
2392
|
+
if (error instanceof ExecLoss)
|
|
2393
|
+
return error.output;
|
|
2394
|
+
if (error instanceof AdapterError8)
|
|
2395
|
+
return ctx.reject(error.code, error.message);
|
|
2396
|
+
throw error;
|
|
2397
|
+
}
|
|
2398
|
+
}, { finiteStdin: "bytes" }),
|
|
2399
|
+
files
|
|
2400
|
+
};
|
|
2401
|
+
}
|
|
2402
|
+
});
|
|
2403
|
+
}
|
|
2404
|
+
var upstashBoxAdapter = createUpstashBoxAdapter();
|
|
2405
|
+
|
|
2406
|
+
// src/index.ts
|
|
2407
|
+
function upstashBox(options) {
|
|
2408
|
+
const { apiKey, ...config } = options;
|
|
2409
|
+
return bindAdapter(upstashBoxAdapter, config, { apiKey });
|
|
2410
|
+
}
|
|
2411
|
+
export {
|
|
2412
|
+
createUpstashBoxAdapter,
|
|
2413
|
+
upstashBox,
|
|
2414
|
+
upstashBoxAdapter
|
|
2415
|
+
};
|