@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.
Files changed (74) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +400 -2
  3. package/_dist/bubblewrap.d.ts +38 -0
  4. package/_dist/bubblewrap.d.ts.map +1 -0
  5. package/_dist/cloudflare.d.ts +136 -0
  6. package/_dist/cloudflare.d.ts.map +1 -0
  7. package/_dist/configuration.d.ts +13 -0
  8. package/_dist/configuration.d.ts.map +1 -0
  9. package/_dist/docker.d.ts +15 -0
  10. package/_dist/docker.d.ts.map +1 -0
  11. package/_dist/effects.d.ts +6 -0
  12. package/_dist/effects.d.ts.map +1 -0
  13. package/_dist/lifecycle.d.ts +38 -0
  14. package/_dist/lifecycle.d.ts.map +1 -0
  15. package/_dist/mod.d.ts +4 -0
  16. package/_dist/mod.d.ts.map +1 -0
  17. package/_dist/provider.d.ts +33 -0
  18. package/_dist/provider.d.ts.map +1 -0
  19. package/_dist/pve.d.ts +17 -0
  20. package/_dist/pve.d.ts.map +1 -0
  21. package/_dist/recovery.d.ts +71 -0
  22. package/_dist/recovery.d.ts.map +1 -0
  23. package/_dist/tools.d.ts +4 -0
  24. package/_dist/tools.d.ts.map +1 -0
  25. package/_dist/vocab.d.ts +5 -0
  26. package/_dist/vocab.d.ts.map +1 -0
  27. package/archive.js +60 -0
  28. package/archive.js.map +1 -0
  29. package/archive.ts +49 -0
  30. package/bubblewrap.js +495 -0
  31. package/bubblewrap.js.map +1 -0
  32. package/bubblewrap.ts +555 -0
  33. package/cloudflare.js +434 -0
  34. package/cloudflare.js.map +1 -0
  35. package/cloudflare.ts +592 -0
  36. package/configuration.js +84 -0
  37. package/configuration.js.map +1 -0
  38. package/configuration.ts +120 -0
  39. package/deno.json +1 -0
  40. package/docker.js +149 -0
  41. package/docker.js.map +1 -0
  42. package/docker.ts +206 -0
  43. package/effects.js +86 -0
  44. package/effects.js.map +1 -0
  45. package/effects.ts +78 -0
  46. package/lifecycle.js +153 -0
  47. package/lifecycle.js.map +1 -0
  48. package/lifecycle.ts +207 -0
  49. package/mod.js +6 -0
  50. package/mod.js.map +1 -0
  51. package/mod.ts +7 -0
  52. package/package.json +64 -4
  53. package/provider.js +11 -0
  54. package/provider.js.map +1 -0
  55. package/provider.ts +44 -0
  56. package/pve.js +197 -0
  57. package/pve.js.map +1 -0
  58. package/pve.ts +259 -0
  59. package/recovery-script.js +187 -0
  60. package/recovery-script.js.map +1 -0
  61. package/recovery-script.ts +186 -0
  62. package/recovery.js +231 -0
  63. package/recovery.js.map +1 -0
  64. package/recovery.ts +317 -0
  65. package/sandbox-runner.js +218 -0
  66. package/sandbox-runner.js.map +1 -0
  67. package/sandbox-runner.ts +217 -0
  68. package/tools.js +42 -0
  69. package/tools.js.map +1 -0
  70. package/tools.ts +45 -0
  71. package/vocab.js +13 -0
  72. package/vocab.js.map +1 -0
  73. package/vocab.json +180 -0
  74. package/vocab.ts +11 -0
