@yaks/sqlite 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 (289) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +1596 -2
  3. package/_dist/archetype.d.ts +75 -0
  4. package/_dist/archetype.d.ts.map +1 -0
  5. package/_dist/branches.d.ts +23 -0
  6. package/_dist/branches.d.ts.map +1 -0
  7. package/_dist/budget.d.ts +52 -0
  8. package/_dist/budget.d.ts.map +1 -0
  9. package/_dist/bundle.d.ts +2 -0
  10. package/_dist/bundle.d.ts.map +1 -0
  11. package/_dist/cache.d.ts +24 -0
  12. package/_dist/cache.d.ts.map +1 -0
  13. package/_dist/catalog.d.ts +9 -0
  14. package/_dist/catalog.d.ts.map +1 -0
  15. package/_dist/check.d.ts +4 -0
  16. package/_dist/check.d.ts.map +1 -0
  17. package/_dist/db.d.ts +36 -0
  18. package/_dist/db.d.ts.map +1 -0
  19. package/_dist/ddl.d.ts +143 -0
  20. package/_dist/ddl.d.ts.map +1 -0
  21. package/_dist/doom.d.ts +22 -0
  22. package/_dist/doom.d.ts.map +1 -0
  23. package/_dist/follow.d.ts +74 -0
  24. package/_dist/follow.d.ts.map +1 -0
  25. package/_dist/history-shapes.d.ts +3 -0
  26. package/_dist/history-shapes.d.ts.map +1 -0
  27. package/_dist/history.d.ts +18 -0
  28. package/_dist/history.d.ts.map +1 -0
  29. package/_dist/inspect.d.ts +43 -0
  30. package/_dist/inspect.d.ts.map +1 -0
  31. package/_dist/jsonb.d.ts +17 -0
  32. package/_dist/jsonb.d.ts.map +1 -0
  33. package/_dist/layout.d.ts +7 -0
  34. package/_dist/layout.d.ts.map +1 -0
  35. package/_dist/ledger.d.ts +41 -0
  36. package/_dist/ledger.d.ts.map +1 -0
  37. package/_dist/meta.d.ts +89 -0
  38. package/_dist/meta.d.ts.map +1 -0
  39. package/_dist/migration.d.ts +41 -0
  40. package/_dist/migration.d.ts.map +1 -0
  41. package/_dist/mod.d.ts +201 -0
  42. package/_dist/mod.d.ts.map +1 -0
  43. package/_dist/mode.d.ts +14 -0
  44. package/_dist/mode.d.ts.map +1 -0
  45. package/_dist/overlay.d.ts +30 -0
  46. package/_dist/overlay.d.ts.map +1 -0
  47. package/_dist/owe.d.ts +180 -0
  48. package/_dist/owe.d.ts.map +1 -0
  49. package/_dist/physical.d.ts +89 -0
  50. package/_dist/physical.d.ts.map +1 -0
  51. package/_dist/point.d.ts +10 -0
  52. package/_dist/point.d.ts.map +1 -0
  53. package/_dist/raise.d.ts +22 -0
  54. package/_dist/raise.d.ts.map +1 -0
  55. package/_dist/read-db.d.ts +9 -0
  56. package/_dist/read-db.d.ts.map +1 -0
  57. package/_dist/read-store.d.ts +10 -0
  58. package/_dist/read-store.d.ts.map +1 -0
  59. package/_dist/read.d.ts +59 -0
  60. package/_dist/read.d.ts.map +1 -0
  61. package/_dist/reader.d.ts +11 -0
  62. package/_dist/reader.d.ts.map +1 -0
  63. package/_dist/rules.d.ts +19 -0
  64. package/_dist/rules.d.ts.map +1 -0
  65. package/_dist/service.d.ts +12 -0
  66. package/_dist/service.d.ts.map +1 -0
  67. package/_dist/shape.d.ts +12 -0
  68. package/_dist/shape.d.ts.map +1 -0
  69. package/_dist/statements.d.ts +4 -0
  70. package/_dist/statements.d.ts.map +1 -0
  71. package/_dist/survey.d.ts +31 -0
  72. package/_dist/survey.d.ts.map +1 -0
  73. package/_dist/tools.d.ts +15 -0
  74. package/_dist/tools.d.ts.map +1 -0
  75. package/_dist/trash.d.ts +18 -0
  76. package/_dist/trash.d.ts.map +1 -0
  77. package/_dist/unit.d.ts +11 -0
  78. package/_dist/unit.d.ts.map +1 -0
  79. package/_dist/vocab.d.ts +6 -0
  80. package/_dist/vocab.d.ts.map +1 -0
  81. package/_dist/write.d.ts +169 -0
  82. package/_dist/write.d.ts.map +1 -0
  83. package/answer.js +110 -0
  84. package/answer.js.map +1 -0
  85. package/answer.ts +122 -0
  86. package/archetype.js +730 -0
  87. package/archetype.js.map +1 -0
  88. package/archetype.ts +790 -0
  89. package/binary_cases.ts +240 -0
  90. package/branches.js +195 -0
  91. package/branches.js.map +1 -0
  92. package/branches.ts +257 -0
  93. package/budget.js +89 -0
  94. package/budget.js.map +1 -0
  95. package/budget.ts +117 -0
  96. package/builtin.js +34 -0
  97. package/builtin.js.map +1 -0
  98. package/builtin.ts +31 -0
  99. package/bundle.js +21 -0
  100. package/bundle.js.map +1 -0
  101. package/bundle.ts +22 -0
  102. package/buried.js +95 -0
  103. package/buried.js.map +1 -0
  104. package/buried.ts +124 -0
  105. package/cache.js +153 -0
  106. package/cache.js.map +1 -0
  107. package/cache.ts +154 -0
  108. package/cache_worker.ts +16 -0
  109. package/catalog.js +173 -0
  110. package/catalog.js.map +1 -0
  111. package/catalog.ts +224 -0
  112. package/check.js +80 -0
  113. package/check.js.map +1 -0
  114. package/check.ts +92 -0
  115. package/checkpoint.js +98 -0
  116. package/checkpoint.js.map +1 -0
  117. package/checkpoint.ts +129 -0
  118. package/checkpoint_worker.ts +37 -0
  119. package/db.js +170 -0
  120. package/db.js.map +1 -0
  121. package/db.ts +173 -0
  122. package/ddl.js +1441 -0
  123. package/ddl.js.map +1 -0
  124. package/ddl.ts +1508 -0
  125. package/deno.json +1 -0
  126. package/doom.js +59 -0
  127. package/doom.js.map +1 -0
  128. package/doom.ts +75 -0
  129. package/driver.js +69 -0
  130. package/driver.js.map +1 -0
  131. package/driver.ts +101 -0
  132. package/error.js +30 -0
  133. package/error.js.map +1 -0
  134. package/error.ts +46 -0
  135. package/ffi/LICENSE +202 -0
  136. package/ffi/blob.js +99 -0
  137. package/ffi/blob.js.map +1 -0
  138. package/ffi/blob.ts +156 -0
  139. package/ffi/constants.js +65 -0
  140. package/ffi/constants.js.map +1 -0
  141. package/ffi/constants.ts +67 -0
  142. package/ffi/database.js +613 -0
  143. package/ffi/database.js.map +1 -0
  144. package/ffi/database.ts +931 -0
  145. package/ffi/ffi.js +535 -0
  146. package/ffi/ffi.js.map +1 -0
  147. package/ffi/ffi.ts +604 -0
  148. package/ffi/mod.js +15 -0
  149. package/ffi/mod.js.map +1 -0
  150. package/ffi/mod.ts +28 -0
  151. package/ffi/statement.js +555 -0
  152. package/ffi/statement.js.map +1 -0
  153. package/ffi/statement.ts +788 -0
  154. package/ffi/util.js +32 -0
  155. package/ffi/util.js.map +1 -0
  156. package/ffi/util.ts +48 -0
  157. package/follow.js +342 -0
  158. package/follow.js.map +1 -0
  159. package/follow.ts +401 -0
  160. package/history-branch.js +166 -0
  161. package/history-branch.js.map +1 -0
  162. package/history-branch.ts +140 -0
  163. package/history-shapes.js +254 -0
  164. package/history-shapes.js.map +1 -0
  165. package/history-shapes.ts +268 -0
  166. package/history.js +620 -0
  167. package/history.js.map +1 -0
  168. package/history.ts +674 -0
  169. package/inspect.js +120 -0
  170. package/inspect.js.map +1 -0
  171. package/inspect.ts +164 -0
  172. package/jsonb.js +73 -0
  173. package/jsonb.js.map +1 -0
  174. package/jsonb.ts +108 -0
  175. package/layout.js +22 -0
  176. package/layout.js.map +1 -0
  177. package/layout.ts +26 -0
  178. package/ledger.js +210 -0
  179. package/ledger.js.map +1 -0
  180. package/ledger.ts +210 -0
  181. package/legacy.js +4 -0
  182. package/legacy.js.map +1 -0
  183. package/legacy.ts +3 -0
  184. package/maintenance.js +148 -0
  185. package/maintenance.js.map +1 -0
  186. package/maintenance.ts +154 -0
  187. package/measure.js +133 -0
  188. package/measure.js.map +1 -0
  189. package/measure.ts +167 -0
  190. package/measure_worker.ts +18 -0
  191. package/memo.js +1250 -0
  192. package/memo.js.map +1 -0
  193. package/memo.ts +1480 -0
  194. package/meta.js +265 -0
  195. package/meta.js.map +1 -0
  196. package/meta.ts +321 -0
  197. package/migration.js +272 -0
  198. package/migration.js.map +1 -0
  199. package/migration.ts +286 -0
  200. package/mod.js +1103 -0
  201. package/mod.js.map +1 -0
  202. package/mod.ts +1762 -0
  203. package/mode.js +192 -0
  204. package/mode.js.map +1 -0
  205. package/mode.ts +207 -0
  206. package/native.js +544 -0
  207. package/native.js.map +1 -0
  208. package/native.ts +544 -0
  209. package/overlay.js +408 -0
  210. package/overlay.js.map +1 -0
  211. package/overlay.ts +485 -0
  212. package/owe.js +719 -0
  213. package/owe.js.map +1 -0
  214. package/owe.ts +873 -0
  215. package/package.json +99 -4
  216. package/physical.js +350 -0
  217. package/physical.js.map +1 -0
  218. package/physical.ts +434 -0
  219. package/plan.js +78 -0
  220. package/plan.js.map +1 -0
  221. package/plan.ts +104 -0
  222. package/point.js +81 -0
  223. package/point.js.map +1 -0
  224. package/point.ts +52 -0
  225. package/population.js +639 -0
  226. package/population.js.map +1 -0
  227. package/population.ts +630 -0
  228. package/purge.js +117 -0
  229. package/purge.js.map +1 -0
  230. package/purge.ts +127 -0
  231. package/raise.js +270 -0
  232. package/raise.js.map +1 -0
  233. package/raise.ts +316 -0
  234. package/read-db.js +381 -0
  235. package/read-db.js.map +1 -0
  236. package/read-db.ts +282 -0
  237. package/read-store.js +74 -0
  238. package/read-store.js.map +1 -0
  239. package/read-store.ts +86 -0
  240. package/read.js +1100 -0
  241. package/read.js.map +1 -0
  242. package/read.ts +1441 -0
  243. package/reader.js +141 -0
  244. package/reader.js.map +1 -0
  245. package/reader.ts +159 -0
  246. package/rules.js +88 -0
  247. package/rules.js.map +1 -0
  248. package/rules.ts +113 -0
  249. package/service.js +27 -0
  250. package/service.js.map +1 -0
  251. package/service.ts +41 -0
  252. package/shape.js +76 -0
  253. package/shape.js.map +1 -0
  254. package/shape.ts +108 -0
  255. package/sparse_presence_fixture.ts +45 -0
  256. package/sqlitepath.js +24 -0
  257. package/sqlitepath.js.map +1 -0
  258. package/sqlitepath.ts +29 -0
  259. package/statements.js +78 -0
  260. package/statements.js.map +1 -0
  261. package/statements.ts +96 -0
  262. package/survey.js +135 -0
  263. package/survey.js.map +1 -0
  264. package/survey.ts +196 -0
  265. package/tools.js +17 -0
  266. package/tools.js.map +1 -0
  267. package/tools.ts +50 -0
  268. package/trash.js +144 -0
  269. package/trash.js.map +1 -0
  270. package/trash.ts +187 -0
  271. package/unit.js +215 -0
  272. package/unit.js.map +1 -0
  273. package/unit.ts +211 -0
  274. package/versions.js +115 -0
  275. package/versions.js.map +1 -0
  276. package/versions.ts +110 -0
  277. package/vocab.js +19 -0
  278. package/vocab.js.map +1 -0
  279. package/vocab.json +27 -0
  280. package/vocab.ts +19 -0
  281. package/watch.js +33 -0
  282. package/watch.js.map +1 -0
  283. package/watch.ts +42 -0
  284. package/write.js +1164 -0
  285. package/write.js.map +1 -0
  286. package/write.ts +1356 -0
  287. package/written.js +200 -0
  288. package/written.js.map +1 -0
  289. package/written.ts +202 -0
