stompman 0.2.0__tar.gz → 0.3.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: stompman
3
- Version: 0.2.0
3
+ Version: 0.3.0
4
4
  Summary: Python STOMP client with pleasant API
5
5
  Home-page: https://github.com/vrslev/stompman
6
6
  License: MIT
@@ -8,10 +8,15 @@ Keywords: stomp,artemis,activemq,messaging,jms
8
8
  Author: Lev Vereshchagin
9
9
  Author-email: mail@vrslev.com
10
10
  Requires-Python: >=3.11,<4.0
11
+ Classifier: Development Status :: 4 - Beta
11
12
  Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Natural Language :: English
12
14
  Classifier: Programming Language :: Python :: 3
13
15
  Classifier: Programming Language :: Python :: 3.11
14
16
  Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: Implementation :: CPython
18
+ Classifier: Topic :: System :: Networking
19
+ Classifier: Typing :: Typed
15
20
  Project-URL: Repository, https://github.com/vrslev/stompman
16
21
  Description-Content-Type: text/markdown
17
22
 
@@ -128,9 +133,18 @@ stompman takes care of cleaning up resources automatically. When you leave the c
128
133
 
129
134
  ### Handling Connectivity Issues
130
135
 
131
- - If multiple servers are provided, stompman will attempt to connect to each one simultaneously and use the first that succeeds.
132
- - If all servers fail to connect, an `stompman.FailedAllConnectAttemptsError` will be raised. There're no need to handle it, if you should tune retry and timeout parameters to your needs.
133
- - If a connection is lost, a `stompman.ReadTimeoutError` will be raised. You'll need to implement reconnect logic manually. Implementing reconnect logic in the library would be too complex, since there're no global state and clean-ups are automatic (e.g. it won't be possible to re-subscribe to destination because client doesn't keep track of subscriptions).
136
+ - If multiple servers were provided, stompman will attempt to connect to each one simultaneously and will use the first that succeeds.
137
+
138
+ - If all servers fail to connect, an `stompman.FailedAllConnectAttemptsError` will be raised. In normal situation it doesn't need to be handled: tune retry and timeout parameters in `stompman.Client()` to your needs.
139
+
140
+ - If a connection is lost, a `stompman.ConnectionLostError` will be raised. You should implement reconnect logic manually, for example, with stamina:
141
+
142
+ ```python
143
+ for attempt in stamina.retry_context(on=stompman.ConnectionLostError):
144
+ with attempt:
145
+ async with stompman.Client(...) as client:
146
+ ...
147
+ ```
134
148
 
135
149
  ### ...and caveats
136
150
 
@@ -111,9 +111,18 @@ stompman takes care of cleaning up resources automatically. When you leave the c
111
111
 
112
112
  ### Handling Connectivity Issues
113
113
 
114
- - If multiple servers are provided, stompman will attempt to connect to each one simultaneously and use the first that succeeds.
115
- - If all servers fail to connect, an `stompman.FailedAllConnectAttemptsError` will be raised. There're no need to handle it, if you should tune retry and timeout parameters to your needs.
116
- - If a connection is lost, a `stompman.ReadTimeoutError` will be raised. You'll need to implement reconnect logic manually. Implementing reconnect logic in the library would be too complex, since there're no global state and clean-ups are automatic (e.g. it won't be possible to re-subscribe to destination because client doesn't keep track of subscriptions).
114
+ - If multiple servers were provided, stompman will attempt to connect to each one simultaneously and will use the first that succeeds.
115
+
116
+ - If all servers fail to connect, an `stompman.FailedAllConnectAttemptsError` will be raised. In normal situation it doesn't need to be handled: tune retry and timeout parameters in `stompman.Client()` to your needs.
117
+
118
+ - If a connection is lost, a `stompman.ConnectionLostError` will be raised. You should implement reconnect logic manually, for example, with stamina:
119
+
120
+ ```python
121
+ for attempt in stamina.retry_context(on=stompman.ConnectionLostError):
122
+ with attempt:
123
+ async with stompman.Client(...) as client:
124
+ ...
125
+ ```
117
126
 
118
127
  ### ...and caveats
119
128
 
@@ -1,12 +1,19 @@
1
1
  [tool.poetry]
