@yaks/machine 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 +243 -2
- package/_dist/comp.d.ts +5 -0
- package/_dist/comp.d.ts.map +1 -0
- package/_dist/connectors.d.ts +29 -0
- package/_dist/connectors.d.ts.map +1 -0
- package/_dist/effects.d.ts +5 -0
- package/_dist/effects.d.ts.map +1 -0
- package/_dist/execution.d.ts +6 -0
- package/_dist/execution.d.ts.map +1 -0
- package/_dist/graph.d.ts +4 -0
- package/_dist/graph.d.ts.map +1 -0
- package/_dist/mod.d.ts +12 -0
- package/_dist/mod.d.ts.map +1 -0
- package/_dist/recorded.d.ts +4 -0
- package/_dist/recorded.d.ts.map +1 -0
- package/_dist/room.d.ts +45 -0
- package/_dist/room.d.ts.map +1 -0
- package/_dist/targets.d.ts +27 -0
- package/_dist/targets.d.ts.map +1 -0
- package/_dist/tools.d.ts +51 -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/_dist/workspace.d.ts +64 -0
- package/_dist/workspace.d.ts.map +1 -0
- package/_dist/workspaces.d.ts +10 -0
- package/_dist/workspaces.d.ts.map +1 -0
- package/comp.js +3 -0
- package/comp.js.map +1 -0
- package/comp.ts +3 -0
- package/connectors.js +149 -0
- package/connectors.js.map +1 -0
- package/connectors.ts +221 -0
- package/deno.json +1 -0
- package/effect-vocab.json +40 -0
- package/effects.js +71 -0
- package/effects.js.map +1 -0
- package/effects.ts +93 -0
- package/execution.js +239 -0
- package/execution.js.map +1 -0
- package/execution.ts +264 -0
- package/graph.js +70 -0
- package/graph.js.map +1 -0
- package/graph.ts +60 -0
- package/mod.js +5 -0
- package/mod.js.map +1 -0
- package/mod.ts +20 -0
- package/package.json +62 -4
- package/recorded.js +108 -0
- package/recorded.js.map +1 -0
- package/recorded.ts +74 -0
- package/room.js +160 -0
- package/room.js.map +1 -0
- package/room.ts +228 -0
- package/targets.js +127 -0
- package/targets.js.map +1 -0
- package/targets.ts +137 -0
- package/tools.js +346 -0
- package/tools.js.map +1 -0
- package/tools.ts +444 -0
- package/vocab.js +17 -0
- package/vocab.js.map +1 -0
- package/vocab.json +69 -0
- package/vocab.ts +13 -0
- package/workspace.js +79 -0
- package/workspace.js.map +1 -0
- package/workspace.ts +181 -0
- package/workspaces.js +38 -0
- package/workspaces.js.map +1 -0
- package/workspaces.ts +49 -0
package/effects.js
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
// The file-and-command effects take their target from the committed inputs.
|
|
2
|
+
import { CallError } from "@yaks/tools/errors";
|
|
3
|
+
import { processWorkspace, targetFor } from "./targets.js";
|
|
4
|
+
import { unbase64 } from "./workspace.js";
|
|
5
|
+
import { machineDeclared, machineOperations, rooted } from "./tools.js";
|
|
6
|
+
let text = (v)=>typeof v == 'string' && !v.includes('\0');
|
|
7
|
+
let path = (v)=>text(v) && v.length > 0;
|
|
8
|
+
let validate = (name, args)=>{
|
|
9
|
+
if (name == 'wait' || name == 'stop') {
|
|
10
|
+
if (!path(args.process)) {
|
|
11
|
+
throw new CallError('process', 'Name a process id.');
|
|
12
|
+
}
|
|
13
|
+
} else if (name == 'shell') {
|
|
14
|
+
if (!text(args.command)) {
|
|
15
|
+
throw new CallError('command', 'Pass a command string.');
|
|
16
|
+
}
|
|
17
|
+
} else if (name == 'read' && args.paths != null) {
|
|
18
|
+
if (args.path != null || !Array.isArray(args.paths) || !args.paths.every(path)) {
|
|
19
|
+
throw new CallError('path', 'Pass a path or a list of paths to stat.');
|
|
20
|
+
}
|
|
21
|
+
} else if (!path(args.path)) {
|
|
22
|
+
throw new CallError('path', 'Pass a file path.');
|
|
23
|
+
}
|
|
24
|
+
for (let key of [
|
|
25
|
+
'timeout',
|
|
26
|
+
'grace'
|
|
27
|
+
]){
|
|
28
|
+
let value = args[key];
|
|
29
|
+
if (value != null && (typeof value != 'number' || !Number.isFinite(value) || value < 0)) {
|
|
30
|
+
throw new CallError(key, key + ' must be a nonnegative number.');
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
};
|
|
34
|
+
/** Machine effects over the host's workspace capability. */ export let workspaceEffects = (g, use)=>Object.fromEntries(machineDeclared().map(({ name })=>[
|
|
35
|
+
name,
|
|
36
|
+
async (args, ctx)=>{
|
|
37
|
+
validate(name, args);
|
|
38
|
+
let target = name == 'wait' || name == 'stop' ? {
|
|
39
|
+
workspace: await processWorkspace(g, String(args.process)),
|
|
40
|
+
cwd: undefined
|
|
41
|
+
} : await targetFor(g, undefined, args);
|
|
42
|
+
return await use(target.workspace, ctx.actor, async (workspace)=>{
|
|
43
|
+
let body = args.body ?? args.content;
|
|
44
|
+
if (name == 'write' && typeof body != 'string') {
|
|
45
|
+
let encoded = body?.base64;
|
|
46
|
+
if (typeof encoded != 'string') {
|
|
47
|
+
throw new CallError('body', 'Pass text or a base64 body.');
|
|
48
|
+
}
|
|
49
|
+
let bytes;
|
|
50
|
+
try {
|
|
51
|
+
bytes = unbase64(encoded);
|
|
52
|
+
} catch {
|
|
53
|
+
throw new CallError('body', 'The body is not base64.');
|
|
54
|
+
}
|
|
55
|
+
if (!workspace.writeBytes) {
|
|
56
|
+
throw new CallError('body', 'This workspace takes text only.');
|
|
57
|
+
}
|
|
58
|
+
let path = String(args.path);
|
|
59
|
+
await workspace.writeBytes(rooted(path) ? path : `${target.cwd}/${path}`, bytes);
|
|
60
|
+
return {
|
|
61
|
+
body: `wrote ${path}`
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
return await machineOperations(workspace, {
|
|
65
|
+
cwd: ()=>target.cwd,
|
|
66
|
+
call: ctx.id
|
|
67
|
+
})[name](args);
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
]));
|
|
71
|
+
//# sourceMappingURL=effects.js.map
|
package/effects.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"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AE,IAAI,EAAE,GAAK;MAClC;MACA,OAAO,MAAY;QACjB,SAAS,MAAM;QACf,IAAI,SAAS,QAAQ,UAAU,QAAQ,SACnC;UACA,WAAW,MAAM,iBAAiB,GAAG,OAAO,KAAK,OAAO;UACxD,KAAK;QACP,IACE,MAAM,UAAU,GAAG,WAAW;QAClC,OAAO,MAAM,IAAI,OAAO,SAAS,EAAE,IAAI,KAAK,EAAE,OAAO;UACnD,IAAI,OAAO,KAAK,IAAI,IAAI,KAAK,OAAO;UACpC,IAAI,QAAQ,WAAW,OAAO,QAAQ,UAAU;YAC9C,IAAI,UAAW,MAA2B;YAC1C,IAAI,OAAO,WAAW,UAAU;cAC9B,MAAM,IAAI,UAAU,QAAQ;YAC9B;YACA,IAAI;YACJ,IAAI;cACF,QAAQ,SAAS;YACnB,EAAE,OAAM;cACN,MAAM,IAAI,UAAU,QAAQ;YAC9B;YACA,IAAI,CAAC,UAAU,UAAU,EAAE;cACzB,MAAM,IAAI,UAAU,QAAQ;YAC9B;YACA,IAAI,OAAO,OAAO,KAAK,IAAI;YAC3B,MAAM,UAAU,UAAU,CACxB,OAAO,QAAQ,OAAO,GAAG,OAAO,GAAG,CAAC,CAAC,EAAE,MAAM,EAC7C;YAEF,OAAO;cAAE,MAAM,CAAC,MAAM,EAAE,MAAM;YAAC;UACjC;UACA,OAAO,MAAM,kBAAkB,WAAW;YACxC,KAAK,IAAM,OAAO,GAAG;YACrB,MAAM,IAAI,EAAE;UACd,EAAE,CAAC,KAAK,CAAC;QACX;MACF;KACD,GACF"}
|
package/effects.ts
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
// The file-and-command effects take their target from the committed inputs.
|
|
2
|
+
import type { Operation } from 'jsr:@yaks/effects@0.2.36/invocation'
|
|
3
|
+
import type { Actor, Comp, Eid, Graph } from 'jsr:@yaks/graph@0.2.36'
|
|
4
|
+
import { CallError } from '@yaks/tools/errors'
|
|
5
|
+
import { processWorkspace, targetFor } from './targets.js'
|
|
6
|
+
import { unbase64, type Workspace } from './workspace.js'
|
|
7
|
+
import { machineDeclared, machineOperations, rooted } from './tools.js'
|
|
8
|
+
|
|
9
|
+
let text = (v: unknown): v is string =>
|
|
10
|
+
typeof v == 'string' && !v.includes('\0')
|
|
11
|
+
let path = (v: unknown) => text(v) && v.length > 0
|
|
12
|
+
|
|
13
|
+
let validate = (name: string, args: Comp) => {
|
|
14
|
+
if (name == 'wait' || name == 'stop') {
|
|
15
|
+
if (!path(args.process)) {
|
|
16
|
+
throw new CallError('process', 'Name a process id.')
|
|
17
|
+
}
|
|
18
|
+
} else if (name == 'shell') {
|
|
19
|
+
if (!text(args.command)) {
|
|
20
|
+
throw new CallError('command', 'Pass a command string.')
|
|
21
|
+
}
|
|
22
|
+
} else if (name == 'read' && args.paths != null) {
|
|
23
|
+
if (
|
|
24
|
+
args.path != null || !Array.isArray(args.paths) || !args.paths.every(path)
|
|
25
|
+
) {
|
|
26
|
+
throw new CallError('path', 'Pass a path or a list of paths to stat.')
|
|
27
|
+
}
|
|
28
|
+
} else if (!path(args.path)) {
|
|
29
|
+
throw new CallError('path', 'Pass a file path.')
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
for (let key of ['timeout', 'grace']) {
|
|
33
|
+
let value = args[key]
|
|
34
|
+
if (
|
|
35
|
+
value != null &&
|
|
36
|
+
(typeof value != 'number' || !Number.isFinite(value) || value < 0)
|
|
37
|
+
) {
|
|
38
|
+
throw new CallError(key, key + ' must be a nonnegative number.')
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Machine effects over the host's workspace capability. */
|
|
44
|
+
export let workspaceEffects = (
|
|
45
|
+
g: Graph,
|
|
46
|
+
use: <T>(
|
|
47
|
+
id: Eid,
|
|
48
|
+
actor: Actor | undefined,
|
|
49
|
+
run: (workspace: Workspace) => Promise<T>,
|
|
50
|
+
) => Promise<T>,
|
|
51
|
+
): Record<string, Operation> =>
|
|
52
|
+
Object.fromEntries(
|
|
53
|
+
machineDeclared().map(({ name }) => [
|
|
54
|
+
name,
|
|
55
|
+
async (args: Comp, ctx: Parameters<Operation>[1]) => {
|
|
56
|
+
validate(name, args)
|
|
57
|
+
let target = name == 'wait' || name == 'stop'
|
|
58
|
+
? {
|
|
59
|
+
workspace: await processWorkspace(g, String(args.process)),
|
|
60
|
+
cwd: undefined,
|
|
61
|
+
}
|
|
62
|
+
: await targetFor(g, undefined, args)
|
|
63
|
+
return await use(target.workspace, ctx.actor, async (workspace) => {
|
|
64
|
+
let body = args.body ?? args.content
|
|
65
|
+
if (name == 'write' && typeof body != 'string') {
|
|
66
|
+
let encoded = (body as Comp | undefined)?.base64
|
|
67
|
+
if (typeof encoded != 'string') {
|
|
68
|
+
throw new CallError('body', 'Pass text or a base64 body.')
|
|
69
|
+
}
|
|
70
|
+
let bytes: Uint8Array
|
|
71
|
+
try {
|
|
72
|
+
bytes = unbase64(encoded)
|
|
73
|
+
} catch {
|
|
74
|
+
throw new CallError('body', 'The body is not base64.')
|
|
75
|
+
}
|
|
76
|
+
if (!workspace.writeBytes) {
|
|
77
|
+
throw new CallError('body', 'This workspace takes text only.')
|
|
78
|
+
}
|
|
79
|
+
let path = String(args.path)
|
|
80
|
+
await workspace.writeBytes(
|
|
81
|
+
rooted(path) ? path : `${target.cwd}/${path}`,
|
|
82
|
+
bytes,
|
|
83
|
+
)
|
|
84
|
+
return { body: `wrote ${path}` }
|
|
85
|
+
}
|
|
86
|
+
return await machineOperations(workspace, {
|
|
87
|
+
cwd: () => target.cwd,
|
|
88
|
+
call: ctx.id,
|
|
89
|
+
})[name](args)
|
|
90
|
+
})
|
|
91
|
+
},
|
|
92
|
+
]),
|
|
93
|
+
)
|
package/execution.js
ADDED
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
// Durable command receipts live on the launch filesystem, not in a connector
|
|
2
|
+
// object's memory. Reconnecting observes that receipt and never relaunches it.
|
|
3
|
+
import { scope } from "@yaks/process/isolate";
|
|
4
|
+
import { CallError } from "@yaks/tools/errors";
|
|
5
|
+
import { derivedEid } from "@yaks/graph/identity";
|
|
6
|
+
import { decode, quote, shellStat, unbase64 } from "./workspace.js";
|
|
7
|
+
let absolute = (path)=>{
|
|
8
|
+
if (!path.startsWith('/') || path.includes('\0') || path.split('/').includes('..')) throw new Error('Workspace paths must be absolute and contain no ..');
|
|
9
|
+
return path.replace(/\/+$/, '') || '/';
|
|
10
|
+
};
|
|
11
|
+
let fileAt = (root, path)=>absolute(path.startsWith('/') ? path : root + '/' + path);
|
|
12
|
+
let safeId = (id)=>{
|
|
13
|
+
if (!/^[a-zA-Z0-9_-]+$/.test(id)) {
|
|
14
|
+
throw new Error('Invalid durable process handle');
|
|
15
|
+
}
|
|
16
|
+
return id;
|
|
17
|
+
};
|
|
18
|
+
let encode = (bytes)=>{
|
|
19
|
+
let out = '';
|
|
20
|
+
for (let byte of bytes)out += String.fromCharCode(byte);
|
|
21
|
+
return btoa(out);
|
|
22
|
+
};
|
|
23
|
+
// A PID is safe to signal only while its original Linux birth token matches.
|
|
24
|
+
// The supervisor creates its own session; no unrelated/adopted process is killed.
|
|
25
|
+
// The birth file holds the boot id and the process start time, a line each.
|
|
26
|
+
// Only bash builtins run here, so a look costs one shell and no forks.
|
|
27
|
+
let identity = `token() { local stat; read -r born < /proc/sys/kernel/random/boot_id && read -r stat 2>/dev/null < /proc/"$1"/stat || return 1; set -- \${stat##*) }; born="$born
|
|
28
|
+
\${20}"; }
|
|
29
|
+
owned() { local boot= start=; pid=; test -f "$d/pid" && test -f "$d/birth" || return 1; read -r pid < "$d/pid" || :; case "$pid" in ''|*[!0-9]*) return 1;; esac; { read -r boot && read -r start; } < "$d/birth" || return 1; test -n "$boot" && token "$pid" && test "$born" = "$boot
|
|
30
|
+
$start"; }`;
|
|
31
|
+
/** Bind a concrete workspace to an explicitly connected Linux computer.
|
|
32
|
+
* bash, setsid, flock, base64 and /proc are required at the target. No default
|
|
33
|
+
* computer or caller-relative receipt directory is inferred. */ export let executionWorkspace = (g, transport, target)=>{
|
|
34
|
+
let root = absolute(target.root), receipts = absolute(target.receipts);
|
|
35
|
+
let location = (id)=>`${receipts}/${safeId(target.workspace)}/${safeId(id)}`;
|
|
36
|
+
let processFor = (call)=>derivedEid(`workspace process|${target.workspace}|${call}`);
|
|
37
|
+
let row = async (id)=>{
|
|
38
|
+
let [record] = await g.get([
|
|
39
|
+
id
|
|
40
|
+
], [
|
|
41
|
+
'process',
|
|
42
|
+
'exit'
|
|
43
|
+
]);
|
|
44
|
+
if (!record?.process) return;
|
|
45
|
+
let process = record.process;
|
|
46
|
+
if (process.workspace != target.workspace) {
|
|
47
|
+
throw new Error('Process belongs to another workspace');
|
|
48
|
+
}
|
|
49
|
+
return {
|
|
50
|
+
process,
|
|
51
|
+
exit: record.exit
|
|
52
|
+
};
|
|
53
|
+
};
|
|
54
|
+
let observed = async (id)=>{
|
|
55
|
+
let record = await row(id);
|
|
56
|
+
if (!record) return null;
|
|
57
|
+
let data = await transport.execute(`set -eu\nd=${quote(location(id))}\n${identity}
|
|
58
|
+
if test -f "$d/exit"; then printf 'exit '; cat "$d/exit"
|
|
59
|
+
elif owned; then printf 'running %s' "$pid"
|
|
60
|
+
elif test -f "$d/exit"; then printf 'exit '; cat "$d/exit"
|
|
61
|
+
elif test -f "$d/launched"; then printf 'lost'
|
|
62
|
+
else printf 'pending'; fi`);
|
|
63
|
+
let [state, value] = data.trim().split(/\s+/);
|
|
64
|
+
if (state == 'exit' || state == 'lost') {
|
|
65
|
+
let code = state == 'exit' ? Number(value) : null;
|
|
66
|
+
if (code != null && !Number.isSafeInteger(code)) {
|
|
67
|
+
throw new Error('Invalid process exit receipt');
|
|
68
|
+
}
|
|
69
|
+
if (!record.exit) {
|
|
70
|
+
await g.apply([
|
|
71
|
+
{
|
|
72
|
+
entity: {
|
|
73
|
+
eid: id
|
|
74
|
+
},
|
|
75
|
+
exit: code == null ? {} : {
|
|
76
|
+
code
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
]);
|
|
80
|
+
}
|
|
81
|
+
return {
|
|
82
|
+
...record.process.pid != null ? {
|
|
83
|
+
pid: Number(record.process.pid)
|
|
84
|
+
} : {},
|
|
85
|
+
exit: {
|
|
86
|
+
code
|
|
87
|
+
}
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
if (state == 'running') {
|
|
91
|
+
let pid = Number(value);
|
|
92
|
+
if (!Number.isSafeInteger(pid) || pid <= 0) {
|
|
93
|
+
throw new Error('Invalid process pid receipt');
|
|
94
|
+
}
|
|
95
|
+
if (record.process.pid != pid) {
|
|
96
|
+
await g.apply([
|
|
97
|
+
{
|
|
98
|
+
entity: {
|
|
99
|
+
eid: id
|
|
100
|
+
},
|
|
101
|
+
process: {
|
|
102
|
+
pid
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
]);
|
|
106
|
+
}
|
|
107
|
+
return {
|
|
108
|
+
pid
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
if (state != 'pending') throw new Error('Invalid process receipt');
|
|
112
|
+
return {};
|
|
113
|
+
};
|
|
114
|
+
let writeBytes = async (path, content)=>{
|
|
115
|
+
let file = fileAt(root, path), parent = file.slice(0, file.lastIndexOf('/')) || '/';
|
|
116
|
+
await transport.execute(`set -eu; mkdir -p -- ${quote(parent)}; printf '%s' ${quote(encode(content))} | base64 -d > ${quote(file)}`);
|
|
117
|
+
};
|
|
118
|
+
return {
|
|
119
|
+
poll: transport.poll,
|
|
120
|
+
start: async (command, cwd, call)=>{
|
|
121
|
+
let directory = cwd == null ? root : fileAt(root, cwd);
|
|
122
|
+
let id = call ? processFor(call) : crypto.randomUUID();
|
|
123
|
+
let prior = await row(id);
|
|
124
|
+
if (prior && (prior.process?.command != command || prior.process?.cwd != directory)) {
|
|
125
|
+
throw new Error('Call receipt already names another command or directory');
|
|
126
|
+
}
|
|
127
|
+
if (!prior) {
|
|
128
|
+
try {
|
|
129
|
+
await g.apply([
|
|
130
|
+
{
|
|
131
|
+
entity: {
|
|
132
|
+
eid: id
|
|
133
|
+
},
|
|
134
|
+
process: {
|
|
135
|
+
workspace: target.workspace,
|
|
136
|
+
command,
|
|
137
|
+
cwd: directory
|
|
138
|
+
},
|
|
139
|
+
$was: {
|
|
140
|
+
process: {
|
|
141
|
+
workspace: null
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
]);
|
|
146
|
+
} catch (error) {
|
|
147
|
+
let winner = await row(id);
|
|
148
|
+
if (!winner || winner.process?.command != command || winner.process?.cwd != directory) throw error;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
let d = location(id);
|
|
152
|
+
let supervisor = `d=${quote(d)}
|
|
153
|
+
${identity}
|
|
154
|
+
printf '%s' "$$" > "$d/pid"
|
|
155
|
+
token "$$" && printf '%s\n' "$born" > "$d/birth"
|
|
156
|
+
touch "$d/launched"
|
|
157
|
+
set +e
|
|
158
|
+
(cd -- ${quote(directory)} && bash -c ${quote(command)})
|
|
159
|
+
code=$?
|
|
160
|
+
printf '%s' "$code" > "$d/exit.tmp"
|
|
161
|
+
mv -- "$d/exit.tmp" "$d/exit"`;
|
|
162
|
+
// flock serializes competing workers at the original target. A claim is
|
|
163
|
+
// never removed: interruption between claim and launch is ambiguous, not
|
|
164
|
+
// permission to execute a non-idempotent command again.
|
|
165
|
+
await transport.execute(`set -eu
|
|
166
|
+
umask 077
|
|
167
|
+
d=${quote(d)}
|
|
168
|
+
mkdir -p -- "$d"
|
|
169
|
+
exec 9>"$d/lock"
|
|
170
|
+
flock -x 9
|
|
171
|
+
if test ! -f "$d/claimed"; then
|
|
172
|
+
touch "$d/claimed"
|
|
173
|
+
printf '%s' ${quote(supervisor)} > "$d/run"
|
|
174
|
+
if test -d /run/systemd/system; then
|
|
175
|
+
uid=$(id -u)
|
|
176
|
+
export XDG_RUNTIME_DIR="/run/user/$uid"
|
|
177
|
+
export DBUS_SESSION_BUS_ADDRESS="unix:path=/run/user/$uid/bus"
|
|
178
|
+
${scope('yak-process-' + id, target.limits).map(quote).join(' ')} setsid bash "$d/run" 9>&- </dev/null >"$d/output" 2>&1 &
|
|
179
|
+
else
|
|
180
|
+
setsid bash "$d/run" 9>&- </dev/null >"$d/output" 2>&1 &
|
|
181
|
+
fi
|
|
182
|
+
launcher=$!
|
|
183
|
+
while test ! -f "$d/launched"; do
|
|
184
|
+
if ! kill -0 "$launcher" 2>/dev/null; then wait "$launcher"; exit 1; fi
|
|
185
|
+
sleep 0.01
|
|
186
|
+
done
|
|
187
|
+
fi`);
|
|
188
|
+
await observed(id);
|
|
189
|
+
return id;
|
|
190
|
+
},
|
|
191
|
+
receipt: async (call)=>{
|
|
192
|
+
let id = processFor(call);
|
|
193
|
+
return await row(id) ? id : undefined;
|
|
194
|
+
},
|
|
195
|
+
look: observed,
|
|
196
|
+
tail: async (id, n)=>{
|
|
197
|
+
if (!Number.isSafeInteger(n) || n < 0) {
|
|
198
|
+
throw new Error('Tail count must be a nonnegative integer');
|
|
199
|
+
}
|
|
200
|
+
if (!await row(id) || n == 0) return [];
|
|
201
|
+
let output = await transport.execute(`d=${quote(location(id))}; if test -f "$d/output"; then tail -n ${n} -- "$d/output"; fi`);
|
|
202
|
+
return output ? output.replace(/\n$/, '').split('\n') : [];
|
|
203
|
+
},
|
|
204
|
+
output: async (id, from)=>{
|
|
205
|
+
if (!Number.isSafeInteger(from) || from < 0) {
|
|
206
|
+
throw new Error('Output offset must be a nonnegative integer');
|
|
207
|
+
}
|
|
208
|
+
if (!await row(id)) return new Uint8Array();
|
|
209
|
+
let text = await transport.execute(`d=${quote(location(id))}; if test -f "$d/output"; then tail -c +${from + 1} -- "$d/output" | base64; fi`);
|
|
210
|
+
return unbase64(text);
|
|
211
|
+
},
|
|
212
|
+
kill: async (id, signal)=>{
|
|
213
|
+
if (![
|
|
214
|
+
'SIGTERM',
|
|
215
|
+
'SIGKILL'
|
|
216
|
+
].includes(signal)) {
|
|
217
|
+
throw new Error('Unsupported process signal');
|
|
218
|
+
}
|
|
219
|
+
if (!await row(id)) return;
|
|
220
|
+
await transport.execute(`set -eu\nd=${quote(location(id))}\n${identity}\nif test ! -f "$d/exit" && owned; then kill -${signal.slice(3)} -- -"$pid"; fi`);
|
|
221
|
+
},
|
|
222
|
+
read: async (path)=>{
|
|
223
|
+
// Missing/unreadable user paths are an invocation result, not a broken
|
|
224
|
+
// computer connector. Keep the control script successful in that case.
|
|
225
|
+
let answer = await transport.execute(`file=${quote(fileAt(root, path))}; if test -f "$file" && test -r "$file"; then printf 'ok\n'; base64 < "$file"; else printf 'path\n'; fi`);
|
|
226
|
+
if (answer.startsWith('path\n')) {
|
|
227
|
+
throw new CallError('path', 'File is not a readable regular file: ' + path);
|
|
228
|
+
}
|
|
229
|
+
if (!answer.startsWith('ok\n')) {
|
|
230
|
+
throw new Error('Invalid workspace file response');
|
|
231
|
+
}
|
|
232
|
+
return decode(answer.slice(3));
|
|
233
|
+
},
|
|
234
|
+
stat: (paths)=>shellStat(transport.execute)(paths.map((path)=>fileAt(root, path))),
|
|
235
|
+
writeBytes,
|
|
236
|
+
write: (path, content)=>writeBytes(path, new TextEncoder().encode(content))
|
|
237
|
+
};
|
|
238
|
+
};
|
|
239
|
+
//# sourceMappingURL=execution.js.map
|
package/execution.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"execution.js","sources":["./execution.ts"],"names":[],"mappings":"AAAA,6EAA6E;AAC7E,+EAA+E;AAC/E,SAAS,KAAK,qCAA0C;AACxD,SAAS,SAAS,kCAAuC;AAEzD,SAAS,UAAU,oCAAyC;AAE5D,SAEE,MAAM,EACN,KAAK,EACL,SAAS,EACT,QAAQ,yBAGa;AAEvB,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,KAAK,OAAO,CAAC,QAAQ,O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,OAAO,KAAK,CAAC;IAC7B;IACA,MAAM,CAAC,QACL,UAAU,UAAU,OAAO,EAAE,MAAM,GAAG,CAAC,CAAC,OAAS,OAAO,MAAM;IAChE;IACA,OAAO,CAAC,MAAM,UACZ,WAAW,MAAM,IAAI,cAAc,MAAM,CAAC;EAC9C;AACF,EAAC"}
|
package/execution.ts
ADDED
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
// Durable command receipts live on the launch filesystem, not in a connector
|
|
2
|
+
// object's memory. Reconnecting observes that receipt and never relaunches it.
|
|
3
|
+
import { scope } from '@yaks/process/isolate'
|
|
4
|
+
import { CallError } from '@yaks/tools/errors'
|
|
5
|
+
import type { Comp, Graph } from 'jsr:@yaks/graph@0.2.36'
|
|
6
|
+
import { derivedEid } from '@yaks/graph/identity'
|
|
7
|
+
import type { Proc } from './mod.ts'
|
|
8
|
+
import {
|
|
9
|
+
type ComputerTransport,
|
|
10
|
+
decode,
|
|
11
|
+
quote,
|
|
12
|
+
shellStat,
|
|
13
|
+
unbase64,
|
|
14
|
+
type Workspace,
|
|
15
|
+
type WorkspaceTarget,
|
|
16
|
+
} from './workspace.js'
|
|
17
|
+
|
|
18
|
+
let absolute = (path: string) => {
|
|
19
|
+
if (
|
|
20
|
+
!path.startsWith('/') || path.includes('\0') ||
|
|
21
|
+
path.split('/').includes('..')
|
|
22
|
+
) throw new Error('Workspace paths must be absolute and contain no ..')
|
|
23
|
+
return path.replace(/\/+$/, '') || '/'
|
|
24
|
+
}
|
|
25
|
+
let fileAt = (root: string, path: string) =>
|
|
26
|
+
absolute(path.startsWith('/') ? path : root + '/' + path)
|
|
27
|
+
let safeId = (id: string) => {
|
|
28
|
+
if (!/^[a-zA-Z0-9_-]+$/.test(id)) {
|
|
29
|
+
throw new Error('Invalid durable process handle')
|
|
30
|
+
}
|
|
31
|
+
return id
|
|
32
|
+
}
|
|
33
|
+
let encode = (bytes: Uint8Array) => {
|
|
34
|
+
let out = ''
|
|
35
|
+
for (let byte of bytes) out += String.fromCharCode(byte)
|
|
36
|
+
return btoa(out)
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// A PID is safe to signal only while its original Linux birth token matches.
|
|
40
|
+
// The supervisor creates its own session; no unrelated/adopted process is killed.
|
|
41
|
+
// The birth file holds the boot id and the process start time, a line each.
|
|
42
|
+
// Only bash builtins run here, so a look costs one shell and no forks.
|
|
43
|
+
let identity =
|
|
44
|
+
`token() { local stat; read -r born < /proc/sys/kernel/random/boot_id && read -r stat 2>/dev/null < /proc/"$1"/stat || return 1; set -- \${stat##*) }; born="$born
|
|
45
|
+
\${20}"; }
|
|
46
|
+
owned() { local boot= start=; pid=; test -f "$d/pid" && test -f "$d/birth" || return 1; read -r pid < "$d/pid" || :; case "$pid" in ''|*[!0-9]*) return 1;; esac; { read -r boot && read -r start; } < "$d/birth" || return 1; test -n "$boot" && token "$pid" && test "$born" = "$boot
|
|
47
|
+
$start"; }`
|
|
48
|
+
|
|
49
|
+
/** Bind a concrete workspace to an explicitly connected Linux computer.
|
|
50
|
+
* bash, setsid, flock, base64 and /proc are required at the target. No default
|
|
51
|
+
* computer or caller-relative receipt directory is inferred. */
|
|
52
|
+
export let executionWorkspace = (
|
|
53
|
+
g: Graph,
|
|
54
|
+
transport: ComputerTransport,
|
|
55
|
+
target: WorkspaceTarget,
|
|
56
|
+
): Workspace & Pick<Required<Workspace>, 'output'> => {
|
|
57
|
+
let root = absolute(target.root), receipts = absolute(target.receipts)
|
|
58
|
+
let location = (id: string) =>
|
|
59
|
+
`${receipts}/${safeId(target.workspace)}/${safeId(id)}`
|
|
60
|
+
let processFor = (call: string) =>
|
|
61
|
+
derivedEid(`workspace process|${target.workspace}|${call}`)
|
|
62
|
+
let row = async (id: string) => {
|
|
63
|
+
let [record] = await g.get([id], ['process', 'exit'])
|
|
64
|
+
if (!record?.process) return
|
|
65
|
+
let process = record.process as Comp
|
|
66
|
+
if (process.workspace != target.workspace) {
|
|
67
|
+
throw new Error('Process belongs to another workspace')
|
|
68
|
+
}
|
|
69
|
+
return { process, exit: record.exit }
|
|
70
|
+
}
|
|
71
|
+
let observed = async (id: string): Promise<Proc | null> => {
|
|
72
|
+
let record = await row(id)
|
|
73
|
+
if (!record) return null
|
|
74
|
+
let data = await transport.execute(
|
|
75
|
+
`set -eu\nd=${quote(location(id))}\n${identity}
|
|
76
|
+
if test -f "$d/exit"; then printf 'exit '; cat "$d/exit"
|
|
77
|
+
elif owned; then printf 'running %s' "$pid"
|
|
78
|
+
elif test -f "$d/exit"; then printf 'exit '; cat "$d/exit"
|
|
79
|
+
elif test -f "$d/launched"; then printf 'lost'
|
|
80
|
+
else printf 'pending'; fi`,
|
|
81
|
+
)
|
|
82
|
+
let [state, value] = data.trim().split(/\s+/)
|
|
83
|
+
if (state == 'exit' || state == 'lost') {
|
|
84
|
+
let code = state == 'exit' ? Number(value) : null
|
|
85
|
+
if (code != null && !Number.isSafeInteger(code)) {
|
|
86
|
+
throw new Error('Invalid process exit receipt')
|
|
87
|
+
}
|
|
88
|
+
if (!record.exit) {
|
|
89
|
+
await g.apply([{
|
|
90
|
+
entity: { eid: id },
|
|
91
|
+
exit: code == null ? {} : { code },
|
|
92
|
+
}])
|
|
93
|
+
}
|
|
94
|
+
return {
|
|
95
|
+
...record.process.pid != null
|
|
96
|
+
? { pid: Number(record.process.pid) }
|
|
97
|
+
: {},
|
|
98
|
+
exit: { code },
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
if (state == 'running') {
|
|
102
|
+
let pid = Number(value)
|
|
103
|
+
if (!Number.isSafeInteger(pid) || pid <= 0) {
|
|
104
|
+
throw new Error('Invalid process pid receipt')
|
|
105
|
+
}
|
|
106
|
+
if (record.process.pid != pid) {
|
|
107
|
+
await g.apply([{ entity: { eid: id }, process: { pid } }])
|
|
108
|
+
}
|
|
109
|
+
return { pid }
|
|
110
|
+
}
|
|
111
|
+
if (state != 'pending') throw new Error('Invalid process receipt')
|
|
112
|
+
return {}
|
|
113
|
+
}
|
|
114
|
+
let writeBytes: NonNullable<Workspace['writeBytes']> = async (
|
|
115
|
+
path,
|
|
116
|
+
content,
|
|
117
|
+
) => {
|
|
118
|
+
let file = fileAt(root, path),
|
|
119
|
+
parent = file.slice(0, file.lastIndexOf('/')) || '/'
|
|
120
|
+
await transport.execute(
|
|
121
|
+
`set -eu; mkdir -p -- ${quote(parent)}; printf '%s' ${
|
|
122
|
+
quote(encode(content))
|
|
123
|
+
} | base64 -d > ${quote(file)}`,
|
|
124
|
+
)
|
|
125
|
+
}
|
|
126
|
+
return {
|
|
127
|
+
poll: transport.poll,
|
|
128
|
+
start: async (command, cwd, call) => {
|
|
129
|
+
let directory = cwd == null ? root : fileAt(root, cwd)
|
|
130
|
+
let id = call ? processFor(call) : crypto.randomUUID()
|
|
131
|
+
let prior = await row(id)
|
|
132
|
+
if (
|
|
133
|
+
prior &&
|
|
134
|
+
(prior.process?.command != command || prior.process?.cwd != directory)
|
|
135
|
+
) {
|
|
136
|
+
throw new Error(
|
|
137
|
+
'Call receipt already names another command or directory',
|
|
138
|
+
)
|
|
139
|
+
}
|
|
140
|
+
if (!prior) {
|
|
141
|
+
try {
|
|
142
|
+
await g.apply([{
|
|
143
|
+
entity: { eid: id },
|
|
144
|
+
process: { workspace: target.workspace, command, cwd: directory },
|
|
145
|
+
$was: { process: { workspace: null } },
|
|
146
|
+
}])
|
|
147
|
+
} catch (error) {
|
|
148
|
+
let winner = await row(id)
|
|
149
|
+
if (
|
|
150
|
+
!winner || winner.process?.command != command ||
|
|
151
|
+
winner.process?.cwd != directory
|
|
152
|
+
) throw error
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
let d = location(id)
|
|
156
|
+
let supervisor = `d=${quote(d)}
|
|
157
|
+
${identity}
|
|
158
|
+
printf '%s' "$$" > "$d/pid"
|
|
159
|
+
token "$$" && printf '%s\n' "$born" > "$d/birth"
|
|
160
|
+
touch "$d/launched"
|
|
161
|
+
set +e
|
|
162
|
+
(cd -- ${quote(directory)} && bash -c ${quote(command)})
|
|
163
|
+
code=$?
|
|
164
|
+
printf '%s' "$code" > "$d/exit.tmp"
|
|
165
|
+
mv -- "$d/exit.tmp" "$d/exit"`
|
|
166
|
+
// flock serializes competing workers at the original target. A claim is
|
|
167
|
+
// never removed: interruption between claim and launch is ambiguous, not
|
|
168
|
+
// permission to execute a non-idempotent command again.
|
|
169
|
+
await transport.execute(`set -eu
|
|
170
|
+
umask 077
|
|
171
|
+
d=${quote(d)}
|
|
172
|
+
mkdir -p -- "$d"
|
|
173
|
+
exec 9>"$d/lock"
|
|
174
|
+
flock -x 9
|
|
175
|
+
if test ! -f "$d/claimed"; then
|
|
176
|
+
touch "$d/claimed"
|
|
177
|
+
printf '%s' ${quote(supervisor)} > "$d/run"
|
|
178
|
+
if test -d /run/systemd/system; then
|
|
179
|
+
uid=$(id -u)
|
|
180
|
+
export XDG_RUNTIME_DIR="/run/user/$uid"
|
|
181
|
+
export DBUS_SESSION_BUS_ADDRESS="unix:path=/run/user/$uid/bus"
|
|
182
|
+
${
|
|
183
|
+
scope('yak-process-' + id, target.limits).map(quote).join(' ')
|
|
184
|
+
} setsid bash "$d/run" 9>&- </dev/null >"$d/output" 2>&1 &
|
|
185
|
+
else
|
|
186
|
+
setsid bash "$d/run" 9>&- </dev/null >"$d/output" 2>&1 &
|
|
187
|
+
fi
|
|
188
|
+
launcher=$!
|
|
189
|
+
while test ! -f "$d/launched"; do
|
|
190
|
+
if ! kill -0 "$launcher" 2>/dev/null; then wait "$launcher"; exit 1; fi
|
|
191
|
+
sleep 0.01
|
|
192
|
+
done
|
|
193
|
+
fi`)
|
|
194
|
+
await observed(id)
|
|
195
|
+
return id
|
|
196
|
+
},
|
|
197
|
+
receipt: async (call) => {
|
|
198
|
+
let id = processFor(call)
|
|
199
|
+
return await row(id) ? id : undefined
|
|
200
|
+
},
|
|
201
|
+
look: observed,
|
|
202
|
+
tail: async (id, n) => {
|
|
203
|
+
if (!Number.isSafeInteger(n) || n < 0) {
|
|
204
|
+
throw new Error('Tail count must be a nonnegative integer')
|
|
205
|
+
}
|
|
206
|
+
if (!await row(id) || n == 0) return []
|
|
207
|
+
let output = await transport.execute(
|
|
208
|
+
`d=${
|
|
209
|
+
quote(location(id))
|
|
210
|
+
}; if test -f "$d/output"; then tail -n ${n} -- "$d/output"; fi`,
|
|
211
|
+
)
|
|
212
|
+
return output ? output.replace(/\n$/, '').split('\n') : []
|
|
213
|
+
},
|
|
214
|
+
output: async (id, from) => {
|
|
215
|
+
if (!Number.isSafeInteger(from) || from < 0) {
|
|
216
|
+
throw new Error('Output offset must be a nonnegative integer')
|
|
217
|
+
}
|
|
218
|
+
if (!await row(id)) return new Uint8Array()
|
|
219
|
+
let text = await transport.execute(
|
|
220
|
+
`d=${quote(location(id))}; if test -f "$d/output"; then tail -c +${
|
|
221
|
+
from + 1
|
|
222
|
+
} -- "$d/output" | base64; fi`,
|
|
223
|
+
)
|
|
224
|
+
return unbase64(text)
|
|
225
|
+
},
|
|
226
|
+
kill: async (id, signal) => {
|
|
227
|
+
if (!['SIGTERM', 'SIGKILL'].includes(signal)) {
|
|
228
|
+
throw new Error('Unsupported process signal')
|
|
229
|
+
}
|
|
230
|
+
if (!await row(id)) return
|
|
231
|
+
await transport.execute(
|
|
232
|
+
`set -eu\nd=${
|
|
233
|
+
quote(location(id))
|
|
234
|
+
}\n${identity}\nif test ! -f "$d/exit" && owned; then kill -${
|
|
235
|
+
signal.slice(3)
|
|
236
|
+
} -- -"$pid"; fi`,
|
|
237
|
+
)
|
|
238
|
+
},
|
|
239
|
+
read: async (path) => {
|
|
240
|
+
// Missing/unreadable user paths are an invocation result, not a broken
|
|
241
|
+
// computer connector. Keep the control script successful in that case.
|
|
242
|
+
let answer = await transport.execute(
|
|
243
|
+
`file=${
|
|
244
|
+
quote(fileAt(root, path))
|
|
245
|
+
}; if test -f "$file" && test -r "$file"; then printf 'ok\n'; base64 < "$file"; else printf 'path\n'; fi`,
|
|
246
|
+
)
|
|
247
|
+
if (answer.startsWith('path\n')) {
|
|
248
|
+
throw new CallError(
|
|
249
|
+
'path',
|
|
250
|
+
'File is not a readable regular file: ' + path,
|
|
251
|
+
)
|
|
252
|
+
}
|
|
253
|
+
if (!answer.startsWith('ok\n')) {
|
|
254
|
+
throw new Error('Invalid workspace file response')
|
|
255
|
+
}
|
|
256
|
+
return decode(answer.slice(3))
|
|
257
|
+
},
|
|
258
|
+
stat: (paths) =>
|
|
259
|
+
shellStat(transport.execute)(paths.map((path) => fileAt(root, path))),
|
|
260
|
+
writeBytes,
|
|
261
|
+
write: (path, content) =>
|
|
262
|
+
writeBytes(path, new TextEncoder().encode(content)),
|
|
263
|
+
}
|
|
264
|
+
}
|