@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
package/pve.js ADDED
@@ -0,0 +1,197 @@
1
+ // PVE LXC clones on an explicitly connected PVE computer. Host receipts reserve
2
+ // one deterministic VMID; the container's description proves its ownership.
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 == '/' || path.includes('\0') || path.split('/').some((p)=>p == '.' || p == '..')) throw new Error('PVE receipt directory must be absolute without . or ..');
8
+ let normalized = path.replace(/\/+$/, '');
9
+ if (!normalized) throw new Error('PVE receipt directory cannot be root');
10
+ return normalized;
11
+ };
12
+ let vmid = (n)=>Number.isSafeInteger(n) && n >= 100 && n <= 999999999;
13
+ /** Linked clones only, on the template storage. The template needs bash, flock, setsid, base64, python3
14
+ * and /proc for executionWorkspace. Missing/ambiguous clones are never rebuilt.
15
+ * A hash collision refuses the request rather than silently choosing a new id.
16
+ * The configured state directory and VMID grant must remain stable on reconnect.
17
+ * Host locks coordinate this adapter, not unrelated PVE administrators. */ export let pveClones = (g, options)=>{
18
+ let state = absolute(options.state);
19
+ let [first, last] = options.vmidRange;
20
+ if (!vmid(first) || !vmid(last) || last < first || !vmid(options.template) || options.template >= first && options.template <= last) {
21
+ throw new Error('PVE requires a template outside an explicit valid VMID range');
22
+ }
23
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(options.storage)) {
24
+ throw new Error('PVE requires an explicit storage id');
25
+ }
26
+ let root = '/workspace';
27
+ let address = (ref)=>{
28
+ if (!/^[a-zA-Z0-9_-]+$/.test(ref.id)) throw new Error('Invalid sandbox id');
29
+ let hash = 2166136261;
30
+ for (let c of ref.id){
31
+ hash = Math.imul(hash ^ c.charCodeAt(0), 16777619) >>> 0;
32
+ }
33
+ let value = String(first + hash % (last - first + 1));
34
+ if (ref.address != null && ref.address != value) {
35
+ throw new Error('PVE address does not match its reserved VMID');
36
+ }
37
+ return value;
38
+ };
39
+ // All pct failures propagate, including list/config permission or connection
40
+ // failures. Only a successful list establishes that a container is absent.
41
+ let control = (ref, body)=>{
42
+ let target = address(ref);
43
+ return options.transport.execute(`set -eu
44
+ umask 077
45
+ mkdir -p -- ${quote(state)}
46
+ exec 9>${quote(state + '/lock')}
47
+ flock -x 9
48
+ vmid=${quote(target)}
49
+ d=${quote(state + '/vmids/' + target)}
50
+ mkdir -p -- "$d"
51
+ id=${quote(ref.id)}
52
+ pct list </dev/null > "$d/list"
53
+ exists() { awk 'NR > 1 { print $1 }' "$d/list" | grep -Fxq -- "$vmid"; }
54
+ claimed() {
55
+ test -f "$d/owner" && test "$(cat "$d/owner")" = "$id" || { echo 'PVE VMID is not owned by this sandbox' >&2; exit 1; }
56
+ }
57
+ owned() {
58
+ test -s "$d/token" || { echo 'PVE ownership receipt is missing' >&2; exit 1; }
59
+ pct config "$vmid" </dev/null > "$d/config"
60
+ grep -Fxq -- "description: $(cat "$d/token")" "$d/config" || { echo 'PVE container ownership changed' >&2; exit 1; }
61
+ if grep -q '^lock:' "$d/config"; then echo 'PVE container is locked' >&2; exit 1; fi
62
+ }
63
+ ${body}`);
64
+ };
65
+ let present = `claimed
66
+ test ! -f "$d/released" || { echo 'PVE sandbox was disposed' >&2; exit 1; }
67
+ test -f "$d/created" || { echo 'PVE clone creation is incomplete; refusing reconstruction' >&2; exit 1; }
68
+ exists || { echo 'PVE clone is missing; refusing reconstruction' >&2; exit 1; }
69
+ owned`;
70
+ let ready = `${present}
71
+ test -f "$d/ready" || { echo 'PVE sandbox preparation is incomplete' >&2; exit 1; }`;
72
+ let running = `pct status "$vmid" </dev/null > "$d/status"
73
+ grep -Fxq 'status: running' "$d/status" || { echo 'PVE sandbox is not running' >&2; exit 1; }`;
74
+ let inside = (ref, script, prepared = true)=>control(ref, `${prepared ? ready : present}
75
+ ${running}
76
+ pct exec "$vmid" --keep-env 0 -- bash -c ${quote(script)} </dev/null`);
77
+ let connection = async (ref, prepared = true)=>{
78
+ await control(ref, `${prepared ? ready : present}\n${running}`);
79
+ let transport = {
80
+ execute: (script)=>inside(ref, script, prepared)
81
+ };
82
+ return {
83
+ workspace: executionWorkspace(g, transport, {
84
+ workspace: ref.id,
85
+ root,
86
+ receipts: root + '/.yak/processes'
87
+ }),
88
+ root,
89
+ address: address(ref)
90
+ };
91
+ };
92
+ return {
93
+ request: async (request)=>{
94
+ if (request.image != null) {
95
+ throw new Error('PVE image is unsupported; configure an explicit template');
96
+ }
97
+ if (request.from != null && !options.prepare) {
98
+ throw new Error('PVE commit preparation is not configured');
99
+ }
100
+ let spec = JSON.stringify({
101
+ template: options.template,
102
+ storage: options.storage,
103
+ vmidRange: options.vmidRange,
104
+ from: request.from
105
+ });
106
+ // Description is set by clone itself, not by a later command that could
107
+ // accidentally adopt a foreign container after a failed clone.
108
+ let token = 'yak-sandbox:' + request.id + ':' + crypto.randomUUID();
109
+ await control(request, `if test -f "$d/owner"; then
110
+ claimed
111
+ test ! -f "$d/released" || { echo 'PVE sandbox was disposed' >&2; exit 1; }
112
+ test "$(cat "$d/spec")" = ${quote(spec)} || { echo 'PVE request changed' >&2; exit 1; }
113
+ else
114
+ if exists; then echo 'PVE VMID already exists without ownership' >&2; exit 1; fi
115
+ pct config ${options.template} </dev/null > "$d/template"
116
+ grep -Fxq 'template: 1' "$d/template" || { echo 'PVE source is not a template' >&2; exit 1; }
117
+ awk -F ': ' -v storage=${quote(options.storage)} '
118
+ $1 == "rootfs" || $1 ~ /^mp[0-9]+$/ {
119
+ volume=$2; sub(/,.*/, "", volume); sub(/^volume=/, "", volume)
120
+ if (index(volume, storage ":") != 1) bad=1
121
+ if ($1 == "rootfs") root=1
122
+ }
123
+ END { exit (bad || !root) }
124
+ ' "$d/template" || { echo 'PVE linked clone requires every template volume on configured storage' >&2; exit 1; }
125
+ printf '%s' ${quote(spec)} > "$d/spec"
126
+ printf '%s' ${quote(token)} > "$d/token"
127
+ printf '%s' "$id" > "$d/owner.tmp"
128
+ mv -- "$d/owner.tmp" "$d/owner"
129
+ pct clone ${options.template} "$vmid" --full 0 --description "$(cat "$d/token")" </dev/null > /dev/null
130
+ owned
131
+ touch "$d/created"
132
+ fi
133
+ ${present.replace('exists ||', 'pct list </dev/null > "$d/list"\nexists ||')}
134
+ pct status "$vmid" </dev/null > "$d/status"
135
+ if grep -Fxq 'status: stopped' "$d/status"; then pct start "$vmid" </dev/null > /dev/null; fi
136
+ ${running}`);
137
+ let connected = await connection(request, false);
138
+ await inside(request, `mkdir -p -- ${quote(root + '/.yak/processes')}`, false);
139
+ let prepared = await control(request, `${present}\nif test -f "$d/ready"; then printf yes; fi`);
140
+ if (prepared != 'yes') {
141
+ if (request.from != null) {
142
+ await options.prepare(request.from, connected.workspace, root);
143
+ }
144
+ await control(request, `${present}\ntouch "$d/ready"`);
145
+ }
146
+ return await connection(request);
147
+ },
148
+ connect: (ref)=>connection(ref),
149
+ dispose: async (ref)=>{
150
+ await control(ref, `claimed
151
+ if test -f "$d/released"; then exit 0; fi
152
+ if exists; then
153
+ owned
154
+ pct status "$vmid" </dev/null > "$d/status"
155
+ if grep -Fxq 'status: running' "$d/status"; then pct stop "$vmid" </dev/null > /dev/null; fi
156
+ fi
157
+ touch "$d/released"`);
158
+ },
159
+ restore: async (ref)=>{
160
+ await control(ref, `claimed
161
+ exists || { echo 'PVE clone is missing; refusing reconstruction' >&2; exit 1; }
162
+ owned
163
+ pct status "$vmid" </dev/null > "$d/status"
164
+ if grep -Fxq 'status: stopped' "$d/status"; then pct start "$vmid" </dev/null > /dev/null; fi
165
+ rm -f -- "$d/released"`);
166
+ },
167
+ export: async function*(ref, paths) {
168
+ // Validate the whole request before issuing any remote read.
169
+ for (let path of paths)exportPath(path);
170
+ for (let path of paths){
171
+ let encoded = await inside(ref, `python3 -c ${quote(`import os, sys, base64
172
+ parts = sys.argv[1].split('/')
173
+ fd = os.open('/workspace', os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
174
+ try:
175
+ for i, part in enumerate(parts):
176
+ flags = os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK
177
+ if i < len(parts) - 1:
178
+ flags |= os.O_DIRECTORY
179
+ child = os.open(part, flags, dir_fd=fd)
180
+ os.close(fd)
181
+ fd = child
182
+ import stat
183
+ if not stat.S_ISREG(os.fstat(fd).st_mode):
184
+ raise ValueError('Export requires a regular file')
185
+ with os.fdopen(os.dup(fd), 'rb') as file:
186
+ sys.stdout.write(base64.b64encode(file.read()).decode('ascii'))
187
+ finally:
188
+ os.close(fd)`)} ${quote(path)}`);
189
+ yield {
190
+ path,
191
+ bytes: Uint8Array.from(atob(encoded.replaceAll(/\s/g, '')), (c)=>c.charCodeAt(0))
192
+ };
193
+ }
194
+ }
195
+ };
196
+ };
197
+ //# sourceMappingURL=pve.js.map
package/pve.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pve.js","sources":["./pve.ts"],"names":[],"mappings":"AAAA,gFAAgF;AAChF,4EAA4E;AAG5E,SAAS,kBAAkB,uCAA4C;AAC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,MAAM,OAAO;QAEnB,MAAM;UACJ;UACA,OAAO,WAAW,IAAI,CACpB,KAAK,QAAQ,UAAU,CAAC,OAAO,MAC/B,CAAC,IAAM,EAAE,UAAU,CAAC;QAExB;MACF;IACF;EACF;AACF,EAAC"}
package/pve.ts ADDED
@@ -0,0 +1,259 @@
1
+ // PVE LXC clones on an explicitly connected PVE computer. Host receipts reserve
2
+ // one deterministic VMID; the container's description proves its ownership.
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
+ } from './provider.js'
12
+
13
+ export type PveOptions = {
14
+ /** Usually the transport returned by the configured PVE SSH connector. */
15
+ transport: ComputerTransport
16
+ /** Private, persistent directory on PVE, outside every clone. */
17
+ state: string
18
+ template: number
19
+ /** Every template volume must already reside on this storage. */
20
+ storage: string
21
+ /** Inclusive range granted for these clones, excluding the template. */
22
+ vmidRange: readonly [number, number]
23
+ /** Materialize the initial commit; must tolerate retries after interruption. */
24
+ prepare?: (from: string, workspace: Workspace, root: string) => Promise<void>
25
+ }
26
+
27
+ let absolute = (path: string) => {
28
+ if (
29
+ !path.startsWith('/') || path == '/' || path.includes('\0') ||
30
+ path.split('/').some((p) => p == '.' || p == '..')
31
+ ) throw new Error('PVE receipt directory must be absolute without . or ..')
32
+ let normalized = path.replace(/\/+$/, '')
33
+ if (!normalized) throw new Error('PVE receipt directory cannot be root')
34
+ return normalized
35
+ }
36
+ let vmid = (n: number) => Number.isSafeInteger(n) && n >= 100 && n <= 999999999
37
+
38
+ /** Linked clones only, on the template storage. The template needs bash, flock, setsid, base64, python3
39
+ * and /proc for executionWorkspace. Missing/ambiguous clones are never rebuilt.
40
+ * A hash collision refuses the request rather than silently choosing a new id.
41
+ * The configured state directory and VMID grant must remain stable on reconnect.
42
+ * Host locks coordinate this adapter, not unrelated PVE administrators. */
43
+ export let pveClones = (g: Graph, options: PveOptions): SandboxProvider => {
44
+ let state = absolute(options.state)
45
+ let [first, last] = options.vmidRange
46
+ if (
47
+ !vmid(first) || !vmid(last) || last < first || !vmid(options.template) ||
48
+ (options.template >= first && options.template <= last)
49
+ ) {
50
+ throw new Error(
51
+ 'PVE requires a template outside an explicit valid VMID range',
52
+ )
53
+ }
54
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(options.storage)) {
55
+ throw new Error('PVE requires an explicit storage id')
56
+ }
57
+ let root = '/workspace'
58
+ let address = (ref: SandboxRef) => {
59
+ if (!/^[a-zA-Z0-9_-]+$/.test(ref.id)) throw new Error('Invalid sandbox id')
60
+ let hash = 2166136261
61
+ for (let c of ref.id) {
62
+ hash = Math.imul(hash ^ c.charCodeAt(0), 16777619) >>> 0
63
+ }
64
+ let value = String(first + hash % (last - first + 1))
65
+ if (ref.address != null && ref.address != value) {
66
+ throw new Error('PVE address does not match its reserved VMID')
67
+ }
68
+ return value
69
+ }
70
+ // All pct failures propagate, including list/config permission or connection
71
+ // failures. Only a successful list establishes that a container is absent.
72
+ let control = (ref: SandboxRef, body: string) => {
73
+ let target = address(ref)
74
+ return options.transport.execute(`set -eu
75
+ umask 077
76
+ mkdir -p -- ${quote(state)}
77
+ exec 9>${quote(state + '/lock')}
78
+ flock -x 9
79
+ vmid=${quote(target)}
80
+ d=${quote(state + '/vmids/' + target)}
81
+ mkdir -p -- "$d"
82
+ id=${quote(ref.id)}
83
+ pct list </dev/null > "$d/list"
84
+ exists() { awk 'NR > 1 { print $1 }' "$d/list" | grep -Fxq -- "$vmid"; }
85
+ claimed() {
86
+ test -f "$d/owner" && test "$(cat "$d/owner")" = "$id" || { echo 'PVE VMID is not owned by this sandbox' >&2; exit 1; }
87
+ }
88
+ owned() {
89
+ test -s "$d/token" || { echo 'PVE ownership receipt is missing' >&2; exit 1; }
90
+ pct config "$vmid" </dev/null > "$d/config"
91
+ grep -Fxq -- "description: $(cat "$d/token")" "$d/config" || { echo 'PVE container ownership changed' >&2; exit 1; }
92
+ if grep -q '^lock:' "$d/config"; then echo 'PVE container is locked' >&2; exit 1; fi
93
+ }
94
+ ${body}`)
95
+ }
96
+ let present = `claimed
97
+ test ! -f "$d/released" || { echo 'PVE sandbox was disposed' >&2; exit 1; }
98
+ test -f "$d/created" || { echo 'PVE clone creation is incomplete; refusing reconstruction' >&2; exit 1; }
99
+ exists || { echo 'PVE clone is missing; refusing reconstruction' >&2; exit 1; }
100
+ owned`
101
+ let ready = `${present}
102
+ test -f "$d/ready" || { echo 'PVE sandbox preparation is incomplete' >&2; exit 1; }`
103
+ let running = `pct status "$vmid" </dev/null > "$d/status"
104
+ grep -Fxq 'status: running' "$d/status" || { echo 'PVE sandbox is not running' >&2; exit 1; }`
105
+ let inside = (ref: SandboxRef, script: string, prepared = true) =>
106
+ control(
107
+ ref,
108
+ `${prepared ? ready : present}
109
+ ${running}
110
+ pct exec "$vmid" --keep-env 0 -- bash -c ${quote(script)} </dev/null`,
111
+ )
112
+ let connection = async (ref: SandboxRef, prepared = true) => {
113
+ await control(ref, `${prepared ? ready : present}\n${running}`)
114
+ let transport: ComputerTransport = {
115
+ execute: (script) => inside(ref, script, prepared),
116
+ }
117
+ return {
118
+ workspace: executionWorkspace(g, transport, {
119
+ workspace: ref.id,
120
+ root,
121
+ receipts: root + '/.yak/processes',
122
+ }),
123
+ root,
124
+ address: address(ref),
125
+ }
126
+ }
127
+ return {
128
+ request: async (request) => {
129
+ if (request.image != null) {
130
+ throw new Error(
131
+ 'PVE image is unsupported; configure an explicit template',
132
+ )
133
+ }
134
+ if (request.from != null && !options.prepare) {
135
+ throw new Error('PVE commit preparation is not configured')
136
+ }
137
+ let spec = JSON.stringify({
138
+ template: options.template,
139
+ storage: options.storage,
140
+ vmidRange: options.vmidRange,
141
+ from: request.from,
142
+ })
143
+ // Description is set by clone itself, not by a later command that could
144
+ // accidentally adopt a foreign container after a failed clone.
145
+ let token = 'yak-sandbox:' + request.id + ':' + crypto.randomUUID()
146
+ await control(
147
+ request,
148
+ `if test -f "$d/owner"; then
149
+ claimed
150
+ test ! -f "$d/released" || { echo 'PVE sandbox was disposed' >&2; exit 1; }
151
+ test "$(cat "$d/spec")" = ${
152
+ quote(spec)
153
+ } || { echo 'PVE request changed' >&2; exit 1; }
154
+ else
155
+ if exists; then echo 'PVE VMID already exists without ownership' >&2; exit 1; fi
156
+ pct config ${options.template} </dev/null > "$d/template"
157
+ grep -Fxq 'template: 1' "$d/template" || { echo 'PVE source is not a template' >&2; exit 1; }
158
+ awk -F ': ' -v storage=${quote(options.storage)} '
159
+ $1 == "rootfs" || $1 ~ /^mp[0-9]+$/ {
160
+ volume=$2; sub(/,.*/, "", volume); sub(/^volume=/, "", volume)
161
+ if (index(volume, storage ":") != 1) bad=1
162
+ if ($1 == "rootfs") root=1
163
+ }
164
+ END { exit (bad || !root) }
165
+ ' "$d/template" || { echo 'PVE linked clone requires every template volume on configured storage' >&2; exit 1; }
166
+ printf '%s' ${quote(spec)} > "$d/spec"
167
+ printf '%s' ${quote(token)} > "$d/token"
168
+ printf '%s' "$id" > "$d/owner.tmp"
169
+ mv -- "$d/owner.tmp" "$d/owner"
170
+ pct clone ${options.template} "$vmid" --full 0 --description "$(cat "$d/token")" </dev/null > /dev/null
171
+ owned
172
+ touch "$d/created"
173
+ fi
174
+ ${present.replace('exists ||', 'pct list </dev/null > "$d/list"\nexists ||')}
175
+ pct status "$vmid" </dev/null > "$d/status"
176
+ if grep -Fxq 'status: stopped' "$d/status"; then pct start "$vmid" </dev/null > /dev/null; fi
177
+ ${running}`,
178
+ )
179
+ let connected = await connection(request, false)
180
+ await inside(
181
+ request,
182
+ `mkdir -p -- ${quote(root + '/.yak/processes')}`,
183
+ false,
184
+ )
185
+ let prepared = await control(
186
+ request,
187
+ `${present}\nif test -f "$d/ready"; then printf yes; fi`,
188
+ )
189
+ if (prepared != 'yes') {
190
+ if (request.from != null) {
191
+ await options.prepare!(request.from, connected.workspace, root)
192
+ }
193
+ await control(request, `${present}\ntouch "$d/ready"`)
194
+ }
195
+ return await connection(request)
196
+ },
197
+ connect: (ref) => connection(ref),
198
+ dispose: async (ref) => {
199
+ await control(
200
+ ref,
201
+ `claimed
202
+ if test -f "$d/released"; then exit 0; fi
203
+ if exists; then
204
+ owned
205
+ pct status "$vmid" </dev/null > "$d/status"
206
+ if grep -Fxq 'status: running' "$d/status"; then pct stop "$vmid" </dev/null > /dev/null; fi
207
+ fi
208
+ touch "$d/released"`,
209
+ )
210
+ },
211
+ restore: async (ref) => {
212
+ await control(
213
+ ref,
214
+ `claimed
215
+ exists || { echo 'PVE clone is missing; refusing reconstruction' >&2; exit 1; }
216
+ owned
217
+ pct status "$vmid" </dev/null > "$d/status"
218
+ if grep -Fxq 'status: stopped' "$d/status"; then pct start "$vmid" </dev/null > /dev/null; fi
219
+ rm -f -- "$d/released"`,
220
+ )
221
+ },
222
+ export: async function* (ref, paths) {
223
+ // Validate the whole request before issuing any remote read.
224
+ for (let path of paths) exportPath(path)
225
+ for (let path of paths) {
226
+ let encoded = await inside(
227
+ ref,
228
+ `python3 -c ${
229
+ quote(`import os, sys, base64
230
+ parts = sys.argv[1].split('/')
231
+ fd = os.open('/workspace', os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
232
+ try:
233
+ for i, part in enumerate(parts):
234
+ flags = os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK
235
+ if i < len(parts) - 1:
236
+ flags |= os.O_DIRECTORY
237
+ child = os.open(part, flags, dir_fd=fd)
238
+ os.close(fd)
239
+ fd = child
240
+ import stat
241
+ if not stat.S_ISREG(os.fstat(fd).st_mode):
242
+ raise ValueError('Export requires a regular file')
243
+ with os.fdopen(os.dup(fd), 'rb') as file:
244
+ sys.stdout.write(base64.b64encode(file.read()).decode('ascii'))
245
+ finally:
246
+ os.close(fd)`)
247
+ } ${quote(path)}`,
248
+ )
249
+ yield {
250
+ path,
251
+ bytes: Uint8Array.from(
252
+ atob(encoded.replaceAll(/\s/g, '')),
253
+ (c) => c.charCodeAt(0),
254
+ ),
255
+ }
256
+ }
257
+ },
258
+ }
259
+ }
@@ -0,0 +1,187 @@
1
+ // Only filesystem effects live here. The image's unchanged bytes are
2
+ // regenerable, and so are temporary files and package caches; every other
3
+ // changed file and original-file deletion is retained.
4
+ export let script = String.raw`
5
+ import io, json, os, stat, subprocess, sys, tarfile, time
6
+
7
+ root = sys.argv[2] if len(sys.argv) > 2 else '/'
8
+ held = os.path.join(root, '.yak-recovery')
9
+ baseline = os.path.join(held, 'baseline.json')
10
+ archive = os.path.join(held, 'snapshot.tar.gz')
11
+ ready = os.path.join(held, 'ready')
12
+ excluded = {'.yak-recovery', 'proc', 'sys', 'dev'}
13
+ # Temporary files, caches and the yak CLI's versions: each refills itself
14
+ # when needed, and together they were most of a 1.7 GB snapshot whose restore
15
+ # held a waking sandbox for two minutes. root/.cache is the XDG cache, which
16
+ # holds only what can be fetched or computed again, such as a 730 MB
17
+ # Playwright browser download the image's own browser had replaced.
18
+ regenerable = ('tmp', 'var/tmp', 'var/cache', 'var/lib/apt/lists',
19
+ 'root/.npm/_cacache', 'root/.cache',
20
+ 'root/.cargo/registry/cache', 'opt/yaks-cli')
21
+ def kept(name):
22
+ return not any(name == r or name.startswith(r + '/') for r in regenerable)
23
+ # Kernel views, wherever they are mounted (a runtime may mount procfs under
24
+ # /run), hold no workbench bytes and refuse some reads with EINVAL.
25
+ virtual = {'proc', 'sysfs', 'devtmpfs', 'devpts', 'cgroup', 'cgroup2',
26
+ 'mqueue', 'debugfs', 'tracefs', 'securityfs', 'pstore', 'bpf',
27
+ 'configfs', 'fusectl', 'binfmt_misc', 'hugetlbfs', 'autofs',
28
+ 'nsfs', 'rpc_pipefs'}
29
+
30
+ def mounts():
31
+ try:
32
+ with open('/proc/mounts') as source:
33
+ lines = source.read().splitlines()
34
+ except OSError:
35
+ return set()
36
+ found = set()
37
+ for line in lines:
38
+ fields = line.split()
39
+ if len(fields) > 2 and fields[2] in virtual:
40
+ point = fields[1].encode().decode('unicode_escape')
41
+ found.add(os.path.normpath(point))
42
+ return found
43
+
44
+ def path(name):
45
+ return os.path.join(root, name)
46
+
47
+ def scan():
48
+ found = {}
49
+ skipped = mounts()
50
+ def walk(name):
51
+ if os.path.normpath(path(name)) in skipped or not kept(name):
52
+ return
53
+ try:
54
+ entry = os.lstat(path(name))
55
+ except OSError:
56
+ return
57
+ if stat.S_ISSOCK(entry.st_mode):
58
+ return
59
+ if stat.S_ISDIR(entry.st_mode):
60
+ try:
61
+ children = os.listdir(path(name))
62
+ except OSError:
63
+ return
64
+ found[name] = [entry.st_mode, entry.st_size, entry.st_mtime_ns,
65
+ entry.st_ctime_ns, entry.st_uid, entry.st_gid]
66
+ if stat.S_ISDIR(entry.st_mode):
67
+ for child in children:
68
+ walk(os.path.join(name, child))
69
+ for name in os.listdir(root):
70
+ if name not in excluded:
71
+ walk(name)
72
+ return found
73
+
74
+ # Whether a file is as the baseline saw it. Its ctime is left out: a restore
75
+ # rewrites every file it brings back, so with it a restored file that matches
76
+ # the image would be kept again by every save after.
77
+ def same(before, now):
78
+ return before is not None and before[:3] + before[4:] == now[:3] + now[4:]
79
+
80
+ def write_baseline(before):
81
+ with open(baseline + '.part', 'w') as out:
82
+ json.dump(before, out)
83
+ os.replace(baseline + '.part', baseline)
84
+
85
+ os.makedirs(held, exist_ok=True)
86
+ mode = sys.argv[1]
87
+ if mode in ('fresh', 'existing'):
88
+ if os.path.exists(baseline):
89
+ print('existing' if os.path.exists(ready) else 'fresh')
90
+ else:
91
+ # A pre-deploy running container has no pristine-image manifest.
92
+ # Keep all its bytes instead of mistaking its files for the image.
93
+ write_baseline(scan() if mode == 'fresh' else {})
94
+ print('fresh')
95
+ elif mode == 'ready':
96
+ open(ready, 'a').close()
97
+ elif mode == 'save':
98
+ # A missing or incomplete baseline cannot distinguish edits from image
99
+ # files. Keep all eligible files and replace the baseline conservatively.
100
+ try:
101
+ with open(baseline) as source:
102
+ before = json.load(source)
103
+ except (FileNotFoundError, ValueError):
104
+ before = {}
105
+ write_baseline(before)
106
+ current = scan()
107
+ # A baseline written before a path was regenerable still lists it.
108
+ removed = sorted({n for n in before if n not in current and kept(n)},
109
+ key=len, reverse=True)
110
+ with tarfile.open(archive, 'w:gz', dereference=False, compresslevel=1) as out:
111
+ content = json.dumps(removed).encode()
112
+ entry = tarfile.TarInfo('.yak-recovery/deleted.json')
113
+ entry.size = len(content)
114
+ out.addfile(entry, io.BytesIO(content))
115
+ for name, metadata in current.items():
116
+ if not same(before.get(name), metadata):
117
+ out.add(path(name), arcname=name, recursive=False)
118
+ # An unstable file is not a successful checkpoint: leave the box alive.
119
+ if scan() != current:
120
+ raise RuntimeError('workbench files changed during snapshot; retry')
121
+ print(os.path.getsize(archive))
122
+ elif mode == 'restore':
123
+ # The download is extracted as it arrives, and kept whole beside it for
124
+ # the next save to replace; a cut download fails curl, gzip or the size.
125
+ started = time.monotonic()
126
+ partial = archive + '.part'
127
+ class Tee:
128
+ def __init__(self, source, out):
129
+ self.source, self.out, self.size = source, out, 0
130
+ def read(self, n=-1):
131
+ chunk = self.source.read(n)
132
+ self.out.write(chunk)
133
+ self.size += len(chunk)
134
+ return chunk
135
+ deleted = '.yak-recovery/deleted.json'
136
+ def remove(source, entry):
137
+ removed = json.load(source.extractfile(entry))
138
+ # The archive lists deleted image entries children first.
139
+ for name in removed:
140
+ target = path(name)
141
+ if os.path.islink(target) or os.path.isfile(target):
142
+ os.unlink(target)
143
+ elif os.path.isdir(target):
144
+ os.rmdir(target)
145
+ def extract(source, entry):
146
+ target = path(entry.name)
147
+ if os.path.islink(target):
148
+ os.unlink(target)
149
+ elif os.path.lexists(target) and not entry.isdir():
150
+ if os.path.isdir(target):
151
+ os.rmdir(target)
152
+ else:
153
+ os.unlink(target)
154
+ elif entry.isdir() and os.path.lexists(target) and not os.path.isdir(target):
155
+ os.unlink(target)
156
+ source.extract(entry, root, filter='fully_trusted')
157
+ download = None
158
+ try:
159
+ download = subprocess.Popen(['curl', '--fail', '--silent',
160
+ '--show-error', '--noproxy', '*',
161
+ sys.argv[3]], stdout=subprocess.PIPE)
162
+ with open(partial, 'wb') as out:
163
+ tee = Tee(download.stdout, out)
164
+ # Removed names and archived ones never overlap (save), so the
165
+ # deletion list applies wherever it comes, first or, in older
166
+ # archives, last.
167
+ with tarfile.open(fileobj=tee, mode='r|gz') as source:
168
+ for entry in source:
169
+ if entry.name == deleted:
170
+ remove(source, entry)
171
+ else:
172
+ extract(source, entry)
173
+ while tee.read(1 << 20):
174
+ pass
175
+ if download.wait():
176
+ raise RuntimeError('workbench snapshot download failed')
177
+ if tee.size != int(sys.argv[4]):
178
+ raise RuntimeError('workbench snapshot is incomplete')
179
+ os.replace(partial, archive)
180
+ finally:
181
+ if download and download.poll() is None:
182
+ download.kill()
183
+ if os.path.exists(partial):
184
+ os.unlink(partial)
185
+ print(json.dumps({'restoreMs': round(1000 * (time.monotonic() - started))}))
186
+ `;
187
+ //# sourceMappingURL=recovery-script.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"recovery-script.js","sources":["./recovery-script.ts"],"names":[],"mappings":"AAAA,qEAAqE;AACrE,0EAA0E;AAC1E,uDAAuD;AACvD,OAAO,IAAI,SAAS,OAAO,GAAG,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsL/B,CAAC,CAAA"}