2
2
  name = "stompman"
3
- version = "0.2.0"
3
+ version = "0.3.0"
4
4
  description = "Python STOMP client with pleasant API"
5
5
  license = "MIT"
6
6
  authors = ["Lev Vereshchagin <mail@vrslev.com>"]
7
7
  readme = "README.md"
8
8
  repository = "https://github.com/vrslev/stompman"
9
9
  keywords = ["stomp", "artemis", "activemq", "messaging", "jms"]
10
+ classifiers = [
11
+ "Development Status :: 4 - Beta",
12
+ "Natural Language :: English",
13
+ "Programming Language :: Python :: Implementation :: CPython",
14
+ "Topic :: System :: Networking",
15
+ "Typing :: Typed",
16
+ ]
10
17
 
11
18
  [tool.poetry.dependencies]
12
19
  python = "^3.11"
@@ -34,7 +41,9 @@ target-version = "py311"
34
41
  fix = true
35
42
  unsafe-fixes = true
36
43
  line-length = 120
44
+
37
45
  [tool.ruff.lint]
46
+ preview = true
38
47
  select = ["ALL"]
39
48
  ignore = [
40
49
  "EM",
@@ -51,6 +60,7 @@ ignore = [
51
60
  "ISC001",
52
61
  "S101",
53
62
  "SLF001",
63
+ "CPY001",
54
64
  ]
55
65
 
56
66
  [tool.pytest.ini_options]
@@ -1,19 +1,18 @@
1
1
  from stompman.client import Client, Heartbeat
2
2
  from stompman.connection import AbstractConnection, Connection, ConnectionParameters
3
3
  from stompman.errors import (
4
- ConnectError,
5
4
  ConnectionConfirmationTimeoutError,
5
+ ConnectionLostError,
6
6
  Error,
7
7
  FailedAllConnectAttemptsError,
8
- ReadTimeoutError,
9
8
  UnsupportedProtocolVersionError,
10
9
  )
11
10
  from stompman.frames import (
12
11
  AbortFrame,
13
12
  AckFrame,
14
- AnyFrame,
13
+ AnyClientFrame,
14
+ AnyServerFrame,
15
15
  BeginFrame,
16
- ClientFrame,
17
16
  CommitFrame,
18
17
  ConnectedFrame,
19
18
  ConnectFrame,
@@ -24,7 +23,6 @@ from stompman.frames import (
24
23
  NackFrame,
25
24
  ReceiptFrame,
26
25
  SendFrame,
27
- ServerFrame,
28
26
  SubscribeFrame,
29
27
  UnsubscribeFrame,
30
28
  )
@@ -34,34 +32,31 @@ __all__ = [
34
32
  "AbortFrame",
35
33
  "AbstractConnection",
36
34
  "AckFrame",
37
- "FailedAllConnectAttemptsError",
38
- "AnyFrame",
35
+ "AnyClientFrame",
39
36
  "AnyListeningEvent",
40
- "BaseListenEvent",
37
+ "AnyServerFrame",
41
38
  "BeginFrame",
42
- "ClientFrame",
39
+ "Client",
43
40
  "CommitFrame",
44
- "ConnectedFrame",
45
- "ConnectError",
46
41
  "ConnectFrame",
42
+ "ConnectedFrame",
43
+ "Connection",
47
44
  "ConnectionConfirmationTimeoutError",
45
+ "ConnectionLostError",
48
46
  "ConnectionParameters",
49
47
  "DisconnectFrame",
48
+ "Error",
50
49
  "ErrorEvent",
51
50
  "ErrorFrame",
51
+ "FailedAllConnectAttemptsError",
52
52
  "Heartbeat",
53
53
  "HeartbeatEvent",
54
54
  "HeartbeatFrame",
55
55
  "MessageEvent",
56
56
  "MessageFrame",
57
57
  "NackFrame",
58
- "ReadTimeoutError",
59
58
  "ReceiptFrame",
60
59
  "SendFrame",
61
- "ServerFrame",
62
- "Client",
63
- "Connection",
64
- "Error",
65
60
  "SubscribeFrame",
66
61
  "UnsubscribeFrame",
67
62
  "UnsupportedProtocolVersionError",
@@ -8,7 +8,6 @@ from uuid import uuid4
8
8
 
9
9
  from stompman.connection import AbstractConnection, Connection, ConnectionParameters
10
10
  from stompman.errors import (
11
- ConnectError,
12
11
  ConnectionConfirmationTimeoutError,
13
12
  FailedAllConnectAttemptsError,
14
13
  UnsupportedProtocolVersionError,
@@ -80,12 +79,9 @@ class Client:
80
79
  read_timeout=self.read_timeout,
81
80
  read_max_chunk_size=self.read_max_chunk_size,
82
81
  )
83
- try:
84
- await connection.connect()
85
- except ConnectError:
86
- await asyncio.sleep(self.connect_retry_interval * (attempt + 1))
87
- else:
82
+ if await connection.connect():
88
83
  return connection
84
+ await asyncio.sleep(self.connect_retry_interval * (attempt + 1))
89
85
  return None
90
86
 
91
87
  async def _connect_to_any_server(self) -> AbstractConnection:
@@ -1,11 +1,11 @@
1
1
  import asyncio
2
- from collections.abc import AsyncGenerator, Iterable
2
+ from collections.abc import AsyncGenerator, Iterator
3
3
  from dataclasses import dataclass, field
4
4
  from typing import Protocol, TypeVar, cast
5
5
 
6
- from stompman.errors import ConnectError, ReadTimeoutError
7
- from stompman.frames import AnyRealFrame, ClientFrame, ServerFrame
8
- from stompman.protocol import NEWLINE, Parser, dump_frame, separate_complete_and_incomplete_packet_parts
6
+ from stompman.errors import ConnectionLostError
7
+ from stompman.frames import AnyClientFrame, AnyServerFrame
8
+ from stompman.protocol import NEWLINE, Parser, dump_frame
9
9
 
10
10
 
11
11
  @dataclass
@@ -16,7 +16,7 @@ class ConnectionParameters:
16
16
  passcode: str = field(repr=False)
17
17
 
18
18
 
19
- FrameT = TypeVar("FrameT", bound=AnyRealFrame)
19
+ FrameT = TypeVar("FrameT", bound=AnyClientFrame | AnyServerFrame)
20
20
 
21
21
 
22
22
  @dataclass
@@ -26,11 +26,11 @@ class AbstractConnection(Protocol):
26
26
  read_timeout: int
27
27
  read_max_chunk_size: int
28
28
 
29
- async def connect(self) -> None: ...
29
+ async def connect(self) -> bool: ...
30
30
  async def close(self) -> None: ...
31
31
  def write_heartbeat(self) -> None: ...
32
- async def write_frame(self, frame: ClientFrame) -> None: ...
33
- def read_frames(self) -> AsyncGenerator[ServerFrame, None]: ...
32
+ async def write_frame(self, frame: AnyClientFrame) -> None: ...
33
+ def read_frames(self) -> AsyncGenerator[AnyServerFrame, None]: ...
34
34
 
35
35
  async def read_frame_of_type(self, type_: type[FrameT]) -> FrameT:
36
36
  while True:
@@ -48,14 +48,15 @@ class Connection(AbstractConnection):
48
48
  reader: asyncio.StreamReader = field(init=False)
49
49
  writer: asyncio.StreamWriter = field(init=False)
50
50
 
51
- async def connect(self) -> None:
51
+ async def connect(self) -> bool:
52
52
  try:
53
53
  self.reader, self.writer = await asyncio.wait_for(
54
54
  asyncio.open_connection(self.connection_parameters.host, self.connection_parameters.port),
55
55
  timeout=self.connect_timeout,
56
56
  )
57
- except (TimeoutError, ConnectionError) as exception:
58
- raise ConnectError(self.connection_parameters) from exception
57
+ except (TimeoutError, ConnectionError):
58
+ return False
59
+ return True
59
60
 
60
61
  async def close(self) -> None:
61
62
  self.writer.close()
@@ -64,7 +65,7 @@ class Connection(AbstractConnection):
64
65
  def write_heartbeat(self) -> None:
65
66
  return self.writer.write(NEWLINE)
66
67
 
67
- async def write_frame(self, frame: ClientFrame) -> None:
68
+ async def write_frame(self, frame: AnyClientFrame) -> None:
68
69
  self.writer.write(dump_frame(frame))
69
70
  await self.writer.drain()
70
71
 
@@ -75,18 +76,14 @@ class Connection(AbstractConnection):
75
76
  await asyncio.sleep(0)
76
77
  return chunk
77
78
 
78
- async def read_frames(self) -> AsyncGenerator[ServerFrame, None]:
79
- incomplete_bytes = b""
79
+ async def read_frames(self) -> AsyncGenerator[AnyServerFrame, None]:
80
80
  parser = Parser()
81
81
 
82
82
  while True:
83
83
  try:
84
- received_bytes = await asyncio.wait_for(self._read_non_empty_bytes(), timeout=self.read_timeout)
84
+ raw_frames = await asyncio.wait_for(self._read_non_empty_bytes(), timeout=self.read_timeout)
85
85
  except TimeoutError as exception:
86
- raise ReadTimeoutError(timeout=self.read_timeout) from exception
86
+ raise ConnectionLostError(self.read_timeout) from exception
87
87
 
88
- complete_bytes, incomplete_bytes = separate_complete_and_incomplete_packet_parts(
89
- incomplete_bytes + received_bytes
90
- )
91
- for frame in cast(Iterable[ServerFrame], parser.load_frames(received_bytes)):
88
+ for frame in cast(Iterator[AnyServerFrame], parser.load_frames(raw_frames)):
92
89
  yield frame
@@ -22,11 +22,6 @@ class UnsupportedProtocolVersionError(Error):
22
22
  supported_version: str
23
23
 
24
24
 
25
- @dataclass
26
- class ConnectError(Error):
27
- connection_parameters: "ConnectionParameters"
28
-
29
-
30
25
  @dataclass
31
26
  class FailedAllConnectAttemptsError(Error):
32
27
  servers: list["ConnectionParameters"]
@@ -36,5 +31,5 @@ class FailedAllConnectAttemptsError(Error):
36
31
 
37
32
 
38
33
  @dataclass
39
- class ReadTimeoutError(Error):
34
+ class ConnectionLostError(Error):
40
35
  timeout: int
@@ -244,7 +244,7 @@ COMMANDS_TO_FRAMES: dict[
244
244
  }
245
245
  FRAMES_TO_COMMANDS = {value: key for key, value in COMMANDS_TO_FRAMES.items()}
246
246
 
247
- ClientFrame = (
247
+ AnyClientFrame = (
248
248
  SendFrame
249
249
  | SubscribeFrame
250
250
  | UnsubscribeFrame
@@ -257,6 +257,4 @@ ClientFrame = (
257
257
  | ConnectFrame
258
258
  | StompFrame
259
259
  )
260
- ServerFrame = ConnectedFrame | MessageFrame | ReceiptFrame | ErrorFrame
261
- AnyRealFrame = ClientFrame | ServerFrame
262
- AnyFrame = AnyRealFrame | HeartbeatFrame
260
+ AnyServerFrame = ConnectedFrame | MessageFrame | ReceiptFrame | ErrorFrame
@@ -7,8 +7,8 @@ from typing import Any, cast
7
7
  from stompman.frames import (
8
8
  COMMANDS_TO_FRAMES,
9
9
  FRAMES_TO_COMMANDS,
10
- AnyFrame,
11
- AnyRealFrame,
10
+ AnyClientFrame,
11
+ AnyServerFrame,
12
12
  HeartbeatFrame,
13
13
  )
14
14
 
@@ -37,7 +37,7 @@ def dump_header(key: str, value: str) -> bytes:
37
37
  return f"{escaped_key}:{escaped_value}\n".encode()
38
38
 
39
39
 
40
- def dump_frame(frame: AnyRealFrame) -> bytes:
40
+ def dump_frame(frame: AnyClientFrame | AnyServerFrame) -> bytes:
41
41
  lines = (
42
42
  FRAMES_TO_COMMANDS[type(frame)],
43
43
  NEWLINE,
@@ -49,16 +49,6 @@ def dump_frame(frame: AnyRealFrame) -> bytes:
49
49
  return b"".join(lines)
50
50
 
51
51
 
52
- def separate_complete_and_incomplete_packet_parts(raw_frames: bytes) -> tuple[bytes, bytes]:
53
- if raw_frames.replace(NEWLINE, b"") == b"":
54
- return (raw_frames, b"")
55
- parts = raw_frames.rpartition(NULL)
56
- if parts[2].replace(NEWLINE, b"") == b"":
57
- return (raw_frames, b"")
58
-
59
- return parts[0] + parts[1], parts[2]
60
-
61
-
62
52
  def unescape_byte(byte: bytes, previous_byte: bytes | None) -> bytes | None:
63
53
  if byte == b"\\":
64
54
  return None
@@ -89,7 +79,7 @@ def parse_headers(buffer: list[bytes]) -> tuple[str, str] | None:
89
79
  return (b"".join(key_buffer).decode(), b"".join(value_buffer).decode()) if key_parsed else None
90
80
 
91
81
 
92
- def parse_lines_into_frame(lines: deque[list[bytes]]) -> AnyFrame | None:
82
+ def parse_lines_into_frame(lines: deque[list[bytes]]) -> AnyClientFrame | AnyServerFrame | None:
93
83
  command = b"".join(lines.popleft())
94
84
  headers = {}
95
85
 
@@ -106,43 +96,38 @@ def parse_lines_into_frame(lines: deque[list[bytes]]) -> AnyFrame | None:
106
96
 
107
97
  @dataclass
108
98
  class Parser:
109
- _remainder_from_last_packet: bytes = field(default=b"", init=False)
110
-
111
- def load_frames(self, raw_frames: bytes) -> Iterator[AnyFrame]:
112
- all_bytes = self._remainder_from_last_packet + raw_frames
113
- buffer = deque(struct.unpack(f"{len(all_bytes)!s}c", all_bytes))
114
- lines = deque[list[bytes]]()
115
- current_line: list[bytes] = []
116
- previous_byte = None
117
- headers_processed = False
99
+ _lines: deque[list[bytes]] = field(default_factory=deque, init=False)
100
+ _current_line: list[bytes] = field(default_factory=list, init=False)
101
+ _previous_byte: bytes = field(default=b"", init=False)
102
+ _headers_processed: bool = field(default=False, init=False)
118
103
 
104
+ def load_frames(self, raw_frames: bytes) -> Iterator[AnyClientFrame | AnyServerFrame | HeartbeatFrame]:
105
+ buffer = deque(struct.unpack(f"{len(raw_frames)!s}c", raw_frames))
119
106
  while buffer:
120
107
  byte = buffer.popleft()
121
108
 
122
- if headers_processed and byte == NULL:
123
- lines.append(current_line)
124
- if parsed_frame := parse_lines_into_frame(lines):
109
+ if self._headers_processed and byte == NULL:
110
+ self._lines.append(self._current_line)
111
+ if parsed_frame := parse_lines_into_frame(self._lines):
125
112
  yield parsed_frame
126
- headers_processed = False
127
- lines.clear()
128
- current_line = []
113
+ self._headers_processed = False
114
+ self._lines.clear()
115
+ self._current_line = []
129
116
 
130
- elif not headers_processed and byte == NEWLINE:
131
- if current_line or lines:
132
- if not current_line: # extra empty line after headers
133
- headers_processed = True
117
+ elif not self._headers_processed and byte == NEWLINE:
118
+ if self._current_line or self._lines:
119
+ if not self._current_line: # extra empty line after headers
120
+ self._headers_processed = True
134
121
 
135
- if previous_byte == b"\r":
136
- current_line.pop()
122
+ if self._previous_byte == b"\r":
123
+ self._current_line.pop()
137
124
 
138
- lines.append(current_line)
139
- current_line = []
125
+ self._lines.append(self._current_line)
126
+ self._current_line = []
140
127
  else:
141
128
  yield HeartbeatFrame()
142
129
 
143
130
  else:
144
- current_line.append(byte)
145
-
146
- previous_byte = byte
131
+ self._current_line.append(byte)
147
132
 
148
- self._remainder_from_last_packet = b"".join(current_line)
133
+ self._previous_byte = byte
File without changes
File without changes