-
Notifications
You must be signed in to change notification settings - Fork 443
Expand file tree
/
Copy pathpg_ext.pyx
More file actions
2078 lines (1837 loc) · 74.3 KB
/
pg_ext.pyx
File metadata and controls
2078 lines (1837 loc) · 74.3 KB
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 2022-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.
#
import codecs
import collections
import contextlib
import copy
import encodings.aliases
import logging
import hashlib
import json
import os
import sys
import time
import uuid
from collections import deque
from typing import Sequence
cimport cython
import immutables
from libc.stdint cimport int32_t, int16_t, uint32_t
from edb import errors
from edb.common import debug
from edb.common.log import current_tenant
from edb.pgsql.common import setting_to_sql
from edb.pgsql.parser import exceptions as parser_errors
import edb.pgsql.parser.parser as pg_parser
cimport edb.pgsql.parser.parser as pg_parser
from edb.server import args as srvargs
from edb.server import defines, metrics
from edb.server import tenant as edbtenant
from edb.server.compiler import dbstate, enums
from edb.server.pgcon import errors as pgerror
from edb.server.pgcon.pgcon cimport PGAction, PGMessage
from edb.server.protocol cimport frontend
DEFAULT_SETTINGS = dbstate.DEFAULT_SQL_SETTINGS
DEFAULT_FE_SETTINGS = dbstate.DEFAULT_SQL_FE_SETTINGS
cdef object logger = logging.getLogger('edb.server')
cdef object DEFAULT_STATE = None
encodings.aliases.aliases["sql_ascii"] = "ascii"
class ExtendedQueryError(Exception):
pass
@contextlib.contextmanager
def managed_error():
try:
yield
except Exception as e:
raise ExtendedQueryError(e)
@cython.final
cdef class PreparedStmt:
def __init__(self, PGMessage parse_action, pg_parser.Source source):
self.parse_action = parse_action
self.source = source
@cython.final
cdef class ConnectionView:
def __init__(self):
self._in_tx_explicit = False
self._in_tx_implicit = False
# Kepp track of backend settings so that we can sync to use different
# backend connections (pgcon) within the same frontend connection,
# see serialize_state() below and its usages in pgcon.pyx.
self._settings = DEFAULT_SETTINGS
self._in_tx_settings = None
# Frontend-only settings are defined by the high-level compiler, and
# tracked only here, syncing between the compiler process,
# see current_fe_settings(), fe_transaction_state() and usages below.
self._local_fe_defaults = DEFAULT_FE_SETTINGS
self._fe_settings = self._local_fe_defaults
self._in_tx_fe_settings = None
self._in_tx_fe_local_settings = None
self._in_tx_portals = {}
self._in_tx_new_portals = set()
self._in_tx_savepoints = collections.deque()
self._tx_error = False
global DEFAULT_STATE
if DEFAULT_STATE is None:
DEFAULT_STATE = json.dumps(
[
{
"type": "P",
"name": key,
"value": setting_to_sql(key, val),
}
for key, val in DEFAULT_SETTINGS.items()
] + [
{
"type": "S",
"name": key,
"value": setting_to_sql(key, val),
}
for key, val in DEFAULT_FE_SETTINGS.items()
]
).encode("utf-8")
self._session_state_db_cache = (
DEFAULT_SETTINGS, DEFAULT_FE_SETTINGS, DEFAULT_STATE
)
cdef _init_user_configs(self, username, tenant):
assert self._fe_settings is DEFAULT_FE_SETTINGS
assert self._in_tx_fe_local_settings is None
role = tenant.get_roles()[username]
apply_default = role['apply_access_policies_pg_default']
if apply_default is not None:
self._local_fe_defaults = self._local_fe_defaults.set(
'apply_access_policies_pg',
(str(apply_default).lower(),),
)
self._fe_settings = self._local_fe_defaults
cpdef inline current_fe_settings(self):
if self.in_tx():
# For easier access, _in_tx_fe_local_settings is always a superset
# of _in_tx_fe_settings; _in_tx_fe_settings only keeps track of
# non-local settings, so that the local settings don't go across
# transaction boundaries; this must be consistent with dbstate.py.
return self._in_tx_fe_local_settings or self._local_fe_defaults
else:
return self._fe_settings
cdef inline fe_transaction_state(self):
return dbstate.SQLTransactionState(
in_tx=self.in_tx(),
settings=self._fe_settings,
in_tx_settings=self._in_tx_fe_settings,
in_tx_local_settings=self._in_tx_fe_local_settings,
savepoints=[sp[:3] for sp in self._in_tx_savepoints],
)
cpdef inline bint in_tx(self):
return self._in_tx_explicit or self._in_tx_implicit
cdef inline _reset_tx_state(
self, bint chain_implicit, bint chain_explicit
):
# This method is a part of ending a transaction. COMMIT must be handled
# before calling this method. If any of the chain_* flag is set, a new
# transaction will be opened immediately after clean-up.
self._in_tx_implicit = chain_implicit
self._in_tx_explicit = chain_explicit
self._in_tx_settings = self._settings if self.in_tx() else None
self._in_tx_fe_settings = self._fe_settings if self.in_tx() else None
self._in_tx_fe_local_settings = self._in_tx_fe_settings
self._in_tx_portals.clear()
self._in_tx_new_portals.clear()
self._in_tx_savepoints.clear()
self._tx_error = False
def start_implicit(self):
if self._in_tx_implicit:
raise RuntimeError("already in implicit transaction")
else:
if not self.in_tx():
self._in_tx_settings = self._settings
self._in_tx_fe_settings = self._fe_settings
self._in_tx_fe_local_settings = self._fe_settings
self._in_tx_implicit = True
def end_implicit(self):
if not self._in_tx_implicit:
raise RuntimeError("not in implicit transaction")
if self._in_tx_explicit:
# There is an explicit transaction, nothing to do other than
# turning off the implicit flag so that we can start_implicit again
self._in_tx_implicit = False
else:
# Commit or rollback the implicit transaction
if not self._tx_error:
self._settings = self._in_tx_settings
self._fe_settings = self._in_tx_fe_settings
self._reset_tx_state(False, False)
def on_success(self, unit: dbstate.SQLQueryUnit):
# Handle ROLLBACK first before self._tx_error
if unit.tx_action == dbstate.TxAction.ROLLBACK:
if not self._in_tx_explicit:
# TODO: warn about "no tx" but still rollback implicit
pass
self._reset_tx_state(self._in_tx_implicit, unit.tx_chain)
elif unit.tx_action == dbstate.TxAction.ROLLBACK_TO_SAVEPOINT:
if not self._in_tx_explicit:
if self._in_tx_implicit:
self._tx_error = True
raise errors.TransactionError(
"ROLLBACK TO SAVEPOINT can only be used "
"in transaction blocks"
)
while self._in_tx_savepoints:
(
sp_name,
fe_settings,
fe_local_settings,
settings,
new_portals,
) = self._in_tx_savepoints[-1]
for name in new_portals:
self._in_tx_portals.pop(name, None)
if sp_name == unit.sp_name:
new_portals.clear()
self._in_tx_settings = settings
self._in_tx_fe_settings = fe_settings
self._in_tx_fe_local_settings = fe_local_settings
self._in_tx_new_portals = new_portals
break
else:
self._in_tx_savepoints.pop()
else:
self._tx_error = True
raise errors.TransactionError(
f'savepoint "{unit.sp_name}" does not exist'
)
elif self._tx_error:
raise errors.TransactionError(
"current transaction is aborted, "
"commands ignored until end of transaction block"
)
elif unit.tx_action == dbstate.TxAction.START:
if self._in_tx_explicit:
# TODO: warning: there is already a transaction in progress
pass
else:
if not self.in_tx():
self._in_tx_settings = self._settings
self._in_tx_fe_settings = self._fe_settings
self._in_tx_fe_local_settings = self._fe_settings
self._in_tx_explicit = True
elif unit.tx_action == dbstate.TxAction.COMMIT:
if not self._in_tx_explicit:
# TODO: warning: there is no transaction in progress
# but we still commit implicit transactions if any
pass
if self.in_tx():
self._settings = self._in_tx_settings
self._fe_settings = self._in_tx_fe_settings
self._reset_tx_state(self._in_tx_implicit, unit.tx_chain)
elif unit.tx_action == dbstate.TxAction.DECLARE_SAVEPOINT:
if not self._in_tx_explicit:
raise errors.TransactionError(
"SAVEPOINT can only be used in transaction blocks"
)
self._in_tx_new_portals = set()
self._in_tx_savepoints.append((
unit.sp_name,
self._in_tx_fe_settings,
self._in_tx_fe_local_settings,
self._in_tx_settings,
self._in_tx_new_portals,
))
elif unit.tx_action == dbstate.TxAction.RELEASE_SAVEPOINT:
pass
if unit.set_vars:
# only session settings here
if unit.set_vars == {None: None}: # RESET ALL
if self.in_tx():
self._in_tx_settings = DEFAULT_SETTINGS
self._in_tx_fe_settings = self._local_fe_defaults
self._in_tx_fe_local_settings = self._local_fe_defaults
else:
self._settings = DEFAULT_SETTINGS
self._fe_settings = self._local_fe_defaults
else:
if self.in_tx():
if unit.frontend_only:
if not unit.is_local:
settings = self._in_tx_fe_settings.mutate()
for k, v in unit.set_vars.items():
if v is None:
if k in self._local_fe_defaults:
settings[k] = self._local_fe_defaults[k]
else:
settings.pop(k, None)
else:
settings[k] = v
self._in_tx_fe_settings = settings.finish()
settings = self._in_tx_fe_local_settings.mutate()
else:
settings = self._in_tx_settings.mutate()
elif not unit.is_local:
if unit.frontend_only:
settings = self._fe_settings.mutate()
else:
settings = self._settings.mutate()
else:
return
for k, v in unit.set_vars.items():
if v is None:
if unit.frontend_only and k in self._local_fe_defaults:
settings[k] = self._local_fe_defaults[k]
else:
settings.pop(k, None)
else:
settings[k] = v
if self.in_tx():
if unit.frontend_only:
self._in_tx_fe_local_settings = settings.finish()
else:
self._in_tx_settings = settings.finish()
else:
if unit.frontend_only:
self._fe_settings = settings.finish()
else:
self._settings = settings.finish()
def on_error(self):
self._tx_error = True
cpdef inline close_portal(self, str name):
try:
return self._in_tx_portals.pop(name)
except KeyError:
raise pgerror.new(
pgerror.ERROR_INVALID_CURSOR_NAME,
f"cursor \"{name}\" does not exist",
) from None
cpdef inline close_portal_if_exists(self, str name):
return self._in_tx_portals.pop(name, None)
def create_portal(self, str name, query_unit):
if not self.in_tx():
raise RuntimeError(
"portals cannot be created outside a transaction"
)
if name and name in self._in_tx_portals:
raise pgerror.new(
pgerror.ERROR_DUPLICATE_CURSOR,
f"cursor \"{name}\" already exists",
)
self._in_tx_portals[name] = query_unit
cdef inline find_portal(self, str name):
try:
return self._in_tx_portals[name]
except KeyError:
raise pgerror.new(
pgerror.ERROR_INVALID_CURSOR_NAME,
f"cursor \"{name}\" does not exist",
) from None
cdef inline portal_exists(self, str name):
return name in self._in_tx_portals
def serialize_state(self):
if self.in_tx():
raise errors.InternalServerError(
'no need to serialize state while in transaction')
if (
self._settings == DEFAULT_SETTINGS
and self._fe_settings == DEFAULT_FE_SETTINGS
):
return DEFAULT_STATE
if self._session_state_db_cache is not None:
if self._session_state_db_cache[:2] == (
self._settings, self._fe_settings
):
return self._session_state_db_cache[-1]
rv = json.dumps(
[
{"type": "P", "name": key, "value": setting_to_sql(key, val)}
for key, val in self._settings.items()
] + [
{"type": "S", "name": key, "value": setting_to_sql(key, val)}
for key, val in self._fe_settings.items()
]
).encode("utf-8")
self._session_state_db_cache = (self._settings, self._fe_settings, rv)
return rv
cdef bint needs_commit_after_state_sync(self):
return any(
tx_conf in self._settings
for tx_conf in [
"default_transaction_isolation",
"default_transaction_deferrable",
"default_transaction_read_only",
]
)
cdef class PgConnection(frontend.FrontendConnection):
interface = "sql"
def __init__(self, server, sslctx, endpoint_security, **kwargs):
super().__init__(server, None, **kwargs)
self._dbview = ConnectionView()
self._id = str(<int32_t><uint32_t>(int(self._id) % (2 ** 32)))
self.prepared_stmts = {} # via extended query Parse
self.sql_prepared_stmts = {} # via a PREPARE statement
self.sql_prepared_stmts_map = {}
# Tracks prepared statements of operations
# on *other* prepared statements.
self.wrapping_prepared_stmts = {}
self.ignore_till_sync = False
self.sslctx = sslctx
self.endpoint_security = endpoint_security
self.is_tls = False
self._disable_cache = debug.flags.disable_qcache
self._disable_normalization = debug.flags.edgeql_disable_normalization
cdef _main_task_created(self):
self.server.on_pgext_client_connected(self)
# complete the client initial message with a mocked type
self.buffer.feed_data(b'\xff')
def connection_lost(self, exc):
self.server.on_pgext_client_disconnected(self)
super().connection_lost(exc)
cdef is_in_tx(self):
return self._dbview.in_tx()
cdef write_error(self, exc):
cdef WriteBuffer buf
if self.debug and not isinstance(exc, errors.BackendUnavailableError):
self.debug_print('EXCEPTION', type(exc).__name__, exc)
from edb.common.markup import dump
dump(exc)
if debug.flags.server and not isinstance(
exc, errors.BackendUnavailableError
):
self.loop.call_exception_handler({
'message': (
'an error in edgedb protocol'
),
'exception': exc,
'protocol': self,
'transport': self._transport,
})
message = str(exc)
buf = WriteBuffer.new_message(b'E')
if isinstance(exc, pgerror.BackendError):
if exc.code_is(pgerror.ERROR_SERIALIZATION_FAILURE):
metrics.transaction_serialization_errors.inc(
1.0, self.get_tenant_label()
)
elif isinstance(exc, parser_errors.PSqlUnsupportedError):
exc = pgerror.FeatureNotSupported(str(exc))
elif isinstance(exc, parser_errors.PSqlSyntaxError):
exc = pgerror.new(
pgerror.ERROR_SYNTAX_ERROR,
str(exc),
P=str(exc.cursor_pos),
)
elif isinstance(exc, errors.AuthenticationError):
exc = pgerror.InvalidAuthSpec(str(exc), severity="FATAL")
elif isinstance(exc, errors.BinaryProtocolError):
exc = pgerror.ProtocolViolation(
str(exc), detail=exc.details, severity="FATAL"
)
elif isinstance(exc, errors.UnsupportedFeatureError):
args = {}
if exc.line >= 0:
args['L'] = str(exc.line)
if exc.position >= 0:
args['P'] = str(exc.position + 1)
exc = pgerror.new(
pgerror.ERROR_FEATURE_NOT_SUPPORTED,
str(exc),
**args,
)
elif isinstance(exc, errors.EdgeDBError):
args = dict(hint=exc.hint, detail=exc.details)
if exc.line >= 0:
args['L'] = str(exc.line)
if exc.position >= 0:
# pg uses 1 based indexes for showing errors.
args['P'] = str(exc.position + 1)
exc = pgerror.new(
exc.pgext_code or pgerror.ERROR_INTERNAL_ERROR,
str(exc),
**args,
)
if isinstance(exc, errors.TransactionSerializationError):
metrics.transaction_serialization_errors.inc(
1.0, self.get_tenant_label()
)
else:
exc = pgerror.new(
pgerror.ERROR_INTERNAL_ERROR,
str(exc),
severity="FATAL",
)
for k, v in exc.fields.items():
buf.write_byte(ord(k))
buf.write_str(v, "utf-8")
buf.write_byte(b'\0')
self.write(buf.end_message())
async def _handshake(self):
cdef int16_t proto_ver_major, proto_ver_minor
for first in (True, False):
if not self.buffer.take_message():
await self.wait_for_message(report_idling=True)
proto_ver_major = self.buffer.read_int16()
proto_ver_minor = self.buffer.read_int16()
if proto_ver_major == 1234:
if proto_ver_minor == 5678: # CancelRequest
pid = str(self.buffer.read_int32())
secret = self.buffer.read_bytes(4)
self.buffer.finish_message()
if self.debug:
self.debug_print("CancelRequest", pid, secret)
self.server.cancel_pgext_connection(pid, secret)
self.request_stop()
break
elif proto_ver_minor == 5679: # SSLRequest
if self.debug:
self.debug_print("SSLRequest")
if not first:
raise pgerror.ProtocolViolation(
"found multiple SSLRequest", severity="FATAL"
)
self.buffer.finish_message()
if self._transport is None:
raise ConnectionAbortedError
if self.debug:
self.debug_print("S for SSLRequest")
self._transport.write(b'S')
# complete the next client message with a mocked type
self.buffer.feed_data(b'\xff')
self._transport = await self.loop.start_tls(
self._transport,
self,
self.sslctx,
server_side=True,
)
tenant = self.server.retrieve_tenant(
self._transport.get_extra_info("ssl_object")
)
if tenant is edbtenant.host_tenant:
tenant = None
self.tenant = tenant
if self.tenant is not None:
current_tenant.set(self.tenant.get_instance_name())
self.is_tls = True
elif proto_ver_minor == 5680: # GSSENCRequest
raise pgerror.FeatureNotSupported(
"GSSENCRequest is not supported", severity="FATAL"
)
else:
raise pgerror.FeatureNotSupported(severity="FATAL")
elif proto_ver_major == 3 and proto_ver_minor == 0:
# StartupMessage with 3.0 protocol
if self.debug:
self.debug_print("StartupMessage")
if (
not self.is_tls and self.endpoint_security ==
srvargs.ServerEndpointSecurityMode.Tls
):
raise pgerror.InvalidAuthSpec(
"TLS required due to server endpoint security",
severity="FATAL",
)
await super()._handshake()
break
else:
raise pgerror.ProtocolViolation(
"invalid protocol version", severity="FATAL"
)
def cancel(self, secret):
if (
self.secret == secret and
self._pinned_pgcon is not None and
not self._pinned_pgcon.idle and
self.tenant.accept_new_tasks
):
self.tenant.create_task(
self.tenant.cancel_pgcon_operation(self._pinned_pgcon),
interruptable=False,
)
def debug_print(self, *args):
print("::PGEXT::", f"id:{self._id}", *args, file=sys.stderr)
cdef WriteBuffer _make_authentication_sasl_initial(self, list methods):
cdef WriteBuffer msg_buf
msg_buf = WriteBuffer.new_message(b'R')
msg_buf.write_int32(10)
for method in methods:
msg_buf.write_bytestring(method)
msg_buf.write_byte(b'\0')
msg_buf.end_message()
if self.debug:
self.debug_print("AuthenticationSASL:", *methods)
return msg_buf
cdef _expect_sasl_initial_response(self):
mtype = self.buffer.get_message_type()
if mtype != b'p':
raise pgerror.ProtocolViolation(
f'expected SASL response, got message type {mtype}')
selected_mech = self.buffer.read_null_str()
try:
client_first = self.buffer.read_len_prefixed_bytes()
except BufferError:
client_first = None
self.buffer.finish_message()
if self.debug:
self.debug_print(
"SASLInitialResponse:",
selected_mech,
len(client_first) if client_first else client_first,
)
if not client_first:
# The client didn't send the Client Initial Response
# in SASLInitialResponse, this is an error.
raise pgerror.ProtocolViolation(
'client did not send the Client Initial Response '
'data in SASLInitialResponse')
return selected_mech, client_first
cdef WriteBuffer _make_authentication_sasl_msg(
self, bytes data, bint final
):
cdef WriteBuffer msg_buf
msg_buf = WriteBuffer.new_message(b'R')
if final:
msg_buf.write_int32(12)
else:
msg_buf.write_int32(11)
msg_buf.write_bytes(data)
msg_buf.end_message()
if self.debug:
self.debug_print(
"AuthenticationSASLFinal" if final
else "AuthenticationSASLContinue",
len(data),
)
return msg_buf
cdef bytes _expect_sasl_response(self):
mtype = self.buffer.get_message_type()
if mtype != b'p':
raise pgerror.ProtocolViolation(
f'expected SASL response, got message type {mtype}')
client_final = self.buffer.consume_message()
if self.debug:
self.debug_print("SASLResponse", len(client_final))
return client_final
def check_readiness(self):
if self.tenant.is_blocked():
readiness_reason = self.tenant.get_readiness_reason()
msg = "the server is not accepting requests"
if readiness_reason:
msg = f"{msg}: {readiness_reason}"
raise pgerror.CannotConnectNowError(msg)
elif not self.tenant.is_online():
readiness_reason = self.tenant.get_readiness_reason()
msg = "the server is going offline"
if readiness_reason:
msg = f"{msg}: {readiness_reason}"
raise pgerror.CannotConnectNowError(msg)
async def authenticate(self):
cdef:
WriteBuffer msg_buf
WriteBuffer buf
self.check_readiness()
params = {}
while True:
name = self.buffer.read_null_str()
if not name:
break
value = self.buffer.read_null_str()
params[name.decode("utf-8")] = value.decode("utf-8")
if self.debug:
self.debug_print("StartupMessage params:", params)
if "user" not in params:
raise pgerror.ProtocolViolation(
"StartupMessage must have a \"user\"", severity="FATAL"
)
self.buffer.finish_message()
user = params["user"]
database = params.get("database", user)
if "client_encoding" in params:
encoding = params["client_encoding"]
client_encoding = encodings.normalize_encoding(encoding).upper()
try:
codecs.lookup(client_encoding)
except LookupError:
raise pgerror.new(
pgerror.ERROR_INVALID_PARAMETER_VALUE,
f'invalid value for parameter "client_encoding": "{encoding}"',
)
self._dbview._settings = self._dbview._settings.set(
"client_encoding", (client_encoding,)
)
else:
client_encoding = "UTF8"
logger.debug('received pg connection request by %s to database %s',
user, database)
if database == '__default__':
database = self.tenant.default_database
elif (
database == defines.EDGEDB_OLD_DEFAULT_DB
and self.tenant.maybe_get_db(
dbname=defines.EDGEDB_OLD_DEFAULT_DB
) is None
):
database = self.tenant.default_database
user = self.tenant.resolve_user_name(user)
await self._authenticate(user, database, params)
logger.debug('successfully authenticated %s in database %s',
user, database)
if not self.tenant.is_database_connectable(database):
raise pgerror.InvalidAuthSpec(
f'database {database!r} does not accept connections',
severity="FATAL",
)
self.database = self.tenant.get_db(dbname=database)
await self.database.introspection()
self.dbname = database
self.username = user
self._dbview._init_user_configs(user, self.tenant)
buf = WriteBuffer()
msg_buf = WriteBuffer.new_message(b'R')
msg_buf.write_int32(0)
msg_buf.end_message()
buf.write_buffer(msg_buf)
if self.debug:
self.debug_print("AuthenticationOk")
self.secret = os.urandom(4)
msg_buf = WriteBuffer.new_message(b'K')
msg_buf.write_int32(int(self._id))
msg_buf.write_bytes(self.secret)
msg_buf.end_message()
buf.write_buffer(msg_buf)
if self.debug:
self.debug_print("BackendKeyData")
async with self.with_pgcon() as conn:
for name, value in conn.parameter_status.items():
msg_buf = WriteBuffer.new_message(b'S')
msg_buf.write_str(name, "utf-8")
if name == "client_encoding":
value = client_encoding
elif name == "server_version":
value = str(defines.PGEXT_POSTGRES_VERSION)
elif name == "session_authorization":
value = user
elif name == "application_name":
value = self.tenant.get_instance_name()
msg_buf.write_str(value, "utf-8")
msg_buf.end_message()
buf.write_buffer(msg_buf)
if self.debug:
self.debug_print(f"ParameterStatus: {name}={value}")
self.write(buf)
# Try to sync the settings, especially client_encoding.
await conn.sql_apply_state(self._dbview)
self.write(self.ready_for_query())
self.flush()
cdef inline WriteBuffer ready_for_query(self):
cdef WriteBuffer msg_buf
self.ignore_till_sync = False
msg_buf = WriteBuffer.new_message(b'Z')
if self._dbview.in_tx():
if self._dbview._tx_error:
msg_buf.write_byte(b'E')
else:
msg_buf.write_byte(b'T')
else:
msg_buf.write_byte(b'I')
return msg_buf.end_message()
def on_success(self, query_unit):
cdef:
PreparedStmt stmt
if query_unit.deallocate is not None:
stmt_name = query_unit.deallocate.stmt_name
self.sql_prepared_stmts.pop(stmt_name, None)
self.sql_prepared_stmts_map.pop(stmt_name, None)
self.prepared_stmts.pop(stmt_name, None)
# If any wrapping prepared statements referred to this
# prepared statement, invalidate them.
for wrapping_ps in self.wrapping_prepared_stmts.pop(stmt_name, []):
stmt = self.prepared_stmts.get(wrapping_ps)
if stmt is not None:
stmt.parse_action.invalidate()
def on_error(self, query_unit):
cdef:
PreparedStmt stmt
if query_unit.prepare is not None:
stmt_name = query_unit.prepare.stmt_name
self.sql_prepared_stmts.pop(stmt_name, None)
self.sql_prepared_stmts_map.pop(stmt_name, None)
self.prepared_stmts.pop(stmt_name, None)
# If any wrapping prepared statements referred to this
# prepared statement, invalidate them.
for wrapping_ps in self.wrapping_prepared_stmts.pop(stmt_name, []):
stmt = self.prepared_stmts.get(wrapping_ps)
if stmt is not None:
stmt.parse_action.invalidate()
async def main_step(self, char mtype):
try:
await self._main_step(mtype)
except pgerror.BackendError as ex:
self.write_error(ex)
self.write(self.ready_for_query())
self.flush()
self.request_stop()
async def _main_step(self, char mtype):
cdef:
WriteBuffer buf
ConnectionView dbv
dbv = self._dbview
self.check_readiness()
if self.debug:
self.debug_print("main_step", repr(chr(mtype)))
if self.ignore_till_sync:
self.debug_print("ignoring")
if mtype == b'S': # Sync
self.buffer.finish_message()
if self.debug:
self.debug_print("Sync")
if dbv._in_tx_implicit:
actions = [PGMessage(PGAction.SYNC)]
async with self.with_pgcon() as conn:
success, _ = await conn.sql_extended_query(
actions, self, self.database.dbver, dbv)
self.ignore_till_sync = not success
else:
self.ignore_till_sync = False
self.write(self.ready_for_query())
self.flush()
elif mtype == b'X': # Terminate
self.buffer.finish_message()
if self.debug:
self.debug_print("Terminate")
self.close()
return True
elif self.ignore_till_sync:
self.buffer.discard_message()
elif mtype == b'Q': # Query
try:
query = self.buffer.read_null_str()
metrics.query_size.observe(
len(query), self.get_tenant_label(), 'sql'
)
query_str = query.decode("utf8")
self.buffer.finish_message()
if self.debug:
self.debug_print("Query", query_str)
actions = await self.simple_query(query_str)
del query_str, query
except Exception as ex:
self.write_error(ex)
self.write(self.ready_for_query())
self.flush()
else:
async with self.with_pgcon() as conn:
try:
_, rq_sent = await conn.sql_extended_query(
actions,
self,
self.database.dbver,
dbv,
)
except Exception as ex:
self.write_error(ex)
self.write(self.ready_for_query())
else:
if not rq_sent:
self.write(self.ready_for_query())
self.flush()
elif (
mtype == b'P' or mtype == b'B' or mtype == b'D' or mtype == b'E' or
# One of Parse, Bind, Describe or Execute starts an extended query
mtype == b'C' # or Close
):
try:
actions, exception = await self.extended_query()
except ExtendedQueryError as ex:
actions = ()
exception = ex
else:
async with self.with_pgcon() as conn:
try:
success, _ = await conn.sql_extended_query(
actions, self, self.database.dbver, dbv)
self.ignore_till_sync = not success
except Exception as ex:
self.write_error(ex)
self.flush()
self.ignore_till_sync = True
if exception:
self.write_error(exception.args[0])
self.flush()
self.ignore_till_sync = True
elif mtype == b'H': # Flush
self.buffer.finish_message()
if self.debug:
self.debug_print("Flush")
self.flush()
else:
if self.debug:
self.debug_print(
"MESSAGE", chr(mtype), self.buffer.consume_message()
)
raise pgerror.FeatureNotSupported()
async def simple_query(self, query_str: str) -> list[PGMessage]:
cdef: