@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.
Files changed (71) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +243 -2
  3. package/_dist/comp.d.ts +5 -0
  4. package/_dist/comp.d.ts.map +1 -0
  5. package/_dist/connectors.d.ts +29 -0
  6. package/_dist/connectors.d.ts.map +1 -0
  7. package/_dist/effects.d.ts +5 -0
  8. package/_dist/effects.d.ts.map +1 -0
  9. package/_dist/execution.d.ts +6 -0
  10. package/_dist/execution.d.ts.map +1 -0
  11. package/_dist/graph.d.ts +4 -0
  12. package/_dist/graph.d.ts.map +1 -0
  13. package/_dist/mod.d.ts +12 -0
  14. package/_dist/mod.d.ts.map +1 -0
  15. package/_dist/recorded.d.ts +4 -0
  16. package/_dist/recorded.d.ts.map +1 -0
  17. package/_dist/room.d.ts +45 -0
  18. package/_dist/room.d.ts.map +1 -0
  19. package/_dist/targets.d.ts +27 -0
  20. package/_dist/targets.d.ts.map +1 -0
  21. package/_dist/tools.d.ts +51 -0
  22. package/_dist/tools.d.ts.map +1 -0
  23. package/_dist/vocab.d.ts +5 -0
  24. package/_dist/vocab.d.ts.map +1 -0
  25. package/_dist/workspace.d.ts +64 -0
  26. package/_dist/workspace.d.ts.map +1 -0
  27. package/_dist/workspaces.d.ts +10 -0
  28. package/_dist/workspaces.d.ts.map +1 -0
  29. package/comp.js +3 -0
  30. package/comp.js.map +1 -0
  31. package/comp.ts +3 -0
  32. package/connectors.js +149 -0
  33. package/connectors.js.map +1 -0
  34. package/connectors.ts +221 -0
  35. package/deno.json +1 -0
  36. package/effect-vocab.json +40 -0
  37. package/effects.js +71 -0
  38. package/effects.js.map +1 -0
  39. package/effects.ts +93 -0
  40. package/execution.js +239 -0
  41. package/execution.js.map +1 -0
  42. package/execution.ts +264 -0
  43. package/graph.js +70 -0
  44. package/graph.js.map +1 -0
  45. package/graph.ts +60 -0
  46. package/mod.js +5 -0
  47. package/mod.js.map +1 -0
  48. package/mod.ts +20 -0
  49. package/package.json +62 -4
  50. package/recorded.js +108 -0
  51. package/recorded.js.map +1 -0
  52. package/recorded.ts +74 -0
  53. package/room.js +160 -0
  54. package/room.js.map +1 -0
  55. package/room.ts +228 -0
  56. package/targets.js +127 -0
  57. package/targets.js.map +1 -0
  58. package/targets.ts +137 -0
  59. package/tools.js +346 -0
  60. package/tools.js.map +1 -0
  61. package/tools.ts +444 -0
  62. package/vocab.js +17 -0
  63. package/vocab.js.map +1 -0
  64. package/vocab.json +69 -0
  65. package/vocab.ts +13 -0
  66. package/workspace.js +79 -0
  67. package/workspace.js.map +1 -0
  68. package/workspace.ts +181 -0
  69. package/workspaces.js +38 -0
  70. package/workspaces.js.map +1 -0
  71. package/workspaces.ts +49 -0
