@yaks/sandbox 0.0.0-stage → 0.2.36
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/LICENSE +202 -0
- package/README.md +400 -2
- package/_dist/bubblewrap.d.ts +38 -0
- package/_dist/bubblewrap.d.ts.map +1 -0
- package/_dist/cloudflare.d.ts +136 -0
- package/_dist/cloudflare.d.ts.map +1 -0
- package/_dist/configuration.d.ts +13 -0
- package/_dist/configuration.d.ts.map +1 -0
- package/_dist/docker.d.ts +15 -0
- package/_dist/docker.d.ts.map +1 -0
- package/_dist/effects.d.ts +6 -0
- package/_dist/effects.d.ts.map +1 -0
- package/_dist/lifecycle.d.ts +38 -0
- package/_dist/lifecycle.d.ts.map +1 -0
- package/_dist/mod.d.ts +4 -0
- package/_dist/mod.d.ts.map +1 -0
- package/_dist/provider.d.ts +33 -0
- package/_dist/provider.d.ts.map +1 -0
- package/_dist/pve.d.ts +17 -0
- package/_dist/pve.d.ts.map +1 -0
- package/_dist/recovery.d.ts +71 -0
- package/_dist/recovery.d.ts.map +1 -0
- package/_dist/tools.d.ts +4 -0
- package/_dist/tools.d.ts.map +1 -0
- package/_dist/vocab.d.ts +5 -0
- package/_dist/vocab.d.ts.map +1 -0
- package/archive.js +60 -0
- package/archive.js.map +1 -0
- package/archive.ts +49 -0
- package/bubblewrap.js +495 -0
- package/bubblewrap.js.map +1 -0
- package/bubblewrap.ts +555 -0
- package/cloudflare.js +434 -0
- package/cloudflare.js.map +1 -0
- package/cloudflare.ts +592 -0
- package/configuration.js +84 -0
- package/configuration.js.map +1 -0
- package/configuration.ts +120 -0
- package/deno.json +1 -0
- package/docker.js +149 -0
- package/docker.js.map +1 -0
- package/docker.ts +206 -0
- package/effects.js +86 -0
- package/effects.js.map +1 -0
- package/effects.ts +78 -0
- package/lifecycle.js +153 -0
- package/lifecycle.js.map +1 -0
- package/lifecycle.ts +207 -0
- package/mod.js +6 -0
- package/mod.js.map +1 -0
- package/mod.ts +7 -0
- package/package.json +64 -4
- package/provider.js +11 -0
- package/provider.js.map +1 -0
- package/provider.ts +44 -0
- package/pve.js +197 -0
- package/pve.js.map +1 -0
- package/pve.ts +259 -0
- package/recovery-script.js +187 -0
- package/recovery-script.js.map +1 -0
- package/recovery-script.ts +186 -0
- package/recovery.js +231 -0
- package/recovery.js.map +1 -0
- package/recovery.ts +317 -0
- package/sandbox-runner.js +218 -0
- package/sandbox-runner.js.map +1 -0
- package/sandbox-runner.ts +217 -0
- package/tools.js +42 -0
- package/tools.js.map +1 -0
- package/tools.ts +45 -0
- package/vocab.js +13 -0
- package/vocab.js.map +1 -0
- package/vocab.json +180 -0
- package/vocab.ts +11 -0
package/cloudflare.ts
ADDED
|
@@ -0,0 +1,592 @@
|
|
|
1
|
+
// Cloudflare containers as sandbox providers. The namespace supplies the
|
|
2
|
+
// deployed image; the host supplies invocation environment and RPC retry policy.
|
|
3
|
+
// Grants, accounts and billing are not container concerns.
|
|
4
|
+
import { type Clock, sleep, system } from '@yaks/fp'
|
|
5
|
+
import { type Bundle, type Comp, identityEid } from '@yaks/graph'
|
|
6
|
+
import { shellStat, type Workspace } from '@yaks/machine'
|
|
7
|
+
import type {
|
|
8
|
+
SandboxFile,
|
|
9
|
+
SandboxProvider,
|
|
10
|
+
SandboxRef,
|
|
11
|
+
SandboxRequest,
|
|
12
|
+
} from './provider.ts'
|
|
13
|
+
|
|
14
|
+
/** How a command runs in the container: where, for how long at most, and with
|
|
15
|
+
* what beside the container's own environment. */
|
|
16
|
+
type Run = { cwd?: string; timeout?: number; env?: Record<string, string> }
|
|
17
|
+
|
|
18
|
+
/** One sandbox, as this file asks for it: what the tools do with it, plus the
|
|
19
|
+
* one knob the deploy has no way to set. The SDK's process calls answer
|
|
20
|
+
* objects carrying methods as well; only their data is read here. */
|
|
21
|
+
export type Box = {
|
|
22
|
+
getState(): Promise<{ status: string }>
|
|
23
|
+
exec(
|
|
24
|
+
cmd: string,
|
|
25
|
+
opts?: Run,
|
|
26
|
+
): Promise<{ stdout: string; stderr: string; exitCode: number }>
|
|
27
|
+
startProcess(
|
|
28
|
+
cmd: string,
|
|
29
|
+
opts?: Run & { autoCleanup?: boolean; processId?: string },
|
|
30
|
+
): Promise<{ id: string; pid?: number }>
|
|
31
|
+
getProcess(
|
|
32
|
+
id: string,
|
|
33
|
+
): Promise<{ pid?: number; status: string; exitCode?: number } | null>
|
|
34
|
+
killProcess(id: string): Promise<unknown>
|
|
35
|
+
getProcessLogs(id: string): Promise<{ stdout: string; stderr: string }>
|
|
36
|
+
mkdir(path: string, opts?: { recursive?: boolean }): Promise<unknown>
|
|
37
|
+
writeFile(
|
|
38
|
+
path: string,
|
|
39
|
+
content: string,
|
|
40
|
+
opts?: { encoding?: string },
|
|
41
|
+
): unknown
|
|
42
|
+
readFile(
|
|
43
|
+
path: string,
|
|
44
|
+
opts?: { encoding?: string },
|
|
45
|
+
): Promise<{ content: string }>
|
|
46
|
+
readBytes(path: string): Promise<Bytes>
|
|
47
|
+
destroy(): Promise<unknown>
|
|
48
|
+
setSleepAfter?(after: string): unknown
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
type Bytes = { stream: ReadableStream<Uint8Array>; size: number }
|
|
52
|
+
|
|
53
|
+
/** The sandboxes binding: a Durable Object namespace handing out one by name. */
|
|
54
|
+
export type Sandboxes = {
|
|
55
|
+
idFromName(name: string): unknown
|
|
56
|
+
get(id: unknown): Box
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** The deployed image's writable working directory. */
|
|
60
|
+
export let CWD = '/workspace'
|
|
61
|
+
/** Commands have a four-minute ceiling, including background processes. */
|
|
62
|
+
export let TIMEOUT = 240_000
|
|
63
|
+
/** An idle workbench releases its container after one minute. */
|
|
64
|
+
export let NAP = 60
|
|
65
|
+
export let SLEEP = `${NAP / 60}m`
|
|
66
|
+
/** How long one call keeps a container awake, in seconds: the longest
|
|
67
|
+
* command, then the nap before it sleeps on its own. */
|
|
68
|
+
export let HELD = TIMEOUT / 1000 + NAP
|
|
69
|
+
|
|
70
|
+
let POOL_WAIT = 90_000
|
|
71
|
+
let POOL_POLL = 2_000
|
|
72
|
+
let MAX_INSTANCES = 'Maximum number of running container instances exceeded'
|
|
73
|
+
export let POOL_BUSY =
|
|
74
|
+
'All sandbox containers are busy. Try the same call again shortly.'
|
|
75
|
+
|
|
76
|
+
let capacity = (error: unknown): boolean => {
|
|
77
|
+
for (let cause = error; cause instanceof Error; cause = cause.cause) {
|
|
78
|
+
if (cause.message.includes(MAX_INSTANCES)) return true
|
|
79
|
+
}
|
|
80
|
+
return false
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Wait for a free slot during startup, before any workspace operation runs.
|
|
84
|
+
* The window gives an idle workbench time to snapshot and release its slot. */
|
|
85
|
+
export let admitted = async <T>(
|
|
86
|
+
start: () => T | Promise<T>,
|
|
87
|
+
clock: Clock = system,
|
|
88
|
+
): Promise<T> => {
|
|
89
|
+
let until = clock.now() + POOL_WAIT
|
|
90
|
+
for (;;) {
|
|
91
|
+
try {
|
|
92
|
+
return await start()
|
|
93
|
+
} catch (error) {
|
|
94
|
+
if (!capacity(error)) throw error
|
|
95
|
+
let left = until - clock.now()
|
|
96
|
+
if (left <= 0) throw new Error(POOL_BUSY, { cause: error })
|
|
97
|
+
await sleep(Math.min(left, POOL_POLL), undefined, clock)
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
let STATUS_WAIT = 5_000
|
|
103
|
+
|
|
104
|
+
let UPDATE_WAIT = 5 * 60_000
|
|
105
|
+
let UPDATE_POLL = 10_000
|
|
106
|
+
|
|
107
|
+
// A kernel can take a deployment before its active workbench. Cloudflare
|
|
108
|
+
// defers the object's update for up to five minutes. Only its missing stream
|
|
109
|
+
// RPC means it has yet to update. A file error must still reach the caller.
|
|
110
|
+
let afterUpdate = async <T>(read: () => Promise<T>, clock = system) => {
|
|
111
|
+
let until = clock.now() + UPDATE_WAIT
|
|
112
|
+
for (;;) {
|
|
113
|
+
try {
|
|
114
|
+
return await read()
|
|
115
|
+
} catch (error) {
|
|
116
|
+
let left = until - clock.now()
|
|
117
|
+
if (
|
|
118
|
+
left <= 0 || !(error instanceof Error) ||
|
|
119
|
+
!error.message.includes(
|
|
120
|
+
'RPC receiver does not implement the method "readBytes"',
|
|
121
|
+
)
|
|
122
|
+
) throw error
|
|
123
|
+
await sleep(Math.min(left, UPDATE_POLL), undefined, clock)
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** Process status is a short, read-only control request. The HTTP SDK bounds
|
|
129
|
+
* startup retries, but one unresponsive container read can consume minutes.
|
|
130
|
+
* Cancel that read at the transport and try again. The container proxy's
|
|
131
|
+
* plain 500 also means it could not reach the container. Sandbox API errors
|
|
132
|
+
* carry JSON, including a missing process. */
|
|
133
|
+
export let processStatus = async (
|
|
134
|
+
req: Request,
|
|
135
|
+
send: (req: Request) => Promise<Response>,
|
|
136
|
+
clock: Clock = system,
|
|
137
|
+
): Promise<Response> => {
|
|
138
|
+
let timeout = new DOMException(
|
|
139
|
+
'Sandbox process status timed out',
|
|
140
|
+
'TimeoutError',
|
|
141
|
+
)
|
|
142
|
+
let read = async () => {
|
|
143
|
+
let stop = new AbortController()
|
|
144
|
+
let cancel = clock.after(STATUS_WAIT, () => stop.abort(timeout))
|
|
145
|
+
try {
|
|
146
|
+
return await send(
|
|
147
|
+
new Request(req, {
|
|
148
|
+
signal: AbortSignal.any([req.signal, stop.signal]),
|
|
149
|
+
}),
|
|
150
|
+
)
|
|
151
|
+
} catch (error) {
|
|
152
|
+
throw stop.signal.aborted && !req.signal.aborted ? timeout : error
|
|
153
|
+
} finally {
|
|
154
|
+
cancel()
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
try {
|
|
158
|
+
let response = await read()
|
|
159
|
+
if (
|
|
160
|
+
response.status != 500 || req.signal.aborted ||
|
|
161
|
+
response.headers.get('content-type')?.includes('application/json')
|
|
162
|
+
) {
|
|
163
|
+
return response
|
|
164
|
+
}
|
|
165
|
+
await response.body?.cancel()
|
|
166
|
+
} catch (error) {
|
|
167
|
+
if (error !== timeout || req.signal.aborted) throw error
|
|
168
|
+
}
|
|
169
|
+
return read()
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** The container a group lends one person, by name: one each, so the
|
|
173
|
+
* person's every way in reaches one workbench. The group's id rather than a
|
|
174
|
+
* name of it, since a renamed group keeps its containers. */
|
|
175
|
+
export let named = (within: string, to: string) => `build-${within}-${to}`
|
|
176
|
+
|
|
177
|
+
/** Where a group's lent sandboxes are kept: a graph store's reads and
|
|
178
|
+
* writes, `lent` among its words. */
|
|
179
|
+
export type Lending = {
|
|
180
|
+
read(line: string): Bundle[] | Promise<Bundle[]>
|
|
181
|
+
apply(bundles: Bundle[]): unknown
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** One lent sandbox: whom it is lent to, and the second it sleeps by (0 once
|
|
185
|
+
* it is known to be asleep). */
|
|
186
|
+
export type Lent = { to: string; until: number }
|
|
187
|
+
|
|
188
|
+
let lentRow = (within: string, to: string, until: number | null): Bundle => ({
|
|
189
|
+
entity: { eid: identityEid('lent', [within, to]) },
|
|
190
|
+
lent: {
|
|
191
|
+
to,
|
|
192
|
+
within,
|
|
193
|
+
until: until == null ? null : new Date(until * 1000).toISOString(),
|
|
194
|
+
},
|
|
195
|
+
})
|
|
196
|
+
|
|
197
|
+
/** Every sandbox the group has lent, awake or asleep: whose editable files
|
|
198
|
+
* must survive group trash, members who have since left included. */
|
|
199
|
+
export let lending = async (
|
|
200
|
+
store: Lending,
|
|
201
|
+
within: string,
|
|
202
|
+
): Promise<Lent[]> =>
|
|
203
|
+
(await store.read(`.lent.within=${within}`)).map((row) => {
|
|
204
|
+
let { to, until } = row.lent as Comp
|
|
205
|
+
return {
|
|
206
|
+
to: String(to),
|
|
207
|
+
until: until ? Math.floor(Date.parse(String(until)) / 1000) : 0,
|
|
208
|
+
}
|
|
209
|
+
})
|
|
210
|
+
|
|
211
|
+
/** How many of the group's sandboxes are awake at second `now` beside `to`'s. */
|
|
212
|
+
export let awakeBeside = (lent: Lent[], to: string, now: number): number =>
|
|
213
|
+
lent.filter((l) => l.to != to && l.until > now).length
|
|
214
|
+
|
|
215
|
+
/**
|
|
216
|
+
* `to`'s sandbox in the group, held awake for {@link HELD} more seconds —
|
|
217
|
+
* unless `allowed` others already are, when nothing is written and the answer
|
|
218
|
+
* is how many. The row is written only once its hold is half spent: a build
|
|
219
|
+
* calls faster than its store need hear about it.
|
|
220
|
+
*/
|
|
221
|
+
export let hold = async (
|
|
222
|
+
store: Lending,
|
|
223
|
+
within: string,
|
|
224
|
+
to: string,
|
|
225
|
+
allowed: number,
|
|
226
|
+
now: number = Date.now(),
|
|
227
|
+
): Promise<{ held: true } | { held: false; awake: number }> => {
|
|
228
|
+
let t = Math.floor(now / 1000)
|
|
229
|
+
let lent = await lending(store, within)
|
|
230
|
+
let awake = awakeBeside(lent, to, t)
|
|
231
|
+
if (awake >= allowed) return { held: false, awake }
|
|
232
|
+
let mine = lent.find((l) => l.to == to)
|
|
233
|
+
if (!mine || mine.until - t <= HELD / 2) {
|
|
234
|
+
await store.apply([lentRow(within, to, t + HELD)])
|
|
235
|
+
}
|
|
236
|
+
return { held: true }
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/** `to`'s sandbox in the group, asleep: a stopped container gives its place
|
|
240
|
+
* back at once rather than when its nap would. */
|
|
241
|
+
export let slept = async (
|
|
242
|
+
store: Lending,
|
|
243
|
+
within: string,
|
|
244
|
+
to: string,
|
|
245
|
+
): Promise<void> => {
|
|
246
|
+
await store.apply([lentRow(within, to, null)])
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/** Stored outside the container. locked serializes lifecycle calls across
|
|
250
|
+
* hosts; save is durable before it resolves. Disposal receipts must be kept. */
|
|
251
|
+
export type CloudflareLifecycle = {
|
|
252
|
+
locked<T>(
|
|
253
|
+
id: string,
|
|
254
|
+
act: (receipt: {
|
|
255
|
+
state?: 'provisioning' | 'ready' | 'disposing' | 'released'
|
|
256
|
+
save(
|
|
257
|
+
state: 'provisioning' | 'ready' | 'disposing' | 'released',
|
|
258
|
+
): Promise<void>
|
|
259
|
+
}) => Promise<T>,
|
|
260
|
+
): Promise<T>
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
export type CloudflareOptions = {
|
|
264
|
+
/** Mandatory for durable sandbox lifecycle, unless `ephemeral`. */
|
|
265
|
+
lifecycle?: CloudflareLifecycle
|
|
266
|
+
/** The container's disk does not outlive its {@link NAP}: connect wakes a
|
|
267
|
+
* fresh one from the deployed image and keeps no lifecycle receipts, as a
|
|
268
|
+
* deployed Cloudflare Container does. */
|
|
269
|
+
ephemeral?: boolean
|
|
270
|
+
/** Prepare existing writable storage before each public workspace RPC,
|
|
271
|
+
* including restoration after an ephemeral container wakes. */
|
|
272
|
+
prepare?: (ref: SandboxRef, box: Box) => Promise<void>
|
|
273
|
+
/** Preserve recoverable writable storage, then stop the container. This
|
|
274
|
+
* boundary owns teardown; disposal never calls destroy on its own. */
|
|
275
|
+
trash?: (ref: SandboxRef, box: Box) => Promise<void>
|
|
276
|
+
/** Explicitly restore a durable resource retained by trash. */
|
|
277
|
+
restore?: (ref: SandboxRef, box: Box) => Promise<void>
|
|
278
|
+
env?: () => Promise<Record<string, string>>
|
|
279
|
+
retry?: <T>(send: () => T | Promise<T>) => Promise<T>
|
|
280
|
+
clock?: Clock
|
|
281
|
+
sleepError?: (error: unknown) => void
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/** Cloudflare's synchronous exec is also used to expand artifact globs. */
|
|
285
|
+
export type CloudflareProvider = SandboxProvider & {
|
|
286
|
+
exec(ref: SandboxRef, command: string): ReturnType<Box['exec']>
|
|
287
|
+
open(ref: SandboxRef, path: string): Promise<Bytes>
|
|
288
|
+
/** writes one file's bytes, as `export` reads them: an absolute path is
|
|
289
|
+
* kept, a relative one is under {@link CWD}, and its directory is made */
|
|
290
|
+
put(ref: SandboxRef, file: SandboxFile): Promise<void>
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
let exported = (path: string) => {
|
|
294
|
+
if (!path || path.split('/').includes('..')) {
|
|
295
|
+
throw new Error(`cloudflare: invalid export path: ${path}`)
|
|
296
|
+
}
|
|
297
|
+
return path.startsWith('/') ? path : `${CWD}/${path}`
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
let base64 = (bytes: Uint8Array): string => {
|
|
301
|
+
let parts: string[] = []
|
|
302
|
+
for (let i = 0; i < bytes.length; i += 8192) {
|
|
303
|
+
parts.push(String.fromCharCode(...bytes.subarray(i, i + 8192)))
|
|
304
|
+
}
|
|
305
|
+
return btoa(parts.join(''))
|
|
306
|
+
}
|
|
307
|
+
let checked = async (box: Box, command: string): Promise<string> => {
|
|
308
|
+
let result = await box.exec(command, { timeout: TIMEOUT })
|
|
309
|
+
if (result.exitCode !== 0) {
|
|
310
|
+
throw new Error(`cloudflare: workspace command failed: ${result.stderr}`)
|
|
311
|
+
}
|
|
312
|
+
return result.stdout
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
/** A provider bound to one deployed container namespace. Stable request ids
|
|
316
|
+
* are the namespace names, so connect, export and dispose need no live handle.
|
|
317
|
+
* `from`, `image` and addresses are refused: this namespace boots its deployed
|
|
318
|
+
* image, not a graph commit or an existing sandbox. */
|
|
319
|
+
export let cloudflareProvider = (
|
|
320
|
+
ns: Sandboxes,
|
|
321
|
+
options: CloudflareOptions = {},
|
|
322
|
+
): CloudflareProvider => {
|
|
323
|
+
let retry = options.retry ??
|
|
324
|
+
(async <T>(send: () => T | Promise<T>) => await send())
|
|
325
|
+
let boxOf = (ref: SandboxRef, invocation = true, internal = false): Box => {
|
|
326
|
+
if (ref.address != null) {
|
|
327
|
+
throw new Error('cloudflare: cannot attach an existing sandbox')
|
|
328
|
+
}
|
|
329
|
+
let call = <T>(send: (box: Box) => T | Promise<T>) =>
|
|
330
|
+
retry(async () => {
|
|
331
|
+
if (options.ephemeral || internal) {
|
|
332
|
+
let box = ns.get(ns.idFromName(ref.id))
|
|
333
|
+
if (!internal) await options.prepare?.(ref, box)
|
|
334
|
+
return await send(box)
|
|
335
|
+
}
|
|
336
|
+
if (!options.lifecycle) {
|
|
337
|
+
throw new Error('cloudflare: durable lifecycle storage is required')
|
|
338
|
+
}
|
|
339
|
+
return await options.lifecycle.locked(ref.id, async ({ state }) => {
|
|
340
|
+
if (state != 'ready') {
|
|
341
|
+
throw new Error('cloudflare: sandbox is not ready or was disposed')
|
|
342
|
+
}
|
|
343
|
+
let box = ns.get(ns.idFromName(ref.id))
|
|
344
|
+
let { status } = await box.getState()
|
|
345
|
+
if (status != 'running' && status != 'healthy') {
|
|
346
|
+
throw new Error(
|
|
347
|
+
'cloudflare: sandbox storage is unavailable; refusing recreation',
|
|
348
|
+
)
|
|
349
|
+
}
|
|
350
|
+
// Hold the lifecycle lock through RPC completion: disposal cannot
|
|
351
|
+
// race a stale workspace handle into recreating destroyed storage.
|
|
352
|
+
await options.prepare?.(ref, box)
|
|
353
|
+
return await send(box)
|
|
354
|
+
})
|
|
355
|
+
})
|
|
356
|
+
let dressed = async <T extends Run>(opts?: T) => ({
|
|
357
|
+
...opts,
|
|
358
|
+
...(invocation
|
|
359
|
+
? { env: { ...await options.env?.(), ...opts?.env } }
|
|
360
|
+
: {}),
|
|
361
|
+
})
|
|
362
|
+
return {
|
|
363
|
+
exec: (cmd, opts) =>
|
|
364
|
+
call(async (box) => box.exec(cmd, await dressed(opts))),
|
|
365
|
+
getState: () => call((box) => box.getState()),
|
|
366
|
+
startProcess: (cmd, opts) => {
|
|
367
|
+
let sent = false, failure: unknown
|
|
368
|
+
return call(async (box) => {
|
|
369
|
+
let id = opts?.processId
|
|
370
|
+
if (sent) {
|
|
371
|
+
if (id) {
|
|
372
|
+
let found = await box.getProcess(id)
|
|
373
|
+
if (found) return { id, pid: found.pid }
|
|
374
|
+
}
|
|
375
|
+
throw new Error('Sandbox process start could not be confirmed', {
|
|
376
|
+
cause: failure,
|
|
377
|
+
})
|
|
378
|
+
}
|
|
379
|
+
let args = await dressed(opts)
|
|
380
|
+
sent = true
|
|
381
|
+
try {
|
|
382
|
+
return await box.startProcess(cmd, args)
|
|
383
|
+
} catch (error) {
|
|
384
|
+
failure = error
|
|
385
|
+
throw error
|
|
386
|
+
}
|
|
387
|
+
})
|
|
388
|
+
},
|
|
389
|
+
getProcess: (id) => call((box) => box.getProcess(id)),
|
|
390
|
+
killProcess: (id) => call((box) => box.killProcess(id)),
|
|
391
|
+
getProcessLogs: (id) => call((box) => box.getProcessLogs(id)),
|
|
392
|
+
mkdir: (path, opts) => call((box) => box.mkdir(path, opts)),
|
|
393
|
+
writeFile: (path, content, opts) =>
|
|
394
|
+
call((box) => box.writeFile(path, content, opts)),
|
|
395
|
+
readFile: (path, opts) => call((box) => box.readFile(path, opts)),
|
|
396
|
+
readBytes: (path) => call((box) => box.readBytes(path)),
|
|
397
|
+
destroy: () => call((box) => box.destroy()),
|
|
398
|
+
setSleepAfter: (after) => call((box) => box.setSleepAfter?.(after)),
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
let lifecycle = <T>(
|
|
402
|
+
ref: SandboxRef,
|
|
403
|
+
act: (
|
|
404
|
+
receipt: Parameters<Parameters<CloudflareLifecycle['locked']>[1]>[0],
|
|
405
|
+
) => Promise<T>,
|
|
406
|
+
) => {
|
|
407
|
+
// Validate addresses even when no lifecycle store is configured.
|
|
408
|
+
boxOf(ref)
|
|
409
|
+
if (!options.lifecycle) {
|
|
410
|
+
throw new Error('cloudflare: durable lifecycle storage is required')
|
|
411
|
+
}
|
|
412
|
+
return options.lifecycle.locked(ref.id, act)
|
|
413
|
+
}
|
|
414
|
+
let connection = (ref: SandboxRef) => ({
|
|
415
|
+
workspace: workspaceOf(boxOf(ref)),
|
|
416
|
+
root: CWD,
|
|
417
|
+
})
|
|
418
|
+
return {
|
|
419
|
+
request: async (request: SandboxRequest) => {
|
|
420
|
+
if (request.from != null || request.image != null) {
|
|
421
|
+
throw new Error(
|
|
422
|
+
"cloudflare: uses the namespace's deployed image; from and image are unsupported",
|
|
423
|
+
)
|
|
424
|
+
}
|
|
425
|
+
let prepare = async () => {
|
|
426
|
+
let box = boxOf(request, true, true)
|
|
427
|
+
// mkdir is idempotent and starts the namespace's deployed image.
|
|
428
|
+
if (!options.ephemeral) await box.mkdir(CWD, { recursive: true })
|
|
429
|
+
await Promise.resolve(box.setSleepAfter?.(SLEEP)).catch((e) =>
|
|
430
|
+
options.sleepError?.(e)
|
|
431
|
+
)
|
|
432
|
+
return connection(request)
|
|
433
|
+
}
|
|
434
|
+
if (options.ephemeral) return await prepare()
|
|
435
|
+
return await lifecycle(request, async (receipt) => {
|
|
436
|
+
if (receipt.state == 'released' || receipt.state == 'disposing') {
|
|
437
|
+
throw new Error('cloudflare: sandbox was disposed; request a new id')
|
|
438
|
+
}
|
|
439
|
+
if (receipt.state == 'ready') {
|
|
440
|
+
let { status } = await boxOf(request, true, true).getState()
|
|
441
|
+
if (status != 'running' && status != 'healthy') {
|
|
442
|
+
throw new Error(
|
|
443
|
+
'cloudflare: sandbox storage is unavailable; refusing recreation',
|
|
444
|
+
)
|
|
445
|
+
}
|
|
446
|
+
return connection(request)
|
|
447
|
+
}
|
|
448
|
+
if (receipt.state == 'provisioning') {
|
|
449
|
+
// An interrupted first request may have created writable storage.
|
|
450
|
+
// A stopped/missing instance cannot prove that storage survived.
|
|
451
|
+
let { status } = await boxOf(request, true, true).getState()
|
|
452
|
+
if (status != 'running' && status != 'healthy') {
|
|
453
|
+
throw new Error(
|
|
454
|
+
'cloudflare: interrupted provisioning; refusing recreation',
|
|
455
|
+
)
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
await receipt.save('provisioning')
|
|
459
|
+
let lent = await prepare()
|
|
460
|
+
await receipt.save('ready')
|
|
461
|
+
return lent
|
|
462
|
+
})
|
|
463
|
+
},
|
|
464
|
+
connect: async (ref) => {
|
|
465
|
+
if (options.ephemeral) return connection(ref)
|
|
466
|
+
return await lifecycle(ref, async ({ state }) => {
|
|
467
|
+
if (state != 'ready') {
|
|
468
|
+
throw new Error('cloudflare: sandbox is not ready or was disposed')
|
|
469
|
+
}
|
|
470
|
+
let { status } = await boxOf(ref, true, true).getState()
|
|
471
|
+
if (status != 'running' && status != 'healthy') {
|
|
472
|
+
throw new Error(
|
|
473
|
+
'cloudflare: sandbox storage is unavailable; refusing recreation',
|
|
474
|
+
)
|
|
475
|
+
}
|
|
476
|
+
return connection(ref)
|
|
477
|
+
})
|
|
478
|
+
},
|
|
479
|
+
dispose: async (ref) => {
|
|
480
|
+
if (!options.trash) {
|
|
481
|
+
throw new Error('cloudflare: recoverable trash storage is required')
|
|
482
|
+
}
|
|
483
|
+
boxOf(ref)
|
|
484
|
+
let trash = () =>
|
|
485
|
+
retry(() => options.trash!(ref, ns.get(ns.idFromName(ref.id))))
|
|
486
|
+
if (options.ephemeral) {
|
|
487
|
+
await trash()
|
|
488
|
+
return
|
|
489
|
+
}
|
|
490
|
+
await lifecycle(ref, async (receipt) => {
|
|
491
|
+
if (receipt.state == 'released') return
|
|
492
|
+
await receipt.save('disposing')
|
|
493
|
+
await trash()
|
|
494
|
+
await receipt.save('released')
|
|
495
|
+
})
|
|
496
|
+
},
|
|
497
|
+
restore: async (ref) => {
|
|
498
|
+
if (!options.restore) {
|
|
499
|
+
throw new Error('cloudflare: restore is not configured')
|
|
500
|
+
}
|
|
501
|
+
await lifecycle(ref, async (receipt) => {
|
|
502
|
+
if (receipt.state == 'ready') return
|
|
503
|
+
await retry(() => options.restore!(ref, ns.get(ns.idFromName(ref.id))))
|
|
504
|
+
await receipt.save('ready')
|
|
505
|
+
})
|
|
506
|
+
},
|
|
507
|
+
exec: (ref, command) => boxOf(ref).exec(command, { cwd: CWD }),
|
|
508
|
+
open: (ref, path) => {
|
|
509
|
+
let at = exported(path)
|
|
510
|
+
let box = boxOf(ref)
|
|
511
|
+
return afterUpdate(() => box.readBytes(at), options.clock)
|
|
512
|
+
},
|
|
513
|
+
put: async (ref, { path, bytes }) => {
|
|
514
|
+
let box = boxOf(ref)
|
|
515
|
+
let at = path.startsWith('/') ? path : `${CWD}/${path}`
|
|
516
|
+
await writeFile(box, at, base64(bytes), 'base64')
|
|
517
|
+
},
|
|
518
|
+
export: async function* (ref, paths) {
|
|
519
|
+
// Absolute paths are kept for sandbox_ship's published contract. Relative
|
|
520
|
+
// paths resolve from the deployed image's workspace.
|
|
521
|
+
let box = boxOf(ref)
|
|
522
|
+
for (let path of paths) {
|
|
523
|
+
let { content } = await box.readFile(
|
|
524
|
+
exported(path),
|
|
525
|
+
{ encoding: 'base64' },
|
|
526
|
+
)
|
|
527
|
+
yield {
|
|
528
|
+
path,
|
|
529
|
+
bytes: Uint8Array.from(atob(content.trim()), (c) => c.charCodeAt(0)),
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
},
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
// What the container calls a process that has not ended yet.
|
|
537
|
+
let RUNNING = new Set(['starting', 'running'])
|
|
538
|
+
|
|
539
|
+
let lines = (said: string) => said ? said.replace(/\n$/, '').split('\n') : []
|
|
540
|
+
|
|
541
|
+
/**
|
|
542
|
+
* A container as the workspace @yaks/harness's machine tools run on
|
|
543
|
+
* (`machineTools`). Every command is a background process of the container's
|
|
544
|
+
* own, bounded by {@link TIMEOUT} and kept after it exits so a later `wait`
|
|
545
|
+
* still finds its code; the container's destruction clears them all.
|
|
546
|
+
*
|
|
547
|
+
* Its output is two streams where a box has one, so an answer's tail is what
|
|
548
|
+
* it printed to stdout followed by what it printed to stderr, where a
|
|
549
|
+
* compiler's errors are. A kill is the container's one kill: it takes no
|
|
550
|
+
* signal, so SIGTERM and SIGKILL are the same call.
|
|
551
|
+
*/
|
|
552
|
+
let workspaceOf = (box: Box): Workspace => ({
|
|
553
|
+
// Every look is a call into the container, so it looks twice a second.
|
|
554
|
+
poll: 500,
|
|
555
|
+
start: async (command, cwd, call) =>
|
|
556
|
+
(await box.startProcess(command, {
|
|
557
|
+
cwd: cwd ?? CWD,
|
|
558
|
+
timeout: TIMEOUT,
|
|
559
|
+
autoCleanup: false,
|
|
560
|
+
...call ? { processId: call } : {},
|
|
561
|
+
})).id,
|
|
562
|
+
receipt: async (call) => await box.getProcess(call) ? call : undefined,
|
|
563
|
+
look: async (id) => {
|
|
564
|
+
let p = await box.getProcess(id)
|
|
565
|
+
return p && {
|
|
566
|
+
...p.pid ? { pid: p.pid } : {},
|
|
567
|
+
...RUNNING.has(p.status) ? {} : { exit: { code: p.exitCode ?? null } },
|
|
568
|
+
}
|
|
569
|
+
},
|
|
570
|
+
tail: async (id, n) => {
|
|
571
|
+
let { stdout, stderr } = await box.getProcessLogs(id)
|
|
572
|
+
return [...lines(stdout), ...lines(stderr)].slice(-n)
|
|
573
|
+
},
|
|
574
|
+
kill: async (id) => {
|
|
575
|
+
await box.killProcess(id)
|
|
576
|
+
},
|
|
577
|
+
read: async (path) => (await box.readFile(path)).content,
|
|
578
|
+
stat: shellStat((script) => checked(box, `cd ${CWD} || exit 1\n${script}`)),
|
|
579
|
+
write: (path, content) => writeFile(box, path, content),
|
|
580
|
+
writeBytes: (path, bytes) => writeFile(box, path, base64(bytes), 'base64'),
|
|
581
|
+
})
|
|
582
|
+
|
|
583
|
+
let writeFile = async (
|
|
584
|
+
box: Box,
|
|
585
|
+
path: string,
|
|
586
|
+
content: string,
|
|
587
|
+
encoding?: 'base64',
|
|
588
|
+
) => {
|
|
589
|
+
let dir = path.slice(0, path.lastIndexOf('/'))
|
|
590
|
+
if (dir) await box.mkdir(dir, { recursive: true })
|
|
591
|
+
await box.writeFile(path, content, encoding ? { encoding } : undefined)
|
|
592
|
+
}
|
package/configuration.js
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { importing } from "@yaks/fp/imports";
|
|
2
|
+
import { computer, localConnector, sshConnector } from "@yaks/machine/connectors";
|
|
3
|
+
/** Adapter modules export sandboxProvider(host, options, placement). Built-in
|
|
4
|
+
* Docker/PVE bindings use only their machine row's configured local/SSH address.
|
|
5
|
+
* No missing placement becomes the server computer. */ export let resolveOptions = async (host, options = {})=>{
|
|
6
|
+
let providers = {};
|
|
7
|
+
for (let [name, entry] of Object.entries(options.providers ?? host.config?.sandboxes?.providers ?? {})){
|
|
8
|
+
if ('provider' in entry) {
|
|
9
|
+
providers[name] = entry;
|
|
10
|
+
continue;
|
|
11
|
+
}
|
|
12
|
+
let settings = entry.with ?? {};
|
|
13
|
+
let transport;
|
|
14
|
+
if (entry.machine) {
|
|
15
|
+
let [row] = await host.graph.get([
|
|
16
|
+
entry.machine
|
|
17
|
+
]);
|
|
18
|
+
if (!row?.machine) {
|
|
19
|
+
throw new Error('Sandbox computer is missing: ' + entry.machine);
|
|
20
|
+
}
|
|
21
|
+
transport = await computer(row.machine.address, {
|
|
22
|
+
local: localConnector(),
|
|
23
|
+
ssh: sshConnector({
|
|
24
|
+
identity: typeof settings.identity == 'string' ? settings.identity : undefined,
|
|
25
|
+
knownHosts: typeof settings.knownHosts == 'string' ? settings.knownHosts : undefined
|
|
26
|
+
})
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
let provider;
|
|
30
|
+
if (entry.use == '@yaks/sandbox/docker' || entry.use == '@yaks/sandbox/pve') {
|
|
31
|
+
if (!transport) {
|
|
32
|
+
throw new Error('Sandbox adapter requires an explicit computer: ' + name);
|
|
33
|
+
}
|
|
34
|
+
if (typeof settings.state != 'string') {
|
|
35
|
+
throw new Error('Sandbox adapter requires a durable host state directory');
|
|
36
|
+
}
|
|
37
|
+
if (entry.use == '@yaks/sandbox/docker') {
|
|
38
|
+
let { dockerSandboxes } = await import("./docker.js");
|
|
39
|
+
provider = dockerSandboxes(host.graph, {
|
|
40
|
+
transport,
|
|
41
|
+
state: settings.state,
|
|
42
|
+
...typeof settings.root == 'string' ? {
|
|
43
|
+
root: settings.root
|
|
44
|
+
} : {},
|
|
45
|
+
...typeof settings.image == 'string' ? {
|
|
46
|
+
image: settings.image
|
|
47
|
+
} : {}
|
|
48
|
+
});
|
|
49
|
+
} else {
|
|
50
|
+
let { pveClones } = await import("./pve.js");
|
|
51
|
+
if (typeof settings.template != 'number' || typeof settings.storage != 'string' || !Array.isArray(settings.vmidRange) || settings.vmidRange.length != 2) {
|
|
52
|
+
throw new Error('PVE binding requires template, storage and vmidRange');
|
|
53
|
+
}
|
|
54
|
+
provider = pveClones(host.graph, {
|
|
55
|
+
transport,
|
|
56
|
+
state: settings.state,
|
|
57
|
+
template: settings.template,
|
|
58
|
+
storage: settings.storage,
|
|
59
|
+
vmidRange: settings.vmidRange
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
} else {
|
|
63
|
+
// Module factories also serve Cloudflare bindings and local jail options.
|
|
64
|
+
let module = await importing(import.meta.resolve(entry.use));
|
|
65
|
+
if (typeof module.sandboxProvider != 'function') {
|
|
66
|
+
throw new Error('Sandbox module must export sandboxProvider: ' + entry.use);
|
|
67
|
+
}
|
|
68
|
+
provider = await module.sandboxProvider(host, settings, {
|
|
69
|
+
machine: entry.machine,
|
|
70
|
+
transport
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
providers[name] = {
|
|
74
|
+
provider,
|
|
75
|
+
...entry.machine ? {
|
|
76
|
+
machine: entry.machine
|
|
77
|
+
} : {}
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
return {
|
|
81
|
+
providers
|
|
82
|
+
};
|
|
83
|
+
};
|
|
84
|
+
//# sourceMappingURL=configuration.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"configuration.js","sources":["./configuration.ts"],"names":[],"mappings":"AAAA,SAAS,SAAS,gCAAqC;AAIvD,SACE,QAAQ,EACR,cAAc,EACd,YAAY,wCAC8B;AAU5C;;qDAEqD,GACrD,OAAO,IAAI,iBAAiB,OAC1B,MACA,UAAyB,CAAC,CAAC;EAE3B,IAAI,YAAyC,CAAC;EAC9C,KACE,IAAI,CAAC,MAAM,MAAM,IAAI,OAAO,OAAO,CACjC,QAAQ,SAAS,IAAI,KAAK,MAAM,EAAE,WAAW,aAAa,CAAC,GAE7D;IACA,IAAI,cAAc,OAAO;MACvB,SAAS,CAAC,KAAK,GAAG;MAClB;IACF;IACA,IAAI,WAAW,MAAM,IAAI,IAAI,CAAC;IAC9B,IAAI;IACJ,IAAI,MAAM,OAAO,EAAE;MACjB,IAAI,CAAC,IAAI,GAAG,MAAM,KAAK,KAAK,CAAC,GAAG,CAAC;QAAC,MAAM,OAAO;OAAC;MAChD,IAAI,CAAC,KAAK,SAAS;QACjB,MAAM,IAAI,MAAM,kCAAkC,MAAM,OAAO;MACjE;MACA,YAAY,MAAM,SAChB,AAAC,IAAI,OAAO,CAAU,OAAO,EAC7B;QACE,OAAO;QACP,KAAK,aAAa;UAChB,UAAU,OAAO,SAAS,QAAQ,IAAI,WAClC,SAAS,QAAQ,GACjB;UACJ,YAAY,OAAO,SAAS,UAAU,IAAI,WACtC,SAAS,UAAU,GACnB;QACN;MACF;IAEJ;IACA,IAAI;IACJ,IACE,MAAM,GAAG,IAAI,0BAA0B,MAAM,GAAG,IAAI,qBACpD;MACA,IAAI,CAAC,WAAW;QACd,MAAM,IAAI,MACR,oDAAoD;MAExD;MACA,IAAI,OAAO,SAAS,KAAK,IAAI,UAAU;QACrC,MAAM,IAAI,MACR;MAEJ;MACA,IAAI,MAAM,GAAG,IAAI,wBAAwB;QACvC,IAAI,EAAE,eAAe,EAAE,GAAG,MAAM,MAAM,CAAC;QACvC,WAAW,gBAAgB,KAAK,KAAK,EAAE;UACrC;UACA,OAAO,SAAS,KAAK;UACrB,GAAI,OAAO,SAAS,IAAI,IAAI,WAAW;YAAE,MAAM,SAAS,IAAI;UAAC,IAAI,CAAC,CAAC;UACnE,GAAI,OAAO,SAAS,KAAK,IAAI,WACzB;YAAE,OAAO,SAAS,KAAK;UAAC,IACxB,CAAC,CAAC;QACR;MACF,OAAO;QACL,IAAI,EAAE,SAAS,EAAE,GAAG,MAAM,MAAM,CAAC;QACjC,IACE,OAAO,SAAS,QAAQ,IAAI,YAC5B,OAAO,SAAS,OAAO,IAAI,YAC3B,CAAC,MAAM,OAAO,CAAC,SAAS,SAAS,KAAK,SAAS,SAAS,CAAC,MAAM,IAAI,GACnE;UACA,MAAM,IAAI,MACR;QAEJ;QACA,WAAW,UAAU,KAAK,KAAK,EAAE;UAC/B;UACA,OAAO,SAAS,KAAK;UACrB,UAAU,SAAS,QAAQ;UAC3B,SAAS,SAAS,OAAO;UACzB,WAAW,SAAS,SAAS;QAC/B;MACF;IACF,OAAO;MACL,0EAA0E;MAC1E,IAAI,SAAS,MAAM,UAAU,YAAY,OAAO,CAAC,MAAM,GAAG;MAC1D,IAAI,OAAO,OAAO,eAAe,IAAI,YAAY;QAC/C,MAAM,IAAI,MACR,iDAAiD,MAAM,GAAG;MAE9D;MACA,WAAW,MAAM,OAAO,eAAe,CAAC,MAAM,UAAU;QACtD,SAAS,MAAM,OAAO;QACtB;MACF;IACF;IACA,SAAS,CAAC,KAAK,GAAG;MAChB;MACA,GAAI,MAAM,OAAO,GAAG;QAAE,SAAS,MAAM,OAAO;MAAC,IAAI,CAAC,CAAC;IACrD;EACF;EACA,OAAO;IAAE;EAAU;AACrB,EAAC"}
|