-
Notifications
You must be signed in to change notification settings - Fork 8
/
mod.js
2621 lines (2536 loc) · 94.7 KB
/
mod.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Copyright (c) 2024 [email protected] at KAGIS
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/** @deprecated */
export async function pgconnect(...optionsChain) {
const conn = pgconnection(...optionsChain);
await conn.query();
return conn;
}
// https://github.com/kagis/pgwire/issues/15
export function pgconnection(...optionsChain) {
return new PgConnection(computeConnectionOptions(optionsChain));
}
export function pgpool(...optionsChain) {
return new PgPool(computeConnectionOptions(optionsChain));
}
export function pgliteral(s) {
if (s == null) return 'NULL';
// TODO array
return `'` + String(s).replace(/'/g, `''`) + `'`;
}
export function pgident(...segments) {
return segments.map(it => '"' + it.replace(/"/g, '""') + '"').join('.');
}
// TODO avoid class export
export class PgError extends Error {
constructor(errorResponse) {
super(errorResponse.message, { cause: errorResponse });
this.name = 'PgError.' + errorResponse.code;
Object.defineProperty(this, 'name', { enumerable: false });
}
}
function computeConnectionOptions(optionsChain) {
return optionsChain.reduceRight(reduceConnectionOptions, {
host: '127.0.0.1',
port: '5432',
});
}
function reduceConnectionOptions(result, uriOrObj) {
if (typeof uriOrObj == 'string') {
uriOrObj = new URL(uriOrObj);
}
if (uriOrObj instanceof URL) {
uriOrObj = {
host: decodeURIComponent(uriOrObj.hostname) || undefined,
port: uriOrObj.port || undefined,
password: decodeURIComponent(uriOrObj.password) || undefined,
'user': decodeURIComponent(uriOrObj.username) || undefined,
'database': decodeURIComponent(uriOrObj.pathname).replace(/^[/]/, '') || undefined,
...Object.fromEntries(uriOrObj.searchParams)
};
}
for (const [k, v] of Object.entries(uriOrObj)) {
if (v === undefined) continue;
result[k] = v;
}
return result;
}
class PgPool {
// TODO? .pending, .queryable
constructor(options) {
/** @type {Set<PgConnection>} */
this._connections = new Set();
this._endReason = null;
this._options = { ...options, _noExplicitTransactions: true };
this._poolSize = Math.max(options._poolSize, 0);
// postgres v14 has `idle_session_timeout` option.
// But if .query will be called when socket is closed by server
// (but Connection is not yet deleted from pool)
// then query will be rejected with error.
// We should be ready to repeat query in this case
// and this is more difficult to implement than client side timeout
this._poolIdleTimeout = Math.max(millis(options._poolIdleTimeout), 0);
}
query(...args) {
return PgResult.fromStream(this.stream(...args));
}
async * stream(...args) {
if (this._endReason) {
throw Error('postgres query late', { cause: this._endReason });
}
const conn = this._getConnection();
try {
yield * conn.stream(...args);
} finally {
await this._recycleConnection(conn);
}
}
async end() {
this._endReason ||= Error('postgres pool ended');
await Promise.all(Array.from(this._connections, conn => conn.end()));
}
async [Symbol.asyncDispose]() {
await this.end();
}
destroy(cause) {
this._endReason ||= Error('postgres pool destroyed', { cause });
this._connections.forEach(it => it.destroy(cause));
}
[Symbol.dispose]() {
this.destroy();
}
_getConnection() {
// try to reuse connection
if (this._poolSize > 0) {
const queryableConns = Array.from(this._connections).filter(conn => conn.queryable);
const full = queryableConns.length >= this._poolSize;
const [leastBusyConn] = queryableConns.sort((a, b) => a.pending - b.pending);
if (leastBusyConn?.pending == 0 || full) {
clearTimeout(leastBusyConn._poolTimeoutId);
return leastBusyConn;
}
}
const newConn = new PgConnection(this._options);
newConn._poolTimeoutId = null; // TODO check whether it disables v8 hidden class optimization
this._connections.add(newConn);
newConn.whenDestroyed.then(this._onConnectionDestroyed.bind(this, newConn));
return newConn;
}
async _recycleConnection(conn) {
if (!(this._poolSize > 0)) {
// TODO not wait
// but pgbouncer does not allow async Terminate anyway.
// May be other poolers do
await conn.end();
return;
}
if (this._poolIdleTimeout && conn.queryable && !conn.pending /* is idle */) {
conn._poolTimeoutId = setTimeout(this._onConnectionTimeout, this._poolIdleTimeout, this, conn);
}
}
_onConnectionTimeout(_self, conn) {
conn.end();
// TODO conn.destroy() if .end() stuck?
}
_onConnectionDestroyed(conn) {
clearTimeout(conn._poolTimeoutId);
this._connections.delete(conn);
}
}
class PgConnection {
constructor({
host, // https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNECT-HOST
port, // https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNECT-PORT
password, // https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNECT-PASSWORD
keepalives = '1', // https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-KEEPALIVES
sslmode, // https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNECT-SSLMODE
sslrootcert, // TODO accept filename as psql do
_connectRetry = 0, // TODO connect_timeout
_wakeInterval = 2000,
_noExplicitTransactions = false,
_maxReadBuf = 50 << 20, // 50 MiB
_debug = false,
...options
}) {
this.onnotification = null;
this.parameters = Object.create(null);
this._debug = /^(true|on|yes|1)$/i.test(_debug);
this._socketOptions = {
host,
port: Number(port),
keepAlive: /^(true|on|yes|1)$/i.test(keepalives),
// TODO windows support
// https://github.com/postgres/postgres/blob/c37267162e889fe783786b9e28d1b65b82365a00/src/include/libpq/pqcomm.h#L67
path: /^[/]/.test(host) && host.replace(/[/]*$/g, '/.s.PGSQL.' + port),
};
this._user = options.user;
this._password = password || '';
this._sslmode = sslmode;
this._sslrootcert = sslrootcert;
this._ssl = false;
// TODO ioloop starts not now
this._connectDeadline = performance.now() + (Math.max(millis(_connectRetry), 0) || NaN);
this._socket = null;
this._backendKeyData = null;
this._lastErrorResponse = null;
this._queuedResponseChannels = [];
/** @type {'start'|'idle'|'responding'|'end'} */
this._readyState = 'start';
this._transactionStatus = -1;
this._wakeSupress = true;
this._wakeInterval = Math.max(millis(_wakeInterval), 0);
this._wakeTimer = null;
this._maxReadBuf = _maxReadBuf;
this._rowProto = null;
this._rowTextDecoder = new TextDecoder('utf-8', { fatal: true });
this._copyingOut = false;
this._femsgw = null;
this._femsgq = new Channel();
this._endReason = null;
this._sasl = null;
this._noExplicitTransactions = _noExplicitTransactions;
// create StartupMessage here to validate options in constructor call stack
this._startupmsg = new FrontendMessage.StartupMessage({
// Underscored props are used for client only,
// Underscore prefix is not supported by postgres anyway
// https://github.com/postgres/postgres/blob/REL_14_2/src/backend/utils/misc/guc.c#L5398
...Object.fromEntries(
Object.entries(options)
.filter(([k]) => !k.startsWith('_'))
),
'client_encoding': 'UTF8', // TextEncoder supports UTF8 only, so hardcode and force UTF8
});
this._pipeFemsgqPromise = null;
this._ioloopPromise = null;
}
get whenDestroyed() {
return this._femsgq._whenEnded.then(_ => this._ioloopPromise);
}
/** Number of pending queries. */
get pending() {
return this._queuedResponseChannels.length;
}
get queryable() {
return !this._endReason;
}
/** ID of postgres backend process. */
get pid() {
if (!this._backendKeyData) return null;
return this._backendKeyData.pid;
}
get ssl() {
return this._ssl;
}
/** Truthy if connection is idle in transaction. */
get inTransaction() {
const s = this._transactionStatus;
return this._readyState == 'idle' && s != 0x49 ? s : 0;
}
// TODO executemany?
// Parse
// Describe(portal)
// Bind
// Execute
// Bind
// Execute
query(...args) {
return PgResult.fromStream(this.stream(...args));
}
async * stream(...args) {
if (this._endReason) {
throw Error('postgres query late', this._endReason);
}
// TODO test .query after .end should throw stable error ? what if auth failed after .end
const stdinAborter = new AbortController();
const responseEndLock = new Channel();
const responseChannel = new Channel();
// Collect outgoing messages into intermediate array
// to let errors occur before any message enqueued.
const frontendMessages = [];
// To cancel query we should send CancelRequest _after_ query is received
// by server and started executing. We going to prepend query with Sync
// message to detect response start boundary by receiving ReadyForQuery.
// ReadyForQuery is flushed immediatly after Sync is handled by server
// so we can know when query is started and can be cancelled.
// Also it makes possible to determine whether NoticeResponse/ErrorResponse
// is asyncronous server message or belongs to query.
// Seems that its ok to do Sync during simple protocol even when replication=database.
// TODO Maybe there is a small window between first ReadyForQuery and actual
// query execution, when async messages can be received. Need more source digging
frontendMessages.push(new FrontendMessage.Sync());
let signal;
if (typeof args[0] == 'string') {
const [simpleSql, simpleOptions] = args;
signal = simpleOptions?.signal;
simpleQuery(frontendMessages, stdinAborter.signal, simpleSql, simpleOptions, responseEndLock);
} else {
signal = extendedQuery(frontendMessages, stdinAborter.signal, args);
}
// this._throwIfQueryAborted(signal);
const onabort = this._wake.bind(this);
// TODO if next two steps throw error then abort handler will not be removed.
signal?.addEventListener('abort', onabort);
// TODO This two steps should be executed atomiсally.
// If one fails then connection instance
// will be desyncronized and should be destroyed.
// But I see no cases when this can throw error.
frontendMessages.forEach(this._femsgq.push, this._femsgq);
this._queuedResponseChannels.push(responseChannel);
this._ioloopPromise ||= this._ioloop();
try {
let value, done, errorResponse;
for (;;) {
// Important to call responseChannel.next() as first step of try block
// to maximize chance that finally block will be executed after
// query is received by server. So CancelRequest will be emited
// in case of error, and skip-waiting duration will be minimized.
({ value, done } = await responseChannel.next());
if (done) break;
if (value.tag == 'ErrorResponse') {
errorResponse = value.payload;
}
yield value;
if (signal?.aborted) {
throw Error('postgres query aborted', { cause: signal.reason });
}
}
if (errorResponse) {
throw new PgError(errorResponse);
}
if (value) { // TODO Error('postgres connection destroyed during query') ?
throw Error('postgres query failed', value);
}
} catch (ex) {
stdinAborter.abort(ex);
throw ex;
} finally {
// if query completed successfully then all stdins are drained,
// so abort will have no effect and will not break anything.
// Оtherwise
// - if error occured
// - or iter was .return()'ed
// - or no COPY FROM STDIN was queried
// then we should abort all pending stdins
stdinAborter.abort();
// https://github.com/kagis/pgwire/issues/17
if ( // going to do CancelRequest
// if response is started and not ended
// and there are no other pending responses
// (to prevent miscancel of next queued query)
this._readyState == 'responding' &&
this._queuedResponseChannels.length == 1 &&
this._queuedResponseChannels[0] == responseChannel
) {
if (!this._endReason) {
// new queries should not be emitted during CancelRequest
this._femsgq.push(responseEndLock);
}
// TODO there is a small window between first Sync and Query message
// when query is not actually executing, so there is small chance
// that CancelRequest may be ignored. So need to repeat CancelRequest until
// responseChannel.return() is resolved
await this._cancelRequest().catch(this._log);
}
await responseChannel.return(); // wait ReadyForQuery
responseEndLock.end();
// signal is user-provided object, so it can throw and override query error.
// TODO Its not clear how should we handle this errors, so just do this step
// at the end of function to minimize impact on code above.
signal?.removeEventListener('abort', onabort);
}
}
// should immediately close connection for new queries
// should terminate connection gracefully
// should be idempotent
// should never throw, at least when used in finally block.
/** terminates connection gracefully if possible and waits until termination complete */
async end() {
// TODO implement options.timeout ?
if (!this._endReason) {
// TODO
// if (pgbouncer) {
// const lock = new Channel();
// this._whenIdle.then(_ => lock.end());
// this._tx.push(lock);
// }
this._femsgq.push(new FrontendMessage.Terminate());
this._femsgq.end();
this._endReason = { cause: Error('postgres connection ended') };
}
// TODO _net.close can throw
await this._ioloopPromise;
}
async [Symbol.asyncDispose]() {
await this.end();
}
destroy(cause = Error('postgres connection destroyed')) {
clearInterval(this._wakeTimer);
// TODO it can be overwritten in ioloop.
// It used for PgConnection.pid which is used to
// determine if connection is alive.
this._backendKeyData = null;
this._msgw = null;
_net.closeNullable(this._socket); // TODO can throw ?
this._socket = null;
if (!this._endReason) {
this._femsgq.end();
this._endReason = { cause };
this._log('connection destroyed', cause);
}
// TODO await _flushData
this._readyState = 'end';
while (this._queuedResponseChannels.length) {
this._queuedResponseChannels.shift().end({ cause });
}
// TODO do CancelRequest to wake stuck connection which can continue executing ?
}
[Symbol.dispose]() {
this.destroy();
}
logicalReplication(options) {
return new ReplicationStream(this, options);
}
async _cancelRequest() {
if (!this._backendKeyData) {
throw Error('CancelRequest attempt before BackendKeyData received');
}
const socket = await _net.connect({ ...this._socketOptions, keepAlive: false });
try {
// TODO ssl support
// if (this._ssl) {
// socket = await this._sslNegotiate(socket);
// }
const m = new FrontendMessage.CancelRequest(this._backendKeyData);
this._logFemsg(m, null);
await MessageWriter.writeMessage(socket, m);
} finally {
_net.closeNullable(socket);
}
}
async _ioloop() {
let caughtException;
try {
while (await this._ioloopAttempt());
} catch (ex) {
caughtException = ex || Error('ioloop failed', { cause: ex });
}
if (this._lastErrorResponse && this._readyState != 'responding') {
// broadcast _lastErrorResponse if it not belongs to current query
// e.g. ErrorResponse during startup
const errorResponseChunk = new PgChunk();
errorResponseChunk.tag = 'ErrorResponse';
errorResponseChunk.payload = this._lastErrorResponse;
this._queuedResponseChannels.forEach(it => it.push(errorResponseChunk));
}
// TODO If we have _lastErrorResponse when socket closed abruptly
// then we should report _lastErrorResponse instead of io error
// because _lastErrorResponse will contain more usefull information
// about socket destroy reason.
this.destroy(
caughtException ||
this._lastErrorResponse ||
Error('postgres eof unexpectedly')
);
await this._pipeFemsgqPromise;
}
async _ioloopAttempt() {
this.parameters = Object.create(null);
this._lastErrorResponse = null;
this._ssl = false;
this._sasl = null;
this._femsgw = null;
_net.closeNullable(this._socket);
this._socket = null;
try {
this._socket = await _net.connect(this._socketOptions);
} catch (ex) {
if (_net.reconnectable(ex) && await this._connectRetryPause()) {
this._log('retrying connection', ex);
return true; // restart
}
throw ex;
}
// TODO tcp only? which host should be used in case of unix socket?
if (/^(try_ssl|require|prefer)$/.test(this._sslmode)) {
// https://www.postgresql.org/docs/16/protocol-flow.html#PROTOCOL-FLOW-SSL
const sslReq = new FrontendMessage.SSLRequest();
this._logFemsg(sslReq, null);
await MessageWriter.writeMessage(this._socket, sslReq);
const sslResp = await MessageReader.readSSLResponse(this._socket);
this._log('n-> ssl available %o', sslResp);
if (sslResp) {
try {
this._socket = await _net.startTls(this._socket, {
hostname: this._socketOptions.host,
caCerts: this._sslrootcert && [].concat(this._sslrootcert),
});
} catch (ex) {
if (this._sslmode == 'prefer') {
this._log('retrying connection without ssl because', ex);
this._sslmode = 'try_nossl';
return true; // restart
}
throw ex;
}
this._ssl = true; // ssl established
} else if (this._sslmode == 'require') {
throw Error('postgres does not support ssl');
} else if (this._sslmode == 'try_ssl') {
// TODO throw error which caused connection retry
throw Error('postgres does not support ssl (retry)');
}
}
this._femsgw = new MessageWriter(this._socket);
await this._writeFemsg(this._startupmsg);
for await (const chunk of MessageReader.readMessages(this._socket, this._maxReadBuf)) {
await this._recvMessages(chunk);
}
// retry connection if ErrorResponse received before authenticated
if (this._lastErrorResponse && this._readyState == 'start') {
const { code } = this._lastErrorResponse;
// 57P03 cannot_connect_now
if (code == '57P03' && await this._connectRetryPause()) {
this._log('retrying connection');
return true; // restart
}
// 28000 invalid_authorization_specification
if (code == '28000' && this._sslmode == 'prefer' && this._ssl) {
this._log('retrying connection without ssl');
this._sslmode = 'try_nossl';
return true; // restart
}
// TODO can this._ssl be true when this._sslmode == 'allow' ?
if (code == '28000' && this._sslmode == 'allow' && !this._ssl) {
this._log('retrying connection with ssl');
this._sslmode = 'try_ssl';
return true; // restart
}
// TODO if error during this._sslmode = try_nossl
// then should throw original error which caused connection retry
}
}
async _connectRetryPause() {
return (
this._connectDeadline - performance.now() > 0 &&
new Promise(resolve => setTimeout(resolve, 2000, true))
);
}
async _recvMessages({ nparsed, messages }) {
// we are going to batch DataRows and CopyData synchronously
const batch = {
rows: [],
copies: [],
pos: 0,
buf: null,
// Use last backend messages chunk size as buf size hint.
bufsize: nparsed,
};
for (const m of messages) {
this._logBemsg(m);
// TODO check if connection is destroyed to prevent errors?
switch (m.tag) {
case 'DataRow': this._recvDataRow(m, m.payload, batch); continue;
case 'CopyData': this._recvCopyData(m, m.payload, batch); continue;
}
await this._flushBatch(batch);
// TODO sync push to responseChannel and wait for currResponseChannel drained in the end
switch (m.tag) {
case 'CopyInResponse': await this._recvCopyInResponse(m, m.payload); break;
case 'CopyOutResponse': await this._recvCopyOutResponse(m, m.payload); break;
case 'CopyBothResponse': await this._recvCopyBothResponse(m, m.payload); break;
case 'CopyDone': await this._recvCopyDone(m, m.payload); break;
case 'RowDescription': await this._recvRowDescription(m, m.payload); break;
case 'CommandComplete': await this._recvCommandComplete(m, m.payload); break;
case 'ParameterStatus': await this._recvParameterStatus(m, m.payload); break;
case 'BackendKeyData': await this._recvBackendKeyData(m, m.payload); break;
case 'NoticeResponse': await this._recvNoticeResponse(m, m.payload); break;
case 'ErrorResponse': await this._recvErrorResponse(m, m.payload); break;
case 'ReadyForQuery': await this._recvReadyForQuery(m, m.payload); break;
case 'NotificationResponse': this._recvNotificationResponse(m, m.payload); break;
case 'NoData':
case 'ParameterDescription':
case 'ParseComplete':
case 'BindComplete':
case 'PortalSuspended':
case 'CloseComplete':
case 'EmptyQueryResponse':
await this._fwdBemsg(m);
break;
case 'AuthenticationOk': await this._recvAuthenticationOk(m, m.payload); break;
case 'AuthenticationMD5Password': await this._recvAuthenticationMD5Password(m, m.payload); break;
case 'AuthenticationCleartextPassword': await this._recvAuthenticationCleartextPassword(m, m.payload); break;
case 'AuthenticationSASL': await this._recvAuthenticationSASL(m, m.payload); break;
case 'AuthenticationSASLContinue': await this._recvAuthenticationSASLContinue(m, m.payload); break;
case 'AuthenticationSASLFinal': await this._recvAuthenticationSASLFinal(m, m.payload); break;
default:
throw Error('postgres sent unsupported message', { case: m });
}
}
await this._flushBatch(batch);
}
async _pipeFemsgq() {
const stack = [];
try {
// we are going to buffer messages from source iterator until
// .next returns resolved promises, and then flush buffered
// messages when .next goes to do real asynchronous work.
const stub = { pending: true };
for (let pnext = { value: this._femsgq };;) {
const { pending, done, value } = await Promise.race([pnext, stub]);
if (pending) {
await this._femsgw.flush();
await pnext;
continue;
}
if (done) {
await this._femsgw.flush();
await stack.shift().return();
if (!stack.length) break;
} else if (value[Symbol.asyncIterator]) {
stack.unshift(value[Symbol.asyncIterator]());
} else {
this._logFemsg(value);
// TODO flush if buffer size reached threshold
this._femsgw.writeMessage(value);
// msgbuf.count = msgbuf.count + 1 || 1;
}
pnext = stack[0].next();
}
} catch (ex) {
// _femsgq.return() will wait until _femsgq.end()
// so we need to destroy connection here to prevent deadlock.
this.destroy(ex);
} finally {
await Promise.all(stack.map(it => it.return()));
}
}
async _writeFemsg(m) {
this._logFemsg(m);
this._femsgw.writeMessage(m);
await this._femsgw.flush();
}
_logFemsg({ tag, payload }, pid = this.pid) {
if (!this._debug) return;
pid = pid || 'n';
const tagStyle = 'font-weight: bold; color: magenta';
if (typeof payload == 'undefined') {
return console.error('%s<- %c%s', pid, tagStyle, tag);
}
console.error('%s<- %c%s%c %o', pid, tagStyle, tag, '', payload);
}
_logBemsg({ tag, payload }) {
if (!this._debug) return;
const pid = this.pid || 'n';
if (typeof payload == 'undefined') {
return console.error('%s-> %s', pid, tag);
}
console.error('%s-> %s %o', pid, tag, payload);
}
async _recvRowDescription(m, columns) {
const kRawTuple = Symbol('RawTuple');
function PgRow(raw) {
this[kRawTuple] = raw;
}
Object.defineProperties(PgRow.prototype, {
length: { enumerable: false, value: columns.length },
columns: { enumerable: false, value: columns },
raw: { enumerable: false, get() { return this[kRawTuple]; } },
[Symbol.iterator]: { value: Array.prototype.values },
});
for (const [i, { typeOid }] of columns.entries()) {
Object.defineProperty(PgRow.prototype, i, {
enumerable: true,
get() {
const val = this[kRawTuple][i];
return typeof val == 'string' ? PgType.decode(val, typeOid) : val;
},
});
}
this._rowCtor = PgRow;
await this._fwdBemsg(m);
}
_recvDataRow(_, /** @type {Array<Uint8Array>} */ row, batch) {
const { columns } = this._rowCtor.prototype;
for (let i = 0; i < columns.length; i++) {
const valbuf = row[i];
if (!valbuf) continue;
const { binary } = columns[i];
// TODO avoid this._rowTextDecoder.decode for bytea
// TODO maybe allocate buffer per socket.read will be faster
// then allocating and copying buffer per cell in binary case?
row[i] = binary ? valbuf.slice() : this._rowTextDecoder.decode(valbuf);
}
batch.rows.push(new this._rowCtor(row));
}
_recvCopyData(_, /** @type {Uint8Array} */ data, batch) {
if (!this._copyingOut) {
// postgres can send CopyData when not in copy out mode, steps to reproduce:
//
// <- StartupMessage({ database: 'postgres', user: 'postgres', replication: 'database' })
// <- Query('CREATE_REPLICATION_SLOT a LOGICAL test_decoding')
// wait for ReadyForQuery
// <- Query('START_REPLICATION SLOT a LOGICAL 0/0');
// <- CopyDone() before wal_sender_timeout expires
// -> CopyData keepalive message can be received here after CopyDone but before ReadyForQuery
//
// <- Query('CREATE_REPLICATION_SLOT b LOGICAL test_decoding')
// -> CopyData keepalive message sometimes can be received here before RowDescription message
return;
}
batch.buf ||= new Uint8Array(batch.bufsize);
batch.buf.set(data, batch.pos);
batch.copies.push(batch.buf.subarray(batch.pos, batch.pos + data.length));
batch.pos += data.length;
}
async _flushBatch(batch) {
if (batch.copies.length) {
const copyChunk = new PgChunk(batch.buf.buffer, batch.buf.byteOffset, batch.pos);
copyChunk.tag = 'CopyData';
copyChunk.copies = batch.copies;
batch.buf = batch.buf.subarray(batch.pos);
batch.pos = 0;
batch.copies = [];
this._wakeSupress = true;
await this._queuedResponseChannels[0].push(copyChunk);
}
if (batch.rows.length) {
const rowsChunk = new PgChunk();
rowsChunk.tag = 'DataRow';
rowsChunk.rows = batch.rows;
this._wakeSupress = true;
await this._queuedResponseChannels[0].push(rowsChunk);
batch.rows = [];
}
}
async _recvCopyInResponse(m) {
await this._fwdBemsg(m);
}
async _recvCopyOutResponse(m) {
this._copyingOut = true;
await this._fwdBemsg(m);
}
async _recvCopyBothResponse(m) {
this._copyingOut = true;
await this._fwdBemsg(m);
}
async _recvCopyDone(m) {
this._copyingOut = false;
await this._fwdBemsg(m);
}
async _recvCommandComplete(m) {
// when call START_REPLICATION second time then replication is not started,
// but CommandComplete received right after CopyBothResponse without CopyDone.
// I cannot find any documentation about this postgres behavior.
// Seems that this line is responsible for this
// https://github.com/postgres/postgres/blob/0266e98c6b865246c3031bbf55cb15f330134e30/src/backend/replication/walsender.c#L2307
// streamingDoneReceiving and streamingDoneSending not reset to false before replication start
this._copyingOut = false;
await this._fwdBemsg(m);
}
async _recvAuthenticationCleartextPassword() {
// should be always encoded as utf8 even when server_encoding is win1251
await this._writeFemsg(new FrontendMessage.PasswordMessage(this._password));
}
async _recvAuthenticationMD5Password(_, { salt }) {
// should use server_encoding, but there is
// no way to know server_encoding before authentication.
// So it should be possible to provide password as Uint8Array
const pwduser = Uint8Array.of(...utf8Encode(this._password), ...utf8Encode(this._user));
const a = utf8Encode(hexEncode(md5(pwduser)));
const b = 'md5' + hexEncode(md5(Uint8Array.of(...a, ...salt)));
await this._writeFemsg(new FrontendMessage.PasswordMessage(b));
function hexEncode(/** @type {Uint8Array} */ bytes) {
return Array.from(bytes, b => b.toString(16).padStart(2, '0')).join('');
}
function utf8Encode(inp) {
if (inp instanceof Uint8Array) return inp;
return new TextEncoder().encode(inp);
}
}
async _recvAuthenticationSASL(_, { mechanism }) {
// TODO mechanism is suggestion list:
// the server sends an AuthenticationSASL message.
// It includes a list of SASL authentication mechanisms that the server can accept, in the server's preferred order.
// if (mechanism != 'SCRAM-SHA-256') {
// throw new PgError({ message: 'Unsupported SASL mechanism ' + JSON.stringify(mechanism) });
// }
this._sasl = new SaslScramSha256();
const data = await this._sasl.start();
await this._writeFemsg(new FrontendMessage.SASLInitialResponse({
mechanism: 'SCRAM-SHA-256',
data,
}));
}
async _recvAuthenticationSASLContinue(_, data) {
const finmsg = await this._sasl.continue(data, this._password);
await this._writeFemsg(new FrontendMessage.SASLResponse(finmsg));
}
_recvAuthenticationSASLFinal(_, data) {
this._sasl.finish(data);
this._sasl = null;
}
_recvAuthenticationOk() {}
async _recvErrorResponse(m, payload) {
this._copyingOut = false;
this._lastErrorResponse = payload;
if (this._readyState == 'responding') {
await this._fwdBemsg(m);
}
}
async _recvReadyForQuery(m, { transactionStatus }) {
switch (this._readyState) {
case 'start':
this._startupComplete();
this._readyState = 'idle';
break;
case 'idle': // response start
this._readyState = 'responding';
await this._fwdBemsg(m);
break;
case 'responding': // response end
if (this._noExplicitTransactions && transactionStatus != 0x49 /*I*/) {
// TODO how to prevent next query from executing in transaction of previous query?
throw Error('postgres connection left in transaction', { cause: this._lastErrorResponse });
}
await this._fwdBemsg(m);
this._readyState = 'idle';
this._lastErrorResponse = null;
this._queuedResponseChannels.shift().end();
break;
}
this._transactionStatus = transactionStatus;
}
_startupComplete() {
// we dont need password anymore, its more secure to forget it
this._password = null;
// check if SASL auth is complete and server is verified
if (this._sasl) {
throw Error('incomplete SASL authentication');
}
// TODO impl require_auth
// https://www.postgresql.org/docs/16/libpq-connect.html#LIBPQ-CONNECT-REQUIRE-AUTH
this._pipeFemsgqPromise = this._pipeFemsgq();
if (this._wakeInterval > 0) {
this._wakeTimer = setInterval(
this._wakeIfStuck.bind(this),
this._wakeInterval,
);
}
}
async _recvNoticeResponse(m) {
if (this._readyState == 'responding') {
await this._fwdBemsg(m);
}
// TODO dispatchEvent for nonquery NoticeResponse
}
_recvParameterStatus(_, { parameter, value }) {
this.parameters[parameter] = value;
// TODO emit event ?
}
_recvBackendKeyData(_, backendKeyData) {
this._backendKeyData = backendKeyData;
}
_recvNotificationResponse(_, payload) {
// Detach onnotification call from _ioloop to avoid error swallowing.
Promise.resolve(payload).then(this.onnotification);
}
async _fwdBemsg({ tag, payload }) {
const chunk = new PgChunk();
chunk.tag = tag;
chunk.payload = payload;
this._wakeSupress = true;
await this._queuedResponseChannels[0].push(chunk);
}
_wakeIfStuck() {
// We will send 'wake' chunk if response
// is stuck longer then _wakeInterval
// so user have a chance to break loop
if (this._wakeSupress) {
this._wakeSupress = false;
return;
}
this._wake();
}
_wake() {
const resp = this._queuedResponseChannels[0];
if (this._readyState == 'responding' && resp.drained) {
const wakeChunk = new PgChunk();
wakeChunk.tag = 'wake';
resp.push(wakeChunk);
}
}
_log = (...args) => {
if (!this._debug) return;
console.error(...args);
}
}
class PgChunk extends Uint8Array {
tag;
payload = null;
rows = [];
copies = [];
}
function simpleQuery(out, stdinSignal, script, { stdin, stdins = [] } = 0, responseEndLock) {
out.push(new FrontendMessage.Query(script));
// TODO handle case when number of stdins is unknown
// should block tx and wait for CopyInResponse/CopyBothResponse
if (stdin) {
out.push(wrapCopyData(stdin, stdinSignal));
}
for (const stdin of stdins) {
out.push(wrapCopyData(stdin, stdinSignal));
}
// when CREATE_REPLICATION_SLOT or START_REPLICATION is emitted
// then no other queries should be emmited until ReadyForQuery is received.
// Seems that its a postgres server bug.
// This workaround looks like fragile hack but its not.
// Its dirty but safe enough because no comments or other statements can
// precede CREATE_REPLICATION_SLOT or START_REPLICATION
if (/^\s*(CREATE_REPLICATION_SLOT|START_REPLICATION)\b/.test(script)) {
out.push(responseEndLock);
} else {
out.push(new FrontendMessage.CopyFail('no stdin provided'));
}
}
function extendedQuery(out, stdinSignal, blocks) {
let signalBlock;
for (const m of blocks) {
if (signalBlock !== undefined) {
throw Error('signal block must be last block');
}
if ('signal' in m) {
signalBlock = m;
continue;
}
switch (m.message) {
case undefined:
case null: extendedQueryStatement(out, m, stdinSignal); break;
case 'Parse': extendedQueryParse(out, m); break;
case 'Bind': extendedQueryBind(out, m); break;
case 'Execute': extendedQueryExecute(out, m, stdinSignal); break;
case 'DescribeStatement': extendedQueryDescribeStatement(out, m); break;
case 'CloseStatement': extendedQueryCloseStatement(out, m); break;
case 'DescribePortal': extendedQueryDescribePortal(out, m); break;
case 'ClosePortal': extendedQueryClosePortal(out, m); break;
case 'Flush': out.push(new FrontendMessage.Flush()); break;
default: throw Error('unknown extended message');
}
}
out.push(new FrontendMessage.Sync());
return signalBlock?.signal;
}
function extendedQueryStatement(out, { statement, params = [], limit, binary, stdin, noBuffer }, stdinSignal) {
const paramTypes = params.map(({ type }) => type);
extendedQueryParse(out, { statement, paramTypes });
extendedQueryBind(out, { params, binary });
extendedQueryExecute(out, { limit, stdin, noBuffer }, stdinSignal);
// if (noBuffer) {
// out.push(new Flush());
// }
}
function extendedQueryParse(out, { statement, statementName, paramTypes = [] }) {
const paramTypeOids = paramTypes.map(PgType.resolve, PgType);
out.push(new FrontendMessage.Parse({ statement, statementName, paramTypeOids }));
}
function extendedQueryBind(out, { portal, statementName, binary, params = [] }) {
params = params.map(encodeParam);
out.push(new FrontendMessage.Bind({ portal, statementName, binary, params }));
function encodeParam({ value, type}) {
if (value == null) return null;
// treat Uint8Array values as already encoded,
// so user can receive value with unknown type as Uint8Array
// from extended .query and pass it back as parameter
// it also "encodes" bytea in efficient way instead of hex
if (value instanceof Uint8Array) return value;