@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
@@ -0,0 +1,191 @@
1
+ import * as system from '@yaks/process/system'
2
+ import { command as launchCommand } from '@yaks/process/command'
3
+ // A systemd ExecStopPost reports outside the failed process, so a timeout or
4
+ // SIGKILL cannot silence it. Exit metadata and bounded output from that
5
+ // invocation go to the ordinary spool; the environment is never copied.
6
+ //
7
+ // A clean stop is a failure too when it leaves its template with no instance
8
+ // ready: an in-place `systemctl restart` of the only web refuses every
9
+ // connection until the new one listens, and an MCP client that retries for
10
+ // seconds gives up for good. `yak restart` stops old units only once their
11
+ // replacements are ready (./restart.ts), so a handover reports nothing; its
12
+ // `--replace` hands over a role that already runs current code.
13
+ import type { Command } from './run.ts'
14
+ import { names, read } from './config.js'
15
+ import { reporter } from './report.js'
16
+ import { instanceOf, others } from './restart.js'
17
+
18
+ export type UnitExit = {
19
+ unit: string
20
+ result?: string
21
+ code?: string
22
+ status?: string
23
+ invocation?: string
24
+ /** how many other instances of the unit's template are ready, when asked
25
+ * (`others`) */
26
+ others?: number
27
+ }
28
+
29
+ export let unitFailure = (exit: UnitExit): Error | undefined => {
30
+ if (exit.result == 'success' && exit.others === 0) {
31
+ return Object.assign(
32
+ new Error(
33
+ `systemd unit ${exit.unit} stopped with no other ${
34
+ instanceOf(exit.unit)?.[0]
35
+ }@ ready, so nothing serves it until one starts; ` +
36
+ '`yak restart` hands over ready-first',
37
+ ),
38
+ { name: 'SystemdUnitAlone' },
39
+ )
40
+ }
41
+ if (!exit.result || exit.result == 'success') return
42
+ return Object.assign(
43
+ new Error(
44
+ `systemd unit ${exit.unit} failed: ${exit.result} (${
45
+ exit.code ?? 'unknown'
46
+ } ${exit.status ?? 'unknown'})`,
47
+ ),
48
+ { name: 'SystemdUnitFailure' },
49
+ )
50
+ }
51
+
52
+ // Keep failures of the same unit together only when their termination and
53
+ // known diagnostic agree. The reporter's normal message key drops numbers,
54
+ // which would give every numeric exit code the same bug.
55
+ let diagnostics = [
56
+ ['heap-exhausted', /Fatal JavaScript out of memory/i],
57
+ ['runtime-panic', /Deno has panicked/i],
58
+ ['shutdown-deadline', /yak work shutdown did not drain/i],
59
+ ['inspector-address-in-use', /Failed to start inspector server/i],
60
+ ['dependency-resolution', /Deno expects the node_modules\/ directory/i],
61
+ ['duplicate-component', /component '.+' is declared twice, by /i],
62
+ ] as const
63
+
64
+ let failureKey = (exit: UnitExit, stderr: string) => {
65
+ let unit = instanceOf(exit.unit)?.[0] ?? exit.unit
66
+ let diagnosis = diagnostics.find(([, message]) => message.test(stderr))?.[0]
67
+ return JSON.stringify([
68
+ 'systemd',
69
+ unit,
70
+ exit.result,
71
+ exit.code,
72
+ exit.status,
73
+ diagnosis,
74
+ ])
75
+ }
76
+
77
+ export type Run = (
78
+ command: string,
79
+ args: string[],
80
+ ) => Promise<{ code: number; stdout: string }>
81
+
82
+ let execute: Run = async (command, args) => {
83
+ let output = await launchCommand(command, {
84
+ args,
85
+ stdout: 'piped',
86
+ stderr: 'null',
87
+ stdin: 'null',
88
+ }).output()
89
+ return { code: output.code, stdout: new TextDecoder().decode(output.stdout) }
90
+ }
91
+
92
+ /** Read only this invocation, never a previous restart's output. Journald
93
+ * merges stdout and stderr for these units, so retain both. A host whose
94
+ * runtime journal is root-only may allow a noninteractive privileged read. */
95
+ export let unitOutput = async (
96
+ exit: UnitExit,
97
+ run: Run = execute,
98
+ ): Promise<string> => {
99
+ if (!exit.invocation || !/^[a-f0-9]{32}$/i.test(exit.invocation)) return ''
100
+ let args = [
101
+ '--quiet',
102
+ '--no-pager',
103
+ '--output=cat',
104
+ '--lines=40',
105
+ `_SYSTEMD_USER_UNIT=${exit.unit}`,
106
+ `_SYSTEMD_INVOCATION_ID=${exit.invocation}`,
107
+ `_UID=${system.uid()}`,
108
+ '_TRANSPORT=stdout',
109
+ ]
110
+ for (
111
+ let [command, prefix] of [
112
+ ['journalctl', []],
113
+ ['sudo', ['-n', 'journalctl']],
114
+ ] as const
115
+ ) {
116
+ try {
117
+ let output = await run(command, [...prefix, ...args])
118
+ if (output.code == 0 && output.stdout.trim()) {
119
+ // deno-lint-ignore no-control-regex -- remove journald's ANSI styling
120
+ return output.stdout.replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, '')
121
+ .slice(-8192).trim()
122
+ }
123
+ } catch { /* A missing journal must not silence the failure report. */ }
124
+ }
125
+ return ''
126
+ }
127
+
128
+ export let reportUnit = async (
129
+ exit: UnitExit,
130
+ report: (error: Error, tags: Record<string, string>) => Promise<void>,
131
+ output: (exit: UnitExit) => Promise<string> = unitOutput,
132
+ ): Promise<void> => {
133
+ let error = unitFailure(exit)
134
+ if (!error) return
135
+ let stderr = await output(exit)
136
+ if (exit.result != 'success') {
137
+ Object.assign(error, { fault: failureKey(exit, stderr) })
138
+ }
139
+ await report(
140
+ error,
141
+ {
142
+ ...Object.fromEntries(
143
+ Object.entries(exit).filter(([, value]) => value != null)
144
+ .map(([key, value]) => [key, String(value)]),
145
+ ),
146
+ ...stderr ? { stderr } : {},
147
+ },
148
+ )
149
+ }
150
+
151
+ export let unitFailureCommand: Command = {
152
+ name: 'unit_failure',
153
+ noun: 'unit',
154
+ verb: 'failure',
155
+ description:
156
+ 'Report a systemd unit that failed, or stopped with no other instance of its template ready, from ExecStopPost to the configured tracker spool',
157
+ positional: ['unit'],
158
+ offered: (c) => names(c.config, 'tracker'),
159
+ inputSchema: {
160
+ type: 'object',
161
+ additionalProperties: false,
162
+ required: ['unit'],
163
+ properties: {
164
+ unit: { type: 'string', description: 'the unit that ended (%n)' },
165
+ },
166
+ },
167
+ run: async (args, context) => {
168
+ let exit: UnitExit = {
169
+ unit: String(args.unit),
170
+ result: system.env.get('SERVICE_RESULT'),
171
+ code: system.env.get('EXIT_CODE'),
172
+ status: system.env.get('EXIT_STATUS'),
173
+ invocation: system.env.get('INVOCATION_ID'),
174
+ }
175
+ let runtimeDir = system.env.get('XDG_RUNTIME_DIR')
176
+ if (exit.result == 'success' && runtimeDir) {
177
+ exit.others = await others(exit.unit, runtimeDir)
178
+ }
179
+ if (!unitFailure(exit)) return 0
180
+ if (!context.config) throw new Error('unit failure needs --config')
181
+ let config = read(context.config)
182
+ if (!config.tracker) throw new Error('unit failure needs a tracker spool')
183
+ let report = reporter(config, undefined, undefined, {
184
+ command: 'systemd unit',
185
+ source: 'systemd',
186
+ })
187
+ await reportUnit(exit, (error, tags) => report(error, { tags }))
188
+ await report.close()
189
+ return 0
190
+ },
191
+ }
@@ -0,0 +1,32 @@
1
+ // Schema windows can wait on the disk even when their row count is bounded.
2
+ // Keep that connection, its ANALYZE and its write locks off the duty loop.
3
+ import { portLink } from "@yaks/sync/port";
4
+ export let upkeepThread = async (config, signal, report, start = ()=>new Worker(new URL('./upkeep_worker.ts', import.meta.url), {
5
+ type: 'module'
6
+ }))=>{
7
+ if (signal.aborted) return;
8
+ let worker = start();
9
+ let link = portLink(worker, {
10
+ receive: (work, error)=>report(new Error(String(error)), work)
11
+ });
12
+ // Stop cooperatively: ending a worker during its write would leave a lock
13
+ // held until the native call returned, and would discard its failure.
14
+ let stop = ()=>{
15
+ void link.request('stop', undefined, {
16
+ timeout: null
17
+ }).catch(()=>{});
18
+ };
19
+ signal.addEventListener('abort', stop, {
20
+ once: true
21
+ });
22
+ try {
23
+ await link.request('run', config, {
24
+ timeout: null
25
+ });
26
+ } finally{
27
+ signal.removeEventListener('abort', stop);
28
+ link.close();
29
+ worker.terminate();
30
+ }
31
+ };
32
+ //# sourceMappingURL=upkeep_thread.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"upkeep_thread.js","sources":["./upkeep_thread.ts"],"names":[],"mappings":"AAAA,4EAA4E;AAC5E,2EAA2E;AAE3E,SAAoB,QAAQ,+BAAoC;AAIhE,OAAO,IAAI,eAAe,OACxB,QACA,QACA,QACA,QAAsB,IACpB,IAAI,OAAO,IAAI,IAAI,sBAAsB,YAAY,GAAG,GAAG;IACzD,MAAM;EACR,EAAE;EAEJ,IAAI,OAAO,OAAO,EAAE;EACpB,IAAI,SAAS;EACb,IAAI,OAAO,SAAS,QAAQ;IAC1B,SAAS,CAAC,MAAM,QAAU,OAAO,IAAI,MAAM,OAAO,SAAS;EAC7D;EACA,0EAA0E;EAC1E,sEAAsE;EACtE,IAAI,OAAO;IACT,KAAK,KAAK,OAAO,CAAC,QAAQ,WAAW;MAAE,SAAS;IAAK,GAAG,KAAK,CAAC,KAAO;EACvE;EACA,OAAO,gBAAgB,CAAC,SAAS,MAAM;IAAE,MAAM;EAAK;EACpD,IAAI;IACF,MAAM,KAAK,OAAO,CAAC,OAAO,QAAQ;MAAE,SAAS;IAAK;EACpD,SAAU;IACR,OAAO,mBAAmB,CAAC,SAAS;IACpC,KAAK,KAAK;IACV,OAAO,SAAS;EAClB;AACF,EAAC"}
@@ -0,0 +1,35 @@
1
+ // Schema windows can wait on the disk even when their row count is bounded.
2
+ // Keep that connection, its ANALYZE and its write locks off the duty loop.
3
+ import type { Config } from './config.ts'
4
+ import { type Port, portLink } from '@yaks/sync/port'
5
+
6
+ type Thread = Port & { terminate: () => void }
7
+
8
+ export let upkeepThread = async (
9
+ config: Config,
10
+ signal: AbortSignal,
11
+ report: (error: unknown, work: string) => void,
12
+ start: () => Thread = () =>
13
+ new Worker(new URL('./upkeep_worker.ts', import.meta.url), {
14
+ type: 'module',
15
+ }),
16
+ ): Promise<void> => {
17
+ if (signal.aborted) return
18
+ let worker = start()
19
+ let link = portLink(worker, {
20
+ receive: (work, error) => report(new Error(String(error)), work),
21
+ })
22
+ // Stop cooperatively: ending a worker during its write would leave a lock
23
+ // held until the native call returned, and would discard its failure.
24
+ let stop = () => {
25
+ void link.request('stop', undefined, { timeout: null }).catch(() => {})
26
+ }
27
+ signal.addEventListener('abort', stop, { once: true })
28
+ try {
29
+ await link.request('run', config, { timeout: null })
30
+ } finally {
31
+ signal.removeEventListener('abort', stop)
32
+ link.close()
33
+ worker.terminate()
34
+ }
35
+ }
@@ -0,0 +1,27 @@
1
+ /// <reference no-default-lib="true" />
2
+ /// <reference lib="deno.worker" />
3
+ import { compose, facet } from './host.ts'
4
+ import type { Config } from './config.ts'
5
+ import { type Port, portLink } from 'jsr:@yaks/sync@0.2.36/port'
6
+
7
+ let stopping = new AbortController()
8
+ let link = portLink(self as unknown as Port, {
9
+ receive: async (method, value) => {
10
+ if (method == 'stop') return stopping.abort()
11
+ if (method != 'run') throw new Error(`unknown upkeep request: ${method}`)
12
+ let host = await compose(value as Config, ['graph'], facet, {
13
+ process: false,
14
+ })
15
+ try {
16
+ await host.upkeep(stopping.signal, (error, work) => {
17
+ void link.request(
18
+ work,
19
+ error instanceof Error ? error.stack ?? error.message : String(error),
20
+ { timeout: null },
21
+ )
22
+ })
23
+ } finally {
24
+ await host.close()
25
+ }
26
+ },
27
+ })
package/vault.js ADDED
@@ -0,0 +1,186 @@
1
+ import * as disk from "@yaks/file/io";
2
+ import { queue, ramVault } from "@yaks/secrets";
3
+ // A secret's id is derived from its name, so it is always a uuid. Anything
4
+ // else never came from this vault, and is never turned into a path.
5
+ let OURS = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
6
+ let lstat = (path)=>{
7
+ try {
8
+ return disk.lstatSync(path);
9
+ } catch (e) {
10
+ if (e instanceof disk.errors.NotFound) return null;
11
+ throw e;
12
+ }
13
+ };
14
+ let refuse = (path)=>{
15
+ throw new Error(`${path} is not a vault's own file: refusing to follow it`);
16
+ };
17
+ // The directory, made private — or refused, where something other than the
18
+ // directory this vault made is standing there.
19
+ let own = (dir)=>{
20
+ let at = lstat(dir);
21
+ if (at && (at.isSymlink || !at.isDirectory)) refuse(dir);
22
+ if (!at) disk.mkdirSync(dir, {
23
+ recursive: true,
24
+ mode: 0o700
25
+ });
26
+ disk.chmodSync(dir, 0o700);
27
+ };
28
+ let readIn = (path)=>{
29
+ let at = lstat(path);
30
+ if (!at) return undefined;
31
+ if (at.isSymlink || !at.isFile) refuse(path);
32
+ return disk.readTextFileSync(path);
33
+ };
34
+ let writeIn = (dir, path, text)=>{
35
+ own(dir);
36
+ let at = lstat(path);
37
+ if (at && (at.isSymlink || !at.isFile)) refuse(path);
38
+ let temp = `${path}.${crypto.randomUUID()}.tmp`;
39
+ try {
40
+ disk.writeTextFileSync(temp, text, {
41
+ createNew: true,
42
+ mode: 0o600
43
+ });
44
+ disk.chmodSync(temp, 0o600);
45
+ disk.renameSync(temp, path);
46
+ } catch (e) {
47
+ try {
48
+ disk.removeSync(temp);
49
+ } catch {}
50
+ throw e;
51
+ }
52
+ };
53
+ let unhex = (hex)=>new Uint8Array(hex.match(/../g).map((b)=>parseInt(b, 16)));
54
+ let hex = (bytes)=>[
55
+ ...bytes
56
+ ].map((b)=>b.toString(16).padStart(2, '0')).join('');
57
+ /** The vault in a directory: `<dir>/<eid>.json` per secret, and `<dir>/salt`,
58
+ * the key its sentinels are hashed under, made the first time one is asked
59
+ * for. */ export let fileVault = (dir)=>{
60
+ let file = (eid)=>`${dir}/${eid}.json`;
61
+ let held = queue();
62
+ let version = (path)=>{
63
+ let data = JSON.parse(readIn(path));
64
+ return data.sealed ? data : {
65
+ sealed: data,
66
+ at: lstat(path).mtime.getTime()
67
+ };
68
+ };
69
+ let trash = ()=>{
70
+ if (!lstat(`${dir}/trash`)) return [];
71
+ own(`${dir}/trash`);
72
+ let out = [];
73
+ for (let entry of disk.readDirSync(`${dir}/trash`)){
74
+ let [eid, id, ext] = entry.name.split('.');
75
+ if (ext != 'json' || !OURS.test(eid) || !OURS.test(id)) continue;
76
+ let path = `${dir}/trash/${entry.name}`;
77
+ let { sealed, at } = version(path);
78
+ out.push({
79
+ id,
80
+ eid,
81
+ handle: sealed.handle,
82
+ name: sealed.name,
83
+ at
84
+ });
85
+ }
86
+ return out.sort((a, b)=>b.at - a.at);
87
+ };
88
+ let archive = (eid, move = true)=>{
89
+ let path = file(eid);
90
+ let text = readIn(path);
91
+ if (text === undefined) return;
92
+ let at = Math.max(Date.now(), ...trash().map((entry)=>entry.at + 1));
93
+ let to = `${dir}/trash/${eid}.${crypto.randomUUID()}.json`;
94
+ writeIn(`${dir}/trash`, to, JSON.stringify({
95
+ sealed: JSON.parse(text),
96
+ at
97
+ }) + '\n');
98
+ if (move) disk.removeSync(path);
99
+ };
100
+ let archived = (id)=>{
101
+ let saved = trash().find((entry)=>entry.id == id);
102
+ return saved && {
103
+ ...saved,
104
+ path: `${dir}/trash/${saved.eid}.${saved.id}.json`
105
+ };
106
+ };
107
+ let salt;
108
+ return {
109
+ salt: ()=>{
110
+ if (salt) return salt;
111
+ let said = readIn(`${dir}/salt`)?.trim();
112
+ if (said) return salt = unhex(said);
113
+ salt = crypto.getRandomValues(new Uint8Array(32));
114
+ writeIn(dir, `${dir}/salt`, hex(salt) + '\n');
115
+ return salt;
116
+ },
117
+ read: (eid)=>{
118
+ if (!OURS.test(eid)) return undefined;
119
+ let text = readIn(file(eid));
120
+ return text ? JSON.parse(text) : undefined;
121
+ },
122
+ seal: (eid, sealed)=>{
123
+ if (!OURS.test(eid)) throw new Error(`not a secret's id: ${eid}`);
124
+ let text = JSON.stringify(sealed) + '\n';
125
+ if (readIn(file(eid)) == text) return;
126
+ archive(eid, false);
127
+ writeIn(dir, file(eid), text);
128
+ },
129
+ drop: (eid)=>{
130
+ if (OURS.test(eid)) archive(eid);
131
+ },
132
+ all: ()=>{
133
+ if (!lstat(dir)) return [];
134
+ let out = [];
135
+ for (let e of disk.readDirSync(dir)){
136
+ let eid = e.name.replace(/\.json$/, '');
137
+ if (e.name == eid || !OURS.test(eid)) continue;
138
+ let text = readIn(file(eid));
139
+ if (text) out.push([
140
+ eid,
141
+ JSON.parse(text)
142
+ ]);
143
+ }
144
+ return out;
145
+ },
146
+ trash,
147
+ past: (id)=>{
148
+ let saved = archived(id);
149
+ return saved ? version(saved.path).sealed : undefined;
150
+ },
151
+ restore: (id)=>{
152
+ let saved = archived(id);
153
+ if (!saved) return false;
154
+ archive(saved.eid, false);
155
+ writeIn(dir, file(saved.eid), JSON.stringify(version(saved.path).sealed) + '\n');
156
+ disk.removeSync(saved.path);
157
+ return true;
158
+ },
159
+ purge: (id)=>{
160
+ let saved = archived(id);
161
+ if (saved) disk.removeSync(saved.path);
162
+ },
163
+ // The other writers in this process wait in the queue; the other
164
+ // processes on the box wait on the lock file.
165
+ lock: (eid, fn)=>held(eid, async ()=>{
166
+ if (!OURS.test(eid)) throw new Error(`not a secret's id: ${eid}`);
167
+ own(dir);
168
+ using lock = await disk.open(`${dir}/${eid}.lock`, {
169
+ create: true,
170
+ write: true,
171
+ mode: 0o600
172
+ });
173
+ await lock.lock(true);
174
+ return await fn();
175
+ })
176
+ };
177
+ };
178
+ /** The vault for the graph in the database at `db`: files in a `secrets`
179
+ * directory beside it, or memory for a graph in memory. Made once per graph
180
+ * and handed round, so the plugin sealing a value and the code reading it back
181
+ * hold the same vault — for a graph in memory, the only way they could. */ export let vaultOf = (db)=>{
182
+ if (db == ':memory:') return ramVault();
183
+ let at = db.lastIndexOf('/');
184
+ return fileVault(`${at < 0 ? '.' : db.slice(0, at) || '/'}/secrets`);
185
+ };
186
+ //# sourceMappingURL=vault.js.map
package/vault.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"vault.js","sources":["./vault.ts"],"names":[],"mappings":"AAAA,YAAY,+BAAoC;AAyBhD,SAEE,KAAK,EACL,QAAQ,6BAGuB;AAEjC,2EAA2E;AAC3E,oEAAoE;AACpE,IAAI,OAAO;AAEX,IAAI,QAAQ,CAAC;EACX,IAAI;IACF,OAAO,KAAK,SAAS,CAAC;EACxB,EAAE,OAAO,GAAG;IACV,IAAI,aAAa,KAAK,MAAM,CAAC,QAAQ,EAAE,OAAO;IAC9C,MAAM;EACR;AACF;AAEA,IAAI,SAAS,CAAC;EACZ,MAAM,IAAI,MAAM,GAAG,KAAK,iDAAiD,CAAC;AAC5E;AAEA,2EAA2E;AAC3E,+CAA+C;AAC/C,IAAI,MAAM,CAAC;EACT,IAAI,KAAK,MAAM;EACf,IAAI,MAAM,CAAC,GAAG,SAAS,IAAI,CAAC,GAAG,WAAW,GAAG,OAAO;EACpD,IAAI,CAAC,IAAI,KAAK,SAAS,CAAC,KAAK;IAAE,WAAW;IAAM,MAAM;EAAM;EAC5D,KAAK,SAAS,CAAC,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