@otwdesign/db-core 1.4.2 → 1.5.0

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 (62) hide show
  1. package/README.md +38 -0
  2. package/dist/backup/api.js +2 -33
  3. package/dist/backup/api.js.map +1 -1
  4. package/dist/body.d.ts +17 -0
  5. package/dist/body.js +88 -0
  6. package/dist/body.js.map +1 -0
  7. package/dist/browser.d.ts +1 -0
  8. package/dist/drivers/mysql-connection.d.ts +101 -0
  9. package/dist/drivers/mysql-connection.js +204 -0
  10. package/dist/drivers/mysql-connection.js.map +1 -0
  11. package/dist/drivers/mysql-import.d.ts +22 -0
  12. package/dist/drivers/mysql-import.js +688 -0
  13. package/dist/drivers/mysql-import.js.map +1 -0
  14. package/dist/drivers/mysql.d.ts +11 -1
  15. package/dist/drivers/mysql.js +87 -97
  16. package/dist/drivers/mysql.js.map +1 -1
  17. package/dist/errors.d.ts +4 -0
  18. package/dist/errors.js.map +1 -1
  19. package/dist/handler.d.ts +31 -0
  20. package/dist/handler.js +93 -9
  21. package/dist/handler.js.map +1 -1
  22. package/dist/import/api.d.ts +65 -0
  23. package/dist/import/api.js +1282 -0
  24. package/dist/import/api.js.map +1 -0
  25. package/dist/import/audit.d.ts +47 -0
  26. package/dist/import/audit.js +434 -0
  27. package/dist/import/audit.js.map +1 -0
  28. package/dist/import/charsets.d.ts +25 -0
  29. package/dist/import/charsets.js +39 -0
  30. package/dist/import/charsets.js.map +1 -0
  31. package/dist/import/frames.d.ts +26 -0
  32. package/dist/import/frames.js +158 -0
  33. package/dist/import/frames.js.map +1 -0
  34. package/dist/import/grants.d.ts +26 -0
  35. package/dist/import/grants.js +122 -0
  36. package/dist/import/grants.js.map +1 -0
  37. package/dist/import/protocol.d.ts +462 -0
  38. package/dist/import/protocol.js +72 -0
  39. package/dist/import/protocol.js.map +1 -0
  40. package/dist/import/shared.d.ts +3 -0
  41. package/dist/import/shared.js +9 -0
  42. package/dist/import/shared.js.map +1 -0
  43. package/dist/index.d.ts +1 -0
  44. package/dist/types.d.ts +308 -2
  45. package/package.json +7 -2
  46. package/src/backup/api.ts +2 -33
  47. package/src/body.ts +94 -0
  48. package/src/browser.ts +24 -0
  49. package/src/drivers/mysql-connection.ts +282 -0
  50. package/src/drivers/mysql-import.ts +769 -0
  51. package/src/drivers/mysql.ts +96 -107
  52. package/src/errors.ts +2 -0
  53. package/src/handler.ts +126 -8
  54. package/src/import/api.ts +1530 -0
  55. package/src/import/audit.ts +467 -0
  56. package/src/import/charsets.ts +46 -0
  57. package/src/import/frames.ts +191 -0
  58. package/src/import/grants.ts +117 -0
  59. package/src/import/protocol.ts +540 -0
  60. package/src/import/shared.ts +8 -0
  61. package/src/index.ts +24 -0
  62. package/src/types.ts +319 -2