@@ -0,0 +1,120 @@
1
+ import { importing } from '@yaks/fp/imports'
2
+ // JSON configuration binds adapters to explicit computer rows. A module may
3
+ // supply backend-specific SDK bindings without putting SDKs in generic lifecycle.
4
+ import type { Comp, Graph } from 'jsr:@yaks/graph@0.2.36'
5
+ import {
6
+ computer,
7
+ localConnector,
8
+ sshConnector,
9
+ } from '@yaks/machine/connectors'
10
+ import type { Configuration, SandboxOptions } from './lifecycle.ts'
11
+ export type { Configuration } from './lifecycle.ts'
12
+ import type { SandboxProvider } from './provider.ts'
13
+
14
+ export type ConfigurationHost = {
15
+ graph: Graph
16
+ config?: { sandboxes?: Configuration }
17
+ }
18
+
19
+ /** Adapter modules export sandboxProvider(host, options, placement). Built-in
20
+ * Docker/PVE bindings use only their machine row's configured local/SSH address.
21
+ * No missing placement becomes the server computer. */
22
+ export let resolveOptions = async (
23
+ host: ConfigurationHost,
24
+ options: Configuration = {},
25
+ ): Promise<SandboxOptions> => {
26
+ let providers: SandboxOptions['providers'] = {}
27
+ for (
28
+ let [name, entry] of Object.entries(
29
+ options.providers ?? host.config?.sandboxes?.providers ?? {},
30
+ )
31
+ ) {
32
+ if ('provider' in entry) {
33
+ providers[name] = entry
34
+ continue
35
+ }
36
+ let settings = entry.with ?? {}
37
+ let transport
38
+ if (entry.machine) {
39
+ let [row] = await host.graph.get([entry.machine])
40
+ if (!row?.machine) {
41
+ throw new Error('Sandbox computer is missing: ' + entry.machine)
42
+ }
43
+ transport = await computer(
44
+ (row.machine as Comp).address as string | undefined,
45
+ {
46
+ local: localConnector(),
47
+ ssh: sshConnector({
48
+ identity: typeof settings.identity == 'string'
49
+ ? settings.identity
50
+ : undefined,
51
+ knownHosts: typeof settings.knownHosts == 'string'
52
+ ? settings.knownHosts
53
+ : undefined,
54
+ }),
55
+ },
56
+ )
57
+ }
58
+ let provider: SandboxProvider
59
+ if (
60
+ entry.use == '@yaks/sandbox/docker' || entry.use == '@yaks/sandbox/pve'
61
+ ) {
62
+ if (!transport) {
63
+ throw new Error(
64
+ 'Sandbox adapter requires an explicit computer: ' + name,
65
+ )
66
+ }
67
+ if (typeof settings.state != 'string') {
68
+ throw new Error(
69
+ 'Sandbox adapter requires a durable host state directory',
70
+ )
71
+ }
72
+ if (entry.use == '@yaks/sandbox/docker') {
73
+ let { dockerSandboxes } = await import('./docker.js')
74
+ provider = dockerSandboxes(host.graph, {
75
+ transport,
76
+ state: settings.state,
77
+ ...(typeof settings.root == 'string' ? { root: settings.root } : {}),
78
+ ...(typeof settings.image == 'string'
79
+ ? { image: settings.image }
80
+ : {}),
81
+ })
82
+ } else {
83
+ let { pveClones } = await import('./pve.js')
84
+ if (
85
+ typeof settings.template != 'number' ||
86
+ typeof settings.storage != 'string' ||
87
+ !Array.isArray(settings.vmidRange) || settings.vmidRange.length != 2
88
+ ) {
89
+ throw new Error(
90
+ 'PVE binding requires template, storage and vmidRange',
91
+ )
92
+ }
93
+ provider = pveClones(host.graph, {
94
+ transport,
95
+ state: settings.state,
96
+ template: settings.template,
97
+ storage: settings.storage,
98
+ vmidRange: settings.vmidRange as [number, number],
99
+ })
100
+ }
101
+ } else {
102
+ // Module factories also serve Cloudflare bindings and local jail options.
103
+ let module = await importing(import.meta.resolve(entry.use))
104
+ if (typeof module.sandboxProvider != 'function') {
105
+ throw new Error(
106
+ 'Sandbox module must export sandboxProvider: ' + entry.use,
107
+ )
108
+ }
109
+ provider = await module.sandboxProvider(host, settings, {
110
+ machine: entry.machine,
111
+ transport,
112
+ })
113
+ }
114
+ providers[name] = {
115
+ provider,
116
+ ...(entry.machine ? { machine: entry.machine } : {}),
117
+ }
118
+ }
119
+ return { providers }
120
+ }
package/deno.json ADDED
@@ -0,0 +1 @@
1
+ {"publish":{"exclude":["**/*_test.ts","testing.ts"]},"name":"@yaks/sandbox","version":"0.2.36","license":"Apache-2.0","description":"Containers and jails recorded separately from computers, with provisioning intentions and confirmed disposal in the graph.","exports":{".":"./mod.ts","./vocab":"./vocab.ts","./docker":"./docker.ts","./cloudflare":"./cloudflare.ts","./recovery":"./recovery.ts","./bubblewrap":"./bubblewrap.ts","./pve":"./pve.ts","./effects":"./effects.ts","./tools":"./tools.ts","./lifecycle":"./lifecycle.ts","./configuration":"./configuration.ts"},"imports":{"@yaks/sandbox":"./mod.ts","@yaks/sandbox/vocab":"./vocab.ts","@yaks/sandbox/docker":"./docker.ts","@yaks/sandbox/cloudflare":"./cloudflare.ts","@yaks/sandbox/recovery":"./recovery.ts","@yaks/sandbox/bubblewrap":"./bubblewrap.ts","@yaks/sandbox/pve":"./pve.ts","@yaks/sandbox/effects":"./effects.ts","@yaks/sandbox/tools":"./tools.ts","@yaks/sandbox/lifecycle":"./lifecycle.ts","@yaks/sandbox/configuration":"./configuration.ts"}}
package/docker.js ADDED
@@ -0,0 +1,149 @@
1
+ // Docker Sandboxes runs on an explicitly connected computer. Its resource and
2
+ // lifecycle receipts remain there across reconnects; no local Docker is used.
3
+ import { executionWorkspace } from "@yaks/machine/execution";
4
+ import { quote } from "@yaks/machine/connectors";
5
+ import { exportPath } from "./provider.js";
6
+ let absolute = (path)=>{
7
+ if (!path.startsWith('/') || path.includes('\0') || path.split('/').includes('..')) throw new Error('Docker paths must be absolute without ..');
8
+ return path;
9
+ };
10
+ let nameOf = (ref)=>{
11
+ if (!/^[a-zA-Z0-9_-]+$/.test(ref.id)) throw new Error('Invalid sandbox id');
12
+ let name = 'yak-' + ref.id.toLowerCase().replaceAll('_', '-');
13
+ if (ref.address && ref.address != name) {
14
+ throw new Error('Sandbox address does not match its durable id');
15
+ }
16
+ return name;
17
+ };
18
+ let encoded = (text)=>{
19
+ let binary = '';
20
+ for (let byte of new TextEncoder().encode(text)){
21
+ binary += String.fromCharCode(byte);
22
+ }
23
+ return btoa(binary);
24
+ };
25
+ // Keep the script itself out of sbx argument reconstruction: the decoded
26
+ // script has no nested command-line quoting for sbx to interpret.
27
+ let inside = (name, script, root = false)=>`sbx exec ${root ? '-u root ' : ''}${quote(name)} bash -c ${quote('echo ' + encoded(script + '\n') + ' | base64 -d | bash')} </dev/null`;
28
+ /** A local sbx adapter, reached through a computer transport (usually SSH).
29
+ * No --cloud, bind mount or agent launch is implicit. sbx exec wakes existing
30
+ * storage; a missing resource is an error rather than permission to recreate. */ export let dockerSandboxes = (g, options)=>{
31
+ let root = absolute(options.root ?? '/workspace');
32
+ let state = absolute(options.state);
33
+ let control = (ref, body)=>options.transport.execute(`set -eu
34
+ umask 077
35
+ mkdir -p -- ${quote(state)}
36
+ d=${quote(state + '/' + nameOf(ref))}
37
+ mkdir -p -- "$d"
38
+ exec 9>"$d/lock"
39
+ flock -x 9
40
+ name=${quote(nameOf(ref))}
41
+ sbx ls -q </dev/null > "$d/list"
42
+ exists() { grep -Fxq -- "$name" "$d/list"; }
43
+ owned() { test -s "$d/token" && test "$(sbx exec "$name" printenv YAK_SANDBOX_TOKEN </dev/null)" = "$(cat "$d/token")"; }
44
+ ${body}`);
45
+ let present = `test -f "$d/claimed" || { echo 'Sandbox is not owned by this provider' >&2; exit 1; }
46
+ test ! -f "$d/released" || { echo 'Sandbox was disposed' >&2; exit 1; }
47
+ exists || { echo 'Sandbox is missing; refusing reconstruction' >&2; exit 1; }
48
+ owned || { echo 'Sandbox ownership changed' >&2; exit 1; }`;
49
+ let connection = async (ref, ready = true)=>{
50
+ await control(ref, present + (ready ? `\ntest -f "$d/ready" || { echo 'Sandbox preparation is incomplete' >&2; exit 1; }` : ''));
51
+ let transport = {
52
+ execute: (script)=>control(ref, `${present}\n${inside(nameOf(ref), script)}`)
53
+ };
54
+ let workspace = executionWorkspace(g, transport, {
55
+ workspace: ref.id,
56
+ root,
57
+ receipts: root + '/.yak/processes'
58
+ });
59
+ return {
60
+ workspace,
61
+ root,
62
+ address: nameOf(ref)
63
+ };
64
+ };
65
+ return {
66
+ request: async (request)=>{
67
+ if (request.from && !options.prepare) {
68
+ throw new Error('Docker commit preparation is not configured');
69
+ }
70
+ let image = request.image ?? options.image;
71
+ let spec = JSON.stringify({
72
+ from: request.from,
73
+ image,
74
+ root
75
+ });
76
+ await control(request, `test ! -f "$d/released" || { echo 'Sandbox was disposed' >&2; exit 1; }
77
+ if test -f "$d/claimed"; then
78
+ test "$(cat "$d/spec")" = ${quote(spec)} || { echo 'Sandbox request changed' >&2; exit 1; }
79
+ exists || { echo 'Interrupted or missing sandbox; refusing reconstruction' >&2; exit 1; }
80
+ else
81
+ if exists; then echo 'Sandbox name already exists without ownership' >&2; exit 1; fi
82
+ printf '%s' ${quote(spec)} > "$d/spec"
83
+ cat /proc/sys/kernel/random/uuid > "$d/token"
84
+ touch "$d/claimed"
85
+ sbx create --name "$name" --no-progress --env ${'"YAK_SANDBOX_TOKEN=$(cat "$d/token")"'}${image ? ' --template ' + quote(image) : ''} shell </dev/null
86
+ fi`);
87
+ // The shell template's default user need not own /. Create only the
88
+ // configured root as root, then give that directory to the sandbox user.
89
+ await control(request, `${present}
90
+ owner=$(sbx exec "$name" id -u </dev/null):$(sbx exec "$name" id -g </dev/null)
91
+ case "$owner" in *[!0-9:]*|:*) echo 'Invalid sandbox uid/gid' >&2; exit 1;; esac
92
+ ${inside(nameOf(request), `mkdir -p -- ${quote(root)}`, true)}
93
+ sbx exec -u root "$name" chown "$owner" ${quote(root)} </dev/null`);
94
+ let connected = await connection(request, false);
95
+ await connected.workspace.write(root + '/.yak/ready', '');
96
+ // A completion marker is separate from creation: interrupted preparation
97
+ // may be retried, so the supplied preparation must itself be idempotent.
98
+ if (request.from) {
99
+ let prepared = await control(request, `if test -f "$d/prepared"; then printf yes; fi`);
100
+ if (prepared != 'yes') {
101
+ await options.prepare(request.from, connected.workspace, root);
102
+ await control(request, `${present}\ntouch "$d/prepared"`);
103
+ }
104
+ }
105
+ await control(request, `${present}\ntouch "$d/ready"`);
106
+ return connected;
107
+ },
108
+ connect: (ref)=>connection(ref),
109
+ dispose: async (ref)=>{
110
+ await control(ref, `if test -f "$d/released"; then exit 0; fi
111
+ test -f "$d/claimed" || { echo 'Sandbox is not owned by this provider' >&2; exit 1; }
112
+ if exists; then owned || { echo 'Sandbox ownership changed' >&2; exit 1; }; sbx stop "$name" </dev/null; fi
113
+ touch "$d/released"`);
114
+ },
115
+ restore: async (ref)=>{
116
+ await control(ref, `test -f "$d/claimed" || { echo 'Sandbox is not owned by this provider' >&2; exit 1; }
117
+ exists || { echo 'Sandbox is missing; refusing reconstruction' >&2; exit 1; }
118
+ owned || { echo 'Sandbox ownership changed' >&2; exit 1; }
119
+ rm -f -- "$d/released"`);
120
+ },
121
+ export: async function*(ref, paths) {
122
+ await control(ref, present);
123
+ for (let path of paths){
124
+ exportPath(path);
125
+ // Open relative components by directory descriptor, rejecting symlinks
126
+ // and special files even if a sandbox process races the export.
127
+ let script = `import os, stat, base64
128
+ fd = os.open(${JSON.stringify(root)}, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
129
+ try:
130
+ for part in ${JSON.stringify(path.split('/'))}:
131
+ next = os.open(part, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=fd)
132
+ os.close(fd)
133
+ fd = next
134
+ if not stat.S_ISREG(os.fstat(fd).st_mode): raise ValueError('Export is not a regular file')
135
+ with os.fdopen(fd, 'rb') as file:
136
+ fd = -1
137
+ print(base64.b64encode(file.read()).decode())
138
+ finally:
139
+ if fd >= 0: os.close(fd)`;
140
+ let data = await control(ref, `${present}\n${inside(nameOf(ref), 'python3 -I -c ' + quote(script))}`);
141
+ yield {
142
+ path,
143
+ bytes: Uint8Array.from(atob(data.replaceAll(/\s/g, '')), (c)=>c.charCodeAt(0))
144
+ };
145
+ }
146
+ }
147
+ };
148
+ };
149
+ //# sourceMappingURL=docker.js.map
package/docker.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"docker.js","sources":["./docker.ts"],"names":[],"mappings":"AAAA,8EAA8E;AAC9E,8EAA8E;AAG9E,SAAS,kBAAkB,uCAA4C;AACvE,SAAS,KAAK,wCAA6C;AAC3D,SACE,UAAU,wBAIU;AAWtB,IAAI,WAAW,CAAC;EACd,IACE,CAAC,KAAK,UAAU,CAAC,QAAQ,KAAK,QAAQ,CAAC,SACvC,KAAK,KAAK,CAAC,KAAK,QAAQ,CAAC,OACzB,MAAM,IAAI,MAAM;EAClB,OAAO;AACT;AACA,IAAI,SAAS,CAAC;EACZ,IAAI,CAAC,mBAAmB,IAAI,CAAC,IAAI,EAAE,GAAG,MAAM,IAAI,MAAM;EACtD,IAAI,OAAO,SAAS,IAAI,EAAE,CAAC,WAAW,GAAG,UAAU,CAAC,KAAK;EACzD,IAAI,IAAI,OAAO,IAAI,IAAI,OAAO,IAAI,MAAM;IACtC,MAAM,IAAI,MAAM;EAClB;EACA,OAAO;AACT;AACA,IAAI,UAAU,CAAC;EACb,IAAI,SAAS;EACb,KAAK,IAAI,QAAQ,IAAI,cAAc,MAAM,CAAC,MAAO;IAC/C,UAAU,OAAO,YAAY,CAAC;EAChC;EACA,OAAO,KAAK;AACd;AACA,yEAAyE;AACzE,kEAAkE;AAClE,IAAI,S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M;UACJ;UACA,OAAO,WAAW,IAAI,CACpB,KAAK,KAAK,UAAU,CAAC,OAAO,MAC5B,CAAC,IAAM,EAAE,UAAU,CAAC;QAExB;MACF;IACF;EACF;AACF,EAAC"}
package/docker.ts ADDED
@@ -0,0 +1,206 @@
1
+ // Docker Sandboxes runs on an explicitly connected computer. Its resource and
2
+ // lifecycle receipts remain there across reconnects; no local Docker is used.
3
+ import type { Graph } from 'jsr:@yaks/graph@0.2.36'
4
+ import type { ComputerTransport, Workspace } from 'jsr:@yaks/machine@0.2.36'
5
+ import { executionWorkspace } from '@yaks/machine/execution'
6
+ import { quote } from '@yaks/machine/connectors'
7
+ import {
8
+ exportPath,
9
+ type SandboxProvider,
10
+ type SandboxRef,
11
+ type SandboxRequest,
12
+ } from './provider.js'
13
+
14
+ /** Host state is outside the sandbox so the trash receipt and retained
15
+ * sandbox survive disposal; restoration reconnects the same writable storage. */
16
+ export type DockerOptions = {
17
+ transport: ComputerTransport
18
+ state: string
19
+ root?: string
20
+ image?: string
21
+ prepare?: (from: string, workspace: Workspace, root: string) => Promise<void>
22
+ }
23
+ let absolute = (path: string) => {
24
+ if (
25
+ !path.startsWith('/') || path.includes('\0') ||
26
+ path.split('/').includes('..')
27
+ ) throw new Error('Docker paths must be absolute without ..')
28
+ return path
29
+ }
30
+ let nameOf = (ref: SandboxRef) => {
31
+ if (!/^[a-zA-Z0-9_-]+$/.test(ref.id)) throw new Error('Invalid sandbox id')
32
+ let name = 'yak-' + ref.id.toLowerCase().replaceAll('_', '-')
33
+ if (ref.address && ref.address != name) {
34
+ throw new Error('Sandbox address does not match its durable id')
35
+ }
36
+ return name
37
+ }
38
+ let encoded = (text: string) => {
39
+ let binary = ''
40
+ for (let byte of new TextEncoder().encode(text)) {
41
+ binary += String.fromCharCode(byte)
42
+ }
43
+ return btoa(binary)
44
+ }
45
+ // Keep the script itself out of sbx argument reconstruction: the decoded
46
+ // script has no nested command-line quoting for sbx to interpret.
47
+ let inside = (name: string, script: string, root = false) =>
48
+ `sbx exec ${root ? '-u root ' : ''}${quote(name)} bash -c ${
49
+ quote('echo ' + encoded(script + '\n') + ' | base64 -d | bash')
50
+ } </dev/null`
51
+
52
+ /** A local sbx adapter, reached through a computer transport (usually SSH).
53
+ * No --cloud, bind mount or agent launch is implicit. sbx exec wakes existing
54
+ * storage; a missing resource is an error rather than permission to recreate. */
55
+ export let dockerSandboxes = (
56
+ g: Graph,
57
+ options: DockerOptions,
58
+ ): SandboxProvider => {
59
+ let root = absolute(options.root ?? '/workspace')
60
+ let state = absolute(options.state)
61
+ let control = (ref: SandboxRef, body: string) =>
62
+ options.transport.execute(`set -eu
63
+ umask 077
64
+ mkdir -p -- ${quote(state)}
65
+ d=${quote(state + '/' + nameOf(ref))}
66
+ mkdir -p -- "$d"
67
+ exec 9>"$d/lock"
68
+ flock -x 9
69
+ name=${quote(nameOf(ref))}
70
+ sbx ls -q </dev/null > "$d/list"
71
+ exists() { grep -Fxq -- "$name" "$d/list"; }
72
+ owned() { test -s "$d/token" && test "$(sbx exec "$name" printenv YAK_SANDBOX_TOKEN </dev/null)" = "$(cat "$d/token")"; }
73
+ ${body}`)
74
+ let present =
75
+ `test -f "$d/claimed" || { echo 'Sandbox is not owned by this provider' >&2; exit 1; }
76
+ test ! -f "$d/released" || { echo 'Sandbox was disposed' >&2; exit 1; }
77
+ exists || { echo 'Sandbox is missing; refusing reconstruction' >&2; exit 1; }
78
+ owned || { echo 'Sandbox ownership changed' >&2; exit 1; }`
79
+ let connection = async (ref: SandboxRef, ready = true) => {
80
+ await control(
81
+ ref,
82
+ present +
83
+ (ready
84
+ ? `\ntest -f "$d/ready" || { echo 'Sandbox preparation is incomplete' >&2; exit 1; }`
85
+ : ''),
86
+ )
87
+ let transport: ComputerTransport = {
88
+ execute: (script) =>
89
+ control(ref, `${present}\n${inside(nameOf(ref), script)}`),
90
+ }
91
+ let workspace = executionWorkspace(g, transport, {
92
+ workspace: ref.id,
93
+ root,
94
+ receipts: root + '/.yak/processes',
95
+ })
96
+ return { workspace, root, address: nameOf(ref) }
97
+ }
98
+ return {
99
+ request: async (request: SandboxRequest) => {
100
+ if (request.from && !options.prepare) {
101
+ throw new Error('Docker commit preparation is not configured')
102
+ }
103
+ let image = request.image ?? options.image
104
+ let spec = JSON.stringify({ from: request.from, image, root })
105
+ await control(
106
+ request,
107
+ `test ! -f "$d/released" || { echo 'Sandbox was disposed' >&2; exit 1; }
108
+ if test -f "$d/claimed"; then
109
+ test "$(cat "$d/spec")" = ${
110
+ quote(spec)
111
+ } || { echo 'Sandbox request changed' >&2; exit 1; }
112
+ exists || { echo 'Interrupted or missing sandbox; refusing reconstruction' >&2; exit 1; }
113
+ else
114
+ if exists; then echo 'Sandbox name already exists without ownership' >&2; exit 1; fi
115
+ printf '%s' ${quote(spec)} > "$d/spec"
116
+ cat /proc/sys/kernel/random/uuid > "$d/token"
117
+ touch "$d/claimed"
118
+ sbx create --name "$name" --no-progress --env ${'"YAK_SANDBOX_TOKEN=$(cat "$d/token")"'}${
119
+ image ? ' --template ' + quote(image) : ''
120
+ } shell </dev/null
121
+ fi`,
122
+ )
123
+ // The shell template's default user need not own /. Create only the
124
+ // configured root as root, then give that directory to the sandbox user.
125
+ await control(
126
+ request,
127
+ `${present}
128
+ owner=$(sbx exec "$name" id -u </dev/null):$(sbx exec "$name" id -g </dev/null)
129
+ case "$owner" in *[!0-9:]*|:*) echo 'Invalid sandbox uid/gid' >&2; exit 1;; esac
130
+ ${inside(nameOf(request), `mkdir -p -- ${quote(root)}`, true)}
131
+ sbx exec -u root "$name" chown "$owner" ${quote(root)} </dev/null`,
132
+ )
133
+ let connected = await connection(request, false)
134
+ await connected.workspace.write(root + '/.yak/ready', '')
135
+ // A completion marker is separate from creation: interrupted preparation
136
+ // may be retried, so the supplied preparation must itself be idempotent.
137
+ if (request.from) {
138
+ let prepared = await control(
139
+ request,
140
+ `if test -f "$d/prepared"; then printf yes; fi`,
141
+ )
142
+ if (prepared != 'yes') {
143
+ await options.prepare!(request.from, connected.workspace, root)
144
+ await control(request, `${present}\ntouch "$d/prepared"`)
145
+ }
146
+ }
147
+ await control(request, `${present}\ntouch "$d/ready"`)
148
+ return connected
149
+ },
150
+ connect: (ref) => connection(ref),
151
+ dispose: async (ref) => {
152
+ await control(
153
+ ref,
154
+ `if test -f "$d/released"; then exit 0; fi
155
+ test -f "$d/claimed" || { echo 'Sandbox is not owned by this provider' >&2; exit 1; }
156
+ if exists; then owned || { echo 'Sandbox ownership changed' >&2; exit 1; }; sbx stop "$name" </dev/null; fi
157
+ touch "$d/released"`,
158
+ )
159
+ },
160
+ restore: async (ref) => {
161
+ await control(
162
+ ref,
163
+ `test -f "$d/claimed" || { echo 'Sandbox is not owned by this provider' >&2; exit 1; }
164
+ exists || { echo 'Sandbox is missing; refusing reconstruction' >&2; exit 1; }
165
+ owned || { echo 'Sandbox ownership changed' >&2; exit 1; }
166
+ rm -f -- "$d/released"`,
167
+ )
168
+ },
169
+ export: async function* (ref, paths) {
170
+ await control(ref, present)
171
+ for (let path of paths) {
172
+ exportPath(path)
173
+ // Open relative components by directory descriptor, rejecting symlinks
174
+ // and special files even if a sandbox process races the export.
175
+ let script = `import os, stat, base64
176
+ fd = os.open(${
177
+ JSON.stringify(root)
178
+ }, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
179
+ try:
180
+ for part in ${JSON.stringify(path.split('/'))}:
181
+ next = os.open(part, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=fd)
182
+ os.close(fd)
183
+ fd = next
184
+ if not stat.S_ISREG(os.fstat(fd).st_mode): raise ValueError('Export is not a regular file')
185
+ with os.fdopen(fd, 'rb') as file:
186
+ fd = -1
187
+ print(base64.b64encode(file.read()).decode())
188
+ finally:
189
+ if fd >= 0: os.close(fd)`
190
+ let data = await control(
191
+ ref,
192
+ `${present}\n${
193
+ inside(nameOf(ref), 'python3 -I -c ' + quote(script))
194
+ }`,
195
+ )
196
+ yield {
197
+ path,
198
+ bytes: Uint8Array.from(
199
+ atob(data.replaceAll(/\s/g, '')),
200
+ (c) => c.charCodeAt(0),
201
+ ),
202
+ }
203
+ }
204
+ },
205
+ }
206
+ }
package/effects.js ADDED
@@ -0,0 +1,86 @@
1
+ // Provisioning runs only after the durable intention has committed.
2
+ import { token } from "@yaks/graph";
3
+ import { sandboxBinding, sandboxRef } from "./lifecycle.js";
4
+ /** At-least-once request uses the preallocated identity; adapter request must
5
+ * reconnect an existing resource, and must never replace a destroyed resource. */ export let provisioning = ({ providers })=>async (event, tx, write, attempt)=>{
6
+ let row = (await tx.get([
7
+ event.entity.eid
8
+ ]))[0];
9
+ if (!row?.sandbox || !row.pending || row.released || row.failed) return;
10
+ let sandbox = row.sandbox;
11
+ let workspace = row.workspace;
12
+ let guard = {
13
+ sandbox: {
14
+ provider: token(sandbox.provider),
15
+ address: sandbox.address == null ? null : token(sandbox.address),
16
+ from: sandbox.from == null ? null : token(sandbox.from),
17
+ image: sandbox.image == null ? null : token(sandbox.image)
18
+ },
19
+ workspace: {
20
+ machine: workspace.machine == null ? null : token(workspace.machine),
21
+ root: workspace.root == null ? null : token(workspace.root)
22
+ },
23
+ released: {
24
+ at: null
25
+ }
26
+ };
27
+ try {
28
+ let binding = sandboxBinding(row, providers);
29
+ if (!binding.provider.request) {
30
+ throw new Error('Sandbox provider cannot create');
31
+ }
32
+ let connection = await binding.provider.request({
33
+ ...sandboxRef(row),
34
+ ...sandbox.from ? {
35
+ from: String(sandbox.from)
36
+ } : {},
37
+ ...sandbox.image ? {
38
+ image: String(sandbox.image)
39
+ } : {}
40
+ });
41
+ let root = connection.root;
42
+ if (!root || !root.startsWith('/')) {
43
+ throw new Error('Sandbox provider returned no absolute workspace root');
44
+ }
45
+ // Retry storage without replaying the external request.
46
+ let complete = async ()=>await write([
47
+ {
48
+ entity: row.entity,
49
+ $was: guard,
50
+ workspace: {
51
+ root
52
+ },
53
+ ...connection.address ? {
54
+ sandbox: {
55
+ address: connection.address
56
+ }
57
+ } : {},
58
+ pending: null,
59
+ failed: null
60
+ }
61
+ ]);
62
+ if (attempt?.retry) await attempt.retry(complete);
63
+ else await complete();
64
+ } catch (error) {
65
+ if (!attempt || attempt.last()) {
66
+ await write([
67
+ {
68
+ entity: row.entity,
69
+ $was: guard,
70
+ pending: null,
71
+ failed: {
72
+ reason: String(error)
73
+ }
74
+ }
75
+ ]);
76
+ }
77
+ throw error;
78
+ }
79
+ };
80
+ /** Resolve adapters only when an effect runs, after the graph is open. */ export let effects = (host, options = {})=>({
81
+ sandbox_provision: async (...args)=>{
82
+ let { resolveOptions } = await import("./configuration.js");
83
+ return await provisioning(await resolveOptions(host, options))(...args);
84
+ }
85
+ });
86
+ //# sourceMappingURL=effects.js.map
package/effects.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"effects.js","sources":["./effects.ts"],"names":[],"mappings":"AAAA,oEAAoE;AAEpE,SAAoB,KAAK,2BAAgC;AACzD,SAAS,cAAc,EAAuB,UAAU,yBAAwB;AAEhF;gFACgF,GAChF,OAAO,IAAI,eACT,CAAC,EAAE,SAAS,EAAkB,GAC9B,OAAO,OAAO,IAAI,OAAO;IACvB,IAAI,MAAM,CAAC,MAAM,GAAG,GAAG,CAAC;MAAC,MAAM,MAAM,CAAC,GAAG;KAAC,CAAC,CAAC,CAAC,EAAE;IAC/C,IAAI,CAAC,KAAK,WAAW,CAAC,IAAI,OAAO,IAAI,IAAI,QAAQ,IAAI,IAAI,MAAM,EAAE;IACjE,IAAI,UAAU,IAAI,OAAO;IACzB,IAAI,YAAY,IAAI,SAAS;IAC7B,IAAI,QAAQ;MACV,SAAS;QACP,UAAU,MAAM,QAAQ,QAAQ;QAChC,SAAS,QAAQ,OAAO,IAAI,OAAO,OAAO,MAAM,QAAQ,OAAO;QAC/D,MAAM,QAAQ,IAAI,IAAI,OAAO,OAAO,MAAM,QAAQ,IAAI;QACtD,OAAO,QAAQ,KAAK,IAAI,OAAO,OAAO,MAAM,QAAQ,KAAK;MAC3D;MACA,WA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,MACA,UAAsD,CAAC,CAAC,GAC3C,CAAC;IACd,mBAAmB,OAAO,GAAG;MAC3B,IAAI,EAAE,cAAc,EAAE,GAAG,MAAM,MAAM,CAAC;MACtC,OAAO,MAAM,aAAa,MAAM,eAAe,MAAM,aAAa;IACpE;EACF,CAAC,EAAC"}
package/effects.ts ADDED
@@ -0,0 +1,78 @@
1
+ // Provisioning runs only after the durable intention has committed.
2
+ import type { Handler, Handlers } from 'jsr:@yaks/effects@0.2.36'
3
+ import { type Comp, token } from '@yaks/graph'
4
+ import { sandboxBinding, type SandboxOptions, sandboxRef } from './lifecycle.js'
5
+
6
+ /** At-least-once request uses the preallocated identity; adapter request must
7
+ * reconnect an existing resource, and must never replace a destroyed resource. */
8
+ export let provisioning =
9
+ ({ providers }: SandboxOptions): Handler =>
10
+ async (event, tx, write, attempt) => {
11
+ let row = (await tx.get([event.entity.eid]))[0]
12
+ if (!row?.sandbox || !row.pending || row.released || row.failed) return
13
+ let sandbox = row.sandbox as Comp
14
+ let workspace = row.workspace as Comp
15
+ let guard = {
16
+ sandbox: {
17
+ provider: token(sandbox.provider),
18
+ address: sandbox.address == null ? null : token(sandbox.address),
19
+ from: sandbox.from == null ? null : token(sandbox.from),
20
+ image: sandbox.image == null ? null : token(sandbox.image),
21
+ },
22
+ workspace: {
23
+ machine: workspace.machine == null ? null : token(workspace.machine),
24
+ root: workspace.root == null ? null : token(workspace.root),
25
+ },
26
+ released: { at: null },
27
+ }
28
+ try {
29
+ let binding = sandboxBinding(row, providers)
30
+ if (!binding.provider.request) {
31
+ throw new Error('Sandbox provider cannot create')
32
+ }
33
+ let connection = await binding.provider.request({
34
+ ...sandboxRef(row),
35
+ ...(sandbox.from ? { from: String(sandbox.from) } : {}),
36
+ ...(sandbox.image ? { image: String(sandbox.image) } : {}),
37
+ })
38
+ let root = connection.root
39
+ if (!root || !root.startsWith('/')) {
40
+ throw new Error('Sandbox provider returned no absolute workspace root')
41
+ }
42
+ // Retry storage without replaying the external request.
43
+ let complete = async () =>
44
+ await write([{
45
+ entity: row.entity,
46
+ $was: guard,
47
+ workspace: { root },
48
+ ...(connection.address
49
+ ? { sandbox: { address: connection.address } }
50
+ : {}),
51
+ pending: null,
52
+ failed: null,
53
+ }])
54
+ if (attempt?.retry) await attempt.retry(complete)
55
+ else await complete()
56
+ } catch (error) {
57
+ if (!attempt || attempt.last()) {
58
+ await write([{
59
+ entity: row.entity,
60
+ $was: guard,
61
+ pending: null,
62
+ failed: { reason: String(error) },
63
+ }])
64
+ }
65
+ throw error
66
+ }
67
+ }
68
+
69
+ /** Resolve adapters only when an effect runs, after the graph is open. */
70
+ export let effects = (
71
+ host: import('./configuration.js').ConfigurationHost,
72
+ options: import('./configuration.js').Configuration = {},
73
+ ): Handlers => ({
74
+ sandbox_provision: async (...args) => {
75
+ let { resolveOptions } = await import('./configuration.js')
76
+ return await provisioning(await resolveOptions(host, options))(...args)
77
+ },
78
+ })