@yaks/cli 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 (331) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +1059 -2
  3. package/_dist/account-forward.d.ts +12 -0
  4. package/_dist/account-forward.d.ts.map +1 -0
  5. package/_dist/accounts.d.ts +23 -0
  6. package/_dist/accounts.d.ts.map +1 -0
  7. package/_dist/answer.d.ts +88 -0
  8. package/_dist/answer.d.ts.map +1 -0
  9. package/_dist/apply.d.ts +17 -0
  10. package/_dist/apply.d.ts.map +1 -0
  11. package/_dist/args.d.ts +86 -0
  12. package/_dist/args.d.ts.map +1 -0
  13. package/_dist/commands.d.ts +15 -0
  14. package/_dist/commands.d.ts.map +1 -0
  15. package/_dist/complete.d.ts +15 -0
  16. package/_dist/complete.d.ts.map +1 -0
  17. package/_dist/config.d.ts +37 -0
  18. package/_dist/config.d.ts.map +1 -0
  19. package/_dist/dependencies.d.ts +6 -0
  20. package/_dist/dependencies.d.ts.map +1 -0
  21. package/_dist/facets.d.ts +71 -0
  22. package/_dist/facets.d.ts.map +1 -0
  23. package/_dist/grammar.d.ts +5 -0
  24. package/_dist/grammar.d.ts.map +1 -0
  25. package/_dist/host.d.ts +164 -0
  26. package/_dist/host.d.ts.map +1 -0
  27. package/_dist/install.d.ts +43 -0
  28. package/_dist/install.d.ts.map +1 -0
  29. package/_dist/main.d.ts +16 -0
  30. package/_dist/main.d.ts.map +1 -0
  31. package/_dist/memo.d.ts +60 -0
  32. package/_dist/memo.d.ts.map +1 -0
  33. package/_dist/mod.d.ts +46 -0
  34. package/_dist/mod.d.ts.map +1 -0
  35. package/_dist/page.d.ts +73 -0
  36. package/_dist/page.d.ts.map +1 -0
  37. package/_dist/platform.d.ts +27 -0
  38. package/_dist/platform.d.ts.map +1 -0
  39. package/_dist/reader.d.ts +10 -0
  40. package/_dist/reader.d.ts.map +1 -0
  41. package/_dist/release.d.ts +48 -0
  42. package/_dist/release.d.ts.map +1 -0
  43. package/_dist/remote.d.ts +13 -0
  44. package/_dist/remote.d.ts.map +1 -0
  45. package/_dist/reported.d.ts +11 -0
  46. package/_dist/reported.d.ts.map +1 -0
  47. package/_dist/roles.d.ts +2 -0
  48. package/_dist/roles.d.ts.map +1 -0
  49. package/_dist/roster.d.ts +41 -0
  50. package/_dist/roster.d.ts.map +1 -0
  51. package/_dist/rpc.d.ts +29 -0
  52. package/_dist/rpc.d.ts.map +1 -0
  53. package/_dist/run.d.ts +164 -0
  54. package/_dist/run.d.ts.map +1 -0
  55. package/_dist/runtime.d.ts +4 -0
  56. package/_dist/runtime.d.ts.map +1 -0
  57. package/_dist/searching.d.ts +7 -0
  58. package/_dist/searching.d.ts.map +1 -0
  59. package/_dist/show.d.ts +22 -0
  60. package/_dist/show.d.ts.map +1 -0
  61. package/_dist/store.d.ts +25 -0
  62. package/_dist/store.d.ts.map +1 -0
  63. package/_dist/terminal.d.ts +17 -0
  64. package/_dist/terminal.d.ts.map +1 -0
  65. package/_dist/tool.d.ts +55 -0
  66. package/_dist/tool.d.ts.map +1 -0
  67. package/_dist/tty.d.ts +3 -0
  68. package/_dist/tty.d.ts.map +1 -0
  69. package/_dist/vault.d.ts +9 -0
  70. package/_dist/vault.d.ts.map +1 -0
  71. package/_dist/words.d.ts +11 -0
  72. package/_dist/words.d.ts.map +1 -0
  73. package/_dist/yak.d.ts +10 -0
  74. package/_dist/yak.d.ts.map +1 -0
  75. package/account-forward.js +40 -0
  76. package/account-forward.js.map +1 -0
  77. package/account-forward.ts +50 -0
  78. package/accounts.js +162 -0
  79. package/accounts.js.map +1 -0
  80. package/accounts.ts +228 -0
  81. package/answer.js +394 -0
  82. package/answer.js.map +1 -0
  83. package/answer.ts +569 -0
  84. package/apply.js +49 -0
  85. package/apply.js.map +1 -0
  86. package/apply.ts +54 -0
  87. package/args.js +420 -0
  88. package/args.js.map +1 -0
  89. package/args.ts +494 -0
  90. package/code.js +209 -0
  91. package/code.js.map +1 -0
  92. package/code.ts +227 -0
  93. package/commands.js +131 -0
  94. package/commands.js.map +1 -0
  95. package/commands.ts +142 -0
  96. package/complete.js +104 -0
  97. package/complete.js.map +1 -0
  98. package/complete.ts +152 -0
  99. package/config.js +125 -0
  100. package/config.js.map +1 -0
  101. package/config.ts +180 -0
  102. package/declarations.js +67 -0
  103. package/declarations.js.map +1 -0
  104. package/declarations.ts +84 -0
  105. package/deno.json +1 -0
  106. package/dependencies.js +126 -0
  107. package/dependencies.js.map +1 -0
  108. package/dependencies.ts +141 -0
  109. package/derive.js +102 -0
  110. package/derive.js.map +1 -0
  111. package/derive.ts +125 -0
  112. package/drain.js +83 -0
  113. package/drain.js.map +1 -0
  114. package/drain.ts +115 -0
  115. package/duties.ts +17 -0
  116. package/exports.json +1486 -0
  117. package/external.js +373 -0
  118. package/external.js.map +1 -0
  119. package/external.ts +435 -0
  120. package/facets.js +214 -0
  121. package/facets.js.map +1 -0
  122. package/facets.ts +232 -0
  123. package/feedback.js +54 -0
  124. package/feedback.js.map +1 -0
  125. package/feedback.ts +57 -0
  126. package/files.js +84 -0
  127. package/files.js.map +1 -0
  128. package/files.ts +112 -0
  129. package/get_starts.js +31 -0
  130. package/get_starts.js.map +1 -0
  131. package/get_starts.ts +34 -0
  132. package/git-credential.js +79 -0
  133. package/git-credential.js.map +1 -0
  134. package/git-credential.ts +77 -0
  135. package/grammar.js +4 -0
  136. package/grammar.js.map +1 -0
  137. package/grammar.ts +5 -0
  138. package/held.js +51 -0
  139. package/held.js.map +1 -0
  140. package/held.ts +66 -0
  141. package/host.js +1174 -0
  142. package/host.js.map +1 -0
  143. package/host.ts +1343 -0
  144. package/init.js +138 -0
  145. package/init.js.map +1 -0
  146. package/init.ts +139 -0
  147. package/install.js +216 -0
  148. package/install.js.map +1 -0
  149. package/install.ts +223 -0
  150. package/lifetime.js +56 -0
  151. package/lifetime.js.map +1 -0
  152. package/lifetime.ts +66 -0
  153. package/local-page.ts +114 -0
  154. package/local.js +417 -0
  155. package/local.js.map +1 -0
  156. package/local.ts +537 -0
  157. package/lockfile.js +20 -0
  158. package/lockfile.js.map +1 -0
  159. package/lockfile.ts +32 -0
  160. package/machines.js +33 -0
  161. package/machines.js.map +1 -0
  162. package/machines.ts +51 -0
  163. package/made/4f855610bdabcd736100d34e4e467ea5.json +1 -0
  164. package/main.js +534 -0
  165. package/main.js.map +1 -0
  166. package/main.ts +547 -0
  167. package/mcp.js +108 -0
  168. package/mcp.js.map +1 -0
  169. package/mcp.ts +113 -0
  170. package/member.js +103 -0
  171. package/member.js.map +1 -0
  172. package/member.ts +133 -0
  173. package/memo.js +503 -0
  174. package/memo.js.map +1 -0
  175. package/memo.ts +634 -0
  176. package/mod.js +46 -0
  177. package/mod.js.map +1 -0
  178. package/mod.ts +99 -0
  179. package/operations.js +53 -0
  180. package/operations.js.map +1 -0
  181. package/operations.ts +68 -0
  182. package/package.json +115 -4
  183. package/page.js +211 -0
  184. package/page.js.map +1 -0
  185. package/page.ts +308 -0
  186. package/parser.js +45 -0
  187. package/parser.js.map +1 -0
  188. package/parser.ts +77 -0
  189. package/people-search.js +112 -0
  190. package/people-search.js.map +1 -0
  191. package/people-search.ts +162 -0
  192. package/platform.js +184 -0
  193. package/platform.js.map +1 -0
  194. package/platform.ts +224 -0
  195. package/platform_effects.js +5 -0
  196. package/platform_effects.js.map +1 -0
  197. package/platform_effects.ts +13 -0
  198. package/prepare.js +40 -0
  199. package/prepare.js.map +1 -0
  200. package/prepare.ts +46 -0
  201. package/read_activity.js +54 -0
  202. package/read_activity.js.map +1 -0
  203. package/read_activity.ts +61 -0
  204. package/read_thread.js +387 -0
  205. package/read_thread.js.map +1 -0
  206. package/read_thread.ts +506 -0
  207. package/read_worker.ts +164 -0
  208. package/reader.js +48 -0
  209. package/reader.js.map +1 -0
  210. package/reader.ts +57 -0
  211. package/release.js +82 -0
  212. package/release.js.map +1 -0
  213. package/release.json +127 -0
  214. package/release.ts +98 -0
  215. package/remote-page.ts +70 -0
  216. package/remote.js +96 -0
  217. package/remote.js.map +1 -0
  218. package/remote.ts +153 -0
  219. package/report.js +83 -0
  220. package/report.js.map +1 -0
  221. package/report.ts +101 -0
  222. package/reported.js +32 -0
  223. package/reported.js.map +1 -0
  224. package/reported.ts +38 -0
  225. package/restart.js +349 -0
  226. package/restart.js.map +1 -0
  227. package/restart.ts +478 -0
  228. package/restore.js +32 -0
  229. package/restore.js.map +1 -0
  230. package/restore.ts +38 -0
  231. package/roles.js +32 -0
  232. package/roles.js.map +1 -0
  233. package/roles.ts +49 -0
  234. package/roster.js +65 -0
  235. package/roster.js.map +1 -0
  236. package/roster.ts +84 -0
  237. package/rpc.js +113 -0
  238. package/rpc.js.map +1 -0
  239. package/rpc.ts +159 -0
  240. package/run.js +533 -0
  241. package/run.js.map +1 -0
  242. package/run.ts +741 -0
  243. package/runtime.js +381 -0
  244. package/runtime.js.map +1 -0
  245. package/runtime.ts +433 -0
  246. package/sandboxes.js +26 -0
  247. package/sandboxes.js.map +1 -0
  248. package/sandboxes.ts +30 -0
  249. package/searching.js +33 -0
  250. package/searching.js.map +1 -0
  251. package/searching.ts +50 -0
  252. package/show.js +109 -0
  253. package/show.js.map +1 -0
  254. package/show.ts +144 -0
  255. package/shown.js +13 -0
  256. package/shown.js.map +1 -0
  257. package/shown.ts +44 -0
  258. package/stall.js +90 -0
  259. package/stall.js.map +1 -0
  260. package/stall.ts +156 -0
  261. package/stall_profile.js +113 -0
  262. package/stall_profile.js.map +1 -0
  263. package/stall_profile.ts +142 -0
  264. package/stall_wait.js +183 -0
  265. package/stall_wait.js.map +1 -0
  266. package/stall_wait.ts +249 -0
  267. package/stall_wait_worker.ts +11 -0
  268. package/start.js +349 -0
  269. package/start.js.map +1 -0
  270. package/start.ts +343 -0
  271. package/starvation.js +147 -0
  272. package/starvation.js.map +1 -0
  273. package/starvation.ts +224 -0
  274. package/store.js +118 -0
  275. package/store.js.map +1 -0
  276. package/store.ts +193 -0
  277. package/subcommands.js +62 -0
  278. package/subcommands.js.map +1 -0
  279. package/subcommands.ts +77 -0
  280. package/terminal.js +93 -0
  281. package/terminal.js.map +1 -0
  282. package/terminal.ts +128 -0
  283. package/text.js +20 -0
  284. package/text.js.map +1 -0
  285. package/text.ts +37 -0
  286. package/tool.js +76 -0
  287. package/tool.js.map +1 -0
  288. package/tool.ts +157 -0
  289. package/trace_control.js +231 -0
  290. package/trace_control.js.map +1 -0
  291. package/trace_control.ts +233 -0
  292. package/traces.js +138 -0
  293. package/traces.js.map +1 -0
  294. package/traces.ts +160 -0
  295. package/tracker.js +22 -0
  296. package/tracker.js.map +1 -0
  297. package/tracker.ts +27 -0
  298. package/tty.js +82 -0
  299. package/tty.js.map +1 -0
  300. package/tty.ts +142 -0
  301. package/unit_failure.js +178 -0
  302. package/unit_failure.js.map +1 -0
  303. package/unit_failure.ts +191 -0
  304. package/upkeep_thread.js +32 -0
  305. package/upkeep_thread.js.map +1 -0
  306. package/upkeep_thread.ts +35 -0
  307. package/upkeep_worker.ts +27 -0
  308. package/vault.js +186 -0
  309. package/vault.js.map +1 -0
  310. package/vault.ts +220 -0
  311. package/vocab-ids.js +63 -0
  312. package/vocab-ids.js.map +1 -0
  313. package/vocab-ids.ts +62 -0
  314. package/vocab.json +35 -0
  315. package/warm.js +138 -0
  316. package/warm.js.map +1 -0
  317. package/warm.ts +171 -0
  318. package/watch_revision.js +25 -0
  319. package/watch_revision.js.map +1 -0
  320. package/watch_revision.ts +30 -0
  321. package/words.js +29 -0
  322. package/words.js.map +1 -0
  323. package/words.ts +41 -0
  324. package/workspaces.js +40 -0
  325. package/workspaces.js.map +1 -0
  326. package/workspaces.ts +58 -0
  327. package/yak-unit-failure.conf +6 -0
  328. package/yak-unit-handoff.conf +2 -0
  329. package/yak.js +123 -0
  330. package/yak.js.map +1 -0
  331. package/yak.ts +136 -0
