leanqueue 0.2.1__cp38-abi3-win32.whl
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.
- leanqueue/__init__.py +5 -0
- leanqueue/leanqueue.pyd +0 -0
- leanqueue-0.2.1.dist-info/METADATA +36 -0
- leanqueue-0.2.1.dist-info/RECORD +19 -0
- leanqueue-0.2.1.dist-info/WHEEL +4 -0
- leanqueue-0.2.1.dist-info/entry_points.txt +3 -0
- leanqueue-0.2.1.dist-info/licenses/LICENSE +21 -0
- leanqueue-0.2.1.dist-info/sboms/leanqueue.cyclonedx.json +1049 -0
- leanqueue_server/__init__.py +14 -0
- leanqueue_server/cli.py +71 -0
- leanqueue_server/client.py +216 -0
- leanqueue_server/leanqueue.proto +99 -0
- leanqueue_server/leanqueue_pb2.py +82 -0
- leanqueue_server/leanqueue_pb2_grpc.py +662 -0
- leanqueue_server/serve.py +529 -0
- leanqueue_server/serve_grpc.py +340 -0
- leanqueue_server/serve_guardrails.py +441 -0
- leanqueue_server/service.py +433 -0
- leanqueuedb.py +590 -0
|
@@ -0,0 +1,340 @@
|
|
|
1
|
+
"""LeanQueue gRPC API server — the gRPC twin of serve.py (REST).
|
|
2
|
+
|
|
3
|
+
One shared `leanqueuedb.Broker` for the process lifetime + a ThreadPoolExecutor so
|
|
4
|
+
each RPC runs on a worker thread (the Rust core releases the GIL for lock waits, IO
|
|
5
|
+
and fsync). `Consume` is a server-streaming push with a prefetch window. Graceful
|
|
6
|
+
shutdown (SIGINT/SIGTERM) stops the server, requeues what open streams still hold,
|
|
7
|
+
and closes every queue (fsync).
|
|
8
|
+
|
|
9
|
+
Trust boundary (as LeanText): binds 127.0.0.1 by default with an insecure port only
|
|
10
|
+
for loopback. Elsewhere it needs TLS (LEANQUEUE_GRPC_TLS_CERT / LEANQUEUE_GRPC_TLS_KEY)
|
|
11
|
+
AND a token (LEANQUEUE_API_TOKEN, sent as `authorization: Bearer <token>` metadata),
|
|
12
|
+
or an explicit LEANQUEUE_ALLOW_INSECURE=1.
|
|
13
|
+
|
|
14
|
+
Requirements: pip install "leanqueue[grpc]"
|
|
15
|
+
Run: leanqueue-grpc --data-dir /data/queues
|
|
16
|
+
Env: LEANQUEUE_DATA_DIR, GRPC_HOST, GRPC_PORT, LEANQUEUE_GRPC_WORKERS,
|
|
17
|
+
LEANQUEUE_GRPC_MAX_CONCURRENT_RPCS, LEANQUEUE_GRPC_MAX_STREAMS, LEANQUEUE_API_TOKEN,
|
|
18
|
+
LEANQUEUE_ALLOW_INSECURE, LEANQUEUE_GRPC_TLS_CERT, LEANQUEUE_GRPC_TLS_KEY
|
|
19
|
+
"""
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import hmac
|
|
23
|
+
import os
|
|
24
|
+
import signal
|
|
25
|
+
import threading
|
|
26
|
+
import time
|
|
27
|
+
from concurrent import futures
|
|
28
|
+
|
|
29
|
+
import grpc
|
|
30
|
+
import orjson
|
|
31
|
+
|
|
32
|
+
import leanqueue
|
|
33
|
+
from . import leanqueue_pb2 as pb
|
|
34
|
+
from . import leanqueue_pb2_grpc as pb_grpc
|
|
35
|
+
from . import serve_guardrails as _sg
|
|
36
|
+
from .serve_guardrails import (Guardrails, QueueNotFound, classify as _classify_error, env_flag,
|
|
37
|
+
is_loopback, public_detail)
|
|
38
|
+
from .service import POLL_SECONDS, Consumer, QueueService, broker_from_env
|
|
39
|
+
|
|
40
|
+
_DATA_DIR = os.environ.get("LEANQUEUE_DATA_DIR", "leanqueue_data")
|
|
41
|
+
_WORKERS = int(os.environ.get("LEANQUEUE_GRPC_WORKERS", str(min(64, (os.cpu_count() or 4) * 2))))
|
|
42
|
+
_guard = Guardrails("LEANQUEUE", per_result_bytes=4096, workers=_WORKERS)
|
|
43
|
+
# Each open Consume stream occupies a worker thread for its whole life; cap them so
|
|
44
|
+
# streams cannot starve unary RPCs (Ack included, which streams depend on).
|
|
45
|
+
_MAX_STREAMS = int(os.environ.get("LEANQUEUE_GRPC_MAX_STREAMS", str(max(1, _WORKERS // 2))))
|
|
46
|
+
# A long-poll Get (wait_ms > 0) also holds a worker while it waits. At most this many
|
|
47
|
+
# wait at once; past it a Get degrades to a non-blocking one (returns what is there,
|
|
48
|
+
# possibly nothing) instead of occupying another worker, so Ack/Health never starve.
|
|
49
|
+
_MAX_LONG_POLLS = int(os.environ.get("LEANQUEUE_GRPC_MAX_LONG_POLLS", str(max(1, _WORKERS // 4))))
|
|
50
|
+
|
|
51
|
+
_HOST = os.environ.get("GRPC_HOST", "127.0.0.1")
|
|
52
|
+
_PORT = os.environ.get("GRPC_PORT", "50054")
|
|
53
|
+
_API_TOKEN = os.environ.get("LEANQUEUE_API_TOKEN") or None
|
|
54
|
+
_ALLOW_INSECURE = env_flag("LEANQUEUE_ALLOW_INSECURE")
|
|
55
|
+
_TLS_CERT = os.environ.get("LEANQUEUE_GRPC_TLS_CERT") or None
|
|
56
|
+
_TLS_KEY = os.environ.get("LEANQUEUE_GRPC_TLS_KEY") or None
|
|
57
|
+
# Running + queued RPCs past this get RESOURCE_EXHAUSTED (clients back off) instead of
|
|
58
|
+
# piling up in grpcio's queue without limit. Default 16 per worker thread; 0 = unbounded.
|
|
59
|
+
_MAX_CONCURRENT_RPCS = int(os.environ.get("LEANQUEUE_GRPC_MAX_CONCURRENT_RPCS", str(_WORKERS * 16)))
|
|
60
|
+
if _MAX_CONCURRENT_RPCS < 0:
|
|
61
|
+
raise ValueError("LEANQUEUE_GRPC_MAX_CONCURRENT_RPCS must be >= 0 (0 = unbounded)")
|
|
62
|
+
_MAX_CONCURRENT_RPCS = _MAX_CONCURRENT_RPCS or None
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
_is_loopback = is_loopback
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def check_trust_boundary(host: str) -> None:
|
|
69
|
+
"""Refuse an unauthenticated or unencrypted non-loopback listener."""
|
|
70
|
+
if _is_loopback(host) or _ALLOW_INSECURE:
|
|
71
|
+
return
|
|
72
|
+
if _TLS_CERT and _TLS_KEY and _API_TOKEN:
|
|
73
|
+
return
|
|
74
|
+
raise RuntimeError(
|
|
75
|
+
f"refusing to bind {host} without TLS and a token: this API can publish, consume, "
|
|
76
|
+
f"purge and delete every queue. Set LEANQUEUE_GRPC_TLS_CERT/LEANQUEUE_GRPC_TLS_KEY "
|
|
77
|
+
f"and LEANQUEUE_API_TOKEN, bind 127.0.0.1 behind an authenticating proxy, or set "
|
|
78
|
+
f"LEANQUEUE_ALLOW_INSECURE=1 if this port is genuinely on a trusted private network.")
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
class _AuthInterceptor(grpc.ServerInterceptor):
|
|
82
|
+
"""Require `authorization: Bearer <token>` on every RPC (unary and streaming) but
|
|
83
|
+
Health."""
|
|
84
|
+
|
|
85
|
+
def __init__(self, token: str):
|
|
86
|
+
self._token = token.encode()
|
|
87
|
+
|
|
88
|
+
def deny(request, context):
|
|
89
|
+
context.abort(grpc.StatusCode.UNAUTHENTICATED, "missing or invalid bearer token")
|
|
90
|
+
|
|
91
|
+
self._deny_unary = grpc.unary_unary_rpc_method_handler(deny)
|
|
92
|
+
self._deny_stream = grpc.unary_stream_rpc_method_handler(deny)
|
|
93
|
+
|
|
94
|
+
def intercept_service(self, continuation, handler_call_details):
|
|
95
|
+
method = handler_call_details.method or ""
|
|
96
|
+
if method.endswith("/Health"):
|
|
97
|
+
return continuation(handler_call_details)
|
|
98
|
+
supplied = ""
|
|
99
|
+
for key, value in handler_call_details.invocation_metadata or ():
|
|
100
|
+
if key.lower() == "authorization":
|
|
101
|
+
supplied = value[7:] if value.lower().startswith("bearer ") else ""
|
|
102
|
+
break
|
|
103
|
+
if hmac.compare_digest(supplied.encode(), self._token):
|
|
104
|
+
return continuation(handler_call_details)
|
|
105
|
+
return self._deny_stream if method.endswith("/Consume") else self._deny_unary
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
_CODE_FOR_KIND = {
|
|
109
|
+
_sg.NOT_FOUND: grpc.StatusCode.NOT_FOUND,
|
|
110
|
+
_sg.OVER_CAPACITY: grpc.StatusCode.RESOURCE_EXHAUSTED,
|
|
111
|
+
_sg.UNAVAILABLE: grpc.StatusCode.UNAVAILABLE,
|
|
112
|
+
_sg.INVALID: grpc.StatusCode.INVALID_ARGUMENT,
|
|
113
|
+
_sg.INTERNAL: grpc.StatusCode.INTERNAL,
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _opt(req, field):
|
|
118
|
+
return getattr(req, field) if req.HasField(field) else None
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _delivery(m) -> pb.Delivery:
|
|
122
|
+
return pb.Delivery(seq=m.seq, deliveries=m.deliveries, enqueued_at_ms=m.enqueued_at_ms,
|
|
123
|
+
body=m.body)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
class LeanQueueServicer(pb_grpc.LeanQueueServicer):
|
|
127
|
+
def __init__(self, service: QueueService, max_streams: int = _MAX_STREAMS,
|
|
128
|
+
max_long_polls: int = _MAX_LONG_POLLS):
|
|
129
|
+
self.svc = service
|
|
130
|
+
self._streams = threading.BoundedSemaphore(max(1, max_streams))
|
|
131
|
+
self._long_polls = threading.BoundedSemaphore(max(1, max_long_polls))
|
|
132
|
+
self._consumers = set()
|
|
133
|
+
self._consumers_lock = threading.Lock()
|
|
134
|
+
self._stopping = threading.Event()
|
|
135
|
+
|
|
136
|
+
def _fail(self, ctx, e, reply):
|
|
137
|
+
ctx.set_code(_CODE_FOR_KIND[_classify_error(e)])
|
|
138
|
+
ctx.set_details(public_detail(e))
|
|
139
|
+
return reply
|
|
140
|
+
|
|
141
|
+
def _run(self, ctx, reply_type, fn):
|
|
142
|
+
try:
|
|
143
|
+
return fn()
|
|
144
|
+
except Exception as e:
|
|
145
|
+
return self._fail(ctx, e, reply_type())
|
|
146
|
+
|
|
147
|
+
# ---- unary ----
|
|
148
|
+
def Health(self, request, context):
|
|
149
|
+
return pb.HealthReply(ready=not self._stopping.is_set(), version=leanqueue.__version__,
|
|
150
|
+
limits_json=orjson.dumps(_guard.info()).decode())
|
|
151
|
+
|
|
152
|
+
def ListQueues(self, request, context):
|
|
153
|
+
return self._run(context, pb.ListQueuesReply,
|
|
154
|
+
lambda: pb.ListQueuesReply(queues=self.svc.list()))
|
|
155
|
+
|
|
156
|
+
def DeclareQueue(self, request, context):
|
|
157
|
+
return self._run(context, pb.DeclareReply,
|
|
158
|
+
lambda: pb.DeclareReply(created=self.svc.declare(request.queue)))
|
|
159
|
+
|
|
160
|
+
def DeleteQueue(self, request, context):
|
|
161
|
+
def go():
|
|
162
|
+
if not self.svc.delete(request.queue):
|
|
163
|
+
raise QueueNotFound(f"queue {request.queue[:128]!r} does not exist")
|
|
164
|
+
return pb.DeleteReply(deleted=True)
|
|
165
|
+
return self._run(context, pb.DeleteReply, go)
|
|
166
|
+
|
|
167
|
+
def Stats(self, request, context):
|
|
168
|
+
return self._run(context, pb.StatsReply, lambda: pb.StatsReply(
|
|
169
|
+
stats_json=orjson.dumps(self.svc.stats(request.queue)).decode()))
|
|
170
|
+
|
|
171
|
+
def Publish(self, request, context):
|
|
172
|
+
def go():
|
|
173
|
+
with _guard.admit(len(request.body)):
|
|
174
|
+
return pb.PublishReply(seq=self.svc.publish(request.queue, [request.body], False)[0])
|
|
175
|
+
return self._run(context, pb.PublishReply, go)
|
|
176
|
+
|
|
177
|
+
def PublishBatch(self, request, context):
|
|
178
|
+
def go():
|
|
179
|
+
bodies = list(request.bodies)
|
|
180
|
+
_guard.check_batch(len(bodies))
|
|
181
|
+
with _guard.admit(sum(len(b) for b in bodies) + 64 * len(bodies)):
|
|
182
|
+
return pb.PublishBatchReply(seqs=self.svc.publish(request.queue, bodies, True))
|
|
183
|
+
return self._run(context, pb.PublishBatchReply, go)
|
|
184
|
+
|
|
185
|
+
def Get(self, request, context):
|
|
186
|
+
def go():
|
|
187
|
+
wait_ms = _guard.check_wait(request.wait_ms)
|
|
188
|
+
waiting = bool(wait_ms) and self._long_polls.acquire(blocking=False)
|
|
189
|
+
try:
|
|
190
|
+
msgs = self.svc.get_wait(request.queue, request.max_messages or 1,
|
|
191
|
+
_opt(request, "lease_ms"), wait_ms if waiting else 0,
|
|
192
|
+
alive=lambda: context.is_active()
|
|
193
|
+
and not self._stopping.is_set())
|
|
194
|
+
finally:
|
|
195
|
+
if waiting:
|
|
196
|
+
self._long_polls.release()
|
|
197
|
+
return pb.GetReply(messages=[_delivery(m) for m in msgs])
|
|
198
|
+
return self._run(context, pb.GetReply, go)
|
|
199
|
+
|
|
200
|
+
def Ack(self, request, context):
|
|
201
|
+
return self._run(context, pb.CountReply, lambda: pb.CountReply(
|
|
202
|
+
count=self.svc.ack(request.queue, list(request.seqs))))
|
|
203
|
+
|
|
204
|
+
def Nack(self, request, context):
|
|
205
|
+
return self._run(context, pb.CountReply, lambda: pb.CountReply(
|
|
206
|
+
count=self.svc.nack(request.queue, list(request.seqs), not request.drop)))
|
|
207
|
+
|
|
208
|
+
def Extend(self, request, context):
|
|
209
|
+
return self._run(context, pb.CountReply, lambda: pb.CountReply(
|
|
210
|
+
count=self.svc.extend(request.queue, list(request.seqs), _opt(request, "lease_ms"))))
|
|
211
|
+
|
|
212
|
+
def States(self, request, context):
|
|
213
|
+
def go():
|
|
214
|
+
out = []
|
|
215
|
+
for st in self.svc.states(request.queue, list(request.seqs)):
|
|
216
|
+
if st is None:
|
|
217
|
+
out.append(pb.MessageState(exists=False))
|
|
218
|
+
else:
|
|
219
|
+
out.append(pb.MessageState(
|
|
220
|
+
exists=True, in_flight=st["state"] == "in_flight",
|
|
221
|
+
deliveries=st["deliveries"], lease_until_ms=st["lease_until_ms"] or 0))
|
|
222
|
+
return pb.StatesReply(states=out)
|
|
223
|
+
return self._run(context, pb.StatesReply, go)
|
|
224
|
+
|
|
225
|
+
def Purge(self, request, context):
|
|
226
|
+
def go():
|
|
227
|
+
self.svc.purge(request.queue)
|
|
228
|
+
return pb.PurgeReply()
|
|
229
|
+
return self._run(context, pb.PurgeReply, go)
|
|
230
|
+
|
|
231
|
+
# ---- streaming ----
|
|
232
|
+
def Consume(self, request, context):
|
|
233
|
+
if not self._streams.acquire(blocking=False):
|
|
234
|
+
context.abort(grpc.StatusCode.RESOURCE_EXHAUSTED,
|
|
235
|
+
"too many open Consume streams (LEANQUEUE_GRPC_MAX_STREAMS)")
|
|
236
|
+
consumer = None
|
|
237
|
+
try:
|
|
238
|
+
try:
|
|
239
|
+
consumer = Consumer(self.svc, request.queue, request.prefetch or 1,
|
|
240
|
+
_opt(request, "lease_ms"))
|
|
241
|
+
except Exception as e:
|
|
242
|
+
context.abort(_CODE_FOR_KIND[_classify_error(e)], public_detail(e))
|
|
243
|
+
with self._consumers_lock:
|
|
244
|
+
self._consumers.add(consumer)
|
|
245
|
+
# Runs when the RPC ends for any reason (client cancel, deadline, shutdown),
|
|
246
|
+
# possibly while this generator is blocked; Consumer.finish is idempotent and
|
|
247
|
+
# hands back anything leased after it ran.
|
|
248
|
+
context.add_callback(consumer.finish)
|
|
249
|
+
idle_ms = request.idle_timeout_ms
|
|
250
|
+
last = time.monotonic()
|
|
251
|
+
while context.is_active() and not self._stopping.is_set():
|
|
252
|
+
room = consumer.room()
|
|
253
|
+
if room <= 0:
|
|
254
|
+
time.sleep(POLL_SECONDS)
|
|
255
|
+
continue
|
|
256
|
+
try:
|
|
257
|
+
msgs = consumer.take(room)
|
|
258
|
+
except Exception as e:
|
|
259
|
+
context.abort(_CODE_FOR_KIND[_classify_error(e)], public_detail(e))
|
|
260
|
+
if not msgs:
|
|
261
|
+
if idle_ms and (time.monotonic() - last) * 1000 >= idle_ms:
|
|
262
|
+
break
|
|
263
|
+
consumer.wait(POLL_SECONDS) # wakes at once on a put
|
|
264
|
+
continue
|
|
265
|
+
last = time.monotonic()
|
|
266
|
+
for m in msgs:
|
|
267
|
+
yield _delivery(m)
|
|
268
|
+
finally:
|
|
269
|
+
if consumer is not None:
|
|
270
|
+
consumer.finish()
|
|
271
|
+
with self._consumers_lock:
|
|
272
|
+
self._consumers.discard(consumer)
|
|
273
|
+
self._streams.release()
|
|
274
|
+
|
|
275
|
+
def stop(self) -> None:
|
|
276
|
+
"""Shutdown: end the streams and requeue what they hold."""
|
|
277
|
+
self._stopping.set()
|
|
278
|
+
with self._consumers_lock:
|
|
279
|
+
consumers = list(self._consumers)
|
|
280
|
+
for c in consumers:
|
|
281
|
+
c.finish()
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def build_server(service: QueueService, host: str, port, *, workers: int = _WORKERS,
|
|
285
|
+
token=_API_TOKEN, tls=(None, None)):
|
|
286
|
+
servicer = LeanQueueServicer(service)
|
|
287
|
+
interceptors = [_AuthInterceptor(token)] if token else []
|
|
288
|
+
cap = _guard.max_body_bytes
|
|
289
|
+
server = grpc.server(
|
|
290
|
+
futures.ThreadPoolExecutor(max_workers=workers),
|
|
291
|
+
options=[("grpc.max_send_message_length", cap),
|
|
292
|
+
("grpc.max_receive_message_length", cap),
|
|
293
|
+
("grpc.keepalive_time_ms", 60_000),
|
|
294
|
+
("grpc.keepalive_timeout_ms", 20_000),
|
|
295
|
+
("grpc.http2.max_pings_without_data", 0),
|
|
296
|
+
# grpcio sets SO_REUSEPORT by default: a second server started on the
|
|
297
|
+
# same port (another data dir, a stale instance) would bind silently and
|
|
298
|
+
# the kernel would split clients between the two. Fail the bind instead.
|
|
299
|
+
("grpc.so_reuseport", 0)],
|
|
300
|
+
interceptors=interceptors,
|
|
301
|
+
maximum_concurrent_rpcs=_MAX_CONCURRENT_RPCS,
|
|
302
|
+
)
|
|
303
|
+
pb_grpc.add_LeanQueueServicer_to_server(servicer, server)
|
|
304
|
+
addr = f"{host}:{port}"
|
|
305
|
+
cert, key = tls
|
|
306
|
+
if cert and key:
|
|
307
|
+
with open(key, "rb") as f:
|
|
308
|
+
k = f.read()
|
|
309
|
+
with open(cert, "rb") as f:
|
|
310
|
+
c = f.read()
|
|
311
|
+
bound = server.add_secure_port(addr, grpc.ssl_server_credentials([(k, c)]))
|
|
312
|
+
else:
|
|
313
|
+
bound = server.add_insecure_port(addr)
|
|
314
|
+
if not bound: # older grpcio reports a failed bind as port 0 instead of raising
|
|
315
|
+
raise RuntimeError(f"LeanQueue gRPC: cannot bind {addr} (address in use?)")
|
|
316
|
+
return server, servicer, bound
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def serve():
|
|
320
|
+
check_trust_boundary(_HOST)
|
|
321
|
+
service = QueueService(broker_from_env(_DATA_DIR), _guard)
|
|
322
|
+
server, servicer, _ = build_server(service, _HOST, _PORT, tls=(_TLS_CERT, _TLS_KEY))
|
|
323
|
+
server.start()
|
|
324
|
+
scheme = "TLS" if (_TLS_CERT and _TLS_KEY) else "insecure"
|
|
325
|
+
print(f"LeanQueue gRPC serving on {_HOST}:{_PORT} ({scheme}, "
|
|
326
|
+
f"{'token auth' if _API_TOKEN else 'no auth'}, {_WORKERS} workers, "
|
|
327
|
+
f"data={_DATA_DIR})", flush=True)
|
|
328
|
+
stop = threading.Event()
|
|
329
|
+
for sig in (signal.SIGINT, signal.SIGTERM):
|
|
330
|
+
signal.signal(sig, lambda *_: stop.set())
|
|
331
|
+
stop.wait()
|
|
332
|
+
servicer.stop()
|
|
333
|
+
server.stop(grace=5).wait()
|
|
334
|
+
service.close() # fsync + release every queue
|
|
335
|
+
print("LeanQueue gRPC stopped", flush=True)
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
if __name__ == "__main__":
|
|
339
|
+
serve()
|
|
340
|
+
|