package/graph.js ADDED
@@ -0,0 +1,70 @@
1
+ // Workspace placement is stable for the lifetime of its resource. Home writes
2
+ // through any door must name a workspace and an absolute command directory.
3
+ import { hook } from "@yaks/graph";
4
+ export let workspacePolicy = ()=>({
5
+ name: '@yaks/machine/workspaces',
6
+ authorize: hook([
7
+ 'home',
8
+ 'workspace'
9
+ ], async (bundles, tx)=>{
10
+ let held = new Map((await tx.get(bundles.map((b)=>b.entity.eid))).map((b)=>[
11
+ b.entity.eid,
12
+ b
13
+ ]));
14
+ let merged = new Map();
15
+ for (let b of bundles){
16
+ let old = merged.get(b.entity.eid) ?? held.get(b.entity.eid);
17
+ let record = {
18
+ ...old,
19
+ ...b
20
+ };
21
+ for (let name of [
22
+ 'home',
23
+ 'workspace'
24
+ ]){
25
+ if (b[name]) {
26
+ record[name] = {
27
+ ...old?.[name],
28
+ ...b[name]
29
+ };
30
+ }
31
+ }
32
+ merged.set(b.entity.eid, record);
33
+ let before = held.get(b.entity.eid)?.workspace;
34
+ if (before && Object.hasOwn(b, 'workspace')) {
35
+ let after = record.workspace;
36
+ for (let property of [
37
+ 'root',
38
+ 'machine',
39
+ 'sandbox'
40
+ ]){
41
+ if (property == 'root' && before.root == null && held.get(b.entity.eid)?.pending && held.get(b.entity.eid)?.sandbox) continue;
42
+ if ((before[property] ?? null) !== (after?.[property] ?? null)) {
43
+ throw new Error('Workspace placement is immutable: ' + property);
44
+ }
45
+ }
46
+ }
47
+ }
48
+ for (let b of merged.values()){
49
+ if (!b.home || b.$delete) continue;
50
+ let home = b.home;
51
+ if (home.cwd != null && (typeof home.cwd != 'string' || !home.cwd.startsWith('/') || home.cwd.includes('\0'))) {
52
+ throw new Error('Home cwd must be an absolute path');
53
+ }
54
+ if (home.workspace != null) {
55
+ let id = String(home.workspace);
56
+ let target = merged.get(id) ?? (await tx.get([
57
+ id
58
+ ]))[0];
59
+ if (!target?.workspace || target.$delete) {
60
+ throw new Error('Not a workspace: ' + id);
61
+ }
62
+ }
63
+ }
64
+ return bundles;
65
+ })
66
+ });
67
+ /** Graph facet: the policy applies to generic graph writes as well as tools. */ export let plugins = ()=>[
68
+ workspacePolicy()
69
+ ];
70
+ //# sourceMappingURL=graph.js.map
package/graph.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"graph.js","sources":["./graph.ts"],"names":[],"mappings":"AAAA,8EAA8E;AAC9E,4EAA4E;AAC5E,SAAiC,IAAI,2BAA6C;AAElF,OAAO,IAAI,kBAAkB,IAAc,CAAC;IAC1C,MAAM;IACN,WAAW,KAAK;MAAC;MAAQ;KAAY,EAAE,OAAO,SAAS;MACrD,IAAI,OAAO,IAAI,IACb,CAAC,MAAM,GAAG,GAAG,CAAC,QAAQ,GAAG,CAAC,CAAC,IAAM,EAAE,MAAM,CAAC,GAAG,EAAE,EAAE,GAAG,CAAC,CACnD,IACG;UAAC,EAAE,MAAM,CAAC,GAAG;UAAE;SAAE;MAExB,IAAI,SAAS,IAAI;MACjB,KAAK,IAAI,KAAK,QAAS;QACrB,IAAI,MAAM,OAAO,GAAG,CAAC,EAAE,MAAM,CAAC,GAAG,KAAK,KAAK,GAAG,CAAC,EAAE,MAAM,CAAC,GAA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AAG,CAAC,OAAO,CAAC,MAAM,GAAG,GAAG,CAAC;YAAC;WAAG,CAAC,CAAC,CAAC,EAAE;UACtD,IAAI,CAAC,QAAQ,aAAa,OAAO,OAAO,EAAE;YACxC,MAAM,IAAI,MAAM,sBAAsB;UACxC;QACF;MACF;MACA,OAAO;IACT;EACF,CAAC,EAAC;AAEF,8EAA8E,GAC9E,OAAO,IAAI,UAAU,IAAgB;IAAC;GAAkB,CAAA"}
package/graph.ts ADDED
@@ -0,0 +1,60 @@
1
+ // Workspace placement is stable for the lifetime of its resource. Home writes
2
+ // through any door must name a workspace and an absolute command directory.
3
+ import { type Bundle, type Comp, hook, type Plugin } from '@yaks/graph'
4
+
5
+ export let workspacePolicy = (): Plugin => ({
6
+ name: '@yaks/machine/workspaces',
7
+ authorize: hook(['home', 'workspace'], async (bundles, tx) => {
8
+ let held = new Map(
9
+ (await tx.get(bundles.map((b) => b.entity.eid))).map((
10
+ b,
11
+ ) => [b.entity.eid, b]),
12
+ )
13
+ let merged = new Map<string, Bundle>()
14
+ for (let b of bundles) {
15
+ let old = merged.get(b.entity.eid) ?? held.get(b.entity.eid)
16
+ let record = { ...old, ...b }
17
+ for (let name of ['home', 'workspace']) {
18
+ if (b[name]) {
19
+ record[name] = { ...old?.[name] as Comp, ...b[name] as Comp }
20
+ }
21
+ }
22
+ merged.set(b.entity.eid, record)
23
+ let before = held.get(b.entity.eid)?.workspace as Comp | undefined
24
+ if (before && Object.hasOwn(b, 'workspace')) {
25
+ let after = record.workspace as Comp | null
26
+ for (let property of ['root', 'machine', 'sandbox']) {
27
+ if (
28
+ property == 'root' && before.root == null &&
29
+ held.get(b.entity.eid)?.pending && held.get(b.entity.eid)?.sandbox
30
+ ) continue
31
+ if ((before[property] ?? null) !== (after?.[property] ?? null)) {
32
+ throw new Error('Workspace placement is immutable: ' + property)
33
+ }
34
+ }
35
+ }
36
+ }
37
+ for (let b of merged.values()) {
38
+ if (!b.home || b.$delete) continue
39
+ let home = b.home as Comp
40
+ if (
41
+ home.cwd != null &&
42
+ (typeof home.cwd != 'string' || !home.cwd.startsWith('/') ||
43
+ home.cwd.includes('\0'))
44
+ ) {
45
+ throw new Error('Home cwd must be an absolute path')
46
+ }
47
+ if (home.workspace != null) {
48
+ let id = String(home.workspace)
49
+ let target = merged.get(id) ?? (await tx.get([id]))[0]
50
+ if (!target?.workspace || target.$delete) {
51
+ throw new Error('Not a workspace: ' + id)
52
+ }
53
+ }
54
+ }
55
+ return bundles
56
+ }),
57
+ })
58
+
59
+ /** Graph facet: the policy applies to generic graph writes as well as tools. */
60
+ export let plugins = (): Plugin[] => [workspacePolicy()]
package/mod.js ADDED
@@ -0,0 +1,5 @@
1
+ // Computers and workspace contracts, independent of provisioning or a runner.
2
+ /** A process as the machine holds it: `exit` is absent while it runs, and its
3
+ * code is null when the machine could not learn it. */ export * from "./comp.js";
4
+ export { follow, settle, shellStat } from "./workspace.js";
5
+ //# sourceMappingURL=mod.js.map
package/mod.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mod.js","sources":["./mod.ts"],"names":[],"mappings":"AAAA,8EAA8E;AAE9E;qDACqD,GAMrD,0BAAyB;AAEzB,SAAS,MAAM,EAAE,MAAM,EAAE,SAAS,yBAAwB"}
package/mod.ts ADDED
@@ -0,0 +1,20 @@
1
+ // Computers and workspace contracts, independent of provisioning or a runner.
2
+
3
+ /** A process as the machine holds it: `exit` is absent while it runs, and its
4
+ * code is null when the machine could not learn it. */
5
+ export type Proc = { pid?: number; exit?: { code: number | null } }
6
+
7
+ /** Compatibility name for the shared Workspace interface. */
8
+ export type Machine = import('./workspace.js').Workspace
9
+
10
+ export * from './comp.js'
11
+
12
+ export { follow, settle, shellStat } from './workspace.js'
13
+ export type {
14
+ ComputerConnector,
15
+ ComputerTransport,
16
+ SettleOpts,
17
+ Stat,
18
+ Workspace,
19
+ WorkspaceTarget,
20
+ } from './workspace.js'
package/package.json CHANGED
@@ -1,6 +1,64 @@
1
1
  {
2
2
  "name": "@yaks/machine",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.36",
4
+ "homepage": "https://jsr.io/@yaks/machine",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": {
8
+ "types": "./_dist/mod.d.ts",
9
+ "default": "./mod.js"
10
+ },
11
+ "./vocab": {
12
+ "types": "./_dist/vocab.d.ts",
13
+ "default": "./vocab.js"
14
+ },
15
+ "./connectors": {
16
+ "types": "./_dist/connectors.d.ts",
17
+ "default": "./connectors.js"
18
+ },
19
+ "./execution": {
20
+ "types": "./_dist/execution.d.ts",
21
+ "default": "./execution.js"
22
+ },
23
+ "./recorded": {
24
+ "types": "./_dist/recorded.d.ts",
25
+ "default": "./recorded.js"
26
+ },
27
+ "./effects": {
28
+ "types": "./_dist/effects.d.ts",
29
+ "default": "./effects.js"
30
+ },
31
+ "./tools": {
32
+ "types": "./_dist/tools.d.ts",
33
+ "default": "./tools.js"
34
+ },
35
+ "./targets": {
36
+ "types": "./_dist/targets.d.ts",
37
+ "default": "./targets.js"
38
+ },
39
+ "./workspaces": {
40
+ "types": "./_dist/workspaces.d.ts",
41
+ "default": "./workspaces.js"
42
+ },
43
+ "./graph": {
44
+ "types": "./_dist/graph.d.ts",
45
+ "default": "./graph.js"
46
+ },
47
+ "./room": {
48
+ "types": "./_dist/room.d.ts",
49
+ "default": "./room.js"
50
+ }
51
+ },
52
+ "license": "Apache-2.0",
53
+ "dependencies": {
54
+ "@yaks/effects": "0.2.36",
55
+ "@yaks/fp": "0.2.36",
56
+ "@yaks/graph": "0.2.36",
57
+ "@yaks/process": "0.2.36",
58
+ "@yaks/query": "0.2.36",
59
+ "@yaks/tools": "0.2.36",
60
+ "@yaks/vocab": "0.2.36"
61
+ },
62
+ "description": "Computers, explicit connection transports and durable file-and-command workspaces, separate from sandbox provisioning.",
63
+ "repository": "https://github.com/yak-sh/yak.git"
64
+ }
package/recorded.js ADDED
@@ -0,0 +1,108 @@
1
+ // Workspace backends that keep their own process IDs can publish their
2
+ // receipts in the graph without knowing anything about the graph themselves.
3
+ import { derivedEid, mint } from "@yaks/graph/identity";
4
+ /** Give a workspace graph identities for its running commands and exits. */ export let recordedWorkspace = (g, workspace, port)=>{
5
+ let idOf = (call)=>derivedEid(`workspace process|${workspace}|${call}`);
6
+ let record = async (eid)=>{
7
+ let [row] = await g.get([
8
+ eid
9
+ ], [
10
+ 'process',
11
+ 'exit'
12
+ ]);
13
+ return row?.process?.workspace == workspace ? row : undefined;
14
+ };
15
+ let handle = (row)=>String(row.process.handle ?? row.entity.eid);
16
+ let look = async (eid)=>{
17
+ let row = await record(eid);
18
+ if (!row) return null;
19
+ let old = row.process;
20
+ if (row.exit) {
21
+ return {
22
+ ...old.pid == null ? {} : {
23
+ pid: Number(old.pid)
24
+ },
25
+ exit: {
26
+ code: row.exit.code ?? null
27
+ }
28
+ };
29
+ }
30
+ let seen = await port.look(handle(row));
31
+ if (!seen) return null;
32
+ let pid = seen.pid != null && seen.pid != old.pid ? seen.pid : undefined;
33
+ if (pid != null || seen.exit) {
34
+ await g.apply([
35
+ {
36
+ entity: {
37
+ eid
38
+ },
39
+ ...pid == null ? {} : {
40
+ process: {
41
+ pid
42
+ }
43
+ },
44
+ ...seen.exit ? {
45
+ exit: seen.exit.code == null ? {} : seen.exit
46
+ } : {}
47
+ }
48
+ ], {
49
+ trusted: true
50
+ });
51
+ }
52
+ return seen;
53
+ };
54
+ return {
55
+ ...port,
56
+ start: async (command, cwd, call)=>{
57
+ let eid = call ? idOf(call) : mint();
58
+ let prior = await record(eid);
59
+ if (prior) return eid;
60
+ await g.apply([
61
+ {
62
+ entity: {
63
+ eid
64
+ },
65
+ process: {
66
+ workspace,
67
+ command,
68
+ cwd
69
+ },
70
+ $was: {
71
+ process: {
72
+ workspace: null
73
+ }
74
+ }
75
+ }
76
+ ], {
77
+ trusted: true
78
+ });
79
+ let remote = await port.start(command, cwd, eid);
80
+ if (remote != eid) {
81
+ await g.apply([
82
+ {
83
+ entity: {
84
+ eid
85
+ },
86
+ process: {
87
+ handle: remote
88
+ }
89
+ }
90
+ ], {
91
+ trusted: true
92
+ });
93
+ }
94
+ return eid;
95
+ },
96
+ receipt: async (call)=>await record(idOf(call)) ? idOf(call) : undefined,
97
+ look,
98
+ tail: async (eid, n)=>{
99
+ let row = await record(eid);
100
+ return row ? await port.tail(handle(row), n) : [];
101
+ },
102
+ kill: async (eid, signal)=>{
103
+ let row = await record(eid);
104
+ if (row && !row.exit) await port.kill(handle(row), signal);
105
+ }
106
+ };
107
+ };
108
+ //# sourceMappingURL=recorded.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"recorded.js","sources":["./recorded.ts"],"names":[],"mappings":"AAAA,uEAAuE;AACvE,6EAA6E;AAE7E,SAAS,UAAU,EAAE,IAAI,oCAAyC;AAGlE,0EAA0E,GAC1E,OAAO,IAAI,oBAAoB,CAC7B,GACA,WACA;EAEA,IAAI,OAAO,CAAC,OAAc,WAAW,CAAC,kBAAkB,EAAE,UAAU,CAAC,EAAE,MAAM;EAC7E,IAAI,SAAS,OAAO;IAClB,IAAI,CAAC,IAAI,GAAG,MAAM,EAAE,GAAG,CAAC;MAAC;KAAI,EAAE;MAAC;MAAW;KAAO;IAClD,OAAO,AAAC,KAAK,SAA8B,aAAa,YACpD,MACA;EACN;EACA,IAAI,SAAS,CAAC,MACZ,OAAO,AAAC,IAAI,OAAO,CAAU,MAAM,IAAI,IAAI,MAAM,CAAC,GAAG;EACvD,IAAI,OAA0B,OAAO;IACnC,IAAI,MAAM,MAAM,OAAO;IACvB,IAAI,CAAC,KAAK,OAAO;IACjB,IAAI,MAAM,IAAI,OAAO;IACrB,IAAI,IAAI,IAAI,EAAE;MACZ,OAAO;QACL,GAAG,IAAI,GAAG,IAAI,OAAO,CAAC,IAAI;UAAE,KAAK,OAAO,IAAI,GAAG;QAAE,CAAC;QAClD,MAAM;UAAE,MAAM,AAAC,AAAC,IAAI,IAAI,CAAU,IAAI,I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AAO;MACvB,OAAO,MAAM,MAAM,KAAK,IAAI,CAAC,OAAO,MAAM,KAAK,EAAE;IACnD;IACA,MAAM,OAAO,KAAK;MAChB,IAAI,MAAM,MAAM,OAAO;MACvB,IAAI,OAAO,CAAC,IAAI,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC,OAAO,MAAM;IACrD;EACF;AACF,EAAC"}
package/recorded.ts ADDED
@@ -0,0 +1,74 @@
1
+ // Workspace backends that keep their own process IDs can publish their
2
+ // receipts in the graph without knowing anything about the graph themselves.
3
+ import type { Comp, Eid, Graph } from 'jsr:@yaks/graph@0.2.36'
4
+ import { derivedEid, mint } from '@yaks/graph/identity'
5
+ import type { Workspace } from './workspace.ts'
6
+
7
+ /** Give a workspace graph identities for its running commands and exits. */
8
+ export let recordedWorkspace = (
9
+ g: Graph,
10
+ workspace: Eid,
11
+ port: Workspace,
12
+ ): Workspace => {
13
+ let idOf = (call: Eid) => derivedEid(`workspace process|${workspace}|${call}`)
14
+ let record = async (eid: Eid) => {
15
+ let [row] = await g.get([eid], ['process', 'exit'])
16
+ return (row?.process as Comp | undefined)?.workspace == workspace
17
+ ? row
18
+ : undefined
19
+ }
20
+ let handle = (row: NonNullable<Awaited<ReturnType<typeof record>>>) =>
21
+ String((row.process as Comp).handle ?? row.entity.eid)
22
+ let look: Workspace['look'] = async (eid) => {
23
+ let row = await record(eid)
24
+ if (!row) return null
25
+ let old = row.process as Comp
26
+ if (row.exit) {
27
+ return {
28
+ ...old.pid == null ? {} : { pid: Number(old.pid) },
29
+ exit: { code: ((row.exit as Comp).code as number) ?? null },
30
+ }
31
+ }
32
+ let seen = await port.look(handle(row))
33
+ if (!seen) return null
34
+ let pid = seen.pid != null && seen.pid != old.pid ? seen.pid : undefined
35
+ if (pid != null || seen.exit) {
36
+ await g.apply([{
37
+ entity: { eid },
38
+ ...pid == null ? {} : { process: { pid } },
39
+ ...seen.exit ? { exit: seen.exit.code == null ? {} : seen.exit } : {},
40
+ }], { trusted: true })
41
+ }
42
+ return seen
43
+ }
44
+ return {
45
+ ...port,
46
+ start: async (command, cwd, call) => {
47
+ let eid = call ? idOf(call) : mint()
48
+ let prior = await record(eid)
49
+ if (prior) return eid
50
+ await g.apply([{
51
+ entity: { eid },
52
+ process: { workspace, command, cwd },
53
+ $was: { process: { workspace: null } },
54
+ }], { trusted: true })
55
+ let remote = await port.start(command, cwd, eid)
56
+ if (remote != eid) {
57
+ await g.apply([{ entity: { eid }, process: { handle: remote } }], {
58
+ trusted: true,
59
+ })
60
+ }
61
+ return eid
62
+ },
63
+ receipt: async (call) => await record(idOf(call)) ? idOf(call) : undefined,
64
+ look,
65
+ tail: async (eid, n) => {
66
+ let row = await record(eid)
67
+ return row ? await port.tail(handle(row), n) : []
68
+ },
69
+ kill: async (eid, signal) => {
70
+ let row = await record(eid)
71
+ if (row && !row.exit) await port.kill(handle(row), signal)
72
+ },
73
+ }
74
+ }
package/room.js ADDED
@@ -0,0 +1,160 @@
1
+ // A machine's room: available memory and CPU, I/O and memory pressure.
2
+ // Read them in one control call and judge them with pure functions. Work
3
+ // asks its {@link admitter} first and waits for room when it does not fit,
4
+ // so the machine can finish what it already started.
5
+ import { localConnector } from "./connectors.js";
6
+ import { applicationSlice } from "@yaks/process/isolate";
7
+ import { quote } from "./workspace.js";
8
+ /** An agent run on the box holds 0.3 to 0.6 GB, and its test runs add to that
9
+ * for a while (T-1463 measured 3.6 GB at p90 when tests were heavier). Each
10
+ * start reserves this much until the readings carry its growth. */ export let NEED = {
11
+ memory: 1.5 * 1024 ** 3,
12
+ pressure: 10,
13
+ cpuPressure: 30,
14
+ ioPressure: 20,
15
+ settle: 120_000
16
+ };
17
+ /** Read the machine's pressure, then its memory, in one control call. The
18
+ * cgroup mount root covers the container. Host I/O pressure also covers work
19
+ * outside it, such as Proxmox snapshots on the same disk. */ export let SCRIPT = `cgroup=/sys/fs/cgroup
20
+ wait_pressure() {
21
+ label="$1"
22
+ file="$2"
23
+ if [ -r "$file" ] && read -r kind ten minute rest 2>/dev/null <"$file"; then
24
+ case "$kind:$minute" in
25
+ some:avg60=*) printf '%s: %s\\n' "$label" "\${minute#avg60=}" ;;
26
+ esac
27
+ fi
28
+ }
29
+ for resource in cpu io; do
30
+ path="$cgroup/$resource.pressure"
31
+ [ -r "$path" ] || path="/proc/pressure/$resource"
32
+ wait_pressure "$resource" "$path"
33
+ done
34
+ if [ -r "$cgroup/io.pressure" ]; then
35
+ wait_pressure io /proc/pressure/io
36
+ fi
37
+ pressure=$(cat "$cgroup/memory.pressure" 2>/dev/null) || pressure=''
38
+ case "$pressure" in
39
+ 'some avg10='*) printf '%s\\n' "$pressure" ;;
40
+ *) cat /proc/pressure/memory || exit ;;
41
+ esac
42
+ if read -r limit 2>/dev/null <"$cgroup/memory.max" &&
43
+ read -r current 2>/dev/null <"$cgroup/memory.current"; then
44
+ printf 'CgroupMemory: %s %s\\n' "$limit" "$current"
45
+ fi
46
+ cat /proc/meminfo || exit`;
47
+ // Slice capacity follows its capped ancestors. The parent can be short of
48
+ // room even when the slice could grow into its own cap.
49
+ let sliceRoom = (slice)=>`
50
+ group=$(systemctl --user show --property=ControlGroup --value ${quote(slice)} 2>/dev/null)
51
+ [ -n "$group" ] || exit 0
52
+ while [ -n "$group" ]; do
53
+ path="$cgroup$group"
54
+ if read -r limit <"$path/memory.max" && read -r used <"$path/memory.current"; then
55
+ awk -v limit="$limit" -v used="$used" '
56
+ $1 == "inactive_file" { cache = $2 }
57
+ $1 == "file_dirty" || $1 == "file_writeback" { dirty += $2 }
58
+ END {
59
+ clean = cache > dirty ? cache - dirty : 0
60
+ if (limit != "max") printf "SliceMemory: %.0f\\n", limit - used + clean
61
+ }
62
+ ' "$path/memory.stat"
63
+ sed -n 's/^some avg10=\\([^ ]*\\) .*/SlicePressure: \\1/p' "$path/memory.pressure"
64
+ fi
65
+ wait_pressure cpu "$path/cpu.pressure"
66
+ wait_pressure io "$path/io.pressure"
67
+ group=\${group%/*}
68
+ done`;
69
+ let mem = (text, field)=>{
70
+ let kb = text.match(new RegExp(`^${field}:[ \\t]+(\\d+) kB$`, 'm'));
71
+ if (kb) return Number(kb[1]) * 1024;
72
+ };
73
+ let available = (text)=>{
74
+ let reported = mem(text, 'MemAvailable');
75
+ if (reported != null) return reported;
76
+ let free = mem(text, 'MemFree');
77
+ if (free != null) {
78
+ let cache = (mem(text, 'Buffers') ?? 0) + (mem(text, 'Cached') ?? 0);
79
+ return free + Math.max(0, cache - (mem(text, 'Shmem') ?? 0));
80
+ }
81
+ let group = text.match(/^CgroupMemory: (max|\d+) (\d+)$/m);
82
+ let total = mem(text, 'MemTotal');
83
+ let limit = group && group[1] != 'max' ? Number(group[1]) : total;
84
+ if (group && limit != null) return Math.max(0, limit - Number(group[2]));
85
+ if (total != null) return 0;
86
+ throw new Error('Machine memory reading is missing');
87
+ };
88
+ /** Read a machine's room from what {@link SCRIPT} prints. */ export let roomOf = (text)=>{
89
+ let some = text.match(/^some[ \t]+avg10=(\d+(?:\.\d+)?)(?:[ \t]|$)/m);
90
+ if (!some) {
91
+ throw new Error('Machine memory pressure (PSI some avg10) is missing');
92
+ }
93
+ let limits = [
94
+ ...text.matchAll(/^SliceMemory: (-?\d+)$/gm)
95
+ ];
96
+ let pressures = [
97
+ ...text.matchAll(/^SlicePressure: (\d+(?:\.\d+)?)$/gm)
98
+ ];
99
+ let wait = (resource)=>{
100
+ let readings = [
101
+ ...text.matchAll(new RegExp(`^${resource}: (\\d+(?:\\.\\d+)?)$`, 'gm'))
102
+ ];
103
+ if (readings.length) {
104
+ return Math.max(...readings.map(([, value])=>Number(value)));
105
+ }
106
+ };
107
+ let cpuPressure = wait('cpu'), ioPressure = wait('io');
108
+ return {
109
+ available: Math.max(0, Math.min(available(text), ...limits.map(([, bytes])=>Number(bytes)))),
110
+ pressure: Math.max(Number(some[1]), ...pressures.map(([, pressure])=>Number(pressure))),
111
+ ...cpuPressure == null ? {} : {
112
+ cpuPressure
113
+ },
114
+ ...ioPressure == null ? {} : {
115
+ ioPressure
116
+ }
117
+ };
118
+ };
119
+ /** Read a computer's room, optionally within a systemd user slice. */ export let room = async (transport, slice)=>roomOf(await transport.execute(slice ? SCRIPT + sliceRoom(slice) : SCRIPT));
120
+ /** Whether one more run fits, with `held` runs admitted but not yet grown. */ export let fits = (r, need = NEED, held = 0)=>r.pressure < need.pressure && (r.cpuPressure ?? 0) < (need.cpuPressure ?? Infinity) && (r.ioPressure ?? 0) < (need.ioPressure ?? Infinity) && r.available - held * need.memory >= need.memory;
121
+ /** Read the room left for a start, reserving its need for `settle` ms if it
122
+ * fits. Calls are answered in order so a burst sees its own reservations. */ export let reserving = (read, need = NEED, now = Date.now)=>{
123
+ let held = [];
124
+ let turn = Promise.resolve();
125
+ let reserve = async ()=>{
126
+ let room = await read();
127
+ let t = now();
128
+ held = held.filter((at)=>t - at < need.settle);
129
+ let remaining = {
130
+ ...room,
131
+ available: Math.max(0, room.available - held.length * need.memory)
132
+ };
133
+ if (fits(remaining, need)) held.push(t);
134
+ return remaining;
135
+ };
136
+ return ()=>{
137
+ let answer = turn.then(reserve);
138
+ turn = answer.catch(()=>{});
139
+ return answer;
140
+ };
141
+ };
142
+ /**
143
+ * Whether a run can start now, with room reserved for recent starts.
144
+ *
145
+ * ```ts
146
+ * import { admitter } from '@yaks/machine/room'
147
+ *
148
+ * let admit = admitter(() =>
149
+ * Promise.resolve({ available: 9 * 1024 ** 3, pressure: 0 })
150
+ * )
151
+ * console.assert(await admit() && await admit() && !await admit())
152
+ * ```
153
+ */ export let admitter = (read, need = NEED, now = Date.now)=>{
154
+ let reserve = reserving(read, need, now);
155
+ return async ()=>fits(await reserve(), need);
156
+ };
157
+ /** The room of the computer this process runs on. */ export let hereRoom = async (slice)=>room(await localConnector().connect('local://'), slice);
158
+ /** The {@link admitter} of the computer this process runs on. */ export let here = (need = NEED)=>admitter(hereRoom, need);
159
+ /** The room in the systemd slice that holds managed runs. */ export let managedRoom = ()=>hereRoom(applicationSlice);
160
+ //# sourceMappingURL=room.js.map
package/room.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