@powersync/service-jpgwire 0.21.26 → 0.21.28

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.
@@ -0,0 +1,2681 @@
1
+ /* Copyright (c) 2026 exe-dealer@yandex.kz
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be included
12
+ in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
17
+ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
18
+ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
19
+ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
20
+ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21
+ */
22
+ /** @deprecated */
23
+ export async function pgconnect(...optionsChain) {
24
+ const conn = pgconnection(...optionsChain);
25
+ await conn.query();
26
+ return conn;
27
+ }
28
+ // https://github.com/kagis/pgwire/issues/15
29
+ export function pgconnection(...optionsChain) {
30
+ return new PgConnection(computeConnectionOptions(optionsChain));
31
+ }
32
+ export function pgpool(...optionsChain) {
33
+ return new PgPool(computeConnectionOptions(optionsChain));
34
+ }
35
+ export function pgliteral(s) {
36
+ if (s == null)
37
+ return 'NULL';
38
+ // TODO array
39
+ return `'` + String(s).replace(/'/g, `''`) + `'`;
40
+ }
41
+ export function pgident(...segments) {
42
+ return segments.map(it => '"' + it.replace(/"/g, '""') + '"').join('.');
43
+ }
44
+ // TODO avoid class export
45
+ export class PgError extends Error {
46
+ constructor(errorResponse) {
47
+ super(errorResponse.message, { cause: errorResponse });
48
+ this.name = 'PgError.' + errorResponse.code;
49
+ Object.defineProperty(this, 'name', { enumerable: false });
50
+ }
51
+ }
52
+ function computeConnectionOptions(optionsChain) {
53
+ return optionsChain.reduceRight(reduceConnectionOptions, {
54
+ host: '127.0.0.1',
55
+ port: '5432',
56
+ });
57
+ }
58
+ function reduceConnectionOptions(result, uriOrObj) {
59
+ if (typeof uriOrObj == 'string') {
60
+ uriOrObj = new URL(uriOrObj);
61
+ }
62
+ if (uriOrObj instanceof URL) {
63
+ uriOrObj = {
64
+ host: decodeURIComponent(uriOrObj.hostname) || undefined,
65
+ port: uriOrObj.port || undefined,
66
+ password: decodeURIComponent(uriOrObj.password) || undefined,
67
+ 'user': decodeURIComponent(uriOrObj.username) || undefined,
68
+ 'database': decodeURIComponent(uriOrObj.pathname).replace(/^[/]/, '') || undefined,
69
+ ...Object.fromEntries(uriOrObj.searchParams)
70
+ };
71
+ }
72
+ for (const [k, v] of Object.entries(uriOrObj)) {
73
+ if (v === undefined)
74
+ continue;
75
+ result[k] = v;
76
+ }
77
+ return result;
78
+ }
79
+ class PgPool {
80
+ // TODO? .pending, .queryable
81
+ constructor(options) {
82
+ /** @type {Set<PgConnection>} */
83
+ this._connections = new Set();
84
+ this._endReason = null;
85
+ this._options = { ...options, _noExplicitTransactions: true };
86
+ this._poolSize = Math.max(options._poolSize, 0);
87
+ // postgres v14 has `idle_session_timeout` option.
88
+ // But if .query will be called when socket is closed by server
89
+ // (but Connection is not yet deleted from pool)
90
+ // then query will be rejected with error.
91
+ // We should be ready to repeat query in this case
92
+ // and this is more difficult to implement than client side timeout
93
+ this._poolIdleTimeout = Math.max(millis(options._poolIdleTimeout), 0);
94
+ }
95
+ query(...args) {
96
+ return PgResult.fromStream(this.stream(...args));
97
+ }
98
+ async *stream(...args) {
99
+ if (this._endReason) {
100
+ throw Error('postgres query late', { cause: this._endReason });
101
+ }
102
+ const conn = this._getConnection();
103
+ try {
104
+ yield* conn.stream(...args);
105
+ }
106
+ finally {
107
+ await this._recycleConnection(conn);
108
+ }
109
+ }
110
+ async end() {
111
+ this._endReason ||= Error('postgres pool ended');
112
+ await Promise.all(Array.from(this._connections, conn => conn.end()));
113
+ }
114
+ async [Symbol.asyncDispose]() {
115
+ await this.end();
116
+ }
117
+ destroy(cause) {
118
+ this._endReason ||= Error('postgres pool destroyed', { cause });
119
+ this._connections.forEach(it => it.destroy(cause));
120
+ }
121
+ [Symbol.dispose]() {
122
+ this.destroy();
123
+ }
124
+ _getConnection() {
125
+ // try to reuse connection
126
+ if (this._poolSize > 0) {
127
+ const queryableConns = Array.from(this._connections).filter(conn => conn.queryable);
128
+ const full = queryableConns.length >= this._poolSize;
129
+ const [leastBusyConn] = queryableConns.sort((a, b) => a.pending - b.pending);
130
+ if (leastBusyConn?.pending == 0 || full) {
131
+ clearTimeout(leastBusyConn._poolTimeoutId);
132
+ return leastBusyConn;
133
+ }
134
+ }
135
+ const newConn = new PgConnection(this._options);
136
+ newConn._poolTimeoutId = null; // TODO check whether it disables v8 hidden class optimization
137
+ this._connections.add(newConn);
138
+ newConn.whenDestroyed.then(this._onConnectionDestroyed.bind(this, newConn));
139
+ return newConn;
140
+ }
141
+ async _recycleConnection(conn) {
142
+ if (!(this._poolSize > 0)) {
143
+ // TODO not wait
144
+ // but pgbouncer does not allow async Terminate anyway.
145
+ // May be other poolers do
146
+ await conn.end();
147
+ return;
148
+ }
149
+ if (this._poolIdleTimeout && conn.queryable && !conn.pending /* is idle */) {
150
+ conn._poolTimeoutId = setTimeout(this._onConnectionTimeout, this._poolIdleTimeout, this, conn);
151
+ }
152
+ }
153
+ _onConnectionTimeout(_self, conn) {
154
+ conn.end();
155
+ // TODO conn.destroy() if .end() stuck?
156
+ }
157
+ _onConnectionDestroyed(conn) {
158
+ clearTimeout(conn._poolTimeoutId);
159
+ this._connections.delete(conn);
160
+ }
161
+ }
162
+ class PgConnection {
163
+ constructor({ host, // https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNECT-HOST
164
+ port, // https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNECT-PORT
165
+ password, // https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNECT-PASSWORD
166
+ keepalives = '1', // https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-KEEPALIVES
167
+ sslmode, // https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNECT-SSLMODE
168
+ sslrootcert, // TODO accept filename as psql do
169
+ _connectRetry = 0, // TODO connect_timeout
170
+ _wakeInterval = 2000, _noExplicitTransactions = false, _maxReadBuf = 50 << 20, // 50 MiB
171
+ _debug = false, ...options }) {
172
+ this.onnotification = null;
173
+ this.parameters = Object.create(null);
174
+ this._debug = /^(true|on|yes|1)$/i.test(_debug);
175
+ this._socketOptions = {
176
+ host,
177
+ port: Number(port),
178
+ keepAlive: /^(true|on|yes|1)$/i.test(keepalives),
179
+ // TODO windows support
180
+ // https://github.com/postgres/postgres/blob/c37267162e889fe783786b9e28d1b65b82365a00/src/include/libpq/pqcomm.h#L67
181
+ path: /^[/]/.test(host) && host.replace(/[/]*$/g, '/.s.PGSQL.' + port),
182
+ };
183
+ this._user = options.user;
184
+ this._password = password || '';
185
+ this._sslmode = sslmode;
186
+ this._sslrootcert = sslrootcert;
187
+ this._ssl = false;
188
+ // TODO ioloop starts not now
189
+ this._connectDeadline = performance.now() + (Math.max(millis(_connectRetry), 0) || NaN);
190
+ this._socket = null;
191
+ this._backendKeyData = null;
192
+ this._lastErrorResponse = null;
193
+ this._queuedResponseChannels = [];
194
+ /** @type {'start'|'idle'|'responding'|'end'} */
195
+ this._readyState = 'start';
196
+ this._transactionStatus = -1;
197
+ this._wakeSupress = true;
198
+ this._wakeInterval = Math.max(millis(_wakeInterval), 0);
199
+ this._wakeTimer = null;
200
+ this._maxReadBuf = _maxReadBuf;
201
+ this._rowProto = null;
202
+ this._rowTextDecoder = new TextDecoder('utf-8', { fatal: true });
203
+ this._copyingOut = false;
204
+ this._femsgw = null;
205
+ this._femsgq = new Channel();
206
+ this._endReason = null;
207
+ this._sasl = null;
208
+ this._noExplicitTransactions = _noExplicitTransactions;
209
+ // create StartupMessage here to validate options in constructor call stack
210
+ this._startupmsg = new FrontendMessage.StartupMessage({
211
+ // Underscored props are used for client only,
212
+ // Underscore prefix is not supported by postgres anyway
213
+ // https://github.com/postgres/postgres/blob/REL_14_2/src/backend/utils/misc/guc.c#L5398
214
+ ...Object.fromEntries(Object.entries(options)
215
+ .filter(([k]) => !k.startsWith('_'))),
216
+ 'client_encoding': 'UTF8', // TextEncoder supports UTF8 only, so hardcode and force UTF8
217
+ });
218
+ this._pipeFemsgqPromise = null;
219
+ this._ioloopPromise = null;
220
+ }
221
+ get whenDestroyed() {
222
+ return this._femsgq._whenEnded.then(_ => this._ioloopPromise);
223
+ }
224
+ /** Number of pending queries. */
225
+ get pending() {
226
+ return this._queuedResponseChannels.length;
227
+ }
228
+ get queryable() {
229
+ return !this._endReason;
230
+ }
231
+ /** ID of postgres backend process. */
232
+ get pid() {
233
+ if (!this._backendKeyData)
234
+ return null;
235
+ return this._backendKeyData.pid;
236
+ }
237
+ get ssl() {
238
+ return this._ssl;
239
+ }
240
+ /** Truthy if connection is idle in transaction. */
241
+ get inTransaction() {
242
+ const s = this._transactionStatus;
243
+ return this._readyState == 'idle' && s != 0x49 ? s : 0;
244
+ }
245
+ // TODO executemany?
246
+ // Parse
247
+ // Describe(portal)
248
+ // Bind
249
+ // Execute
250
+ // Bind
251
+ // Execute
252
+ query(...args) {
253
+ return PgResult.fromStream(this.stream(...args));
254
+ }
255
+ async *stream(...args) {
256
+ if (this._endReason) {
257
+ throw Error('postgres query late', this._endReason);
258
+ }
259
+ // TODO test .query after .end should throw stable error ? what if auth failed after .end
260
+ const stdinAborter = new AbortController();
261
+ const responseEndLock = new Channel();
262
+ const responseChannel = new Channel();
263
+ // Collect outgoing messages into intermediate array
264
+ // to let errors occur before any message enqueued.
265
+ const frontendMessages = [];
266
+ // To cancel query we should send CancelRequest _after_ query is received
267
+ // by server and started executing. We going to prepend query with Sync
268
+ // message to detect response start boundary by receiving ReadyForQuery.
269
+ // ReadyForQuery is flushed immediatly after Sync is handled by server
270
+ // so we can know when query is started and can be cancelled.
271
+ // Also it makes possible to determine whether NoticeResponse/ErrorResponse
272
+ // is asyncronous server message or belongs to query.
273
+ // Seems that its ok to do Sync during simple protocol even when replication=database.
274
+ // TODO Maybe there is a small window between first ReadyForQuery and actual
275
+ // query execution, when async messages can be received. Need more source digging
276
+ frontendMessages.push(new FrontendMessage.Sync());
277
+ let signal;
278
+ if (typeof args[0] == 'string') {
279
+ const [simpleSql, simpleOptions] = args;
280
+ signal = simpleOptions?.signal;
281
+ simpleQuery(frontendMessages, stdinAborter.signal, simpleSql, simpleOptions, responseEndLock);
282
+ }
283
+ else {
284
+ signal = extendedQuery(frontendMessages, stdinAborter.signal, args);
285
+ }
286
+ // this._throwIfQueryAborted(signal);
287
+ const onabort = this._wake.bind(this);
288
+ // TODO if next two steps throw error then abort handler will not be removed.
289
+ signal?.addEventListener('abort', onabort);
290
+ // TODO This two steps should be executed atomiсally.
291
+ // If one fails then connection instance
292
+ // will be desyncronized and should be destroyed.
293
+ // But I see no cases when this can throw error.
294
+ frontendMessages.forEach(this._femsgq.push, this._femsgq);
295
+ this._queuedResponseChannels.push(responseChannel);
296
+ this._ioloopPromise ||= this._ioloop();
297
+ try {
298
+ let value, done, errorResponse;
299
+ for (;;) {
300
+ // Important to call responseChannel.next() as first step of try block
301
+ // to maximize chance that finally block will be executed after
302
+ // query is received by server. So CancelRequest will be emited
303
+ // in case of error, and skip-waiting duration will be minimized.
304
+ ({ value, done } = await responseChannel.next());
305
+ if (done)
306
+ break;
307
+ if (value.tag == 'ErrorResponse') {
308
+ errorResponse = value.payload;
309
+ }
310
+ yield value;
311
+ if (signal?.aborted) {
312
+ throw Error('postgres query aborted', { cause: signal.reason });
313
+ }
314
+ }
315
+ if (errorResponse) {
316
+ throw new PgError(errorResponse);
317
+ }
318
+ if (value) { // TODO Error('postgres connection destroyed during query') ?
319
+ throw Error('postgres query failed', value);
320
+ }
321
+ }
322
+ catch (ex) {
323
+ stdinAborter.abort(ex);
324
+ throw ex;
325
+ }
326
+ finally {
327
+ // if query completed successfully then all stdins are drained,
328
+ // so abort will have no effect and will not break anything.
329
+ // Оtherwise
330
+ // - if error occured
331
+ // - or iter was .return()'ed
332
+ // - or no COPY FROM STDIN was queried
333
+ // then we should abort all pending stdins
334
+ stdinAborter.abort();
335
+ // https://github.com/kagis/pgwire/issues/17
336
+ if ( // going to do CancelRequest
337
+ // if response is started and not ended
338
+ // and there are no other pending responses
339
+ // (to prevent miscancel of next queued query)
340
+ this._readyState == 'responding' &&
341
+ this._queuedResponseChannels.length == 1 &&
342
+ this._queuedResponseChannels[0] == responseChannel) {
343
+ if (!this._endReason) {
344
+ // new queries should not be emitted during CancelRequest
345
+ this._femsgq.push(responseEndLock);
346
+ }
347
+ // TODO there is a small window between first Sync and Query message
348
+ // when query is not actually executing, so there is small chance
349
+ // that CancelRequest may be ignored. So need to repeat CancelRequest until
350
+ // responseChannel.return() is resolved
351
+ await this._cancelRequest().catch(this._log);
352
+ }
353
+ await responseChannel.return(); // wait ReadyForQuery
354
+ responseEndLock.end();
355
+ // signal is user-provided object, so it can throw and override query error.
356
+ // TODO Its not clear how should we handle this errors, so just do this step
357
+ // at the end of function to minimize impact on code above.
358
+ signal?.removeEventListener('abort', onabort);
359
+ }
360
+ }
361
+ // should immediately close connection for new queries
362
+ // should terminate connection gracefully
363
+ // should be idempotent
364
+ // should never throw, at least when used in finally block.
365
+ /** terminates connection gracefully if possible and waits until termination complete */
366
+ async end() {
367
+ // TODO implement options.timeout ?
368
+ if (!this._endReason) {
369
+ // TODO
370
+ // if (pgbouncer) {
371
+ // const lock = new Channel();
372
+ // this._whenIdle.then(_ => lock.end());
373
+ // this._tx.push(lock);
374
+ // }
375
+ this._femsgq.push(new FrontendMessage.Terminate());
376
+ this._femsgq.end();
377
+ this._endReason = { cause: Error('postgres connection ended') };
378
+ }
379
+ // TODO _net.close can throw
380
+ await this._ioloopPromise;
381
+ }
382
+ async [Symbol.asyncDispose]() {
383
+ await this.end();
384
+ }
385
+ destroy(cause = Error('postgres connection destroyed')) {
386
+ clearInterval(this._wakeTimer);
387
+ // TODO it can be overwritten in ioloop.
388
+ // It used for PgConnection.pid which is used to
389
+ // determine if connection is alive.
390
+ this._backendKeyData = null;
391
+ this._msgw = null;
392
+ _net.closeNullable(this._socket); // TODO can throw ?
393
+ this._socket = null;
394
+ if (!this._endReason) {
395
+ this._femsgq.end();
396
+ this._endReason = { cause };
397
+ this._log('connection destroyed', cause);
398
+ }
399
+ // TODO await _flushData
400
+ this._readyState = 'end';
401
+ while (this._queuedResponseChannels.length) {
402
+ this._queuedResponseChannels.shift().end({ cause });
403
+ }
404
+ // TODO do CancelRequest to wake stuck connection which can continue executing ?
405
+ }
406
+ [Symbol.dispose]() {
407
+ this.destroy();
408
+ }
409
+ logicalReplication(options) {
410
+ return new ReplicationStream(this, options);
411
+ }
412
+ async _cancelRequest() {
413
+ if (!this._backendKeyData) {
414
+ throw Error('CancelRequest attempt before BackendKeyData received');
415
+ }
416
+ const socket = await _net.connect({ ...this._socketOptions, keepAlive: false });
417
+ try {
418
+ // TODO ssl support
419
+ // if (this._ssl) {
420
+ // socket = await this._sslNegotiate(socket);
421
+ // }
422
+ const m = new FrontendMessage.CancelRequest(this._backendKeyData);
423
+ this._logFemsg(m, null);
424
+ await MessageWriter.writeMessage(socket, m);
425
+ // The server closes this connection after processing CancelRequest.
426
+ // Wait before releasing responseEndLock so a late cancellation cannot
427
+ // affect the next query, even if ReadyForQuery has already arrived.
428
+ const response = new Uint8Array(1);
429
+ while ((await _net.read(socket, response)) != null) {
430
+ // Drain until EOF. A CancelRequest has no response message.
431
+ }
432
+ }
433
+ finally {
434
+ _net.closeNullable(socket);
435
+ }
436
+ }
437
+ async _ioloop() {
438
+ let caughtException;
439
+ try {
440
+ while (await this._ioloopAttempt())
441
+ ;
442
+ }
443
+ catch (ex) {
444
+ caughtException = ex || Error('ioloop failed', { cause: ex });
445
+ }
446
+ if (this._lastErrorResponse && this._readyState != 'responding') {
447
+ // broadcast _lastErrorResponse if it not belongs to current query
448
+ // e.g. ErrorResponse during startup
449
+ const errorResponseChunk = new PgChunk();
450
+ errorResponseChunk.tag = 'ErrorResponse';
451
+ errorResponseChunk.payload = this._lastErrorResponse;
452
+ this._queuedResponseChannels.forEach(it => it.push(errorResponseChunk));
453
+ }
454
+ // TODO If we have _lastErrorResponse when socket closed abruptly
455
+ // then we should report _lastErrorResponse instead of io error
456
+ // because _lastErrorResponse will contain more usefull information
457
+ // about socket destroy reason.
458
+ this.destroy(caughtException ||
459
+ this._lastErrorResponse ||
460
+ Error('postgres eof unexpectedly'));
461
+ await this._pipeFemsgqPromise;
462
+ }
463
+ async _ioloopAttempt() {
464
+ this.parameters = Object.create(null);
465
+ this._lastErrorResponse = null;
466
+ this._ssl = false;
467
+ this._sasl = null;
468
+ this._femsgw = null;
469
+ _net.closeNullable(this._socket);
470
+ this._socket = null;
471
+ try {
472
+ this._socket = await _net.connect(this._socketOptions);
473
+ }
474
+ catch (ex) {
475
+ if (_net.reconnectable(ex) && await this._connectRetryPause()) {
476
+ this._log('retrying connection', ex);
477
+ return true; // restart
478
+ }
479
+ throw ex;
480
+ }
481
+ // TODO tcp only? which host should be used in case of unix socket?
482
+ if (/^(try_ssl|require|prefer)$/.test(this._sslmode)) {
483
+ // https://www.postgresql.org/docs/16/protocol-flow.html#PROTOCOL-FLOW-SSL
484
+ const sslReq = new FrontendMessage.SSLRequest();
485
+ this._logFemsg(sslReq, null);
486
+ await MessageWriter.writeMessage(this._socket, sslReq);
487
+ const sslResp = await MessageReader.readSSLResponse(this._socket);
488
+ this._log('n-> ssl available %o', sslResp);
489
+ if (sslResp) {
490
+ try {
491
+ this._socket = await _net.startTls(this._socket, {
492
+ hostname: this._socketOptions.host,
493
+ caCerts: this._sslrootcert && [].concat(this._sslrootcert),
494
+ });
495
+ }
496
+ catch (ex) {
497
+ if (this._sslmode == 'prefer') {
498
+ this._log('retrying connection without ssl because', ex);
499
+ this._sslmode = 'try_nossl';
500
+ return true; // restart
501
+ }
502
+ throw ex;
503
+ }
504
+ this._ssl = true; // ssl established
505
+ }
506
+ else if (this._sslmode == 'require') {
507
+ throw Error('postgres does not support ssl');
508
+ }
509
+ else if (this._sslmode == 'try_ssl') {
510
+ // TODO throw error which caused connection retry
511
+ throw Error('postgres does not support ssl (retry)');
512
+ }
513
+ }
514
+ this._femsgw = new MessageWriter(this._socket);
515
+ await this._writeFemsg(this._startupmsg);
516
+ for await (const chunk of MessageReader.readMessages(this._socket, this._maxReadBuf)) {
517
+ await this._recvMessages(chunk);
518
+ }
519
+ // retry connection if ErrorResponse received before authenticated
520
+ if (this._lastErrorResponse && this._readyState == 'start') {
521
+ const { code } = this._lastErrorResponse;
522
+ // 57P03 cannot_connect_now
523
+ if (code == '57P03' && await this._connectRetryPause()) {
524
+ this._log('retrying connection');
525
+ return true; // restart
526
+ }
527
+ // 28000 invalid_authorization_specification
528
+ if (code == '28000' && this._sslmode == 'prefer' && this._ssl) {
529
+ this._log('retrying connection without ssl');
530
+ this._sslmode = 'try_nossl';
531
+ return true; // restart
532
+ }
533
+ // TODO can this._ssl be true when this._sslmode == 'allow' ?
534
+ if (code == '28000' && this._sslmode == 'allow' && !this._ssl) {
535
+ this._log('retrying connection with ssl');
536
+ this._sslmode = 'try_ssl';
537
+ return true; // restart
538
+ }
539
+ // TODO if error during this._sslmode = try_nossl
540
+ // then should throw original error which caused connection retry
541
+ }
542
+ }
543
+ async _connectRetryPause() {
544
+ return (this._connectDeadline - performance.now() > 0 &&
545
+ new Promise(resolve => setTimeout(resolve, 2000, true)));
546
+ }
547
+ async _recvMessages({ nparsed, messages }) {
548
+ // we are going to batch DataRows and CopyData synchronously
549
+ const batch = {
550
+ rows: [],
551
+ copies: [],
552
+ pos: 0,
553
+ buf: null,
554
+ // Use last backend messages chunk size as buf size hint.
555
+ bufsize: nparsed,
556
+ };
557
+ for (const m of messages) {
558
+ this._logBemsg(m);
559
+ // TODO check if connection is destroyed to prevent errors?
560
+ switch (m.tag) {
561
+ case 'DataRow':
562
+ this._recvDataRow(m, m.payload, batch);
563
+ continue;
564
+ case 'CopyData':
565
+ this._recvCopyData(m, m.payload, batch);
566
+ continue;
567
+ }
568
+ await this._flushBatch(batch);
569
+ // TODO sync push to responseChannel and wait for currResponseChannel drained in the end
570
+ switch (m.tag) {
571
+ case 'CopyInResponse':
572
+ await this._recvCopyInResponse(m, m.payload);
573
+ break;
574
+ case 'CopyOutResponse':
575
+ await this._recvCopyOutResponse(m, m.payload);
576
+ break;
577
+ case 'CopyBothResponse':
578
+ await this._recvCopyBothResponse(m, m.payload);
579
+ break;
580
+ case 'CopyDone':
581
+ await this._recvCopyDone(m, m.payload);
582
+ break;
583
+ case 'RowDescription':
584
+ await this._recvRowDescription(m, m.payload);
585
+ break;
586
+ case 'CommandComplete':
587
+ await this._recvCommandComplete(m, m.payload);
588
+ break;
589
+ case 'ParameterStatus':
590
+ await this._recvParameterStatus(m, m.payload);
591
+ break;
592
+ case 'BackendKeyData':
593
+ await this._recvBackendKeyData(m, m.payload);
594
+ break;
595
+ case 'NoticeResponse':
596
+ await this._recvNoticeResponse(m, m.payload);
597
+ break;
598
+ case 'ErrorResponse':
599
+ await this._recvErrorResponse(m, m.payload);
600
+ break;
601
+ case 'ReadyForQuery':
602
+ await this._recvReadyForQuery(m, m.payload);
603
+ break;
604
+ case 'NotificationResponse':
605
+ this._recvNotificationResponse(m, m.payload);
606
+ break;
607
+ case 'NoData':
608
+ case 'ParameterDescription':
609
+ case 'ParseComplete':
610
+ case 'BindComplete':
611
+ case 'PortalSuspended':
612
+ case 'CloseComplete':
613
+ case 'EmptyQueryResponse':
614
+ await this._fwdBemsg(m);
615
+ break;
616
+ case 'AuthenticationOk':
617
+ await this._recvAuthenticationOk(m, m.payload);
618
+ break;
619
+ case 'AuthenticationMD5Password':
620
+ await this._recvAuthenticationMD5Password(m, m.payload);
621
+ break;
622
+ case 'AuthenticationCleartextPassword':
623
+ await this._recvAuthenticationCleartextPassword(m, m.payload);
624
+ break;
625
+ case 'AuthenticationSASL':
626
+ await this._recvAuthenticationSASL(m, m.payload);
627
+ break;
628
+ case 'AuthenticationSASLContinue':
629
+ await this._recvAuthenticationSASLContinue(m, m.payload);
630
+ break;
631
+ case 'AuthenticationSASLFinal':
632
+ await this._recvAuthenticationSASLFinal(m, m.payload);
633
+ break;
634
+ default:
635
+ throw Error('postgres sent unsupported message', { case: m });
636
+ }
637
+ }
638
+ await this._flushBatch(batch);
639
+ }
640
+ async _pipeFemsgq() {
641
+ const stack = [];
642
+ try {
643
+ // we are going to buffer messages from source iterator until
644
+ // .next returns resolved promises, and then flush buffered
645
+ // messages when .next goes to do real asynchronous work.
646
+ const stub = { pending: true };
647
+ for (let pnext = { value: this._femsgq };;) {
648
+ const { pending, done, value } = await Promise.race([pnext, stub]);
649
+ if (pending) {
650
+ await this._femsgw.flush();
651
+ await pnext;
652
+ continue;
653
+ }
654
+ if (done) {
655
+ await this._femsgw.flush();
656
+ await stack.shift().return();
657
+ if (!stack.length)
658
+ break;
659
+ }
660
+ else if (value[Symbol.asyncIterator]) {
661
+ stack.unshift(value[Symbol.asyncIterator]());
662
+ }
663
+ else {
664
+ this._logFemsg(value);
665
+ // TODO flush if buffer size reached threshold
666
+ this._femsgw.writeMessage(value);
667
+ // msgbuf.count = msgbuf.count + 1 || 1;
668
+ }
669
+ pnext = stack[0].next();
670
+ }
671
+ }
672
+ catch (ex) {
673
+ // _femsgq.return() will wait until _femsgq.end()
674
+ // so we need to destroy connection here to prevent deadlock.
675
+ this.destroy(ex);
676
+ }
677
+ finally {
678
+ await Promise.all(stack.map(it => it.return()));
679
+ }
680
+ }
681
+ async _writeFemsg(m) {
682
+ this._logFemsg(m);
683
+ this._femsgw.writeMessage(m);
684
+ await this._femsgw.flush();
685
+ }
686
+ _logFemsg({ tag, payload }, pid = this.pid) {
687
+ if (!this._debug)
688
+ return;
689
+ pid = pid || 'n';
690
+ const tagStyle = 'font-weight: bold; color: magenta';
691
+ if (typeof payload == 'undefined') {
692
+ return console.error('%s<- %c%s', pid, tagStyle, tag);
693
+ }
694
+ console.error('%s<- %c%s%c %o', pid, tagStyle, tag, '', payload);
695
+ }
696
+ _logBemsg({ tag, payload }) {
697
+ if (!this._debug)
698
+ return;
699
+ const pid = this.pid || 'n';
700
+ if (typeof payload == 'undefined') {
701
+ return console.error('%s-> %s', pid, tag);
702
+ }
703
+ console.error('%s-> %s %o', pid, tag, payload);
704
+ }
705
+ async _recvRowDescription(m, columns) {
706
+ const kRawTuple = Symbol('RawTuple');
707
+ function PgRow(raw) {
708
+ this[kRawTuple] = raw;
709
+ }
710
+ Object.defineProperties(PgRow.prototype, {
711
+ length: { enumerable: false, value: columns.length },
712
+ columns: { enumerable: false, value: columns },
713
+ raw: { enumerable: false, get() { return this[kRawTuple]; } },
714
+ [Symbol.iterator]: { value: Array.prototype.values },
715
+ });
716
+ for (const [i, { typeOid }] of columns.entries()) {
717
+ Object.defineProperty(PgRow.prototype, i, {
718
+ enumerable: true,
719
+ get() {
720
+ const val = this[kRawTuple][i];
721
+ return typeof val == 'string' ? PgType.decode(val, typeOid) : val;
722
+ },
723
+ });
724
+ }
725
+ /** @type {any} Required for TypeScript declaration emit of this private row constructor. */
726
+ this._rowCtor = PgRow;
727
+ await this._fwdBemsg(m);
728
+ }
729
+ _recvDataRow(_, /** @type {Array<Uint8Array>} */ row, batch) {
730
+ const { columns } = this._rowCtor.prototype;
731
+ for (let i = 0; i < columns.length; i++) {
732
+ const valbuf = row[i];
733
+ if (!valbuf)
734
+ continue;
735
+ const { binary } = columns[i];
736
+ // TODO avoid this._rowTextDecoder.decode for bytea
737
+ // TODO maybe allocate buffer per socket.read will be faster
738
+ // then allocating and copying buffer per cell in binary case?
739
+ row[i] = binary ? valbuf.slice() : this._rowTextDecoder.decode(valbuf);
740
+ }
741
+ batch.rows.push(new this._rowCtor(row));
742
+ }
743
+ _recvCopyData(_, /** @type {Uint8Array} */ data, batch) {
744
+ if (!this._copyingOut) {
745
+ // postgres can send CopyData when not in copy out mode, steps to reproduce:
746
+ //
747
+ // <- StartupMessage({ database: 'postgres', user: 'postgres', replication: 'database' })
748
+ // <- Query('CREATE_REPLICATION_SLOT a LOGICAL test_decoding')
749
+ // wait for ReadyForQuery
750
+ // <- Query('START_REPLICATION SLOT a LOGICAL 0/0');
751
+ // <- CopyDone() before wal_sender_timeout expires
752
+ // -> CopyData keepalive message can be received here after CopyDone but before ReadyForQuery
753
+ //
754
+ // <- Query('CREATE_REPLICATION_SLOT b LOGICAL test_decoding')
755
+ // -> CopyData keepalive message sometimes can be received here before RowDescription message
756
+ return;
757
+ }
758
+ batch.buf ||= new Uint8Array(batch.bufsize);
759
+ batch.buf.set(data, batch.pos);
760
+ batch.copies.push(batch.buf.subarray(batch.pos, batch.pos + data.length));
761
+ batch.pos += data.length;
762
+ }
763
+ async _flushBatch(batch) {
764
+ if (batch.copies.length) {
765
+ const copyChunk = new PgChunk(batch.buf.buffer, batch.buf.byteOffset, batch.pos);
766
+ copyChunk.tag = 'CopyData';
767
+ copyChunk.copies = batch.copies;
768
+ batch.buf = batch.buf.subarray(batch.pos);
769
+ batch.pos = 0;
770
+ batch.copies = [];
771
+ this._wakeSupress = true;
772
+ await this._queuedResponseChannels[0].push(copyChunk);
773
+ }
774
+ if (batch.rows.length) {
775
+ const rowsChunk = new PgChunk();
776
+ rowsChunk.tag = 'DataRow';
777
+ rowsChunk.rows = batch.rows;
778
+ this._wakeSupress = true;
779
+ await this._queuedResponseChannels[0].push(rowsChunk);
780
+ batch.rows = [];
781
+ }
782
+ }
783
+ async _recvCopyInResponse(m) {
784
+ await this._fwdBemsg(m);
785
+ }
786
+ async _recvCopyOutResponse(m) {
787
+ this._copyingOut = true;
788
+ await this._fwdBemsg(m);
789
+ }
790
+ async _recvCopyBothResponse(m) {
791
+ this._copyingOut = true;
792
+ await this._fwdBemsg(m);
793
+ }
794
+ async _recvCopyDone(m) {
795
+ this._copyingOut = false;
796
+ await this._fwdBemsg(m);
797
+ }
798
+ async _recvCommandComplete(m) {
799
+ // when call START_REPLICATION second time then replication is not started,
800
+ // but CommandComplete received right after CopyBothResponse without CopyDone.
801
+ // I cannot find any documentation about this postgres behavior.
802
+ // Seems that this line is responsible for this
803
+ // https://github.com/postgres/postgres/blob/0266e98c6b865246c3031bbf55cb15f330134e30/src/backend/replication/walsender.c#L2307
804
+ // streamingDoneReceiving and streamingDoneSending not reset to false before replication start
805
+ this._copyingOut = false;
806
+ await this._fwdBemsg(m);
807
+ }
808
+ async _recvAuthenticationCleartextPassword() {
809
+ // should be always encoded as utf8 even when server_encoding is win1251
810
+ await this._writeFemsg(new FrontendMessage.PasswordMessage(this._password));
811
+ }
812
+ async _recvAuthenticationMD5Password(_, { salt }) {
813
+ // should use server_encoding, but there is
814
+ // no way to know server_encoding before authentication.
815
+ // So it should be possible to provide password as Uint8Array
816
+ const pwduser = Uint8Array.of(...utf8Encode(this._password), ...utf8Encode(this._user));
817
+ const a = utf8Encode(hexEncode(md5(pwduser)));
818
+ const b = 'md5' + hexEncode(md5(Uint8Array.of(...a, ...salt)));
819
+ await this._writeFemsg(new FrontendMessage.PasswordMessage(b));
820
+ function hexEncode(/** @type {Uint8Array} */ bytes) {
821
+ return Array.from(bytes, b => b.toString(16).padStart(2, '0')).join('');
822
+ }
823
+ function utf8Encode(inp) {
824
+ if (inp instanceof Uint8Array)
825
+ return inp;
826
+ return new TextEncoder().encode(inp);
827
+ }
828
+ }
829
+ async _recvAuthenticationSASL(_, { mechanism }) {
830
+ // TODO mechanism is suggestion list:
831
+ // the server sends an AuthenticationSASL message.
832
+ // It includes a list of SASL authentication mechanisms that the server can accept, in the server's preferred order.
833
+ // if (mechanism != 'SCRAM-SHA-256') {
834
+ // throw new PgError({ message: 'Unsupported SASL mechanism ' + JSON.stringify(mechanism) });
835
+ // }
836
+ this._sasl = new SaslScramSha256();
837
+ const data = await this._sasl.start();
838
+ await this._writeFemsg(new FrontendMessage.SASLInitialResponse({
839
+ mechanism: 'SCRAM-SHA-256',
840
+ data,
841
+ }));
842
+ }
843
+ async _recvAuthenticationSASLContinue(_, data) {
844
+ const finmsg = await this._sasl.continue(data, this._password);
845
+ await this._writeFemsg(new FrontendMessage.SASLResponse(finmsg));
846
+ }
847
+ _recvAuthenticationSASLFinal(_, data) {
848
+ this._sasl.finish(data);
849
+ this._sasl = null;
850
+ }
851
+ _recvAuthenticationOk() { }
852
+ async _recvErrorResponse(m, payload) {
853
+ this._copyingOut = false;
854
+ this._lastErrorResponse = payload;
855
+ if (this._readyState == 'responding') {
856
+ await this._fwdBemsg(m);
857
+ }
858
+ }
859
+ async _recvReadyForQuery(m, { transactionStatus }) {
860
+ switch (this._readyState) {
861
+ case 'start':
862
+ this._startupComplete();
863
+ this._readyState = 'idle';
864
+ break;
865
+ case 'idle': // response start
866
+ this._readyState = 'responding';
867
+ await this._fwdBemsg(m);
868
+ break;
869
+ case 'responding': // response end
870
+ if (this._noExplicitTransactions && transactionStatus != 0x49 /*I*/) {
871
+ // TODO how to prevent next query from executing in transaction of previous query?
872
+ throw Error('postgres connection left in transaction', { cause: this._lastErrorResponse });
873
+ }
874
+ await this._fwdBemsg(m);
875
+ this._readyState = 'idle';
876
+ this._lastErrorResponse = null;
877
+ this._queuedResponseChannels.shift().end();
878
+ break;
879
+ }
880
+ this._transactionStatus = transactionStatus;
881
+ }
882
+ _startupComplete() {
883
+ // we dont need password anymore, its more secure to forget it
884
+ this._password = null;
885
+ // check if SASL auth is complete and server is verified
886
+ if (this._sasl) {
887
+ throw Error('incomplete SASL authentication');
888
+ }
889
+ // TODO impl require_auth
890
+ // https://www.postgresql.org/docs/16/libpq-connect.html#LIBPQ-CONNECT-REQUIRE-AUTH
891
+ this._pipeFemsgqPromise = this._pipeFemsgq();
892
+ if (this._wakeInterval > 0) {
893
+ this._wakeTimer = setInterval(this._wakeIfStuck.bind(this), this._wakeInterval);
894
+ }
895
+ }
896
+ async _recvNoticeResponse(m) {
897
+ if (this._readyState == 'responding') {
898
+ await this._fwdBemsg(m);
899
+ }
900
+ // TODO dispatchEvent for nonquery NoticeResponse
901
+ }
902
+ _recvParameterStatus(_, { parameter, value }) {
903
+ this.parameters[parameter] = value;
904
+ // TODO emit event ?
905
+ }
906
+ _recvBackendKeyData(_, backendKeyData) {
907
+ this._backendKeyData = backendKeyData;
908
+ }
909
+ _recvNotificationResponse(_, payload) {
910
+ // Detach onnotification call from _ioloop to avoid error swallowing.
911
+ Promise.resolve(payload).then(this.onnotification);
912
+ }
913
+ async _fwdBemsg({ tag, payload }) {
914
+ const chunk = new PgChunk();
915
+ chunk.tag = tag;
916
+ chunk.payload = payload;
917
+ this._wakeSupress = true;
918
+ await this._queuedResponseChannels[0].push(chunk);
919
+ }
920
+ _wakeIfStuck() {
921
+ // We will send 'wake' chunk if response
922
+ // is stuck longer then _wakeInterval
923
+ // so user have a chance to break loop
924
+ if (this._wakeSupress) {
925
+ this._wakeSupress = false;
926
+ return;
927
+ }
928
+ this._wake();
929
+ }
930
+ _wake() {
931
+ const resp = this._queuedResponseChannels[0];
932
+ if (this._readyState == 'responding' && resp.drained) {
933
+ const wakeChunk = new PgChunk();
934
+ wakeChunk.tag = 'wake';
935
+ resp.push(wakeChunk);
936
+ }
937
+ }
938
+ _log = (...args) => {
939
+ if (!this._debug)
940
+ return;
941
+ console.error(...args);
942
+ };
943
+ }
944
+ class PgChunk extends Uint8Array {
945
+ tag;
946
+ payload = null;
947
+ rows = [];
948
+ copies = [];
949
+ }
950
+ function simpleQuery(out, stdinSignal, script, { stdin, stdins = [] } = 0, responseEndLock) {
951
+ out.push(new FrontendMessage.Query(script));
952
+ // TODO handle case when number of stdins is unknown
953
+ // should block tx and wait for CopyInResponse/CopyBothResponse
954
+ if (stdin) {
955
+ out.push(wrapCopyData(stdin, stdinSignal));
956
+ }
957
+ for (const stdin of stdins) {
958
+ out.push(wrapCopyData(stdin, stdinSignal));
959
+ }
960
+ // when CREATE_REPLICATION_SLOT or START_REPLICATION is emitted
961
+ // then no other queries should be emmited until ReadyForQuery is received.
962
+ // Seems that its a postgres server bug.
963
+ // This workaround looks like fragile hack but its not.
964
+ // Its dirty but safe enough because no comments or other statements can
965
+ // precede CREATE_REPLICATION_SLOT or START_REPLICATION
966
+ if (/^\s*(CREATE_REPLICATION_SLOT|START_REPLICATION)\b/.test(script)) {
967
+ out.push(responseEndLock);
968
+ }
969
+ else {
970
+ out.push(new FrontendMessage.CopyFail('no stdin provided'));
971
+ }
972
+ }
973
+ function extendedQuery(out, stdinSignal, blocks) {
974
+ let signalBlock;
975
+ for (const m of blocks) {
976
+ if (signalBlock !== undefined) {
977
+ throw Error('signal block must be last block');
978
+ }
979
+ if ('signal' in m) {
980
+ signalBlock = m;
981
+ continue;
982
+ }
983
+ switch (m.message) {
984
+ case undefined:
985
+ case null:
986
+ extendedQueryStatement(out, m, stdinSignal);
987
+ break;
988
+ case 'Parse':
989
+ extendedQueryParse(out, m);
990
+ break;
991
+ case 'Bind':
992
+ extendedQueryBind(out, m);
993
+ break;
994
+ case 'Execute':
995
+ extendedQueryExecute(out, m, stdinSignal);
996
+ break;
997
+ case 'DescribeStatement':
998
+ extendedQueryDescribeStatement(out, m);
999
+ break;
1000
+ case 'CloseStatement':
1001
+ extendedQueryCloseStatement(out, m);
1002
+ break;
1003
+ case 'DescribePortal':
1004
+ extendedQueryDescribePortal(out, m);
1005
+ break;
1006
+ case 'ClosePortal':
1007
+ extendedQueryClosePortal(out, m);
1008
+ break;
1009
+ case 'Flush':
1010
+ out.push(new FrontendMessage.Flush());
1011
+ break;
1012
+ default: throw Error('unknown extended message');
1013
+ }
1014
+ }
1015
+ out.push(new FrontendMessage.Sync());
1016
+ return signalBlock?.signal;
1017
+ }
1018
+ function extendedQueryStatement(out, { statement, params = [], limit, binary, stdin, noBuffer }, stdinSignal) {
1019
+ const paramTypes = params.map(({ type }) => type);
1020
+ extendedQueryParse(out, { statement, paramTypes });
1021
+ extendedQueryBind(out, { params, binary });
1022
+ extendedQueryExecute(out, { limit, stdin, noBuffer }, stdinSignal);
1023
+ // if (noBuffer) {
1024
+ // out.push(new Flush());
1025
+ // }
1026
+ }
1027
+ function extendedQueryParse(out, { statement, statementName, paramTypes = [] }) {
1028
+ const paramTypeOids = paramTypes.map(PgType.resolve, PgType);
1029
+ out.push(new FrontendMessage.Parse({ statement, statementName, paramTypeOids }));
1030
+ }
1031
+ function extendedQueryBind(out, { portal, statementName, binary, params = [] }) {
1032
+ params = params.map(encodeParam);
1033
+ out.push(new FrontendMessage.Bind({ portal, statementName, binary, params }));
1034
+ function encodeParam({ value, type }) {
1035
+ if (value == null)
1036
+ return null;
1037
+ // treat Uint8Array values as already encoded,
1038
+ // so user can receive value with unknown type as Uint8Array
1039
+ // from extended .query and pass it back as parameter
1040
+ // it also "encodes" bytea in efficient way instead of hex
1041
+ if (value instanceof Uint8Array)
1042
+ return value;
1043
+ return PgType.encode(value, PgType.resolve(type));
1044
+ }
1045
+ }
1046
+ function extendedQueryExecute(out, { portal, stdin, limit, noBuffer }, stdinSignal) {
1047
+ // TODO write test to explain why
1048
+ // we need unconditional DescribePortal
1049
+ // before Execute
1050
+ out.push(new FrontendMessage.DescribePortal(portal));
1051
+ out.push(new FrontendMessage.Execute({ portal, limit }));
1052
+ // if (noBuffer) {
1053
+ // out.push(new Flush());
1054
+ // }
1055
+ if (stdin) {
1056
+ out.push(wrapCopyData(stdin, stdinSignal));
1057
+ }
1058
+ else {
1059
+ // CopyFail message ignored by postgres
1060
+ // if there is no COPY FROM statement
1061
+ out.push(new FrontendMessage.CopyFail('no stdin provided'));
1062
+ }
1063
+ // TODO nobuffer option
1064
+ // yield new Flush();
1065
+ }
1066
+ function extendedQueryDescribeStatement(out, { statementName }) {
1067
+ out.push(new FrontendMessage.DescribeStatement(statementName));
1068
+ }
1069
+ function extendedQueryCloseStatement(out, { statementName }) {
1070
+ out.push(new FrontendMessage.CloseStatement(statementName));
1071
+ }
1072
+ function extendedQueryDescribePortal(out, { portal }) {
1073
+ out.push(new FrontendMessage.DescribePortal(portal));
1074
+ }
1075
+ function extendedQueryClosePortal({ portal }) {
1076
+ out.push(new FrontendMessage.ClosePortal(portal));
1077
+ }
1078
+ async function* wrapCopyData(source, signal) {
1079
+ // TODO dry
1080
+ // if (abortSignal.aborted) {
1081
+ // return;
1082
+ // }
1083
+ try {
1084
+ // TODO find a way to abort source
1085
+ for await (const chunk of source) {
1086
+ if (signal.aborted) {
1087
+ throw signal.reason;
1088
+ }
1089
+ yield new FrontendMessage.CopyData(chunk);
1090
+ }
1091
+ yield new FrontendMessage.CopyDone();
1092
+ }
1093
+ catch (ex) {
1094
+ // TODO err.stack lost
1095
+ // store err
1096
+ // do CopyFail (copy_error_key)
1097
+ // rethrow stored err when ErrorResponse received
1098
+ yield new FrontendMessage.CopyFail(String(ex));
1099
+ }
1100
+ }
1101
+ class PgResult {
1102
+ static async fromStream(stream) {
1103
+ const notices = [];
1104
+ const results = [];
1105
+ let result = new PgSubResult();
1106
+ for await (const chunk of stream) {
1107
+ result.rows.push(...chunk.rows);
1108
+ // lastResult.copies.push(...chunk.copies); // TODO chunk.copies
1109
+ switch (chunk.tag) {
1110
+ // TODO NoData
1111
+ // TODO ParameterDescription
1112
+ // TODO CopyOutResponse
1113
+ case 'NoticeResponse':
1114
+ notices.push(chunk.payload);
1115
+ break;
1116
+ // case 'CopyOutResponse':
1117
+ // case 'CopyBothResponse':
1118
+ // lastResult.columns = chunk.payload.columns;
1119
+ // break;
1120
+ case 'RowDescription':
1121
+ result.columns = chunk.payload;
1122
+ break;
1123
+ // statement result boundaries
1124
+ case 'CommandComplete':
1125
+ case 'PortalSuspended':
1126
+ case 'EmptyQueryResponse':
1127
+ result.status = chunk.payload || chunk.tag;
1128
+ results.push(result);
1129
+ result = new PgSubResult();
1130
+ break;
1131
+ }
1132
+ }
1133
+ return new PgResult(results, notices);
1134
+ }
1135
+ constructor(results, notices) {
1136
+ /** @type {PgSubResult[]} */
1137
+ this.results = results;
1138
+ /** @type {ErrorOrNotice[]} */
1139
+ this.notices = notices;
1140
+ }
1141
+ /** @deprecated */
1142
+ get scalar() {
1143
+ const [scalar] = this;
1144
+ return scalar;
1145
+ }
1146
+ get rows() {
1147
+ return this._lastSelect?.rows || [];
1148
+ }
1149
+ get columns() {
1150
+ return this._lastSelect?.columns || [];
1151
+ }
1152
+ get status() {
1153
+ // TODO return last statement status?
1154
+ return this.results.length == 1 ? this.results[0].status : null;
1155
+ }
1156
+ *[Symbol.iterator]() {
1157
+ const [row] = this.rows;
1158
+ if (row)
1159
+ yield* row;
1160
+ }
1161
+ get _lastSelect() {
1162
+ for (let i = this.results.length - 1; i >= 0; i--) {
1163
+ if (!this.results[i].columns.length)
1164
+ continue;
1165
+ return this.results[i];
1166
+ }
1167
+ }
1168
+ }
1169
+ class PgSubResult {
1170
+ /** @type {Row[]} */
1171
+ rows = [];
1172
+ /** @type {ColumnDescription[]} */
1173
+ columns = [];
1174
+ /** @type {string} */
1175
+ status = null;
1176
+ /** @deprecated */
1177
+ get scalar() { return this.rows[0]?.[0]; }
1178
+ }
1179
+ // https://www.postgresql.org/docs/14/protocol-message-types.html
1180
+ class BinaryReader {
1181
+ /** @type {Uint8Array} */
1182
+ _b = null;
1183
+ _p = 0;
1184
+ // should not use { fatal: true } because ErrorResponse can use invalid utf8 chars
1185
+ static defaultTextDecoder = new TextDecoder();
1186
+ _textDecoder = BinaryReader.defaultTextDecoder;
1187
+ _reset(/** @type {Uint8Array} */ b) {
1188
+ this._b = b;
1189
+ this._p = 0;
1190
+ }
1191
+ _readUint8() {
1192
+ this._checkSize(1);
1193
+ return this._b[this._p++];
1194
+ }
1195
+ _readInt16() {
1196
+ this._checkSize(2);
1197
+ return (this._b[this._p++] << 8 | this._b[this._p++]) << 16 >> 16;
1198
+ }
1199
+ _readInt32() {
1200
+ this._checkSize(4);
1201
+ return ((this._b[this._p++] << 8 | this._b[this._p++]) << 8 |
1202
+ this._b[this._p++]) << 8 | this._b[this._p++];
1203
+ }
1204
+ _readString() {
1205
+ const endIdx = this._b.indexOf(0x00, this._p);
1206
+ if (endIdx < 0) {
1207
+ throw Error('unexpected end of message');
1208
+ }
1209
+ const strbuf = this._b.subarray(this._p, endIdx);
1210
+ this._p = endIdx + 1;
1211
+ return this._textDecoder.decode(strbuf);
1212
+ }
1213
+ _read(n) {
1214
+ this._checkSize(n);
1215
+ return this._b.subarray(this._p, this._p += n);
1216
+ }
1217
+ _readToEnd() {
1218
+ const p = this._p;
1219
+ this._p = this._b.length;
1220
+ return this._b.subarray(p);
1221
+ }
1222
+ _checkSize(n) {
1223
+ if (this._b.length < this._p + n) {
1224
+ throw Error('unexpected end of message');
1225
+ }
1226
+ }
1227
+ /**
1228
+ * @template T
1229
+ * @param {() => T} fn
1230
+ * @return {T[]} */
1231
+ _array(length, fn) {
1232
+ return Array.from({ length }, fn, this);
1233
+ }
1234
+ // replication helpers
1235
+ _readLsn() {
1236
+ const h = this._readUint32(), l = this._readUint32();
1237
+ if (h == 0 && l == 0)
1238
+ return null;
1239
+ return (h.toString(16).padStart(8, '0') + '/' +
1240
+ l.toString(16).padStart(8, '0')).toUpperCase();
1241
+ }
1242
+ _readTime() {
1243
+ // (POSTGRES_EPOCH_JDATE - UNIX_EPOCH_JDATE) * USECS_PER_DAY == 946684800000000
1244
+ return this._readUint64() + 946684800000000n;
1245
+ }
1246
+ _readUint64() {
1247
+ return BigInt(this._readUint32()) << 32n | BigInt(this._readUint32());
1248
+ }
1249
+ _readUint32() {
1250
+ return this._readInt32() >>> 0;
1251
+ }
1252
+ }
1253
+ // https://www.postgresql.org/docs/14/protocol-message-formats.html
1254
+ class MessageReader extends BinaryReader {
1255
+ static async *readMessages(socket, maxReadBuf) {
1256
+ let buf = new Uint8Array(0x80000); // 512k
1257
+ maxReadBuf = Math.max(buf.length, maxReadBuf) | 0;
1258
+ let nbuf = 0;
1259
+ const msgr = new this();
1260
+ for (;;) {
1261
+ if (nbuf >= maxReadBuf) {
1262
+ throw Error('postgres sent too big message'); // TODO limit message size instead?
1263
+ }
1264
+ if (nbuf >= buf.length) { // grow buffer
1265
+ const oldbuf = buf;
1266
+ buf = new Uint8Array(Math.min(buf.length * 2, maxReadBuf));
1267
+ buf.set(oldbuf);
1268
+ }
1269
+ const nread = await _net.read(socket, buf.subarray(nbuf));
1270
+ if (nread == null)
1271
+ break; // EOF
1272
+ nbuf += nread;
1273
+ let nparsed = 0;
1274
+ const messages = [];
1275
+ for (;;) {
1276
+ const itag = nparsed;
1277
+ const isize = itag + 1;
1278
+ const ipayload = isize + 4;
1279
+ if (nbuf < ipayload)
1280
+ break; // incomplete message
1281
+ msgr._reset(buf.subarray(isize, ipayload));
1282
+ const size = msgr._readInt32();
1283
+ if (size < 4) {
1284
+ throw Error('postgres sent invalid message size');
1285
+ }
1286
+ const inext = isize + size;
1287
+ // TODO use grow hint
1288
+ if (nbuf < inext)
1289
+ break; // incomplete message
1290
+ msgr._reset(buf.subarray(ipayload, inext));
1291
+ const message = msgr._readBackendMessage(buf[itag]);
1292
+ messages.push(message);
1293
+ // TODO batch DataRow here
1294
+ nparsed = inext;
1295
+ }
1296
+ if (nparsed) {
1297
+ yield { nparsed, messages };
1298
+ buf.copyWithin(0, nparsed, nbuf); // move unconsumed bytes to begining of buffer
1299
+ nbuf -= nparsed;
1300
+ }
1301
+ }
1302
+ if (nbuf > 0) {
1303
+ throw Error('postgres eof before message complete'); // TODO report { cause: buf }
1304
+ }
1305
+ }
1306
+ /**
1307
+ * @template {string} T
1308
+ * @template P
1309
+ * @param {T} tag
1310
+ * @param {P} payload
1311
+ */
1312
+ _m(tag, payload) {
1313
+ return { tag, payload };
1314
+ }
1315
+ _readBackendMessage(asciiTag) {
1316
+ const m = this._m;
1317
+ switch (asciiTag) {
1318
+ case 0x64 /*d*/: return m('CopyData', this._b);
1319
+ case 0x44 /*D*/: return m('DataRow', this._readDataRow());
1320
+ case 0x76 /*v*/: return m('NegotiateProtocolVersion', this._readNegotiateProtocolVersion());
1321
+ case 0x53 /*S*/: return m('ParameterStatus', this._readParameterStatus());
1322
+ case 0x4b /*K*/: return m('BackendKeyData', this._readBackendKeyData());
1323
+ case 0x5a /*Z*/: return m('ReadyForQuery', this._readReadyForQuery());
1324
+ case 0x48 /*H*/: return m('CopyOutResponse', this._readCopyResponse());
1325
+ case 0x47 /*G*/: return m('CopyInResponse', this._readCopyResponse());
1326
+ case 0x57 /*W*/: return m('CopyBothResponse', this._readCopyResponse());
1327
+ case 0x63 /*c*/: return m('CopyDone');
1328
+ case 0x54 /*T*/: return m('RowDescription', this._readRowDescription());
1329
+ case 0x74 /*t*/: return m('ParameterDescription', this._readParameterDescription());
1330
+ case 0x43 /*C*/: return m('CommandComplete', this._readString());
1331
+ case 0x31 /*1*/: return m('ParseComplete');
1332
+ case 0x32 /*2*/: return m('BindComplete');
1333
+ case 0x33 /*3*/: return m('CloseComplete');
1334
+ case 0x73 /*s*/: return m('PortalSuspended');
1335
+ case 0x49 /*I*/: return m('EmptyQueryResponse');
1336
+ case 0x4e /*N*/: return m('NoticeResponse', this._readErrorOrNotice());
1337
+ case 0x45 /*E*/: return m('ErrorResponse', this._readErrorOrNotice());
1338
+ case 0x6e /*n*/: return m('NoData');
1339
+ case 0x41 /*A*/: return m('NotificationResponse', this._readNotificationResponse());
1340
+ case 0x52 /*R*/: {
1341
+ const authTag = this._readInt32();
1342
+ switch (authTag) {
1343
+ case 0: return m('AuthenticationOk');
1344
+ case 2: return m('AuthenticationKerberosV5');
1345
+ case 3: return m('AuthenticationCleartextPassword');
1346
+ case 5: return m('AuthenticationMD5Password', { salt: this._read(4) });
1347
+ case 6: return m('AuthenticationSCMCredential');
1348
+ case 7: return m('AuthenticationGSS');
1349
+ case 8: return m('AuthenticationGSSContinue', this._readToEnd());
1350
+ case 9: return m('AuthenticationSSPI');
1351
+ case 10: return m('AuthenticationSASL', { mechanism: this._readString() });
1352
+ case 11: return m('AuthenticationSASLContinue', this._readToEnd());
1353
+ case 12: return m('AuthenticationSASLFinal', this._readToEnd());
1354
+ default: throw Error('postgres sent unknown auth message', { cause: { authTag } });
1355
+ }
1356
+ }
1357
+ default: throw Error('postgres sent unknown message', { cause: { asciiTag } });
1358
+ }
1359
+ }
1360
+ // https://www.postgresql.org/docs/16/protocol-message-formats.html#PROTOCOL-MESSAGE-FORMATS-DATAROW
1361
+ _readDataRow() {
1362
+ const nfields = this._readInt16();
1363
+ const row = Array(nfields);
1364
+ for (let i = 0; i < nfields; i++) {
1365
+ const valsize = this._readInt32();
1366
+ row[i] = valsize < 0 ? null : this._read(valsize);
1367
+ }
1368
+ return row;
1369
+ }
1370
+ // https://www.postgresql.org/docs/16/protocol-message-formats.html#PROTOCOL-MESSAGE-FORMATS-NEGOTIATEPROTOCOLVERSION
1371
+ _readNegotiateProtocolVersion() {
1372
+ const version = this._readInt32();
1373
+ const unrecognizedOptions = this._array(this._readInt32(), this._readString);
1374
+ return { version, unrecognizedOptions };
1375
+ }
1376
+ // https://www.postgresql.org/docs/16/protocol-message-formats.html#PROTOCOL-MESSAGE-FORMATS-PARAMETERDESCRIPTION
1377
+ _readParameterDescription() {
1378
+ return this._array(this._readInt16(), this._readInt32);
1379
+ }
1380
+ // https://www.postgresql.org/docs/16/protocol-message-formats.html#PROTOCOL-MESSAGE-FORMATS-BACKENDKEYDATA
1381
+ _readBackendKeyData() {
1382
+ const pid = this._readInt32();
1383
+ const secretKey = this._readInt32();
1384
+ return { pid, secretKey };
1385
+ }
1386
+ // https://www.postgresql.org/docs/16/protocol-message-formats.html#PROTOCOL-MESSAGE-FORMATS-READYFORQUERY
1387
+ _readReadyForQuery() {
1388
+ return { transactionStatus: this._readUint8() };
1389
+ }
1390
+ // https://www.postgresql.org/docs/16/protocol-message-formats.html#PROTOCOL-MESSAGE-FORMATS-COPYINRESPONSE
1391
+ // https://www.postgresql.org/docs/16/protocol-message-formats.html#PROTOCOL-MESSAGE-FORMATS-COPYOUTRESPONSE
1392
+ // https://www.postgresql.org/docs/16/protocol-message-formats.html#PROTOCOL-MESSAGE-FORMATS-COPYBOTHRESPONSE
1393
+ _readCopyResponse() {
1394
+ const binary = this._readUint8();
1395
+ const columns = this._array(this._readInt16(), _ => ({
1396
+ // TODO make consistent with _readParameterDescription, object[] or number[]
1397
+ binary: this._readInt16(),
1398
+ }));
1399
+ return { binary, columns };
1400
+ }
1401
+ // https://www.postgresql.org/docs/16/protocol-message-formats.html#PROTOCOL-MESSAGE-FORMATS-ROWDESCRIPTION
1402
+ _readRowDescription() {
1403
+ return this._array(this._readInt16(), _ => ({
1404
+ name: this._readString(),
1405
+ tableOid: this._readInt32(),
1406
+ tableColumn: this._readInt16(),
1407
+ typeOid: this._readInt32(),
1408
+ typeSize: this._readInt16(),
1409
+ typeMod: this._readInt32(),
1410
+ binary: this._readInt16(),
1411
+ }));
1412
+ }
1413
+ // https://www.postgresql.org/docs/16/protocol-message-formats.html#PROTOCOL-MESSAGE-FORMATS-PARAMETERSTATUS
1414
+ _readParameterStatus() {
1415
+ const parameter = this._readString();
1416
+ const value = this._readString();
1417
+ return { parameter, value };
1418
+ }
1419
+ // https://www.postgresql.org/docs/16/protocol-message-formats.html#PROTOCOL-MESSAGE-FORMATS-ERRORRESPONSE
1420
+ _readErrorOrNotice() {
1421
+ const fields = /** @type {string[]} */ (Array(256));
1422
+ for (;;) {
1423
+ const fieldCode = this._readUint8();
1424
+ if (!fieldCode)
1425
+ break;
1426
+ fields[fieldCode] = this._readString();
1427
+ }
1428
+ // https://www.postgresql.org/docs/16/protocol-error-fields.html
1429
+ return {
1430
+ __proto__: pgErrorOrNoticeProto, // https://github.com/denoland/deno/issues/23416
1431
+ severity: fields[0x53], // S
1432
+ code: fields[0x43], // C
1433
+ message: fields[0x4d], // M
1434
+ detail: fields[0x44], // D
1435
+ hint: fields[0x48], // H
1436
+ position: fields[0x50] && Number(fields[0x50]), // P
1437
+ internalPosition: fields[0x70] && Number(fields[0x70]), // p
1438
+ internalQuery: fields[0x71], // q
1439
+ where: fields[0x57], // W
1440
+ file: fields[0x46], // F
1441
+ // TODO not parse L number? doc says no details about number format
1442
+ line: fields[0x4c] && Number(fields[0x4c]), // L
1443
+ routine: fields[0x52], // R
1444
+ schema: fields[0x73], // s
1445
+ table: fields[0x74], // t
1446
+ column: fields[0x63], // c
1447
+ datatype: fields[0x64], // d
1448
+ constraint: fields[0x6e], // n
1449
+ severityEn: fields[0x56], // V
1450
+ };
1451
+ }
1452
+ // https://www.postgresql.org/docs/16/protocol-message-formats.html#PROTOCOL-MESSAGE-FORMATS-NOTIFICATIONRESPONSE
1453
+ _readNotificationResponse() {
1454
+ const pid = this._readInt32();
1455
+ const channel = this._readString();
1456
+ const payload = this._readString();
1457
+ return { pid, channel, payload };
1458
+ }
1459
+ static async readSSLResponse(socket) {
1460
+ const readbuf = new Uint8Array(1);
1461
+ // Deno doc says that nread never equals 0, so don't need to repeat
1462
+ const nread = await _net.read(socket, readbuf);
1463
+ if (nread == null) {
1464
+ throw Error('postgres eof during ssl response');
1465
+ }
1466
+ const [resp] = readbuf;
1467
+ if (resp == 0x53 /*S*/)
1468
+ return true;
1469
+ if (resp == 0x4e /*N*/)
1470
+ return false;
1471
+ // TODO postgres doc says that we can receive
1472
+ // ErrorResponse in case of ancient server
1473
+ throw Error('postgres sent bad ssl response', { cause: { resp } });
1474
+ }
1475
+ }
1476
+ const pgErrorOrNoticeProto = {
1477
+ toString() {
1478
+ return JSON.stringify(this, null, 2);
1479
+ }
1480
+ };
1481
+ // https://www.postgresql.org/docs/14/protocol-replication.html#id-1.10.5.9.7.1.5.1.8
1482
+ class ReplicationStream extends BinaryReader {
1483
+ constructor(conn, options) {
1484
+ super();
1485
+ this._tx = new Channel();
1486
+ this._ackingLsn = '00000000/00000000';
1487
+ this._ackmsg = Uint8Array.of(0x72, // r
1488
+ 0, 0, 0, 0, 0, 0, 0, 0, // 1 - written lsn
1489
+ 0, 0, 0, 0, 0, 0, 0, 0, // 9 - flushed lsn
1490
+ 0, 0, 0, 0, 0, 0, 0, 0, // 17 - applied lsn
1491
+ 0, 0, 0, 0, 0, 0, 0, 0, // 25 - time
1492
+ 0);
1493
+ this._ackmsgWrittenLsn = new DataView(this._ackmsg.buffer, 1, 8);
1494
+ this._ackmsgFlushedLsn = new DataView(this._ackmsg.buffer, 9, 8);
1495
+ this._ackmsgAppliedLsn = new DataView(this._ackmsg.buffer, 17, 8);
1496
+ this._iterator = this._start(conn, options);
1497
+ }
1498
+ pgoutputDecode() {
1499
+ return PgoutputReader.decodeStream(this);
1500
+ }
1501
+ [Symbol.asyncIterator]() {
1502
+ return this._iterator;
1503
+ }
1504
+ // TODO signal
1505
+ async *_start(conn, { slot, startLsn = '0/0', options = {}, ackInterval = 10e3 }) {
1506
+ this.ack(startLsn);
1507
+ const optionsSql = (Object.entries(options)
1508
+ .map(([k, v]) => pgident(k) + ' ' + pgliteral(v))
1509
+ .join(',')
1510
+ .replace(/.+/s, '($&)'));
1511
+ // TODO get wal_sender_timeout,
1512
+ // but user may have no access to wal_sender_timeout setting
1513
+ const startReplSql = `START_REPLICATION SLOT ${pgident(slot)} LOGICAL ${startLsn} ${optionsSql}`;
1514
+ const rx = conn.stream(startReplSql, { stdin: this._tx });
1515
+ const ackTimer = setInterval(this._ackImmediate.bind(this), ackInterval);
1516
+ let lastLsn = '00000000/00000000';
1517
+ let lastTime = 0n;
1518
+ try {
1519
+ for (;;) {
1520
+ const { value: chunk, done } = await rx.next();
1521
+ if (done)
1522
+ break;
1523
+ const messages = [];
1524
+ let shouldAck = false;
1525
+ for (const copyData of chunk.copies) {
1526
+ this._reset(copyData);
1527
+ const msg = this._readReplicationMessage();
1528
+ switch (msg.tag) {
1529
+ case 'XLogData':
1530
+ messages.push(msg);
1531
+ break;
1532
+ case 'PrimaryKeepaliveMessage':
1533
+ shouldAck = shouldAck || msg.shouldReply;
1534
+ // TODO messages.push(msg); ?
1535
+ break;
1536
+ }
1537
+ if (lastLsn < msg.lsn)
1538
+ lastLsn = msg.lsn;
1539
+ if (lastLsn < msg.endLsn)
1540
+ lastLsn = msg.endLsn;
1541
+ if (lastTime < msg.time)
1542
+ lastTime = msg.time;
1543
+ }
1544
+ if (shouldAck) {
1545
+ this._ackImmediate();
1546
+ }
1547
+ yield { lastLsn, lastTime, messages };
1548
+ }
1549
+ }
1550
+ finally {
1551
+ clearInterval(ackTimer);
1552
+ this._ackImmediate();
1553
+ this._tx.end();
1554
+ // TODO handle errors?
1555
+ for await (const _ of rx)
1556
+ ; // drain rx until end
1557
+ }
1558
+ }
1559
+ ack(lsn) {
1560
+ if (!/^[0-9a-f]{1,8}[/][0-9a-f]{1,8}$/i.test(lsn)) {
1561
+ throw RangeError('invalid lsn');
1562
+ }
1563
+ lsn = lsnMakeComparable(lsn);
1564
+ if (lsn > this._ackingLsn) {
1565
+ this._ackingLsn = lsn;
1566
+ }
1567
+ const nlsn = BigInt('0x' + this._ackingLsn.replace('/', ''));
1568
+ // https://github.com/postgres/postgres/blob/0526f2f4c38cb50d3e2a6e0aa5d51354158df6e3/src/backend/replication/logical/worker.c#L2473-L2478
1569
+ // https://github.com/postgres/postgres/blob/0526f2f4c38cb50d3e2a6e0aa5d51354158df6e3/src/backend/replication/walsender.c#L2021-L2023
1570
+ // TODO accept { written, flushed, applied, immediate }
1571
+ // Comments say that flushed/written are used for synchronous replication.
1572
+ // What walsender does with flushed/written?
1573
+ this._ackmsgWrittenLsn.setBigUint64(0, nlsn);
1574
+ this._ackmsgFlushedLsn.setBigUint64(0, nlsn);
1575
+ this._ackmsgAppliedLsn.setBigUint64(0, nlsn);
1576
+ }
1577
+ _ackImmediate() {
1578
+ if (!this._tx.drained)
1579
+ return;
1580
+ this._tx.push(this._ackmsg);
1581
+ }
1582
+ _readReplicationMessage() {
1583
+ const tag = this._readUint8();
1584
+ switch (tag) {
1585
+ case 0x77 /*w*/: return this._readXLogData();
1586
+ case 0x6b /*k*/: return this._readPrimaryKeepaliveMessage();
1587
+ default: throw Error('unknown replication message');
1588
+ }
1589
+ }
1590
+ _readXLogData() {
1591
+ return {
1592
+ tag: /** @type {const} */ ('XLogData'),
1593
+ lsn: this._readLsn(),
1594
+ // `endLsn` is always the same as `lsn` in case of logical replication.
1595
+ // https://github.com/postgres/postgres/blob/0a455b8d61d8fc5a7d1fdc152667f9ba1fd27fda/src/backend/replication/walsender.c#L1240
1596
+ endLsn: this._readLsn(),
1597
+ // https://github.com/postgres/postgres/blob/0a455b8d61d8fc5a7d1fdc152667f9ba1fd27fda/src/backend/replication/walsender.c#L1270-L1271
1598
+ time: this._readTime(),
1599
+ data: this._readToEnd(),
1600
+ };
1601
+ }
1602
+ _readPrimaryKeepaliveMessage() {
1603
+ return {
1604
+ tag: /** @type {const} */ ('PrimaryKeepaliveMessage'),
1605
+ lsn: null, // hidden class opt
1606
+ endLsn: this._readLsn(),
1607
+ time: this._readTime(),
1608
+ shouldReply: this._readUint8(),
1609
+ };
1610
+ }
1611
+ }
1612
+ // https://www.postgresql.org/docs/14/protocol-logicalrep-message-formats.html
1613
+ class PgoutputReader extends BinaryReader {
1614
+ static async *decodeStream(replstream) {
1615
+ const pgoreader = new PgoutputReader();
1616
+ for await (const chunk of replstream) {
1617
+ for (const msg of chunk.messages) {
1618
+ pgoreader._reset(msg.data);
1619
+ pgoreader._upgradeMsg(msg);
1620
+ msg.data = null; // free XLogData buffer
1621
+ }
1622
+ yield chunk;
1623
+ }
1624
+ }
1625
+ /** @type {Map<number, { typeSchema: string, typeName: string }>} */
1626
+ _typeCache = new Map();
1627
+ _relationCache = new Map();
1628
+ _upgradeMsg(out) {
1629
+ const tag = this._readUint8();
1630
+ switch (tag) {
1631
+ case 0x42 /*B*/: return this._upgradeMsgBegin(out);
1632
+ case 0x4f /*O*/: return this._upgradeMsgOrigin(out);
1633
+ case 0x59 /*Y*/: return this._upgradeMsgType(out);
1634
+ case 0x52 /*R*/: return this._upgradeMsgRelation(out);
1635
+ case 0x49 /*I*/: return this._upgradeMsgChange(out, 'insert', true);
1636
+ case 0x55 /*U*/: return this._upgradeMsgChange(out, 'update', true);
1637
+ case 0x44 /*D*/: return this._upgradeMsgChange(out, 'delete', false);
1638
+ case 0x54 /*T*/: return this._upgradeMsgTruncate(out);
1639
+ case 0x4d /*M*/: return this._upgradeMsgMessage(out);
1640
+ case 0x43 /*C*/: return this._upgradeMsgCommit(out);
1641
+ default: throw Error('unknown pgoutput message', { cause: { tag } });
1642
+ }
1643
+ }
1644
+ _upgradeMsgBegin(out) {
1645
+ // TODO lsn can be null if origin sended
1646
+ // https://github.com/postgres/postgres/blob/85c61ba8920ba73500e1518c63795982ee455d14/src/backend/replication/pgoutput/pgoutput.c#L409
1647
+ out.tag = 'begin';
1648
+ // https://github.com/postgres/postgres/blob/27b77ecf9f4d5be211900eda54d8155ada50d696/src/include/replication/reorderbuffer.h#L275
1649
+ out.commitLsn = this._readLsn();
1650
+ out.commitTime = this._readTime();
1651
+ // https://github.com/postgres/postgres/blob/4d5105a684ba20bf6a98e6ae48224fe93382c040/src/backend/replication/logical/proto.c#LL67C30-L67C30
1652
+ // https://github.com/postgres/postgres/blob/4d5105a684ba20bf6a98e6ae48224fe93382c040/src/include/libpq/pqformat.h#L143-L149
1653
+ // pq_sendint32 handles both int32 and uint32, xid is uint32
1654
+ out.xid = this._readUint32();
1655
+ }
1656
+ _upgradeMsgOrigin(out) {
1657
+ out.tag = 'origin';
1658
+ out.originLsn = this._readLsn();
1659
+ out.originName = this._readString();
1660
+ }
1661
+ _upgradeMsgType(out) {
1662
+ out.tag = 'type';
1663
+ out.typeOid = this._readInt32();
1664
+ out.typeSchema = this._readString();
1665
+ out.typeName = this._readString();
1666
+ // mem leak not likely to happen because amount of types is usually small
1667
+ this._typeCache.set(out.typeOid, {
1668
+ typeSchema: out.typeSchema,
1669
+ typeName: out.typeName,
1670
+ });
1671
+ }
1672
+ _upgradeMsgRelation(out) {
1673
+ // lsn expected to be null
1674
+ // https://github.com/postgres/postgres/blob/27b77ecf9f4d5be211900eda54d8155ada50d696/src/backend/replication/walsender.c#L1342
1675
+ out.tag = 'relation';
1676
+ out.relationOid = this._readInt32();
1677
+ out.schema = this._readString();
1678
+ out.name = this._readString();
1679
+ out.replicaIdentity = this._readRelationReplicaIdentity();
1680
+ out.columns = this._array(this._readInt16(), this._readRelationColumn);
1681
+ out._tupleCtor = PgoTuple;
1682
+ const kRawTuple = Symbol('RawTuple'); // TODO global static
1683
+ function PgoTuple(raw) {
1684
+ this[kRawTuple] = raw;
1685
+ }
1686
+ PgoTuple.prototype = {
1687
+ __proto__: null,
1688
+ *[Symbol.iterator]() { for (const k in this)
1689
+ yield [k, this[k]]; },
1690
+ };
1691
+ for (const { name, typeOid } of out.columns) {
1692
+ Object.defineProperty(PgoTuple.prototype, name, {
1693
+ enumerable: true,
1694
+ get() {
1695
+ const val = this[kRawTuple][name];
1696
+ // TODO is !typeOid possible?
1697
+ return typeof val == 'string' && typeOid ? PgType.decode(val, typeOid) : val;
1698
+ },
1699
+ });
1700
+ }
1701
+ // mem leak not likely to happen because amount of relations is usually small
1702
+ this._relationCache.set(out.relationOid, out);
1703
+ }
1704
+ _readRelationReplicaIdentity() {
1705
+ // https://www.postgresql.org/docs/14/catalog-pg-class.html
1706
+ const relreplident = this._readUint8();
1707
+ switch (relreplident) {
1708
+ case 0x64 /*d*/: return 'default';
1709
+ case 0x6e /*n*/: return 'nothing';
1710
+ case 0x66 /*f*/: return 'full';
1711
+ case 0x69 /*i*/: return 'index';
1712
+ default: return relreplident;
1713
+ }
1714
+ }
1715
+ _readRelationColumn() {
1716
+ const col = {
1717
+ flags: this._readUint8(),
1718
+ name: this._readString(),
1719
+ typeOid: this._readInt32(),
1720
+ typeMod: this._readInt32(),
1721
+ typeSchema: null,
1722
+ typeName: null, // TODO resolve builtin type names?
1723
+ };
1724
+ Object.assign(col, this._typeCache.get(col.typeOid));
1725
+ return col;
1726
+ }
1727
+ _upgradeMsgChange(out, tag, mustHaveNewTuple) {
1728
+ const relid = this._readInt32();
1729
+ const relation = this._relationCache.get(relid);
1730
+ let before = Object.create(null);
1731
+ let after = null;
1732
+ const isNewTuple = this._readTuple(relation, before);
1733
+ if (isNewTuple) {
1734
+ after = before;
1735
+ before = null;
1736
+ }
1737
+ else if (mustHaveNewTuple) {
1738
+ after = Object.create(null);
1739
+ this._readTuple(relation, after, before);
1740
+ // TODO assert isNewTuple
1741
+ }
1742
+ out.tag = tag;
1743
+ out.relation = relation;
1744
+ // https://github.com/kagis/pgwire/issues/16
1745
+ // https://github.com/kagis/pgwire/issues/27
1746
+ out.beforeRaw = before;
1747
+ out.before = before && new relation._tupleCtor(before);
1748
+ out.afterRaw = after;
1749
+ out.after = after && new relation._tupleCtor(after);
1750
+ // avoid use out.new to make message destructuring easy
1751
+ }
1752
+ _readTuple({ columns }, tuple, unchangedToastFallback) {
1753
+ const kon = this._readUint8();
1754
+ // Treat nulls in key-only tuple (K) as placeholders rather then actual column values.
1755
+ // Key cannot have nulls by documentation anyway.
1756
+ const nullval = kon == 0x4b /*K*/ ? undefined : null;
1757
+ const nfields = this._readInt16();
1758
+ for (let i = 0; i < nfields; i++) {
1759
+ const { name } = columns[i];
1760
+ const kind = this._readUint8();
1761
+ let val;
1762
+ switch (kind) {
1763
+ case 0x62: // 'b' binary
1764
+ case 0x74: // 't' text
1765
+ // no need to clone bytes because new buffer
1766
+ // is created for each replication chunk
1767
+ val = this._read(this._readInt32());
1768
+ if (kind == 0x74 /* t */) {
1769
+ val = this._textDecoder.decode(val); // TODO fatal: true, lossless utf8 decoding
1770
+ }
1771
+ break;
1772
+ case 0x6e: // 'n' null
1773
+ val = nullval;
1774
+ break;
1775
+ case 0x75: // 'u' unchanged toast datum
1776
+ val = unchangedToastFallback?.[name];
1777
+ break;
1778
+ default:
1779
+ throw Error('unknown attribute kind', { cause: { kind } });
1780
+ }
1781
+ tuple[name] = val;
1782
+ }
1783
+ return kon == 0x4e /*N*/;
1784
+ }
1785
+ _upgradeMsgTruncate(out) {
1786
+ const nrels = this._readInt32();
1787
+ out.tag = 'truncate';
1788
+ out.flags = this._readUint8();
1789
+ out.cascade = Boolean(out.flags & 0b1);
1790
+ out.restartIdentity = Boolean(out.flags & 0b10);
1791
+ out.relations = this._array(nrels, _ => this._relationCache.get(this._readInt32()));
1792
+ }
1793
+ _upgradeMsgMessage(out) {
1794
+ out.tag = 'message';
1795
+ out.flags = this._readUint8();
1796
+ out.transactional = Boolean(out.flags & 0b1);
1797
+ out.messageLsn = this._readLsn();
1798
+ out.prefix = this._readString();
1799
+ out.content = this._read(this._readInt32());
1800
+ }
1801
+ _upgradeMsgCommit(out) {
1802
+ out.tag = 'commit';
1803
+ out.flags = this._readUint8(); // reserved unused
1804
+ // should be the same as begin.commitLsn,
1805
+ // postgres somehow uses it to synchronize initial dump with slot position.
1806
+ out.commitLsn = this._readLsn();
1807
+ // `out.commitEndLsn` is redundant because it always the same as `out.lsn` .
1808
+ // Here we see that ctx->write_location = txn->end_lsn
1809
+ // https://github.com/postgres/postgres/blob/0a455b8d61d8fc5a7d1fdc152667f9ba1fd27fda/src/backend/replication/logical/logical.c#L819
1810
+ // Here we see that ctx->write_location is used for `out.lsn` field.
1811
+ // https://github.com/postgres/postgres/blob/0a455b8d61d8fc5a7d1fdc152667f9ba1fd27fda/src/backend/replication/logical/logical.c#L634
1812
+ // https://github.com/postgres/postgres/blob/0a455b8d61d8fc5a7d1fdc152667f9ba1fd27fda/src/backend/replication/walsender.c#L1239
1813
+ // And here we see that txn->end_lsn is used for `out.commitEndLsn` field.
1814
+ // https://github.com/postgres/postgres/blob/0a455b8d61d8fc5a7d1fdc152667f9ba1fd27fda/src/backend/replication/logical/proto.c#L87
1815
+ // Seems that they include `out.commitEndLsn` into pgoutput message to simplify `apply_handle_commit` code
1816
+ // so it can be independent of `out.lsn`, which is lower level XLogData message field.
1817
+ // https://github.com/postgres/postgres/blob/0a455b8d61d8fc5a7d1fdc152667f9ba1fd27fda/src/backend/replication/logical/worker.c#L780
1818
+ out.commitEndLsn = this._readLsn();
1819
+ out.commitTime = this._readTime();
1820
+ }
1821
+ }
1822
+ // https://www.postgresql.org/docs/16/protocol-message-formats.html
1823
+ class FrontendMessage {
1824
+ constructor(payload) {
1825
+ this.payload = payload;
1826
+ // TODO string size depends on encoder
1827
+ this.size = MessageSizer.getMessageSize(this);
1828
+ }
1829
+ get tag() {
1830
+ return this.constructor.name; // we will use it only for debug logging
1831
+ }
1832
+ // https://www.postgresql.org/docs/16/protocol-message-formats.html#PROTOCOL-MESSAGE-FORMATS-STARTUPMESSAGE
1833
+ static StartupMessage = class extends this {
1834
+ write(w, size, options) {
1835
+ w.writeInt32(size);
1836
+ w.writeInt32(0x00030000);
1837
+ for (const [key, val] of Object.entries(options)) {
1838
+ w.writeString(key);
1839
+ w.writeString(val);
1840
+ }
1841
+ w.writeUint8(0);
1842
+ }
1843
+ };
1844
+ // https://www.postgresql.org/docs/16/protocol-message-formats.html#PROTOCOL-MESSAGE-FORMATS-CANCELREQUEST
1845
+ static CancelRequest = class extends this {
1846
+ write(w, _size, { pid, secretKey }) {
1847
+ w.writeInt32(16);
1848
+ w.writeInt32(80877102); // (1234 << 16) | 5678
1849
+ w.writeInt32(pid);
1850
+ w.writeInt32(secretKey);
1851
+ }
1852
+ };
1853
+ // https://www.postgresql.org/docs/16/protocol-message-formats.html#PROTOCOL-MESSAGE-FORMATS-SSLREQUEST
1854
+ static SSLRequest = class extends this {
1855
+ write(w) {
1856
+ w.writeInt32(8);
1857
+ w.writeInt32(80877103); // (1234 << 16) | 5679
1858
+ }
1859
+ };
1860
+ // https://www.postgresql.org/docs/16/protocol-message-formats.html#PROTOCOL-MESSAGE-FORMATS-PASSWORDMESSAGE
1861
+ static PasswordMessage = class extends this {
1862
+ write(w, size, payload) {
1863
+ w.writeUint8(0x70); // p
1864
+ w.writeInt32(size - 1);
1865
+ w.writeString(payload);
1866
+ }
1867
+ };
1868
+ // https://www.postgresql.org/docs/16/protocol-message-formats.html#PROTOCOL-MESSAGE-FORMATS-SASLINITIALRESPONSE
1869
+ static SASLInitialResponse = class extends this {
1870
+ write(w, size, { mechanism, data }) {
1871
+ w.writeUint8(0x70); // p
1872
+ w.writeInt32(size - 1);
1873
+ w.writeString(mechanism);
1874
+ if (data) {
1875
+ w.writeInt32(data.byteLength);
1876
+ w.write(data);
1877
+ }
1878
+ else {
1879
+ w.writeInt32(-1);
1880
+ }
1881
+ }
1882
+ };
1883
+ // https://www.postgresql.org/docs/16/protocol-message-formats.html#PROTOCOL-MESSAGE-FORMATS-SASLRESPONSE
1884
+ static SASLResponse = class extends this {
1885
+ write(w, size, data) {
1886
+ w.writeUint8(0x70); // p
1887
+ w.writeInt32(size - 1);
1888
+ w.write(data);
1889
+ }
1890
+ };
1891
+ // https://www.postgresql.org/docs/16/protocol-message-formats.html#PROTOCOL-MESSAGE-FORMATS-QUERY
1892
+ static Query = class extends this {
1893
+ write(w, size) {
1894
+ w.writeUint8(0x51); // Q
1895
+ w.writeInt32(size - 1);
1896
+ w.writeString(this.payload);
1897
+ }
1898
+ };
1899
+ // https://www.postgresql.org/docs/16/protocol-message-formats.html#PROTOCOL-MESSAGE-FORMATS-PARSE
1900
+ static Parse = class extends this {
1901
+ write(w, size, { statement, statementName = '', paramTypeOids = [] }) {
1902
+ w.writeUint8(0x50); // P
1903
+ w.writeInt32(size - 1);
1904
+ w.writeString(statementName);
1905
+ w.writeString(statement);
1906
+ w.writeInt16(paramTypeOids.length);
1907
+ for (const typeOid of paramTypeOids) {
1908
+ w.writeUint32(typeOid || 0);
1909
+ }
1910
+ }
1911
+ };
1912
+ // https://www.postgresql.org/docs/16/protocol-message-formats.html#PROTOCOL-MESSAGE-FORMATS-BIND
1913
+ static Bind = class extends this {
1914
+ write(w, size, { portal = '', statementName = '', params = [], binary = [] }) {
1915
+ w.writeUint8(0x42); // B
1916
+ w.writeInt32(size - 1);
1917
+ w.writeString(portal);
1918
+ w.writeString(statementName);
1919
+ w.writeInt16(params.length);
1920
+ for (const p of params) {
1921
+ w.writeInt16(Number(p instanceof Uint8Array));
1922
+ }
1923
+ w.writeInt16(params.length);
1924
+ for (const p of params) {
1925
+ if (p == null) {
1926
+ w.writeInt32(-1);
1927
+ continue;
1928
+ }
1929
+ w.writeCounted(p);
1930
+ }
1931
+ w.writeInt16(binary.length);
1932
+ for (const fmt of binary) {
1933
+ w.writeInt16(fmt);
1934
+ }
1935
+ }
1936
+ };
1937
+ // https://www.postgresql.org/docs/16/protocol-message-formats.html#PROTOCOL-MESSAGE-FORMATS-EXECUTE
1938
+ static Execute = class extends this {
1939
+ write(w, size, { portal = '', limit = 0 }) {
1940
+ w.writeUint8(0x45); // E
1941
+ w.writeInt32(size - 1);
1942
+ w.writeString(portal);
1943
+ w.writeUint32(limit);
1944
+ }
1945
+ };
1946
+ // https://www.postgresql.org/docs/16/protocol-message-formats.html#PROTOCOL-MESSAGE-FORMATS-DESCRIBE
1947
+ static DescribeStatement = class extends this {
1948
+ write(w, size, statementName = '') {
1949
+ w.writeUint8(0x44); // D
1950
+ w.writeInt32(size - 1);
1951
+ w.writeUint8(0x53); // S
1952
+ w.writeString(statementName);
1953
+ }
1954
+ };
1955
+ static DescribePortal = class extends this {
1956
+ write(w, size, portal = '') {
1957
+ w.writeUint8(0x44); // D
1958
+ w.writeInt32(size - 1);
1959
+ w.writeUint8(0x50); // P
1960
+ w.writeString(portal);
1961
+ }
1962
+ };
1963
+ // https://www.postgresql.org/docs/16/protocol-message-formats.html#PROTOCOL-MESSAGE-FORMATS-CLOSE
1964
+ static ClosePortal = class extends this {
1965
+ write(w, size, portal = '') {
1966
+ w.writeUint8(0x43); // C
1967
+ w.writeInt32(size - 1);
1968
+ w.writeUint8(0x50); // P
1969
+ w.writeString(portal);
1970
+ }
1971
+ };
1972
+ static CloseStatement = class extends this {
1973
+ write(w, size, statementName = '') {
1974
+ w.writeUint8(0x43); // C
1975
+ w.writeInt32(size - 1);
1976
+ w.writeUint8(0x53); // S
1977
+ w.writeString(statementName);
1978
+ }
1979
+ };
1980
+ // https://www.postgresql.org/docs/16/protocol-message-formats.html#PROTOCOL-MESSAGE-FORMATS-SYNC
1981
+ static Sync = class extends this {
1982
+ write(w) {
1983
+ w.writeUint8(0x53); // S
1984
+ w.writeInt32(4);
1985
+ }
1986
+ };
1987
+ // https://www.postgresql.org/docs/16/protocol-message-formats.html#PROTOCOL-MESSAGE-FORMATS-FLUSH
1988
+ static Flush = class extends this {
1989
+ write(w) {
1990
+ w.writeUint8(0x48); // H
1991
+ w.writeInt32(4);
1992
+ }
1993
+ };
1994
+ // https://www.postgresql.org/docs/16/protocol-message-formats.html#PROTOCOL-MESSAGE-FORMATS-COPYDATA
1995
+ static CopyData = class extends this {
1996
+ write(w, size, data) {
1997
+ w.writeUint8(0x64); // d
1998
+ w.writeInt32(size - 1);
1999
+ w.write(data);
2000
+ }
2001
+ };
2002
+ // https://www.postgresql.org/docs/16/protocol-message-formats.html#PROTOCOL-MESSAGE-FORMATS-COPYDONE
2003
+ static CopyDone = class extends this {
2004
+ write(w) {
2005
+ w.writeUint8(0x63); // c
2006
+ w.writeInt32(4);
2007
+ }
2008
+ };
2009
+ // https://www.postgresql.org/docs/16/protocol-message-formats.html#PROTOCOL-MESSAGE-FORMATS-COPYFAIL
2010
+ static CopyFail = class extends this {
2011
+ write(w, size, cause) {
2012
+ w.writeUint8(0x66); // f
2013
+ w.writeInt32(size - 1);
2014
+ w.writeString(cause);
2015
+ }
2016
+ };
2017
+ // https://www.postgresql.org/docs/16/protocol-message-formats.html#PROTOCOL-MESSAGE-FORMATS-TERMINATE
2018
+ static Terminate = class extends this {
2019
+ write(w) {
2020
+ w.writeUint8(0x58); // X
2021
+ w.writeInt32(4);
2022
+ }
2023
+ };
2024
+ }
2025
+ class MessageWriter {
2026
+ static defaultTextEncoder = new TextEncoder();
2027
+ static async writeMessage(socket, m) {
2028
+ // TODO too big allocation
2029
+ const msgw = new this(socket);
2030
+ msgw.writeMessage(m);
2031
+ await msgw.flush();
2032
+ }
2033
+ constructor(socket) {
2034
+ this._buf = new Uint8Array(32 * 1024);
2035
+ this._v = new DataView(this._buf.buffer);
2036
+ this._pos = 0;
2037
+ this._textEncoder = MessageWriter.defaultTextEncoder;
2038
+ this._socket = socket;
2039
+ }
2040
+ get length() {
2041
+ return this._pos;
2042
+ }
2043
+ writeMessage(m) {
2044
+ this._grow(m.size);
2045
+ // TODO zero copy CopyData, Bind
2046
+ m.write(this, m.size, m.payload);
2047
+ }
2048
+ _grow(size) {
2049
+ const availableSize = this._buf.length - this._pos;
2050
+ if (availableSize >= size)
2051
+ return;
2052
+ const newSize = Math.max(this._buf.length * 2, this._pos + size);
2053
+ const newBuf = new Uint8Array(newSize);
2054
+ newBuf.set(this._buf.subarray(0, this._pos));
2055
+ this._buf = newBuf;
2056
+ this._v = new DataView(this._buf.buffer);
2057
+ }
2058
+ async flush() {
2059
+ if (!this._pos)
2060
+ return;
2061
+ await _net.write(this._socket, this._buf.subarray(0, this._pos));
2062
+ this._pos = 0;
2063
+ }
2064
+ writeUint8(val) {
2065
+ this._v.setUint8(this._pos, val);
2066
+ this._pos++;
2067
+ }
2068
+ writeInt16(val) {
2069
+ this._v.setInt16(this._pos, val);
2070
+ this._pos += 2;
2071
+ }
2072
+ writeInt32(val) {
2073
+ this._v.setInt32(this._pos, val);
2074
+ this._pos += 4;
2075
+ }
2076
+ writeUint32(val) {
2077
+ this._v.setUint32(this._pos, val);
2078
+ this._pos += 4;
2079
+ }
2080
+ writeString(val) {
2081
+ this.write(val);
2082
+ this.writeUint8(0);
2083
+ }
2084
+ writeCounted(val) {
2085
+ const start = this._pos;
2086
+ this.writeInt32(-1); // size prefix, will update later
2087
+ const size = this.write(val);
2088
+ this._v.setInt32(start, size); // update size prefix
2089
+ }
2090
+ write(val) {
2091
+ if (val instanceof Uint8Array) {
2092
+ return this._writeUint8Array(val);
2093
+ }
2094
+ if (typeof val == 'string') {
2095
+ return this._writeString(val);
2096
+ }
2097
+ throw TypeError('string or Uint8Array expected');
2098
+ }
2099
+ _writeUint8Array(val) {
2100
+ this._buf.set(val, this._pos);
2101
+ this._pos += val.length;
2102
+ return val.length;
2103
+ }
2104
+ _writeString(val) {
2105
+ const tail = this._buf.subarray(this._pos);
2106
+ const { read, written } = this._textEncoder.encodeInto(val, tail);
2107
+ if (read < val.length) {
2108
+ throw Error('too small buffer');
2109
+ }
2110
+ this._pos += written;
2111
+ return written;
2112
+ }
2113
+ }
2114
+ class MessageSizer {
2115
+ static _inst = new this();
2116
+ static getMessageSize(m) {
2117
+ this._inst.result = 0;
2118
+ m.write(this._inst, 0, m.payload);
2119
+ return this._inst.result;
2120
+ }
2121
+ result = 0;
2122
+ writeUint8() {
2123
+ this.result += 1;
2124
+ }
2125
+ writeInt16() {
2126
+ this.result += 2;
2127
+ }
2128
+ writeInt32() {
2129
+ this.result += 4;
2130
+ }
2131
+ writeUint32() {
2132
+ this.result += 4;
2133
+ }
2134
+ writeString(val) {
2135
+ // do write before zero check to validate val type first
2136
+ this.write(val);
2137
+ const z = val instanceof Uint8Array ? 0x0 : '\0';
2138
+ if (~val.indexOf(z)) {
2139
+ throw TypeError('zero char is not allowed');
2140
+ }
2141
+ this.writeUint8(0);
2142
+ }
2143
+ writeCounted(val) {
2144
+ this.writeInt32(0);
2145
+ this.write(val);
2146
+ }
2147
+ write(val) {
2148
+ if (val instanceof Uint8Array) {
2149
+ this.result += val.length;
2150
+ }
2151
+ else if (typeof val == 'string') {
2152
+ // TODO count length with this._textEncoder
2153
+ this.result += this._utf8length(val);
2154
+ }
2155
+ else {
2156
+ throw TypeError('string or Uint8Array expected');
2157
+ }
2158
+ }
2159
+ _utf8length(s) {
2160
+ // TODO still not shure that its correct.
2161
+ // May be better use the same aproach as writeCounted:
2162
+ // seek back and mutate 'size' prefix instead of
2163
+ // compute message size ahead of allocation.
2164
+ let result = 0;
2165
+ for (let i = 0; i < s.length; i++) {
2166
+ const c = s.codePointAt(i);
2167
+ if (c > 0xffff)
2168
+ i++, result += 4;
2169
+ else if (c > 0x7ff)
2170
+ result += 3;
2171
+ else if (c > 0x7f)
2172
+ result += 2;
2173
+ else
2174
+ result++;
2175
+ }
2176
+ return result;
2177
+ }
2178
+ }
2179
+ class PgType {
2180
+ static resolve(oidOrName) {
2181
+ if (typeof oidOrName == 'number') { // TODO NaN, Infinity, negative, floats
2182
+ return oidOrName;
2183
+ }
2184
+ switch (oidOrName) { // add line here when register new type
2185
+ case 'text': return 25;
2186
+ case 'text[]': return 1009;
2187
+ case 'uuid': return 2950;
2188
+ case 'uuid[]': return 2951;
2189
+ case 'varchar': return 1043;
2190
+ case 'varchar[]': return 1015;
2191
+ case 'bool': return 16;
2192
+ case 'bool[]': return 1000;
2193
+ case 'bytea': return 17;
2194
+ case 'bytea[]': return 1001;
2195
+ case 'int2': return 21;
2196
+ case 'int2[]': return 1005;
2197
+ case 'int4': return 23;
2198
+ case 'int4[]': return 1007;
2199
+ case 'oid': return 26;
2200
+ case 'oid[]': return 1028;
2201
+ case 'float4': return 700;
2202
+ case 'float4[]': return 1021;
2203
+ case 'float8': return 701;
2204
+ case 'float8[]': return 1022;
2205
+ case 'int8': return 20;
2206
+ case 'int8[]': return 1016;
2207
+ case 'json': return 114;
2208
+ case 'json[]': return 199;
2209
+ case 'jsonb': return 3802;
2210
+ case 'jsonb[]': return 3807;
2211
+ case 'pg_lsn': return 3220;
2212
+ case 'pg_lsn[]': return 3221;
2213
+ }
2214
+ throw Error('unknown builtin type name ' + JSON.stringify(oidOrName));
2215
+ }
2216
+ static encode(value, typeOid) {
2217
+ switch (typeOid) { // add line here when register new type (optional)
2218
+ case 114 /* json */:
2219
+ case 3802 /* jsonb */: return JSON.stringify(value);
2220
+ case 17 /* bytea */: return this._encodeBytea(value); // bytea encoder is used only for array element encoding
2221
+ }
2222
+ const elemTypeid = this._elemTypeOid(typeOid);
2223
+ if (elemTypeid) {
2224
+ return this._encodeArray(value, elemTypeid);
2225
+ }
2226
+ return String(value);
2227
+ }
2228
+ static decode(text, typeOid) {
2229
+ switch (typeOid) { // add line here when register new type
2230
+ case 25 /* text */:
2231
+ case 2950 /* uuid */:
2232
+ case 1043 /* varchar */: return text;
2233
+ case 16 /* bool */: return text == 't';
2234
+ case 17 /* bytea */: return this._decodeBytea(text);
2235
+ case 21 /* int2 */:
2236
+ case 23 /* int4 */:
2237
+ case 26 /* oid */:
2238
+ case 700 /* float4 */:
2239
+ case 701 /* float8 */: return Number(text); // TODO Number.parseFloat ? (fix '' -> 0)
2240
+ case 20 /* int8 */: return BigInt(text);
2241
+ case 114 /* json */:
2242
+ case 3802 /* jsonb */: return JSON.parse(text);
2243
+ case 3220 /* pg_lsn */: return lsnMakeComparable(text);
2244
+ }
2245
+ const elemTypeid = this._elemTypeOid(typeOid);
2246
+ if (elemTypeid) {
2247
+ return this._decodeArray(text, elemTypeid);
2248
+ }
2249
+ return text; // unknown type
2250
+ }
2251
+ static _elemTypeOid(arrayTypeOid) {
2252
+ switch (arrayTypeOid) { // add line here when register new type
2253
+ case 1009: return 25; // text
2254
+ case 1000: return 16; // bool
2255
+ case 1001: return 17; // bytea
2256
+ case 1005: return 21; // int2
2257
+ case 1007: return 23; // int4
2258
+ case 1028: return 26; // oid
2259
+ case 1021: return 700; // float4
2260
+ case 1022: return 701; // float8
2261
+ case 1016: return 20; // int8
2262
+ case 199: return 114; // json
2263
+ case 3807: return 3802; // jsonb
2264
+ case 3221: return 3220; // pg_lsn
2265
+ case 2951: return 2950; // uuid
2266
+ case 1015: return 1043; // varchar
2267
+ }
2268
+ }
2269
+ static _decodeArray(text, elemTypeOid) {
2270
+ text = text.replace(/^\[.+=/, ''); // skip dimensions
2271
+ let result;
2272
+ for (let i = 0, inQuotes = false, elStart = 0, stack = []; i < text.length; i++) {
2273
+ const ch = text.charCodeAt(i);
2274
+ if (ch == 0x5c /*\*/)
2275
+ i++; // escape
2276
+ else if (ch == 0x22 /*"*/)
2277
+ inQuotes = !inQuotes;
2278
+ else if (inQuotes)
2279
+ ; // continue
2280
+ else if (ch == 0x7b /*{*/)
2281
+ stack.unshift([]), elStart = i + 1;
2282
+ else if (ch == 0x7d /*}*/ || ch == 0x2c /*,*/) { // TODO configurable delimiter
2283
+ // TODO ensure .slice is cheap enough to do it unconditionally
2284
+ const escaped = text.slice(elStart, i); // TODO trim ' \t\n\r\v\f'
2285
+ if (result) {
2286
+ stack[0].push(result);
2287
+ }
2288
+ else if (/^NULL$/i.test(escaped)) {
2289
+ stack[0].push(null);
2290
+ }
2291
+ else if (escaped.length) {
2292
+ const unescaped = escaped.replace(/^"|"$|(?<!\\)\\/g, '');
2293
+ // TODO accept decodeFn as argument,
2294
+ // extract parseArray logic out of decoder,
2295
+ // do benchmark of static vs dynamic dispatch
2296
+ const decoded = this.decode(unescaped, elemTypeOid);
2297
+ stack[0].push(decoded);
2298
+ }
2299
+ result = ch == 0x7d /*}*/ && stack.shift();
2300
+ elStart = i + 1; // TODO dry
2301
+ }
2302
+ }
2303
+ return result;
2304
+ }
2305
+ // TODO multi dimension
2306
+ // TODO array_nulls https://www.postgresql.org/docs/16/runtime-config-compatible.html#GUC-ARRAY-NULLS
2307
+ static _encodeArray(arr, elemTypeOid) {
2308
+ const quoteElem = elem => {
2309
+ if (elem == null)
2310
+ return 'NULL';
2311
+ elem = this.encode(elem, elemTypeOid);
2312
+ elem = elem.replace(/(?=\\|")/g, '\\');
2313
+ return `"${elem}"`;
2314
+ };
2315
+ const delim = ','; // TODO box[] uses semicolon
2316
+ return `{${arr.map(quoteElem).join(delim)}}`;
2317
+ }
2318
+ // https://github.com/postgres/postgres/blob/367c989cd8405663bb9a35ec1aa4f79b673a55ff/src/backend/utils/adt/varlena.c#L290
2319
+ static _decodeBytea(/** @type {string} */ text) {
2320
+ // https://www.postgresql.org/docs/16/datatype-binary.html#DATATYPE-BINARY-BYTEA-HEX-FORMAT
2321
+ if (/^\\x/.test(text)) {
2322
+ const hexmap = [
2323
+ ,
2324
+ , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,
2325
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, , , , , , , ,
2326
+ 10, 11, 12, 13, 14, 15, , , , , , , , , , , , , , , , , , , , , , , , , , ,
2327
+ 10, 11, 12, 13, 14, 15,
2328
+ ];
2329
+ text = text.slice(2);
2330
+ const bytes = new Uint8Array(text.length >> 1);
2331
+ for (let i = 0; i < bytes.length; i++) {
2332
+ const h = hexmap[text.charCodeAt(i << 1)];
2333
+ const l = hexmap[text.charCodeAt(i << 1 | 1)];
2334
+ if (isNaN(h + l))
2335
+ throw Error('bad encoded bytea received');
2336
+ bytes[i] = h << 4 | l;
2337
+ }
2338
+ return bytes;
2339
+ }
2340
+ // https://www.postgresql.org/docs/16/datatype-binary.html#DATATYPE-BINARY-BYTEA-ESCAPE-FORMAT
2341
+ const utf8enc = new TextEncoder();
2342
+ const bytes = utf8enc.encode(text);
2343
+ let j = 0;
2344
+ for (let i = 0; i < bytes.length;) {
2345
+ const b0 = bytes[i++];
2346
+ if (b0 != 0x5c) {
2347
+ bytes[j++] = b0;
2348
+ continue;
2349
+ }
2350
+ const b1 = bytes[i++];
2351
+ if (b1 == 0x5c) {
2352
+ bytes[j++] = 0x5c;
2353
+ continue;
2354
+ }
2355
+ const b2 = bytes[i++];
2356
+ const b3 = bytes[i++];
2357
+ if ((b1 & ~0b11) == 0x30 && (b2 & ~0b111) == 0x30 && (b3 & ~0b111) == 0x30) {
2358
+ bytes[j++] = (b1 & 0b11) << 6 | (b2 & 0b111) << 3 | (b3 & 0b111);
2359
+ continue;
2360
+ }
2361
+ throw Error('bad encoded bytea received');
2362
+ }
2363
+ return bytes.subarray(0, j);
2364
+ }
2365
+ static _encodeBytea(bytes) {
2366
+ return '\\x' + Array.from(bytes, b => b.toString(16).padStart(2, '0')).join('');
2367
+ }
2368
+ }
2369
+ function lsnMakeComparable(text) {
2370
+ const [h, l] = text.toUpperCase().split('/');
2371
+ return h.padStart(8, '0') + '/' + l.padStart(8, '0');
2372
+ }
2373
+ function millis(inp) {
2374
+ if (typeof inp == 'number')
2375
+ return inp;
2376
+ if (typeof inp != 'string')
2377
+ return;
2378
+ inp = inp.trim().toLowerCase();
2379
+ const [unit] = /[a-z]*$/i.exec(inp);
2380
+ const num = Number.parseFloat(inp);
2381
+ if (!unit || unit == 'ms')
2382
+ return num;
2383
+ if (unit == 's')
2384
+ return num * 1000;
2385
+ if (unit == 'min')
2386
+ return num * 1000 * 60;
2387
+ if (unit == 'h')
2388
+ return num * 1000 * 60 * 60;
2389
+ if (unit == 'd')
2390
+ return num * 1000 * 60 * 60 * 24;
2391
+ }
2392
+ class Channel {
2393
+ constructor() {
2394
+ this._qnext = [];
2395
+ this._qpush = [];
2396
+ this._value = undefined;
2397
+ this._pausePushAsync = resolve => this._qpush.push({ done: false, value: this._value, resolve });
2398
+ this._pauseNextAsync = resolve => this._qnext.push(resolve);
2399
+ this._resolveEnded = null;
2400
+ this._whenEnded = new Promise(resolve => this._resolveEnded = resolve);
2401
+ }
2402
+ /** `true` if subsequent .push will immediately pass value to awaiting .next */
2403
+ get drained() {
2404
+ return Boolean(this._qnext?.length);
2405
+ }
2406
+ async push(value) {
2407
+ if (!this._qnext)
2408
+ throw Error('push after ended');
2409
+ const resumeNext = this._qnext.shift();
2410
+ if (resumeNext)
2411
+ return resumeNext({ done: false, value });
2412
+ if (!this._qpush)
2413
+ return; // iterator returned
2414
+ this._value = value;
2415
+ await new Promise(this._pausePushAsync);
2416
+ }
2417
+ end(value) {
2418
+ if (!this._qnext)
2419
+ throw Error('already ended');
2420
+ this._value = value;
2421
+ for (const resumeNext of this._qnext) {
2422
+ resumeNext({ done: true, value });
2423
+ // TODO return { value: undefined }
2424
+ }
2425
+ this._qnext = null; // do not pull anymore
2426
+ this._resolveEnded();
2427
+ }
2428
+ async next() {
2429
+ if (!this._qpush)
2430
+ return { done: true, value: undefined };
2431
+ const unpushed = this._qpush.shift();
2432
+ if (unpushed)
2433
+ return unpushed.resolve(), unpushed;
2434
+ if (!this._qnext)
2435
+ return { done: true, value: this._value };
2436
+ return new Promise(this._pauseNextAsync);
2437
+ }
2438
+ async return(value) {
2439
+ if (this._qpush) {
2440
+ this._qpush.forEach(it => it.resolve());
2441
+ this._qpush = null; // do not push anymore
2442
+ }
2443
+ await this._whenEnded;
2444
+ return { done: true, value };
2445
+ }
2446
+ [Symbol.asyncIterator]() {
2447
+ return this;
2448
+ }
2449
+ }
2450
+ // https://www.postgresql.org/docs/14/sasl-authentication.html
2451
+ // https://datatracker.ietf.org/doc/html/rfc5802#section-3
2452
+ /** @internal */
2453
+ export class SaslScramSha256 {
2454
+ _clientFirstMessageBare;
2455
+ _serverSignatureB64;
2456
+ async start() {
2457
+ const clientNonce = this._randomBytes(24);
2458
+ this._clientFirstMessageBare = 'n=,r=' + this._b64encode(clientNonce);
2459
+ const utf8enc = new TextEncoder();
2460
+ return utf8enc.encode('n,,' + this._clientFirstMessageBare);
2461
+ }
2462
+ async continue(serverFirstMessageUtf8, password) {
2463
+ const utf8dec = new TextDecoder();
2464
+ const serverFirstMessage = utf8dec.decode(serverFirstMessageUtf8);
2465
+ const utf8enc = new TextEncoder();
2466
+ const { 'i': iterations, 's': saltB64, 'r': nonceB64 } = this._parseMsg(serverFirstMessage);
2467
+ const finalMessageWithoutProof = 'c=biws,r=' + nonceB64;
2468
+ const salt = this._b64decode(saltB64);
2469
+ const passwordUtf8 = utf8enc.encode(password.normalize());
2470
+ const saltedPassword = await this._hi(passwordUtf8, salt, +iterations);
2471
+ const clientKey = await this._hmac(saltedPassword, utf8enc.encode('Client Key'));
2472
+ const storedKey = await this._hash(clientKey);
2473
+ const authMessage = utf8enc.encode(this._clientFirstMessageBare + ',' +
2474
+ serverFirstMessage + ',' +
2475
+ finalMessageWithoutProof);
2476
+ const clientSignature = await this._hmac(storedKey, authMessage);
2477
+ const clientProof = xor(clientKey, clientSignature);
2478
+ const serverKey = await this._hmac(saltedPassword, utf8enc.encode('Server Key'));
2479
+ const serverSignature = await this._hmac(serverKey, authMessage);
2480
+ this._serverSignatureB64 = this._b64encode(serverSignature);
2481
+ return utf8enc.encode(finalMessageWithoutProof + ',p=' + this._b64encode(clientProof));
2482
+ function xor(a, b) {
2483
+ return Uint8Array.from(a, (ai, i) => ai ^ b[i]);
2484
+ }
2485
+ }
2486
+ finish(responseUtf8) {
2487
+ const utf8dec = new TextDecoder();
2488
+ const response = utf8dec.decode(responseUtf8);
2489
+ if (!this._serverSignatureB64) {
2490
+ throw Error('unexpected auth finish');
2491
+ }
2492
+ const { 'v': receivedServerSignatureB64 } = this._parseMsg(response);
2493
+ if (this._serverSignatureB64 != receivedServerSignatureB64) {
2494
+ throw Error('invalid server SCRAM signature');
2495
+ }
2496
+ }
2497
+ _parseMsg(msg) {
2498
+ return Object.fromEntries(msg.split(',').map(it => /^(.*?)=(.*)$/.exec(it).slice(1)));
2499
+ }
2500
+ _b64encode(bytes) {
2501
+ return btoa(String.fromCharCode(...bytes));
2502
+ }
2503
+ _b64decode(b64) {
2504
+ return Uint8Array.from(atob(b64), x => x.charCodeAt());
2505
+ }
2506
+ _randomBytes(n) {
2507
+ return crypto.getRandomValues(new Uint8Array(n));
2508
+ }
2509
+ async _hash(val) {
2510
+ return new Uint8Array(await crypto.subtle.digest('SHA-256', val));
2511
+ }
2512
+ async _hmac(key, msg) {
2513
+ // https://en.wikipedia.org/wiki/HMAC
2514
+ const bskey = new Uint8Array(64);
2515
+ bskey.set(key.length > bskey.length ? await this._hash(key) : key);
2516
+ const inner = await this._hash(Uint8Array.of(...bskey.map(x => 0x36 ^ x), ...msg));
2517
+ return await this._hash(Uint8Array.of(...bskey.map(x => 0x5c ^ x), ...inner));
2518
+ }
2519
+ async _hi(pwd, salt, iterations) {
2520
+ const cryptoKey = await crypto.subtle.importKey('raw', pwd, 'PBKDF2', false, ['deriveBits']);
2521
+ const pbkdf2params = { name: 'PBKDF2', hash: 'SHA-256', salt, iterations };
2522
+ const buf = await crypto.subtle.deriveBits(pbkdf2params, cryptoKey, 32 * 8);
2523
+ return new Uint8Array(buf);
2524
+ }
2525
+ }
2526
+ function md5(/** @type {Uint8Array} */ input) {
2527
+ const padded = new Uint8Array(Math.ceil((input.byteLength + 1 + 8) / 64) * 64);
2528
+ const paddedv = new DataView(padded.buffer);
2529
+ padded.set(input);
2530
+ paddedv.setUint8(input.byteLength, 0b10000000);
2531
+ paddedv.setBigUint64(paddedv.byteLength - 8, BigInt(input.byteLength) * 8n, true);
2532
+ let a0 = 0x67452301;
2533
+ let b0 = 0xefcdab89;
2534
+ let c0 = 0x98badcfe;
2535
+ let d0 = 0x10325476;
2536
+ const m = Array(16);
2537
+ for (let i = 0; i < paddedv.byteLength; i += 64) {
2538
+ let a = a0, b = b0, c = c0, d = d0;
2539
+ for (let j = 0; j < 16; j++) {
2540
+ m[j] = paddedv.getUint32(i + j * 4, true);
2541
+ }
2542
+ // round 1
2543
+ a = b + rol32((((c ^ d) & b) ^ d) + a + m[0x0] + 0xd76aa478, 7);
2544
+ d = a + rol32((((b ^ c) & a) ^ c) + d + m[0x1] + 0xe8c7b756, 12);
2545
+ c = d + rol32((((a ^ b) & d) ^ b) + c + m[0x2] + 0x242070db, 17);
2546
+ b = c + rol32((((d ^ a) & c) ^ a) + b + m[0x3] + 0xc1bdceee, 22);
2547
+ a = b + rol32((((c ^ d) & b) ^ d) + a + m[0x4] + 0xf57c0faf, 7);
2548
+ d = a + rol32((((b ^ c) & a) ^ c) + d + m[0x5] + 0x4787c62a, 12);
2549
+ c = d + rol32((((a ^ b) & d) ^ b) + c + m[0x6] + 0xa8304613, 17);
2550
+ b = c + rol32((((d ^ a) & c) ^ a) + b + m[0x7] + 0xfd469501, 22);
2551
+ a = b + rol32((((c ^ d) & b) ^ d) + a + m[0x8] + 0x698098d8, 7);
2552
+ d = a + rol32((((b ^ c) & a) ^ c) + d + m[0x9] + 0x8b44f7af, 12);
2553
+ c = d + rol32((((a ^ b) & d) ^ b) + c + m[0xa] + 0xffff5bb1, 17);
2554
+ b = c + rol32((((d ^ a) & c) ^ a) + b + m[0xb] + 0x895cd7be, 22);
2555
+ a = b + rol32((((c ^ d) & b) ^ d) + a + m[0xc] + 0x6b901122, 7);
2556
+ d = a + rol32((((b ^ c) & a) ^ c) + d + m[0xd] + 0xfd987193, 12);
2557
+ c = d + rol32((((a ^ b) & d) ^ b) + c + m[0xe] + 0xa679438e, 17);
2558
+ b = c + rol32((((d ^ a) & c) ^ a) + b + m[0xf] + 0x49b40821, 22);
2559
+ // round 2
2560
+ a = b + rol32((((b ^ c) & d) ^ c) + a + m[0x1] + 0xf61e2562, 5);
2561
+ d = a + rol32((((a ^ b) & c) ^ b) + d + m[0x6] + 0xc040b340, 9);
2562
+ c = d + rol32((((d ^ a) & b) ^ a) + c + m[0xb] + 0x265e5a51, 14);
2563
+ b = c + rol32((((c ^ d) & a) ^ d) + b + m[0x0] + 0xe9b6c7aa, 20);
2564
+ a = b + rol32((((b ^ c) & d) ^ c) + a + m[0x5] + 0xd62f105d, 5);
2565
+ d = a + rol32((((a ^ b) & c) ^ b) + d + m[0xa] + 0x02441453, 9);
2566
+ c = d + rol32((((d ^ a) & b) ^ a) + c + m[0xf] + 0xd8a1e681, 14);
2567
+ b = c + rol32((((c ^ d) & a) ^ d) + b + m[0x4] + 0xe7d3fbc8, 20);
2568
+ a = b + rol32((((b ^ c) & d) ^ c) + a + m[0x9] + 0x21e1cde6, 5);
2569
+ d = a + rol32((((a ^ b) & c) ^ b) + d + m[0xe] + 0xc33707d6, 9);
2570
+ c = d + rol32((((d ^ a) & b) ^ a) + c + m[0x3] + 0xf4d50d87, 14);
2571
+ b = c + rol32((((c ^ d) & a) ^ d) + b + m[0x8] + 0x455a14ed, 20);
2572
+ a = b + rol32((((b ^ c) & d) ^ c) + a + m[0xd] + 0xa9e3e905, 5);
2573
+ d = a + rol32((((a ^ b) & c) ^ b) + d + m[0x2] + 0xfcefa3f8, 9);
2574
+ c = d + rol32((((d ^ a) & b) ^ a) + c + m[0x7] + 0x676f02d9, 14);
2575
+ b = c + rol32((((c ^ d) & a) ^ d) + b + m[0xc] + 0x8d2a4c8a, 20);
2576
+ // round 3
2577
+ a = b + rol32((b ^ c ^ d) + a + m[0x5] + 0xfffa3942, 4);
2578
+ d = a + rol32((a ^ b ^ c) + d + m[0x8] + 0x8771f681, 11);
2579
+ c = d + rol32((d ^ a ^ b) + c + m[0xb] + 0x6d9d6122, 16);
2580
+ b = c + rol32((c ^ d ^ a) + b + m[0xe] + 0xfde5380c, 23);
2581
+ a = b + rol32((b ^ c ^ d) + a + m[0x1] + 0xa4beea44, 4);
2582
+ d = a + rol32((a ^ b ^ c) + d + m[0x4] + 0x4bdecfa9, 11);
2583
+ c = d + rol32((d ^ a ^ b) + c + m[0x7] + 0xf6bb4b60, 16);
2584
+ b = c + rol32((c ^ d ^ a) + b + m[0xa] + 0xbebfbc70, 23);
2585
+ a = b + rol32((b ^ c ^ d) + a + m[0xd] + 0x289b7ec6, 4);
2586
+ d = a + rol32((a ^ b ^ c) + d + m[0x0] + 0xeaa127fa, 11);
2587
+ c = d + rol32((d ^ a ^ b) + c + m[0x3] + 0xd4ef3085, 16);
2588
+ b = c + rol32((c ^ d ^ a) + b + m[0x6] + 0x04881d05, 23);
2589
+ a = b + rol32((b ^ c ^ d) + a + m[0x9] + 0xd9d4d039, 4);
2590
+ d = a + rol32((a ^ b ^ c) + d + m[0xc] + 0xe6db99e5, 11);
2591
+ c = d + rol32((d ^ a ^ b) + c + m[0xf] + 0x1fa27cf8, 16);
2592
+ b = c + rol32((c ^ d ^ a) + b + m[0x2] + 0xc4ac5665, 23);
2593
+ // round 4
2594
+ a = b + rol32((c ^ (b | ~d)) + a + m[0x0] + 0xf4292244, 6);
2595
+ d = a + rol32((b ^ (a | ~c)) + d + m[0x7] + 0x432aff97, 10);
2596
+ c = d + rol32((a ^ (d | ~b)) + c + m[0xe] + 0xab9423a7, 15);
2597
+ b = c + rol32((d ^ (c | ~a)) + b + m[0x5] + 0xfc93a039, 21);
2598
+ a = b + rol32((c ^ (b | ~d)) + a + m[0xc] + 0x655b59c3, 6);
2599
+ d = a + rol32((b ^ (a | ~c)) + d + m[0x3] + 0x8f0ccc92, 10);
2600
+ c = d + rol32((a ^ (d | ~b)) + c + m[0xa] + 0xffeff47d, 15);
2601
+ b = c + rol32((d ^ (c | ~a)) + b + m[0x1] + 0x85845dd1, 21);
2602
+ a = b + rol32((c ^ (b | ~d)) + a + m[0x8] + 0x6fa87e4f, 6);
2603
+ d = a + rol32((b ^ (a | ~c)) + d + m[0xf] + 0xfe2ce6e0, 10);
2604
+ c = d + rol32((a ^ (d | ~b)) + c + m[0x6] + 0xa3014314, 15);
2605
+ b = c + rol32((d ^ (c | ~a)) + b + m[0xd] + 0x4e0811a1, 21);
2606
+ a = b + rol32((c ^ (b | ~d)) + a + m[0x4] + 0xf7537e82, 6);
2607
+ d = a + rol32((b ^ (a | ~c)) + d + m[0xb] + 0xbd3af235, 10);
2608
+ c = d + rol32((a ^ (d | ~b)) + c + m[0x2] + 0x2ad7d2bb, 15);
2609
+ b = c + rol32((d ^ (c | ~a)) + b + m[0x9] + 0xeb86d391, 21);
2610
+ a0 = (a0 + a) >>> 0;
2611
+ b0 = (b0 + b) >>> 0;
2612
+ c0 = (c0 + c) >>> 0;
2613
+ d0 = (d0 + d) >>> 0;
2614
+ }
2615
+ const hash = new Uint8Array(16);
2616
+ const hashv = new DataView(hash.buffer);
2617
+ hashv.setUint32(0, a0, true);
2618
+ hashv.setUint32(4, b0, true);
2619
+ hashv.setUint32(8, c0, true);
2620
+ hashv.setUint32(12, d0, true);
2621
+ return hash;
2622
+ function rol32(x, n) {
2623
+ return (x << n) | (x >>> (32 - n));
2624
+ }
2625
+ }
2626
+ /** @internal */
2627
+ export const _net = {
2628
+ connect(options) {
2629
+ return options.path ? this.connectUnix(options) : this.connectTcp(options);
2630
+ },
2631
+ async connectTcp({ host, port, keepAlive }) {
2632
+ const socket = await Deno.connect({ hostname: host, port });
2633
+ if (keepAlive) {
2634
+ socket.setKeepAlive(keepAlive); // TODO should close socket on error?
2635
+ }
2636
+ return socket;
2637
+ },
2638
+ async connectUnix({ path }) {
2639
+ return await Deno.connect({ transport: 'unix', path });
2640
+ },
2641
+ reconnectable(err) {
2642
+ return (err instanceof Deno.errors.ConnectionRefused ||
2643
+ err instanceof Deno.errors.ConnectionReset);
2644
+ },
2645
+ async startTls(socket, options) {
2646
+ const tlssock = await Deno.startTls(socket, options);
2647
+ try {
2648
+ await tlssock.handshake();
2649
+ }
2650
+ catch (ex) {
2651
+ tlssock.close();
2652
+ throw ex;
2653
+ }
2654
+ return tlssock;
2655
+ },
2656
+ async write(socket, arr) {
2657
+ let nwritten = 0;
2658
+ while (nwritten < arr.length) {
2659
+ nwritten += await socket.write(arr.subarray(nwritten));
2660
+ }
2661
+ },
2662
+ read(socket, buf) {
2663
+ return socket.read(buf);
2664
+ },
2665
+ closeNullable(socket) {
2666
+ if (!socket)
2667
+ return;
2668
+ try {
2669
+ socket.close();
2670
+ }
2671
+ catch (ex) {
2672
+ if (ex instanceof Deno.errors.BadResource)
2673
+ return; // already closed
2674
+ throw ex;
2675
+ }
2676
+ },
2677
+ };
2678
+ /** @typedef {ArrayLike & Iterable & { raw: (string | Uint8Array | null)[] }} Row */
2679
+ /** @typedef {ReturnType<typeof MessageReader.prototype._readRowDescription>[0]} ColumnDescription */
2680
+ /** @typedef {ReturnType<typeof MessageReader.prototype._readErrorOrNotice>} ErrorOrNotice */
2681
+ //# sourceMappingURL=mod.js.map