dsmq 1.3.0__tar.gz → 1.4.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.
- {dsmq-1.3.0 → dsmq-1.4.0}/PKG-INFO +11 -1
- {dsmq-1.3.0 → dsmq-1.4.0}/README.md +10 -0
- dsmq-1.4.0/post.md +244 -0
- {dsmq-1.3.0 → dsmq-1.4.0}/pyproject.toml +1 -1
- dsmq-1.4.0/src/dsmq/.client.py.swp +0 -0
- dsmq-1.4.0/src/dsmq/.server.py.swp +0 -0
- {dsmq-1.3.0 → dsmq-1.4.0}/src/dsmq/client.py +34 -2
- {dsmq-1.3.0 → dsmq-1.4.0}/src/dsmq/demo.py +8 -3
- dsmq-1.4.0/src/dsmq/server.py +305 -0
- {dsmq-1.3.0 → dsmq-1.4.0}/src/dsmq/tests/integration_test.py +44 -17
- {dsmq-1.3.0 → dsmq-1.4.0}/src/dsmq/tests/performance_suite.py +11 -2
- dsmq-1.4.0/uv.lock +177 -0
- dsmq-1.3.0/src/dsmq/.server.py.swp +0 -0
- dsmq-1.3.0/src/dsmq/server.py +0 -245
- dsmq-1.3.0/src/dsmq/tests/.performance_suite.py.swp +0 -0
- dsmq-1.3.0/uv.lock +0 -177
- {dsmq-1.3.0 → dsmq-1.4.0}/.gitignore +0 -0
- {dsmq-1.3.0 → dsmq-1.4.0}/.python-version +0 -0
- {dsmq-1.3.0 → dsmq-1.4.0}/LICENSE +0 -0
- {dsmq-1.3.0 → dsmq-1.4.0}/src/dsmq/__init__.py +0 -0
- {dsmq-1.3.0 → dsmq-1.4.0}/src/dsmq/example_get_client.py +0 -0
- {dsmq-1.3.0 → dsmq-1.4.0}/src/dsmq/example_put_client.py +0 -0
- {dsmq-1.3.0 → dsmq-1.4.0}/src/dsmq/tests/__init__.py +0 -0
@@ -1,6 +1,6 @@
|
|
1
1
|
Metadata-Version: 2.4
|
2
2
|
Name: dsmq
|
3
|
-
Version: 1.
|
3
|
+
Version: 1.4.0
|
4
4
|
Summary: A dead simple message queue
|
5
5
|
License-File: LICENSE
|
6
6
|
Requires-Python: >=3.10
|
@@ -152,6 +152,16 @@ connected to the server.
|
|
152
152
|
in the topic, or the topic doesn't yet exist,
|
153
153
|
returns `""`.
|
154
154
|
|
155
|
+
### `get_latest(topic)`
|
156
|
+
|
157
|
+
Get the *most recent* eligible message from the queue named `topic`.
|
158
|
+
All the messages older than that in the queue become ineligible and never
|
159
|
+
get seen by the client.
|
160
|
+
- `topic` (str)
|
161
|
+
- returns str, the content of the message. If there was no eligble message
|
162
|
+
in the topic, or the topic doesn't yet exist,
|
163
|
+
returns `""`.
|
164
|
+
|
155
165
|
### `get_wait(topic)`
|
156
166
|
|
157
167
|
A variant of `get()` that retries a few times until it gets
|
@@ -142,6 +142,16 @@ connected to the server.
|
|
142
142
|
in the topic, or the topic doesn't yet exist,
|
143
143
|
returns `""`.
|
144
144
|
|
145
|
+
### `get_latest(topic)`
|
146
|
+
|
147
|
+
Get the *most recent* eligible message from the queue named `topic`.
|
148
|
+
All the messages older than that in the queue become ineligible and never
|
149
|
+
get seen by the client.
|
150
|
+
- `topic` (str)
|
151
|
+
- returns str, the content of the message. If there was no eligble message
|
152
|
+
in the topic, or the topic doesn't yet exist,
|
153
|
+
returns `""`.
|
154
|
+
|
145
155
|
### `get_wait(topic)`
|
146
156
|
|
147
157
|
A variant of `get()` that retries a few times until it gets
|
dsmq-1.4.0/post.md
ADDED
@@ -0,0 +1,244 @@
|
|
1
|
+
# dsmq
|
2
|
+
|
3
|
+
I'd like to introduce [dsmq](https://github.com/brohrer/dsmq),
|
4
|
+
the Dead Simple Message Queue, to the world.
|
5
|
+
|
6
|
+
Part mail room, part bulletin board, dsmq is a central location for sharing messages
|
7
|
+
between processes, even when they are running on different computers.
|
8
|
+
|
9
|
+
Its defining characteristic is bare-bones simplicity.
|
10
|
+
|
11
|
+