@@ -0,0 +1,1282 @@
1
+ import { createHash, randomBytes } from 'node:crypto';
2
+ import { readBytes } from "../body.js";
3
+ import { DbAdminError } from "../errors.js";
4
+ import { auditParts } from "./audit.js";
5
+ import { readsAs } from "./charsets.js";
6
+ import { batchLast, batchNumbers, decodeFrames } from "./frames.js";
7
+ import { privilegesIn } from "./grants.js";
8
+ import { IMPORT_BATCH_BYTES, IMPORT_BATCH_STATEMENTS, IMPORT_BODY_MS, IMPORT_HEARTBEAT_MS, IMPORT_STATEMENT_BYTES, } from "./protocol.js";
9
+ const SYSTEM_CLOCK = {
10
+ now: () => performance.now(),
11
+ after(ms, run) {
12
+ const timer = setTimeout(run, ms);
13
+ // A limit that is still counting keeps no process alive that is otherwise done.
14
+ timer.unref();
15
+ return () => clearTimeout(timer);
16
+ },
17
+ };
18
+ /** Where the registry is: on the process, so every copy of this module finds the same one. */
19
+ const REGISTRY = Symbol.for('otw-db.imports');
20
+ /** An import's id: 128 random bits, in hex. Anything else is not looked up. */
21
+ const ID = /^[0-9a-f]{32}$/;
22
+ /** How long the way an import ended is remembered, in milliseconds: an hour. */
23
+ const KEPT_MS = 3_600_000;
24
+ const MINUTE_MS = 60_000;
25
+ /** A number in a URL: digits, and few enough to be read as one. */
26
+ const DIGITS = /^\d{1,16}$/;
27
+ /** The server's own databases, which no file is imported into. */
28
+ const SYSTEM_DATABASES = new Set([
29
+ 'mysql',
30
+ 'information_schema',
31
+ 'performance_schema',
32
+ 'sys',
33
+ ]);
34
+ /** The databases listed at most. */
35
+ const MAX_DATABASES = 10_000;
36
+ /** The longest name MySQL gives a database, in characters. */
37
+ const DATABASE_NAME_CHARS = 64;
38
+ /** The longest name of a file that is logged, in characters. */
39
+ const FILE_NAME_CHARS = 255;
40
+ /**
41
+ * The name this session logged in with, as PROCESSLIST has it: USER() without its host, which
42
+ * is what follows the last @ (a name can hold one, a host can't).
43
+ */
44
+ const OWN_LOGIN = "LEFT(USER(), CHAR_LENGTH(USER()) - CHAR_LENGTH(SUBSTRING_INDEX(USER(), '@', -1)) - 1)";
45
+ /**
46
+ * The SQLSTATE class that says a transaction was rolled back. A deadlock is 40001, and so is a
47
+ * commit that a server in a cluster refuses because another server's conflicts with it; MySQL's
48
+ * group replication says 40000 for that.
49
+ */
50
+ const ROLLED_BACK_CLASS = '40';
51
+ /**
52
+ * The errors a statement that commits first was seen to fail with after that commit held, with
53
+ * what ran before it kept: errors of its own work, such as a table that exists or doesn't, a
54
+ * definition the server refuses, a privilege the login lacks, data an ALTER can't convert. Each
55
+ * was seen so on MySQL 8.4 or on MariaDB 11.4, inside START TRANSACTION and with autocommit off,
56
+ * and means the same on the other. Only after one of these is a transaction that is gone known
57
+ * to be committed.
58
+ *
59
+ * What is known is listed, and not what a failed commit is answered with: that has no end. The
60
+ * engine's 1180, a replication hook's 3100, the waits for a backup's lock (1205, 1317, 1969), a
61
+ * read-only server's 1290, 1105 from MySQL's commit and from MariaDB's Galera (past its
62
+ * write-set limit), Galera's 1235 and 1047, the binary log's 1026 and 1024, a file's own numbers
63
+ * below 100, and whatever a plugin or a cluster adds. Each server rolls the transaction back
64
+ * then. After an error on neither list, whether what ran was kept is not known.
65
+ */
66
+ const AFTER_COMMIT = new Set([
67
+ ...[1005, 1007, 1008, 1044, 1049, 1050, 1051, 1054, 1060, 1061, 1062, 1067, 1068, 1071],
68
+ ...[1072, 1075, 1090, 1091, 1118, 1138, 1141, 1142, 1146, 1147, 1166, 1170, 1171, 1227],
69
+ ...[1264, 1265, 1286, 1292, 1304, 1305, 1347, 1359, 1360, 1366, 1370, 1396, 1410, 1418],
70
+ ...[1419, 1451, 1452, 1537, 1539, 1701, 1824, 1826],
71
+ ]);
72
+ /**
73
+ * The same, of one server alone, by its product: past 1900 the two number their errors apart,
74
+ * and a number of one may be another error on the other, or none.
75
+ */
76
+ const AFTER_COMMIT_ON = {
77
+ MySQL: new Set([3503, 3730, 3734, 3780, 3819]),
78
+ MariaDB: new Set([4025, 4092]),
79
+ };
80
+ /**
81
+ * Errors a failed commit is known to be answered with, beside those of class 40, though not all
82
+ * of them (see AFTER_COMMIT). When a statement that commits first fails with one of these and
83
+ * a transaction is open after it, that is not taken for the one that was open before. A failed
84
+ * commit rolls back on both servers (ha_commit_trans), so none is open after one; these are
85
+ * doubted all the same, as class 40 is. Never a reason to call anything kept.
86
+ */
87
+ const COMMIT_FAILED = new Set([1180, 3100, 1205, 1317, 1969, 1290]);
88
+ /** A SQLSTATE: five digits and capitals. */
89
+ const SQLSTATE = /^[0-9A-Z]{5}$/;
90
+ /** The SQLSTATE of an error that has none of its own. */
91
+ const NO_SQLSTATE = 'HY000';
92
+ /** White space as the server skips it before and between a statement's words. */
93
+ const GAP = '[ \\t\\n\\r\\f\\v]';
94
+ /**
95
+ * Statements that can't commit, by their first word: after one of these, a transaction still
96
+ * open is the one that was open before it, and none that is open was begun after a commit.
97
+ * Anything else may have committed on its way and begun anew (a second START TRANSACTION,
98
+ * COMMIT AND CHAIN, a CALL), and nothing in the server's answer tells. The list only ever
99
+ * makes the import more careful: it decides what may be run again, never what may run.
100
+ *
101
+ * SET is not on it, for two reasons. It can commit: with autocommit turned on, as SET PASSWORD,
102
+ * and on MariaDB as SET STATEMENT … FOR, which runs any statement after it. And what it sets
103
+ * (the character set, the time zone, the sql_mode, a variable) stays set when the transaction
104
+ * around it is undone, so the statements from there would be read otherwise a second time.
105
+ */
106
+ const STAYS_WITHIN = new RegExp(`^${GAP}*(?:INSERT|REPLACE|UPDATE|DELETE|SELECT|DO|SAVEPOINT|RELEASE|USE)(?![A-Za-z0-9_$])`, 'i');
107
+ /** Where a word ends, as the server reads one: letters, digits, _ and $ go on, and all beyond ASCII. */
108
+ const WORD_END = '(?![A-Za-z0-9_$\\u0080-\\uffff])';
109
+ /** A user's or a host's name, bare or in quotes of any kind. */
110
+ const ACCOUNT_PART = '(?:`[^`]*`|\'[^\']*\'|"[^"]*"|[A-Za-z0-9_$.%-]+)';
111
+ /** What CREATE and ALTER may say between themselves and what they make or change. */
112
+ const MADE_HOW = [
113
+ `OR${GAP}+REPLACE`,
114
+ `ALGORITHM${GAP}*=${GAP}*[A-Za-z]+`,
115
+ `DEFINER${GAP}*=${GAP}*(?:CURRENT_USER${GAP}*\\(${GAP}*\\)|${ACCOUNT_PART}(?:@${ACCOUNT_PART})?)`,
116
+ `SQL${GAP}+SECURITY${GAP}+[A-Za-z]+`,
117
+ 'UNIQUE',
118
+ 'FULLTEXT',
119
+ 'SPATIAL',
120
+ ].join('|');
121
+ /** What CREATE, ALTER and DROP commit for. TEMPORARY is not among them: such a table commits nothing. */
122
+ const MADE = 'DATABASE|SCHEMA|TABLE|INDEX|VIEW|TRIGGER|PROCEDURE|FUNCTION|EVENT|USER';
123
+ /**
124
+ * Statements that commit what is open before they do anything of their own, by their first
125
+ * words: when one of these fails and the transaction that was open is gone, it was committed,
126
+ * unless that commit itself is what failed. None of them runs statements of the file's
127
+ * choosing, so nothing else can have rolled it back. Only an error known to come from the
128
+ * statement's own work after that commit (see `cameAfterCommit`) says it held: after any other,
129
+ * whether the transaction was committed is not known.
130
+ *
131
+ * Only what is sure to be one is on it, each kind seen to commit before it fails on MySQL and
132
+ * on MariaDB. Anything else that ended the transaction (a CALL, an EXECUTE, a COMMIT that
133
+ * failed, a statement behind a comment, a CREATE AGGREGATE FUNCTION, which no server was seen
134
+ * to commit for) may have rolled it back, and is not taken at its word.
135
+ */
136
+ const COMMITS_FIRST = new RegExp(`^${GAP}*(?:` +
137
+ [
138
+ `(?:CREATE|ALTER)(?:${GAP}+(?:${MADE_HOW})${WORD_END})*${GAP}+(?:${MADE})`,
139
+ `DROP${GAP}+(?:${MADE}|TABLES)`,
140
+ `RENAME${GAP}+(?:TABLES?|USER)`,
141
+ `LOCK${GAP}+TABLES?`,
142
+ 'TRUNCATE',
143
+ 'GRANT',
144
+ 'REVOKE',
145
+ ].join('|') +
146
+ `)${WORD_END}`, 'i');
147
+ /**
148
+ * SET with what it sets right behind it: a variable's name or @, a word like GLOBAL or NAMES.
149
+ * It can't roll back, for it runs no statement. It can commit (see STAYS_WITHIN), but then the
150
+ * server ends the transaction with it: after every SET that commits that was tried (autocommit
151
+ * turned on, SET PASSWORD) none was open, on MySQL 8.4 and MariaDB 11.4. So with a transaction
152
+ * open after it, it committed nothing. MariaDB's SET STATEMENT … FOR runs any statement, and is
153
+ * not this; nor is a SET with a comment behind it, which may hide that word.
154
+ */
155
+ const ONLY_SETS = new RegExp(`^${GAP}*SET${GAP}+(?!STATEMENT${WORD_END})[A-Za-z_@\`]`, 'i');
156
+ /** What START TRANSACTION may say of the transaction it opens. */
157
+ const HOW = `(?:WITH${GAP}+CONSISTENT${GAP}+SNAPSHOT|READ${GAP}+(?:ONLY|WRITE))`;
158
+ /**
159
+ * Statements that open a transaction and do nothing else, from first character to last: BEGIN,
160
+ * BEGIN WORK, and START TRANSACTION with its own words. Whole, because what follows the word
161
+ * decides: MariaDB's BEGIN NOT ATOMIC starts a block of statements of any kind.
162
+ */
163
+ const OPENS = new RegExp(`^${GAP}*(?:BEGIN(?:${GAP}+WORK)?|START${GAP}+TRANSACTION(?:${GAP}+${HOW}(?:${GAP}*,${GAP}*${HOW})*)?)${GAP}*$`, 'i');
164
+ function registry() {
165
+ const shared = globalThis;
166
+ return (shared[REGISTRY] ??= {
167
+ open: new Map(),
168
+ viewers: new Set(),
169
+ connections: new Map(),
170
+ ended: new Map(),
171
+ closes: new WeakMap(),
172
+ clock: SYSTEM_CLOCK,
173
+ });
174
+ }
175
+ /**
176
+ * Puts `clock` in the place of the system's timers for every import started from now on, in the
177
+ * whole process; with none, puts the system's back. For tests of the limits.
178
+ */
179
+ export function setImportClock(clock) {
180
+ registry().clock = clock ?? SYSTEM_CLOCK;
181
+ }
182
+ function bindingOf(ctx) {
183
+ // Two createDbAdmins may give one name to two servers: an import is one server's.
184
+ const url = createHash('sha256').update(ctx.connection.url).digest('hex');
185
+ return {
186
+ key: JSON.stringify([ctx.viewer.id, ctx.connection.name, url]),
187
+ connection: JSON.stringify([ctx.connection.name, url]),
188
+ };
189
+ }
190
+ /** What the Import SQL dialog shows first: the server, its databases, what the login may do. */
191
+ export async function options(ctx) {
192
+ importable(ctx);
193
+ const info = await ctx.db.info();
194
+ const names = await databasesOf(ctx, info.database);
195
+ const grants = await grantsOf(ctx);
196
+ return {
197
+ product: info.product,
198
+ version: info.version,
199
+ database: names.includes(info.database) ? info.database : null,
200
+ databases: names.map((name) => ({
201
+ name,
202
+ privileges: grants ? privilegesIn(grants, name) : null,
203
+ })),
204
+ limits: limitsOf(ctx.settings),
205
+ current: currentOf(bindingOf(ctx).key),
206
+ };
207
+ }
208
+ /**
209
+ * Opens an import: a connection of its own, with the database selected, the database's name as
210
+ * the person typed it checked against what the server says is selected.
211
+ *
212
+ * The viewer's place and one of the connection's are taken first, with nothing awaited between
213
+ * the look and the taking, so no number of requests at once gets past them; and given back
214
+ * whatever then refuses.
215
+ */
216
+ export async function start(ctx, body, signal) {
217
+ importable(ctx);
218
+ const request = startRequest(body);
219
+ const binding = bindingOf(ctx);
220
+ const closes = registry().closes.get(ctx.owner) ?? 0;
221
+ const release = takePlaces(ctx, binding);
222
+ try {
223
+ if (request.previousThread !== undefined)
224
+ await endedOnServer(ctx, request.previousThread);
225
+ const own = ctx.connection.databases === 'one' ? (await ctx.db.info()).database : '';
226
+ if (!(await databasesOf(ctx, own)).includes(request.database)) {
227
+ throw new DbAdminError(`There’s no database "${request.database}" to import into on connection "${ctx.connection.name}".`, 404, 'unknown-database');
228
+ }
229
+ const importer = await ctx.db.importer({ idleMs: ctx.settings.idleMs });
230
+ try {
231
+ const session = await importer.use(request.database);
232
+ if (request.confirm !== session.database) {
233
+ throw new DbAdminError(`To import, send the database’s name, "${session.database}", as "confirm".`, 400, 'unconfirmed');
234
+ }
235
+ // Its createDbAdmin closed meanwhile, and its driver with it: this connection too.
236
+ if ((registry().closes.get(ctx.owner) ?? 0) !== closes) {
237
+ throw new DbAdminError('The tool was closed while the import opened.', 409, 'closed');
238
+ }
239
+ const opened = new OpenImport(ctx, binding, importer, request.database, session, release);
240
+ await opened.began(request.file);
241
+ // The request went while the import opened: its id reaches nobody, so nothing could ever
242
+ // ask after it or end it. It would hold its connection until its idle time is over.
243
+ if (signal?.aborted) {
244
+ await opened.end('unheard');
245
+ throw unheard();
246
+ }
247
+ return {
248
+ import: opened.id,
249
+ thread: importer.target.thread,
250
+ sqlMode: importer.target.sqlMode,
251
+ noBackslashEscapes: session.noBackslashEscapes,
252
+ ansiQuotes: session.ansiQuotes,
253
+ characterSet: session.characterSet,
254
+ database: session.database,
255
+ limits: limitsOf(ctx.settings),
256
+ };
257
+ }
258
+ catch (error) {
259
+ await importer.end().catch(() => { });
260
+ throw error;
261
+ }
262
+ }
263
+ catch (error) {
264
+ release();
265
+ throw error;
266
+ }
267
+ }
268
+ /**
269
+ * One batch of an import's statements. Everything that can refuse it from what the server
270
+ * holds is looked at first, in one step with nothing awaited, and the import is marked busy in
271
+ * that same step: only then is the body read. The answer's lines follow the batch, which runs
272
+ * to its end whether or not anyone reads them.
273
+ */
274
+ export async function run(ctx, request) {
275
+ const found = lookup(ctx, new URL(request.url).searchParams.get('import'));
276
+ if (!found.open)
277
+ throw closed();
278
+ const batch = batchOf(new URL(request.url).searchParams);
279
+ const refused = found.open.claim(batch);
280
+ if (refused)
281
+ throw new DbAdminError(refused.message, 409, refused.code);
282
+ let statements;
283
+ try {
284
+ statements = batch.count
285
+ ? decodeFrames(await readBytes(request, IMPORT_BATCH_BYTES, 'A batch of statements', IMPORT_BODY_MS), batch.count)
286
+ : [];
287
+ }
288
+ catch (error) {
289
+ found.open.unclaim();
290
+ throw error;
291
+ }
292
+ const answer = found.open.accept(batch, statements);
293
+ if (!answer)
294
+ throw closed();
295
+ return answer;
296
+ }
297
+ /** Where an import is, from what the server holds: nothing is asked of its connection. */
298
+ export async function status(ctx, id) {
299
+ const found = lookup(ctx, id);
300
+ return found.open ? found.open.status() : found.kept.status;
301
+ }
302
+ /**
303
+ * Ends an import: what runs is stopped, what is open is rolled back, the connection closed.
304
+ *
305
+ * The import is named by its id, or it is the viewer's open one on the connection (`current`).
306
+ * That is for a window that never had the id, or lost it with its page: without it, an import
307
+ * whose dialog is gone would hold its connection, and that connection's locks, until its idle
308
+ * time is over. Both ways end it the same.
309
+ */
310
+ export async function end(ctx, body) {
311
+ if (body.current !== undefined)
312
+ return ownOpen(ctx, body).end('asked');
313
+ const found = lookup(ctx, body.import);
314
+ return found.open ? found.open.end('asked') : found.kept.ended;
315
+ }
316
+ /** Ends every import `owner`, a createDbAdmin, opened: its drivers are about to close. */
317
+ export async function close(owner) {
318
+ const { open, closes } = registry();
319
+ closes.set(owner, (closes.get(owner) ?? 0) + 1);
320
+ await Promise.all([...open.values()].filter((o) => o.owner === owner).map((o) => o.end('closed')));
321
+ }
322
+ /** Refuses a viewer who may not write, and a connection no file can be imported into. */
323
+ function importable(ctx) {
324
+ if (ctx.access !== 'write') {
325
+ throw new DbAdminError(`Importing needs write access, and connection "${ctx.connection.name}" is read-only.`, 403, 'read-only');
326
+ }
327
+ if (typeof ctx.db.importer !== 'function') {
328
+ throw new DbAdminError(`Connection "${ctx.connection.name}" can't take an SQL file here: imports are for MySQL and MariaDB.`, 400, 'no-imports');
329
+ }
330
+ }
331
+ /**
332
+ * The viewer's import with this id on this connection: the open one, which this request then
333
+ * counts as a sign of life for, or how it ended. Anything else is one refusal: an id nobody
334
+ * has, another viewer's, another connection's.
335
+ */
336
+ function lookup(ctx, id) {
337
+ importable(ctx);
338
+ const { key } = bindingOf(ctx);
339
+ if (typeof id === 'string' && ID.test(id)) {
340
+ const open = registry().open.get(id);
341
+ if (open?.key === key) {
342
+ open.touch(ctx);
343
+ return { open };
344
+ }
345
+ const kept = keptFor(key);
346
+ if (kept?.id === id)
347
+ return { kept };
348
+ }
349
+ throw unknownImport();
350
+ }
351
+ /**
352
+ * The viewer's open import on this connection, for a request that names it by `current` and
353
+ * not by its id. It is found by who asks and never by what they send, so it is never another
354
+ * viewer's; with none open, the refusal is the one for an id nobody has.
355
+ */
356
+ function ownOpen(ctx, body) {
357
+ importable(ctx);
358
+ if ((body.current !== true && body.current !== 1) || body.import !== undefined) {
359
+ throw bad('To end your open import on the connection without its id, send "current": true and no "import"; with its id, send "import" alone.');
360
+ }
361
+ const open = openFor(bindingOf(ctx).key);
362
+ if (!open)
363
+ throw unknownImport();
364
+ open.touch(ctx);
365
+ return open;
366
+ }
367
+ function unknownImport() {
368
+ return new DbAdminError('There’s no such import. It may have ended more than an hour ago, or the server has restarted since it began.', 404, 'unknown-import');
369
+ }
370
+ const ENDED = { code: 'import-ended', message: 'The import has ended.' };
371
+ /** What import-start answers when nobody is left to hear it, for the log of whoever serves it. */
372
+ function unheard() {
373
+ return new DbAdminError('The request for the import had gone before the import was open, and nothing could have named it: it was ended.', 409, ENDED.code);
374
+ }
375
+ function closed() {
376
+ return new DbAdminError(ENDED.message, 409, ENDED.code);
377
+ }
378
+ /** How the viewer's last import on the connection ended, for as long as that is remembered. */
379
+ function keptFor(key) {
380
+ const { ended, clock } = registry();
381
+ const kept = ended.get(key);
382
+ if (kept && clock.now() - kept.at >= KEPT_MS)
383
+ ended.delete(key);
384
+ return ended.get(key);
385
+ }
386
+ /** The viewer's open import on the connection. */
387
+ function openFor(key) {
388
+ for (const open of registry().open.values())
389
+ if (open.key === key)
390
+ return open;
391
+ return undefined;
392
+ }
393
+ /** The viewer's open import on the connection, or how the last one ended; never its id. */
394
+ function currentOf(key) {
395
+ return openFor(key)?.status() ?? keptFor(key)?.status ?? null;
396
+ }
397
+ /**
398
+ * Takes the viewer's place on the connection and one of the connection's, or refuses. The
399
+ * answer gives both back, once.
400
+ */
401
+ function takePlaces(ctx, binding) {
402
+ const { viewers, connections } = registry();
403
+ const name = ctx.connection.name;
404
+ if (viewers.has(binding.key)) {
405
+ throw new DbAdminError(placeTaken(binding.key, name), 409, 'import-open');
406
+ }
407
+ const taken = connections.get(binding.connection) ?? 0;
408
+ if (taken >= ctx.settings.perDriver) {
409
+ throw new DbAdminError(`Connection "${name}" has ${taken} ${taken === 1 ? 'import' : 'imports'} open, the most it takes at once. Try again when one has ended.`, 409, 'import-limit');
410
+ }
411
+ viewers.add(binding.key);
412
+ connections.set(binding.connection, taken + 1);
413
+ let held = true;
414
+ return () => {
415
+ if (!held)
416
+ return;
417
+ held = false;
418
+ viewers.delete(binding.key);
419
+ const left = (connections.get(binding.connection) ?? 1) - 1;
420
+ if (left > 0)
421
+ connections.set(binding.connection, left);
422
+ else
423
+ connections.delete(binding.connection);
424
+ };
425
+ }
426
+ /**
427
+ * Why the viewer's place on connection `name` is taken, and when it is free again. The dialog
428
+ * that started the import may be gone, reloaded or closed: its viewer is told how long the
429
+ * import still has when nothing is done, and that ending it frees the place at once.
430
+ */
431
+ function placeTaken(key, name) {
432
+ const left = openFor(key)?.closesInMs();
433
+ // The place is held from before the import opens until after it has closed.
434
+ if (left === undefined) {
435
+ return `An import of yours is opening or closing on connection "${name}". Ask again in a moment.`;
436
+ }
437
+ const minutes = Math.max(1, Math.ceil(left / MINUTE_MS));
438
+ return `You already have an import open on connection "${name}". It closes by itself in about ${minutes} ${minutes === 1 ? 'minute' : 'minutes'} if nothing asks after it. To start another now, end that one first.`;
439
+ }
440
+ function limitsOf(settings) {
441
+ return {
442
+ batchBytes: IMPORT_BATCH_BYTES,
443
+ batchStatements: IMPORT_BATCH_STATEMENTS,
444
+ statementBytes: IMPORT_STATEMENT_BYTES,
445
+ heartbeatMs: IMPORT_HEARTBEAT_MS,
446
+ bodyMs: IMPORT_BODY_MS,
447
+ statementTimeoutMs: settings.statementTimeoutMs,
448
+ idleMs: settings.idleMs,
449
+ pauseMs: settings.pauseMs,
450
+ };
451
+ }
452
+ /**
453
+ * The databases a file can be imported into: the server's list as the login sees it, empty
454
+ * ones too, without the server's own; or the connection's own alone (`own`), when it is pinned
455
+ * to it.
456
+ */
457
+ async function databasesOf(ctx, own) {
458
+ const mine = (name) => !SYSTEM_DATABASES.has(name);
459
+ if (ctx.connection.databases === 'one')
460
+ return own && mine(own) ? [own] : [];
461
+ const { rows } = await ctx.db.query('SELECT SCHEMA_NAME FROM information_schema.SCHEMATA ORDER BY SCHEMA_NAME', { access: 'read', maxRows: MAX_DATABASES, timeoutMs: ctx.timeoutMs });
462
+ return rows.flatMap(([name]) => (name && mine(name) ? [name] : []));
463
+ }
464
+ /**
465
+ * Refuses (409) while the database server still runs a statement on `thread`: the connection
466
+ * of an import this process no longer knows, because the tool restarted under it. Its statement
467
+ * runs on with nobody to hear its answer, and the same file begun again would run beside it.
468
+ *
469
+ * Only a connection of this login that is running something counts. One whose client has gone
470
+ * never sleeps: the server ends it once it has nothing to run. A sleeping one with that number
471
+ * is someone else's, numbered anew after the database server itself restarted, and may sleep
472
+ * for good. So may the connection this is asked on have that number, and it is running this.
473
+ */
474
+ async function endedOnServer(ctx, thread) {
475
+ const { rows } = await ctx.db.query(`SELECT COUNT(*) FROM information_schema.PROCESSLIST
476
+ WHERE ID = ${thread} AND ID <> CONNECTION_ID() AND COMMAND <> 'Sleep' AND USER = ${OWN_LOGIN}`, { access: 'read', maxRows: 1, timeoutMs: ctx.timeoutMs });
477
+ if (rows[0]?.[0] === '0')
478
+ return;
479
+ throw new DbAdminError(`The server is still running a statement of your last import, on its connection ${thread}. A new import can start when that has ended.`, 409, 'import-thread');
480
+ }
481
+ /** The lines of the login's SHOW GRANTS; null when the server won't say. */
482
+ async function grantsOf(ctx) {
483
+ try {
484
+ const { rows } = await ctx.db.query('SHOW GRANTS', {
485
+ access: 'read',
486
+ maxRows: MAX_DATABASES,
487
+ timeoutMs: ctx.timeoutMs,
488
+ });
489
+ return rows.flatMap(([line]) => (line ? [line] : []));
490
+ }
491
+ catch (error) {
492
+ console.error(`otw-db: could not read the grants of "${ctx.connection.name}"`, error);
493
+ return null;
494
+ }
495
+ }
496
+ /**
497
+ * What import-start was sent, checked: the database, the name typed, the file for the log, and
498
+ * the server's connection of an earlier import, when the browser had one that went unknown.
499
+ */
500
+ function startRequest(body) {
501
+ const { database, confirm, previousThread } = body;
502
+ if (typeof database !== 'string' || !database || database.length > DATABASE_NAME_CHARS) {
503
+ throw bad('"database" is the name of the database to import into.');
504
+ }
505
+ // It goes into a statement as its digits: nothing but a whole number gets that far.
506
+ if (previousThread !== undefined &&
507
+ (!Number.isSafeInteger(previousThread) || previousThread < 1)) {
508
+ throw bad('"previousThread" is the "thread" an earlier import-start answered with, a whole number.');
509
+ }
510
+ const file = body.file;
511
+ if (typeof file !== 'object' || file === null)
512
+ throw bad('"file" says which file is imported.');
513
+ const { name, size, statements } = file;
514
+ if (typeof name !== 'string' || !name || name.length > FILE_NAME_CHARS) {
515
+ throw bad(`"file.name" is the file’s name, ${FILE_NAME_CHARS} characters at most.`);
516
+ }
517
+ if (!Number.isSafeInteger(size) || size < 0) {
518
+ throw bad('"file.size" is the file’s size in bytes.');
519
+ }
520
+ if (!Number.isSafeInteger(statements) || statements < 1) {
521
+ throw bad('"file.statements" is how many statements the file holds, 1 or more.');
522
+ }
523
+ return {
524
+ database,
525
+ confirm,
526
+ previousThread: previousThread,
527
+ file: { name, size: size, statements: statements },
528
+ };
529
+ }
530
+ function batchOf(params) {
531
+ const batch = {
532
+ start: numberIn(params, 'start'),
533
+ count: numberIn(params, 'count'),
534
+ ...(params.has('skip') ? { skip: numberIn(params, 'skip') } : {}),
535
+ noBackslashEscapes: bitIn(params, 'nbe'),
536
+ ansiQuotes: bitIn(params, 'aq'),
537
+ };
538
+ // Refuses (400) the numbers no batch has.
539
+ batchLast(batch);
540
+ return batch;
541
+ }
542
+ function numberIn(params, name) {
543
+ const value = params.get(name) ?? '';
544
+ if (!DIGITS.test(value))
545
+ throw bad(`"${name}" is a whole number.`);
546
+ return Number(value);
547
+ }
548
+ function bitIn(params, name) {
549
+ const value = params.get(name);
550
+ if (value !== '0' && value !== '1')
551
+ throw bad(`"${name}" is 0 or 1.`);
552
+ return value === '1';
553
+ }
554
+ /**
555
+ * The answer to import-run, as the batch writes it. The batch only ever writes: a reader that
556
+ * has gone is noted here, and nothing of it reaches the batch.
557
+ */
558
+ class Lines {
559
+ #encoder = new TextEncoder();
560
+ #controller;
561
+ #gone = false;
562
+ #stream = new ReadableStream({
563
+ start: (controller) => {
564
+ this.#controller = controller;
565
+ },
566
+ cancel: () => {
567
+ this.#gone = true;
568
+ },
569
+ });
570
+ write(line) {
571
+ if (this.#gone)
572
+ return;
573
+ try {
574
+ this.#controller.enqueue(this.#encoder.encode(`${JSON.stringify(line)}\n`));
575
+ }
576
+ catch {
577
+ this.#gone = true;
578
+ }
579
+ }
580
+ /** A line that only says the batch is alive: left out when the last one is still unread. */
581
+ beat(line) {
582
+ if (!this.#gone && (this.#controller.desiredSize ?? 0) > 0)
583
+ this.write(line);
584
+ }
585
+ close() {
586
+ if (this.#gone)
587
+ return;
588
+ this.#gone = true;
589
+ try {
590
+ this.#controller.close();
591
+ }
592
+ catch {
593
+ // Its reader went first.
594
+ }
595
+ }
596
+ response() {
597
+ return new Response(this.#stream, {
598
+ headers: {
599
+ 'content-type': 'application/x-ndjson; charset=utf-8',
600
+ // A proxy that holds lines back to fill a buffer, or to compress, hides a batch that runs.
601
+ // And no cache, the browser's own included, keeps an answer whose errors can quote the
602
+ // file. The Chromium that Playwright brings (156) lists such a streamed answer as a
603
+ // cancelled request though it was read to its end; Google Chrome (158) doesn't, and
604
+ // that is no reason to let it be stored.
605
+ 'cache-control': 'no-store, no-transform',
606
+ 'x-accel-buffering': 'no',
607
+ 'x-content-type-options': 'nosniff',
608
+ },
609
+ });
610
+ }
611
+ }
612
+ /** One import, from when its connection has the database selected until it has closed. */
613
+ class OpenImport {
614
+ id = randomBytes(16).toString('hex');
615
+ key;
616
+ owner;
617
+ #importer;
618
+ #settings;
619
+ #release;
620
+ /** What every audit event of it says: who, on which connection, into which database. */
621
+ #about;
622
+ /** The audit log of the createDbAdmin that last asked for it. */
623
+ #record;
624
+ /** The number of the last statement done or left out. */
625
+ #done = 0;
626
+ /** The session as the server last said it is. */
627
+ #session;
628
+ /**
629
+ * The number of the statement that opened the transaction that is open, or the earliest it
630
+ * can have begun at (see `#committedSince`).
631
+ */
632
+ #since;
633
+ /** The session as it was just before that statement. */
634
+ #opened;
635
+ /**
636
+ * A statement from `#since` on can't be sent again to do what it first did: a SET, whose
637
+ * setting a rollback leaves; one that may have committed; one that opened the transaction and
638
+ * may have done more than open it; or the transaction was open before the import's first.
639
+ * What a rollback undid is then not offered again. Said anew by each statement that opens a
640
+ * transaction, and of no meaning while none is open.
641
+ */
642
+ #mixed = false;
643
+ /**
644
+ * A statement from `#since` on may have committed on its way, and begun another transaction:
645
+ * anything but a plain statement (STAYS_WITHIN), a SET (ONLY_SETS), and as the transaction's
646
+ * first a statement that only opens it (OPENS) or one that commits first (what it commits is
647
+ * from before it). The open transaction may then be a later one than began at `#since`, and
648
+ * what ran from there committed in part: nothing tells where that commit was, so nothing from
649
+ * `#since` is called undone. Said anew with `#mixed`.
650
+ */
651
+ #committedSince = false;
652
+ /** Statements the server refused, until each is done or left out. */
653
+ #refused = new Set();
654
+ #failure;
655
+ /** A batch has the import: from before its body is read until its last line is written. */
656
+ #busy = false;
657
+ #batch = null;
658
+ /** The statement the server is being waited on for, and since when. */
659
+ #running;
660
+ /** The import is ending: no further statement starts. */
661
+ #stopping = false;
662
+ #ending = null;
663
+ /** The connection went, other than by the import's end. */
664
+ #lost = false;
665
+ /** A statement that got no answer: whether it finished is the connection's end to say. */
666
+ #unanswered;
667
+ /** A refused statement's session could not be asked: what it left open is not known. */
668
+ #unknown = false;
669
+ /** When the last request for it came, on the registry's clock: its idle time counts from here. */
670
+ #asked = 0;
671
+ #stopIdle = () => { };
672
+ #stopPause = () => { };
673
+ constructor(ctx, binding, importer, database, session, release) {
674
+ this.key = binding.key;
675
+ this.owner = ctx.owner;
676
+ this.#importer = importer;
677
+ this.#settings = ctx.settings;
678
+ this.#release = release;
679
+ this.#about = { viewer: ctx.viewer.id, connection: ctx.connection.name, database };
680
+ this.#record = ctx.record;
681
+ this.#session = session;
682
+ // Open already as the import begins: whatever the file adds to it goes with it. Nothing
683
+ // of the file opened it, so nothing of the file can open it again as it was.
684
+ if (session.inTransaction) {
685
+ this.#since = 1;
686
+ this.#opened = session;
687
+ this.#mixed = true;
688
+ }
689
+ registry().open.set(this.id, this);
690
+ importer.onLost(() => {
691
+ this.#lost = true;
692
+ // A batch that runs still has an answer to hear, and ends the import itself after it.
693
+ if (!this.#batch)
694
+ void this.end('lost');
695
+ });
696
+ this.#rest();
697
+ }
698
+ /** Writes the import's first audit event: nothing of the file has run. */
699
+ async began(file) {
700
+ await this.#log(`import of ${JSON.stringify(file.name)} (${file.size} bytes, ${file.statements} statements)`, { step: 'start', thread: this.#importer.target.thread, file });
701
+ }
702
+ /** A request for it that passed every check: its browser is still there. */
703
+ touch(ctx) {
704
+ this.#record = ctx.record;
705
+ this.#rest();
706
+ }
707
+ /** Starts the time the import may sit with no request for it, from now. */
708
+ #rest() {
709
+ this.#stopIdle();
710
+ if (this.#ending)
711
+ return;
712
+ const { clock } = registry();
713
+ this.#asked = clock.now();
714
+ this.#stopIdle = clock.after(this.#settings.idleMs, () => void this.end('idle'));
715
+ }
716
+ /**
717
+ * How long it stays open at most if no request comes for it, in milliseconds: until its idle
718
+ * time is over, or the time for the choice after a failure, whichever is first. Undefined once
719
+ * it is ending: its place is then free as soon as its connection has closed.
720
+ */
721
+ closesInMs() {
722
+ if (this.#ending)
723
+ return undefined;
724
+ const { idleMs, pauseMs } = this.#settings;
725
+ const idle = this.#asked + idleMs;
726
+ const closes = this.#failure ? Math.min(idle, this.#failure.at + pauseMs) : idle;
727
+ return closes - registry().clock.now();
728
+ }
729
+ /**
730
+ * Takes the import for `batch`, or says why it can't have it, from what is held in memory
731
+ * alone: no other batch has it, the batch starts at the next statement, it was split as the
732
+ * session reads strings now, and what it leaves out is a statement the server refused.
733
+ */
734
+ claim(batch) {
735
+ if (this.#ending)
736
+ return ENDED;
737
+ if (this.#busy) {
738
+ return {
739
+ code: 'import-busy',
740
+ message: 'The import is running a batch. Ask import-status where it is.',
741
+ };
742
+ }
743
+ if (batch.start !== this.#done + 1) {
744
+ return {
745
+ code: 'import-position',
746
+ message: `The import’s next statement is ${this.#done + 1}, not ${batch.start}.`,
747
+ };
748
+ }
749
+ const { noBackslashEscapes, ansiQuotes } = this.#session;
750
+ if (batch.noBackslashEscapes !== noBackslashEscapes || batch.ansiQuotes !== ansiQuotes) {
751
+ return {
752
+ code: 'import-mode',
753
+ message: 'The batch was split under another sql_mode than the import’s session has now. Ask import-status, and split it again.',
754
+ };
755
+ }
756
+ if (batch.skip !== undefined && !this.#refused.has(batch.skip)) {
757
+ return {
758
+ code: 'import-skip',
759
+ message: `Statement ${batch.skip} can’t be left out: the server didn’t refuse it.`,
760
+ };
761
+ }
762
+ this.#busy = true;
763
+ return null;
764
+ }
765
+ /** Lets go of the import for a batch whose body was refused: nothing of it ran. */
766
+ unclaim() {
767
+ this.#busy = false;
768
+ }
769
+ /**
770
+ * Starts the batch whose body has arrived whole, and answers with its lines as they come;
771
+ * null when the import was closed while the body arrived.
772
+ */
773
+ accept(batch, statements) {
774
+ this.#busy = !this.#ending;
775
+ if (this.#ending)
776
+ return null;
777
+ // The choice after a failure is made: its time is over.
778
+ this.#stopPause();
779
+ this.#failure = undefined;
780
+ const lines = new Lines();
781
+ this.#batch = this.#run(batch, statements, lines);
782
+ return lines.response();
783
+ }
784
+ status() {
785
+ const { clock } = registry();
786
+ // Once it is ending, no batch is taken and no choice is waited for: to say `failed` or
787
+ // `idle` would offer what `claim` then refuses. How it ended can be said when it has.
788
+ const ending = this.#ending !== null;
789
+ const state = this.#batch || ending ? 'running' : this.#failure ? 'failed' : 'idle';
790
+ const since = this.#since ?? this.#failure?.since;
791
+ const { n, error, state: became, at } = this.#failure ?? {};
792
+ return {
793
+ state,
794
+ done: this.#done,
795
+ ...(this.#running
796
+ ? { running: { n: this.#running.n, ms: Math.round(clock.now() - this.#running.at) } }
797
+ : {}),
798
+ ...(n === undefined ? {} : { failure: { n, error: error, state: became } }),
799
+ inTransaction: this.#session.inTransaction,
800
+ ...(since === undefined ? {} : { since }),
801
+ ...this.#reading(),
802
+ ...(state === 'failed'
803
+ ? { pauseLeftMs: Math.max(0, Math.round(at + this.#settings.pauseMs - clock.now())) }
804
+ : {}),
805
+ ...(ending ? { ending: true } : {}),
806
+ };
807
+ }
808
+ /** The session's reading, as the server last heard it: see protocol.ts. */
809
+ #reading() {
810
+ const { noBackslashEscapes, ansiQuotes, characterSet, database } = this.#session;
811
+ return { noBackslashEscapes, ansiQuotes, characterSet, database };
812
+ }
813
+ /**
814
+ * Ends the import, once, whoever asks first: no further statement starts, what runs is
815
+ * stopped and waited for, what is open is rolled back and the connection is closed.
816
+ */
817
+ end(why) {
818
+ this.#ending ??= this.#close(why);
819
+ return this.#ending;
820
+ }
821
+ async #close(why) {
822
+ this.#stopping = true;
823
+ this.#stopIdle();
824
+ this.#stopPause();
825
+ const batch = this.#batch;
826
+ let ended = { done: this.#done, rolledBack: this.#session.inTransaction };
827
+ try {
828
+ const how = await this.#importer.end().catch((error) => {
829
+ console.error('otw-db: an import’s connection could not be closed', error);
830
+ return { transaction: 'abandoned', inDoubt: true };
831
+ });
832
+ // The batch has heard its statement's end by now, and writes its last line.
833
+ await batch;
834
+ ended = this.#ended(how);
835
+ }
836
+ finally {
837
+ const { open, ended: kept, clock } = registry();
838
+ open.delete(this.id);
839
+ this.#release();
840
+ for (const [key, old] of kept)
841
+ if (clock.now() - old.at >= KEPT_MS)
842
+ kept.delete(key);
843
+ kept.set(this.key, {
844
+ id: this.id,
845
+ at: clock.now(),
846
+ status: this.#closedStatus(why, ended),
847
+ ended,
848
+ });
849
+ }
850
+ const { done, rolledBack, doubt } = ended;
851
+ await this.#log(`import ended (${why}) after statement ${done}`, {
852
+ step: 'end',
853
+ thread: this.#importer.target.thread,
854
+ why,
855
+ done,
856
+ rolledBack,
857
+ ...(doubt === undefined ? {} : { doubt }),
858
+ });
859
+ return ended;
860
+ }
861
+ /**
862
+ * How far the import got, from how its connection closed. Only a rollback the server took is
863
+ * known. Where the connection went without one, the server undoes what was open on it: that
864
+ * is whatever was open as far as this import last heard, and after a refused statement it
865
+ * could not ask about, it counts as one.
866
+ *
867
+ * What was rolled back is said to be from `#since` only when that is where the transaction
868
+ * began: after a statement in it that may have committed, statements from there may be kept.
869
+ */
870
+ #ended(how) {
871
+ const rolledBack = how.transaction === 'rolled-back' ||
872
+ (how.transaction === 'abandoned' && (this.#session.inTransaction || this.#unknown));
873
+ const doubt = how.inDoubt ? this.#unanswered : undefined;
874
+ const since = rolledBack && !this.#committedSince ? this.#since : undefined;
875
+ return {
876
+ done: this.#done,
877
+ rolledBack,
878
+ ...(since === undefined ? {} : { since }),
879
+ ...(doubt === undefined ? {} : { doubt }),
880
+ };
881
+ }
882
+ /**
883
+ * What is remembered of the import once it has closed: where it got to and how it ended, in
884
+ * numbers. Nothing of the file is among them, so the error is kept without its message.
885
+ *
886
+ * After a failure that undid the transaction, or left it unknown whether it was kept, `since`
887
+ * is where those statements begin, as the failure said; otherwise it is the end's.
888
+ */
889
+ #closedStatus(why, ended) {
890
+ const { n, error, state } = this.#failure ?? {};
891
+ const since = state === 'rolled-back' || state === 'unknown' ? this.#failure.since : ended.since;
892
+ return {
893
+ state: why === 'lost' ? 'lost' : 'ended',
894
+ done: ended.done,
895
+ ...(n === undefined ? {} : { failure: { n, error: numbersOf(error), state: state } }),
896
+ inTransaction: false,
897
+ ...(since === undefined ? {} : { since }),
898
+ ...this.#reading(),
899
+ ...(ended.rolledBack ? { rolledBack: true } : {}),
900
+ ...(ended.doubt === undefined ? {} : { doubt: ended.doubt }),
901
+ };
902
+ }
903
+ /**
904
+ * One batch, from its first audit event to its last line. It is the import's and not the
905
+ * request's: nothing a browser does, and nothing here, can stop it short of the import's end.
906
+ * It never rejects.
907
+ */
908
+ async #run(batch, statements, lines) {
909
+ const { clock } = registry();
910
+ const started = clock.now();
911
+ const tally = { rows: 0, error: undefined };
912
+ let last;
913
+ lines.write({ type: 'accepted', start: batch.start, count: batch.count });
914
+ try {
915
+ // In the log before the first of them is sent: what ran is never more than what it says.
916
+ for (const event of this.#events(batch, statements)) {
917
+ await this.#log(event.statement, event.detail);
918
+ }
919
+ last = await this.#statements(batch, statements, lines, tally);
920
+ }
921
+ catch (error) {
922
+ console.error('otw-db: an import’s batch stopped on an error of the tool’s own', error);
923
+ tally.error = error.message;
924
+ this.#lost = true;
925
+ last = { type: 'lost', done: this.#done };
926
+ }
927
+ try {
928
+ // Its result too, whether or not anyone still reads the answer.
929
+ await this.#log(`statements ${batch.start} to ${batchLast(batch)} of the import: ${last.type}`, {
930
+ ...this.#detail(batch.start, batch.count, batch.skip),
931
+ ended: last.type,
932
+ done: this.#done,
933
+ }, {
934
+ durationMs: Math.round(clock.now() - started),
935
+ rows: tally.rows,
936
+ ...(tally.error === undefined ? {} : { error: tally.error }),
937
+ });
938
+ }
939
+ finally {
940
+ // Let go before the last line is written: whoever reads it may send the next batch at once.
941
+ this.#batch = null;
942
+ this.#busy = false;
943
+ // The time for the choice starts once the choice can be made.
944
+ if (this.#failure && !this.#stopping)
945
+ this.#pause();
946
+ lines.write(last);
947
+ lines.close();
948
+ if (this.#lost)
949
+ void this.end('lost');
950
+ }
951
+ }
952
+ /** Starts the time the choice after a failure may take. */
953
+ #pause() {
954
+ const { clock } = registry();
955
+ this.#failure.at = clock.now();
956
+ this.#stopPause = clock.after(this.#settings.pauseMs, () => void this.end('pause'));
957
+ }
958
+ /** The batch's statements as its audit events hold them, each naming the statements it has. */
959
+ #events(batch, statements) {
960
+ const numbers = batchNumbers(batch);
961
+ // Read as the session reads them: the batch's word for that was held against the server's.
962
+ return auditParts(statements, batch).map((part) => {
963
+ const start = part.from === 0 ? batch.start : numbers[part.from];
964
+ const skip = batch.skip !== undefined && batch.skip >= start && batch.skip <= start + part.count
965
+ ? batch.skip
966
+ : undefined;
967
+ return {
968
+ statement: part.statement || `statement ${batch.skip} left out`,
969
+ detail: this.#detail(start, part.count, skip),
970
+ };
971
+ });
972
+ }
973
+ #detail(start, count, skip) {
974
+ return {
975
+ step: 'batch',
976
+ thread: this.#importer.target.thread,
977
+ start,
978
+ count,
979
+ ...(skip === undefined ? {} : { skip }),
980
+ };
981
+ }
982
+ /** Runs the batch's statements in turn, and answers with the line the batch ends on. */
983
+ async #statements(batch, statements, lines, tally) {
984
+ const numbers = batchNumbers(batch);
985
+ this.#leaveOut(batch.skip);
986
+ for (const [i, sql] of statements.entries()) {
987
+ const n = numbers[i];
988
+ const before = this.#session;
989
+ const watched = this.#watch(n, lines);
990
+ let result;
991
+ try {
992
+ result = await this.#importer.run(sql, { timeoutMs: this.#settings.statementTimeoutMs });
993
+ }
994
+ catch (error) {
995
+ // No answer came for it: whether it finished is for the connection's end to say.
996
+ this.#unanswered = n;
997
+ tally.error = error.message;
998
+ return this.#stopping ? { type: 'stopped', done: this.#done } : this.#gone(true);
999
+ }
1000
+ finally {
1001
+ watched.end();
1002
+ }
1003
+ if (result.error) {
1004
+ tally.error = result.error.message;
1005
+ return this.#refusedAt(n, sql, result.error, before);
1006
+ }
1007
+ // Counted here, when its result has arrived and before any line says so.
1008
+ this.#done = n;
1009
+ this.#refused.delete(n);
1010
+ this.#leaveOut(batch.skip);
1011
+ tally.rows += result.affected;
1012
+ lines.write({
1013
+ type: 'statement',
1014
+ n,
1015
+ affected: result.affected,
1016
+ warnings: result.warnings,
1017
+ rows: result.rows,
1018
+ ms: watched.ms(),
1019
+ });
1020
+ if (result.lost) {
1021
+ tally.error = result.lost.message;
1022
+ return this.#gone(false);
1023
+ }
1024
+ const { inTransaction, noBackslashEscapes, ansiQuotes, database, characterSet } = result;
1025
+ const after = { inTransaction, noBackslashEscapes, ansiQuotes, database, characterSet };
1026
+ // One that commits first ended the transaction that was open: one open after it began in it.
1027
+ this.#ran(n, sql, before, after, !before.inTransaction || COMMITS_FIRST.test(sql));
1028
+ if (!sameReading(before, after)) {
1029
+ // The rest was split and checked as the session no longer reads it: none of it is sent.
1030
+ lines.write({ type: 'mode', after: n, ...this.#reading() });
1031
+ break;
1032
+ }
1033
+ }
1034
+ return {
1035
+ type: 'done',
1036
+ done: this.#done,
1037
+ inTransaction: this.#session.inTransaction,
1038
+ ...(this.#since === undefined ? {} : { since: this.#since }),
1039
+ };
1040
+ }
1041
+ /** Counts the statement a batch leaves out as done, once those before it are. */
1042
+ #leaveOut(skip) {
1043
+ if (skip !== this.#done + 1)
1044
+ return;
1045
+ this.#done = skip;
1046
+ this.#refused.delete(skip);
1047
+ }
1048
+ /**
1049
+ * Marks statement `n` as the one the server is waited on for, and writes a line every ten
1050
+ * seconds for as long as it is.
1051
+ */
1052
+ #watch(n, lines) {
1053
+ const { clock } = registry();
1054
+ const at = clock.now();
1055
+ const ms = () => Math.round(clock.now() - at);
1056
+ this.#running = { n, at };
1057
+ let stop = () => { };
1058
+ const beat = () => {
1059
+ stop = clock.after(IMPORT_HEARTBEAT_MS, () => {
1060
+ lines.beat({ type: 'beat', n, ms: ms() });
1061
+ beat();
1062
+ });
1063
+ };
1064
+ beat();
1065
+ return {
1066
+ ms,
1067
+ end: () => {
1068
+ stop();
1069
+ this.#running = undefined;
1070
+ },
1071
+ };
1072
+ }
1073
+ /**
1074
+ * The session after statement `n` ran or was refused, and with it where the open transaction
1075
+ * began, and what can still be told of what that transaction holds. `began` says that a
1076
+ * transaction open after `n` began in it: none was open before, or `n` committed that one.
1077
+ */
1078
+ #ran(n, sql, before, after, began) {
1079
+ const plain = STAYS_WITHIN.test(sql);
1080
+ const sets = ONLY_SETS.test(sql);
1081
+ if (!after.inTransaction)
1082
+ this.#since = this.#opened = undefined;
1083
+ else if (began) {
1084
+ this.#since = n;
1085
+ this.#opened = before;
1086
+ // Opened by something that only opens, or by a plain statement, it can be sent again.
1087
+ this.#mixed = !OPENS.test(sql) && !plain;
1088
+ this.#committedSince = this.#mixed && !sets && !COMMITS_FIRST.test(sql);
1089
+ }
1090
+ else if (!plain) {
1091
+ this.#mixed = true;
1092
+ if (!sets)
1093
+ this.#committedSince = true;
1094
+ }
1095
+ this.#session = after;
1096
+ }
1097
+ /**
1098
+ * Statement `n` was refused by the import itself, and never sent (`unsent`): the server changed
1099
+ * nothing. What ran before it is as it was, and a transaction that was open is still open, so
1100
+ * the import waits for a choice, whatever kind of statement it is.
1101
+ */
1102
+ #unsentAt(n, error) {
1103
+ this.#refused.add(n);
1104
+ const state = this.#session.inTransaction ? 'uncommitted' : 'committed';
1105
+ const since = state === 'uncommitted' ? this.#since : undefined;
1106
+ const first = since === undefined ? {} : { since };
1107
+ this.#failure = { n, error, state, ...first, at: registry().clock.now() };
1108
+ return { type: 'failed', n, error, state, done: this.#done, ...first };
1109
+ }
1110
+ /**
1111
+ * Statement `n` was refused. An error says nothing of the transaction it ran in, so the
1112
+ * server is asked, and what it says decides what became of the statements before:
1113
+ * - nothing was sent: the import refused it itself (`unsent`), and the server changed nothing.
1114
+ * They are as they were, and the server isn't asked;
1115
+ * - a transaction is open, after a statement that can't have rolled one back: they ran and are
1116
+ * not committed, or the statement committed them and they are kept. Either way they count,
1117
+ * and the open one is counted from where the one before began. One of a kind that commits
1118
+ * first was only seen to fail and leave one open when the server refused it before its
1119
+ * commit (a syntax error, a collation it doesn't know), on MySQL and on MariaDB: it
1120
+ * committed nothing. Nothing says so, though, and as it may have, nothing from there is
1121
+ * called undone after it (`#committedSince`). Not when its error is one a failed commit is
1122
+ * answered with (`mayBeTheCommit`): that is the next case;
1123
+ * - a transaction is open, after anything else: it may be another than the one that was open.
1124
+ * A procedure can roll back, begin anew and pass its error on, and the server only says
1125
+ * that one is open, not which. They are neither counted nor run again;
1126
+ * - the transaction is gone after a statement that can't have committed it: they are undone,
1127
+ * whatever the error's number, and the import is back before the transaction's first
1128
+ * statement. Unless a statement since that first may have committed on its way: then some
1129
+ * of them may be kept, and it is not known which, as below;
1130
+ * - the transaction is gone after a statement of a kind that commits first: they are kept,
1131
+ * if the error is one known to come after that commit (`cameAfterCommit`). After any other,
1132
+ * that commit may be what failed, and it is the next case;
1133
+ * - the transaction is gone after anything else: the statement may have committed it or rolled
1134
+ * it back, and nothing the server says tells which. The error's number doesn't either: a
1135
+ * procedure can commit and then fail as a deadlock does. They are neither counted nor run
1136
+ * again;
1137
+ * - none was open: each was committed as it ran.
1138
+ *
1139
+ * What was undone is offered to be run again only when that is sure to do what it first did.
1140
+ * Otherwise, and whenever what was kept is not known, the import ends with the failure.
1141
+ */
1142
+ async #refusedAt(n, sql, error, before) {
1143
+ if (error.unsent === true)
1144
+ return this.#unsentAt(n, error);
1145
+ let after;
1146
+ try {
1147
+ after = await this.#importer.state();
1148
+ }
1149
+ catch {
1150
+ this.#unknown = true;
1151
+ // What its connection's end rolls back may have begun within this statement.
1152
+ if (!STAYS_WITHIN.test(sql) && !ONLY_SETS.test(sql))
1153
+ this.#committedSince = true;
1154
+ return this.#stopping ? { type: 'stopped', done: this.#done } : this.#gone(false);
1155
+ }
1156
+ this.#refused.add(n);
1157
+ const since = this.#since;
1158
+ const plain = STAYS_WITHIN.test(sql);
1159
+ const commitsFirst = before.inTransaction && COMMITS_FIRST.test(sql);
1160
+ const gone = before.inTransaction && !after.inTransaction;
1161
+ // Gone after a statement that can't commit is undone, whatever the error's number: the
1162
+ // server rolls back on more of them than say so (a lock table that is full, for one).
1163
+ // After any other statement no number says so: what it names may have come after a commit.
1164
+ // And only what is in the transaction that was open is undone, which may have begun later.
1165
+ const undone = gone && plain && !this.#committedSince;
1166
+ // Open before and open after is the same transaction only if nothing rolled back between:
1167
+ // one that commits first was refused before its commit, unless its error may be a commit's.
1168
+ const swapped = before.inTransaction &&
1169
+ after.inTransaction &&
1170
+ !(plain || (commitsFirst && !mayBeTheCommit(error)) || ONLY_SETS.test(sql));
1171
+ // A rollback is never called kept, and a commit never rolled back: only a statement that
1172
+ // commits before it runs has kept them, and only with an error known to come after that.
1173
+ const kept = gone && commitsFirst && cameAfterCommit(error, this.#importer.target.product);
1174
+ const unknown = swapped || (gone && !undone && !kept);
1175
+ // What a rollback undid can be run again only if it is known what that was, and if it would
1176
+ // be read as it first was: a rollback undoes rows and nothing of the session, so under what
1177
+ // a later statement set these would be other statements, or go into another database.
1178
+ const over = unknown || (undone && (this.#mixed || !sameReading(this.#opened, after)));
1179
+ if (undone || unknown)
1180
+ this.#done = since - 1;
1181
+ // Open before and after, it is the one that was open, from `since` on, whatever the kind.
1182
+ this.#ran(n, sql, before, after, !before.inTransaction);
1183
+ const state = unknown
1184
+ ? 'unknown'
1185
+ : after.inTransaction
1186
+ ? 'uncommitted'
1187
+ : undone
1188
+ ? 'rolled-back'
1189
+ : 'committed';
1190
+ const first = state === 'uncommitted' ? this.#since : undone || unknown ? since : undefined;
1191
+ const at = registry().clock.now();
1192
+ this.#failure = { n, error, state, ...(first === undefined ? {} : { since: first }), at };
1193
+ // Its end rolls back what is open, the transaction a statement left in the other's place too.
1194
+ if (over)
1195
+ void this.end('failed');
1196
+ return {
1197
+ type: 'failed',
1198
+ n,
1199
+ error,
1200
+ state,
1201
+ done: this.#done,
1202
+ ...(first === undefined ? {} : { since: first }),
1203
+ ...(over ? { ended: true } : {}),
1204
+ };
1205
+ }
1206
+ /**
1207
+ * The connection went under the batch: the import is over. `unanswered` says the statement
1208
+ * that ran got no answer, and then the connection's end says whether it is in doubt.
1209
+ */
1210
+ async #gone(unanswered) {
1211
+ this.#lost = true;
1212
+ const how = unanswered
1213
+ ? await this.#importer
1214
+ .end()
1215
+ .catch(() => ({ transaction: 'abandoned', inDoubt: true }))
1216
+ : null;
1217
+ return {
1218
+ type: 'lost',
1219
+ done: this.#done,
1220
+ ...(how?.inDoubt && this.#unanswered !== undefined ? { doubt: this.#unanswered } : {}),
1221
+ };
1222
+ }
1223
+ #log(statement, detail, more = {}) {
1224
+ return this.#record({
1225
+ ...this.#about,
1226
+ action: 'import',
1227
+ statement,
1228
+ durationMs: 0,
1229
+ ...more,
1230
+ import: detail,
1231
+ });
1232
+ }
1233
+ }
1234
+ /**
1235
+ * An error by its numbers alone, as the `mysql` client begins its line, and whether it was sent.
1236
+ * The server's message quotes the statement it refused and the values in it ("near '…'",
1237
+ * "Duplicate entry '…'"), and those are the file's.
1238
+ */
1239
+ function numbersOf({ errno, code, unsent }) {
1240
+ const number = Number.isSafeInteger(errno) ? errno : 0;
1241
+ const state = SQLSTATE.test(code) ? code : NO_SQLSTATE;
1242
+ return {
1243
+ errno: number,
1244
+ code: state,
1245
+ message: `ERROR ${number} (${state})`,
1246
+ ...(unsent === true ? { unsent } : {}),
1247
+ };
1248
+ }
1249
+ /**
1250
+ * Whether the error of a statement that commits first is one this server was seen to give only
1251
+ * after that commit held: on AFTER_COMMIT, or on its own list. Never with a SQLSTATE that says
1252
+ * a transaction was rolled back: no error on the lists has one, so a number that comes with it
1253
+ * is some other error. After any other, that commit may be what failed, and then everything
1254
+ * before the statement is undone.
1255
+ */
1256
+ function cameAfterCommit({ errno, code }, product) {
1257
+ if (code.startsWith(ROLLED_BACK_CLASS))
1258
+ return false;
1259
+ return AFTER_COMMIT.has(errno) || AFTER_COMMIT_ON[product]?.has(errno) === true;
1260
+ }
1261
+ /**
1262
+ * Whether the error is one a failed commit is known to be answered with: its SQLSTATE says a
1263
+ * transaction was rolled back (a server in a cluster refuses a commit that another server's
1264
+ * conflicts with), or it is one of COMMIT_FAILED.
1265
+ */
1266
+ function mayBeTheCommit({ errno, code }) {
1267
+ return code.startsWith(ROLLED_BACK_CLASS) || COMMIT_FAILED.has(errno);
1268
+ }
1269
+ /**
1270
+ * Whether statements split, checked and sent under `then` would be read the same under `now`:
1271
+ * cut where they were, the same of them sent, into the same database.
1272
+ */
1273
+ function sameReading(then, now) {
1274
+ return (then.noBackslashEscapes === now.noBackslashEscapes &&
1275
+ then.ansiQuotes === now.ansiQuotes &&
1276
+ readsAs(then.characterSet) === readsAs(now.characterSet) &&
1277
+ then.database === now.database);
1278
+ }
1279
+ function bad(message) {
1280
+ return new DbAdminError(message, 400, 'bad-request');
1281
+ }
1282
+ //# sourceMappingURL=api.js.map