@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.
- package/README.md +38 -0
- package/dist/backup/api.js +2 -33
- package/dist/backup/api.js.map +1 -1
- package/dist/body.d.ts +17 -0
- package/dist/body.js +88 -0
- package/dist/body.js.map +1 -0
- package/dist/browser.d.ts +1 -0
- package/dist/drivers/mysql-connection.d.ts +101 -0
- package/dist/drivers/mysql-connection.js +204 -0
- package/dist/drivers/mysql-connection.js.map +1 -0
- package/dist/drivers/mysql-import.d.ts +22 -0
- package/dist/drivers/mysql-import.js +688 -0
- package/dist/drivers/mysql-import.js.map +1 -0
- package/dist/drivers/mysql.d.ts +11 -1
- package/dist/drivers/mysql.js +87 -97
- package/dist/drivers/mysql.js.map +1 -1
- package/dist/errors.d.ts +4 -0
- package/dist/errors.js.map +1 -1
- package/dist/handler.d.ts +31 -0
- package/dist/handler.js +93 -9
- package/dist/handler.js.map +1 -1
- package/dist/import/api.d.ts +65 -0
- package/dist/import/api.js +1282 -0
- package/dist/import/api.js.map +1 -0
- package/dist/import/audit.d.ts +47 -0
- package/dist/import/audit.js +434 -0
- package/dist/import/audit.js.map +1 -0
- package/dist/import/charsets.d.ts +25 -0
- package/dist/import/charsets.js +39 -0
- package/dist/import/charsets.js.map +1 -0
- package/dist/import/frames.d.ts +26 -0
- package/dist/import/frames.js +158 -0
- package/dist/import/frames.js.map +1 -0
- package/dist/import/grants.d.ts +26 -0
- package/dist/import/grants.js +122 -0
- package/dist/import/grants.js.map +1 -0
- package/dist/import/protocol.d.ts +462 -0
- package/dist/import/protocol.js +72 -0
- package/dist/import/protocol.js.map +1 -0
- package/dist/import/shared.d.ts +3 -0
- package/dist/import/shared.js +9 -0
- package/dist/import/shared.js.map +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/types.d.ts +308 -2
- package/package.json +7 -2
- package/src/backup/api.ts +2 -33
- package/src/body.ts +94 -0
- package/src/browser.ts +24 -0
- package/src/drivers/mysql-connection.ts +282 -0
- package/src/drivers/mysql-import.ts +769 -0
- package/src/drivers/mysql.ts +96 -107
- package/src/errors.ts +2 -0
- package/src/handler.ts +126 -8
- package/src/import/api.ts +1530 -0
- package/src/import/audit.ts +467 -0
- package/src/import/charsets.ts +46 -0
- package/src/import/frames.ts +191 -0
- package/src/import/grants.ts +117 -0
- package/src/import/protocol.ts +540 -0
- package/src/import/shared.ts +8 -0
- package/src/index.ts +24 -0
- package/src/types.ts +319 -2
package/src/drivers/mysql.ts
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import type { Connection as CallbackConnection } from 'mysql2'
|
|
2
|
-
import type * as MySqlModule from 'mysql2/promise'
|
|
3
2
|
import type {
|
|
4
3
|
ConnectionOptions,
|
|
5
4
|
FieldPacket,
|
|
@@ -8,6 +7,17 @@ import type {
|
|
|
8
7
|
PoolOptions,
|
|
9
8
|
} from 'mysql2/promise'
|
|
10
9
|
import { ConnectionError, DbAdminError, QueryError } from '../errors.ts'
|
|
10
|
+
// What is written in mysql2's types and shared with an import's connection is kept there: this
|
|
11
|
+
// file's exports are the package's, and their declarations must not name mysql2.
|
|
12
|
+
import {
|
|
13
|
+
connectionOptions,
|
|
14
|
+
interrupted,
|
|
15
|
+
isRefusal,
|
|
16
|
+
killQuery,
|
|
17
|
+
loadMySql,
|
|
18
|
+
watchStatement,
|
|
19
|
+
type MySql,
|
|
20
|
+
} from './mysql-connection.ts'
|
|
11
21
|
import { refuseBeyondReadingMysql } from './read-only.ts'
|
|
12
22
|
import type {
|
|
13
23
|
ApplyResult,
|
|
@@ -16,6 +26,7 @@ import type {
|
|
|
16
26
|
Column,
|
|
17
27
|
Driver,
|
|
18
28
|
ExportColumn,
|
|
29
|
+
Importer,
|
|
19
30
|
QueryOptions,
|
|
20
31
|
QueryResult,
|
|
21
32
|
ResultSet,
|
|
@@ -36,28 +47,6 @@ import {
|
|
|
36
47
|
type Dialect,
|
|
37
48
|
} from './sql.ts'
|
|
38
49
|
|
|
39
|
-
type MySql = typeof MySqlModule
|
|
40
|
-
|
|
41
|
-
let module: Promise<MySql> | undefined
|
|
42
|
-
|
|
43
|
-
/** mysql2, imported on the first MySQL connection, so other hosts never load it. */
|
|
44
|
-
function loadMySql(): Promise<MySql> {
|
|
45
|
-
// Imported where the host runs, not bundled (see postgres.ts).
|
|
46
|
-
module ??= import(/* webpackIgnore: true */ /* turbopackIgnore: true */ 'mysql2/promise').then(
|
|
47
|
-
// CommonJS: its exports arrive as the default.
|
|
48
|
-
(m) => (m as unknown as { default?: MySql }).default ?? (m as unknown as MySql),
|
|
49
|
-
(error: unknown) => {
|
|
50
|
-
module = undefined
|
|
51
|
-
throw new DbAdminError(
|
|
52
|
-
`MySQL and MariaDB connections need the mysql2 package: npm install mysql2 (${(error as Error).message})`,
|
|
53
|
-
500,
|
|
54
|
-
'driver-missing',
|
|
55
|
-
)
|
|
56
|
-
},
|
|
57
|
-
)
|
|
58
|
-
return module
|
|
59
|
-
}
|
|
60
|
-
|
|
61
50
|
/** A name in backticks, so any name is taken as a name and never as SQL. */
|
|
62
51
|
export function backtick(identifier: string): string {
|
|
63
52
|
if (typeof identifier !== 'string' || !identifier || identifier.includes('\0')) {
|
|
@@ -77,7 +66,7 @@ export function mysqlLiteral(value: string | null): string {
|
|
|
77
66
|
* it's safe whatever sql_mode says about backslashes; a coercible literal, it takes the column's
|
|
78
67
|
* collation in comparisons.
|
|
79
68
|
*/
|
|
80
|
-
function hexLiteral(value: string | null): string {
|
|
69
|
+
export function hexLiteral(value: string | null): string {
|
|
81
70
|
if (value === null) return 'NULL'
|
|
82
71
|
return value === '' ? "''" : `_utf8mb4 X'${Buffer.from(value, 'utf8').toString('hex')}'`
|
|
83
72
|
}
|
|
@@ -196,26 +185,33 @@ export function mysqlDriver(url: string): Driver {
|
|
|
196
185
|
return new MySqlDriver(url)
|
|
197
186
|
}
|
|
198
187
|
|
|
188
|
+
/** The product and its version, from what VERSION() says: `11.4.2-MariaDB-ubu2404` is MariaDB 11.4.2. */
|
|
189
|
+
export function serverOf(version: string): Pick<ServerInfo, 'product' | 'version'> {
|
|
190
|
+
return {
|
|
191
|
+
product: /mariadb/i.test(version) ? 'MariaDB' : 'MySQL',
|
|
192
|
+
version: /^\d+(\.\d+)*/.exec(version)?.[0] ?? version,
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
199
196
|
class MySqlDriver implements Driver {
|
|
200
197
|
readonly kind = 'mysql'
|
|
201
198
|
readonly capabilities: Capabilities = { schemas: true, transactionalDdl: false, cancel: true }
|
|
202
199
|
readonly sql = sqlDialect
|
|
200
|
+
/** As given: an import's connection takes its own choice of the URL's options. */
|
|
201
|
+
readonly #url: string
|
|
203
202
|
/** One connection's settings: the pool's, and the one that carries KILL QUERY. */
|
|
204
203
|
readonly #single: ConnectionOptions
|
|
205
204
|
readonly #config: PoolOptions
|
|
206
205
|
#pool: Promise<{ pool: Pool; mysql: MySql }> | undefined
|
|
206
|
+
/** The imports whose connections are open: nobody else would end them at `close()`. */
|
|
207
|
+
readonly #importers = new Set<Importer>()
|
|
208
|
+
/** Those still opening: `close()` waits for each, and ends it with the others once it is open. */
|
|
209
|
+
readonly #opening = new Set<Promise<unknown>>()
|
|
210
|
+
#closed = false
|
|
207
211
|
|
|
208
212
|
constructor(url: string) {
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
this.#single = {
|
|
212
|
-
uri: address,
|
|
213
|
-
// One statement a query: `COMMIT; DROP …` is a syntax error.
|
|
214
|
-
multipleStatements: false,
|
|
215
|
-
// Rows matched, not rows changed: an update to the same value still counts its row.
|
|
216
|
-
flags: ['FOUND_ROWS', '-LOCAL_FILES'],
|
|
217
|
-
connectAttributes: { program_name: 'otw-db' },
|
|
218
|
-
}
|
|
213
|
+
this.#url = url
|
|
214
|
+
this.#single = connectionOptions(url)
|
|
219
215
|
this.#config = { ...this.#single, connectionLimit: 3, maxIdle: 3, idleTimeout: 10_000 }
|
|
220
216
|
}
|
|
221
217
|
|
|
@@ -249,32 +245,22 @@ class MySqlDriver implements Driver {
|
|
|
249
245
|
sql: string,
|
|
250
246
|
{ timeoutMs, signal }: { timeoutMs: number; signal?: AbortSignal },
|
|
251
247
|
): Promise<{ rows: (string | null)[][]; fields: FieldPacket[]; affected: number | null }> {
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
void this.#kill(mysql, connection.threadId)
|
|
260
|
-
// KILL QUERY needs a connection of its own, which a server at its limit refuses, and some
|
|
261
|
-
// proxies never pass it on: the statement would run on, and the request wait with it.
|
|
262
|
-
// Closing its connection ends the wait whatever the server does.
|
|
263
|
-
giveUp = setTimeout(() => {
|
|
264
|
-
connection.destroy()
|
|
265
|
-
abandon(interrupted(why, timeoutMs))
|
|
266
|
-
}, KILL_GRACE_MS)
|
|
267
|
-
}
|
|
268
|
-
const timer = setTimeout(() => stop('timeout'), timeoutMs)
|
|
269
|
-
const abort = () => stop('cancel')
|
|
270
|
-
signal?.addEventListener('abort', abort, { once: true })
|
|
248
|
+
// Refused here, with nothing sent, if `signal` has already aborted.
|
|
249
|
+
const watch = watchStatement(connection, {
|
|
250
|
+
timeoutMs,
|
|
251
|
+
graceMs: KILL_GRACE_MS,
|
|
252
|
+
kill: (threadId) => killQuery(mysql, this.#single, threadId),
|
|
253
|
+
...(signal ? { signal } : {}),
|
|
254
|
+
})
|
|
271
255
|
try {
|
|
272
|
-
if (signal?.aborted) throw new DbAdminError('The query was canceled.', 409, 'canceled')
|
|
273
256
|
const running = connection.query({ sql, rowsAsArray: true, typeCast: asBytes })
|
|
274
257
|
// Abandoned, it fails later with its connection gone: nobody is left to hear that.
|
|
275
258
|
running.catch(() => {})
|
|
259
|
+
const abandoned = watch.abandoned.then((why) => {
|
|
260
|
+
throw interrupted(why, timeoutMs)
|
|
261
|
+
})
|
|
276
262
|
const [result, fields] = await Promise.race([running, abandoned])
|
|
277
|
-
if (stopped) throw interrupted(stopped, timeoutMs)
|
|
263
|
+
if (watch.stopped) throw interrupted(watch.stopped, timeoutMs)
|
|
278
264
|
if (!Array.isArray(result)) {
|
|
279
265
|
return { rows: [], fields: [], affected: (result as { affectedRows: number }).affectedRows }
|
|
280
266
|
}
|
|
@@ -285,38 +271,17 @@ class MySqlDriver implements Driver {
|
|
|
285
271
|
affected: null,
|
|
286
272
|
}
|
|
287
273
|
} catch (error) {
|
|
288
|
-
if (stopped && !(error instanceof DbAdminError))
|
|
274
|
+
if (watch.stopped && !(error instanceof DbAdminError)) {
|
|
275
|
+
throw interrupted(watch.stopped, timeoutMs)
|
|
276
|
+
}
|
|
289
277
|
throw error
|
|
290
278
|
} finally {
|
|
291
|
-
|
|
292
|
-
clearTimeout(giveUp)
|
|
293
|
-
signal?.removeEventListener('abort', abort)
|
|
294
|
-
}
|
|
295
|
-
}
|
|
296
|
-
|
|
297
|
-
/** KILL QUERY on a connection of its own: the busy one can't take it. You may kill your own. */
|
|
298
|
-
async #kill(mysql: MySql, threadId: number): Promise<void> {
|
|
299
|
-
try {
|
|
300
|
-
const killer = await mysql.createConnection(this.#single)
|
|
301
|
-
try {
|
|
302
|
-
await killer.query(`KILL QUERY ${whole(threadId)}`)
|
|
303
|
-
} finally {
|
|
304
|
-
await killer.end()
|
|
305
|
-
}
|
|
306
|
-
} catch (error) {
|
|
307
|
-
console.error('otw-db: could not stop a MySQL query', error)
|
|
279
|
+
watch.end()
|
|
308
280
|
}
|
|
309
281
|
}
|
|
310
282
|
|
|
311
283
|
async #catalog(sql: string): Promise<(string | null)[][]> {
|
|
312
|
-
|
|
313
|
-
try {
|
|
314
|
-
return (await this.#run(connection, mysql, sql, { timeoutMs: 30_000 })).rows
|
|
315
|
-
} catch (error) {
|
|
316
|
-
throw toError(error)
|
|
317
|
-
} finally {
|
|
318
|
-
connection.release()
|
|
319
|
-
}
|
|
284
|
+
return (await this.#pooled(sql, { timeoutMs: 30_000 })).rows
|
|
320
285
|
}
|
|
321
286
|
|
|
322
287
|
async tables(): Promise<TableSummary[]> {
|
|
@@ -481,12 +446,7 @@ class MySqlDriver implements Driver {
|
|
|
481
446
|
const [[version, database, user]] = (await this.#catalog(
|
|
482
447
|
'SELECT VERSION(), DATABASE(), CURRENT_USER()',
|
|
483
448
|
)) as [[string, string | null, string]]
|
|
484
|
-
return {
|
|
485
|
-
product: /mariadb/i.test(version) ? 'MariaDB' : 'MySQL',
|
|
486
|
-
version: /^\d+(\.\d+)*/.exec(version)?.[0] ?? version,
|
|
487
|
-
database: database ?? '',
|
|
488
|
-
user,
|
|
489
|
-
}
|
|
449
|
+
return { ...serverOf(version), database: database ?? '', user }
|
|
490
450
|
}
|
|
491
451
|
|
|
492
452
|
/**
|
|
@@ -587,7 +547,7 @@ class MySqlDriver implements Driver {
|
|
|
587
547
|
() => {
|
|
588
548
|
if (!listening || silent || performance.now() - heard <= timeoutMs) return
|
|
589
549
|
silent = true
|
|
590
|
-
void
|
|
550
|
+
void killQuery(mysql, this.#single, connection.threadId)
|
|
591
551
|
// Where KILL QUERY can't reach it, its connection goes instead.
|
|
592
552
|
setTimeout(() => connection.destroy(), KILL_GRACE_MS).unref()
|
|
593
553
|
},
|
|
@@ -628,10 +588,50 @@ class MySqlDriver implements Driver {
|
|
|
628
588
|
}
|
|
629
589
|
}
|
|
630
590
|
|
|
591
|
+
/**
|
|
592
|
+
* A connection for one import, open until its `end()`, or this driver's `close()`. The code
|
|
593
|
+
* for it is loaded with the first.
|
|
594
|
+
*/
|
|
595
|
+
importer(options: { idleMs?: number } = {}): Promise<Importer> {
|
|
596
|
+
const opening = this.#import(options)
|
|
597
|
+
// What it fails of is its caller's to hear; `close()` only waits for it to be over.
|
|
598
|
+
const over: Promise<unknown> = opening.catch(() => {}).finally(() => this.#opening.delete(over))
|
|
599
|
+
this.#opening.add(over)
|
|
600
|
+
return opening
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
async #import(options: { idleMs?: number }): Promise<Importer> {
|
|
604
|
+
this.#refuseClosed()
|
|
605
|
+
const mysql = await loadMySql()
|
|
606
|
+
const { openImporter } = await import('./mysql-import.ts')
|
|
607
|
+
// Forgotten when its connection has gone, which it may before it has opened.
|
|
608
|
+
const open: { importer?: Importer } = {}
|
|
609
|
+
const forget = () => void (open.importer && this.#importers.delete(open.importer))
|
|
610
|
+
const importer = await openImporter(mysql, this.#url, { ...options, closed: forget })
|
|
611
|
+
open.importer = importer
|
|
612
|
+
this.#importers.add(importer)
|
|
613
|
+
// Closed while this one opened: `close()` is waiting for it, and ends it with the others.
|
|
614
|
+
this.#refuseClosed()
|
|
615
|
+
return importer
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
/** An import holds its connection for as long as it likes: none opens on a driver let go. */
|
|
619
|
+
#refuseClosed(): void {
|
|
620
|
+
if (this.#closed) throw new ConnectionError('This connection to MySQL was closed. Try again.')
|
|
621
|
+
}
|
|
622
|
+
|
|
631
623
|
async close(): Promise<void> {
|
|
624
|
+
this.#closed = true
|
|
632
625
|
const opened = this.#pool
|
|
633
626
|
this.#pool = undefined
|
|
634
|
-
|
|
627
|
+
try {
|
|
628
|
+
// One that is still opening has a connection nobody here knows of yet: it is waited
|
|
629
|
+
// for, and ended with the others. Until then this driver is not closed.
|
|
630
|
+
await Promise.all([...this.#opening])
|
|
631
|
+
await Promise.all([...this.#importers].map((importer) => importer.end()))
|
|
632
|
+
} finally {
|
|
633
|
+
if (opened) await (await opened).pool.end()
|
|
634
|
+
}
|
|
635
635
|
}
|
|
636
636
|
}
|
|
637
637
|
|
|
@@ -695,25 +695,14 @@ function stripComments(sql: string): string {
|
|
|
695
695
|
return sql.replace(/^(\s|--[^\n]*\n|\/\*[\s\S]*?\*\/|#[^\n]*\n)*/, '')
|
|
696
696
|
}
|
|
697
697
|
|
|
698
|
-
function interrupted(why: 'timeout' | 'cancel', timeoutMs: number): DbAdminError {
|
|
699
|
-
return why === 'cancel'
|
|
700
|
-
? new DbAdminError('The query was canceled.', 409, 'canceled')
|
|
701
|
-
: new QueryError(`The statement ran past its ${timeoutMs} ms limit and was stopped.`, '70100')
|
|
702
|
-
}
|
|
703
|
-
|
|
704
698
|
/** mysql2's errors as the API's: the server's refusals are the statement's, the rest the connection's. */
|
|
705
|
-
function toError(error: unknown): Error {
|
|
699
|
+
export function toError(error: unknown): Error {
|
|
706
700
|
if (error instanceof DbAdminError) return error
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
errno?: number
|
|
712
|
-
fatal?: boolean
|
|
713
|
-
}
|
|
714
|
-
if (e?.sqlMessage && !e.fatal) {
|
|
715
|
-
const code = e.errno === INTERRUPTED ? '70100' : e.sqlState
|
|
716
|
-
return new QueryError(e.sqlMessage, code)
|
|
701
|
+
if (isRefusal(error)) {
|
|
702
|
+
const { sqlMessage, sqlState, errno } = error
|
|
703
|
+
const code = errno === INTERRUPTED ? '70100' : sqlState
|
|
704
|
+
return new QueryError(sqlMessage, code, Number.isInteger(errno) ? { errno } : {})
|
|
717
705
|
}
|
|
718
|
-
|
|
706
|
+
const message = (error as { message?: string } | null)?.message
|
|
707
|
+
return new ConnectionError(`The MySQL connection failed: ${message ?? String(error)}`)
|
|
719
708
|
}
|
package/src/errors.ts
CHANGED
|
@@ -22,6 +22,8 @@ export class QueryError extends DbAdminError {
|
|
|
22
22
|
position?: number
|
|
23
23
|
detail?: string
|
|
24
24
|
hint?: string
|
|
25
|
+
/** The server's own number for the error, such as MySQL's 1064 for a syntax error. */
|
|
26
|
+
errno?: number
|
|
25
27
|
} = {},
|
|
26
28
|
) {
|
|
27
29
|
super(message, 400, 'query-failed')
|
package/src/handler.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { readText } from './body.ts'
|
|
1
2
|
import { driverKind } from './connections.ts'
|
|
2
3
|
import { openDriver } from './drivers/index.ts'
|
|
3
4
|
import { DbAdminError, QueryError } from './errors.ts'
|
|
@@ -17,6 +18,7 @@ import type {
|
|
|
17
18
|
} from './types.ts'
|
|
18
19
|
import { ROUTES } from './routes.ts'
|
|
19
20
|
import type * as BackupApi from './backup/api.ts'
|
|
21
|
+
import type * as ImportApi from './import/api.ts'
|
|
20
22
|
import { renderAsset, renderIndex, type UiAssets } from './ui.ts'
|
|
21
23
|
|
|
22
24
|
/** What `createDbAdmin` needs: who may use the tool, the databases it may open, its limits. */
|
|
@@ -53,6 +55,37 @@ export interface DbAdminOptions {
|
|
|
53
55
|
/** The biggest backup a restore takes, in bytes. Defaults to 1 GiB. */
|
|
54
56
|
maxRestoreBytes?: number
|
|
55
57
|
}
|
|
58
|
+
/**
|
|
59
|
+
* Imports of SQL files (MySQL and MariaDB). The browser reads the file and sends its statements
|
|
60
|
+
* in batches; the server keeps one connection open for each import, and of the file only the
|
|
61
|
+
* batch that is running.
|
|
62
|
+
*
|
|
63
|
+
* The audit log has the file's statements, though, logged before each batch runs: a
|
|
64
|
+
* `CREATE USER` with its password, the `GRANT`s, the short `INSERT`s with their rows. Only a
|
|
65
|
+
* long `INSERT` or `REPLACE` of nothing but rows of plain values is shortened (see
|
|
66
|
+
* `AuditEvent.statement`). By default that log is the server's own output; `audit` sends it
|
|
67
|
+
* elsewhere, or turns it off.
|
|
68
|
+
*/
|
|
69
|
+
imports?: {
|
|
70
|
+
/** How long one statement of a file may run, in milliseconds. Defaults to 30 minutes. */
|
|
71
|
+
statementTimeoutMs?: number
|
|
72
|
+
/**
|
|
73
|
+
* How long an import stays open with no request for it, in milliseconds, before it is
|
|
74
|
+
* stopped, rolled back and closed: its browser has gone. Defaults to 5 minutes.
|
|
75
|
+
*/
|
|
76
|
+
idleMs?: number
|
|
77
|
+
/**
|
|
78
|
+
* How long the person has to choose after a statement fails (try again, skip, stop), in
|
|
79
|
+
* milliseconds, before the import is closed: its connection may hold locks on a live
|
|
80
|
+
* database. Defaults to 2 minutes.
|
|
81
|
+
*/
|
|
82
|
+
pauseMs?: number
|
|
83
|
+
/**
|
|
84
|
+
* Imports open at once on one connection, all viewers together; each viewer has one at most.
|
|
85
|
+
* Defaults to 2.
|
|
86
|
+
*/
|
|
87
|
+
perDriver?: number
|
|
88
|
+
}
|
|
56
89
|
}
|
|
57
90
|
|
|
58
91
|
/**
|
|
@@ -112,6 +145,15 @@ const OPERATORS: ReadonlySet<string> = new Set<FilterOperator>([
|
|
|
112
145
|
'starts with',
|
|
113
146
|
'ends with',
|
|
114
147
|
])
|
|
148
|
+
/** An import's limits when the options set none. */
|
|
149
|
+
const IMPORT_DEFAULTS: ImportApi.ImportSettings = {
|
|
150
|
+
statementTimeoutMs: 1_800_000,
|
|
151
|
+
idleMs: 300_000,
|
|
152
|
+
pauseMs: 120_000,
|
|
153
|
+
perDriver: 2,
|
|
154
|
+
}
|
|
155
|
+
/** The longest a timer waits, in milliseconds: no limit of an import is longer. */
|
|
156
|
+
const LONGEST_MS = 2_147_483_647
|
|
115
157
|
/** Sent by the browser app on every call; a form on another site can't send it. */
|
|
116
158
|
export const CSRF_HEADER = 'x-db-admin'
|
|
117
159
|
|
|
@@ -154,6 +196,21 @@ export function createDbAdmin(options: DbAdminOptions): DbAdmin {
|
|
|
154
196
|
record,
|
|
155
197
|
maxRestoreBytes,
|
|
156
198
|
})
|
|
199
|
+
// Loaded on the first request about an import, and never by a host that imports nothing.
|
|
200
|
+
let importApi: Promise<typeof ImportApi> | undefined
|
|
201
|
+
const imports = () => (importApi ??= import('./import/api.ts'))
|
|
202
|
+
const importSettings = importSettingsOf(options.imports)
|
|
203
|
+
/** Names this createDbAdmin among the others of the process: its `close()` ends its own imports. */
|
|
204
|
+
const owner = {}
|
|
205
|
+
/** What an import endpoint needs to know. An import names its own database, so none is reached. */
|
|
206
|
+
const importContext = async (viewer: Viewer, connection: unknown) => ({
|
|
207
|
+
...(await reach(viewer, connection)),
|
|
208
|
+
viewer,
|
|
209
|
+
record,
|
|
210
|
+
settings: importSettings,
|
|
211
|
+
timeoutMs: limits.timeoutMs,
|
|
212
|
+
owner,
|
|
213
|
+
})
|
|
157
214
|
|
|
158
215
|
function driver(connection: ConnectionConfig): Driver {
|
|
159
216
|
let found = drivers.get(connection.name)
|
|
@@ -267,6 +324,7 @@ export function createDbAdmin(options: DbAdminOptions): DbAdmin {
|
|
|
267
324
|
...opened.capabilities,
|
|
268
325
|
databases: opensOthers(connection),
|
|
269
326
|
backup: typeof opened.session === 'function',
|
|
327
|
+
import: typeof opened.importer === 'function',
|
|
270
328
|
}
|
|
271
329
|
} catch (error) {
|
|
272
330
|
if (!(error instanceof DbAdminError)) throw error
|
|
@@ -600,6 +658,54 @@ export function createDbAdmin(options: DbAdminOptions): DbAdmin {
|
|
|
600
658
|
return (await backups()).chunk(backupContext(target, viewer), request)
|
|
601
659
|
},
|
|
602
660
|
},
|
|
661
|
+
{
|
|
662
|
+
method: 'GET',
|
|
663
|
+
path: '/api/import-options',
|
|
664
|
+
async run(request, viewer) {
|
|
665
|
+
const params = new URL(request.url).searchParams
|
|
666
|
+
const context = await importContext(viewer, params.get('connection'))
|
|
667
|
+
return (await imports()).options(context)
|
|
668
|
+
},
|
|
669
|
+
},
|
|
670
|
+
{
|
|
671
|
+
method: 'GET',
|
|
672
|
+
path: '/api/import-status',
|
|
673
|
+
async run(request, viewer) {
|
|
674
|
+
const params = new URL(request.url).searchParams
|
|
675
|
+
const context = await importContext(viewer, params.get('connection'))
|
|
676
|
+
return (await imports()).status(context, params.get('import'))
|
|
677
|
+
},
|
|
678
|
+
},
|
|
679
|
+
{
|
|
680
|
+
method: 'POST',
|
|
681
|
+
path: '/api/import-start',
|
|
682
|
+
async run(request, viewer) {
|
|
683
|
+
const body = await json(request)
|
|
684
|
+
const context = await importContext(viewer, body.connection)
|
|
685
|
+
// With the request's signal: an import nobody is left to hear of is ended as it opens.
|
|
686
|
+
return (await imports()).start(context, body, request.signal)
|
|
687
|
+
},
|
|
688
|
+
},
|
|
689
|
+
{
|
|
690
|
+
method: 'POST',
|
|
691
|
+
path: '/api/import-end',
|
|
692
|
+
async run(request, viewer) {
|
|
693
|
+
const body = await json(request)
|
|
694
|
+
const context = await importContext(viewer, body.connection)
|
|
695
|
+
return (await imports()).end(context, body)
|
|
696
|
+
},
|
|
697
|
+
},
|
|
698
|
+
{
|
|
699
|
+
method: 'POST',
|
|
700
|
+
path: '/api/import-run',
|
|
701
|
+
async run(request, viewer) {
|
|
702
|
+
// The body is the batch, and is read only once the import has been found free for it:
|
|
703
|
+
// which import and which statements comes in the address.
|
|
704
|
+
const params = new URL(request.url).searchParams
|
|
705
|
+
const context = await importContext(viewer, params.get('connection'))
|
|
706
|
+
return (await imports()).run(context, request)
|
|
707
|
+
},
|
|
708
|
+
},
|
|
603
709
|
{
|
|
604
710
|
method: 'POST',
|
|
605
711
|
path: '/api/cancel',
|
|
@@ -698,6 +804,9 @@ export function createDbAdmin(options: DbAdminOptions): DbAdmin {
|
|
|
698
804
|
return reply(404, { error: { code: 'not-found', message: 'Not found.' } })
|
|
699
805
|
},
|
|
700
806
|
async close() {
|
|
807
|
+
// Its imports first: each is stopped, rolled back and logged as closed. A driver closed
|
|
808
|
+
// under one would cut its connection with none of that.
|
|
809
|
+
if (importApi) await (await importApi).close(owner)
|
|
701
810
|
const open = [...drivers.values(), ...[...others.values()].flatMap((o) => [...o.values()])]
|
|
702
811
|
drivers.clear()
|
|
703
812
|
others.clear()
|
|
@@ -734,6 +843,22 @@ async function defaultUi(): Promise<UiAssets> {
|
|
|
734
843
|
return assets
|
|
735
844
|
}
|
|
736
845
|
|
|
846
|
+
/** The host's settings for imports, with the defaults for those it leaves out. */
|
|
847
|
+
function importSettingsOf(given: DbAdminOptions['imports'] = {}): ImportApi.ImportSettings {
|
|
848
|
+
const settings = { ...IMPORT_DEFAULTS }
|
|
849
|
+
for (const name of Object.keys(IMPORT_DEFAULTS) as (keyof ImportApi.ImportSettings)[]) {
|
|
850
|
+
const value = given[name]
|
|
851
|
+
if (value === undefined) continue
|
|
852
|
+
if (!Number.isSafeInteger(value) || value < 1 || value > LONGEST_MS) {
|
|
853
|
+
throw new Error(
|
|
854
|
+
`imports.${name} is a whole number from 1 to ${LONGEST_MS}, not ${String(value)}.`,
|
|
855
|
+
)
|
|
856
|
+
}
|
|
857
|
+
settings[name] = value
|
|
858
|
+
}
|
|
859
|
+
return settings
|
|
860
|
+
}
|
|
861
|
+
|
|
737
862
|
function oneDatabase(connection: ConnectionConfig): DbAdminError {
|
|
738
863
|
return new DbAdminError(
|
|
739
864
|
`Connection "${connection.name}" opens its own database only.`,
|
|
@@ -803,10 +928,7 @@ async function json(request: Request): Promise<Record<string, unknown>> {
|
|
|
803
928
|
'unsupported-media-type',
|
|
804
929
|
)
|
|
805
930
|
}
|
|
806
|
-
const
|
|
807
|
-
if (length > MAX_BODY) throw tooLarge()
|
|
808
|
-
const body = await request.text()
|
|
809
|
-
if (body.length > MAX_BODY) throw tooLarge()
|
|
931
|
+
const body = await readText(request, MAX_BODY, 'The request')
|
|
810
932
|
let parsed: unknown
|
|
811
933
|
try {
|
|
812
934
|
parsed = JSON.parse(body)
|
|
@@ -819,10 +941,6 @@ async function json(request: Request): Promise<Record<string, unknown>> {
|
|
|
819
941
|
return parsed as Record<string, unknown>
|
|
820
942
|
}
|
|
821
943
|
|
|
822
|
-
function tooLarge() {
|
|
823
|
-
return new DbAdminError('The request is larger than 1 MB.', 413, 'too-large')
|
|
824
|
-
}
|
|
825
|
-
|
|
826
944
|
function text(value: unknown, field: string): string {
|
|
827
945
|
if (typeof value !== 'string' || !value) {
|
|
828
946
|
throw new DbAdminError(`"${field}" is required.`, 400, 'bad-request')
|