|
27
|
+
|
28
|
+
## What dsmq does
|
29
|
+
|
30
|
+
A message queue lets different processes talk to each other, within or across machines.
|
31
|
+
Message queues are a waystation, a place to publish messages and hold them until
|
32
|
+
they get picked up by the process that needs them.
|
33
|
+
|
34
|
+
In dsmq, a program running the message queue starts up first (the server).
|
35
|
+
It handles all the
|
36
|
+
receiving, delivering, sorting, and storing of messages.
|
37
|
+
|
38
|
+
Other programs (the clients) connect to the server. They add messages to a queue
|
39
|
+
or read messages from a queue. Each queue is a separate topic.
|
40
|
+
|
41
|
+
## Why message queues?
|
42
|
+
Message queues are invaluable for distributed systems of all sorts,
|
43
|
+
but my favorite application is robotics.
|
44
|
+
Robots typically have several (or many) processes doing different things at different
|
45
|
+
speeds. Communication between processes is a fundamental part of any moderately
|
46
|
+
complex automated system.
|
47
|
+
When [ROS](https://www.ros.org) (the Robot Operating System) was
|
48
|
+
released, one of the big gifts it gave to robot builders was a reliable way to
|
49
|
+
pass messages.
|
50
|
+
|
51
|
+
## Why another message queue?
|
52
|
+
|
53
|
+
There are lots of [message queues](https://en.wikipedia.org/wiki/Message_queue)
|
54
|
+
in the world, and some are quite well known--Amazon SQS,
|
55
|
+
RabbitMQ, Apache Kafka to name a few. It's fair to ask why this one was created.
|
56
|
+
|
57
|
+
The official reason for dsmq's existence is that all the other available options
|
58
|
+
are pretty heavy. Take RabbitMQ for instance, a popular open source message queue.
|
59
|
+
It has hundreds of associated repositories and it's core
|
60
|
+
[rabbitmq-server](https://github.com/rabbitmq/rabbitmq-server) repo has many thousands
|
61
|
+
of lines of code. It's a heavy lift to import this to support a small robotics project,
|
62
|
+
and code running on small edge devices may struggle to run it at all.
|
63
|
+
|
64
|
+
RabbitMQ is also mature and optimized and dockerized and multi-platform
|
65
|
+
and fully featured and a lot of other things a robot doesn't need. It would
|
66
|
+
be out of balance to use it for a small project.
|
67
|
+
|
68
|
+

|
71
|
+
|
72
|
+
dsmq is only about 200 lines of Python, including client and server code. It's *tiny*.
|
73
|
+
Good for reading and understanding front-to-back when you're integrating it with
|
74
|
+
your project.
|
75
|
+
|
76
|
+
But the real reason is that I wanted to understand how a message queue might work
|
77
|
+
and the best way I know to learn this is to build one.
|
78
|
+
|
79
|
+
## How to use dsmq
|
80
|
+
|
81
|
+
### Install it
|
82
|
+
|
83
|
+
```
|
84
|
+
pip install dsmq
|
85
|
+
```
|
86
|
+
or
|
87
|
+
```
|
88
|
+
uv add dsmq
|
89
|
+
```
|
90
|
+
|
91
|
+
### Spin up a dsmq server
|
92
|
+
|
93
|
+
```python
|
94
|
+
from dsmq import dsmq
|
95
|
+
dsmq.start_server(host="127.0.0.1", port=12345)
|
96
|
+
```
|
97
|
+
|
98
|
+
### Connect a client to a dsmq server
|
99
|
+
|
100
|
+
```python
|
101
|
+
mq = dsmq.connect_to_server(host="127.0.0.1", port=12345)
|
102
|
+
```
|
103
|
+
|
104
|
+
### Add a message to a topic queue
|
105
|
+
|
106
|
+
```python
|
107
|
+
topic = "greetings"
|
108
|
+
msg = "hello world!"
|
109
|
+
mq.put(topic, msg)
|
110
|
+
```
|
111
|
+
|
112
|
+
### Read a message from a topic queue
|
113
|
+
|
114
|
+
```python
|
115
|
+
topic = "greetings"
|
116
|
+
msg = mq.get(topic)
|
117
|
+
```
|
118
|
+
|
119
|
+
### Run a demo
|
120
|
+
|
121
|
+
0. Open 3 separate terminal windows.
|
122
|
+
1. In the first, run `src/dsmq/dsmq.py`.
|
123
|
+
2. In the second, run `src/dsmq/example_put_client.py`.
|
124
|
+
3. In the third, run `src/dsmq/example_get_client.py`.
|
125
|
+
|
126
|
+
Alternatively, if you're on Linux just run `src/dsmq/demo_linux.py`.
|
127
|
+
(Linux has some process forking capabilities that Windows doesn't and
|
128
|
+
that macOS forbids. It makes for a nice self-contained multiprocess demo.)
|
129
|
+
|
130
|
+
## How it works
|
131
|
+
|
132
|
+
- Many clients can read messages from the same topic queue. dsmq uses a one-to-many
|
133
|
+
publication model.
|
134
|
+
|
135
|
+
- A client will get the oldest message available on a requested topic.
|
136
|
+
Queues are first-in-first-out.
|
137
|
+
|
138
|
+
- Clients will only be able to get messages that were added to a queue after the
|
139
|
+
time they connected to the server. Any messages older that that won't be visible.
|
140
|
+
|
141
|
+
- dsmq is asyncronous. There are no guarantees about how soon a message will arrive
|
142
|
+
at its intended client.
|
143
|
+
|
144
|
+
- dsmq is backed by an in-memory SQLite database. If your message volumes
|
145
|
+
get larger than your RAM, you will reach an out-of-memory condition.
|
146
|
+
```python
|
147
|
+
sqlite_conn = sqlite3.connect("file:mem1?mode=memory&cache=shared")
|
148
|
+
```
|
149
|
+
- `put()` and `get()` operations are fairly quick--less than 100 $`\mu`$s of processing
|
150
|
+
time plus any network latency--so it can comfortably handle requests at rates of
|
151
|
+
hundreds of times per second. But if you have several clients reading and writing
|
152
|
+
at 1 kHz or more, you may overload the queue.
|
153
|
+
|
154
|
+
- A client will not be able to read any of the messages that were put into
|
155
|
+
a queue before it connected.
|
156
|
+
|
157
|
+
- Messages older than 600 seconds will be deleted from the queue.
|
158
|
+
- In case of contention for the lock on the database, failed queries will be
|
159
|
+
retried several times, with exponential backoff. None of this is visible to
|
160
|
+
the clients, but it helps keep the internal operations reliable.
|
161
|
+
|
162
|
+
```python
|
163
|
+
for i_retry in range(_n_retries):
|
164
|
+
try:
|
165
|
+
cursor.execute("""...
|
166
|
+
```
|
167
|
+
|
168
|
+
- To keep things bare bones, the connections are all implemented in the
|
169
|
+
socket layer, rather than WebSockets or http in the application layer.
|
170
|
+
```python
|
171
|
+
self.dsmq_conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
172
|
+
self.dsmq_conn.connect((host, port))
|
173
|
+
```
|
174
|
+
- ...however, working on this lower level meant dsmq had to reinvent the wheel of
|
175
|
+
message headers. Each dsmq message is sent with a header that tells it exactly
|
176
|
+
how many bytes to expect in it. The header format is simplistic--a message
|
177
|
+
with one million plus the number of byes in the following message. Doing it this
|
178
|
+
way means that the header is
|
179
|
+
exactly 23 bytes long every time. (As long as the message is less than nine million
|
180
|
+
bytes long.)
|
181
|
+
|
182
|
+
- Every time a new client connects to the server, a new thread is created.
|
183
|
+
That thread listens for any `get()` or `put()` requests the client might make
|
184
|
+
and handles them immediately.
|
185
|
+
```python
|
186
|
+
Thread(target=_handle_client_connection, args=(socket_conn,)).start()
|
187
|
+
```
|
188
|
+
|
189
|
+
- dsmq retrieves the oldest eligible message from the queue. If a client wants
|
190
|
+
to ensure it is getting the most recent message from the queue, it will need
|
191
|
+
to iteratively get messages until there are no more left to be gotten.
|
192
|
+
```python
|
193
|
+
msg_str = "<no response>"
|
194
|
+
response = None
|
195
|
+
while response != "":
|
196
|
+
msg_str = response
|
197
|
+
response = self.mq.get("<topic>")
|
198
|
+
```
|
199
|
+
|
200
|
+
- dsmq messages are text fields, but Python dictionaries are a very convenient and
|
201
|
+
common format for passing structured messages. Use the `json` library to convert
|
202
|
+
from dictionaries to strings and back.
|
203
|
+
```python
|
204
|
+
topic = "update"
|
205
|
+
msg_dict = {"timestep": 374, "value": 3.897}
|
206
|
+
msg_str = json.dumps(msg_dict)
|
207
|
+
dsmq.put(topic, msg_str)
|
208
|
+
|
209
|
+
msg_str = dsmq.get(topic)
|
210
|
+
msg_dict = json.loads(msg_str)
|
211
|
+
```
|
212
|
+
|
213
|
+
- dsmq is opinionated. Parameters for controlling behavior are set to reasonable
|
214
|
+
defaults and not exposed to the user. The additional complexity in the API is
|
215
|
+
not worth the value of making them user-controlled.
|
216
|
+
However they are also clearly labeled and very easy to find. If anyone cares enough to
|
217
|
+
play with them, they are strongly encouraged to fork dsmq and make it their own.
|
218
|
+
|
219
|
+
```python
|
220
|
+
_message_length_offset = 1_000_000
|
221
|
+
_header_length = 23
|
222
|
+
_n_retries = 5
|
223
|
+
_first_retry = 0.01 # seconds
|
224
|
+
_time_to_live = 600.0 # seconds
|
225
|
+
```
|
226
|
+
|
227
|
+
- dsmq is deliberately built to have as few dependencies as it can get away with.
|
228
|
+
As of this writing, it doesn't depend on any third party packages and just a handful
|
229
|
+
of core packages: `json`, `socket`, `sqlite3`, `sys`, and `threading`.
|
230
|
+
|
231
|
+
# Dead Simple
|
232
|
+
|
233
|
+
Dead simple is an aesthetic.
|
234
|
+
It says that the ideal is achieved not when nothing more can be added,
|
235
|
+
but when nothing more can be taken away.
|
236
|
+
It is the aims to follow the apocryphal advice of Albert Einstein, to make
|
237
|
+
a thing as simple as possible, but no simpler.
|
238
|
+
|
239
|
+
Dead simple is like keystroke golfing, but instead of minimizing the number of
|
240
|
+
characters, it minimizes the number of concepts a developer or a user
|
241
|
+
has to hold in their head.
|
242
|
+
|
243
|
+
I've tried to embody it in dsmq.
|
244
|
+
dsmq has fewer lines of code than RabbitMQ has *repositories*. And that tickles me.
|
Binary file
|
Binary file
|
@@ -18,6 +18,7 @@ def connect(host=_default_host, port=_default_port, verbose=False):
|
|
18
18
|
class DSMQClientSideConnection:
|
19
19
|
def __init__(self, host, port, verbose=False):
|
20
20
|
self.uri = f"ws://{host}:{port}"
|
21
|
+
self.port = port
|
21
22
|
self.verbose = verbose
|
22
23
|
if self.verbose:
|
23
24
|
print(f"Connecting to dsmq server at {self.uri}")
|
@@ -40,13 +41,41 @@ class DSMQClientSideConnection:
|
|
40
41
|
|
41
42
|
def get(self, topic):
|
42
43
|
msg = {"action": "get", "topic": topic}
|
43
|
-
|
44
|
+
try:
|
45
|
+
self.websocket.send(json.dumps(msg))
|
46
|
+
except ConnectionClosedError:
|
47
|
+
return ""
|
48
|
+
|
49
|
+
try:
|
50
|
+
msg_text = self.websocket.recv()
|
51
|
+
except ConnectionClosedError:
|
52
|
+
self.close()
|
53
|
+
return ""
|
54
|
+
|
55
|
+
msg = json.loads(msg_text)
|
56
|
+
return msg["message"]
|
57
|
+
|
58
|
+
def get_latest(self, topic):
|
59
|
+
"""
|
60
|
+
A variant of `get()` that grabs the latest available message
|
61
|
+
(if there is one) rather than grabbing the oldest unread message.
|
62
|
+
It will not go back to read older ones on subsequent calls;
|
63
|
+
it will leave them unread.
|
64
|
+
"""
|
65
|
+
msg = {"action": "get_latest", "topic": topic}
|
66
|
+
try:
|
67
|
+
self.websocket.send(json.dumps(msg))
|
68
|
+
except ConnectionClosedError:
|
69
|
+
return ""
|
70
|
+
|
44
71
|
try:
|
45
72
|
msg_text = self.websocket.recv()
|
46
73
|
except ConnectionClosedError:
|
47
74
|
self.close()
|
75
|
+
return ""
|
48
76
|
|
49
77
|
msg = json.loads(msg_text)
|
78
|
+
|
50
79
|
return msg["message"]
|
51
80
|
|
52
81
|
def get_wait(self, topic):
|
@@ -64,7 +93,10 @@ class DSMQClientSideConnection:
|
|
64
93
|
|
65
94
|
def put(self, topic, msg_body):
|
66
95
|
msg_dict = {"action": "put", "topic": topic, "message": msg_body}
|
67
|
-
|
96
|
+
try:
|
97
|
+
self.websocket.send(json.dumps(msg_dict))
|
98
|
+
except ConnectionClosedError:
|
99
|
+
return
|
68
100
|
|
69
101
|
def shutdown_server(self):
|
70
102
|
msg_dict = {"action": "shutdown", "topic": ""}
|
@@ -1,7 +1,12 @@
|
|
1
1
|
import multiprocessing as mp
|
2
|
-
|
3
|
-
|
4
|
-
|
2
|
+
|
3
|
+
# spawn is the default method on macOS,
|
4
|
+
# starting in Python 3.14 it will be the default in Linux too.
|
5
|
+
mp.set_start_method("spawn")
|
6
|
+
|
7
|
+
from dsmq.server import serve # noqa: E402
|
8
|
+
import dsmq.example_get_client # noqa: E402
|
9
|
+
import dsmq.example_put_client # noqa: E402
|
5
10
|
|
6
11
|
HOST = "127.0.0.1"
|
7
12
|
PORT = 25252
|
@@ -0,0 +1,305 @@
|
|
1
|
+
import json
|
2
|
+
import os
|
3
|
+
import sqlite3
|
4
|
+
import sys
|
5
|
+
from threading import Thread
|
6
|
+
import time
|
7
|
+
from websockets.sync.server import serve as ws_serve
|
8
|
+
from websockets.exceptions import ConnectionClosedError, ConnectionClosedOK
|
9
|
+
|
10
|
+
_default_host = "127.0.0.1"
|
11
|
+
_default_port = 30008
|
12
|
+
_max_queue_length = 10
|
13
|
+
_shutdown_pause = 1.0 # seconds
|
14
|
+
_time_between_cleanup = 3.0 # seconds
|
15
|
+
_time_to_keep = 0.3 # seconds
|
16
|
+
|
17
|
+
# Make this global so it's easy to share
|
18
|
+
dsmq_server = None
|
19
|
+
|
20
|
+
|
21
|
+
def serve(
|
22
|
+
host=_default_host,
|
23
|
+
port=_default_port,
|
24
|
+
name="mqdb",
|
25
|
+
verbose=False,
|
26
|
+
):
|
27
|
+
"""
|
28
|
+
For best results, start this running in its own process and walk away.
|
29
|
+
"""
|
30
|
+
# May occasionally create files with this name.
|
31
|
+
# https://sqlite.org/inmemorydb.html
|
32
|
+
# "...parts of a temporary database might be flushed to disk if the
|
33
|
+
# database becomes large or if SQLite comes under memory pressure."
|
34
|
+
global _db_name
|
35
|
+
_db_name = f"file:{name}?mode=memory&cache=shared"
|
36
|
+
|
37
|
+
cleanup_temp_files()
|
38
|
+
sqlite_conn = sqlite3.connect(_db_name)
|
39
|
+
cursor = sqlite_conn.cursor()
|
40
|
+
|
41
|
+
# Tweak the connection to make it faster
|
42
|
+
# and keep long-term latency more predictable.
|
43
|
+
# These also make it more susceptible to corruption during shutdown,
|
44
|
+
# but since dsmq is meant to be ephemeral, that's not a concern.
|
45
|
+
# See https://www.sqlite.org/pragma.html
|
46
|
+
#
|
47
|
+
cursor.execute("PRAGMA journal_mode = OFF")
|
48
|
+
# cursor.execute("PRAGMA journal_mode = MEMORY")
|
49
|
+
# cursor.execute("PRAGMA synchronous = NORMAL")
|
50
|
+
cursor.execute("PRAGMA synchronous = OFF")
|
51
|
+
cursor.execute("PRAGMA secure_delete = OFF")
|
52
|
+
cursor.execute("PRAGMA temp_store = MEMORY")
|
53
|
+
|
54
|
+
cursor.execute("""
|
55
|
+
CREATE TABLE IF NOT EXISTS messages (timestamp DOUBLE, topic TEXT, message TEXT)
|
56
|
+
""")
|
57
|
+
|
58
|
+
# Making this global in scope is a way to make it available
|
59
|
+
# to the shutdown operation. It's an awkward construction,
|
60
|
+
# and a method of last resort.
|
61
|
+
global dsmq_server
|
62
|
+
|
63
|
+
try:
|
64
|
+
with ws_serve(request_handler, host, port) as dsmq_server:
|
65
|
+
dsmq_server.serve_forever()
|
66
|
+
|
67
|
+
except OSError:
|
68
|
+
# Catch the case where the address is already in use
|
69
|
+
if verbose:
|
70
|
+
print()
|
71
|
+
print(f"Found a dsmq server already running on {host} on port {port}.")
|
72
|
+
print(" Closing it down.")
|
73
|
+
|
74
|
+
def shutdown_gracefully(server_to_shutdown):
|
75
|
+
server_to_shutdown.shutdown()
|
76
|
+
|
77
|
+
Thread(target=shutdown_gracefully, args=(dsmq_server,)).start()
|
78
|
+
time.sleep(_shutdown_pause)
|
79
|
+
|
80
|
+
with ws_serve(request_handler, host, port) as dsmq_server:
|
81
|
+
dsmq_server.serve_forever()
|
82
|
+
|
83
|
+
if verbose:
|
84
|
+
print()
|
85
|
+
print(f"Server started at {host} on port {port}.")
|
86
|
+
print("Waiting for clients...")
|
87
|
+
|
88
|
+
sqlite_conn.close()
|
89
|
+
time.sleep(_shutdown_pause)
|
90
|
+
cleanup_temp_files()
|
91
|
+
|
92
|
+
|
93
|
+
def cleanup_temp_files():
|
94
|
+
# Under some condition
|
95
|
+
# (which I haven't yet been able to pin down)
|
96
|
+
# a file is generated with the db name.
|
97
|
+
# If it is not removed, it gets
|
98
|
+
# treated as a SQLite db on disk,
|
99
|
+
# which dramatically slows it down,
|
100
|
+
# especially the way it's used here for
|
101
|
+
# rapid-fire one-item reads and writes.
|
102
|
+
global _db_name
|
103
|
+
filenames = os.listdir()
|
104
|
+
for filename in filenames:
|
105
|
+
if filename[: len(_db_name)] == _db_name:
|
106
|
+
try:
|
107
|
+
os.remove(filename)
|
108
|
+
except FileNotFoundError:
|
109
|
+
pass
|
110
|
+
|
111
|
+
|
112
|
+
def request_handler(websocket):
|
113
|
+
global _db_name
|
114
|
+
sqlite_conn = sqlite3.connect(_db_name)
|
115
|
+
cursor = sqlite_conn.cursor()
|
116
|
+
|
117
|
+
client_creation_time = time.time()
|
118
|
+
last_read_times = {}
|
119
|
+
time_of_last_purge = time.time()
|
120
|
+
|
121
|
+
try:
|
122
|
+
for msg_text in websocket:
|
123
|
+
msg = json.loads(msg_text)
|
124
|
+
topic = msg["topic"]
|
125
|
+
action = msg["action"]
|
126
|
+
timestamp = time.time()
|
127
|
+
|
128
|
+
if action == "put":
|
129
|
+
msg["timestamp"] = timestamp
|
130
|
+
|
131
|
+
try:
|
132
|
+
cursor.execute(
|
133
|
+
"""
|
134
|
+
INSERT INTO messages (timestamp, topic, message)
|
135
|
+
VALUES (:timestamp, :topic, :message)
|
136
|
+
""",
|
137
|
+
(msg),
|
138
|
+
)
|
139
|
+
sqlite_conn.commit()
|
140
|
+
except sqlite3.OperationalError:
|
141
|
+
pass
|
142
|
+
|
143
|
+
elif action == "get":
|
144
|
+
try:
|
145
|
+
last_read_time = last_read_times[topic]
|
146
|
+
except KeyError:
|
147
|
+
last_read_times[topic] = client_creation_time
|
148
|
+
last_read_time = last_read_times[topic]
|
149
|
+
msg["last_read_time"] = last_read_time
|
150
|
+
|
151
|
+
try:
|
152
|
+
cursor.execute(
|
153
|
+
"""
|
154
|
+
SELECT message,
|
155
|
+
timestamp
|
156
|
+
FROM messages
|
157
|
+
WHERE topic = :topic
|
158
|
+
AND timestamp > :last_read_time
|
159
|
+
ORDER BY timestamp ASC
|
160
|
+
LIMIT 1
|
161
|
+
""",
|
162
|
+
msg,
|
163
|
+
)
|
164
|
+
except sqlite3.OperationalError:
|
165
|
+
pass
|
166
|
+
|
167
|
+
try:
|
168
|
+
result = cursor.fetchall()[0]
|
169
|
+
message = result[0]
|
170
|
+
timestamp = result[1]
|
171
|
+
last_read_times[topic] = timestamp
|
172
|
+
except IndexError:
|
173
|
+
# Handle the case where no results are returned
|
174
|
+
message = ""
|
175
|
+
|
176
|
+
websocket.send(json.dumps({"message": message}))
|
177
|
+
|
178
|
+
elif action == "get_latest":
|
179
|
+
try:
|
180
|
+
last_read_time = last_read_times[topic]
|
181
|
+
except KeyError:
|
182
|
+
last_read_times[topic] = client_creation_time
|
183
|
+
last_read_time = last_read_times[topic]
|
184
|
+
msg["last_read_time"] = last_read_time
|
185
|
+
|
186
|
+
try:
|
187
|
+
cursor.execute(
|
188
|
+
"""
|
189
|
+
SELECT message,
|
190
|
+
timestamp
|
191
|
+
FROM messages
|
192
|
+
WHERE topic = :topic
|
193
|
+
AND timestamp > :last_read_time
|
194
|
+
ORDER BY timestamp DESC
|
195
|
+
LIMIT 1;
|
196
|
+
""",
|
197
|
+
msg,
|
198
|
+
)
|
199
|
+
except sqlite3.OperationalError:
|
200
|
+
pass
|
201
|
+
|
202
|
+
try:
|
203
|
+
result = cursor.fetchall()[0]
|
204
|
+
message = result[0]
|
205
|
+
timestamp = result[1]
|
206
|
+
last_read_times[topic] = timestamp
|
207
|
+
except IndexError:
|
208
|
+
# Handle the case where no results are returned
|
209
|
+
message = ""
|
210
|
+
|
211
|
+
websocket.send(json.dumps({"message": message}))
|
212
|
+
|
213
|
+
elif action == "shutdown":
|
214
|
+
# Run this from a separate thread to prevent deadlock
|
215
|
+
global dsmq_server
|
216
|
+
|
217
|
+
def shutdown_gracefully(server_to_shutdown):
|
218
|
+
server_to_shutdown.shutdown()
|
219
|
+
|
220
|
+
Thread(target=shutdown_gracefully, args=(dsmq_server,)).start()
|
221
|
+
break
|
222
|
+
else:
|
223
|
+
raise RuntimeWarning(
|
224
|
+
"dsmq client action must either be\n"
|
225
|
+
+ "'put', 'get', 'get_wait', 'get_latest', or 'shutdown'"
|
226
|
+
)
|
227
|
+
|
228
|
+
# Periodically clean out messages to keep individual queues at
|
229
|
+
# a manageable length and the overall mq small.
|
230
|
+
if time.time() - time_of_last_purge > _time_between_cleanup:
|
231
|
+
cutoff_time = time.time() - _time_to_keep
|
232
|
+
try:
|
233
|
+
cursor.execute(
|
234
|
+
"""
|
235
|
+
DELETE
|
236
|
+
FROM messages
|
237
|
+
WHERE topic = :topic
|
238
|
+
AND timestamp < :cutoff_time
|
239
|
+
""",
|
240
|
+
{
|
241
|
+
"cutoff_time": cutoff_time,
|
242
|
+
"topic": topic,
|
243
|
+
},
|
244
|
+
)
|
245
|
+
sqlite_conn.commit()
|
246
|
+
time_of_last_purge = time.time()
|
247
|
+
|
248
|
+
cursor.execute(
|
249
|
+
"""
|
250
|
+
DELETE
|
251
|
+
FROM messages
|
252
|
+
WHERE topic = :topic
|
253
|
+
AND timestamp IN (
|
254
|
+
SELECT timestamp
|
255
|
+
FROM (
|
256
|
+
SELECT timestamp,
|
257
|
+
RANK() OVER (ORDER BY timestamp DESC) recency_rank
|
258
|
+
FROM messages
|
259
|
+
WHERE topic = :topic
|
260
|
+
)
|
261
|
+
WHERE recency_rank >= :max_queue_length
|
262
|
+
)
|
263
|
+
""",
|
264
|
+
{
|
265
|
+
"max_queue_length": _max_queue_length,
|
266
|
+
"topic": topic,
|
267
|
+
},
|
268
|
+
)
|
269
|
+
sqlite_conn.commit()
|
270
|
+
time_of_last_purge = time.time()
|
271
|
+
|
272
|
+
except sqlite3.OperationalError:
|
273
|
+
# Database may be locked. Try again next time.
|
274
|
+
pass
|
275
|
+
|
276
|
+
except (ConnectionClosedError, ConnectionClosedOK):
|
277
|
+
# Something happened on the other end and this handler
|
278
|
+
# is no longer needed.
|
279
|
+
pass
|
280
|
+
|
281
|
+
sqlite_conn.close()
|
282
|
+
|
283
|
+
|
284
|
+
if __name__ == "__main__":
|
285
|
+
if len(sys.argv) == 3:
|
286
|
+
host = sys.argv[1]
|
287
|
+
port = int(sys.argv[2])
|
288
|
+
serve(host=host, port=port)
|
289
|
+
elif len(sys.argv) == 2:
|
290
|
+
host = sys.argv[1]
|
291
|
+
serve(host=host)
|
292
|
+
elif len(sys.argv) == 1:
|
293
|
+
serve()
|
294
|
+
else:
|
295
|
+
print(
|
296
|
+
"""
|
297
|
+
Try one of these:
|
298
|
+
$ python3 server.py
|
299
|
+
|
300
|
+
$ python3 server.py 127.0.0.1
|
301
|
+
|
302
|
+
$ python3 server.py 127.0.0.1 25853
|
303
|
+
|
304
|
+
"""
|
305
|
+
)
|