stompman 0.1.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.
@@ -0,0 +1,171 @@
1
+ Metadata-Version: 2.1
2
+ Name: stompman
3
+ Version: 0.1.0
4
+ Summary:
5
+ Author: Lev Vereshchagin
6
+ Author-email: mail@vrslev.com
7
+ Requires-Python: >=3.11,<4.0
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Programming Language :: Python :: 3.11
10
+ Classifier: Programming Language :: Python :: 3.12
11
+ Description-Content-Type: text/markdown
12
+
13
+ # stompman
14
+
15
+ A Python client for STOMP asynchronous messaging protocol that is:
16
+
17
+ - asynchronous,
18
+ - not abandoned,
19
+ - has pleasant and comprehensible API. Also: async generators, match statements, heavy typing coverage and no callbacks.
20
+
21
+ There were no such one—and now there're is.
22
+
23
+ ## How To Use
24
+
25
+ Before you start using stompman, make sure you have it installed:
26
+ ```sh
27
+ pip install stompman
28
+ poetry add stompman
29
+ ```
30
+ Initialize a client:
31
+ ```python
32
+ async with stompman.Client(
33
+ servers=[
34
+ stompman.ConnectionParameters(host="171.0.0.1", port=61616, login="user1", passcode="passcode1"),
35
+ stompman.ConnectionParameters(host="172.0.0.1", port=61616, login="user2", passcode="passcode2"),
36
+ ],
37
+ # Optional parameters with sensible defaults:
38
+ heartbeat=stompman.Heartbeat(will_send_interval_ms=1000, want_to_receive_interval_ms=1000),
39
+ connect_retry_attempts=3,
40
+ connect_retry_interval=1,
41
+ connect_timeout=2,
42
+ connection_confirmation_timeout=2,
43
+ read_timeout=2,
44
+ ) as client:
45
+ ...
46
+ ```
47
+ ### Sending Messages
48
+
49
+ To send a message, use the following code:
50
+ ```python
51
+ await client.send(body=b"hi there!", destination="/DLQ/", headers={"persistent": "true"})
52
+ ```
53
+ Or, to send messages in a transaction:
54
+ ```python
55
+ async with client.enter_transaction() as transaction:
56
+ for _ in range(10):
57
+ await client.send(body=b"hi there!", destination="/DLQ/", transaction=transaction)
58
+ await asyncio.sleep(0.1)
59
+ ```
60
+ **Listening for Messages**
61
+
62
+ Now, let's subscribe to a queue and listen for messages.
63
+
64
+ Notice that `listen()` is not bound to a destination: it will listen to all subscribed destinations. If you want separate subscribtions, create separate clients for that.
65
+ ```python
66
+ async with client.subscribe("/DLQ/"):
67
+ async for event in client.listen():
68
+ ...
69
+ ```
70
+
71
+ `...`—and that's where it gets interesting.
72
+
73
+ Before learning how to processing messages from server, we need to understand how other libraries do it. They use callbacks. Damn callbacks in asynchronous programming.
74
+
75
+ I wanted to avoid them, and came up with an elegant solution: combining async generator and match statement. Here how it looks like:
76
+
77
+ ```python
78
+ async for event in client.listen():
79
+ match event:
80
+ case stompman.MessageEvent(body=body):
81
+ print(f"message: {body!s}")
82
+ await event.ack()
83
+ case stompman.ErrorEvent(message_header=short_description, body=body):
84
+ print(f"{short_description}:\n{body!s}")
85
+ ```
86
+
87
+ More complex example, that involves handling all possible events:
88
+
89
+ ```python
90
+ async for event in client.listen():
91
+ match event:
92
+ case stompman.MessageEvent(body=body):
93
+ try:
94
+ await handle_message(body)
95
+ except Exception:
96
+ await event.nack()
97
+ raise
98
+ else:
99
+ await event.ack()
100
+ case stompman.ErrorEvent(message_header=short_description, body=body):
101
+ logger.error("Received an error from server", short_description=short_description, body=body, event=event)
102
+ case stompman.HeartbeatEvent():
103
+ await update_healthcheck_status()
104
+ case stompman.UnknownEvent():
105
+ logger.error("Received unknown event from server", event=event)
106
+
107
+
108
+ async def handle_message(body: bytes) -> None:
109
+ validated_message = MyModel.model_validate_json(body)
110
+ await run_business_logic(validated_message)
111
+ ```
112
+
113
+ And the last example where `asyncio.TaskGroup()` is used to run tasks concurrently:
114
+
115
+ ```python
116
+ async with asyncio.TaskGroup() as task_group:
117
+ async for event in client.listen():
118
+ match event:
119
+ case stompman.MessageEvent(body=body):
120
+ task_group.create_task(handle_and_ack_or_nack(body, event))
121
+ case stompman.ErrorEvent(message_header=short_description, body=body):
122
+ logger.error(
123
+ "Received an error from server", short_description=short_description, body=body, event=event
124
+ )
125
+ case stompman.HeartbeatEvent():
126
+ task_group.create_task(update_healthcheck_status())
127
+ case stompman.UnknownEvent():
128
+ logger.error("Received unknown event from server", event=event)
129
+
130
+
131
+ async def handle_message(body: bytes) -> None:
132
+ validated_message = MyModel.model_validate_json(body)
133
+ await run_business_logic(validated_message)
134
+
135
+
136
+ async def handle_and_ack_or_nack(body: bytes, event: stompman.MessageEvent) -> None:
137
+ try:
138
+ await handle_message(body)
139
+ except Exception:
140
+ await event.nack()
141
+ raise
142
+ else:
143
+ await event.ack()
144
+ ```
145
+
146
+ ### Cleaning Up
147
+
148
+ stompman takes care of cleaning up resources automatically. When you leave the context of async context managers `stompman.Client()`, `client.subscribe()`, or `client.enter_transaction()`, the necessary frames will be sent to the server.
149
+
150
+ ### Handling Connectivity Issues
151
+
152
+ - If multiple servers are provided, stompman will attempt to connect to each one simultaneously and use the first that succeeds.
153
+ - 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.
154
+ - 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).
155
+
156
+ ### ...and caveats
157
+
158
+ - stompman only runs on Python 3.11 and newer.
159
+ - It only implements [STOMP 1.1](https://stomp.github.io/stomp-specification-1.1.html). I'm open to implementing [STOMP 1.2](https://stomp.github.io/stomp-specification-1.1.html).
160
+ - The client-individual ack mode is used, which means that server requires `ack` or `nack`. In contrast, with `client` ack mode server assumes you don't care about messages that occured before you connected. And, with `auto` ack mode server assumes client successfully received the message.
161
+ - Heartbeats are required, and sent automatically on `listen()` (defaults to 1 second).
162
+
163
+ Also, I want to pointed out that:
164
+
165
+ - Protocol parsing is inspired by [aiostomp](https://github.com/pedrokiefer/aiostomp/blob/3449dcb53f43e5956ccc7662bb5b7d76bc6ef36b/aiostomp/protocol.py) (meaning: consumed by me and refactored from).
166
+ - stompman is tested and used with [Artemis ActiveMQ](https://activemq.apache.org/components/artemis/).
167
+
168
+ ## No docs
169
+
170
+ I try to keep it simple and easy to understand. May be counter-intuitive for some, but concise high-quality code speaks for itself. There're no comments and little indirection. Read the source if you wish, leave an issue if it's not enough or you want to add or fix something.
171
+
@@ -0,0 +1,158 @@
1
+ # stompman
2
+
3
+ A Python client for STOMP asynchronous messaging protocol that is:
4
+
5
+ - asynchronous,
6
+ - not abandoned,
7
+ - has pleasant and comprehensible API. Also: async generators, match statements, heavy typing coverage and no callbacks.
8
+
9
+ There were no such one—and now there're is.
10
+
11
+ ## How To Use
12
+
13
+ Before you start using stompman, make sure you have it installed:
14
+ ```sh
15
+ pip install stompman
16
+ poetry add stompman
17
+ ```
18
+ Initialize a client:
19
+ ```python
20
+ async with stompman.Client(
21
+ servers=[
22
+ stompman.ConnectionParameters(host="171.0.0.1", port=61616, login="user1", passcode="passcode1"),
23
+ stompman.ConnectionParameters(host="172.0.0.1", port=61616, login="user2", passcode="passcode2"),
24
+ ],
25
+ # Optional parameters with sensible defaults:
26
+ heartbeat=stompman.Heartbeat(will_send_interval_ms=1000, want_to_receive_interval_ms=1000),
27
+ connect_retry_attempts=3,
28
+ connect_retry_interval=1,
29
+ connect_timeout=2,
30
+ connection_confirmation_timeout=2,
31
+ read_timeout=2,
32
+ ) as client:
33
+ ...
34
+ ```
35
+ ### Sending Messages
36
+
37
+ To send a message, use the following code:
38
+ ```python
39
+ await client.send(body=b"hi there!", destination="/DLQ/", headers={"persistent": "true"})
40
+ ```
41
+ Or, to send messages in a transaction:
42
+ ```python
43
+ async with client.enter_transaction() as transaction:
44
+ for _ in range(10):
45
+ await client.send(body=b"hi there!", destination="/DLQ/", transaction=transaction)
46
+ await asyncio.sleep(0.1)
47
+ ```
48
+ **Listening for Messages**
49
+
50
+ Now, let's subscribe to a queue and listen for messages.
51
+
52
+ Notice that `listen()` is not bound to a destination: it will listen to all subscribed destinations. If you want separate subscribtions, create separate clients for that.
53
+ ```python
54
+ async with client.subscribe("/DLQ/"):
55
+ async for event in client.listen():
56
+ ...
57
+ ```
58
+
59
+ `...`—and that's where it gets interesting.
60
+
61
+ Before learning how to processing messages from server, we need to understand how other libraries do it. They use callbacks. Damn callbacks in asynchronous programming.
62
+
63
+ I wanted to avoid them, and came up with an elegant solution: combining async generator and match statement. Here how it looks like:
64
+
65
+ ```python
66
+ async for event in client.listen():
67
+ match event:
68
+ case stompman.MessageEvent(body=body):
69
+ print(f"message: {body!s}")
70
+ await event.ack()
71
+ case stompman.ErrorEvent(message_header=short_description, body=body):
72
+ print(f"{short_description}:\n{body!s}")
73
+ ```
74
+
75
+ More complex example, that involves handling all possible events:
76
+
77
+ ```python
78
+ async for event in client.listen():
79
+ match event:
80
+ case stompman.MessageEvent(body=body):
81
+ try:
82
+ await handle_message(body)
83
+ except Exception:
84
+ await event.nack()
85
+ raise
86
+ else:
87
+ await event.ack()
88
+ case stompman.ErrorEvent(message_header=short_description, body=body):
89
+ logger.error("Received an error from server", short_description=short_description, body=body, event=event)
90
+ case stompman.HeartbeatEvent():
91
+ await update_healthcheck_status()
92
+ case stompman.UnknownEvent():
93
+ logger.error("Received unknown event from server", event=event)
94
+
95
+
96
+ async def handle_message(body: bytes) -> None:
97
+ validated_message = MyModel.model_validate_json(body)
98
+ await run_business_logic(validated_message)
99
+ ```
100
+
101
+ And the last example where `asyncio.TaskGroup()` is used to run tasks concurrently:
102
+
103
+ ```python
104
+ async with asyncio.TaskGroup() as task_group:
105
+ async for event in client.listen():
106
+ match event:
107
+ case stompman.MessageEvent(body=body):
108
+ task_group.create_task(handle_and_ack_or_nack(body, event))
109
+ case stompman.ErrorEvent(message_header=short_description, body=body):
110
+ logger.error(
111
+ "Received an error from server", short_description=short_description, body=body, event=event
112
+ )
113
+ case stompman.HeartbeatEvent():
114
+ task_group.create_task(update_healthcheck_status())
115
+ case stompman.UnknownEvent():
116
+ logger.error("Received unknown event from server", event=event)
117
+
118
+
119
+ async def handle_message(body: bytes) -> None:
120
+ validated_message = MyModel.model_validate_json(body)
121
+ await run_business_logic(validated_message)
122
+
123
+
124
+ async def handle_and_ack_or_nack(body: bytes, event: stompman.MessageEvent) -> None:
125
+ try:
126
+ await handle_message(body)
127
+ except Exception:
128
+ await event.nack()
129
+ raise
130
+ else:
131
+ await event.ack()
132
+ ```
133
+
134
+ ### Cleaning Up
135
+
136
+ stompman takes care of cleaning up resources automatically. When you leave the context of async context managers `stompman.Client()`, `client.subscribe()`, or `client.enter_transaction()`, the necessary frames will be sent to the server.
137
+
138
+ ### Handling Connectivity Issues
139
+
140
+ - If multiple servers are provided, stompman will attempt to connect to each one simultaneously and use the first that succeeds.
141
+ - 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.
142
+ - 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).
143
+
144
+ ### ...and caveats
145
+
146
+ - stompman only runs on Python 3.11 and newer.
147
+ - It only implements [STOMP 1.1](https://stomp.github.io/stomp-specification-1.1.html). I'm open to implementing [STOMP 1.2](https://stomp.github.io/stomp-specification-1.1.html).
148
+ - The client-individual ack mode is used, which means that server requires `ack` or `nack`. In contrast, with `client` ack mode server assumes you don't care about messages that occured before you connected. And, with `auto` ack mode server assumes client successfully received the message.
149
+ - Heartbeats are required, and sent automatically on `listen()` (defaults to 1 second).
150
+
151
+ Also, I want to pointed out that:
152
+
153
+ - Protocol parsing is inspired by [aiostomp](https://github.com/pedrokiefer/aiostomp/blob/3449dcb53f43e5956ccc7662bb5b7d76bc6ef36b/aiostomp/protocol.py) (meaning: consumed by me and refactored from).
154
+ - stompman is tested and used with [Artemis ActiveMQ](https://activemq.apache.org/components/artemis/).
155
+
156
+ ## No docs
157
+
158
+ I try to keep it simple and easy to understand. May be counter-intuitive for some, but concise high-quality code speaks for itself. There're no comments and little indirection. Read the source if you wish, leave an issue if it's not enough or you want to add or fix something.
@@ -0,0 +1,59 @@
1
+ [tool.poetry]
2
+ name = "stompman"
3
+ version = "0.1.0"
4
+ description = ""
5
+ authors = ["Lev Vereshchagin <mail@vrslev.com>"]
6
+ readme = "README.md"
7
+
8
+ [tool.poetry.dependencies]
9
+ python = "^3.11"
10
+
11
+
12
+ [tool.poetry.group.dev.dependencies]
13
+ mypy = "^1.10.0"
14
+ ruff = "^0.4.8"
15
+ pytest = "^8.2.2"
16
+ pytest-cov = "^5.0.0"
17
+ anyio = "^4.4.0"
18
+
19
+ [build-system]
20
+ requires = ["poetry-core"]
21
+ build-backend = "poetry.core.masonry.api"
22
+
23
+
24
+ [tool.mypy]
25
+ python_version = "3.11"
26
+ warn_unused_ignores = true
27
+ strict = true
28
+
29
+ [tool.ruff]
30
+ target-version = "py311"
31
+ fix = true
32
+ unsafe-fixes = true
33
+ line-length = 120
34
+ [tool.ruff.lint]
35
+ select = ["ALL"]
36
+ ignore = [
37
+ "EM",
38
+ "FBT",
39
+ "TRY003",
40
+ "D1",
41
+ "D203",
42
+ "D213",
43
+ "G004",
44
+ "FA",
45
+ "ANN101",
46
+ "ANN102",
47
+ "COM812",
48
+ "ISC001",
49
+ "S101",
50
+ "SLF001",
51
+ ]
52
+
53
+ [tool.pytest.ini_options]
54
+ addopts = "--cov -s"
55
+
56
+ [tool.coverage.report]
57
+ skip_covered = true
58
+ show_missing = true
59
+ exclude_also = ["if TYPE_CHECKING:"]
@@ -0,0 +1,73 @@
1
+ from stompman.client import Client, Heartbeat
2
+ from stompman.connection import AbstractConnection, Connection, ConnectionParameters
3
+ from stompman.errors import (
4
+ ConnectError,
5
+ ConnectionConfirmationTimeoutError,
6
+ Error,
7
+ FailedAllConnectAttemptsError,
8
+ ReadTimeoutError,
9
+ UnsupportedProtocolVersionError,
10
+ )
11
+ from stompman.frames import (
12
+ AbortFrame,
13
+ AckFrame,
14
+ AnyFrame,
15
+ BaseFrame,
16
+ BeginFrame,
17
+ ClientFrame,
18
+ CommitFrame,
19
+ ConnectedFrame,
20
+ ConnectFrame,
21
+ DisconnectFrame,
22
+ ErrorFrame,
23
+ HeartbeatFrame,
24
+ MessageFrame,
25
+ NackFrame,
26
+ ReceiptFrame,
27
+ SendFrame,
28
+ ServerFrame,
29
+ SubscribeFrame,
30
+ UnknownFrame,
31
+ UnsubscribeFrame,
32
+ )
33
+ from stompman.listen_events import AnyListenEvent, ErrorEvent, HeartbeatEvent, MessageEvent, UnknownEvent
34
+
35
+ __all__ = [
36
+ "AbortFrame",
37
+ "AbstractConnection",
38
+ "AckFrame",
39
+ "FailedAllConnectAttemptsError",
40
+ "AnyFrame",
41
+ "AnyListenEvent",
42
+ "BaseFrame",
43
+ "BaseListenEvent",
44
+ "BeginFrame",
45
+ "ClientFrame",
46
+ "CommitFrame",
47
+ "ConnectedFrame",
48
+ "ConnectError",
49
+ "ConnectFrame",
50
+ "ConnectionConfirmationTimeoutError",
51
+ "ConnectionParameters",
52
+ "DisconnectFrame",
53
+ "ErrorEvent",
54
+ "ErrorFrame",
55
+ "Heartbeat",
56
+ "HeartbeatEvent",
57
+ "HeartbeatFrame",
58
+ "MessageEvent",
59
+ "MessageFrame",
60
+ "NackFrame",
61
+ "ReadTimeoutError",
62
+ "ReceiptFrame",
63
+ "SendFrame",
64
+ "ServerFrame",
65
+ "Client",
66
+ "Connection",
67
+ "Error",
68
+ "SubscribeFrame",
69
+ "UnknownEvent",
70
+ "UnknownFrame",
71
+ "UnsubscribeFrame",
72
+ "UnsupportedProtocolVersionError",
73
+ ]
@@ -0,0 +1,215 @@
1
+ import asyncio
2
+ import typing
3
+ from collections.abc import AsyncIterator
4
+ from contextlib import asynccontextmanager
5
+ from dataclasses import dataclass, field
6
+ from types import TracebackType
7
+ from typing import NamedTuple, Self
8
+ from uuid import uuid4
9
+
10
+ from stompman.connection import AbstractConnection, Connection, ConnectionParameters
11
+ from stompman.errors import (
12
+ ConnectError,
13
+ ConnectionConfirmationTimeoutError,
14
+ FailedAllConnectAttemptsError,
15
+ UnsupportedProtocolVersionError,
16
+ )
17
+ from stompman.frames import (
18
+ AbortFrame,
19
+ BeginFrame,
20
+ CommitFrame,
21
+ ConnectedFrame,
22
+ ConnectFrame,
23
+ DisconnectFrame,
24
+ ErrorFrame,
25
+ HeartbeatFrame,
26
+ MessageFrame,
27
+ ReceiptFrame,
28
+ SendFrame,
29
+ SubscribeFrame,
30
+ UnsubscribeFrame,
31
+ )
32
+ from stompman.listen_events import AnyListenEvent, ErrorEvent, HeartbeatEvent, MessageEvent, UnknownEvent
33
+ from stompman.protocol import HEARTBEAT_MARKER, PROTOCOL_VERSION
34
+
35
+
36
+ class Heartbeat(NamedTuple):
37
+ will_send_interval_ms: int
38
+ want_to_receive_interval_ms: int
39
+
40
+ def dump(self) -> str:
41
+ return f"{self.will_send_interval_ms},{self.want_to_receive_interval_ms}"
42
+
43
+ @classmethod
44
+ def load(cls, value: str) -> Self:
45
+ first, second = value.split(",", maxsplit=1)
46
+ return cls(int(first), int(second))
47
+
48
+
49
+ @dataclass
50
+ class Client:
51
+ servers: list[ConnectionParameters]
52
+ heartbeat: Heartbeat = field(default=Heartbeat(1000, 1000))
53
+ connect_retry_attempts: int = 3
54
+ connect_retry_interval: int = 1
55
+ connect_timeout: int = 2
56
+ connection_confirmation_timeout = 2
57
+ read_timeout: int = 2
58
+ read_max_chunk_size: int = 1024 * 1024
59
+ connection_class: type[AbstractConnection] = Connection
60
+
61
+ _connection: AbstractConnection = field(init=False)
62
+ _server_heartbeat: Heartbeat = field(init=False)
63
+
64
+ async def _connect_to_one_server(self, server: ConnectionParameters) -> AbstractConnection | None:
65
+ for attempt in range(self.connect_retry_attempts):
66
+ connection = self.connection_class(
67
+ connection_parameters=server,
68
+ connect_timeout=self.connect_timeout,
69
+ read_timeout=self.read_timeout,
70
+ read_max_chunk_size=self.read_max_chunk_size,
71
+ )
72
+ try:
73
+ await connection.connect()
74
+ except ConnectError:
75
+ await asyncio.sleep(self.connect_retry_interval * (attempt + 1))
76
+ else:
77
+ return connection
78
+ return None
79
+
80
+ async def _connect_to_any_server(self) -> AbstractConnection:
81
+ for maybe_connection_future in asyncio.as_completed(
82
+ [self._connect_to_one_server(server) for server in self.servers]
83
+ ):
84
+ maybe_connection = await maybe_connection_future
85
+ if maybe_connection:
86
+ return maybe_connection
87
+ raise FailedAllConnectAttemptsError(
88
+ servers=self.servers,
89
+ retry_attempts=self.connect_retry_attempts,
90
+ retry_interval=self.connect_retry_interval,
91
+ timeout=self.connect_timeout,
92
+ )
93
+
94
+ async def _raise_connection_unconfirmed(self) -> None:
95
+ await asyncio.sleep(self.connection_confirmation_timeout)
96
+ raise ConnectionConfirmationTimeoutError(self.connection_confirmation_timeout)
97
+
98
+ async def __aenter__(self) -> Self:
99
+ self._connection = await self._connect_to_any_server()
100
+ await self._connection.write_frame(
101
+ ConnectFrame(
102
+ headers={
103
+ "accept-version": PROTOCOL_VERSION,
104
+ "heart-beat": self.heartbeat.dump(),
105
+ "login": self._connection.connection_parameters.login,
106
+ "passcode": self._connection.connection_parameters.passcode,
107
+ },
108
+ )
109
+ )
110
+ async with asyncio.TaskGroup() as task_group:
111
+ raise_connection_unconfirmed_task = task_group.create_task(self._raise_connection_unconfirmed())
112
+ async for frame in self._connection.read_frames():
113
+ match frame:
114
+ case ConnectedFrame(headers={"version": version, "heart-beat": raw_heart_beat}):
115
+ if version != PROTOCOL_VERSION:
116
+ raise UnsupportedProtocolVersionError(
117
+ given_version=version,
118
+ supported_version=PROTOCOL_VERSION,
119
+ )
120
+ self._server_heartbeat = Heartbeat.load(raw_heart_beat)
121
+ raise_connection_unconfirmed_task.cancel()
122
+ break
123
+
124
+ return self
125
+
126
+ async def __aexit__(
127
+ self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None
128
+ ) -> None:
129
+ receipt_id = str(uuid4())
130
+ await self._connection.write_frame(DisconnectFrame(headers={"receipt": receipt_id}))
131
+
132
+ async for frame in self._connection.read_frames():
133
+ match frame:
134
+ case ReceiptFrame():
135
+ return await self._connection.close()
136
+ return None # pragma: no cover
137
+
138
+ @asynccontextmanager
139
+ async def subscribe(self, destination: str) -> typing.AsyncGenerator[None, None]:
140
+ subscription_id = str(uuid4())
141
+ await self._connection.write_frame(
142
+ SubscribeFrame(
143
+ headers={
144
+ "id": subscription_id,
145
+ "destination": destination,
146
+ "ack": "client-individual",
147
+ }
148
+ )
149
+ )
150
+
151
+ try:
152
+ yield
153
+ finally:
154
+ await self._connection.write_frame(UnsubscribeFrame(headers={"id": subscription_id}))
155
+
156
+ @asynccontextmanager
157
+ async def _start_sending_heartbeats(self) -> typing.AsyncGenerator[None, None]:
158
+ async def start() -> None:
159
+ while True:
160
+ self._connection.write_raw(HEARTBEAT_MARKER)
161
+ await asyncio.sleep(send_interval)
162
+
163
+ send_interval = (
164
+ max(
165
+ self.heartbeat.will_send_interval_ms,
166
+ self._server_heartbeat.want_to_receive_interval_ms,
167
+ )
168
+ / 1000
169
+ )
170
+
171
+ async with asyncio.TaskGroup() as task_group:
172
+ task_group.create_task(start())
173
+ yield
174
+
175
+ async def listen(self) -> AsyncIterator[AnyListenEvent]:
176
+ async with self._start_sending_heartbeats():
177
+ async for frame in self._connection.read_frames():
178
+ match frame:
179
+ case MessageFrame():
180
+ yield MessageEvent(_client=self, _frame=frame)
181
+ case ErrorFrame():
182
+ yield ErrorEvent(_client=self, _frame=frame)
183
+ case HeartbeatFrame():
184
+ yield HeartbeatEvent(_client=self, _frame=frame)
185
+ case ConnectedFrame() | ReceiptFrame(): # pragma: no cover
186
+ raise AssertionError("unreachable")
187
+ case _:
188
+ yield UnknownEvent(_client=self, _frame=frame)
189
+
190
+ async def send(
191
+ self,
192
+ body: bytes,
193
+ destination: str,
194
+ transaction: str | None = None,
195
+ headers: dict[str, str] | None = None,
196
+ ) -> None:
197
+ full_headers = headers or {}
198
+ full_headers["destination"] = destination
199
+ full_headers["content-length"] = str(len(body))
200
+ if transaction is not None:
201
+ full_headers["transaction"] = transaction
202
+ await self._connection.write_frame(SendFrame(headers=full_headers, body=body))
203
+
204
+ @asynccontextmanager
205
+ async def enter_transaction(self) -> typing.AsyncGenerator[str, None]:
206
+ transaction_id = str(uuid4())
207
+ await self._connection.write_frame(BeginFrame(headers={"transaction": transaction_id}))
208
+
209
+ try:
210
+ yield transaction_id
211
+ except Exception:
212
+ await self._connection.write_frame(AbortFrame(headers={"transaction": transaction_id}))
213
+ raise
214
+ else:
215
+ await self._connection.write_frame(CommitFrame(headers={"transaction": transaction_id}))
@@ -0,0 +1,82 @@
1
+ import asyncio
2
+ from collections.abc import AsyncGenerator, Iterable
3
+ from dataclasses import dataclass, field
4
+ from typing import Protocol, cast
5
+
6
+ from stompman.errors import ConnectError, ReadTimeoutError
7
+ from stompman.frames import ClientFrame, ServerFrame, UnknownFrame
8
+ from stompman.protocol import dump_frame, load_frames, separate_complete_and_incomplete_packets
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
+ @dataclass
20
+ class AbstractConnection(Protocol):
21
+ connection_parameters: ConnectionParameters
22
+ connect_timeout: int
23
+ read_timeout: int
24
+ read_max_chunk_size: int
25
+
26
+ async def connect(self) -> None: ...
27
+ async def close(self) -> None: ...
28
+ def write_raw(self, data: bytes) -> None: ...
29
+ async def write_frame(self, frame: ClientFrame | UnknownFrame) -> None: ...
30
+ def read_frames(self) -> AsyncGenerator[ServerFrame | UnknownFrame, None]: ...
31
+
32
+
33
+ @dataclass
34
+ class Connection(AbstractConnection):
35
+ connection_parameters: ConnectionParameters
36
+ connect_timeout: int
37
+ read_timeout: int
38
+ read_max_chunk_size: int
39
+ reader: asyncio.StreamReader = field(init=False)
40
+ writer: asyncio.StreamWriter = field(init=False)
41
+
42
+ async def connect(self) -> None:
43
+ try:
44
+ self.reader, self.writer = await asyncio.wait_for(
45
+ asyncio.open_connection(self.connection_parameters.host, self.connection_parameters.port),
46
+ timeout=self.connect_timeout,
47
+ )
48
+ except (TimeoutError, ConnectionError) as exception:
49
+ raise ConnectError(self.connection_parameters) from exception
50
+
51
+ async def close(self) -> None:
52
+ self.writer.close()
53
+ await self.writer.wait_closed()
54
+
55
+ def write_raw(self, data: bytes) -> None:
56
+ self.writer.write(data)
57
+
58
+ async def write_frame(self, frame: ClientFrame | UnknownFrame) -> None:
59
+ self.writer.write(dump_frame(frame))
60
+ await self.writer.drain()
61
+
62
+ async def _read_non_empty_bytes(self) -> bytes:
63
+ while (
64
+ read_bytes := await self.reader.read(self.read_max_chunk_size)
65
+ ) == b"": # pragma: no cover (it defenitely happens)
66
+ await asyncio.sleep(0)
67
+ return read_bytes
68
+
69
+ async def read_frames(self) -> AsyncGenerator[ServerFrame | UnknownFrame, None]:
70
+ bytes_to_prepend_in_next_round = b""
71
+
72
+ while True:
73
+ try:
74
+ read_bytes = await asyncio.wait_for(self._read_non_empty_bytes(), timeout=self.read_timeout)
75
+ except TimeoutError as exception:
76
+ raise ReadTimeoutError(timeout=self.read_timeout) from exception
77
+
78
+ frame_read_bytes, bytes_to_prepend_in_next_round = separate_complete_and_incomplete_packets(
79
+ bytes_to_prepend_in_next_round + read_bytes
80
+ )
81
+ for frame in cast(Iterable[ServerFrame], load_frames(frame_read_bytes)):
82
+ yield frame
@@ -0,0 +1,40 @@
1
+ from dataclasses import dataclass
2
+ from typing import TYPE_CHECKING
3
+
4
+ if TYPE_CHECKING:
5
+ from stompman.connection import ConnectionParameters
6
+
7
+
8
+ @dataclass
9
+ class Error(Exception):
10
+ def __str__(self) -> str:
11
+ return self.__repr__()
12
+
13
+
14
+ @dataclass
15
+ class ConnectionConfirmationTimeoutError(Error):
16
+ timeout: int
17
+
18
+
19
+ @dataclass
20
+ class UnsupportedProtocolVersionError(Error):
21
+ given_version: str
22
+ supported_version: str
23
+
24
+
25
+ @dataclass
26
+ class ConnectError(Error):
27
+ connection_parameters: "ConnectionParameters"
28
+
29
+
30
+ @dataclass
31
+ class FailedAllConnectAttemptsError(Error):
32
+ servers: list["ConnectionParameters"]
33
+ retry_attempts: int
34
+ retry_interval: int
35
+ timeout: int
36
+
37
+
38
+ @dataclass
39
+ class ReadTimeoutError(Error):
40
+ timeout: int
@@ -0,0 +1,232 @@
1
+ from dataclasses import dataclass
2
+ from typing import Generic, Literal, TypedDict, TypeVar
3
+
4
+ HeadersType = TypeVar("HeadersType")
5
+
6
+
7
+ @dataclass(frozen=True, kw_only=True)
8
+ class BaseFrame(Generic[HeadersType]):
9
+ command: str
10
+ headers: HeadersType
11
+ body: bytes = b""
12
+
13
+
14
+ ConnectHeaders = TypedDict(
15
+ "ConnectHeaders",
16
+ {
17
+ "accept-version": str,
18
+ "host": str,
19
+ "login": str,
20
+ "passcode": str,
21
+ "heart-beat": str,
22
+ },
23
+ total=False,
24
+ )
25
+
26
+
27
+ @dataclass(frozen=True, kw_only=True)
28
+ class ConnectFrame(BaseFrame[ConnectHeaders]):
29
+ command: Literal["CONNECT", "STOMP"] = "CONNECT"
30
+
31
+
32
+ ConnectedHeaders = TypedDict(
33
+ "ConnectedHeaders",
34
+ {"version": str, "server": str, "heart-beat": str},
35
+ total=False,
36
+ )
37
+
38
+
39
+ @dataclass(frozen=True, kw_only=True)
40
+ class ConnectedFrame(BaseFrame[ConnectedHeaders]):
41
+ command: Literal["CONNECTED"] = "CONNECTED"
42
+
43
+
44
+ SendHeaders = TypedDict(
45
+ "SendHeaders",
46
+ {
47
+ "content-length": str,
48
+ "content-type": str,
49
+ "destination": str,
50
+ "transaction": str,
51
+ },
52
+ total=False,
53
+ )
54
+
55
+
56
+ @dataclass(frozen=True, kw_only=True)
57
+ class SendFrame(BaseFrame[SendHeaders | dict[str, str]]):
58
+ command: Literal["SEND"] = "SEND"
59
+
60
+
61
+ class SubscribeHeaders(TypedDict, total=False):
62
+ id: str
63
+ destination: str
64
+ ack: Literal["client", "client-individual", "auto"]
65
+ transaction: str
66
+
67
+
68
+ @dataclass(frozen=True, kw_only=True)
69
+ class SubscribeFrame(BaseFrame[SubscribeHeaders]):
70
+ command: Literal["SUBSCRIBE"] = "SUBSCRIBE"
71
+
72
+
73
+ class UnsubscribeHeaders(TypedDict, total=False):
74
+ id: str
75
+
76
+
77
+ @dataclass(frozen=True, kw_only=True)
78
+ class UnsubscribeFrame(BaseFrame[UnsubscribeHeaders]):
79
+ command: Literal["UNSUBSCRIBE"] = "UNSUBSCRIBE"
80
+
81
+
82
+ AckHeaders = TypedDict(
83
+ "AckHeaders",
84
+ {
85
+ "subscription": str,
86
+ "message-id": str,
87
+ "transaction": str,
88
+ },
89
+ total=False,
90
+ )
91
+
92
+
93
+ @dataclass(frozen=True, kw_only=True)
94
+ class AckFrame(BaseFrame[AckHeaders]):
95
+ command: Literal["ACK"] = "ACK"
96
+
97
+
98
+ NackHeaders = TypedDict(
99
+ "NackHeaders",
100
+ {
101
+ "subscription": str,
102
+ "message-id": str,
103
+ "transaction": str,
104
+ },
105
+ total=False,
106
+ )
107
+
108
+
109
+ @dataclass(frozen=True, kw_only=True)
110
+ class NackFrame(BaseFrame[NackHeaders]):
111
+ command: Literal["NACK"] = "NACK"
112
+
113
+
114
+ class BeginHeaders(TypedDict, total=False):
115
+ transaction: str
116
+
117
+
118
+ @dataclass(frozen=True, kw_only=True)
119
+ class BeginFrame(BaseFrame[BeginHeaders]):
120
+ command: Literal["BEGIN"] = "BEGIN"
121
+
122
+
123
+ class CommitHeaders(TypedDict, total=False):
124
+ transaction: str
125
+
126
+
127
+ @dataclass(frozen=True, kw_only=True)
128
+ class CommitFrame(BaseFrame[CommitHeaders]):
129
+ command: Literal["COMMIT"] = "COMMIT"
130
+
131
+
132
+ class AbortHeaders(TypedDict, total=False):
133
+ transaction: str
134
+
135
+
136
+ @dataclass(frozen=True, kw_only=True)
137
+ class AbortFrame(BaseFrame[AbortHeaders]):
138
+ command: Literal["ABORT"] = "ABORT"
139
+
140
+
141
+ class DisconnectHeaders(TypedDict, total=False):
142
+ receipt: str
143
+
144
+
145
+ @dataclass(frozen=True, kw_only=True)
146
+ class DisconnectFrame(BaseFrame[DisconnectHeaders]):
147
+ command: Literal["DISCONNECT"] = "DISCONNECT"
148
+
149
+
150
+ ReceiptHeaders = TypedDict(
151
+ "ReceiptHeaders",
152
+ {
153
+ "receipt-id": str,
154
+ },
155
+ total=False,
156
+ )
157
+
158
+
159
+ @dataclass(frozen=True, kw_only=True)
160
+ class ReceiptFrame(BaseFrame[ReceiptHeaders]):
161
+ command: Literal["RECEIPT"] = "RECEIPT"
162
+
163
+
164
+ MessageHeaders = TypedDict(
165
+ "MessageHeaders",
166
+ {
167
+ "subscription": str,
168
+ "message-id": str,
169
+ "destination": str,
170
+ "content-type": str,
171
+ },
172
+ total=False,
173
+ )
174
+
175
+
176
+ @dataclass(frozen=True, kw_only=True)
177
+ class MessageFrame(BaseFrame[MessageHeaders]):
178
+ command: Literal["MESSAGE"] = "MESSAGE"
179
+
180
+
181
+ class ErrorHeaders(TypedDict, total=False):
182
+ message: str
183
+
184
+
185
+ @dataclass(frozen=True, kw_only=True)
186
+ class ErrorFrame(BaseFrame[ErrorHeaders]):
187
+ command: Literal["ERROR"] = "ERROR"
188
+
189
+
190
+ @dataclass(frozen=True, kw_only=True)
191
+ class HeartbeatFrame(BaseFrame[dict[str, str]]):
192
+ command: Literal["HEARTBEAT"] = "HEARTBEAT"
193
+
194
+
195
+ @dataclass(frozen=True, kw_only=True)
196
+ class UnknownFrame(BaseFrame[dict[str, str]]): ...
197
+
198
+
199
+ ClientFrame = (
200
+ ConnectFrame
201
+ | SendFrame
202
+ | SubscribeFrame
203
+ | UnsubscribeFrame
204
+ | BeginFrame
205
+ | CommitFrame
206
+ | AbortFrame
207
+ | AckFrame
208
+ | NackFrame
209
+ | DisconnectFrame
210
+ )
211
+ ServerFrame = ConnectedFrame | MessageFrame | ReceiptFrame | ErrorFrame | HeartbeatFrame
212
+
213
+ AnyFrame = ClientFrame | ServerFrame | UnknownFrame
214
+
215
+ COMMAND_TO_FRAME_TYPE: dict[str, type[ClientFrame | ServerFrame]] = {
216
+ "CONNECT": ConnectFrame,
217
+ "STOMP": ConnectFrame,
218
+ "SEND": SendFrame,
219
+ "SUBSCRIBE": SubscribeFrame,
220
+ "UNSUBSCRIBE": UnsubscribeFrame,
221
+ "BEGIN": BeginFrame,
222
+ "COMMIT": CommitFrame,
223
+ "ABORT": AbortFrame,
224
+ "ACK": AckFrame,
225
+ "NACK": NackFrame,
226
+ "DISCONNECT": DisconnectFrame,
227
+ "HEARTBEAT": HeartbeatFrame,
228
+ "CONNECTED": ConnectedFrame,
229
+ "MESSAGE": MessageFrame,
230
+ "RECEIPT": ReceiptFrame,
231
+ "ERROR": ErrorFrame,
232
+ }
@@ -0,0 +1,71 @@
1
+ from dataclasses import dataclass, field
2
+ from typing import TYPE_CHECKING
3
+
4
+ from stompman.frames import (
5
+ AckFrame,
6
+ ErrorFrame,
7
+ HeartbeatFrame,
8
+ MessageFrame,
9
+ NackFrame,
10
+ UnknownFrame,
11
+ )
12
+
13
+ if TYPE_CHECKING:
14
+ from stompman.client import Client
15
+
16
+
17
+ @dataclass
18
+ class MessageEvent:
19
+ body: bytes = field(init=False)
20
+ _frame: MessageFrame
21
+ _client: "Client" = field(repr=False)
22
+
23
+ def __post_init__(self) -> None:
24
+ self.body = self._frame.body
25
+
26
+ async def ack(self) -> None:
27
+ await self._client._connection.write_frame(
28
+ AckFrame(
29
+ headers={
30
+ "subscription": self._frame.headers["subscription"],
31
+ "message-id": self._frame.headers["message-id"],
32
+ },
33
+ )
34
+ )
35
+
36
+ async def nack(self) -> None:
37
+ await self._client._connection.write_frame(
38
+ NackFrame(
39
+ headers={
40
+ "subscription": self._frame.headers["subscription"],
41
+ "message-id": self._frame.headers["message-id"],
42
+ },
43
+ )
44
+ )
45
+
46
+
47
+ @dataclass
48
+ class ErrorEvent:
49
+ message_header: str = field(init=False)
50
+ body: bytes = field(init=False)
51
+ _frame: ErrorFrame
52
+ _client: "Client" = field(repr=False)
53
+
54
+ def __post_init__(self) -> None:
55
+ self.message_header = self._frame.headers["message"]
56
+ self.body = self._frame.body
57
+
58
+
59
+ @dataclass
60
+ class HeartbeatEvent:
61
+ _frame: HeartbeatFrame
62
+ _client: "Client" = field(repr=False)
63
+
64
+
65
+ @dataclass
66
+ class UnknownEvent:
67
+ _frame: UnknownFrame
68
+ _client: "Client" = field(repr=False)
69
+
70
+
71
+ AnyListenEvent = MessageEvent | ErrorEvent | HeartbeatEvent | UnknownEvent
@@ -0,0 +1,137 @@
1
+ import itertools
2
+ import struct
3
+ from collections import deque
4
+ from collections.abc import Iterator
5
+ from typing import Any, cast
6
+
7
+ from stompman.frames import (
8
+ COMMAND_TO_FRAME_TYPE,
9
+ AnyFrame,
10
+ BaseFrame,
11
+ HeartbeatFrame,
12
+ UnknownFrame,
13
+ )
14
+
15
+ PROTOCOL_VERSION = "1.1" # https://stomp.github.io/stomp-specification-1.1.html
16
+ ESCAPE_CHARS = {
17
+ "\n": "\\n",
18
+ ":": "\\c",
19
+ "\\": "\\\\",
20
+ "\r": "\\r",
21
+ }
22
+ REVERSE_ESCAPE_CHARS = {
23
+ b"n": b"\n"[0],
24
+ b"c": b":"[0],
25
+ b"\\": b"\\"[0],
26
+ b"r": b"\r"[0],
27
+ }
28
+ EOF_MARKER = b"\x00"
29
+ HEARTBEAT_MARKER = b"\n"
30
+ CRLFCRLR_MARKER = (b"\r", b"\n", b"\r", b"\n")
31
+
32
+
33
+ def escape_header_value(header: str) -> str:
34
+ return "".join(ESCAPE_CHARS.get(char, char) for char in header)
35
+
36
+
37
+ def iter_bytes(value: bytes) -> Iterator[bytes]:
38
+ yield from cast(tuple[bytes, ...], struct.unpack(f"{len(value)!s}c", value))
39
+
40
+
41
+ def unescape_header(header: bytes) -> bytes:
42
+ def unescape() -> Iterator[int]:
43
+ previous_byte = None
44
+
45
+ for byte in iter_bytes(header):
46
+ if previous_byte == b"\\":
47
+ yield REVERSE_ESCAPE_CHARS.get(byte, byte[0])
48
+ elif byte != b"\\":
49
+ yield byte[0]
50
+
51
+ previous_byte = byte
52
+
53
+ return bytes(unescape())
54
+
55
+
56
+ def parse_one_line(buffer: deque[bytes]) -> bytes:
57
+ def parse() -> Iterator[int]:
58
+ while (byte := buffer.popleft()) != b"\n":
59
+ yield byte[0]
60
+
61
+ return bytes(parse())
62
+
63
+
64
+ def ends_with_crlf(buffer: deque[bytes]) -> bool:
65
+ size = len(buffer)
66
+ four_last_bytes = tuple(itertools.islice(buffer, max(0, size - 4), size))
67
+ return four_last_bytes == CRLFCRLR_MARKER
68
+
69
+
70
+ def separate_complete_and_incomplete_packets(raw_frames: bytes) -> tuple[bytes, bytes]:
71
+ if raw_frames.replace(b"\n", b"") == b"":
72
+ return (raw_frames, b"")
73
+
74
+ if raw_frames.endswith(EOF_MARKER):
75
+ return (raw_frames, b"")
76
+
77
+ return raw_frames.rpartition(EOF_MARKER)[0] + raw_frames.rpartition(EOF_MARKER)[1], raw_frames.rpartition(
78
+ EOF_MARKER
79
+ )[2]
80
+
81
+
82
+ def dump_frame(frame: BaseFrame[Any]) -> bytes:
83
+ lines = (
84
+ frame.command.encode(),
85
+ b"\n",
86
+ *(f"{key}:{escape_header_value(value)}\n".encode() for key, value in sorted(frame.headers.items())),
87
+ b"\n",
88
+ frame.body,
89
+ EOF_MARKER,
90
+ )
91
+ return b"".join(lines)
92
+
93
+
94
+ def _build_frame_from_buffer(buffer: deque[bytes]) -> AnyFrame:
95
+ command = parse_one_line(buffer).decode()
96
+ headers: Any = {}
97
+
98
+ while len(line := parse_one_line(buffer)) > 1:
99
+ key, value = line.split(b":", 1)
100
+ decoded_key = key.decode()
101
+
102
+ if decoded_key not in headers:
103
+ headers[decoded_key] = unescape_header(value).decode()
104
+
105
+ body = b"".join(buffer)
106
+ if known_frame_type := COMMAND_TO_FRAME_TYPE.get(command):
107
+ return known_frame_type(headers=headers, body=body)
108
+ return UnknownFrame(command=command, headers=headers, body=body)
109
+
110
+
111
+ def load_frames(raw_frames: bytes) -> Iterator[AnyFrame]:
112
+ buffer = deque[bytes]()
113
+ previous_byte = None
114
+ has_processed_headers = False
115
+
116
+ for byte in iter_bytes(raw_frames):
117
+ # parse body until EOF is reached
118
+ if has_processed_headers:
119
+ if byte == EOF_MARKER:
120
+ yield _build_frame_from_buffer(buffer)
121
+ buffer.clear()
122
+ has_processed_headers = False
123
+ else:
124
+ buffer.append(byte)
125
+ # heartbeat sent
126
+ elif byte == HEARTBEAT_MARKER and not buffer:
127
+ yield HeartbeatFrame(headers={})
128
+ continue
129
+ # parse command and headers
130
+ else:
131
+ buffer.append(byte)
132
+
133
+ # command and headers parsed, time to start parsing body
134
+ if byte == b"\n" and (previous_byte == b"\n" or ends_with_crlf(buffer)):
135
+ has_processed_headers = True
136
+
137
+ previous_byte = byte
File without changes