-
Notifications
You must be signed in to change notification settings - Fork 194
/
Copy pathclient.py
2181 lines (1853 loc) · 77.2 KB
/
client.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2016-2023 The NATS 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 __future__ import annotations
import asyncio
import base64
import ipaddress
import json
import logging
import ssl
import string
import time
from collections import UserString
from dataclasses import dataclass
from email.parser import BytesParser
from io import BytesIO
from pathlib import Path
from random import shuffle
from secrets import token_hex
from typing import Any, Awaitable, Callable, Dict, List, Optional, Tuple, Union
from urllib.parse import ParseResult, urlparse
try:
from fast_mail_parser import parse_email
except ImportError:
parse_email = None
import nats.js
from nats import errors
from nats.nuid import NUID
from nats.protocol import command as prot_command
from nats.protocol.parser import (
AUTHORIZATION_VIOLATION,
PERMISSIONS_ERR,
PONG,
STALE_CONNECTION,
Parser,
)
from .errors import ErrInvalidUserCredentials, ErrStaleConnection
from .msg import Msg
from .subscription import (
DEFAULT_SUB_PENDING_BYTES_LIMIT,
DEFAULT_SUB_PENDING_MSGS_LIMIT,
Subscription,
)
from .transport import TcpTransport, Transport, WebSocketTransport
__version__ = "2.9.0"
__lang__ = "python3"
_logger = logging.getLogger(__name__)
PROTOCOL = 1
INFO_OP = b"INFO"
CONNECT_OP = b"CONNECT"
PING_OP = b"PING"
PONG_OP = b"PONG"
OK_OP = b"+OK"
ERR_OP = b"-ERR"
_CRLF_ = b"\r\n"
_CRLF_LEN_ = len(_CRLF_)
_SPC_ = b" "
_SPC_BYTE_ = 32
EMPTY = ""
PING_PROTO = PING_OP + _CRLF_
PONG_PROTO = PONG_OP + _CRLF_
DEFAULT_INBOX_PREFIX = b"_INBOX"
DEFAULT_PENDING_SIZE = 2 * 1024 * 1024
DEFAULT_BUFFER_SIZE = 32768
DEFAULT_RECONNECT_TIME_WAIT = 2 # in seconds
DEFAULT_MAX_RECONNECT_ATTEMPTS = 60
DEFAULT_PING_INTERVAL = 120 # in seconds
DEFAULT_MAX_OUTSTANDING_PINGS = 2
DEFAULT_MAX_PAYLOAD_SIZE = 1048576
DEFAULT_MAX_FLUSHER_QUEUE_SIZE = 1024
DEFAULT_FLUSH_TIMEOUT = 10 # in seconds
DEFAULT_CONNECT_TIMEOUT = 2 # in seconds
DEFAULT_DRAIN_TIMEOUT = 30 # in seconds
MAX_CONTROL_LINE_SIZE = 1024
NATS_HDR_LINE = bytearray(b"NATS/1.0")
NATS_HDR_LINE_SIZE = len(NATS_HDR_LINE)
NO_RESPONDERS_STATUS = "503"
CTRL_STATUS = "100"
STATUS_MSG_LEN = 3 # e.g. 20x, 40x, 50x
Callback = Callable[[], Awaitable[None]]
ErrorCallback = Callable[[Exception], Awaitable[None]]
JWTCallback = Callable[[], Union[bytearray, bytes]]
SignatureCallback = Callable[[str], bytes]
class RawCredentials(UserString):
pass
Credentials = Union[str, Tuple[str, str], RawCredentials, Path]
@dataclass
class Srv:
"""
Srv is a helper data structure to hold state of a server.
"""
uri: ParseResult
reconnects: int = 0
last_attempt: Optional[float] = None
did_connect: bool = False
discovered: bool = False
tls_name: Optional[str] = None
server_version: Optional[str] = None
class ServerVersion:
def __init__(self, server_version: str) -> None:
self._server_version = server_version
self._major_version: Optional[int] = None
self._minor_version: Optional[int] = None
self._patch_version: Optional[int] = None
self._dev_version: Optional[str] = None
# TODO(@orsinium): use cached_property
def parse_version(self) -> None:
v = (self._server_version).split("-")
if len(v) > 1:
self._dev_version = v[1]
tokens = v[0].split(".")
n = len(tokens)
if n > 1:
self._major_version = int(tokens[0])
if n > 2:
self._minor_version = int(tokens[1])
if n > 3:
self._patch_version = int(tokens[2])
@property
def major(self) -> int:
if not self._major_version:
self.parse_version()
return self._major_version or 0
@property
def minor(self) -> int:
if not self._minor_version:
self.parse_version()
return self._minor_version or 0
@property
def patch(self) -> int:
if not self._patch_version:
self.parse_version()
return self._patch_version or 0
@property
def dev(self) -> str:
if not self._dev_version:
self.parse_version()
return self._dev_version or ""
def __repr__(self) -> str:
return f"<nats server v{self._server_version}>"
async def _default_error_callback(ex: Exception) -> None:
"""
Provides a default way to handle async errors if the user
does not provide one.
"""
_logger.error("nats: encountered error", exc_info=ex)
class Client:
"""
Asyncio based client for NATS.
"""
msg_class: type[Msg] = Msg
# FIXME: Use an enum instead.
DISCONNECTED = 0
CONNECTED = 1
CLOSED = 2
RECONNECTING = 3
CONNECTING = 4
DRAINING_SUBS = 5
DRAINING_PUBS = 6
def __repr__(self) -> str:
return f"<nats client v{__version__}>"
def __init__(self) -> None:
self._current_server: Optional[Srv] = None
self._server_info: Dict[str, Any] = {}
self._server_pool: List[Srv] = []
self._reading_task: Optional[asyncio.Task] = None
self._ping_interval_task: Optional[asyncio.Task] = None
self._pings_outstanding: int = 0
self._pongs_received: int = 0
self._pongs: List[asyncio.Future] = []
self._transport: Optional[Transport] = None
self._err: Optional[Exception] = None
# callbacks
self._error_cb: ErrorCallback = _default_error_callback
self._disconnected_cb: Optional[Callback] = None
self._closed_cb: Optional[Callback] = None
self._discovered_server_cb: Optional[Callback] = None
self._reconnected_cb: Optional[Callback] = None
self._reconnection_task: Optional[asyncio.Task[None]] = None
self._reconnection_task_future: Optional[asyncio.Future] = None
self._max_payload: int = DEFAULT_MAX_PAYLOAD_SIZE
# client id that the NATS server knows about.
self._client_id: Optional[int] = None
self._sid: int = 0
self._subs: Dict[int, Subscription] = {}
self._status: int = Client.DISCONNECTED
self._ps: Parser = Parser(self)
# pending queue of commands that will be flushed to the server.
self._pending: List[bytes] = []
# current size of pending data in total.
self._pending_data_size: int = 0
# max pending size is the maximum size of the data that can be buffered.
self._max_pending_size: int = 0
self._flush_queue: Optional[asyncio.Queue[asyncio.Future[Any]]] = None
self._flusher_task: Optional[asyncio.Task] = None
self._flush_timeout: Optional[float] = 0
self._hdr_parser: BytesParser = BytesParser()
# New style request/response
self._resp_map: Dict[str, asyncio.Future] = {}
self._resp_sub_prefix: Optional[bytearray] = None
self._nuid = NUID()
self._inbox_prefix = bytearray(DEFAULT_INBOX_PREFIX)
self._auth_configured: bool = False
# NKEYS support
#
# user_jwt_cb is used to fetch and return the account
# signed JWT for this user.
self._user_jwt_cb: Optional[JWTCallback] = None
# signature_cb is used to sign a nonce from the server while
# authenticating with nkeys. The user should sign the nonce and
# return the base64 encoded signature.
self._signature_cb: Optional[SignatureCallback] = None
# user credentials file can be a tuple or single file.
self._user_credentials: Optional[Credentials] = None
# file that contains the nkeys seed and its public key as a string.
self._nkeys_seed: Optional[str] = None
self._nkeys_seed_str: Optional[str] = None
self._public_nkey: Optional[str] = None
self.options: Dict[str, Any] = {}
self.stats = {
"in_msgs": 0,
"out_msgs": 0,
"in_bytes": 0,
"out_bytes": 0,
"reconnects": 0,
"errors_received": 0,
}
async def connect(
self,
servers: Union[str, List[str]] = ["nats://localhost:4222"],
error_cb: Optional[ErrorCallback] = None,
disconnected_cb: Optional[Callback] = None,
closed_cb: Optional[Callback] = None,
discovered_server_cb: Optional[Callback] = None,
reconnected_cb: Optional[Callback] = None,
name: Optional[str] = None,
pedantic: bool = False,
verbose: bool = False,
allow_reconnect: bool = True,
connect_timeout: int = DEFAULT_CONNECT_TIMEOUT,
reconnect_time_wait: int = DEFAULT_RECONNECT_TIME_WAIT,
max_reconnect_attempts: int = DEFAULT_MAX_RECONNECT_ATTEMPTS,
ping_interval: int = DEFAULT_PING_INTERVAL,
max_outstanding_pings: int = DEFAULT_MAX_OUTSTANDING_PINGS,
dont_randomize: bool = False,
flusher_queue_size: int = DEFAULT_MAX_FLUSHER_QUEUE_SIZE,
no_echo: bool = False,
tls: Optional[ssl.SSLContext] = None,
tls_hostname: Optional[str] = None,
tls_handshake_first: bool = False,
user: Optional[str] = None,
password: Optional[str] = None,
token: Optional[str] = None,
drain_timeout: int = DEFAULT_DRAIN_TIMEOUT,
signature_cb: Optional[SignatureCallback] = None,
user_jwt_cb: Optional[JWTCallback] = None,
user_credentials: Optional[Credentials] = None,
nkeys_seed: Optional[str] = None,
nkeys_seed_str: Optional[str] = None,
inbox_prefix: Union[str, bytes] = DEFAULT_INBOX_PREFIX,
pending_size: int = DEFAULT_PENDING_SIZE,
flush_timeout: Optional[float] = None,
) -> None:
"""
Establishes a connection to NATS.
:param servers: NATS Connection
:param name: Label the connection with name (shown in NATS monitoring)
:param error_cb: Callback to report errors.
:param disconnected_cb: Callback to report disconnection from NATS.
:param closed_cb: Callback to report when client stops reconnection to NATS.
:param discovered_server_cb: Callback to report when a new server joins the cluster.
:param pending_size: Max size of the pending buffer for publishing commands.
:param flush_timeout: Max duration to wait for a forced flush to occur.
Connecting setting all callbacks::
import asyncio
import nats
async def main():
async def disconnected_cb():
print('Got disconnected!')
async def reconnected_cb():
print(f'Got reconnected to {nc.connected_url.netloc}')
async def error_cb(e):
print(f'There was an error: {e}')
async def closed_cb():
print('Connection is closed')
# Connect to NATS with logging callbacks.
nc = await nats.connect('demo.nats.io',
error_cb=error_cb,
reconnected_cb=reconnected_cb,
disconnected_cb=disconnected_cb,
closed_cb=closed_cb,
)
async def handler(msg):
print(f'Received a message on {msg.subject} {msg.reply}: {msg.data}')
await msg.respond(b'OK')
sub = await nc.subscribe('help.please', cb=handler)
resp = await nc.request('help.please', b'help')
print('Response:', resp)
await nc.close()
if __name__ == '__main__':
asyncio.run(main())
Using a context manager::
import asyncio
import nats
async def main():
is_done = asyncio.Future()
async def closed_cb():
print('Connection to NATS is closed.')
is_done.set_result(True)
async with (await nats.connect('nats://demo.nats.io:4222', closed_cb=closed_cb)) as nc:
print(f'Connected to NATS at {nc.connected_url.netloc}...')
async def subscribe_handler(msg):
subject = msg.subject
reply = msg.reply
data = msg.data.decode()
print('Received a message on '{subject} {reply}': {data}'.format(
subject=subject, reply=reply, data=data))
await nc.subscribe('discover', cb=subscribe_handler)
await nc.flush()
for i in range(0, 10):
await nc.publish('discover', b'hello world')
await asyncio.sleep(0.1)
await asyncio.wait_for(is_done, 60.0)
if __name__ == '__main__':
asyncio.run(main())
"""
for cb in [
error_cb,
disconnected_cb,
closed_cb,
reconnected_cb,
discovered_server_cb,
]:
if cb and not asyncio.iscoroutinefunction(cb):
raise errors.InvalidCallbackTypeError
self._setup_server_pool(servers)
self._error_cb = error_cb or _default_error_callback
self._closed_cb = closed_cb
self._discovered_server_cb = discovered_server_cb
self._reconnected_cb = reconnected_cb
self._disconnected_cb = disconnected_cb
# Custom inbox prefix
if isinstance(inbox_prefix, str):
inbox_prefix = inbox_prefix.encode()
assert isinstance(inbox_prefix, bytes)
self._inbox_prefix = bytearray(inbox_prefix)
# NKEYS support
self._signature_cb = signature_cb
self._user_jwt_cb = user_jwt_cb
self._user_credentials = user_credentials
self._nkeys_seed = nkeys_seed
self._nkeys_seed_str = nkeys_seed_str
# Customizable options
self.options["verbose"] = verbose
self.options["pedantic"] = pedantic
self.options["name"] = name
self.options["allow_reconnect"] = allow_reconnect
self.options["dont_randomize"] = dont_randomize
self.options["reconnect_time_wait"] = reconnect_time_wait
self.options["max_reconnect_attempts"] = max_reconnect_attempts
self.options["ping_interval"] = ping_interval
self.options["max_outstanding_pings"] = max_outstanding_pings
self.options["no_echo"] = no_echo
self.options["user"] = user
self.options["password"] = password
self.options["token"] = token
self.options["connect_timeout"] = connect_timeout
self.options["drain_timeout"] = drain_timeout
self.options["tls_handshake_first"] = tls_handshake_first
if tls:
self.options["tls"] = tls
if tls_hostname:
self.options["tls_hostname"] = tls_hostname
# Check if the username or password was set in the server URI
server_auth_configured = False
if len(self._server_pool) > 0:
for server in self._server_pool:
if server.uri.username or server.uri.password:
server_auth_configured = True
break
if user or password or token or server_auth_configured:
self._auth_configured = True
if (self._user_credentials is not None or self._nkeys_seed is not None
or self._nkeys_seed_str is not None):
self._auth_configured = True
self._setup_nkeys_connect()
# Queue used to trigger flushes to the socket.
self._flush_queue = asyncio.Queue(maxsize=flusher_queue_size)
# Max size of buffer used for flushing commands to the server.
self._max_pending_size = pending_size
# Max duration for a force flush (happens when a buffer is full).
self._flush_timeout = flush_timeout
if self.options["dont_randomize"] is False:
shuffle(self._server_pool)
while True:
try:
await self._select_next_server()
await self._process_connect_init()
assert (
self._current_server
), "the current server must be set by _select_next_server"
self._current_server.reconnects = 0
break
except errors.NoServersError as e:
if self.options["max_reconnect_attempts"] < 0:
# Never stop reconnecting
continue
self._err = e
raise e
except (OSError, errors.Error, asyncio.TimeoutError) as e:
self._err = e
await self._error_cb(e)
# Bail on first attempt if reconnecting is disallowed.
if not self.options["allow_reconnect"]:
raise e
await self._close(Client.DISCONNECTED, False)
if self._current_server is not None:
self._current_server.last_attempt = time.monotonic()
self._current_server.reconnects += 1
def _setup_nkeys_connect(self) -> None:
if self._user_credentials is not None:
self._setup_nkeys_jwt_connect()
else:
self._setup_nkeys_seed_connect()
def _setup_nkeys_jwt_connect(self) -> None:
assert self._user_credentials, "_user_credentials required"
import os
import nkeys
creds: Credentials = self._user_credentials
if isinstance(creds, tuple):
assert len(creds) == 2
def user_cb() -> bytearray:
contents = None
with open(creds[0], "rb") as f:
contents = bytearray(os.fstat(f.fileno()).st_size)
f.readinto(contents) # type: ignore[attr-defined]
return contents
self._user_jwt_cb = user_cb
def sig_cb(nonce: str) -> bytes:
seed = None
with open(creds[1], "rb") as f:
seed = bytearray(os.fstat(f.fileno()).st_size)
f.readinto(seed) # type: ignore[attr-defined]
kp = nkeys.from_seed(seed)
raw_signed = kp.sign(nonce.encode())
sig = base64.b64encode(raw_signed)
# Best effort attempt to clear from memory.
kp.wipe()
del kp
del seed
return sig
self._signature_cb = sig_cb
elif (isinstance(creds, str) or isinstance(creds, UserString)
or isinstance(creds, Path)):
# Define the functions to be able to sign things using nkeys.
def user_cb() -> bytearray:
return self._read_creds_user_jwt(creds)
self._user_jwt_cb = user_cb
def sig_cb(nonce: str) -> bytes:
user_seed = self._read_creds_user_nkey(creds)
kp = nkeys.from_seed(user_seed)
raw_signed = kp.sign(nonce.encode())
sig = base64.b64encode(raw_signed)
# Delete all state related to the keys.
kp.wipe()
del user_seed
del kp
return sig
self._signature_cb = sig_cb
def _read_creds_user_nkey(
self, creds: str | UserString | Path
) -> bytearray:
def get_user_seed(f):
for line in f:
# Detect line where the NKEY would start and end,
# then seek and read into a fixed bytearray that
# can be wiped.
if b"BEGIN USER NKEY SEED" in line:
nkey_start_pos = f.tell()
try:
next(f)
except StopIteration:
raise ErrInvalidUserCredentials
nkey_end_pos = f.tell()
nkey_size = nkey_end_pos - nkey_start_pos - 1
f.seek(nkey_start_pos)
# Only gather enough bytes for the user seed
# into the pre allocated bytearray.
user_seed = bytearray(nkey_size)
f.readinto(user_seed) # type: ignore[attr-defined]
return user_seed
if isinstance(creds, UserString):
return get_user_seed(BytesIO(creds.data.encode()))
with open(creds, "rb", buffering=0) as f:
return get_user_seed(f)
def _read_creds_user_jwt(self, creds: str | RawCredentials | Path):
def get_user_jwt(f):
user_jwt = None
while True:
line = bytearray(f.readline())
if b"BEGIN NATS USER JWT" in line:
user_jwt = bytearray(f.readline())
break
# Remove trailing line break but reusing same memory view.
return user_jwt[:len(user_jwt) - 1]
if isinstance(creds, UserString):
return get_user_jwt(BytesIO(creds.data.encode()))
with open(creds, "rb") as f:
return get_user_jwt(f)
def _setup_nkeys_seed_connect(self) -> None:
assert (
self._nkeys_seed or self._nkeys_seed_str
), "Client.connect must be called first"
import nkeys
def _get_nkeys_seed() -> nkeys.KeyPair:
import os
if self._nkeys_seed_str:
seed = bytearray(self._nkeys_seed_str.encode())
else:
creds = self._nkeys_seed
with open(creds, "rb") as f:
seed = bytearray(os.fstat(f.fileno()).st_size)
f.readinto(seed) # type: ignore[attr-defined]
key_pair = nkeys.from_seed(seed)
del seed
return key_pair
kp = _get_nkeys_seed()
self._public_nkey = kp.public_key.decode()
kp.wipe()
del kp
def sig_cb(nonce: str) -> bytes:
kp = _get_nkeys_seed()
raw_signed = kp.sign(nonce.encode())
sig = base64.b64encode(raw_signed)
# Best effort attempt to clear from memory.
kp.wipe()
del kp
return sig
self._signature_cb = sig_cb
async def close(self) -> None:
"""
Closes the socket to which we are connected and
sets the client to be in the CLOSED state.
No further reconnections occur once reaching this point.
"""
await self._close(Client.CLOSED)
async def _close(self, status: int, do_cbs: bool = True) -> None:
if self.is_closed:
self._status = status
return
self._status = Client.CLOSED
# Kick the flusher once again so that Task breaks and avoid pending futures.
await self._flush_pending()
if self._reading_task is not None and not self._reading_task.cancelled(
):
self._reading_task.cancel()
if (self._ping_interval_task is not None
and not self._ping_interval_task.cancelled()):
self._ping_interval_task.cancel()
if self._flusher_task is not None and not self._flusher_task.cancelled(
):
self._flusher_task.cancel()
if self._reconnection_task is not None and not self._reconnection_task.done(
):
self._reconnection_task.cancel()
# Wait for the reconnection task to be done which should be soon.
try:
if (self._reconnection_task_future is not None
and not self._reconnection_task_future.cancelled()):
await asyncio.wait_for(
self._reconnection_task_future,
self.options["reconnect_time_wait"],
)
except (asyncio.CancelledError, asyncio.TimeoutError):
pass
# Relinquish control to allow background tasks to wrap up.
await asyncio.sleep(0)
if self._current_server is not None and self._transport:
# In case there is any pending data at this point, flush before disconnecting.
if self._pending_data_size > 0:
self._transport.writelines(self._pending[:])
self._pending = []
self._pending_data_size = 0
await self._transport.drain()
# Cleanup subscriptions since not reconnecting so no need
# to replay the subscriptions anymore.
for sub in self._subs.values():
# Async subs use join when draining already so just cancel here.
if sub._wait_for_msgs_task and not sub._wait_for_msgs_task.done():
sub._wait_for_msgs_task.cancel()
if sub._message_iterator:
sub._message_iterator._cancel()
# Sync subs may have some inflight next_msg calls that could be blocking
# so cancel them here to unblock them.
if sub._pending_next_msgs_calls:
for fut in sub._pending_next_msgs_calls.values():
fut.cancel()
sub._pending_next_msgs_calls.clear()
self._subs.clear()
if self._transport is not None:
self._transport.close()
try:
await self._transport.wait_closed()
except Exception as e:
await self._error_cb(e)
if do_cbs:
if self._disconnected_cb is not None:
await self._disconnected_cb()
if self._closed_cb is not None:
await self._closed_cb()
# Set the client_id and subscription prefix back to None
self._client_id = None
self._resp_sub_prefix = None
async def drain(self) -> None:
"""
drain will put a connection into a drain state. All subscriptions will
immediately be put into a drain state. Upon completion, the publishers
will be drained and can not publish any additional messages. Upon draining
of the publishers, the connection will be closed. Use the `closed_cb`
option to know when the connection has moved from draining to closed.
"""
if self.is_draining:
return
if self.is_closed:
raise errors.ConnectionClosedError
if self.is_connecting or self.is_reconnecting:
raise errors.ConnectionReconnectingError
drain_tasks = []
for sub in self._subs.values():
coro = sub._drain()
task = asyncio.get_running_loop().create_task(coro)
drain_tasks.append(task)
drain_is_done = asyncio.gather(*drain_tasks)
# Start draining the subscriptions.
# Relinquish CPU to allow drain tasks to start in the background,
# before setting state to draining.
await asyncio.sleep(0)
self._status = Client.DRAINING_SUBS
try:
await asyncio.wait_for(
drain_is_done, self.options["drain_timeout"]
)
except asyncio.TimeoutError:
drain_is_done.exception()
drain_is_done.cancel()
await self._error_cb(errors.DrainTimeoutError())
except asyncio.CancelledError:
pass
finally:
self._status = Client.DRAINING_PUBS
await self.flush()
await self._close(Client.CLOSED)
async def publish(
self,
subject: str,
payload: bytes = b"",
reply: str = "",
headers: Optional[Dict[str, str]] = None,
) -> None:
"""
Publishes a NATS message.
:param subject: Subject to which the message will be published.
:param payload: Message data.
:param reply: Inbox to which a responder can respond.
:param headers: Optional message header.
::
import asyncio
import nats
async def main():
nc = await nats.connect('demo.nats.io')
# Publish as message with an inbox.
inbox = nc.new_inbox()
sub = await nc.subscribe('hello')
# Simple publishing
await nc.publish('hello', b'Hello World!')
# Publish with a reply
await nc.publish('hello', b'Hello World!', reply=inbox)
# Publish with headers
await nc.publish('hello', b'With Headers', headers={'Foo':'Bar'})
while True:
try:
msg = await sub.next_msg()
except:
break
print('----------------------')
print('Subject:', msg.subject)
print('Reply :', msg.reply)
print('Data :', msg.data)
print('Headers:', msg.header)
if __name__ == '__main__':
asyncio.run(main())
"""
if self.is_closed:
raise errors.ConnectionClosedError
if self.is_draining_pubs:
raise errors.ConnectionDrainingError
payload_size = len(payload)
if not self.is_connected:
if (self._max_pending_size <= 0
or payload_size + self._pending_data_size
> self._max_pending_size):
# Cannot publish during a reconnection when the buffering is disabled,
# or if pending buffer is already full.
raise errors.OutboundBufferLimitError
if payload_size > self._max_payload:
raise errors.MaxPayloadError
await self._send_publish(
subject, reply, payload, payload_size, headers
)
async def _send_publish(
self,
subject: str,
reply: str,
payload: bytes,
payload_size: int,
headers: Optional[Dict[str, Any]],
) -> None:
"""
Sends PUB command to the NATS server.
"""
if subject == "":
# Avoid sending messages with empty replies.
raise errors.BadSubjectError
pub_cmd = None
if headers is None:
pub_cmd = prot_command.pub_cmd(subject, reply, payload)
else:
hdr = bytearray()
hdr.extend(NATS_HDR_LINE)
hdr.extend(_CRLF_)
for k, v in headers.items():
key = k.strip()
if not key:
# Skip empty keys
continue
hdr.extend(key.encode())
hdr.extend(b": ")
value = v.strip()
hdr.extend(value.encode())
hdr.extend(_CRLF_)
hdr.extend(_CRLF_)
pub_cmd = prot_command.hpub_cmd(subject, reply, hdr, payload)
self.stats["out_msgs"] += 1
self.stats["out_bytes"] += payload_size
await self._send_command(pub_cmd)
if self._flush_queue is not None and self._flush_queue.empty():
await self._flush_pending()
async def subscribe(
self,
subject: str,
queue: str = "",
cb: Optional[Callable[[Msg], Awaitable[None]]] = None,
future: Optional[asyncio.Future] = None,
max_msgs: int = 0,
pending_msgs_limit: int = DEFAULT_SUB_PENDING_MSGS_LIMIT,
pending_bytes_limit: int = DEFAULT_SUB_PENDING_BYTES_LIMIT,
) -> Subscription:
"""
subscribe registers interest in a given subject.
If a callback is provided, messages will be processed asychronously.
If a callback isn't provided, messages can be retrieved via an
asynchronous iterator on the returned subscription object.
"""
if not subject or (" " in subject):
raise errors.BadSubjectError
if queue and (" " in queue):
raise errors.BadSubjectError
if self.is_closed:
raise errors.ConnectionClosedError
if self.is_draining:
raise errors.ConnectionDrainingError
self._sid += 1
sid = self._sid
sub = Subscription(
self,
sid,
subject,
queue=queue,
cb=cb,
future=future,
max_msgs=max_msgs,
pending_msgs_limit=pending_msgs_limit,
pending_bytes_limit=pending_bytes_limit,
)
sub._start(self._error_cb)
self._subs[sid] = sub
await self._send_subscribe(sub)
return sub
def _remove_sub(self, sid: int, max_msgs: int = 0) -> None:
self._subs.pop(sid, None)
async def _send_subscribe(self, sub: Subscription) -> None:
sub_cmd = None
if sub._queue is None:
sub_cmd = prot_command.sub_cmd(sub._subject, EMPTY, sub._id)
else:
sub_cmd = prot_command.sub_cmd(sub._subject, sub._queue, sub._id)
await self._send_command(sub_cmd)
await self._flush_pending()
async def _init_request_sub(self) -> None:
self._resp_map = {}
self._resp_sub_prefix = self._inbox_prefix[:]
self._resp_sub_prefix.extend(b".")
self._resp_sub_prefix.extend(self._nuid.next())
self._resp_sub_prefix.extend(b".")
resp_mux_subject = self._resp_sub_prefix[:]
resp_mux_subject.extend(b"*")
await self.subscribe(
resp_mux_subject.decode(), cb=self._request_sub_callback
)
async def _request_sub_callback(self, msg: Msg) -> None:
token = msg.subject[len(self._inbox_prefix) + 22 + 2:]
future = self._resp_map.get(token)
if not future:
return
if not future.done():
future.set_result(msg)