stompman 0.2.1__tar.gz → 0.3.1__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.1
3
+ Version: 0.3.1
4
4
  Summary: Python STOMP client with pleasant API
5
5
  Home-page: https://github.com/vrslev/stompman
6
6
  License: MIT
@@ -133,9 +133,18 @@ stompman takes care of cleaning up resources automatically. When you leave the c
133
133
 
134
134
  ### Handling Connectivity Issues
135
135
 
136
- - If multiple servers are provided, stompman will attempt to connect to each one simultaneously and use the first that succeeds.
137
- - 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.
138
- - 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
+ ```
139
148
 
140
149
  ### ...and caveats
141
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,6 +1,6 @@
1
1
  [tool.poetry]
2
2
  name = "stompman"
3
- version = "0.2.1"
3
+ version = "0.3.1"
4
4
  description = "Python STOMP client with pleasant API"
5
5
  license = "MIT"
6
6
  authors = ["Lev Vereshchagin <mail@vrslev.com>"]
@@ -41,7 +41,9 @@ target-version = "py311"
41
41
  fix = true
42
42
  unsafe-fixes = true
43
43
  line-length = 120
44
+
44
45
  [tool.ruff.lint]
46
+ preview = true
45
47
  select = ["ALL"]
46
48
  ignore = [
47
49
  "EM",
@@ -58,6 +60,7 @@ ignore = [
58
60
  "ISC001",
59
61
  "S101",
60
62
  "SLF001",
63
+ "CPY001",
61
64
  ]
62
65
 
63
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:
@@ -0,0 +1,131 @@
1
+ import asyncio
2
+ from collections.abc import AsyncGenerator, Iterator
3
+ from dataclasses import dataclass, field
4
+ from typing import Protocol, Self, TypedDict, TypeVar, cast
5
+
6
+ from stompman.errors import ConnectionLostError
7
+ from stompman.frames import AnyClientFrame, AnyServerFrame
8
+ from stompman.protocol import NEWLINE, Parser, dump_frame
9
+
10
+
11
+ class _MultiHostHostLike(TypedDict):
12
+ username: str | None
13
+ password: str | None
14
+ host: str | None
15
+ port: int | None
16
+
17
+
18
+ @dataclass
19
+ class ConnectionParameters:
20
+ host: str
21
+ port: int
22
+ login: str
23
+ passcode: str = field(repr=False)
24
+
25
+ @classmethod
26
+ def from_pydantic_multihost_hosts(cls, hosts: list[_MultiHostHostLike]) -> list[Self]:
27
+ """Create connection parameters from a list of `MultiHostUrl` objects.
28
+
29
+ .. code-block:: python
30
+ import stompman.
31
+
32
+ ArtemisDsn = typing.Annotated[
33
+ pydantic_core.MultiHostUrl,
34
+ pydantic.UrlConstraints(
35
+ host_required=True,
36
+ allowed_schemes=["tcp"],
37
+ ),
38
+ ]
39
+
40
+ async with stompman.Client(
41
+ servers=stompman.ConnectionParameters.from_pydantic_multihost_hosts(
42
+ ArtemisDsn("tcp://lev:pass@host1:61616,host1:61617,host2:61616").hosts()
43
+ ),
44
+ ):
45
+ ...
46
+ """
47
+ servers: list[Self] = []
48
+ for host in hosts:
49
+ if host["host"] is None:
50
+ raise ValueError("host must be set")
51
+ if host["port"] is None:
52
+ raise ValueError("port must be set")
53
+ if host["username"] is None:
54
+ raise ValueError("username must be set")
55
+ if host["password"] is None:
56
+ raise ValueError("password must be set")
57
+ servers.append(cls(host=host["host"], port=host["port"], login=host["username"], passcode=host["password"]))
58
+ return servers
59
+
60
+
61
+ FrameT = TypeVar("FrameT", bound=AnyClientFrame | AnyServerFrame)
62
+
63
+
64
+ @dataclass
65
+ class AbstractConnection(Protocol):
66
+ connection_parameters: ConnectionParameters
67
+ connect_timeout: int
68
+ read_timeout: int
69
+ read_max_chunk_size: int
70
+
71
+ async def connect(self) -> bool: ...
72
+ async def close(self) -> None: ...
73
+ def write_heartbeat(self) -> None: ...
74
+ async def write_frame(self, frame: AnyClientFrame) -> None: ...
75
+ def read_frames(self) -> AsyncGenerator[AnyServerFrame, None]: ...
76
+
77
+ async def read_frame_of_type(self, type_: type[FrameT]) -> FrameT:
78
+ while True:
79
+ async for frame in self.read_frames():
80
+ if isinstance(frame, type_):
81
+ return frame
82
+
83
+
84
+ @dataclass
85
+ class Connection(AbstractConnection):
86
+ connection_parameters: ConnectionParameters
87
+ connect_timeout: int
88
+ read_timeout: int
89
+ read_max_chunk_size: int
90
+ reader: asyncio.StreamReader = field(init=False)
91
+ writer: asyncio.StreamWriter = field(init=False)
92
+
93
+ async def connect(self) -> bool:
94
+ try:
95
+ self.reader, self.writer = await asyncio.wait_for(
96
+ asyncio.open_connection(self.connection_parameters.host, self.connection_parameters.port),
97
+ timeout=self.connect_timeout,
98
+ )
99
+ except (TimeoutError, ConnectionError):
100
+ return False
101
+ return True
102
+
103
+ async def close(self) -> None:
104
+ self.writer.close()
105
+ await self.writer.wait_closed()
106
+
107
+ def write_heartbeat(self) -> None:
108
+ return self.writer.write(NEWLINE)
109
+
110
+ async def write_frame(self, frame: AnyClientFrame) -> None:
111
+ self.writer.write(dump_frame(frame))
112
+ await self.writer.drain()
113
+
114
+ async def _read_non_empty_bytes(self) -> bytes:
115
+ while (
116
+ chunk := await self.reader.read(self.read_max_chunk_size)
117
+ ) == b"": # pragma: no cover (it defenitely happens)
118
+ await asyncio.sleep(0)
119
+ return chunk
120
+
121
+ async def read_frames(self) -> AsyncGenerator[AnyServerFrame, None]:
122
+ parser = Parser()
123
+
124
+ while True:
125
+ try:
126
+ raw_frames = await asyncio.wait_for(self._read_non_empty_bytes(), timeout=self.read_timeout)
127
+ except TimeoutError as exception:
128
+ raise ConnectionLostError(self.read_timeout) from exception
129
+
130
+ for frame in cast(Iterator[AnyServerFrame], parser.load_frames(raw_frames)):
131
+ 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,
@@ -79,7 +79,7 @@ def parse_headers(buffer: list[bytes]) -> tuple[str, str] | None:
79
79
  return (b"".join(key_buffer).decode(), b"".join(value_buffer).decode()) if key_parsed else None
80
80
 
81
81
 
82
- def parse_lines_into_frame(lines: deque[list[bytes]]) -> AnyFrame | None:
82
+ def parse_lines_into_frame(lines: deque[list[bytes]]) -> AnyClientFrame | AnyServerFrame | None:
83
83
  command = b"".join(lines.popleft())
84
84
  headers = {}
85
85
 
@@ -101,7 +101,7 @@ class Parser:
101
101
  _previous_byte: bytes = field(default=b"", init=False)
102
102
  _headers_processed: bool = field(default=False, init=False)
103
103
 
104
- def load_frames(self, raw_frames: bytes) -> Iterator[AnyFrame]:
104
+ def load_frames(self, raw_frames: bytes) -> Iterator[AnyClientFrame | AnyServerFrame | HeartbeatFrame]:
105
105
  buffer = deque(struct.unpack(f"{len(raw_frames)!s}c", raw_frames))
106
106
  while buffer:
107
107
  byte = buffer.popleft()
@@ -1,88 +0,0 @@
1
- import asyncio
2
- from collections.abc import AsyncGenerator, Iterator
3
- from dataclasses import dataclass, field
4
- from typing import Protocol, TypeVar, cast
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
9
-
10
-
11
- @dataclass
12
- class ConnectionParameters:
13
- host: str
14
- port: int
15
- login: str
16
- passcode: str = field(repr=False)
17
-
18
-
19
- FrameT = TypeVar("FrameT", bound=AnyRealFrame)
20
-
21
-
22
- @dataclass
23
- class AbstractConnection(Protocol):
24
- connection_parameters: ConnectionParameters
25
- connect_timeout: int
26
- read_timeout: int
27
- read_max_chunk_size: int
28
-
29
- async def connect(self) -> None: ...
30
- async def close(self) -> None: ...
31
- def write_heartbeat(self) -> None: ...
32
- async def write_frame(self, frame: ClientFrame) -> None: ...
33
- def read_frames(self) -> AsyncGenerator[ServerFrame, None]: ...
34
-
35
- async def read_frame_of_type(self, type_: type[FrameT]) -> FrameT:
36
- while True:
37
- async for frame in self.read_frames():
38
- if isinstance(frame, type_):
39
- return frame
40
-
41
-
42
- @dataclass
43
- class Connection(AbstractConnection):
44
- connection_parameters: ConnectionParameters
45
- connect_timeout: int
46
- read_timeout: int
47
- read_max_chunk_size: int
48
- reader: asyncio.StreamReader = field(init=False)
49
- writer: asyncio.StreamWriter = field(init=False)
50
-
51
- async def connect(self) -> None:
52
- try:
53
- self.reader, self.writer = await asyncio.wait_for(
54
- asyncio.open_connection(self.connection_parameters.host, self.connection_parameters.port),
55
- timeout=self.connect_timeout,
56
- )
57
- except (TimeoutError, ConnectionError) as exception:
58
- raise ConnectError(self.connection_parameters) from exception
59
-
60
- async def close(self) -> None:
61
- self.writer.close()
62
- await self.writer.wait_closed()
63
-
64
- def write_heartbeat(self) -> None:
65
- return self.writer.write(NEWLINE)
66
-
67
- async def write_frame(self, frame: ClientFrame) -> None:
68
- self.writer.write(dump_frame(frame))
69
- await self.writer.drain()
70
-
71
- async def _read_non_empty_bytes(self) -> bytes:
72
- while (
73
- chunk := await self.reader.read(self.read_max_chunk_size)
74
- ) == b"": # pragma: no cover (it defenitely happens)
75
- await asyncio.sleep(0)
76
- return chunk
77
-
78
- async def read_frames(self) -> AsyncGenerator[ServerFrame, None]:
79
- parser = Parser()
80
-
81
- while True:
82
- try:
83
- raw_frames = await asyncio.wait_for(self._read_non_empty_bytes(), timeout=self.read_timeout)
84
- except TimeoutError as exception:
85
- raise ReadTimeoutError(self.read_timeout) from exception
86
-
87
- for frame in cast(Iterator[ServerFrame], parser.load_frames(raw_frames)):
88
- yield frame
File without changes
File without changes