package/migration.js ADDED
@@ -0,0 +1,272 @@
1
+ /** Cooperative, preannounced SQLite migrations. Not a distributed lock service. */ import { catalogue, col, eq, lit, select, table, val } from "@yaks/sql";
2
+ import { system } from "@yaks/fp";
3
+ const CONTROL = '_yaks_migration';
4
+ let one = eq(col('singleton'), lit(1));
5
+ let reading = select({
6
+ from: table(CONTROL),
7
+ where: one
8
+ });
9
+ let begin = {
10
+ t: 'begin',
11
+ mode: 'immediate'
12
+ };
13
+ let commit = {
14
+ t: 'commit'
15
+ };
16
+ let rollback = {
17
+ t: 'rollback'
18
+ };
19
+ export class MigrationPending extends Error {
20
+ migration;
21
+ constructor(migration){
22
+ super(`Database migration ${migration.migration} is ${migration.state}; restart required`), this.migration = migration;
23
+ this.name = 'MigrationPending';
24
+ }
25
+ }
26
+ /** The control table, as the statement a graph's composed schema carries
27
+ * (./follow.ts): a writer adds it where it is missing, a reader never does. */ export function migrationSchema() {
28
+ return [
29
+ {
30
+ t: 'create table',
31
+ name: CONTROL,
32
+ ifNot: true,
33
+ cols: [
34
+ {
35
+ name: 'singleton',
36
+ type: 'integer',
37
+ pk: true,
38
+ check: eq(col('singleton'), lit(1))
39
+ },
40
+ {
41
+ name: 'generation',
42
+ type: 'integer',
43
+ notNull: true
44
+ },
45
+ {
46
+ name: 'migration',
47
+ type: 'text',
48
+ notNull: true
49
+ },
50
+ {
51
+ name: 'state',
52
+ type: 'text',
53
+ notNull: true
54
+ },
55
+ {
56
+ name: 'announced',
57
+ type: 'real',
58
+ notNull: true
59
+ },
60
+ {
61
+ name: 'not_before',
62
+ type: 'real',
63
+ notNull: true
64
+ },
65
+ {
66
+ name: 'finished',
67
+ type: 'real'
68
+ },
69
+ {
70
+ name: 'error',
71
+ type: 'text'
72
+ }
73
+ ]
74
+ }
75
+ ];
76
+ }
77
+ /** Bind migration control over a graph. A file no writer has brought to its
78
+ * schema (a reader's fresh `:memory:`, a file nothing wrote) has no control
79
+ * table, which reads as no migration ever announced. */ export function migrations(db) {
80
+ const set = (set)=>db.query({
81
+ t: 'update',
82
+ table: CONTROL,
83
+ set,
84
+ where: one
85
+ });
86
+ const read = ()=>{
87
+ if (!catalogue(db).some((o)=>o.name == CONTROL)) return undefined;
88
+ const r = db.query(reading)[0];
89
+ return r && {
90
+ generation: Number(r.generation),
91
+ migration: String(r.migration),
92
+ state: r.state,
93
+ announced: Number(r.announced),
94
+ notBefore: Number(r.not_before),
95
+ finished: r.finished == null ? null : Number(r.finished),
96
+ error: r.error == null ? null : String(r.error)
97
+ };
98
+ };
99
+ // BEGIN IMMEDIATE serializes claims across connections. These APIs must not
100
+ // run inside a caller's transaction: the announcement must become visible.
101
+ const transaction = (body)=>{
102
+ db.query(begin);
103
+ try {
104
+ const value = body();
105
+ db.query(commit);
106
+ return value;
107
+ } catch (error) {
108
+ db.query(rollback);
109
+ throw error;
110
+ }
111
+ };
112
+ const ready = ()=>{
113
+ const value = read();
114
+ if (value && value.state != 'applied') throw new MigrationPending(value);
115
+ return value?.generation ?? 0;
116
+ };
117
+ const announce = (migration, graceMs = 1100)=>{
118
+ if (!migration.trim() || !Number.isFinite(graceMs) || graceMs < 0) {
119
+ throw new TypeError('Migration name and nonnegative graceMs required');
120
+ }
121
+ return transaction(()=>{
122
+ const generation = ready() + 1;
123
+ const now = Date.now();
124
+ const row = {
125
+ singleton: lit(1),
126
+ generation: val(generation),
127
+ migration: val(migration),
128
+ state: val('pending'),
129
+ announced: val(now),
130
+ not_before: val(now + graceMs),
131
+ finished: lit(null),
132
+ error: lit(null)
133
+ };
134
+ db.query({
135
+ t: 'insert',
136
+ into: CONTROL,
137
+ cols: Object.keys(row),
138
+ rows: [
139
+ Object.values(row)
140
+ ],
141
+ upsert: [
142
+ {
143
+ on: [
144
+ col('singleton')
145
+ ],
146
+ set: Object.fromEntries(Object.keys(row).filter((k)=>k != 'singleton').map((k)=>[
147
+ k,
148
+ col(k, 'excluded')
149
+ ]))
150
+ }
151
+ ]
152
+ });
153
+ return read();
154
+ });
155
+ };
156
+ const owned = (claim)=>{
157
+ const current = read();
158
+ if (!current || current.generation != claim.generation || current.migration != claim.migration || current.state != 'pending') {
159
+ throw new Error('Migration announcement is no longer pending or owned');
160
+ }
161
+ return current;
162
+ };
163
+ const fail = (claim, reason)=>transaction(()=>{
164
+ owned(claim);
165
+ set({
166
+ state: val('failed'),
167
+ finished: val(Date.now()),
168
+ error: val(reason)
169
+ });
170
+ });
171
+ const apply = (claim, change)=>{
172
+ try {
173
+ transaction(()=>{
174
+ const current = owned(claim);
175
+ if (Date.now() < current.notBefore) {
176
+ throw new Error('Migration grace period has not elapsed');
177
+ }
178
+ const result = change(db);
179
+ if (result && typeof result.then == 'function') {
180
+ throw new TypeError('Migration callback must be synchronous');
181
+ }
182
+ set({
183
+ state: val('applied'),
184
+ finished: val(Date.now()),
185
+ error: lit(null)
186
+ });
187
+ });
188
+ } catch (error) {
189
+ // Do not mutate a superseded claim or mark an early apply as a failure.
190
+ const current = read();
191
+ if (current?.generation == claim.generation && current.state == 'pending' && Date.now() >= current.notBefore) fail(claim, String(error));
192
+ throw error;
193
+ }
194
+ };
195
+ return {
196
+ read,
197
+ ready,
198
+ announce,
199
+ apply,
200
+ fail,
201
+ /** Explicit operator recovery after inspecting/repairing failed or abandoned
202
+ * work. This does not undo a migration or decide whether retry is safe. */ acknowledge: (generation)=>transaction(()=>{
203
+ const current = read();
204
+ if (!current || current.generation != generation) {
205
+ throw new Error('Migration generation changed');
206
+ }
207
+ set({
208
+ state: val('applied'),
209
+ finished: val(Date.now())
210
+ });
211
+ }),
212
+ /** Publish first, then wait with no write transaction held. Peers must poll
213
+ * no slower than intervalMs; margin is scheduling slack, not an ACK. */ run: async (name, change, options = {})=>{
214
+ const interval = options.intervalMs ?? 1000;
215
+ const margin = options.marginMs ?? 100;
216
+ if (!Number.isFinite(interval) || interval <= 0 || !Number.isFinite(margin) || margin < 0) {
217
+ throw new TypeError('Invalid polling interval/margin');
218
+ }
219
+ const claim = announce(name, interval + margin);
220
+ while(Date.now() < claim.notBefore){
221
+ await new Promise((resolve)=>setTimeout(resolve, claim.notBefore - Date.now()));
222
+ }
223
+ apply(claim, change);
224
+ return read();
225
+ }
226
+ };
227
+ }
228
+ /** One polling loop per application connection, no per-operation queries. A
229
+ * generation change latches even if pending was missed. Callback runs once;
230
+ * caller owns admission/drain/close policy. Poll errors also stop the
231
+ * monitor. It polls on `clock` (default the runtime's). */ export function watchMigrations(control, changed, intervalMs = 1000, clock = system) {
232
+ if (!Number.isFinite(intervalMs) || intervalMs <= 0) {
233
+ throw new TypeError('Invalid polling interval');
234
+ }
235
+ const baseline = control.ready();
236
+ let stopped = false;
237
+ let cancel = ()=>{};
238
+ const stop = ()=>{
239
+ stopped = true;
240
+ cancel();
241
+ };
242
+ const check = ()=>{
243
+ if (stopped) return;
244
+ let error;
245
+ try {
246
+ const current = control.read();
247
+ if (current && (current.generation != baseline || current.state != 'applied')) {
248
+ error = new MigrationPending(current);
249
+ }
250
+ } catch (cause) {
251
+ error = new Error('Migration monitor failed; restart required', {
252
+ cause
253
+ });
254
+ }
255
+ if (error) {
256
+ stop();
257
+ changed(error);
258
+ }
259
+ };
260
+ const poll = ()=>{
261
+ cancel = clock.after(intervalMs, ()=>{
262
+ check();
263
+ if (!stopped) poll();
264
+ });
265
+ };
266
+ poll();
267
+ return {
268
+ check,
269
+ stop
270
+ };
271
+ }
272
+ //# sourceMappingURL=migration.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"migration.js","sources":["./migration.ts"],"names":[],"mappings":"AAAA,iFAAiF,GACjF,SACE,SAAS,EACT,GAAG,EAEH,EAAE,EAEF,GAAG,EACH,MAAM,EAEN,KAAK,EACL,GAAG,yBACwB;AAC7B,SAAqB,MAAM,wBAA6B;AAExD,MAAM,UAAU;AAChB,IAAI,MAAM,GAAG,IAAI,cAAc,IAAI;AACnC,IAAI,UAAU,OAAO;EAAE,MAAM,MAAM;EAAU,OAAO;AAAI;AACxD,IAAI,QAAc;EAAE,GAAG;EAAS,MAAM;AAAY;AAClD,IAAI,SAAe;EAAE,GAAG;AAAS;AACjC,IAAI,WAAiB;EAAE,GAAG;AAAW;AAyBrC,OAAO,MAAM,yBAAyB;;EACpC,YAAY,AAAgB,SAAyB,CAAE;IACrD,KAAK,CACH,CAAC,mBAAmB,EAAE,UAAU,SAAS,CAAC,IAAI,EAAE,UAAU,KAAK,CAAC,kBAAkB,CAAC,QAF3D,YAAA;IAI1B,IAAI,CAAC,IAAI,GAAG;EACd;AACF;AAEA;6EAC6E,GAC7E,OAAO,SAAS;EACd,OAAO;IAAC;MACN,GAAG;MACH,MAAM;MACN,OAAO;MACP,MAAM;QACJ;UACE,MAAM;UACN,MAAM;UACN,IAAI;UACJ,OAAO,GAAG,IAAI,cAAc,IAAI;QAClC;QACA;UAAE,MAAM;UAAc,MAAM;UAAW,SAAS;QAAK;QACrD;UAAE,MAAM;UAAa,MAAM;UAAQ,SAAS;QAAK;QACjD;UAAE,MAAM;UAAS,MAAM;UAAQ,SAAS;QAAK;QAC7C;UAAE,MAAM;UAAa,MAAM;UAAQ,SAAS;QAAK;QACjD;UAAE,MAAM;UAAc,MAAM;UAAQ,SAAS;QAAK;QAClD;UAAE,MAAM;UAAY,MAAM;QAAO;QACjC;UAAE,MAAM;UAAS,MAAM;QAAO;OAC/B;IACH;GAAE;AACJ;A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,QAAQ,UAAU,IAAI,YAAY,QAAQ,KAAK,IAAI,SAAS,GAC7D;QACA,QAAQ,IAAI,iBAAiB;MAC/B;IACF,EAAE,OAAO,OAAO;MACd,QAAQ,IAAI,MAAM,8CAA8C;QAAE;MAAM;IAC1E;IACA,IAAI,OAAO;MACT;MACA,QAAQ;IACV;EACF;EACA,MAAM,OAAO;IACX,SAAS,MAAM,KAAK,CAAC,YAAY;MAC/B;MACA,IAAI,CAAC,SAAS;IAChB;EACF;EACA;EACA,OAAO;IAAE;IAAO;EAAK;AACvB"}
package/migration.ts ADDED
@@ -0,0 +1,286 @@
1
+ /** Cooperative, preannounced SQLite migrations. Not a distributed lock service. */
2
+ import {
3
+ catalogue,
4
+ col,
5
+ type Driver,
6
+ eq,
7
+ type Expr,
8
+ lit,
9
+ select,
10
+ type Stmt,
11
+ table,
12
+ val,
13
+ } from '@yaks/sql'
14
+ import { type Clock, system } from '@yaks/fp'
15
+
16
+ const CONTROL = '_yaks_migration'
17
+ let one = eq(col('singleton'), lit(1))
18
+ let reading = select({ from: table(CONTROL), where: one })
19
+ let begin: Stmt = { t: 'begin', mode: 'immediate' }
20
+ let commit: Stmt = { t: 'commit' }
21
+ let rollback: Stmt = { t: 'rollback' }
22
+
23
+ export type MigrationState = {
24
+ generation: number
25
+ migration: string
26
+ state: 'pending' | 'applied' | 'failed'
27
+ announced: number
28
+ notBefore: number
29
+ finished: number | null
30
+ error: string | null
31
+ }
32
+ export type MigrationControl = {
33
+ read: () => MigrationState | undefined
34
+ ready: () => number
35
+ announce: (migration: string, graceMs?: number) => MigrationState
36
+ apply: (claim: MigrationState, change: (db: Driver) => void) => void
37
+ fail: (claim: MigrationState, reason: string) => void
38
+ acknowledge: (generation: number) => void
39
+ run: (
40
+ name: string,
41
+ change: (db: Driver) => void,
42
+ options?: { intervalMs?: number; marginMs?: number },
43
+ ) => Promise<MigrationState>
44
+ }
45
+ export type MigrationWatch = { check: () => void; stop: () => void }
46
+ export class MigrationPending extends Error {
47
+ constructor(public readonly migration: MigrationState) {
48
+ super(
49
+ `Database migration ${migration.migration} is ${migration.state}; restart required`,
50
+ )
51
+ this.name = 'MigrationPending'
52
+ }
53
+ }
54
+
55
+ /** The control table, as the statement a graph's composed schema carries
56
+ * (./follow.ts): a writer adds it where it is missing, a reader never does. */
57
+ export function migrationSchema(): Stmt[] {
58
+ return [{
59
+ t: 'create table',
60
+ name: CONTROL,
61
+ ifNot: true,
62
+ cols: [
63
+ {
64
+ name: 'singleton',
65
+ type: 'integer',
66
+ pk: true,
67
+ check: eq(col('singleton'), lit(1)),
68
+ },
69
+ { name: 'generation', type: 'integer', notNull: true },
70
+ { name: 'migration', type: 'text', notNull: true },
71
+ { name: 'state', type: 'text', notNull: true },
72
+ { name: 'announced', type: 'real', notNull: true },
73
+ { name: 'not_before', type: 'real', notNull: true },
74
+ { name: 'finished', type: 'real' },
75
+ { name: 'error', type: 'text' },
76
+ ],
77
+ }]
78
+ }
79
+
80
+ /** Bind migration control over a graph. A file no writer has brought to its
81
+ * schema (a reader's fresh `:memory:`, a file nothing wrote) has no control
82
+ * table, which reads as no migration ever announced. */
83
+ export function migrations(db: Driver): MigrationControl {
84
+ const set = (set: Record<string, Expr>) =>
85
+ db.query({ t: 'update', table: CONTROL, set, where: one })
86
+ const read = (): MigrationState | undefined => {
87
+ if (!catalogue(db).some((o) => o.name == CONTROL)) return undefined
88
+ const r = db.query(reading)[0]
89
+ return r && {
90
+ generation: Number(r.generation),
91
+ migration: String(r.migration),
92
+ state: r.state as MigrationState['state'],
93
+ announced: Number(r.announced),
94
+ notBefore: Number(r.not_before),
95
+ finished: r.finished == null ? null : Number(r.finished),
96
+ error: r.error == null ? null : String(r.error),
97
+ }
98
+ }
99
+ // BEGIN IMMEDIATE serializes claims across connections. These APIs must not
100
+ // run inside a caller's transaction: the announcement must become visible.
101
+ const transaction = <T>(body: () => T): T => {
102
+ db.query(begin)
103
+ try {
104
+ const value = body()
105
+ db.query(commit)
106
+ return value
107
+ } catch (error) {
108
+ db.query(rollback)
109
+ throw error
110
+ }
111
+ }
112
+ const ready = () => {
113
+ const value = read()
114
+ if (value && value.state != 'applied') throw new MigrationPending(value)
115
+ return value?.generation ?? 0
116
+ }
117
+ const announce = (migration: string, graceMs = 1100): MigrationState => {
118
+ if (!migration.trim() || !Number.isFinite(graceMs) || graceMs < 0) {
119
+ throw new TypeError('Migration name and nonnegative graceMs required')
120
+ }
121
+ return transaction(() => {
122
+ const generation = ready() + 1
123
+ const now = Date.now()
124
+ const row: Record<string, Expr> = {
125
+ singleton: lit(1),
126
+ generation: val(generation),
127
+ migration: val(migration),
128
+ state: val('pending'),
129
+ announced: val(now),
130
+ not_before: val(now + graceMs),
131
+ finished: lit(null),
132
+ error: lit(null),
133
+ }
134
+ db.query({
135
+ t: 'insert',
136
+ into: CONTROL,
137
+ cols: Object.keys(row),
138
+ rows: [Object.values(row)],
139
+ upsert: [{
140
+ on: [col('singleton')],
141
+ set: Object.fromEntries(
142
+ Object.keys(row).filter((k) => k != 'singleton')
143
+ .map((k) => [k, col(k, 'excluded')]),
144
+ ),
145
+ }],
146
+ })
147
+ return read()!
148
+ })
149
+ }
150
+ const owned = (claim: MigrationState) => {
151
+ const current = read()
152
+ if (
153
+ !current || current.generation != claim.generation ||
154
+ current.migration != claim.migration || current.state != 'pending'
155
+ ) {
156
+ throw new Error('Migration announcement is no longer pending or owned')
157
+ }
158
+ return current
159
+ }
160
+ const fail = (claim: MigrationState, reason: string) =>
161
+ transaction(() => {
162
+ owned(claim)
163
+ set({
164
+ state: val('failed'),
165
+ finished: val(Date.now()),
166
+ error: val(reason),
167
+ })
168
+ })
169
+ const apply = (claim: MigrationState, change: (db: Driver) => void) => {
170
+ try {
171
+ transaction(() => {
172
+ const current = owned(claim)
173
+ if (Date.now() < current.notBefore) {
174
+ throw new Error('Migration grace period has not elapsed')
175
+ }
176
+ const result: unknown = change(db)
177
+ if (result && typeof (result as Promise<unknown>).then == 'function') {
178
+ throw new TypeError('Migration callback must be synchronous')
179
+ }
180
+ set({
181
+ state: val('applied'),
182
+ finished: val(Date.now()),
183
+ error: lit(null),
184
+ })
185
+ })
186
+ } catch (error) {
187
+ // Do not mutate a superseded claim or mark an early apply as a failure.
188
+ const current = read()
189
+ if (
190
+ current?.generation == claim.generation && current.state == 'pending' &&
191
+ Date.now() >= current.notBefore
192
+ ) fail(claim, String(error))
193
+ throw error
194
+ }
195
+ }
196
+ return {
197
+ read,
198
+ ready,
199
+ announce,
200
+ apply,
201
+ fail,
202
+ /** Explicit operator recovery after inspecting/repairing failed or abandoned
203
+ * work. This does not undo a migration or decide whether retry is safe. */
204
+ acknowledge: (generation: number) =>
205
+ transaction(() => {
206
+ const current = read()
207
+ if (!current || current.generation != generation) {
208
+ throw new Error('Migration generation changed')
209
+ }
210
+ set({ state: val('applied'), finished: val(Date.now()) })
211
+ }),
212
+ /** Publish first, then wait with no write transaction held. Peers must poll
213
+ * no slower than intervalMs; margin is scheduling slack, not an ACK. */
214
+ run: async (
215
+ name: string,
216
+ change: (db: Driver) => void,
217
+ options: { intervalMs?: number; marginMs?: number } = {},
218
+ ) => {
219
+ const interval = options.intervalMs ?? 1000
220
+ const margin = options.marginMs ?? 100
221
+ if (
222
+ !Number.isFinite(interval) || interval <= 0 ||
223
+ !Number.isFinite(margin) || margin < 0
224
+ ) {
225
+ throw new TypeError('Invalid polling interval/margin')
226
+ }
227
+ const claim = announce(name, interval + margin)
228
+ while (Date.now() < claim.notBefore) {
229
+ await new Promise((resolve) =>
230
+ setTimeout(resolve, claim.notBefore - Date.now())
231
+ )
232
+ }
233
+ apply(claim, change)
234
+ return read()!
235
+ },
236
+ }
237
+ }
238
+
239
+ /** One polling loop per application connection, no per-operation queries. A
240
+ * generation change latches even if pending was missed. Callback runs once;
241
+ * caller owns admission/drain/close policy. Poll errors also stop the
242
+ * monitor. It polls on `clock` (default the runtime's). */
243
+ export function watchMigrations(
244
+ control: Pick<MigrationControl, 'read' | 'ready'>,
245
+ changed: (reason: Error) => void,
246
+ intervalMs = 1000,
247
+ clock: Clock = system,
248
+ ): MigrationWatch {
249
+ if (!Number.isFinite(intervalMs) || intervalMs <= 0) {
250
+ throw new TypeError('Invalid polling interval')
251
+ }
252
+ const baseline = control.ready()
253
+ let stopped = false
254
+ let cancel = () => {}
255
+ const stop = () => {
256
+ stopped = true
257
+ cancel()
258
+ }
259
+ const check = () => {
260
+ if (stopped) return
261
+ let error: Error | undefined
262
+ try {
263
+ const current = control.read()
264
+ if (
265
+ current &&
266
+ (current.generation != baseline || current.state != 'applied')
267
+ ) {
268
+ error = new MigrationPending(current)
269
+ }
270
+ } catch (cause) {
271
+ error = new Error('Migration monitor failed; restart required', { cause })
272
+ }
273
+ if (error) {
274
+ stop()
275
+ changed(error)
276
+ }
277
+ }
278
+ const poll = () => {
279
+ cancel = clock.after(intervalMs, () => {
280
+ check()
281
+ if (!stopped) poll()
282
+ })
283
+ }
284
+ poll()
285
+ return { check, stop }
286
+ }