dsmq 1.2.3__tar.gz → 1.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.
- {dsmq-1.2.3 → dsmq-1.3.0}/PKG-INFO +6 -1
- {dsmq-1.2.3 → dsmq-1.3.0}/README.md +5 -0
- {dsmq-1.2.3 → dsmq-1.3.0}/pyproject.toml +1 -1
- dsmq-1.3.0/src/dsmq/.server.py.swp +0 -0
- {dsmq-1.2.3 → dsmq-1.3.0}/src/dsmq/client.py +5 -0
- dsmq-1.3.0/src/dsmq/server.py +245 -0
- dsmq-1.3.0/src/dsmq/tests/.performance_suite.py.swp +0 -0
- {dsmq-1.2.3 → dsmq-1.3.0}/src/dsmq/tests/integration_test.py +0 -1
- dsmq-1.3.0/src/dsmq/tests/performance_suite.py +179 -0
- {dsmq-1.2.3 → dsmq-1.3.0}/uv.lock +1 -1
- dsmq-1.2.3/src/dsmq/server.py +0 -206
- {dsmq-1.2.3 → dsmq-1.3.0}/.gitignore +0 -0
- {dsmq-1.2.3 → dsmq-1.3.0}/.python-version +0 -0
- {dsmq-1.2.3 → dsmq-1.3.0}/LICENSE +0 -0
- {dsmq-1.2.3 → dsmq-1.3.0}/src/dsmq/__init__.py +0 -0
- {dsmq-1.2.3 → dsmq-1.3.0}/src/dsmq/demo.py +0 -0
- {dsmq-1.2.3 → dsmq-1.3.0}/src/dsmq/example_get_client.py +0 -0
- {dsmq-1.2.3 → dsmq-1.3.0}/src/dsmq/example_put_client.py +0 -0
- {dsmq-1.2.3 → dsmq-1.3.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.3.0
|
4
4
|
Summary: A dead simple message queue
|
5
5
|
License-File: LICENSE
|
6
6
|
Requires-Python: >=3.10
|
@@ -178,3 +178,8 @@ Run all the tests in `src/dsmq/tests/` with pytest, for example
|
|
178
178
|
```
|
179
179
|
uv run pytest
|
180
180
|
```
|
181
|
+
|
182
|
+
# Performance characterization
|
183
|
+
|
184
|
+
Time typical operations on your system with the script at
|
185
|
+
`src/dsmq/tests/performance_suite.py`
|
Binary file
|
@@ -8,6 +8,7 @@ _default_port = 30008
|
|
8
8
|
|
9
9
|
_n_retries = 10
|
10
10
|
_initial_retry = 0.01 # seconds
|
11
|
+
_shutdown_delay = 0.1 # seconds
|
11
12
|
|
12
13
|
|
13
14
|
def connect(host=_default_host, port=_default_port, verbose=False):
|
@@ -68,6 +69,10 @@ class DSMQClientSideConnection:
|
|
68
69
|
def shutdown_server(self):
|
69
70
|
msg_dict = {"action": "shutdown", "topic": ""}
|
70
71
|
self.websocket.send(json.dumps(msg_dict))
|
72
|
+
# Give the server time to wind down
|
73
|
+
time.sleep(_shutdown_delay)
|
71
74
|
|
72
75
|
def close(self):
|
73
76
|
self.websocket.close()
|
77
|
+
# Give the websocket time to wind down
|
78
|
+
time.sleep(_shutdown_delay)
|
@@ -0,0 +1,245 @@
|
|
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
|
+
_n_retries = 20
|
13
|
+
_first_retry = 0.005 # seconds
|
14
|
+
_time_to_live = 60.0 # seconds
|
15
|
+
|
16
|
+
# _db_name = ":memory:"
|
17
|
+
_db_name = "file::memory:?cache=shared"
|
18
|
+
# May occasionally create files with this name.
|
19
|
+
# https://sqlite.org/inmemorydb.html
|
20
|
+
# "...parts of a temporary database might be flushed to disk if the
|
21
|
+
# database becomes large or if SQLite comes under memory pressure."
|
22
|
+
|
23
|
+
# Make this global so it's easy to share
|
24
|
+
dsmq_server = None
|
25
|
+
|
26
|
+
|
27
|
+
def serve(host=_default_host, port=_default_port, verbose=False):
|
28
|
+
"""
|
29
|
+
For best results, start this running in its own process and walk away.
|
30
|
+
"""
|
31
|
+
# Cleanup temp files.
|
32
|
+
# Under some condition
|
33
|
+
# (which I haven't yet been able to pin down)
|
34
|
+
# a file is generated with the db name.
|
35
|
+
# If it is not removed, it gets
|
36
|
+
# treated as a SQLite db on disk,
|
37
|
+
# which dramatically slows it down,
|
38
|
+
# especially the way it's used here for
|
39
|
+
# rapid-fire one-item reads and writes.
|
40
|
+
filenames = os.listdir()
|
41
|
+
for filename in filenames:
|
42
|
+
if filename[: len(_db_name)] == _db_name:
|
43
|
+
os.remove(filename)
|
44
|
+
|
45
|
+
sqlite_conn = sqlite3.connect(_db_name)
|
46
|
+
cursor = sqlite_conn.cursor()
|
47
|
+
|
48
|
+
# Tweak the connection to make it faster
|
49
|
+
# and keep long-term latency more predictable.
|
50
|
+
# cursor.execute("PRAGMA journal_mode = OFF")
|
51
|
+
cursor.execute("PRAGMA journal_mode = WAL")
|
52
|
+
# cursor.execute("PRAGMA synchronous = OFF")
|
53
|
+
# cursor.execute("PRAGMA secure_delete = OFF")
|
54
|
+
|
55
|
+
cursor.execute("""
|
56
|
+
CREATE TABLE IF NOT EXISTS messages (timestamp DOUBLE, topic TEXT, message TEXT)
|
57
|
+
""")
|
58
|
+
|
59
|
+
# Making this global in scope is a way to make it available
|
60
|
+
# to the shutdown operation. It's an awkward construction,
|
61
|
+
# and a method of last resort. (If you stumble across this and
|
62
|
+
# figure out something more elegant, please submit a PR!
|
63
|
+
# or send it to me at brohrer@gmail.com,
|
64
|
+
global dsmq_server
|
65
|
+
|
66
|
+
# dsmq_server = ws_serve(request_handler, host, port)
|
67
|
+
for i_retry in range(_n_retries):
|
68
|
+
try:
|
69
|
+
with ws_serve(request_handler, host, port) as dsmq_server:
|
70
|
+
dsmq_server.serve_forever()
|
71
|
+
|
72
|
+
if verbose:
|
73
|
+
print()
|
74
|
+
print(f"Server started at {host} on port {port}.")
|
75
|
+
print("Waiting for clients...")
|
76
|
+
|
77
|
+
break
|
78
|
+
|
79
|
+
except OSError:
|
80
|
+
# Catch the case where the address is already in use
|
81
|
+
if verbose:
|
82
|
+
print()
|
83
|
+
if i_retry < _n_retries - 1:
|
84
|
+
print(f"Couldn't start dsmq server on {host} on port {port}.")
|
85
|
+
print(f" Trying again ({i_retry}) ...")
|
86
|
+
else:
|
87
|
+
print()
|
88
|
+
print(f"Failed to start dsmq server on {host} on port {port}.")
|
89
|
+
print()
|
90
|
+
raise
|
91
|
+
|
92
|
+
wait_time = _first_retry * 2**i_retry
|
93
|
+
time.sleep(wait_time)
|
94
|
+
|
95
|
+
sqlite_conn.close()
|
96
|
+
|
97
|
+
|
98
|
+
def request_handler(websocket):
|
99
|
+
sqlite_conn = sqlite3.connect(_db_name)
|
100
|
+
cursor = sqlite_conn.cursor()
|
101
|
+
|
102
|
+
client_creation_time = time.time()
|
103
|
+
last_read_times = {}
|
104
|
+
time_of_last_purge = time.time()
|
105
|
+
|
106
|
+
try:
|
107
|
+
for msg_text in websocket:
|
108
|
+
msg = json.loads(msg_text)
|
109
|
+
topic = msg["topic"]
|
110
|
+
timestamp = time.time()
|
111
|
+
|
112
|
+
if msg["action"] == "put":
|
113
|
+
msg["timestamp"] = timestamp
|
114
|
+
|
115
|
+
# This block allows for multiple retries if the database
|
116
|
+
# is busy.
|
117
|
+
for i_retry in range(_n_retries):
|
118
|
+
try:
|
119
|
+
cursor.execute(
|
120
|
+
"""
|
121
|
+
INSERT INTO messages (timestamp, topic, message)
|
122
|
+
VALUES (:timestamp, :topic, :message)
|
123
|
+
""",
|
124
|
+
(msg),
|
125
|
+
)
|
126
|
+
sqlite_conn.commit()
|
127
|
+
except sqlite3.OperationalError:
|
128
|
+
wait_time = _first_retry * 2**i_retry
|
129
|
+
time.sleep(wait_time)
|
130
|
+
continue
|
131
|
+
break
|
132
|
+
|
133
|
+
elif msg["action"] == "get":
|
134
|
+
try:
|
135
|
+
last_read_time = last_read_times[topic]
|
136
|
+
except KeyError:
|
137
|
+
last_read_times[topic] = client_creation_time
|
138
|
+
last_read_time = last_read_times[topic]
|
139
|
+
msg["last_read_time"] = last_read_time
|
140
|
+
|
141
|
+
# This block allows for multiple retries if the database
|
142
|
+
# is busy.
|
143
|
+
for i_retry in range(_n_retries):
|
144
|
+
try:
|
145
|
+
cursor.execute(
|
146
|
+
"""
|
147
|
+
SELECT message,
|
148
|
+
timestamp
|
149
|
+
FROM messages,
|
150
|
+
(
|
151
|
+
SELECT MIN(timestamp) AS min_time
|
152
|
+
FROM messages
|
153
|
+
WHERE topic = :topic
|
154
|
+
AND timestamp > :last_read_time
|
155
|
+
) a
|
156
|
+
WHERE topic = :topic
|
157
|
+
AND timestamp = a.min_time
|
158
|
+
""",
|
159
|
+
msg,
|
160
|
+
)
|
161
|
+
except sqlite3.OperationalError:
|
162
|
+
wait_time = _first_retry * 2**i_retry
|
163
|
+
time.sleep(wait_time)
|
164
|
+
continue
|
165
|
+
break
|
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
|
+
elif msg["action"] == "shutdown":
|
178
|
+
# Run this from a separate thread to prevent deadlock
|
179
|
+
global dsmq_server
|
180
|
+
|
181
|
+
def shutdown_gracefully(server_to_shutdown):
|
182
|
+
server_to_shutdown.shutdown()
|
183
|
+
|
184
|
+
filenames = os.listdir()
|
185
|
+
for filename in filenames:
|
186
|
+
if filename[: len(_db_name)] == _db_name:
|
187
|
+
try:
|
188
|
+
os.remove(filename)
|
189
|
+
except FileNotFoundError:
|
190
|
+
pass
|
191
|
+
|
192
|
+
Thread(target=shutdown_gracefully, args=(dsmq_server,)).start()
|
193
|
+
break
|
194
|
+
else:
|
195
|
+
raise RuntimeWarning(
|
196
|
+
"dsmq client action must either be 'put', 'get', or 'shutdown'"
|
197
|
+
)
|
198
|
+
|
199
|
+
# Periodically clean out messages from the queue that are
|
200
|
+
# past their sell buy date.
|
201
|
+
# This operation is pretty fast. I clock it at 12 us on my machine.
|
202
|
+
if time.time() - time_of_last_purge > _time_to_live:
|
203
|
+
try:
|
204
|
+
cursor.execute(
|
205
|
+
"""
|
206
|
+
DELETE FROM messages
|
207
|
+
WHERE timestamp < :time_threshold
|
208
|
+
""",
|
209
|
+
{"time_threshold": time_of_last_purge},
|
210
|
+
)
|
211
|
+
sqlite_conn.commit()
|
212
|
+
time_of_last_purge = time.time()
|
213
|
+
except sqlite3.OperationalError:
|
214
|
+
# Database may be locked. Try again next time.
|
215
|
+
pass
|
216
|
+
except (ConnectionClosedError, ConnectionClosedOK):
|
217
|
+
# Something happened on the other end and this handler
|
218
|
+
# is no longer needed.
|
219
|
+
pass
|
220
|
+
|
221
|
+
sqlite_conn.close()
|
222
|
+
|
223
|
+
|
224
|
+
if __name__ == "__main__":
|
225
|
+
if len(sys.argv) == 3:
|
226
|
+
host = sys.argv[1]
|
227
|
+
port = int(sys.argv[2])
|
228
|
+
serve(host=host, port=port)
|
229
|
+
elif len(sys.argv) == 2:
|
230
|
+
host = sys.argv[1]
|
231
|
+
serve(host=host)
|
232
|
+
elif len(sys.argv) == 1:
|
233
|
+
serve()
|
234
|
+
else:
|
235
|
+
print(
|
236
|
+
"""
|
237
|
+
Try one of these:
|
238
|
+
$ python3 server.py
|
239
|
+
|
240
|
+
$ python3 server.py 127.0.0.1
|
241
|
+
|
242
|
+
$ python3 server.py 127.0.0.1 25853
|
243
|
+
|
244
|
+
"""
|
245
|
+
)
|
Binary file
|
@@ -0,0 +1,179 @@
|
|
1
|
+
import multiprocessing as mp
|
2
|
+
import time
|
3
|
+
|
4
|
+
from dsmq.server import serve
|
5
|
+
from dsmq.client import connect
|
6
|
+
|
7
|
+
host = "127.0.0.1"
|
8
|
+
port = 30303
|
9
|
+
verbose = False
|
10
|
+
|
11
|
+
_pause = 0.01
|
12
|
+
_very_long_pause = 1.0
|
13
|
+
|
14
|
+
_n_iter = int(1e3)
|
15
|
+
_n_long_char = int(1e4)
|
16
|
+
|
17
|
+
_short_msg = "q"
|
18
|
+
_long_msg = str(["q"] * _n_long_char)
|
19
|
+
|
20
|
+
_test_topic = "test"
|
21
|
+
|
22
|
+
|
23
|
+
def main():
|
24
|
+
print()
|
25
|
+
print("dsmq timing measurements")
|
26
|
+
|
27
|
+
time_short_writes()
|
28
|
+
time_long_writes()
|
29
|
+
time_empty_reads()
|
30
|
+
time_short_reads()
|
31
|
+
time_long_reads()
|
32
|
+
|
33
|
+
|
34
|
+
def time_short_writes():
|
35
|
+
condition = "short write"
|
36
|
+
|
37
|
+
duration, duration_close = time_writes(msg=_short_msg, n_iter=1)
|
38
|
+
|
39
|
+
print()
|
40
|
+
print(f"Time for first {condition} [including closing]")
|
41
|
+
print(f" {int(duration)} μs [{int(duration_close)} μs]")
|
42
|
+
|
43
|
+
avg_duration, avg_duration_close = time_writes(msg=_short_msg, n_iter=_n_iter)
|
44
|
+
|
45
|
+
print(f"Average time for a {condition} [including closing]")
|
46
|
+
print(f" {int(avg_duration)} μs [{int(avg_duration_close)} μs]")
|
47
|
+
|
48
|
+
|
49
|
+
def time_long_writes():
|
50
|
+
duration, duration_close = time_writes(msg=_long_msg, n_iter=1)
|
51
|
+
|
52
|
+
condition = "long write"
|
53
|
+
print()
|
54
|
+
print(f"Time for first {condition} [including closing]")
|
55
|
+
print(f" {int(duration)} μs [{int(duration_close)} μs]")
|
56
|
+
|
57
|
+
avg_duration, avg_duration_close = time_writes(msg=_long_msg, n_iter=_n_iter)
|
58
|
+
|
59
|
+
condition = f"long write ({_n_long_char} characters)"
|
60
|
+
print(f"Average time for a {condition} [including closing]")
|
61
|
+
print(f" {int(avg_duration)} μs [{int(avg_duration_close)} μs]")
|
62
|
+
|
63
|
+
condition = "long write (per 1000 characters)"
|
64
|
+
print(f"Average time for a {condition} [including closing]")
|
65
|
+
print(
|
66
|
+
f" {int(1000 * avg_duration / _n_long_char)} μs "
|
67
|
+
+ f"[{int(1000 * avg_duration_close / _n_long_char)}] μs"
|
68
|
+
)
|
69
|
+
|
70
|
+
|
71
|
+
def time_writes(msg="message", n_iter=1):
|
72
|
+
p_server = mp.Process(target=serve, args=(host, port, verbose))
|
73
|
+
p_server.start()
|
74
|
+
time.sleep(_pause)
|
75
|
+
write_client = connect(host, port)
|
76
|
+
|
77
|
+
start_time = time.time()
|
78
|
+
for _ in range(n_iter):
|
79
|
+
write_client.put(_test_topic, msg)
|
80
|
+
avg_duration = 1e6 * (time.time() - start_time) / n_iter # microseconds
|
81
|
+
|
82
|
+
write_client.shutdown_server()
|
83
|
+
write_client.close()
|
84
|
+
|
85
|
+
p_server.join(_very_long_pause)
|
86
|
+
if p_server.is_alive():
|
87
|
+
print(" Doing a hard shutdown on mq server")
|
88
|
+
p_server.kill()
|
89
|
+
avg_duration_close = 1e6 * (time.time() - start_time) / n_iter # microseconds
|
90
|
+
|
91
|
+
return avg_duration, avg_duration_close
|
92
|
+
|
93
|
+
|
94
|
+
def time_empty_reads():
|
95
|
+
condition = "empty read"
|
96
|
+
|
97
|
+
duration, duration_close = time_reads(msg=None, n_iter=1)
|
98
|
+
|
99
|
+
print()
|
100
|
+
print(f"Time for first {condition} [including closing]")
|
101
|
+
print(f" {int(duration)} μs [{int(duration_close)} μs]")
|
102
|
+
|
103
|
+
avg_duration, avg_duration_close = time_reads(msg=None, n_iter=_n_iter)
|
104
|
+
|
105
|
+
print(f"Average time for a {condition} [including closing]")
|
106
|
+
print(f" {int(avg_duration)} μs [{int(avg_duration_close)} μs]")
|
107
|
+
|
108
|
+
|
109
|
+
def time_short_reads():
|
110
|
+
condition = "short read"
|
111
|
+
|
112
|
+
duration, duration_close = time_reads(msg=_short_msg, n_iter=1)
|
113
|
+
|
114
|
+
print()
|
115
|
+
print(f"Time for first {condition} [including closing]")
|
116
|
+
print(f" {int(duration)} μs [{int(duration_close)} μs]")
|
117
|
+
|
118
|
+
avg_duration, avg_duration_close = time_reads(msg=_short_msg, n_iter=_n_iter)
|
119
|
+
|
120
|
+
print(f"Average time for a {condition} [including closing]")
|
121
|
+
print(f" {int(avg_duration)} μs [{int(avg_duration_close)} μs]")
|
122
|
+
|
123
|
+
|
124
|
+
def time_long_reads():
|
125
|
+
condition = f"long read ({_n_long_char} characters)"
|
126
|
+
|
127
|
+
duration, duration_close = time_reads(msg=_long_msg, n_iter=1)
|
128
|
+
|
129
|
+
print()
|
130
|
+
print(f"Time for first {condition} [including closing]")
|
131
|
+
print(f" {int(duration)} μs [{int(duration_close)} μs]")
|
132
|
+
|
133
|
+
avg_duration, avg_duration_close = time_reads(msg=_long_msg, n_iter=_n_iter)
|
134
|
+
|
135
|
+
print(f"Average time for a {condition} [including closing]")
|
136
|
+
print(f" {int(avg_duration)} μs [{int(avg_duration_close)} μs]")
|
137
|
+
|
138
|
+
condition = "long read (per 1000 characters)"
|
139
|
+
print(f"Average time for a {condition} [including closing]")
|
140
|
+
print(
|
141
|
+
f" {int(1000 * avg_duration / _n_long_char)} μs "
|
142
|
+
+ f"[{int(1000 * avg_duration_close / _n_long_char)}] μs"
|
143
|
+
)
|
144
|
+
|
145
|
+
|
146
|
+
def time_reads(msg=None, n_iter=1):
|
147
|
+
p_server = mp.Process(target=serve, args=(host, port, verbose))
|
148
|
+
p_server.start()
|
149
|
+
time.sleep(_pause)
|
150
|
+
# write_client = connect(host, port)
|
151
|
+
read_client = connect(host, port)
|
152
|
+
|
153
|
+
if msg is not None:
|
154
|
+
for _ in range(n_iter):
|
155
|
+
read_client.put(_test_topic, msg)
|
156
|
+
|
157
|
+
start_time = time.time()
|
158
|
+
for _ in range(n_iter):
|
159
|
+
msg = read_client.get(_test_topic)
|
160
|
+
|
161
|
+
avg_duration = 1e6 * (time.time() - start_time) / n_iter # microseconds
|
162
|
+
|
163
|
+
read_client.shutdown_server()
|
164
|
+
# write_client.close()
|
165
|
+
read_client.close()
|
166
|
+
|
167
|
+
p_server.join(_very_long_pause)
|
168
|
+
|
169
|
+
if p_server.is_alive():
|
170
|
+
print(" Doing a hard shutdown on mq server")
|
171
|
+
p_server.kill()
|
172
|
+
|
173
|
+
avg_duration_close = 1e6 * (time.time() - start_time) / n_iter # microseconds
|
174
|
+
|
175
|
+
return avg_duration, avg_duration_close
|
176
|
+
|
177
|
+
|
178
|
+
if __name__ == "__main__":
|
179
|
+
main()
|
dsmq-1.2.3/src/dsmq/server.py
DELETED
@@ -1,206 +0,0 @@
|
|
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
|
9
|
-
|
10
|
-
_default_host = "127.0.0.1"
|
11
|
-
_default_port = 30008
|
12
|
-
_n_retries = 5
|
13
|
-
_first_retry = 0.01 # seconds
|
14
|
-
_pause = 0.01 # seconds
|
15
|
-
_time_to_live = 600.0 # seconds
|
16
|
-
|
17
|
-
_db_name = "file::memory:?cache=shared"
|
18
|
-
|
19
|
-
# Make this global so it's easy to share
|
20
|
-
dsmq_server = None
|
21
|
-
|
22
|
-
|
23
|
-
def serve(host=_default_host, port=_default_port, verbose=False):
|
24
|
-
"""
|
25
|
-
For best results, start this running in its own process and walk away.
|
26
|
-
"""
|
27
|
-
# Cleanup temp files.
|
28
|
-
# Under some condition
|
29
|
-
# (which I haven't yet been able to pin down)
|
30
|
-
# a file is generated with the db name.
|
31
|
-
# If it is not removed, it gets
|
32
|
-
# treated as a SQLite db on disk,
|
33
|
-
# which dramatically slows it down,
|
34
|
-
# especially the way it's used here for
|
35
|
-
# rapid-fire one-item reads and writes.
|
36
|
-
filenames = os.listdir()
|
37
|
-
for filename in filenames:
|
38
|
-
if filename[: len(_db_name)] == _db_name:
|
39
|
-
os.remove(filename)
|
40
|
-
|
41
|
-
sqlite_conn = sqlite3.connect(_db_name)
|
42
|
-
cursor = sqlite_conn.cursor()
|
43
|
-
cursor.execute("""
|
44
|
-
CREATE TABLE IF NOT EXISTS messages (timestamp DOUBLE, topic TEXT, message TEXT)
|
45
|
-
""")
|
46
|
-
|
47
|
-
# Making this global in scope is a way to make it available
|
48
|
-
# to the shutdown operation. It's an awkward construction,
|
49
|
-
# and a method of last resort. (If you stumble across this and
|
50
|
-
# figure out something more elegant, please submit a PR!
|
51
|
-
# or send it to me at brohrer@gmail.com,
|
52
|
-
global dsmq_server
|
53
|
-
|
54
|
-
# dsmq_server = ws_serve(request_handler, host, port)
|
55
|
-
with ws_serve(request_handler, host, port) as dsmq_server:
|
56
|
-
dsmq_server.serve_forever()
|
57
|
-
if verbose:
|
58
|
-
print()
|
59
|
-
print(f"Server started at {host} on port {port}.")
|
60
|
-
print("Waiting for clients...")
|
61
|
-
|
62
|
-
sqlite_conn.close()
|
63
|
-
|
64
|
-
|
65
|
-
def request_handler(websocket):
|
66
|
-
sqlite_conn = sqlite3.connect(_db_name)
|
67
|
-
cursor = sqlite_conn.cursor()
|
68
|
-
|
69
|
-
client_creation_time = time.time()
|
70
|
-
last_read_times = {}
|
71
|
-
time_of_last_purge = time.time()
|
72
|
-
|
73
|
-
for msg_text in websocket:
|
74
|
-
msg = json.loads(msg_text)
|
75
|
-
topic = msg["topic"]
|
76
|
-
timestamp = time.time()
|
77
|
-
|
78
|
-
if msg["action"] == "put":
|
79
|
-
msg["timestamp"] = timestamp
|
80
|
-
|
81
|
-
# This block allows for multiple retries if the database
|
82
|
-
# is busy.
|
83
|
-
for i_retry in range(_n_retries):
|
84
|
-
try:
|
85
|
-
cursor.execute(
|
86
|
-
"""
|
87
|
-
INSERT INTO messages (timestamp, topic, message)
|
88
|
-
VALUES (:timestamp, :topic, :message)
|
89
|
-
""",
|
90
|
-
(msg),
|
91
|
-
)
|
92
|
-
sqlite_conn.commit()
|
93
|
-
except sqlite3.OperationalError:
|
94
|
-
wait_time = _first_retry * 2**i_retry
|
95
|
-
time.sleep(wait_time)
|
96
|
-
continue
|
97
|
-
break
|
98
|
-
|
99
|
-
elif msg["action"] == "get":
|
100
|
-
try:
|
101
|
-
last_read_time = last_read_times[topic]
|
102
|
-
except KeyError:
|
103
|
-
last_read_times[topic] = client_creation_time
|
104
|
-
last_read_time = last_read_times[topic]
|
105
|
-
msg["last_read_time"] = last_read_time
|
106
|
-
|
107
|
-
# This block allows for multiple retries if the database
|
108
|
-
# is busy.
|
109
|
-
for i_retry in range(_n_retries):
|
110
|
-
try:
|
111
|
-
cursor.execute(
|
112
|
-
"""
|
113
|
-
SELECT message,
|
114
|
-
timestamp
|
115
|
-
FROM messages,
|
116
|
-
(
|
117
|
-
SELECT MIN(timestamp) AS min_time
|
118
|
-
FROM messages
|
119
|
-
WHERE topic = :topic
|
120
|
-
AND timestamp > :last_read_time
|
121
|
-
) a
|
122
|
-
WHERE topic = :topic
|
123
|
-
AND timestamp = a.min_time
|
124
|
-
""",
|
125
|
-
msg,
|
126
|
-
)
|
127
|
-
except sqlite3.OperationalError:
|
128
|
-
wait_time = _first_retry * 2**i_retry
|
129
|
-
time.sleep(wait_time)
|
130
|
-
continue
|
131
|
-
break
|
132
|
-
|
133
|
-
try:
|
134
|
-
result = cursor.fetchall()[0]
|
135
|
-
message = result[0]
|
136
|
-
timestamp = result[1]
|
137
|
-
last_read_times[topic] = timestamp
|
138
|
-
except IndexError:
|
139
|
-
# Handle the case where no results are returned
|
140
|
-
message = ""
|
141
|
-
|
142
|
-
try:
|
143
|
-
websocket.send(json.dumps({"message": message}))
|
144
|
-
except ConnectionClosedError:
|
145
|
-
pass
|
146
|
-
elif msg["action"] == "shutdown":
|
147
|
-
# Run this from a separate thread to prevent deadlock
|
148
|
-
global dsmq_server
|
149
|
-
|
150
|
-
def shutdown_gracefully(server_to_shutdown):
|
151
|
-
server_to_shutdown.shutdown()
|
152
|
-
|
153
|
-
filenames = os.listdir()
|
154
|
-
for filename in filenames:
|
155
|
-
if filename[: len(_db_name)] == _db_name:
|
156
|
-
try:
|
157
|
-
os.remove(filename)
|
158
|
-
except FileNotFoundError:
|
159
|
-
pass
|
160
|
-
|
161
|
-
Thread(target=shutdown_gracefully, args=(dsmq_server,)).start()
|
162
|
-
break
|
163
|
-
else:
|
164
|
-
raise RuntimeWarning(
|
165
|
-
"dsmq client action must either be 'put', 'get', or 'shutdown'"
|
166
|
-
)
|
167
|
-
|
168
|
-
# Periodically clean out messages from the queue that are
|
169
|
-
# past their sell buy date.
|
170
|
-
# This operation is pretty fast. I clock it at 12 us on my machine.
|
171
|
-
if time.time() - time_of_last_purge > _time_to_live:
|
172
|
-
cursor.execute(
|
173
|
-
"""
|
174
|
-
DELETE FROM messages
|
175
|
-
WHERE timestamp < :time_threshold
|
176
|
-
""",
|
177
|
-
{"time_threshold": time_of_last_purge},
|
178
|
-
)
|
179
|
-
sqlite_conn.commit()
|
180
|
-
time_of_last_purge = time.time()
|
181
|
-
|
182
|
-
sqlite_conn.close()
|
183
|
-
|
184
|
-
|
185
|
-
if __name__ == "__main__":
|
186
|
-
if len(sys.argv) == 3:
|
187
|
-
host = sys.argv[1]
|
188
|
-
port = int(sys.argv[2])
|
189
|
-
serve(host=host, port=port)
|
190
|
-
elif len(sys.argv) == 2:
|
191
|
-
host = sys.argv[1]
|
192
|
-
serve(host=host)
|
193
|
-
elif len(sys.argv) == 1:
|
194
|
-
serve()
|
195
|
-
else:
|
196
|
-
print(
|
197
|
-
"""
|
198
|
-
Try one of these:
|
199
|
-
$ python3 server.py
|
200
|
-
|
201
|
-
$ python3 server.py 127.0.0.1
|
202
|
-
|
203
|
-
$ python3 server.py 127.0.0.1 25853
|
204
|
-
|
205
|
-
"""
|
206
|
-
)
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|