-
Notifications
You must be signed in to change notification settings - Fork 390
/
pgcon.pyx
3196 lines (2721 loc) · 111 KB
/
pgcon.pyx
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
#
# This source file is part of the EdgeDB open source project.
#
# Copyright 2016-present MagicStack Inc. and the EdgeDB authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from typing import (
Any,
Callable,
Dict,
Optional,
)
import asyncio
import contextlib
import decimal
import codecs
import hashlib
import json
import logging
import os.path
import socket
import ssl as ssl_mod
import struct
import textwrap
import time
from collections import deque
cimport cython
cimport cpython
from . cimport cpythonx
from libc.stdint cimport int8_t, uint8_t, int16_t, uint16_t, \
int32_t, uint32_t, int64_t, uint64_t, \
UINT32_MAX
from edb import buildmeta
from edb import errors
from edb.edgeql import qltypes
from edb.schema import objects as s_obj
from edb.pgsql import common as pgcommon
from edb.pgsql.common import quote_ident as pg_qi
from edb.pgsql.common import quote_literal as pg_ql
from edb.pgsql import params as pg_params
from edb.pgsql import codegen as pg_codegen
from edb.server.pgproto cimport hton
from edb.server.pgproto cimport pgproto
from edb.server.pgproto.pgproto cimport (
WriteBuffer,
ReadBuffer,
FRBuffer,
frb_init,
frb_read,
frb_get_len,
frb_slice_from,
)
from edb.server import compiler
from edb.server import defines
from edb.server.cache cimport stmt_cache
from edb.server.dbview cimport dbview
from edb.server.protocol cimport pg_ext
from edb.server import pgconnparams
from edb.server import metrics
from edb.server.protocol cimport frontend
from edb.common import debug
from . import errors as pgerror
include "scram.pyx"
DEF DATA_BUFFER_SIZE = 100_000
DEF PREP_STMTS_CACHE = 100
DEF TCP_KEEPIDLE = 24
DEF TCP_KEEPINTVL = 2
DEF TCP_KEEPCNT = 3
DEF COPY_SIGNATURE = b"PGCOPY\n\377\r\n\0"
DEF TEXT_OID = 25
cdef object CARD_NO_RESULT = compiler.Cardinality.NO_RESULT
cdef object FMT_NONE = compiler.OutputFormat.NONE
cdef dict POSTGRES_SHUTDOWN_ERR_CODES = {
'57P01': 'admin_shutdown',
'57P02': 'crash_shutdown',
}
cdef bytes INIT_CON_SCRIPT = None
cdef str INIT_CON_SCRIPT_DATA = ''
cdef object EMPTY_SQL_STATE = b"{}"
cdef object logger = logging.getLogger('edb.server')
# The '_edgecon_state table' is used to store information about
# the current session. The `type` column is one character, with one
# of the following values:
#
# * 'C': a session-level config setting
#
# * 'B': a session-level config setting that's implemented by setting
# a corresponding Postgres config setting.
# * 'A': an instance-level config setting from command-line arguments
# * 'E': an instance-level config setting from environment variable
SETUP_TEMP_TABLE_SCRIPT = '''
CREATE TEMPORARY TABLE _edgecon_state (
name text NOT NULL,
value jsonb NOT NULL,
type text NOT NULL CHECK(
type = 'C' OR type = 'B' OR type = 'A' OR type = 'E'),
UNIQUE(name, type)
);
'''
SETUP_CONFIG_CACHE_SCRIPT = '''
CREATE TEMPORARY TABLE _config_cache (
source edgedb._sys_config_source_t,
value edgedb._sys_config_val_t NOT NULL
);
'''
def _build_init_con_script(*, check_pg_is_in_recovery: bool) -> bytes:
if check_pg_is_in_recovery:
pg_is_in_recovery = ('''
SELECT CASE WHEN pg_is_in_recovery() THEN
edgedb.raise(
NULL::bigint,
'read_only_sql_transaction',
msg => 'cannot use a hot standby'
)
END;
''').strip()
else:
pg_is_in_recovery = ''
return textwrap.dedent(f'''
{pg_is_in_recovery}
{SETUP_TEMP_TABLE_SCRIPT}
{SETUP_CONFIG_CACHE_SCRIPT}
{INIT_CON_SCRIPT_DATA}
PREPARE _clear_state AS
WITH x1 AS (
DELETE FROM _config_cache
)
DELETE FROM _edgecon_state WHERE type = 'C' OR type = 'B';
PREPARE _apply_state(jsonb) AS
INSERT INTO
_edgecon_state(name, value, type)
SELECT
(CASE
WHEN e->'type' = '"B"'::jsonb
THEN edgedb._apply_session_config(e->>'name', e->'value')
ELSE e->>'name'
END) AS name,
e->'value' AS value,
e->>'type' AS type
FROM
jsonb_array_elements($1::jsonb) AS e;
PREPARE _reset_session_config AS
SELECT edgedb._reset_session_config();
PREPARE _apply_sql_state(jsonb) AS
SELECT
e.key AS name,
pg_catalog.set_config(e.key, e.value, false) AS value
FROM
jsonb_each_text($1::jsonb) AS e;
''').strip().encode('utf-8')
def _set_tcp_keepalive(transport):
# TCP keepalive was initially added here for special cases where idle
# connections are dropped silently on GitHub Action running test suite
# against AWS RDS. We are keeping the TCP keepalive for generic
# Postgres connections as the kernel overhead is considered low, and
# in certain cases it does save us some reconnection time.
#
# In case of high-availability Postgres, TCP keepalive is necessary to
# disconnect from a failing master node, if no other failover information
# is available.
sock = transport.get_extra_info('socket')
sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
# TCP_KEEPIDLE: the time (in seconds) the connection needs to remain idle
# before TCP starts sending keepalive probes. This is socket.TCP_KEEPIDLE
# on Linux, and socket.TCP_KEEPALIVE on macOS from Python 3.10.
if hasattr(socket, 'TCP_KEEPIDLE'):
sock.setsockopt(socket.IPPROTO_TCP,
socket.TCP_KEEPIDLE, TCP_KEEPIDLE)
if hasattr(socket, 'TCP_KEEPALIVE'):
sock.setsockopt(socket.IPPROTO_TCP,
socket.TCP_KEEPALIVE, TCP_KEEPIDLE)
# TCP_KEEPINTVL: The time (in seconds) between individual keepalive probes.
if hasattr(socket, 'TCP_KEEPINTVL'):
sock.setsockopt(socket.IPPROTO_TCP,
socket.TCP_KEEPINTVL, TCP_KEEPINTVL)
# TCP_KEEPCNT: The maximum number of keepalive probes TCP should send
# before dropping the connection.
if hasattr(socket, 'TCP_KEEPCNT'):
sock.setsockopt(socket.IPPROTO_TCP,
socket.TCP_KEEPCNT, TCP_KEEPCNT)
async def _create_ssl_connection(protocol_factory, host, port, *,
loop, ssl_context, ssl_is_advisory,
connect_timeout):
async with asyncio.timeout(connect_timeout):
tr, pr = await loop.create_connection(
lambda: TLSUpgradeProto(loop, host, port,
ssl_context, ssl_is_advisory),
host, port)
_set_tcp_keepalive(tr)
tr.write(struct.pack('!ll', 8, 80877103)) # SSLRequest message.
try:
do_ssl_upgrade = await pr.on_data
except (Exception, asyncio.CancelledError):
tr.close()
raise
if do_ssl_upgrade:
try:
new_tr = await loop.start_tls(
tr, pr, ssl_context, server_hostname=host)
except (Exception, asyncio.CancelledError):
tr.close()
raise
else:
new_tr = tr
pg_proto = protocol_factory()
pg_proto.is_ssl = do_ssl_upgrade
pg_proto.connection_made(new_tr)
new_tr.set_protocol(pg_proto)
return new_tr, pg_proto
class _RetryConnectSignal(Exception):
pass
async def _connect(connargs, dbname, ssl):
loop = asyncio.get_running_loop()
host = connargs.get("host")
port = connargs.get("port")
sslmode = connargs.get('sslmode', pgconnparams.SSLMode.prefer)
timeout = connargs.get('connect_timeout')
try:
if host.startswith('/'):
addr = os.path.join(host, f'.s.PGSQL.{port}')
async with asyncio.timeout(timeout):
_, pgcon = await loop.create_unix_connection(
lambda: PGConnection(dbname, loop, connargs), addr)
else:
if ssl:
_, pgcon = await _create_ssl_connection(
lambda: PGConnection(dbname, loop, connargs),
host,
port,
loop=loop,
ssl_context=ssl,
ssl_is_advisory=(
sslmode == pgconnparams.SSLMode.prefer
),
connect_timeout=timeout,
)
else:
async with asyncio.timeout(timeout):
trans, pgcon = await loop.create_connection(
lambda: PGConnection(dbname, loop, connargs),
host=host, port=port)
_set_tcp_keepalive(trans)
except TimeoutError as ex:
raise pgerror.new(
pgerror.ERROR_CONNECTION_FAILURE,
"timed out connecting to backend",
) from ex
try:
await pgcon.connect()
except pgerror.BackendError as e:
pgcon.terminate()
if not e.code_is(pgerror.ERROR_INVALID_AUTHORIZATION_SPECIFICATION):
raise
if (
sslmode == pgconnparams.SSLMode.allow and not pgcon.is_ssl or
sslmode == pgconnparams.SSLMode.prefer and pgcon.is_ssl
):
# Trigger retry when:
# 1. First attempt with sslmode=allow, ssl=None failed
# 2. First attempt with sslmode=prefer, ssl=ctx failed while the
# server claimed to support SSL (returning "S" for SSLRequest)
# (likely because pg_hba.conf rejected the connection)
raise _RetryConnectSignal()
else:
# but will NOT retry if:
# 1. First attempt with sslmode=prefer failed but the server
# doesn't support SSL (returning 'N' for SSLRequest), because
# we already tried to connect without SSL thru ssl_is_advisory
# 2. Second attempt with sslmode=prefer, ssl=None failed
# 3. Second attempt with sslmode=allow, ssl=ctx failed
# 4. Any other sslmode
raise
return pgcon
async def connect(
connargs: Dict[str, Any],
dbname: str,
backend_params: pg_params.BackendRuntimeParams,
apply_init_script: bool = True,
):
global INIT_CON_SCRIPT
# This is different than parsing DSN and use the default sslmode=prefer,
# because connargs can be set manually thru set_connection_params(), and
# the caller should be responsible for aligning sslmode with ssl.
sslmode = connargs.get('sslmode', pgconnparams.SSLMode.disable)
ssl = connargs.get('ssl')
if sslmode == pgconnparams.SSLMode.allow:
try:
pgcon = await _connect(connargs, dbname, ssl=None)
except _RetryConnectSignal:
pgcon = await _connect(connargs, dbname, ssl=ssl)
elif sslmode == pgconnparams.SSLMode.prefer:
try:
pgcon = await _connect(connargs, dbname, ssl=ssl)
except _RetryConnectSignal:
pgcon = await _connect(connargs, dbname, ssl=None)
else:
pgcon = await _connect(connargs, dbname, ssl=ssl)
if (
backend_params.has_create_role
and backend_params.session_authorization_role
):
sup_role = backend_params.session_authorization_role
if connargs['user'] != sup_role:
# We used to use SET SESSION AUTHORIZATION here, there're some
# security differences over SET ROLE, but as we don't allow
# accessing Postgres directly through EdgeDB, SET ROLE is mostly
# fine here. (Also hosted backends like Postgres on DigitalOcean
# support only SET ROLE)
await pgcon.sql_execute(f'SET ROLE {pg_qi(sup_role)}'.encode())
if 'in_hot_standby' in pgcon.parameter_status:
# in_hot_standby is always present in Postgres 14 and above
if pgcon.parameter_status['in_hot_standby'] == 'on':
# Abort if we're connecting to a hot standby
pgcon.terminate()
raise pgerror.BackendError(fields=dict(
M="cannot use a hot standby",
C=pgerror.ERROR_READ_ONLY_SQL_TRANSACTION,
))
if apply_init_script:
if INIT_CON_SCRIPT is None:
INIT_CON_SCRIPT = _build_init_con_script(
# On lower versions of Postgres we use pg_is_in_recovery() to
# check if it is a hot standby, and error out if it is.
check_pg_is_in_recovery=(
'in_hot_standby' not in pgcon.parameter_status
),
)
await pgcon.sql_execute(INIT_CON_SCRIPT)
return pgcon
def set_init_con_script_data(cfg):
global INIT_CON_SCRIPT, INIT_CON_SCRIPT_DATA
INIT_CON_SCRIPT = None
INIT_CON_SCRIPT_DATA = (f'''
INSERT INTO _edgecon_state
SELECT * FROM jsonb_to_recordset({pg_ql(json.dumps(cfg))}::jsonb)
AS cfg(name text, value jsonb, type text);
''').strip()
class TLSUpgradeProto(asyncio.Protocol):
def __init__(self, loop, host, port, ssl_context, ssl_is_advisory):
self.on_data = loop.create_future()
self.host = host
self.port = port
self.ssl_context = ssl_context
self.ssl_is_advisory = ssl_is_advisory
def data_received(self, data):
if data == b'S':
self.on_data.set_result(True)
elif (self.ssl_is_advisory and
self.ssl_context.verify_mode == ssl_mod.CERT_NONE and
data == b'N'):
# ssl_is_advisory will imply that ssl.verify_mode == CERT_NONE,
# since the only way to get ssl_is_advisory is from
# sslmode=prefer. But be extra sure to disallow insecure
# connections when the ssl context asks for real security.
self.on_data.set_result(False)
else:
self.on_data.set_exception(
ConnectionError(
'PostgreSQL server at "{host}:{port}" '
'rejected SSL upgrade'.format(
host=self.host, port=self.port)))
def connection_lost(self, exc):
if not self.on_data.done():
if exc is None:
exc = ConnectionError('unexpected connection_lost() call')
self.on_data.set_exception(exc)
@cython.final
cdef class EdegDBCodecContext(pgproto.CodecContext):
cdef:
object _codec
def __cinit__(self):
self._codec = codecs.lookup('utf-8')
cpdef get_text_codec(self):
return self._codec
cdef is_encoding_utf8(self):
return True
cdef class PGMessage:
def __init__(
self,
PGAction action,
bytes stmt_name=None,
str portal_name=None,
args=None,
query_unit=None,
fe_settings=None,
injected=False,
):
self.action = action
self.stmt_name = stmt_name
self.orig_portal_name = portal_name
if portal_name:
self.portal_name = b'u' + portal_name.encode("utf-8")
else:
self.portal_name = b''
self.args = args
self.query_unit = query_unit
self.fe_settings = fe_settings
self.valid = True
self.injected = injected
if self.query_unit is not None:
self.frontend_only = self.query_unit.frontend_only
else:
self.frontend_only = False
cdef inline bint is_frontend_only(self):
return self.frontend_only
def invalidate(self):
self.valid = False
cdef inline bint is_valid(self):
return self.valid
cdef inline bint is_injected(self):
return self.injected
def as_injected(self) -> PGMessage:
return PGMessage(
action=self.action,
stmt_name=self.stmt_name,
portal_name=self.orig_portal_name,
args=self.args,
query_unit=self.query_unit,
fe_settings=self.fe_settings,
injected=True,
)
def __repr__(self):
rv = []
if self.action == PGAction.START_IMPLICIT_TX:
rv.append("START_IMPLICIT_TX")
elif self.action == PGAction.PARSE:
rv.append("PARSE")
elif self.action == PGAction.BIND:
rv.append("BIND")
elif self.action == PGAction.DESCRIBE_STMT:
rv.append("DESCRIBE_STMT")
elif self.action == PGAction.DESCRIBE_STMT_ROWS:
rv.append("DESCRIBE_STMT_ROWS")
elif self.action == PGAction.DESCRIBE_PORTAL:
rv.append("DESCRIBE_PORTAL")
elif self.action == PGAction.EXECUTE:
rv.append("EXECUTE")
elif self.action == PGAction.CLOSE_STMT:
rv.append("CLOSE_STMT")
elif self.action == PGAction.CLOSE_PORTAL:
rv.append("CLOSE_PORTAL")
elif self.action == PGAction.FLUSH:
rv.append("FLUSH")
elif self.action == PGAction.SYNC:
rv.append("SYNC")
if self.stmt_name is not None:
rv.append(f"stmt_name={self.stmt_name}")
if self.orig_portal_name is not None:
rv.append(f"portal_name={self.orig_portal_name!r}")
if self.args is not None:
rv.append(f"args={self.args}")
rv.append(f"frontend_only={self.is_frontend_only()}")
rv.append(f"injected={self.is_injected()}")
if self.query_unit is not None:
rv.append(f"query_unit={self.query_unit}")
if len(rv) > 1:
rv.insert(1, ":")
return " ".join(rv)
@cython.final
cdef class PGConnection:
def __init__(self, dbname, loop, addr):
self.buffer = ReadBuffer()
self.loop = loop
self.dbname = dbname
self.transport = None
self.msg_waiter = None
self.prep_stmts = stmt_cache.StatementsCache(maxsize=PREP_STMTS_CACHE)
self.connected_fut = loop.create_future()
self.connected = False
self.waiting_for_sync = 0
self.xact_status = PQTRANS_UNKNOWN
self.backend_pid = -1
self.backend_secret = -1
self.parameter_status = dict()
self.last_parse_prep_stmts = []
self.debug = debug.flags.server_proto
self.log_listeners = []
self.pgaddr = addr
self.server = None
self.tenant = None
self.is_system_db = False
self.close_requested = False
self.pinned_by = None
self.idle = True
self.cancel_fut = None
self._is_ssl = False
# Set to the error the connection has been aborted with
# by the backend.
self.aborted_with_error = None
self.last_state = dbview.DEFAULT_STATE
cpdef set_stmt_cache_size(self, int maxsize):
self.prep_stmts.resize(maxsize)
@property
def is_ssl(self):
return self._is_ssl
@is_ssl.setter
def is_ssl(self, value):
self._is_ssl = value
def debug_print(self, *args):
print(
'::PGCONN::',
hex(id(self)),
f'pgpid: {self.backend_pid}',
*args,
)
def get_pgaddr(self):
return self.pgaddr
def in_tx(self):
return (
self.xact_status == PQTRANS_INTRANS or
self.xact_status == PQTRANS_INERROR
)
def is_cancelling(self):
return self.cancel_fut is not None
def start_pg_cancellation(self):
if self.cancel_fut is not None:
raise RuntimeError('another cancellation is in progress')
self.cancel_fut = self.loop.create_future()
def finish_pg_cancellation(self):
assert self.cancel_fut is not None
self.cancel_fut.set_result(True)
def get_server_parameter_status(self, parameter: str) -> Optional[str]:
return self.parameter_status.get(parameter)
def abort(self):
if not self.transport:
return
self.close_requested = True
self.transport.abort()
self.transport = None
self.connected = False
self.prep_stmts.clear()
def terminate(self):
if not self.transport:
return
self.close_requested = True
self.write(WriteBuffer.new_message(b'X').end_message())
self.transport.close()
self.transport = None
self.connected = False
self.prep_stmts.clear()
if self.msg_waiter and not self.msg_waiter.done():
self.msg_waiter.set_exception(ConnectionAbortedError())
self.msg_waiter = None
async def close(self):
self.terminate()
def set_tenant(self, tenant):
self.tenant = tenant
self.server = tenant.server
def mark_as_system_db(self):
if self.tenant.get_backend_runtime_params().has_create_database:
assert defines.EDGEDB_SYSTEM_DB in self.dbname
self.is_system_db = True
def add_log_listener(self, cb):
self.log_listeners.append(cb)
async def listen_for_sysevent(self):
try:
if self.tenant.get_backend_runtime_params().has_create_database:
assert defines.EDGEDB_SYSTEM_DB in self.dbname
await self.sql_execute(b'LISTEN __edgedb_sysevent__;')
except Exception:
try:
self.abort()
finally:
raise
async def signal_sysevent(self, event, **kwargs):
if self.tenant.get_backend_runtime_params().has_create_database:
assert defines.EDGEDB_SYSTEM_DB in self.dbname
event = json.dumps({
'event': event,
'server_id': self.server._server_id,
'args': kwargs,
})
query = f"""
SELECT pg_notify(
'__edgedb_sysevent__',
{pg_ql(event)}
)
""".encode()
await self.sql_execute(query)
async def sync(self):
if self.waiting_for_sync:
raise RuntimeError('a "sync" has already been requested')
self.before_command()
try:
self.waiting_for_sync += 1
self.write(_SYNC_MESSAGE)
while True:
if not self.buffer.take_message():
await self.wait_for_message()
mtype = self.buffer.get_message_type()
if mtype == b'Z':
self.parse_sync_message()
return
else:
self.fallthrough()
finally:
await self.after_command()
async def wait_for_sync(self):
error = None
try:
while True:
if not self.buffer.take_message():
await self.wait_for_message()
mtype = self.buffer.get_message_type()
if mtype == b'Z':
return self.parse_sync_message()
elif mtype == b'E':
# ErrorResponse
er_cls, fields = self.parse_error_message()
error = er_cls(fields=fields)
else:
if not self.parse_notification():
if PG_DEBUG or self.debug:
self.debug_print(f'PGCon.wait_for_sync: discarding '
f'{chr(mtype)!r} message')
self.buffer.discard_message()
finally:
if error is not None:
# Postgres might send an ErrorResponse if, e.g.
# in implicit transaction fails to commit due to
# serialization conflicts.
raise error
cdef inline str get_tenant_label(self):
if self.tenant is None:
return "system"
else:
return self.tenant.get_instance_name()
cdef bint before_prepare(
self,
bytes stmt_name,
int dbver,
WriteBuffer outbuf,
):
cdef bint parse = 1
while self.prep_stmts.needs_cleanup():
stmt_name_to_clean = self.prep_stmts.cleanup_one()
if self.debug:
self.debug_print(f"discarding ps {stmt_name_to_clean!r}")
outbuf.write_buffer(
self.make_clean_stmt_message(stmt_name_to_clean))
if stmt_name in self.prep_stmts:
if self.prep_stmts[stmt_name] == dbver:
parse = 0
else:
if self.debug:
self.debug_print(f"discarding ps {stmt_name!r}")
outbuf.write_buffer(
self.make_clean_stmt_message(stmt_name))
del self.prep_stmts[stmt_name]
return parse
cdef write_sync(self, WriteBuffer outbuf):
outbuf.write_bytes(_SYNC_MESSAGE)
self.waiting_for_sync += 1
def _build_apply_state_req(self, bytes serstate, WriteBuffer out):
cdef:
WriteBuffer buf
if self.debug:
self.debug_print("Syncing state: ", serstate)
buf = WriteBuffer.new_message(b'B')
buf.write_bytestring(b'') # portal name
buf.write_bytestring(b'_clear_state') # statement name
buf.write_int16(0) # number of format codes
buf.write_int16(0) # number of parameters
buf.write_int16(0) # number of result columns
out.write_buffer(buf.end_message())
buf = WriteBuffer.new_message(b'E')
buf.write_bytestring(b'') # portal name
buf.write_int32(0) # limit: 0 - return all rows
out.write_buffer(buf.end_message())
buf = WriteBuffer.new_message(b'B')
buf.write_bytestring(b'') # portal name
buf.write_bytestring(b'_reset_session_config') # statement name
buf.write_int16(0) # number of format codes
buf.write_int16(0) # number of parameters
buf.write_int16(0) # number of result columns
out.write_buffer(buf.end_message())
buf = WriteBuffer.new_message(b'E')
buf.write_bytestring(b'') # portal name
buf.write_int32(0) # limit: 0 - return all rows
out.write_buffer(buf.end_message())
if serstate is not None:
buf = WriteBuffer.new_message(b'B')
buf.write_bytestring(b'') # portal name
buf.write_bytestring(b'_apply_state') # statement name
buf.write_int16(1) # number of format codes
buf.write_int16(1) # binary
buf.write_int16(1) # number of parameters
buf.write_int32(len(serstate) + 1)
buf.write_byte(1) # jsonb format version
buf.write_bytes(serstate)
buf.write_int16(0) # number of result columns
out.write_buffer(buf.end_message())
buf = WriteBuffer.new_message(b'E')
buf.write_bytestring(b'') # portal name
buf.write_int32(0) # limit: 0 - return all rows
out.write_buffer(buf.end_message())
def _build_apply_sql_state_req(self, bytes state, WriteBuffer out):
cdef:
WriteBuffer buf
buf = WriteBuffer.new_message(b'B')
buf.write_bytestring(b'') # portal name
buf.write_bytestring(b'_reset_session_config') # statement name
buf.write_int16(0) # number of format codes
buf.write_int16(0) # number of parameters
buf.write_int16(0) # number of result columns
out.write_buffer(buf.end_message())
buf = WriteBuffer.new_message(b'E')
buf.write_bytestring(b'') # portal name
buf.write_int32(0) # limit: 0 - return all rows
out.write_buffer(buf.end_message())
if state != EMPTY_SQL_STATE:
buf = WriteBuffer.new_message(b'B')
buf.write_bytestring(b'') # portal name
buf.write_bytestring(b'_apply_sql_state') # statement name
buf.write_int16(1) # number of format codes
buf.write_int16(1) # binary
buf.write_int16(1) # number of parameters
buf.write_int32(len(state) + 1)
buf.write_byte(1) # jsonb format version
buf.write_bytes(state)
buf.write_int16(0) # number of result columns
out.write_buffer(buf.end_message())
buf = WriteBuffer.new_message(b'E')
buf.write_bytestring(b'') # portal name
buf.write_int32(0) # limit: 0 - return all rows
out.write_buffer(buf.end_message())
async def _parse_apply_state_resp(self, int expected_completed):
cdef:
int num_completed = 0
while True:
if not self.buffer.take_message():
await self.wait_for_message()
mtype = self.buffer.get_message_type()
if mtype == b'2' or mtype == b'D':
# BindComplete or Data
self.buffer.discard_message()
elif mtype == b'E':
er_cls, er_fields = self.parse_error_message()
raise er_cls(fields=er_fields)
elif mtype == b'C':
self.buffer.discard_message()
num_completed += 1
if num_completed == expected_completed:
return
else:
self.fallthrough()
@contextlib.asynccontextmanager
async def parse_execute_script_context(self):
self.before_command()
started_at = time.monotonic()
try:
try:
yield
finally:
while self.waiting_for_sync:
await self.wait_for_sync()
finally:
metrics.backend_query_duration.observe(
time.monotonic() - started_at, self.get_tenant_label()
)
await self.after_command()
cdef send_query_unit_group(
self, object query_unit_group, bint sync,
object bind_datas, bytes state,
ssize_t start, ssize_t end, int dbver, object parse_array
):
# parse_array is an array of booleans for output with the same size as
# the query_unit_group, indicating if each unit is freshly parsed
cdef:
WriteBuffer out
WriteBuffer buf
WriteBuffer bind_data
bytes stmt_name
ssize_t idx = start
out = WriteBuffer.new()
parsed = set()
if state is not None and start == 0:
self._build_apply_state_req(state, out)
for query_unit, bind_data in zip(
query_unit_group.units[start:end], bind_datas):
if query_unit.system_config:
raise RuntimeError(
"CONFIGURE INSTANCE command is not allowed in scripts"
)
stmt_name = query_unit.sql_hash
if stmt_name:
assert len(query_unit.sql) == 1
# The same EdgeQL query may show up twice in the same script.
# We just need to know and skip if we've already parsed the
# same query within current send batch, because self.prep_stmts
# will be updated before the next batch, with maybe a different
# dbver after DDL.
if stmt_name not in parsed and self.before_prepare(
stmt_name, dbver, out
):
buf = WriteBuffer.new_message(b'P')
buf.write_bytestring(stmt_name)
buf.write_bytestring(query_unit.sql[0])
buf.write_int16(0)
out.write_buffer(buf.end_message())
parse_array[idx] = True
parsed.add(stmt_name)
buf = WriteBuffer.new_message(b'B')
buf.write_bytestring(b'') # portal name
buf.write_bytestring(stmt_name)
buf.write_buffer(bind_data)
out.write_buffer(buf.end_message())
buf = WriteBuffer.new_message(b'E')
buf.write_bytestring(b'') # portal name
buf.write_int32(0) # limit: 0 - return all rows
out.write_buffer(buf.end_message())
else:
for sql in query_unit.sql:
buf = WriteBuffer.new_message(b'P')
buf.write_bytestring(b'') # statement name
buf.write_bytestring(sql)
buf.write_int16(0)
out.write_buffer(buf.end_message())
buf = WriteBuffer.new_message(b'B')
buf.write_bytestring(b'') # portal name
buf.write_bytestring(b'') # statement name
buf.write_buffer(bind_data)
out.write_buffer(buf.end_message())
buf = WriteBuffer.new_message(b'E')
buf.write_bytestring(b'') # portal name
buf.write_int32(0) # limit: 0 - return all rows
out.write_buffer(buf.end_message())
idx += 1
if sync:
self.write_sync(out)