@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/read_thread.ts ADDED
@@ -0,0 +1,506 @@
1
+ // A web or worker host reads through a bounded pool of read-only workers, each
2
+ // started once and kept. A worker is never ended to cancel a read: Deno keeps part of
3
+ // every worker that ends (7 to 14 MB of the modules it loaded, measured on
4
+ // Deno 2.9), so a web that ended one per cancelled read grew by gigabytes a
5
+ // day as tabs navigated (T-130803). A cancelled read is answered at once, and
6
+ // its worker finishes the synchronous SQL unheard, then takes the next read.
7
+ import { mask, parse, stringify } from '@yaks/query'
8
+ import type {
9
+ Binding,
10
+ Bundle,
11
+ Committed,
12
+ Eid,
13
+ Graph,
14
+ Graves,
15
+ Query,
16
+ ReadOpts,
17
+ Row,
18
+ Taken,
19
+ Tx,
20
+ } from 'jsr:@yaks/graph@0.2.36'
21
+ import type { Search } from 'jsr:@yaks/graph@0.2.36/tools'
22
+ import { type Asker, asker } from '@yaks/graph/asker'
23
+ import type { Meaning, MeaningHit } from 'jsr:@yaks/host@0.2.36'
24
+ import { type Context, context, type Event, forward } from '@yaks/trace'
25
+ import { how, off, own, since, type Spent, spent } from './stall.js'
26
+ import { cpuStarvation, diskStarvation } from './starvation.js'
27
+ import { readActivity } from './read_activity.js'
28
+ import { waitLog, waits, watchWait } from './stall_wait.js'
29
+ import { type Found, searching } from './searching.js'
30
+ import type { Hit } from 'jsr:@yaks/fts@0.2.36'
31
+ import type { Stmt } from 'jsr:@yaks/sql@0.2.36'
32
+
33
+ /** Everything a web host asks of its store that only reads it: the graph's
34
+ * reads, ranked text search and search by meaning. */
35
+ export type Reader = Pick<Graph, 'read' | 'rows' | 'get'> & {
36
+ search: Search
37
+ meaning: Meaning
38
+ storage: Committed
39
+ statements: { query: (stmt: Stmt) => Promise<Row[]> }
40
+ tool: (name: string, call: Bundle) => Promise<Bundle[]>
41
+ readable: (answer: Bundle[]) => Promise<Bundle[]>
42
+ }
43
+
44
+ type Call =
45
+ | { op: 'rawRead'; query: Query; opts?: ReadOpts; comps?: string[] }
46
+ | { op: 'rawRows'; query: Query; opts?: ReadOpts }
47
+ | { op: 'rawGet'; eids: Eid[]; comps?: string[]; opts?: ReadOpts }
48
+ | { op: 'revision' }
49
+ | { op: 'newest'; comp: string }
50
+ | { op: 'buried'; before: string; page: { after?: string; limit: number } }
51
+ | { op: 'bindings'; args: Parameters<NonNullable<Tx['bindings']>> }
52
+ | { op: 'statement'; stmt: Stmt }
53
+ | { op: 'tool'; name: string; call: Bundle }
54
+ | { op: 'readable'; answer: Bundle[] }
55
+ | { op: 'read' | 'rows'; query: Taken; opts?: ReadOpts }
56
+ | { op: 'get'; eids: Eid[]; comps?: string[]; opts?: ReadOpts }
57
+ | {
58
+ op: 'hits' | 'meaning'
59
+ words: string
60
+ opts?: { limit?: number; within?: string; signal?: AbortSignal }
61
+ }
62
+ | {
63
+ op: 'said'
64
+ words: string
65
+ found: Found
66
+ opts: { limit: number; signal?: AbortSignal }
67
+ }
68
+
69
+ export type Said =
70
+ | { start: string; activity: SharedArrayBuffer }
71
+ | (Call & { id: number; observed?: boolean })
72
+ | { close: true }
73
+
74
+ type Traced = { spans?: Event[]; origin?: number }
75
+ export type Heard =
76
+ | ({ id: number; value: unknown } & Traced)
77
+ | (
78
+ & { id: number; error: { name: string; message: string; details: object } }
79
+ & Traced
80
+ )
81
+ | { closed: true }
82
+ /** where the worker's thread is, for {@link spent} */
83
+ | { thread: string }
84
+ /** its worker composed its graph, or failed to: a read it was given begins */
85
+ | { started: true }
86
+
87
+ let later = (fn: () => void, ms: number) => {
88
+ let id = setTimeout(fn, ms)
89
+ return () => clearTimeout(id)
90
+ }
91
+
92
+ /** What a read asked, as a trace keeps it: every value masked, bounded. */
93
+ let asked = (call: Call): string =>
94
+ call.op == 'get' || call.op == 'rawGet'
95
+ ? `get of ${call.eids.length} entities`
96
+ : call.op == 'tool'
97
+ ? call.name
98
+ : 'words' in call
99
+ ? `${call.op} of ${call.words.length} characters`
100
+ : !('query' in call)
101
+ ? call.op
102
+ : mask(typeof call.query == 'string' ? call.query : stringify(call.query))
103
+ .slice(0, 512)
104
+
105
+ // A read refused at shutdown says which read it was and who asked it, so the
106
+ // reader that outlived its host is named in the report.
107
+ let shut = (said: string, call: Call, by = asker()): Error =>
108
+ new Error(`${said}: ${asked(call)}${by ? ` (asked by ${by.door})` : ''}`)
109
+
110
+ /** Independent reads share at most two workers, started when needed or by
111
+ * `ready`, and kept for the reader's life. Each worker owns one read at a time. A read
112
+ * cancelled while it runs is rejected at once and its answer dropped when it
113
+ * comes; only one still running `grace` ms after its caller left and its
114
+ * worker began it (a runaway query) ends its worker, so it cannot hold a lane for good. A read still
115
+ * running when its own time passes `slow` ms is told to whoever `overrun` was
116
+ * given, once, with its masked query and who asked it (@yaks/graph/asker,
117
+ * taken when the read was asked): one that runs on is a failure, and the
118
+ * query and its door are what name it. A read's time begins when its worker
119
+ * has started: a read given to a worker still loading its modules and
120
+ * composing its graph waits on the start, as a queued read waits on its lane,
121
+ * and a start the disk held is not the query's. Its own time is its wall
122
+ * clock less what the box kept its worker waiting for a CPU (./stall.ts), and
123
+ * less the time it was blocked on a disk others kept busy, so a busy box makes
124
+ * no read slow: each is told once per box incident (./starvation.ts), a CPU
125
+ * wait only once it is at least the read's own time. One the worker cuts off past its budget (@yaks/sqlite/budget) is a
126
+ * refusal its caller hears, not a failure. */
127
+ export let readThread = (
128
+ config: string,
129
+ {
130
+ grace = 10_000,
131
+ slow = 10_000,
132
+ timer = later,
133
+ now = Date.now,
134
+ measure = spent,
135
+ starved = cpuStarvation,
136
+ diskStarved = diskStarvation,
137
+ observe = watchWait,
138
+ }: {
139
+ grace?: number
140
+ slow?: number
141
+ /** schedule `fn` after `ms` and return its cancellation */
142
+ timer?: (fn: () => void, ms: number) => () => void
143
+ /** ms since the epoch: the clock the worker stamps its operations by */
144
+ now?: () => number
145
+ /** what a worker's thread has spent, by where it is */
146
+ measure?: (thread: string) => Spent | undefined
147
+ starved?: (evidence: string, report: (error: Error) => void) => void
148
+ diskStarved?: (evidence: string, report: (error: Error) => void) => void
149
+ observe?: typeof watchWait
150
+ } = {},
151
+ ): Reader & {
152
+ ready: () => Promise<void>
153
+ close: () => Promise<void>
154
+ /** where a read that runs past `slow` is told, with who asked it */
155
+ overrun: (tell: (error: Error, asker?: Asker) => void) => void
156
+ } => {
157
+ type Job = {
158
+ id: number
159
+ call: Call
160
+ resolve: (value: unknown) => void
161
+ reject: (error: unknown) => void
162
+ trace?: Context
163
+ /** who asked it, as its door said */
164
+ asker?: Asker
165
+ off: () => void
166
+ /** its caller left; the answer goes nowhere */
167
+ dropped?: boolean
168
+ /** when its worker began it (`now`): given it, once started, and what
169
+ * the worker's thread had spent then */
170
+ sent?: number
171
+ spent?: Spent
172
+ starved?: boolean
173
+ diskStarved?: boolean
174
+ waitLog?: ReturnType<typeof waitLog>
175
+ }
176
+ type Lane = {
177
+ worker: Worker
178
+ job?: Job
179
+ overdue?: () => void
180
+ long?: () => void
181
+ unwatch?: () => void
182
+ /** its worker has composed its graph, or failed to */
183
+ started?: boolean
184
+ /** its worker has answered a read */
185
+ heard?: boolean
186
+ /** where its worker's thread is, once the worker has said */
187
+ thread?: string
188
+ activity: ReturnType<typeof readActivity>
189
+ key: string
190
+ }
191
+ let told: (error: Error, asker?: Asker) => void = () => {}
192
+ let lanes = new Set<Lane>()
193
+ let waiting: Job[] = []
194
+ let next = 0
195
+ let closed = false
196
+ let stop = (lane: Lane) => {
197
+ lane.overdue?.()
198
+ lane.long?.()
199
+ lane.unwatch?.()
200
+ lane.worker.terminate()
201
+ lanes.delete(lane)
202
+ }
203
+ let finish = (lane: Lane, answer: Heard) => {
204
+ if ('thread' in answer) return void (lane.thread = answer.thread)
205
+ if ('started' in answer) {
206
+ lane.started = true
207
+ if (lane.job) begin(lane, lane.job)
208
+ return
209
+ }
210
+ if ('closed' in answer || lane.job?.id != answer.id) return
211
+ let job = lane.job
212
+ lane.job = undefined
213
+ lane.heard = true
214
+ lane.overdue?.()
215
+ lane.long?.()
216
+ lane.unwatch?.()
217
+ job.off()
218
+ if (job.dropped) return drain()
219
+ if (job.trace && answer.spans) {
220
+ forward(job.trace, answer.spans, answer.origin)
221
+ }
222
+ if ('error' in answer) {
223
+ let error = Object.assign(
224
+ new Error(answer.error.message),
225
+ answer.error.details,
226
+ )
227
+ error.name = answer.error.name
228
+ job.reject(error)
229
+ } else {
230
+ job.resolve(
231
+ // Revision tokens belong to one connection: equal numbers from two
232
+ // lanes need not describe the same committed state.
233
+ job.call.op == 'revision' && answer.value !== undefined
234
+ ? JSON.stringify([lane.key, answer.value])
235
+ : answer.value,
236
+ )
237
+ }
238
+ drain()
239
+ }
240
+ let start = () => {
241
+ let worker = new Worker(new URL('./read_worker.ts', import.meta.url), {
242
+ type: 'module',
243
+ })
244
+ let activity = readActivity(undefined, now)
245
+ activity.say('waiting for the worker to receive its configuration')
246
+ let lane: Lane = { worker, activity, key: crypto.randomUUID() }
247
+ lanes.add(lane)
248
+ worker.onmessage = ({ data }: MessageEvent<Heard>) => finish(lane, data)
249
+ worker.onerror = (event) => {
250
+ event.preventDefault()
251
+ let job = lane.job
252
+ stop(lane)
253
+ job?.off()
254
+ job?.reject(
255
+ event.error instanceof Error ? event.error : new Error(event.message),
256
+ )
257
+ drain()
258
+ }
259
+ worker.postMessage(
260
+ { start: config, activity: activity.buffer } satisfies Said,
261
+ )
262
+ return lane
263
+ }
264
+ // The worker's operation, and how long it had been in it, so a report
265
+ // tells a slow query from a slow reply.
266
+ let doing = (lane: Lane) => {
267
+ let op = lane.activity.read()
268
+ return `worker operation: ${
269
+ op
270
+ ? `${op.text}, for ${(op.ms / 1000).toFixed(1)} s`
271
+ : 'changing while sampled'
272
+ }`
273
+ }
274
+ let spentBy = (lane: Lane) => lane.thread ? measure(lane.thread) : undefined
275
+ // What a read past `slow` waited on, as far as this thread can see: how its
276
+ // worker spent the time, a worker that never answered was still loading,
277
+ // and the other lane's read and the queue are what it ran beside.
278
+ let waited = (lane: Lane, job: Job, ran: number, s?: Spent): string =>
279
+ [
280
+ how('its worker', ran, s),
281
+ doing(lane),
282
+ job.waitLog
283
+ ? waits(job.waitLog.read(), job.sent!, job.sent! + ran)
284
+ : lane.thread
285
+ ? 'kernel wait sampling did not start'
286
+ : '',
287
+ lane.heard ? '' : 'its worker had not answered a read yet',
288
+ ...[...lanes].flatMap((l) =>
289
+ l == lane || !l.job
290
+ ? []
291
+ : l.job.sent == undefined
292
+ ? [`the other lane's worker was starting for ${asked(l.job.call)}`]
293
+ : [
294
+ `the other lane ran ${asked(l.job.call)} for ${
295
+ ((now() - l.job.sent) / 1000).toFixed(1)
296
+ } s`,
297
+ ]
298
+ ),
299
+ waiting.length ? `${waiting.length} reads waited behind it` : '',
300
+ ].filter(Boolean).join('; ')
301
+ // The ms the disk held a read: all the time its worker was blocked, when
302
+ // most of its sampled waits were uninterruptible (D: the disk, or memory
303
+ // paged back in) and storage read it under 1 MB a second of them. A query
304
+ // that reads much reads at the disk's speed; one that waits seconds on a
305
+ // few pages waited behind others' use of the disk.
306
+ let diskHeld = (job: Job, ran: number, s?: Spent): number => {
307
+ if (s?.read == undefined || !job.waitLog) return 0
308
+ let samples = job.waitLog.read().filter((w) =>
309
+ w.at >= job.sent! && w.at <= job.sent! + ran
310
+ )
311
+ let stuck = samples.filter((w) => w.state.startsWith('D/')).length
312
+ let blocked = off(ran, s)
313
+ return samples.length && stuck * 2 >= samples.length &&
314
+ s.read < blocked * 1000
315
+ ? blocked
316
+ : 0
317
+ }
318
+ // A timer can run first in the very turn the main thread comes free, with
319
+ // the answer already waiting behind it, so no first look tells: a second
320
+ // one follows a turn later (./stall.ts tells of what held the thread).
321
+ let check = (lane: Lane, job: Job, due: number, looked = false) => () => {
322
+ if (lane.job !== job || lane.activity.completed(job.id)) return
323
+ let at = now()
324
+ let again = (ms: number) =>
325
+ void (lane.long = timer(check(lane, job, at + ms, true), ms))
326
+ let ran = at - job.sent!, s = since(job.spent, spentBy(lane))
327
+ let held = diskHeld(job, ran, s)
328
+ let left = slow - own(ran, s) + held
329
+ // The box starved the read only when it kept it waiting for a CPU at
330
+ // least as long as the read had of its own: a second's wait in a read
331
+ // that spent the rest on its own disk reads is the read's slowness.
332
+ let wait = s?.wait ?? 0
333
+ if (
334
+ left > 0 && wait >= 1000 && wait >= own(ran, s) && !job.starved
335
+ ) {
336
+ job.starved = true
337
+ starved(
338
+ `${how('a read worker', ran, s)}; ${doing(lane)}`,
339
+ (error) => told(error),
340
+ )
341
+ }
342
+ if (left > 0 && held >= 1000 && !job.diskStarved) {
343
+ job.diskStarved = true
344
+ diskStarved(waited(lane, job, ran, s), (error) => told(error))
345
+ }
346
+ if (!looked || at - due >= 1000 || left > 0) {
347
+ return again(Math.max(1000, left))
348
+ }
349
+ told(
350
+ Object.assign(
351
+ new Error(
352
+ `a read has run ${slow / 1000} s and is still running: ` +
353
+ asked(job.call),
354
+ { cause: new Error(waited(lane, job, ran, s)) },
355
+ ),
356
+ { name: 'SlowRead' },
357
+ ),
358
+ job.asker,
359
+ )
360
+ lane.unwatch?.()
361
+ }
362
+ // A read its caller left that still runs `grace` ms on ends its worker.
363
+ let overdue = (lane: Lane, job: Job) =>
364
+ void (lane.overdue = timer(() => {
365
+ if (lane.job !== job || lane.activity.completed(job.id)) return
366
+ stop(lane)
367
+ drain()
368
+ }, grace))
369
+ // A read's clocks start once its worker has: `slow` for its report, and
370
+ // `grace` for one its caller already left.
371
+ let begin = (lane: Lane, job: Job) => {
372
+ job.sent = now()
373
+ job.spent = spentBy(lane)
374
+ lane.unwatch = timer(() => {
375
+ if (lane.job !== job || lane.activity.completed(job.id) || !lane.thread) {
376
+ return
377
+ }
378
+ job.waitLog = waitLog()
379
+ lane.unwatch = observe(lane.thread, job.waitLog, { now })
380
+ }, Math.min(1000, slow))
381
+ lane.long = timer(check(lane, job, job.sent + slow), slow)
382
+ if (job.dropped) overdue(lane, job)
383
+ }
384
+ let drain = () => {
385
+ while (waiting.length && !closed) {
386
+ let lane = [...lanes].find((l) => !l.job)
387
+ if (!lane && lanes.size < 2) lane = start()
388
+ if (!lane) return
389
+ let job = waiting.shift()!
390
+ lane.job = job
391
+ if (lane.started) begin(lane, job)
392
+ lane.worker.postMessage({
393
+ ...job.call,
394
+ id: job.id,
395
+ observed: !!job.trace,
396
+ })
397
+ }
398
+ }
399
+ let ask = (call: Call): Promise<unknown> => {
400
+ if (closed) return Promise.reject(shut('the reader is closed', call))
401
+ let { signal, ...opts } = ('opts' in call ? call.opts : undefined) ?? {}
402
+ if (signal?.aborted) return Promise.reject(signal.reason)
403
+ return new Promise((resolve, reject) => {
404
+ let cancel = () => {
405
+ waiting = waiting.filter((j) => j !== job)
406
+ job.off()
407
+ reject(signal!.reason)
408
+ let lane = [...lanes].find((l) => l.job === job)
409
+ if (!lane) return
410
+ job.dropped = true
411
+ if (job.sent != undefined) overdue(lane, job)
412
+ }
413
+ let job: Job = {
414
+ id: ++next,
415
+ call: { ...call, ...('opts' in call ? { opts } : {}) } as Call,
416
+ resolve,
417
+ reject,
418
+ trace: context(),
419
+ asker: asker(),
420
+ off: () => signal?.removeEventListener('abort', cancel),
421
+ }
422
+ signal?.addEventListener('abort', cancel, { once: true })
423
+ waiting.push(job)
424
+ drain()
425
+ })
426
+ }
427
+ return {
428
+ storage: {
429
+ read: (query, opts, comps) =>
430
+ ask({ op: 'rawRead', query, opts, comps }).then((value) =>
431
+ value as Bundle[]
432
+ ),
433
+ rows: (query, opts) =>
434
+ ask({ op: 'rawRows', query, opts }).then((value) => value as Row[]),
435
+ get: (eids, comps, opts) =>
436
+ ask({ op: 'rawGet', eids, comps, opts }).then((value) =>
437
+ value as Bundle[]
438
+ ),
439
+ revision: () => ask({ op: 'revision' }),
440
+ newest: (comp) => ask({ op: 'newest', comp }),
441
+ buried: (before, page) =>
442
+ ask({ op: 'buried', before, page }).then((value) => value as Graves),
443
+ bindings: (...args) =>
444
+ ask({ op: 'bindings', args }).then((value) => value as Binding[][]),
445
+ },
446
+ statements: {
447
+ query: (stmt) =>
448
+ ask({ op: 'statement', stmt }).then((value) => value as Row[]),
449
+ },
450
+ tool: (name, call) =>
451
+ ask({ op: 'tool', name, call }).then((value) => value as Bundle[]),
452
+ readable: (answer) =>
453
+ ask({ op: 'readable', answer }).then((value) => value as Bundle[]),
454
+ read: (query, opts) =>
455
+ ask({ op: 'read', query: query as Taken, opts }).then((value) =>
456
+ value as Bundle[]
457
+ ),
458
+ rows: (query, opts) =>
459
+ ask({ op: 'rows', query: query as Taken, opts }).then((value) =>
460
+ value as Row[]
461
+ ),
462
+ get: (eids, comps, opts) =>
463
+ ask({ op: 'get', eids, comps, opts }).then((value) => value as Bundle[]),
464
+ // Each half of a search on a lane of its own, at once, then its lines
465
+ // made where its rows are read.
466
+ search: searching(
467
+ (words, count, semantic) =>
468
+ Promise.all([
469
+ ask({ op: 'hits', words, opts: { limit: count } }),
470
+ ask({ op: 'meaning', words: semantic, opts: { limit: count } }),
471
+ ]).then(([hits, meaning]) => ({
472
+ words: hits as Hit[],
473
+ meaning: meaning as MeaningHit[],
474
+ })),
475
+ (words, found, limit) =>
476
+ ask({ op: 'said', words, found, opts: { limit } }).then((value) =>
477
+ value as Bundle[]
478
+ ),
479
+ ),
480
+ meaning: (words, opts) =>
481
+ ask({ op: 'meaning', words, opts }).then((value) =>
482
+ value as MeaningHit[]
483
+ ),
484
+ // Both lanes, so no read waits on a worker starting: one started once the
485
+ // web's stack sampler runs waits in its inspector before it hears anything.
486
+ ready: () =>
487
+ Promise.all(
488
+ [1, 2].map(() => ask({ op: 'read', query: parse('.limit=1') })),
489
+ ).then(() => {}),
490
+ overrun: (tell) => void (told = tell),
491
+ close: () => {
492
+ closed = true
493
+ let jobs = [
494
+ ...waiting,
495
+ ...[...lanes].flatMap((l) => l.job ? [l.job] : []),
496
+ ]
497
+ waiting = []
498
+ for (let lane of lanes) stop(lane)
499
+ for (let job of jobs) {
500
+ job.off()
501
+ job.reject(shut('the reader closed', job.call, job.asker))
502
+ }
503
+ return Promise.resolve()
504
+ },
505
+ }
506
+ }
package/read_worker.ts ADDED
@@ -0,0 +1,164 @@
1
+ /// <reference no-default-lib="true" />
2
+ /// <reference lib="deno.worker" />
3
+ // The read side of one file-backed web or worker host. It composes the same
4
+ // graph over another SQLite WAL connection so a long query cannot hold the
5
+ // thread its requests and duties run on.
6
+ import { read } from './config.ts'
7
+ import { channel, context, record, scope } from 'jsr:@yaks/trace@0.2.36'
8
+ import { compose, facet, type Served } from './host.ts'
9
+ import type { Heard, Said } from './read_thread.ts'
10
+ import { thread } from './stall.ts'
11
+ import { readActivity, readOperations } from './read_activity.ts'
12
+ import { statements } from 'jsr:@yaks/sql@0.2.36'
13
+
14
+ let host: Promise<Served> | undefined
15
+ let activity: ReturnType<typeof readActivity> | undefined
16
+ let tell = (heard: Heard) => {
17
+ self.postMessage(heard)
18
+ if ('id' in heard) activity?.done(heard.id)
19
+ }
20
+ // Where this thread is, so the reader can see how long a read here waited
21
+ // for a CPU while it runs.
22
+ let place = thread()
23
+ if (place) tell({ thread: place })
24
+ let errorOf = (cause: unknown) => {
25
+ let error = cause instanceof Error ? cause : new Error(String(cause))
26
+ return {
27
+ name: error.name,
28
+ message: error.message,
29
+ details: Object.fromEntries(
30
+ Object.entries(error).filter(([key]) => key != 'stack'),
31
+ ),
32
+ }
33
+ }
34
+
35
+ self.onmessage = ({ data }: MessageEvent<Said>) => {
36
+ if ('start' in data) {
37
+ activity = readActivity(data.activity)
38
+ activity.say('composing the read-only graph')
39
+ // Started, composed or not, before any read is answered: a read's time
40
+ // begins here (./read_thread.ts).
41
+ host = Promise.resolve().then(async () => {
42
+ try {
43
+ let host = await compose(read(data.start), ['graph'], facet, {
44
+ process: false,
45
+ readOnly: true,
46
+ })
47
+ // A worker answers reads for the server's life, so what its plugins
48
+ // hold in memory is read now, before its first read waits on the
49
+ // disk. One that fails is reported, and reads go to the disk as before.
50
+ activity?.say('preloading what reads hold in memory')
51
+ await host.preload?.().catch((error) =>
52
+ host.report?.(error, { tags: { step: 'preload' } })
53
+ )
54
+ activity?.say('idle; waiting for a read')
55
+ return host
56
+ } finally {
57
+ tell({ started: true })
58
+ }
59
+ })
60
+ host.catch(() => {})
61
+ return
62
+ }
63
+ if ('close' in data) {
64
+ void host?.then((h) => h.close(), () => {}).finally(() => {
65
+ tell({ closed: true })
66
+ self.close()
67
+ })
68
+ return
69
+ }
70
+ void (async () => {
71
+ let stop: (() => void) | undefined
72
+ try {
73
+ if (!host) throw new Error('the reader was not started')
74
+ activity?.say('waiting for the read-only graph to finish composing')
75
+ let served = await host, graph = served.graph
76
+ activity?.say(`entering graph.${data.op}`)
77
+ stop = readOperations(graph, (text) => activity?.say(text))
78
+ let call = data
79
+ // A storage read begins no span of its own, so its statements are told
80
+ // to the graph's channel here, and the operation `readOperations` shows
81
+ // is the statement a read waits in, not only the read it entered.
82
+ let query = () =>
83
+ scope(context() ?? { channel: channel(graph) }, () => {
84
+ switch (call.op) {
85
+ case 'rawRead':
86
+ return graph.storage.read(call.query, call.opts, call.comps)
87
+ case 'rawRows':
88
+ return graph.storage.rows(call.query, call.opts)
89
+ case 'rawGet':
90
+ return graph.storage.get(call.eids, call.comps, call.opts)
91
+ case 'revision':
92
+ return graph.storage.revision?.()
93
+ case 'newest':
94
+ return graph.storage.newest?.(call.comp)
95
+ case 'buried':
96
+ return graph.storage.buried?.(call.before, call.page) ??
97
+ { eids: [] }
98
+ case 'bindings': {
99
+ if (!graph.storage.bindings) {
100
+ throw new Error('this storage evaluates no bindings')
101
+ }
102
+ return graph.storage.bindings(...call.args)
103
+ }
104
+ case 'statement':
105
+ return statements(served.storage).query(call.stmt)
106
+ case 'tool': {
107
+ let tool = served.registry.get(call.name)
108
+ if (!tool?.readOnly) {
109
+ throw new Error(`the reader has no read-only tool ${call.name}`)
110
+ }
111
+ return tool.run(call.call, graph)
112
+ }
113
+ case 'readable':
114
+ return served.readable?.(call.answer) ?? call.answer
115
+
116
+ case 'get':
117
+ return graph.get(call.eids, call.comps, call.opts)
118
+ case 'read':
119
+ return graph.read(call.query, call.opts)
120
+ case 'rows':
121
+ return graph.rows(call.query, call.opts)
122
+ case 'hits':
123
+ return served.hits?.(call.words, call.opts?.limit ?? 20) ?? []
124
+ case 'said':
125
+ return served.said?.(call.words, call.found, call.opts.limit) ??
126
+ []
127
+ case 'meaning':
128
+ return served.meaning?.(call.words, call.opts) ?? []
129
+ }
130
+ })
131
+ if (!data.observed) {
132
+ let value = await query()
133
+ activity?.say('posting the read result to the main thread')
134
+ tell({ id: data.id, value })
135
+ return
136
+ }
137
+ // Catch inside the recorder so a refused/failed read returns its tree,
138
+ // too, without turning an error into an independent worker report.
139
+ let captured = await record(graph, () => {
140
+ try {
141
+ return Promise.resolve(query()).then(
142
+ (value) => ({ value }),
143
+ (error) => ({ error: errorOf(error) }),
144
+ )
145
+ } catch (error) {
146
+ return Promise.resolve({ error: errorOf(error) })
147
+ }
148
+ }, { history: false })
149
+ activity?.say('posting the read result and trace to the main thread')
150
+ tell({
151
+ id: data.id,
152
+ ...captured.result,
153
+ spans: captured.spans,
154
+ origin: performance.timeOrigin,
155
+ })
156
+ } catch (error) {
157
+ activity?.say('posting the read failure to the main thread')
158
+ tell({ id: data.id, error: errorOf(error) })
159
+ } finally {
160
+ stop?.()
161
+ activity?.say('idle; the read reply was posted')
162
+ }
163
+ })()
164
+ }