forked from ravendb/ravendb-python-client
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrequest_executor.py
More file actions
1514 lines (1226 loc) · 62 KB
/
Copy pathrequest_executor.py
File metadata and controls
1514 lines (1226 loc) · 62 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
from __future__ import annotations
import datetime
import inspect
import json
import logging
import os
from concurrent.futures import ThreadPoolExecutor, Future, FIRST_COMPLETED, wait, ALL_COMPLETED
import uuid
from json import JSONDecodeError
from threading import Timer, Semaphore, Lock, local
import requests
from copy import copy
from ravendb.primitives import constants
from ravendb.documents.session.event_args import BeforeRequestEventArgs, FailedRequestEventArgs, SucceedRequestEventArgs
from ravendb.exceptions.exceptions import (
AllTopologyNodesDownException,
UnsuccessfulRequestException,
DatabaseDoesNotExistException,
AuthorizationException,
RequestedNodeUnavailableException,
)
from ravendb.documents.operations.configuration.operations import GetClientConfigurationOperation
from ravendb.exceptions.exception_dispatcher import ExceptionDispatcher
from ravendb.exceptions.raven_exceptions import ClientVersionMismatchException
from ravendb.http.http_cache import HttpCache, ItemFlags, ReleaseCacheItem
from ravendb.http.misc import (
ReadBalanceBehavior,
ResponseDisposeHandling,
LoadBalanceBehavior,
Broadcast,
AggressiveCacheMode,
AggressiveCacheOptions,
)
from ravendb.http.raven_command import RavenCommand, RavenCommandResponseType
from ravendb.http.server_node import ServerNode
from ravendb.http.topology import Topology, NodeStatus, NodeSelector, CurrentIndexAndNode, UpdateTopologyParameters
from ravendb.http import topology_local_cache
from ravendb.serverwide.commands import GetDatabaseTopologyCommand, GetClusterTopologyCommand
from http import HTTPStatus
from typing import TYPE_CHECKING, List, Dict, Tuple, Optional
if TYPE_CHECKING:
from ravendb.documents.session import SessionInfo
from ravendb.documents.conventions import DocumentConventions
from typing import Union, Callable, Any, Optional
class RequestExecutor:
__INITIAL_TOPOLOGY_ETAG = -2
__GLOBAL_APPLICATION_IDENTIFIER = uuid.uuid4()
CLIENT_VERSION = "7.2.3"
logger = logging.getLogger("request_executor")
# todo: initializer should take also cryptography certificates
def __init__(
self,
database_name: str,
conventions: DocumentConventions,
certificate_path: Optional[str] = None,
trust_store_path: Optional[str] = None,
thread_pool_executor: Optional[ThreadPoolExecutor] = None,
initial_urls: Optional[List[str]] = None,
):
self.__update_topology_timer: Union[None, Timer] = None
self.conventions = copy(conventions)
self._node_selector: NodeSelector = None
self.__default_timeout: datetime.timedelta = conventions.request_timeout
self._cache: HttpCache = HttpCache()
self.__certificate_path = certificate_path
self.__trust_store_path = trust_store_path
self.__topology_taken_from_node: Union[None, ServerNode] = None
self.__update_client_configuration_semaphore = Semaphore(1)
self.__update_database_topology_semaphore = Semaphore(1)
self.__failed_nodes_timers: Dict[ServerNode, NodeStatus] = {}
self._database_name = database_name
self._last_returned_response: Union[None, datetime.datetime] = None
self._thread_pool_executor = (
ThreadPoolExecutor(max_workers=10) if not thread_pool_executor else thread_pool_executor
)
self.number_of_server_requests = 0
self._topology_etag: Union[None, int] = None
self._client_configuration_etag: Union[None, int] = None
self._disable_topology_updates: Union[None, bool] = None
self._disable_client_configuration_updates: Union[None, bool] = None
self._last_server_version: Union[None, str] = None
self.__http_session: Union[None, requests.Session] = None
self.first_broadcast_attempt_timeout: Union[None, datetime.timedelta] = (
conventions.first_broadcast_attempt_timeout
)
self.second_broadcast_attempt_timeout: Union[None, datetime.timedelta] = (
conventions.second_broadcast_attempt_timeout
)
self._first_topology_update_task: Union[None, Future] = None
self._last_known_urls: Union[None, List[str]] = None
self._disposed: Union[None, bool] = None
self.__synchronized_lock = Lock()
self._aggressive_caching_local = local()
# --- events ---
self._on_before_request: List[Callable[[BeforeRequestEventArgs], Any]] = []
self.__on_failed_request: List[Callable[[FailedRequestEventArgs], None]] = []
self.__on_succeed_request: List[Callable[[SucceedRequestEventArgs], None]] = []
self._on_topology_updated: List[Callable[[Topology], None]] = []
@property
def aggressive_caching(self) -> Optional["AggressiveCacheOptions"]:
# threading.local mirrors C#'s AsyncLocal<AggressiveCacheOptions>: each thread
# (each request context) gets its own setting. Without this, one thread enabling
# aggressive caching would bleed into every other thread on the same executor.
return getattr(self._aggressive_caching_local, "value", None)
@aggressive_caching.setter
def aggressive_caching(self, value: Optional["AggressiveCacheOptions"]) -> None:
self._aggressive_caching_local.value = value
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.close()
def close(self):
if self._disposed:
return
self._disposed = True
self._cache.close()
if self.__update_topology_timer:
self.__update_topology_timer.cancel()
self._dispose_all_failed_nodes_timers()
if self.__http_session is not None:
self.__http_session.close()
@property
def certificate_path(self) -> str:
return self.__certificate_path
@property
def trust_store_path(self) -> str:
return self.__trust_store_path
@property
def url(self) -> Union[None, str]:
if self._node_selector is None:
return None
preferred_node = self._node_selector.get_preferred_node()
return preferred_node.current_node.url if preferred_node is not None else None
@property
def last_server_version(self):
return self._last_server_version
@property
def topology_etag(self) -> int:
return self._topology_etag
@property
def topology(self) -> Topology:
return self._node_selector.topology if self._node_selector else None
@property
def http_session(self):
http_session = self.__http_session
if http_session:
return http_session
self.__http_session = self.__create_http_session()
return self.__http_session
def __create_http_session(self) -> requests.Session:
session = requests.session()
session.cert = self.__certificate_path
session.verify = self.__trust_store_path if self.__trust_store_path else True
return session
@property
def cache(self) -> HttpCache:
return self._cache
@property
def topology_nodes(self) -> List[ServerNode]:
return self.topology.nodes if self.topology else None
@property
def client_configuration_etag(self) -> int:
return self._client_configuration_etag
@property
def default_timeout(self) -> datetime.timedelta:
return self.__default_timeout
@default_timeout.setter
def default_timeout(self, value: datetime.timedelta) -> None:
self.__default_timeout = value
@property
def preferred_node(self) -> CurrentIndexAndNode:
self._ensure_node_selector()
return self._node_selector.get_preferred_node()
def get_requested_node(self, node_tag: str, throw_if_contains_failures: bool = False) -> CurrentIndexAndNode:
self._ensure_node_selector()
current_index_and_node = self._node_selector.get_requested_node(node_tag)
if throw_if_contains_failures and not self._node_selector.node_is_available(
current_index_and_node.current_index
):
raise RequestedNodeUnavailableException(
f"Requested node {node_tag} currently unavailable, please try again later."
)
return current_index_and_node
def get_fastest_node(self) -> CurrentIndexAndNode:
self._ensure_node_selector()
return self._node_selector.get_fastest_node()
def get_node_by_session_id(self, session_id: int = None) -> CurrentIndexAndNode:
self._ensure_node_selector()
return self._node_selector.get_node_by_session_id(session_id)
def __on_failed_request_invoke(self, url: str, e: Exception):
for event in self.__on_failed_request:
event(FailedRequestEventArgs(self._database_name, url, e, None, None))
def __on_failed_request_invoke_details(
self, url: str, e: Exception, request: Optional[requests.Request], response: Optional[requests.Response]
) -> None:
for event in self.__on_failed_request:
event(FailedRequestEventArgs(self._database_name, url, e, request, response))
def _on_succeed_request_invoke(
self, database: str, url: str, response: requests.Response, request: requests.Request, attempt_number: int
):
for event in self.__on_succeed_request:
event(SucceedRequestEventArgs(database, url, response, request, attempt_number))
def _on_topology_updated_invoke(self, topology: Topology) -> None:
for event in self._on_topology_updated:
event(topology)
def add_on_succeed_request(self, event: Callable[[SucceedRequestEventArgs], None]):
self.__on_succeed_request.append(event)
def remove_on_succeed_request(self, event: Callable[[SucceedRequestEventArgs], None]):
self.__on_succeed_request.remove(event)
def add_on_failed_request(self, event: Callable[[FailedRequestEventArgs], None]):
self.__on_failed_request.append(event)
def remove_on_failed_request(self, event: Callable[[FailedRequestEventArgs], None]):
self.__on_failed_request.remove(event)
def add_on_before_request(self, event: Callable[[BeforeRequestEventArgs], None]):
self._on_before_request.append(event)
def remove_on_before_request(self, event: Callable[[BeforeRequestEventArgs], None]):
self._on_before_request.remove(event)
def add_on_topology_updated(self, event: Callable[[Topology], None]):
self._on_topology_updated.append(event)
def remove_on_topology_updated(self, event: Callable[[Topology], None]):
self._on_topology_updated.remove(event)
@classmethod
def create(
cls,
initial_urls: List[str],
database_name: str,
conventions: DocumentConventions,
certificate_path: Optional[str] = None,
trust_store_path: Optional[str] = None,
thread_pool_executor: Optional[ThreadPoolExecutor] = None,
) -> RequestExecutor:
executor = cls(database_name, conventions, certificate_path, trust_store_path, thread_pool_executor)
executor._first_topology_update_task = executor._first_topology_update(
initial_urls, cls.__GLOBAL_APPLICATION_IDENTIFIER
)
return executor
@classmethod
def create_for_single_node_with_configuration_updates(
cls,
url: str,
database_name: str,
conventions: DocumentConventions,
certificate_path: Optional[str] = None,
trust_store_path: Optional[str] = None,
thread_pool_executor: Optional[ThreadPoolExecutor] = None,
) -> RequestExecutor:
executor = cls.create_for_single_node_without_configuration_updates(
url, database_name, conventions, certificate_path, trust_store_path, thread_pool_executor
)
executor._disable_client_configuration_updates = False
return executor
@classmethod
def create_for_single_node_without_configuration_updates(
cls,
url: str,
database_name: str,
conventions: DocumentConventions,
certificate_path: Optional[str] = None,
trust_store_path: Optional[str] = None,
thread_pool_executor: Optional[ThreadPoolExecutor] = None,
) -> RequestExecutor:
initial_urls = cls.validate_urls([url])
executor = cls(database_name, conventions, certificate_path, trust_store_path, thread_pool_executor)
topology = Topology(-1, [ServerNode(initial_urls[0], database_name)])
executor._node_selector = NodeSelector(topology, thread_pool_executor)
executor._topology_etag = cls.__INITIAL_TOPOLOGY_ETAG
executor._disable_topology_updates = True
executor._disable_client_configuration_updates = True
return executor
def _update_client_configuration_async(self, server_node: ServerNode) -> Future:
if self._disposed:
future = Future()
future.set_result(None)
return future
def __run_async():
self.__update_client_configuration_semaphore.acquire()
old_disable_client_configuration_updates = self._disable_client_configuration_updates
self._disable_client_configuration_updates = True
try:
if self._disposed:
return
command = GetClientConfigurationOperation.GetClientConfigurationCommand()
self.execute(server_node, None, command, False, None)
result = command.result
if not result:
return
self.conventions.update_from(result.configuration)
self.client_configuration_etag = result.etag
finally:
self._disable_client_configuration_updates = old_disable_client_configuration_updates
self.__update_client_configuration_semaphore.release()
return self._thread_pool_executor.submit(__run_async)
def update_topology_async(self, parameters: UpdateTopologyParameters) -> Future:
if not parameters:
raise ValueError("Parameters cannot be None")
if self._disable_topology_updates:
fut = Future()
fut.set_result(False)
return fut
if self._disposed:
fut = Future()
fut.set_result(False)
return fut
def __supply_async():
# prevent double topology updates if execution takes too much time
# --> in cases with transient issues
lock_taken = self.__update_database_topology_semaphore.acquire(timeout=parameters.timeout_in_ms)
if not lock_taken:
return False
try:
if self._disposed:
return False
command = GetDatabaseTopologyCommand(
parameters.debug_tag,
parameters.application_identifier if self.conventions.send_application_identifier else None,
)
self.execute(parameters.node, None, command, False, None)
topology = command.result
if self._node_selector is None:
self._node_selector = NodeSelector(topology, self._thread_pool_executor)
if self.conventions.read_balance_behavior == ReadBalanceBehavior.FASTEST_NODE:
self._node_selector.schedule_speed_test()
elif self._node_selector.on_update_topology(topology, parameters.force_update):
self._dispose_all_failed_nodes_timers()
if self.conventions.read_balance_behavior == ReadBalanceBehavior.FASTEST_NODE:
self._node_selector.schedule_speed_test()
self._topology_etag = self._node_selector.topology.etag
if not self.conventions.disable_topology_cache and self.conventions.topology_cache_location:
topology_local_cache.try_save(
self.conventions.topology_cache_location,
topology_local_cache.server_hash(parameters.node.url, self._database_name),
self._node_selector.topology,
topology_local_cache.DATABASE_TOPOLOGY_EXTENSION,
)
self._on_topology_updated_invoke(topology)
except Exception as e:
if not self._disposed:
raise e
finally:
self.__update_database_topology_semaphore.release()
return True
return self._thread_pool_executor.submit(__supply_async)
def _first_topology_update(self, input_urls: List[str], application_identifier: Union[None, uuid.UUID]) -> Future:
initial_urls = self.validate_urls(input_urls)
errors: List[Tuple[str, Exception]] = []
def __run(errors: list):
for url in initial_urls:
try:
server_node = ServerNode(url, self._database_name)
update_parameters = UpdateTopologyParameters(server_node)
update_parameters.timeout_in_ms = 0x7FFFFFFF
update_parameters.debug_tag = "first-topology-update"
update_parameters.application_identifier = application_identifier
self.update_topology_async(update_parameters).result()
self.__initialize_update_topology_timer()
self.__topology_taken_from_node = server_node
return
except Exception as e:
if isinstance(e.__cause__, AuthorizationException):
self._last_known_urls = initial_urls
raise e.__cause__
if isinstance(e.__cause__, DatabaseDoesNotExistException):
self._last_known_urls = initial_urls
raise e.__cause__
errors.append((url, e))
# all initial urls unreachable - fall back to the on-disk topology cache when enabled
for url in initial_urls:
cached_topology = self._try_load_topology_from_cache(url)
if cached_topology is not None:
self._node_selector = NodeSelector(cached_topology, self._thread_pool_executor)
self._topology_etag = cached_topology.etag
self.__initialize_update_topology_timer()
self.__topology_taken_from_node = ServerNode(url, self._database_name)
return
topology = Topology(
self._topology_etag,
(
self.topology_nodes
if self.topology_nodes
else list(map(lambda url_val: ServerNode(url_val, self._database_name, "!"), initial_urls))
),
)
self._node_selector = NodeSelector(topology, self._thread_pool_executor)
if initial_urls:
self.__initialize_update_topology_timer()
return
self._last_known_urls = initial_urls
# todo: details from exceptions in inner_list
return self._thread_pool_executor.submit(__run, errors)
def _try_load_topology_from_cache(self, url):
return topology_local_cache.try_load(
None if self.conventions.disable_topology_cache else self.conventions.topology_cache_location,
topology_local_cache.server_hash(url, self._database_name),
topology_local_cache.DATABASE_TOPOLOGY_EXTENSION,
)
@staticmethod
def validate_urls(initial_urls: List[str]) -> List[str]:
# todo: implement validation
return initial_urls
def __initialize_update_topology_timer(self):
if self.__update_topology_timer is not None:
return
with self.__synchronized_lock:
if self.__update_topology_timer is not None:
return
self.__update_topology_timer = Timer(60, self.__update_topology_callback)
def _dispose_all_failed_nodes_timers(self) -> None:
for node, status in self.__failed_nodes_timers.items():
status.close()
self.__failed_nodes_timers.clear()
def execute_command(self, command: RavenCommand, session_info: Optional[SessionInfo] = None) -> None:
self._throw_if_disposed_at_entry()
topology_update = self._first_topology_update_task
if (
topology_update is not None
and (topology_update.done() and (not topology_update.exception()) and (not topology_update.cancelled()))
or self._disable_topology_updates
):
current_index_and_node = self.choose_node_for_request(command, session_info)
self.execute(
current_index_and_node.current_node, current_index_and_node.current_index, command, True, session_info
)
else:
self.__unlikely_execute(command, topology_update, session_info)
@staticmethod
def _throw_object_disposed() -> None:
raise RuntimeError("The request executor has already been disposed and cannot be used")
def _throw_if_disposed_at_entry(self) -> None:
# Entry guard from C# RequestExecutor.ExecuteAsync (v7.2.3).
from ravendb.documents.session.document_session_operations.in_memory_document_session_operations import (
_DISABLE_DISPOSE_CHECKS,
)
if _DISABLE_DISPOSE_CHECKS:
return
if self._disposed:
self._throw_object_disposed()
def execute(
self,
chosen_node: ServerNode = None,
node_index: int = None,
command: RavenCommand = None,
should_retry: bool = None,
session_info: SessionInfo = None,
ret_request: bool = False,
) -> Union[None, requests.Request]:
if command.failover_topology_etag == RequestExecutor.__INITIAL_TOPOLOGY_ETAG:
command.failover_topology_etag = RequestExecutor.__INITIAL_TOPOLOGY_ETAG
if self._node_selector and self._node_selector.topology:
topology = self._node_selector.topology
if topology.etag:
command.failover_topology_etag = topology.etag
request = self.__create_request(chosen_node, command)
url = request.url
if not request:
return
if ret_request:
request_ref = request
if not request:
return
no_caching = session_info.no_caching if session_info else False
cached_item, change_vector, cached_value = self._get_from_cache(command, not no_caching, url)
# Aggressive-cache short-circuit: serve from local cache without touching the server.
# All five conditions must hold:
# 1. Session didn't disable caching.
# 2. Aggressive caching is active on this thread.
# 3. The command doesn't opt out (streaming commands set can_cache_aggressively=False).
# 4. The item is actually in cache AND young enough.
# 5. Under TRACK_CHANGES mode, the cache generation must not have advanced since we
# retrieved the item — if it has, _AggressiveCacheInvalidator saw a server change and
# bumped the generation, so we must revalidate.
if (
not no_caching
and self.aggressive_caching is not None
and command.can_cache_aggressively
and cached_item.item is not None
and cached_item.age < self.aggressive_caching.duration
and (
not cached_item.might_have_been_modified
or self.aggressive_caching.mode != AggressiveCacheMode.TRACK_CHANGES
)
):
if ItemFlags.NOT_FOUND in cached_item.item.flags:
# Cached 404: only trust it when it was itself received inside an aggressive-
# cache context (AGGRESSIVELY_CACHED flag set by set_not_found). A 404 cached
# outside aggressive mode might have been a transient error; re-fetch it.
if ItemFlags.AGGRESSIVELY_CACHED in cached_item.item.flags:
command.set_response(None, True)
return
elif cached_value is not None:
command.set_response(cached_value, True)
return
with cached_item:
# todo: try get from cache
self._set_request_headers(session_info, change_vector, request)
command.number_of_attempts = command.number_of_attempts + 1
attempt_num = command.number_of_attempts
for func in self._on_before_request:
func(BeforeRequestEventArgs(self._database_name, url, request, attempt_num))
response = self._send_request_to_server(
chosen_node, node_index, command, should_retry, session_info, request, url
)
if response is None:
return
refresh_tasks = self._refresh_if_needed(chosen_node, response)
command.status_code = response.status_code
response_dispose = ResponseDisposeHandling.AUTOMATIC
try:
if response.status_code == HTTPStatus.NOT_MODIFIED:
self._on_succeed_request_invoke(self._database_name, url, response, request, attempt_num)
cached_item.not_modified()
if command.response_type == RavenCommandResponseType.OBJECT:
command.set_response(cached_value, True)
return
if response.status_code >= 400:
if not self._handle_unsuccessful_response(
chosen_node,
node_index,
command,
request,
response,
url,
session_info,
should_retry,
):
db_missing_header = response.headers.get("Database-Missing", None)
if db_missing_header is not None:
raise DatabaseDoesNotExistException(db_missing_header)
self._throw_failed_to_contact_all_nodes(command, request)
return # we either handled this already in the unsuccessful response or we are throwing
self._on_succeed_request_invoke(self._database_name, url, response, request, attempt_num)
response_dispose = command.process_response(self._cache, response, url)
self._last_returned_response = datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=None)
finally:
if response_dispose == ResponseDisposeHandling.AUTOMATIC:
response.close()
if len(refresh_tasks) > 0:
try:
wait(refresh_tasks, return_when=ALL_COMPLETED)
except:
raise
def _refresh_if_needed(self, chosen_node: ServerNode, response: requests.Response) -> List[Future]:
refresh_topology = response.headers.get(constants.Headers.REFRESH_TOPOLOGY, False)
refresh_client_configuration = response.headers.get(constants.Headers.REFRESH_CLIENT_CONFIGURATION, False)
refresh_task = Future()
refresh_task.set_result(False)
refresh_client_configuration_task = Future()
refresh_client_configuration_task.set_result(None)
if refresh_topology:
update_parameters = UpdateTopologyParameters(chosen_node)
update_parameters.timeout_in_ms = 0
update_parameters.debug_tag = "refresh-topology-header"
refresh_task = self.update_topology_async(update_parameters)
if refresh_client_configuration:
refresh_client_configuration_task = self._update_client_configuration_async(chosen_node)
return [refresh_task, refresh_client_configuration_task]
def _send_request_to_server(
self,
chosen_node: ServerNode,
node_index: int,
command: RavenCommand,
should_retry: bool,
session_info: SessionInfo,
request: requests.Request,
url: str,
) -> Optional[requests.Response]:
try:
self.number_of_server_requests += 1
timeout = command.timeout if command.timeout else self.__default_timeout
if not timeout:
return self.__send(chosen_node, command, session_info, request)
else:
try:
return self.__send(chosen_node, command, session_info, request)
except requests.Timeout as t:
if not should_retry:
if command.failed_nodes is None:
command.failed_nodes = {}
command.failed_nodes[chosen_node] = t
raise t
if not self.__handle_server_down(
url, chosen_node, node_index, command, request, None, t, session_info, should_retry
):
self._throw_failed_to_contact_all_nodes(command, request)
return None
except (requests.RequestException, OSError) as e:
# RDBC-948: https://issues.hibernatingrhinos.com/issue/RDBC-948/Python-client-connection-failover-breaks-with-unknown-DNS-name-or-server-is-down.
# Handle failover on network errors from both requests and the OS:
# - RequestException covers requests' network stack (connect, TLS, proxies, etc.).
# - OSError covers socket-level issues like DNS getaddrinfo on some platforms.
# Different OS/resolvers surface the same fault differently; catching both mirrors the C# client
# (HttpRequestException/SocketException) and makes failover reliable.
if not should_retry:
raise
if not self.__handle_server_down(
url, chosen_node, node_index, command, request, None, e, session_info, should_retry
):
self._throw_failed_to_contact_all_nodes(command, request)
return None
def __send(
self, chosen_node: ServerNode, command: RavenCommand, session_info: SessionInfo, request: requests.Request
) -> requests.Response:
response: Optional[requests.Response] = None
if self.should_execute_on_all(chosen_node, command):
response = self.__execute_on_all_to_figure_out_the_fastest(chosen_node, command)
else:
response = command.send(self.http_session, request)
# PERF: The reason to avoid rechecking every time is that servers wont change so rapidly
# and therefore we dismish its cost by orders of magnitude just doing it
# once in a while. We dont care also about the potential race conditions that may happen
# here mainly because the idea is to have a lax mechanism to recheck that is at least
# orders of magnitude faster than currently.
if chosen_node.should_update_server_version():
server_version = self.__try_get_server_version(response)
if server_version is not None:
chosen_node.update_server_version(server_version)
self._last_server_version = chosen_node.last_server_version
if session_info and session_info.last_cluster_transaction_index:
# if we reach here it means that sometime a cluster transaction has occurred against this database.
# Since the current executed command can be dependent on that, we have to wait for the cluster transaction.
# But we can't do that if the server is an old one.
if not self._last_server_version or self._last_server_version.lower() < "4.1":
raise ClientVersionMismatchException(
f"The server on {chosen_node.url} has an old version and"
f" can't perform the command since this command dependent on"
f" a cluster transaction which this node doesn't support"
)
return response
def choose_node_for_request(self, cmd: RavenCommand, session_info: SessionInfo) -> CurrentIndexAndNode:
# When we disable topology updates we cannot rely on the node tag,
# Because the initial topology will not have them
if not self._disable_topology_updates:
if cmd.selected_node_tag and not cmd.selected_node_tag.isspace():
return self._node_selector.get_requested_node(cmd.selected_node_tag)
if self.conventions.load_balance_behavior == LoadBalanceBehavior.USE_SESSION_CONTEXT:
if session_info is not None and session_info.can_use_load_balance_behavior:
return self._node_selector.get_node_by_session_id(session_info.session_id)
if not cmd.is_read_request():
return self._node_selector.get_preferred_node()
if self.conventions.read_balance_behavior == ReadBalanceBehavior.NONE:
return self._node_selector.get_preferred_node()
elif self.conventions.read_balance_behavior == ReadBalanceBehavior.ROUND_ROBIN:
return self._node_selector.get_node_by_session_id(session_info.session_id if session_info else 0)
elif self.conventions.read_balance_behavior == ReadBalanceBehavior.FASTEST_NODE:
return self._node_selector.get_fastest_node()
raise RuntimeError()
def __unlikely_execute(
self, command: RavenCommand, topology_update: Union[None, Future[None]], session_info: SessionInfo
) -> None:
self.__wait_for_topology_update(topology_update)
current_index_and_node = self.choose_node_for_request(command, session_info)
self.execute(
current_index_and_node.current_node, current_index_and_node.current_index, command, True, session_info
)
def __wait_for_topology_update(self, topology_update: Future[None]) -> None:
try:
if topology_update is None or topology_update.exception():
with self.__synchronized_lock:
if self._first_topology_update_task is None or topology_update == self._first_topology_update_task:
if self._last_known_urls is None:
# shouldn't happen
raise RuntimeError(
"No known topology and no previously known one, cannot proceed, likely a bug"
)
self._first_topology_update_task = self._first_topology_update(self._last_known_urls, None)
topology_update = self._first_topology_update_task
topology_update.result()
# todo: narrow the exception scope down
except BaseException as e:
with self.__synchronized_lock:
if self._first_topology_update_task == topology_update:
self._first_topology_update_task = None # next request will raise it
raise e
def __update_topology_callback(self) -> None:
time = datetime.datetime.now()
if (time - self._last_returned_response.time) <= datetime.timedelta(minutes=5):
return
try:
selector = self._node_selector
if selector is None:
return
preferred_node = selector.get_preferred_node()
server_node = preferred_node.current_node
except Exception as e:
self.logger.info("Couldn't get preferred node Topology from _updateTopologyTimer", exc_info=e)
return
update_parameters = UpdateTopologyParameters(server_node)
update_parameters.timeout_in_ms = 0
update_parameters.debug_tag = "timer-callback"
try:
self.update_topology_async(update_parameters)
except Exception as e:
self.logger.info("Couldn't update topology from __update_topology_timer", exc_info=e)
def _set_request_headers(
self, session_info: SessionInfo, cached_change_vector: Union[None, str], request: requests.Request
) -> None:
if cached_change_vector is not None:
request.headers[constants.Headers.IF_NONE_MATCH] = f'"{cached_change_vector}"'
if not self._disable_client_configuration_updates:
request.headers[constants.Headers.CLIENT_CONFIGURATION_ETAG] = f'"{self._client_configuration_etag}"'
if session_info and session_info.last_cluster_transaction_index:
request.headers[constants.Headers.LAST_KNOWN_CLUSTER_TRANSACTION_INDEX] = str(
session_info.last_cluster_transaction_index
)
if not self._disable_topology_updates:
request.headers[constants.Headers.TOPOLOGY_ETAG] = f'"{self._topology_etag}"'
if not request.headers.get(constants.Headers.CLIENT_VERSION):
request.headers[constants.Headers.CLIENT_VERSION] = RequestExecutor.CLIENT_VERSION
def _get_from_cache(
self, command: RavenCommand, use_cache: bool, url: str
) -> Tuple[ReleaseCacheItem, Optional[str], Optional[str]]:
if (
use_cache
and command.can_cache
and command.is_read_request()
and command.response_type == RavenCommandResponseType.OBJECT
):
return self._cache.get(url)
return ReleaseCacheItem(), None, None
@staticmethod
def __try_get_server_version(response: requests.Response) -> Union[None, str]:
server_version_header = response.headers.get(constants.Headers.SERVER_VERSION)
if server_version_header is not None:
return server_version_header
def _throw_failed_to_contact_all_nodes(self, command: RavenCommand, request: requests.Request):
if not command.failed_nodes:
raise RuntimeError(
"Received unsuccessful response and couldn't recover from it. "
"Also, no record of exceptions per failed nodes. This is weird and should not happen."
)
if len(command.failed_nodes) == 1:
# raise the single recorded exception
raise next(iter(command.failed_nodes.values()))
message = (
f"Tried to send {command._result_class.__name__} request via {request.method}"
f" {request.url} to all configured nodes in the topology, none of the attempt succeeded.{os.linesep}"
)
if self.__topology_taken_from_node is not None:
message += (
f"I was able to fetch {self.__topology_taken_from_node.database}"
f" topology from {self.__topology_taken_from_node.url}.{os.linesep}"
)
nodes = None
if self._node_selector and self._node_selector.topology:
nodes = self._node_selector.topology.nodes
if nodes is None:
message += "Topology is empty."
else:
message += "Topology: "
for node in nodes:
exception = command.failed_nodes.get(node)
message += (
f"{os.linesep}"
f"[Url: {node.url}, "
f"ClusterTag: {node.cluster_tag}, "
f"Exception: {exception.args[0] if exception else 'No exception'}]"
)
raise AllTopologyNodesDownException(message)
def should_execute_on_all(self, chosen_node: ServerNode, command: RavenCommand) -> bool:
return (
self.conventions.read_balance_behavior == ReadBalanceBehavior.FASTEST_NODE
and self._node_selector
and self._node_selector.in_speed_test_phase
and len(self._node_selector.topology.nodes) > 1
and command.is_read_request()
and command.response_type == RavenCommandResponseType.OBJECT
and chosen_node is not None
and not isinstance(command, Broadcast)
)
def __execute_on_all_to_figure_out_the_fastest(
self, chosen_node: ServerNode, command: RavenCommand
) -> requests.Response:
number_failed_tasks = [0] # mutable integer
preferred_task: Future[RequestExecutor.IndexAndResponse] = None
nodes = self._node_selector.topology.nodes
tasks: List[Future[RequestExecutor.IndexAndResponse]] = [None] * len(nodes)
for i in range(len(nodes)):
task_number = i
self.number_of_server_requests += 1
def __supply_async(
single_element_list_number_failed_tasks: List[int],
) -> (RequestExecutor.IndexAndResponse, int):
try:
request, str_ref = self.__create_request(nodes[task_number], command)
self._set_request_headers(None, None, request)
return self.IndexAndResponse(task_number, command.send(self.http_session, request))
except Exception as e:
single_element_list_number_failed_tasks[0] += 1
tasks[task_number] = None
raise RuntimeError("Request execution failed", e)
task = self._thread_pool_executor.submit(__supply_async, number_failed_tasks)
if nodes[i].cluster_tag == chosen_node.cluster_tag:
preferred_task = task
else:
task.add_done_callback(lambda result: result.response.close())
tasks[i] = task
while number_failed_tasks[0] < len(tasks):
try:
first_finished, slow = wait(list(filter(lambda t: t is not None, tasks)), return_when=FIRST_COMPLETED)
fastest = first_finished.pop().result()
fastest: RequestExecutor.IndexAndResponse
self._node_selector.record_fastest(fastest.index, nodes[fastest.index])
break
except BaseException:
for i in range(len(nodes)):
if tasks[i].exception() is not None:
number_failed_tasks[0] += 1
tasks[i] = None
# we can reach here if number of failed task equal to the number of the nodes,