package/restart.ts ADDED
@@ -0,0 +1,478 @@
1
+ import * as disk from '@yaks/file/io'
2
+ import { command as launchCommand } from '@yaks/process/command'
3
+ import * as system from '@yaks/process/system'
4
+ import { codeFile, stale as codeStale } from './code.js'
5
+ import { launching } from './release.js'
6
+ import { FLAGS, runtimeSource, runtimeTree } from './runtime.js'
7
+ // Ready-first handover for the box's processes, queued from the checkout's
8
+ // `yak` ({@link queue}). A role whose running units run the code and config a
9
+ // replacement would (./code.ts) keeps them. Every
10
+ // other role warms its replacement from its unit template and asks the old
11
+ // units of that role to stop after the readiness file arrives. One role warms
12
+ // at a time, so five cold starts cannot compete with the serving box. A worker
13
+ // is ready once its pool and graph are assembled, and its old
14
+ // one drains its steps in flight. A web is ready once it is listening: it
15
+ // shares its port with the one it replaces (`yak serve --share`), so nothing
16
+ // is refused while the old one stops.
17
+
18
+ export type Role = {
19
+ unit: string
20
+ old: string[]
21
+ optional?: boolean
22
+ }
23
+
24
+ export type RestartOptions = {
25
+ /** Wait for, then hold, the box's one handover lock, which keeps the last
26
+ * successful handover's record. */
27
+ lock?: (path: string) => Promise<Held>
28
+ processes?: import('./config.ts').Config['processes']
29
+ runtimeDir: string
30
+ roles?: Role[]
31
+ systemctl?: string
32
+ run?: Run
33
+ ready?: (path: string) => Promise<boolean>
34
+ now?: () => number
35
+ /** Wall-clock milliseconds, finer than one, shared by every caller on the
36
+ * box. */
37
+ clock?: () => number
38
+ /** Why a running unit must be replaced, or undefined when it runs the code
39
+ * and config a replacement would ({@link stale}). */
40
+ stale?: (unit: string) => Promise<string | undefined>
41
+ sleep?: (milliseconds: number) => Promise<void>
42
+ /** Unit names or shorthand (`yak-web` or `web`) to hand over even when
43
+ * they run this code. */
44
+ replace?: string[]
45
+ }
46
+
47
+ type Run = (
48
+ command: string,
49
+ args: string[],
50
+ ) => Promise<{ code: number; stdout: string; stderr: string }>
51
+
52
+ export type Held = {
53
+ read: () => Promise<string>
54
+ write: (text: string) => Promise<void>
55
+ close: () => void
56
+ }
57
+
58
+ /** The box's roles: its graph's workers and web, then the tracker's, rolled
59
+ * only where they run. */
60
+ export let ROLES: Role[] = [
61
+ { unit: 'yak-work', old: ['yak-work@*.service'] },
62
+ { unit: 'yak-tracker', old: ['yak-tracker@*.service'], optional: true },
63
+ { unit: 'yak-web', old: ['yak-web@*.service'] },
64
+ {
65
+ unit: 'yak-tracker-web',
66
+ old: ['yak-tracker-web@*.service'],
67
+ optional: true,
68
+ },
69
+ ]
70
+
71
+ /** How long the supervised handover waits for its replacements to be ready,
72
+ * from when they start, without holding its caller. */
73
+ export let PATIENCE = 120_000
74
+
75
+ /** One systemctl or systemd-run call only queues a job, but on a box busy with
76
+ * landings and restarts that alone can take seconds; a tighter bound aborted
77
+ * a handover halfway, leaving its ready replacements beside the old units. */
78
+ let CALL = 30_000
79
+
80
+ let run: Run = async (command, args) => {
81
+ let result = await launchCommand(command, {
82
+ args,
83
+ signal: AbortSignal.timeout(CALL),
84
+ stdout: 'piped',
85
+ stderr: 'piped',
86
+ }).output()
87
+ let decoder = new TextDecoder()
88
+ return {
89
+ code: result.code,
90
+ stdout: decoder.decode(result.stdout),
91
+ stderr: decoder.decode(result.stderr),
92
+ }
93
+ }
94
+
95
+ /** Queue one supervised handover; its completion never holds the caller.
96
+ * `launch` invokes this CLI, and `run` is the same command boundary as restart.
97
+ * ExecStopPost reports failures even if systemd kills the handover. */
98
+ export let queueRestart = async (
99
+ launch: string[],
100
+ { config, replace = [] }: { config?: string; replace?: string[] } = {},
101
+ execute: Run = run,
102
+ ): Promise<string> => {
103
+ let aimed = config ? [...launch, '--config', config] : launch
104
+ // systemd parses ExecStopPost as an argv, not a shell command. Literal
105
+ // percent signs must not become unit specifiers.
106
+ let quote = (word: string) =>
107
+ '"' + word.replace(/[%$\\"]/g, (c) =>
108
+ c == '%' || c == '$' ? c + c : '\\' + c) +
109
+ '"'
110
+ // Each queued handover is its own unit, so a second one queues behind the
111
+ // running one's lock instead of being refused.
112
+ let unit = `yak-restart-${crypto.randomUUID()}`
113
+ let report = [...aimed, 'unit', 'failure', `${unit}.service`]
114
+ .map(quote).join(' ')
115
+ let result = await execute('systemd-run', [
116
+ '--user',
117
+ '--no-block',
118
+ '--no-ask-password',
119
+ '--expand-environment=no',
120
+ '--quiet',
121
+ '--collect',
122
+ `--unit=${unit}`,
123
+ '--property=Type=exec',
124
+ `--property=ExecStopPost=${report}`,
125
+ '--',
126
+ ...aimed,
127
+ 'restart',
128
+ '--handover',
129
+ ...replace.flatMap((role) => ['--replace', role]),
130
+ ])
131
+ if (result.code) {
132
+ throw new Error(`Could not queue restart: ${result.stderr.trim()}`)
133
+ }
134
+ return `Restart queued in ${unit}.service; handover and failure reporting continue in the background`
135
+ }
136
+
137
+ /** Queue the handover from the checkout's `yak`, never this process's
138
+ * private copy of it (./runtime.ts): the handover judges each unit against the
139
+ * tree it runs from, so it runs from the code a replacement would. Every door
140
+ * restarts this way, a command and a serving process's tool alike. */
141
+ export let queue = async (
142
+ runtimeDir: string,
143
+ { config, replace }: { config?: string; replace?: string[] } = {},
144
+ execute: Run = run,
145
+ ): Promise<string> => {
146
+ let source = (path: string) =>
147
+ runtimeSource(new URL(path, import.meta.url).href)
148
+ let launch = [
149
+ system.execPath(),
150
+ 'run',
151
+ ...FLAGS,
152
+ '--config',
153
+ await launching(
154
+ () => disk.makeTempDir({ dir: runtimeDir, prefix: 'yak-restart-' }),
155
+ source('./release.ts'),
156
+ ),
157
+ source('./yak.ts'),
158
+ ]
159
+ return queueRestart(launch, {
160
+ config: config && disk.resolve(config),
161
+ replace,
162
+ }, execute)
163
+ }
164
+
165
+ /** Where an instance of a unit template says it is ready: the file its
166
+ * `--ready` names, `<runtime>/<template>-<instance>.ready`. */
167
+ export let readyFile = (
168
+ runtimeDir: string,
169
+ template: string,
170
+ instance: string,
171
+ ): string => `${runtimeDir.replace(/\/$/, '')}/${template}-${instance}.ready`
172
+
173
+ /** Whether a ready file is there. */
174
+ export let ready = async (path: string): Promise<boolean> => {
175
+ try {
176
+ return (await disk.stat(path)).isFile
177
+ } catch (error) {
178
+ if (error instanceof disk.errors.NotFound) return false
179
+ throw error
180
+ }
181
+ }
182
+
183
+ /** Why `unit` must be replaced: what differs between the code its record
184
+ * says it runs (./code.ts) and this process's tree, or that either can't be
185
+ * said. */
186
+ export let stale = async (
187
+ runtimeDir: string,
188
+ unit: string,
189
+ ): Promise<string | undefined> => {
190
+ let tree = runtimeTree()
191
+ if (!tree) return 'this restart runs from no pinned tree'
192
+ let instanceUnit = instanceOf(unit)
193
+ if (!instanceUnit) return 'no instance'
194
+ let [template, instance] = instanceUnit
195
+ let file = codeFile(readyFile(runtimeDir, template, instance))
196
+ let code = await disk.readTextFile(file).then(JSON.parse).catch(() =>
197
+ undefined
198
+ )
199
+ return code ? await codeStale(code, tree) : 'it keeps no code record'
200
+ }
201
+
202
+ let listedUnits = (listed: string): string[] =>
203
+ listed.split('\n').map((line) => line.trim().split(/\s+/)[0])
204
+ .filter((unit) => unit.endsWith('.service'))
205
+
206
+ /** The template and instance of a unit such as `yak-web@<id>.service`. */
207
+ export let instanceOf = (unit: string): [string, string] | undefined => {
208
+ let found = unit.match(/^(.+)@(.+)\.service$/)
209
+ return found ? [found[1], found[2]] : undefined
210
+ }
211
+
212
+ /** How many other active instances of `unit`'s template are ready, by user
213
+ * systemd and the ready files in `runtimeDir`. Undefined when that is no
214
+ * question: a unit that is no template instance, or a manager that is
215
+ * stopping, when every unit stops at once. */
216
+ export let others = async (
217
+ unit: string,
218
+ runtimeDir: string,
219
+ execute: (
220
+ command: string,
221
+ args: string[],
222
+ ) => Promise<{ code: number; stdout: string }> = run,
223
+ exists: (path: string) => Promise<boolean> = ready,
224
+ command = 'systemctl',
225
+ ): Promise<number | undefined> => {
226
+ let template = instanceOf(unit)?.[0]
227
+ if (!template) return
228
+ let state = await execute(command, ['--user', 'is-system-running'])
229
+ if (state.stdout.trim() == 'stopping') return
230
+ let listed = await execute(command, [
231
+ '--user',
232
+ 'list-units',
233
+ '--state=active',
234
+ '--plain',
235
+ '--no-legend',
236
+ '--no-pager',
237
+ `${template}@*.service`,
238
+ ])
239
+ if (listed.code) throw new Error(`systemctl could not list ${template}@`)
240
+ let instances = listedUnits(listed.stdout)
241
+ .filter((peer) => peer != unit)
242
+ .flatMap((peer) => instanceOf(peer)?.slice(1) ?? [])
243
+ let found = await Promise.all(
244
+ instances.map((i) => exists(readyFile(runtimeDir, template, i))),
245
+ )
246
+ return found.filter(Boolean).length
247
+ }
248
+
249
+ let matches = (pattern: string, unit: string) => {
250
+ let [before, after] = pattern.split('*')
251
+ return after == null
252
+ ? unit == before
253
+ : unit.startsWith(before) && unit.endsWith(after)
254
+ }
255
+
256
+ // Keep the inode: unlinking it would let a waiter and a new caller lock
257
+ // different files, so the record is written in place. The OS releases the lock
258
+ // even if the CLI is killed.
259
+ let lock = async (path: string): Promise<Held> => {
260
+ let file = await disk.open(path, { create: true, write: true })
261
+ try {
262
+ await file.lock(true)
263
+ } catch (error) {
264
+ file.close()
265
+ throw error
266
+ }
267
+ return {
268
+ read: () => disk.readTextFile(path),
269
+ write: (text) => disk.writeTextFile(path, text),
270
+ close: () => file.close(),
271
+ }
272
+ }
273
+
274
+ let holdRestart = (options: RestartOptions): Promise<Held> =>
275
+ (options.lock ?? lock)(
276
+ `${options.runtimeDir.replace(/\/$/, '')}/yak-restart.lock`,
277
+ )
278
+
279
+ /** Serialize the snapshot and handover across CLI processes. A second caller
280
+ * waits for the running handover; if one began after it was called, that one
281
+ * already started its code, so it coalesces into it instead of rolling again. */
282
+ export let restart = async (options: RestartOptions): Promise<string> => {
283
+ let clock = options.clock ??
284
+ (() => performance.timeOrigin + performance.now())
285
+ let asked = clock()
286
+ let held = await holdRestart(options)
287
+ try {
288
+ let text = await held.read()
289
+ let last: { began: number; said: string } | undefined = text
290
+ ? JSON.parse(text)
291
+ : undefined
292
+ // A later handover may have kept a role this call asks to replace.
293
+ if (last && last.began > asked && !options.replace?.length) {
294
+ return `Coalesced into the restart that began at ${
295
+ new Date(last.began).toISOString()
296
+ }, after this call:\n${last.said}`
297
+ }
298
+ let began = clock()
299
+ let said = await handover(options)
300
+ await held.write(JSON.stringify({ began, said }))
301
+ return said
302
+ } finally {
303
+ held.close()
304
+ }
305
+ }
306
+
307
+ let systemctl = (options: RestartOptions) => {
308
+ let command = options.systemctl ?? 'systemctl'
309
+ return async (...args: string[]) => {
310
+ let result = await (options.run ?? run)(command, ['--user', ...args])
311
+ if (result.code !== 0) {
312
+ throw new Error(
313
+ `${command} ${
314
+ args.join(' ')
315
+ } failed (${result.code}): ${result.stderr.trim()}`,
316
+ )
317
+ }
318
+ return result.stdout
319
+ }
320
+ }
321
+
322
+ let warm = async (
323
+ template: string,
324
+ options: RestartOptions,
325
+ ): Promise<{ unit: string; took: number }> => {
326
+ let call = systemctl(options)
327
+ let exists = options.ready ?? ready
328
+ let now = options.now ?? (() => performance.now())
329
+ let sleep = options.sleep ??
330
+ ((milliseconds: number) =>
331
+ new Promise<void>((resolve) => setTimeout(resolve, milliseconds)))
332
+ let instance = crypto.randomUUID()
333
+ let unit = `${template}@${instance}.service`
334
+ let file = readyFile(options.runtimeDir, template, instance)
335
+ let began = now()
336
+ let deadline = began + PATIENCE
337
+ try {
338
+ await call('--no-block', 'start', unit)
339
+ while (now() < deadline) {
340
+ if (await exists(file) && now() < deadline) {
341
+ return { unit, took: now() - began }
342
+ }
343
+ await sleep(Math.min(100, Math.max(0, deadline - now())))
344
+ }
345
+ // Read the unit state while systemd still has the instance.
346
+ let state = await call(
347
+ 'show',
348
+ unit,
349
+ '--property=Id,ActiveState,SubState,Result,Job,InvocationID,MainPID,ExecMainStartTimestamp,ExecMainStatus',
350
+ ).catch(String)
351
+ throw new Error(
352
+ `Timed out after ${PATIENCE}ms waiting for ${file}\n${state.trim()}`,
353
+ )
354
+ } catch (error) {
355
+ try {
356
+ await call('--no-block', 'stop', unit)
357
+ } catch (cleanup) {
358
+ throw new AggregateError(
359
+ [error, cleanup],
360
+ 'Handover and cleanup failed',
361
+ )
362
+ }
363
+ throw error
364
+ }
365
+ }
366
+
367
+ /** Keep a supervised role covered during a systemd stop. The stop job sends
368
+ * TERM after ExecStop returns. An in-place restart writes a newer ready file
369
+ * when it comes back, and the peer then drains (./lifetime.ts). */
370
+ export let beforeStop = async (
371
+ unit: string,
372
+ options: RestartOptions,
373
+ ): Promise<string | undefined> => {
374
+ let target = instanceOf(unit)
375
+ if (!target) return
376
+ let [template, instance] = target
377
+ let { runtimeDir, run, ready: exists = ready, systemctl } = options
378
+ if (!await exists(readyFile(runtimeDir, template, instance))) return
379
+ let uncovered = async () =>
380
+ await others(unit, runtimeDir, run, exists, systemctl) === 0
381
+ if (!await uncovered()) return
382
+ let held = await holdRestart(options)
383
+ try {
384
+ if (!await uncovered()) return
385
+ let peer = await warm(template, options)
386
+ return `${peer.unit} ready in ${
387
+ (peer.took / 1000).toFixed(1)
388
+ }s; handing off ${unit}`
389
+ } finally {
390
+ held.close()
391
+ }
392
+ }
393
+
394
+ /** Hand every role whose code changed over through user systemd, and say
395
+ * what was done: each replacement, how long it took to be ready, the units it
396
+ * replaces and why, and the units kept. A failure rejects; optional roles are
397
+ * rolled only when active. */
398
+ let handover = async (options: RestartOptions): Promise<string> => {
399
+ let call = systemctl(options)
400
+ let roles = options.roles ?? options.processes?.map((p) => ({
401
+ unit: p.unit,
402
+ old: [`${p.unit}@*.service`],
403
+ optional: p.optional,
404
+ })) ?? ROLES
405
+ let units = new Set(roles.map((role) => role.unit))
406
+ let asked = new Set(
407
+ options.replace?.map((name) =>
408
+ !units.has(name) && units.has(`yak-${name}`) ? `yak-${name}` : name
409
+ ),
410
+ )
411
+ let unknown = [...asked].filter((name) => !units.has(name))
412
+ if (unknown.length) {
413
+ throw new Error(
414
+ `No role ${unknown.join(', ')} to replace; the roles are ${
415
+ roles.map((r) => r.unit).join(', ')
416
+ }`,
417
+ )
418
+ }
419
+ // Snapshot every role first: no candidate can be mistaken for an old unit.
420
+ let listed = await call(
421
+ 'list-units',
422
+ '--state=active',
423
+ '--plain',
424
+ '--no-legend',
425
+ '--no-pager',
426
+ ...roles.flatMap((r) => r.old),
427
+ )
428
+ let active = listedUnits(listed)
429
+ let running = roles.map((r) => ({
430
+ ...r,
431
+ old: active.filter((unit) => r.old.some((p) => matches(p, unit))),
432
+ })).filter((r) => !r.optional || r.old.length)
433
+ // A role whose every unit runs what a replacement would keeps running: a
434
+ // landing that touched one package interrupts only what loads it.
435
+ let judge = options.stale ??
436
+ ((unit: string) => stale(options.runtimeDir, unit))
437
+ let why = await Promise.all(
438
+ running.map((r) =>
439
+ Promise.all(
440
+ r.old.map((unit) =>
441
+ asked.has(r.unit) ? 'asked to replace' : judge(unit).catch(String)
442
+ ),
443
+ )
444
+ ),
445
+ )
446
+ let replacing = running.filter((r, i) =>
447
+ !r.old.length || why[i].some((w) => w !== undefined)
448
+ )
449
+ let kept = running.filter((r) => !replacing.includes(r))
450
+ .flatMap((r) => r.old.map((unit) => `${unit} runs this code; kept`))
451
+ let reasons = new Map(
452
+ running.flatMap((r, i) =>
453
+ r.old.map((unit, j) => [unit, why[i][j]] as const)
454
+ ),
455
+ )
456
+ let roll = async (role: Role): Promise<string> => {
457
+ let { unit, took } = await warm(role.unit, options)
458
+ if (role.old.length) await call('--no-block', 'stop', ...role.old)
459
+ return `${unit} ready in ${(took / 1000).toFixed(1)}s` +
460
+ (role.old.length
461
+ ? `; stopping ${
462
+ role.old.map((u) => reasons.get(u) ? `${u} (${reasons.get(u)})` : u)
463
+ .join(', ')
464
+ }`
465
+ : '')
466
+ }
467
+ let summaries: string[] = [], errors: unknown[] = []
468
+ for (let role of replacing) {
469
+ try {
470
+ summaries.push(await roll(role))
471
+ } catch (error) {
472
+ errors.push(error)
473
+ }
474
+ }
475
+ if (errors.length == 1) throw errors[0]
476
+ if (errors.length) throw new AggregateError(errors, 'Handover failed')
477
+ return [...summaries, ...kept].join('\n')
478
+ }
package/restore.js ADDED
@@ -0,0 +1,32 @@
1
+ // A local command can restore already stamped bundles. The flag belongs to
2
+ // this filesystem door, never to a public graph tool's input or authority.
3
+ import { Usage } from "./args.js";
4
+ export let restorable = (command, restore)=>({
5
+ ...command,
6
+ inputSchema: {
7
+ ...command.inputSchema,
8
+ properties: {
9
+ ...command.inputSchema?.properties ?? {},
10
+ restore: {
11
+ type: 'boolean',
12
+ description: 'preserve supplied server-owned values in a local graph'
13
+ },
14
+ stamp: {
15
+ type: 'boolean',
16
+ description: 'generate stamps during a local restoration (default: true)'
17
+ }
18
+ }
19
+ },
20
+ run: (args, c)=>{
21
+ let { restore: restoring, ...input } = args;
22
+ if (!restoring) {
23
+ if (input.stamp !== undefined) throw new Usage('--stamp needs --restore');
24
+ return command.run(input, c);
25
+ }
26
+ if (!c.config) {
27
+ throw new Usage('--restore needs a local graph opened with --config');
28
+ }
29
+ return restore(input, c);
30
+ }
31
+ });
32
+ //# sourceMappingURL=restore.js.map
package/restore.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"restore.js","sources":["./restore.ts"],"names":[],"mappings":"AAAA,2EAA2E;AAC3E,2EAA2E;AAE3E,SAAS,KAAK,oBAAmB;AAGjC,OAAO,IAAI,aAAa,CACtB,SACA,UACY,CAAC;IACb,GAAG,OAAO;IACV,aAAa;MACX,GAAG,QAAQ,WAAW;MACtB,YAAY;QACV,GAAI,QAAQ,WAAW,EAAE,cAAyC,CAAC,CAAC;QACpE,SAAS;UACP,MAAM;UACN,aAAa;QACf;QACA,OAAO;UACL,MAAM;UACN,aACE;QACJ;MACF;IACF;IACA,KAAK,CAAC,MAAM;MACV,IAAI,EAAE,SAAS,SAAS,EAAE,GAAG,OAAO,GAAG;MACvC,IAAI,CAAC,WAAW;QACd,IAAI,MAAM,KAAK,KAAK,WAAW,MAAM,IAAI,MAAM;QAC/C,OAAO,QAAQ,GAAG,CAAC,OAAO;MAC5B;MACA,IAAI,CAAC,EAAE,MAAM,EAAE;QACb,MAAM,IAAI,MAAM;MAClB;MACA,OAAO,QAAQ,OAAO;IACxB;EACF,CAAC,EAAC"}
package/restore.ts ADDED
@@ -0,0 +1,38 @@
1
+ // A local command can restore already stamped bundles. The flag belongs to
2
+ // this filesystem door, never to a public graph tool's input or authority.
3
+
4
+ import { Usage } from './args.js'
5
+ import type { Command, Ctx } from './run.ts'
6
+
7
+ export let restorable = (
8
+ command: Command,
9
+ restore: (args: Record<string, unknown>, c: Ctx) => Promise<number>,
10
+ ): Command => ({
11
+ ...command,
12
+ inputSchema: {
13
+ ...command.inputSchema,
14
+ properties: {
15
+ ...(command.inputSchema?.properties as Record<string, unknown> ?? {}),
16
+ restore: {
17
+ type: 'boolean',
18
+ description: 'preserve supplied server-owned values in a local graph',
19
+ },
20
+ stamp: {
21
+ type: 'boolean',
22
+ description:
23
+ 'generate stamps during a local restoration (default: true)',
24
+ },
25
+ },
26
+ },
27
+ run: (args, c) => {
28
+ let { restore: restoring, ...input } = args
29
+ if (!restoring) {
30
+ if (input.stamp !== undefined) throw new Usage('--stamp needs --restore')
31
+ return command.run(input, c)
32
+ }
33
+ if (!c.config) {
34
+ throw new Usage('--restore needs a local graph opened with --config')
35
+ }
36
+ return restore(input, c)
37
+ },
38
+ })
package/roles.js ADDED
@@ -0,0 +1,32 @@
1
+ import { facetsOf, used } from "@yaks/host/config";
2
+ export { ROLES } from "@yaks/host/roles";
3
+ /** The graph and the roles a tool requests. A graph with no effect pool runs
4
+ * its effects where they are committed. */ export let rolesOf = (tool, pooled)=>[
5
+ ...new Set([
6
+ 'graph',
7
+ ...pooled ? [] : [
8
+ 'effects'
9
+ ],
10
+ ...tool.roles ?? []
11
+ ])
12
+ ];
13
+ /** Duties depend on declarations, not a second vocabulary runtime. */ export let dutyRoles = (config, pooled, mine, has)=>[
14
+ ...pooled ? [
15
+ 'effects'
16
+ ] : [],
17
+ ...(config.plugins ?? []).filter((p)=>facetsOf(p)?.includes('service') ?? true).map(used).filter((p)=>has(p, 'service'))
18
+ ].filter((role)=>!mine.includes(role));
19
+ /** A configured worker's duties, validated before composition. */ export let workerRoles = (config, duties, only, process)=>{
20
+ let layout = process ? config.processes?.find((p)=>p.unit == process) : undefined;
21
+ if (process && !layout) throw new Error(`No configured process: ${process}`);
22
+ let roles = only ?? layout?.roles ?? duties;
23
+ roles = roles.filter((role)=>!layout?.except?.includes(role));
24
+ if (roles.some((role)=>!duties.includes(role))) {
25
+ throw new Error('work was asked for a role this config does not serve');
26
+ }
27
+ return [
28
+ 'graph',
29
+ ...roles
30
+ ];
31
+ };
32
+ //# sourceMappingURL=roles.js.map
package/roles.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"roles.js","sources":["./roles.ts"],"names":[],"mappings":"AAAA,SAAS,QAAQ,EAAE,IAAI,iCAAsC;AAM7D,SAAS,KAAK,gCAAqC;AAEnD;yCACyC,GACzC,OAAO,IAAI,UAAU,CACnB,MACA,SACW;OACR,IAAI,IAAI;MAAC;SAAY,SAAS,EAAE,GAAG;QAAC;OAAU;SAAK,KAAK,KAAK,IAAI,EAAE;KAAC;GACxE,CAAA;AAED,oEAAoE,GACpE,OAAO,IAAI,YAAY,CACrB,QACA,QACA,MACA,MAEA;OACK,SAAS;MAAC;KAAU,GAAG,EAAE;OACzB,CAAC,OAAO,OAAO,IAAI,EAAE,EAAE,MAAM,CAAC,CAAC,IAChC,SAAS,IAAI,SAAS,cAAc,MACpC,GAAG,CAAC,MAAM,MAAM,CAAC,CAAC,IAAM,IAAI,GAAG;GAClC,CAAC,MAAM,CAAC,CAAC,OAAS,CAAC,KAAK,QAAQ,CAAC,OAAM;AAE1C,gEAAgE,GAChE,OAAO,IAAI,cAAc,CACvB,QACA,QACA,MACA;EAEA,IAAI,SAAS,UACT,OAAO,SAAS,EAAE,KAAK,CAAC,IAAM,EAAE,IAAI,IAAI,WACxC;EACJ,IAAI,WAAW,CAAC,QAAQ,MAAM,IAAI,MAAM,CAAC,uBAAuB,EAAE,SAAS;EAC3E,IAAI,QAAQ,QAAQ,QAAQ,SAAS;EACrC,QAAQ,MAAM,MAAM,CAAC,CAAC,OAAS,CAAC,QAAQ,QAAQ,SAAS;EACzD,IAAI,MAAM,IAAI,CAAC,CAAC,OAAS,CAAC,OAAO,QAAQ,CAAC,QAAQ;IAChD,MAAM,IAAI,MAAM;EAClB;EACA,OAAO;IAAC;OAAY;GAAM;AAC5B,EAAC"}
package/roles.ts ADDED
@@ -0,0 +1,49 @@
1
+ import { facetsOf, used } from '@yaks/host/config'
2
+ // The facets a process serves, and the roles one command needs. This data is
3
+ // shared by import preparation and composition; reading it opens nothing.
4
+ import type { Declared } from './words.ts'
5
+ import type { Role } from './host.ts'
6
+
7
+ export { ROLES } from '@yaks/host/roles'
8
+
9
+ /** The graph and the roles a tool requests. A graph with no effect pool runs
10
+ * its effects where they are committed. */
11
+ export let rolesOf = (
12
+ tool: Pick<Declared, 'roles'>,
13
+ pooled: boolean,
14
+ ): Role[] => [
15
+ ...new Set(['graph', ...pooled ? [] : ['effects'], ...tool.roles ?? []]),
16
+ ]
17
+
18
+ /** Duties depend on declarations, not a second vocabulary runtime. */
19
+ export let dutyRoles = (
20
+ config: import('./config.ts').Config,
21
+ pooled: boolean,
22
+ mine: readonly Role[],
23
+ has: (plugin: string, facet: string) => boolean,
24
+ ): Role[] =>
25
+ [
26
+ ...pooled ? ['effects'] : [],
27
+ ...(config.plugins ?? []).filter((p) =>
28
+ facetsOf(p)?.includes('service') ?? true
29
+ ).map(used).filter((p) => has(p, 'service')),
30
+ ].filter((role) => !mine.includes(role))
31
+
32
+ /** A configured worker's duties, validated before composition. */
33
+ export let workerRoles = (
34
+ config: import('./config.ts').Config,
35
+ duties: string[],
36
+ only?: string[],
37
+ process?: string,
38
+ ): string[] => {
39
+ let layout = process
40
+ ? config.processes?.find((p) => p.unit == process)
41
+ : undefined
42
+ if (process && !layout) throw new Error(`No configured process: ${process}`)
43
+ let roles = only ?? layout?.roles ?? duties
44
+ roles = roles.filter((role) => !layout?.except?.includes(role))
45
+ if (roles.some((role) => !duties.includes(role))) {
46
+ throw new Error('work was asked for a role this config does not serve')
47
+ }
48
+ return ['graph', ...roles]
49
+ }