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.
@@ -0,0 +1,529 @@
1
+ """LeanQueue HTTP (REST) API server.
2
+
3
+ One shared `leanqueuedb.Broker` for the process lifetime; sync endpoints run in the
4
+ anyio threadpool (the Rust core releases the GIL for lock waits, IO and fsync, so
5
+ requests run in parallel); long-poll gets are async loops that never block the event
6
+ loop; graceful shutdown closes every queue (fsync). Run single-process (workers=1) —
7
+ the queue is also multi-process safe, so several server processes may share a data
8
+ directory if you prefer.
9
+
10
+ Trust boundary (as LeanText): binds 127.0.0.1 by default. To listen anywhere else set
11
+ LEANQUEUE_API_TOKEN (every endpoint but /health then requires
12
+ `Authorization: Bearer <token>`), front it with an authenticating proxy, or declare
13
+ the network trusted with LEANQUEUE_ALLOW_INSECURE=1.
14
+
15
+ Requirements: pip install "leanqueue[server]"
16
+ Run: leanqueue-serve --data-dir /data/queues
17
+ Env: LEANQUEUE_DATA_DIR, HOST, PORT, LEANQUEUE_THREADS, LEANQUEUE_API_TOKEN,
18
+ LEANQUEUE_ALLOW_INSECURE, LEANQUEUE_MAX_* (see CLIENT.md)
19
+ """
20
+ from __future__ import annotations
21
+
22
+ import base64
23
+ import binascii
24
+ import hmac
25
+ import os
26
+ import sys
27
+ import time
28
+ from contextlib import asynccontextmanager
29
+ from typing import Any, Dict, List, Literal, Optional
30
+
31
+ import anyio
32
+ import orjson
33
+ import pydantic
34
+ from fastapi import Depends, FastAPI, HTTPException, Request
35
+ from fastapi.encoders import jsonable_encoder
36
+ from fastapi.exceptions import RequestValidationError
37
+ from fastapi.responses import JSONResponse, Response
38
+ from pydantic import BaseModel, Field
39
+ from typing_extensions import Annotated
40
+
41
+ import leanqueue
42
+ from . import serve_guardrails as _sg
43
+ from .serve_guardrails import (BodyTooLargeError, GuardrailError, Guardrails, body_weight,
44
+ classify as _classify_error, env_flag, is_loopback,
45
+ public_detail, scan_json_chunk)
46
+ from .service import POLL_SECONDS, QueueService, broker_from_env, message_dict
47
+
48
+ if int(pydantic.VERSION.split(".", 1)[0]) < 2: # pragma: no cover
49
+ raise RuntimeError("leanqueue-serve needs pydantic >= 2 (pip install 'leanqueue[server]')")
50
+
51
+ _DATA_DIR = os.environ.get("LEANQUEUE_DATA_DIR", "leanqueue_data")
52
+ _THREADS = int(os.environ.get("LEANQUEUE_THREADS", str(min(64, (os.cpu_count() or 4) * 2))))
53
+
54
+ # ---- trust boundary ----
55
+ _HOST = os.environ.get("HOST", "127.0.0.1")
56
+ _PORT = int(os.environ.get("PORT", "8004"))
57
+ _API_TOKEN = os.environ.get("LEANQUEUE_API_TOKEN") or None
58
+ _ALLOW_INSECURE = env_flag("LEANQUEUE_ALLOW_INSECURE")
59
+ # Slow-client limits (uvicorn): a connection must deliver a request's headers within
60
+ # LEANQUEUE_HEADER_TIMEOUT_S of connecting / of its previous response, idle keep-alive
61
+ # connections close after LEANQUEUE_KEEPALIVE_S, and one incomplete h11 event (a header
62
+ # block) may not exceed LEANQUEUE_MAX_HEADER_BYTES.
63
+ _HEADER_TIMEOUT_S = float(os.environ.get("LEANQUEUE_HEADER_TIMEOUT_S", "10"))
64
+ _KEEPALIVE_S = int(os.environ.get("LEANQUEUE_KEEPALIVE_S", "5"))
65
+ _MAX_HEADER_BYTES = int(os.environ.get("LEANQUEUE_MAX_HEADER_BYTES", str(64 * 1024)))
66
+ _is_loopback = is_loopback
67
+
68
+
69
+ def check_trust_boundary(host: str) -> None:
70
+ """Refuse an unauthenticated, non-loopback listener (RuntimeError says what to do)."""
71
+ if _is_loopback(host) or _API_TOKEN or _ALLOW_INSECURE:
72
+ return
73
+ raise RuntimeError(
74
+ f"refusing to bind {host} without authentication: this API can publish, consume, "
75
+ f"purge and delete every queue. Set LEANQUEUE_API_TOKEN=<secret> to require a bearer "
76
+ f"token, bind 127.0.0.1 behind a reverse proxy, or set LEANQUEUE_ALLOW_INSECURE=1 if "
77
+ f"this port is genuinely on a trusted private network.")
78
+
79
+
80
+ # ~4 KiB per delivered message (Python objects + base64 JSON) for the memory-aware cap.
81
+ _guard = Guardrails("LEANQUEUE", per_result_bytes=4096, workers=_THREADS)
82
+ _svc: Optional[QueueService] = None
83
+
84
+
85
+ def svc() -> QueueService:
86
+ if _svc is None:
87
+ raise HTTPException(503, "server not ready")
88
+ return _svc
89
+
90
+
91
+ _STATUS_FOR_KIND = {
92
+ _sg.NOT_FOUND: (404, False),
93
+ _sg.OVER_CAPACITY: (429, True),
94
+ _sg.UNAVAILABLE: (503, True),
95
+ _sg.INVALID: (400, False),
96
+ _sg.INTERNAL: (500, False),
97
+ }
98
+
99
+
100
+ def _http_error(e: Exception) -> HTTPException:
101
+ if isinstance(e, HTTPException):
102
+ if isinstance(e.detail, str) and len(e.detail) > 512:
103
+ return HTTPException(e.status_code, e.detail[:512], headers=e.headers)
104
+ return e
105
+ if isinstance(e, BodyTooLargeError):
106
+ return HTTPException(413, public_detail(e))
107
+ status, retryable = _STATUS_FOR_KIND[_classify_error(e)]
108
+ return HTTPException(status, public_detail(e),
109
+ headers={"Retry-After": "1"} if retryable else None)
110
+
111
+
112
+ def _call(fn, *args):
113
+ try:
114
+ return fn(*args)
115
+ except Exception as e:
116
+ raise _http_error(e)
117
+
118
+
119
+ @asynccontextmanager
120
+ async def lifespan(app: FastAPI):
121
+ global _svc
122
+ anyio.to_thread.current_default_thread_limiter().total_tokens = _THREADS
123
+ if not _is_loopback(_HOST) and _API_TOKEN is None:
124
+ sys.stderr.write(
125
+ "LeanQueue WARNING: serving an unauthenticated API on a non-loopback bind "
126
+ f"({_HOST}). Set LEANQUEUE_API_TOKEN or bind 127.0.0.1.\n")
127
+ _svc = QueueService(broker_from_env(_DATA_DIR), _guard)
128
+ try:
129
+ yield
130
+ finally:
131
+ s, _svc = _svc, None
132
+ if s is not None:
133
+ s.close() # fsync + release every queue
134
+
135
+
136
+ def _query_names(dependant, out):
137
+ out.update(p.alias for p in dependant.query_params)
138
+ for sub in dependant.dependencies:
139
+ _query_names(sub, out)
140
+ return out
141
+
142
+
143
+ _ROUTE_QUERY_NAMES: Dict[int, frozenset] = {}
144
+
145
+
146
+ async def _reject_unknown_query(request: Request):
147
+ """An undeclared query parameter is an error (422), like an unknown body field."""
148
+ if not request.query_params:
149
+ return
150
+ route = request.scope.get("route")
151
+ dependant = getattr(route, "dependant", None)
152
+ if dependant is None:
153
+ return
154
+ names = _ROUTE_QUERY_NAMES.get(id(route))
155
+ if names is None:
156
+ names = _ROUTE_QUERY_NAMES[id(route)] = frozenset(_query_names(dependant, set()))
157
+ unknown = set(request.query_params) - names
158
+ if unknown:
159
+ shown = sorted(n[:128] for n in unknown)[:4]
160
+ raise HTTPException(422, f"unknown query parameter(s): {', '.join(shown)}")
161
+
162
+
163
+ app = FastAPI(title="LeanQueue API", version=leanqueue.__version__, lifespan=lifespan,
164
+ dependencies=[Depends(_reject_unknown_query)])
165
+
166
+
167
+ @app.exception_handler(RequestValidationError)
168
+ async def _validation_error(request, exc):
169
+ # Bounded and value-free: never echo (possibly huge) request data back.
170
+ errors = []
171
+ for e in exc.errors()[:16]:
172
+ errors.append({
173
+ "type": str(e.get("type", "value_error"))[:64],
174
+ "loc": [p[:128] if isinstance(p, str) else p for p in e.get("loc", ())[:16]],
175
+ "msg": str(e.get("msg", "invalid input"))[:512],
176
+ })
177
+ return JSONResponse(status_code=422, content={"detail": jsonable_encoder(errors)})
178
+
179
+
180
+ def _refuse(status: int, detail: str) -> JSONResponse:
181
+ headers = {"connection": "close"}
182
+ if status == 429:
183
+ headers["retry-after"] = "1"
184
+ return JSONResponse({"detail": detail}, status_code=status, headers=headers)
185
+
186
+
187
+ def _json(value) -> Response:
188
+ return Response(orjson.dumps(value), media_type="application/json")
189
+
190
+
191
+ class _BodyLimit:
192
+ """Admit request bodies before FastAPI parses them (LeanText's design): a declared
193
+ Content-Length past the cap is refused (413) or, when it does not fit the memory
194
+ free now, 429; every body reserves its estimated parse memory as its bytes arrive,
195
+ chunked bodies (and anything with Transfer-Encoding) included; the reservation is
196
+ released on every exit."""
197
+
198
+ def __init__(self, app):
199
+ self.app = app
200
+
201
+ async def __call__(self, scope, receive, send):
202
+ if scope["type"] != "http":
203
+ await self.app(scope, receive, send)
204
+ return
205
+ declared = None
206
+ chunked = False
207
+ for name, value in scope["headers"]:
208
+ if name == b"content-length":
209
+ declared = value
210
+ elif name == b"transfer-encoding":
211
+ chunked = True
212
+ limit = _guard.max_body_bytes
213
+ if declared is not None and not chunked:
214
+ try:
215
+ n = int(declared)
216
+ except ValueError:
217
+ n = -1
218
+ if n < 0:
219
+ await _refuse(400, "invalid content-length")(scope, receive, send)
220
+ return
221
+ try:
222
+ _guard.check_body(n)
223
+ except GuardrailError as e:
224
+ await _refuse(413 if isinstance(e, BodyTooLargeError) else 429, str(e))(
225
+ scope, receive, send)
226
+ return
227
+ limit = n
228
+ seen = commas = openers = colons = held = weight = 0
229
+
230
+ async def metered():
231
+ nonlocal seen, commas, openers, colons, held, weight
232
+ message = await receive()
233
+ if message["type"] == "http.request":
234
+ chunk = message.get("body", b"")
235
+ if chunk:
236
+ seen += len(chunk)
237
+ c, o, k = scan_json_chunk(chunk)
238
+ commas += c
239
+ openers += o
240
+ colons += k
241
+ weight = body_weight(seen, commas, openers, colons)
242
+ try:
243
+ want = max(weight, min(2 * held, limit))
244
+ try:
245
+ held = _guard.reserve_body(want, held, size=seen)
246
+ except GuardrailError as e:
247
+ if want == weight or isinstance(e, BodyTooLargeError):
248
+ raise
249
+ held = _guard.reserve_body(weight, held, size=seen)
250
+ except GuardrailError as e:
251
+ status = 413 if isinstance(e, BodyTooLargeError) else 429
252
+ headers = {"Connection": "close"}
253
+ if status == 429:
254
+ headers["Retry-After"] = "1"
255
+ raise HTTPException(status, str(e), headers=headers)
256
+ if not message.get("more_body", False) and held > weight:
257
+ _guard.release_body(held - weight)
258
+ held = weight
259
+ return message
260
+
261
+ try:
262
+ await self.app(scope, metered, send)
263
+ finally:
264
+ _guard.release_body(held)
265
+ held = 0
266
+
267
+
268
+ app.add_middleware(_BodyLimit) # added before _Gate, so it runs inside it
269
+
270
+
271
+ class _Gate:
272
+ """Bearer-token check as plain ASGI (outermost). Not `@app.middleware("http")`:
273
+ Starlette's BaseHTTPMiddleware hands the endpoint a receive channel that never
274
+ reports the client's disconnect, so a long-poll kept leasing messages for a client
275
+ that was already gone."""
276
+
277
+ def __init__(self, app):
278
+ self.app = app
279
+
280
+ async def __call__(self, scope, receive, send):
281
+ if scope["type"] == "http" and _API_TOKEN is not None and scope.get("path") != "/health":
282
+ header = b""
283
+ for name, value in scope["headers"]:
284
+ if name == b"authorization":
285
+ header = value
286
+ break
287
+ token = header[7:] if header[:7].lower() == b"bearer " else b""
288
+ if not hmac.compare_digest(token, _API_TOKEN.encode()):
289
+ await JSONResponse({"detail": "unauthorized"}, status_code=401,
290
+ headers={"www-authenticate": "Bearer"})(scope, receive, send)
291
+ return
292
+ await self.app(scope, receive, send)
293
+
294
+
295
+ app.add_middleware(_Gate) # added last: runs first (outermost)
296
+
297
+
298
+ # ---- request models (unknown fields rejected; lists stop at the first bad item) ----
299
+ Seq = Annotated[int, Field(ge=0, le=2 ** 64 - 1)]
300
+ LeaseMs = Annotated[int, Field(ge=0, le=2 ** 63 - 1)]
301
+
302
+
303
+ class _Model(BaseModel):
304
+ # strict: JSON `true` is not the integer 1, "5" is not 5.
305
+ model_config = {"extra": "forbid", "populate_by_name": True, "strict": True}
306
+
307
+ @pydantic.model_validator(mode="before")
308
+ @classmethod
309
+ def _bounded(cls, data):
310
+ if isinstance(data, dict) and len(data) > 64:
311
+ raise ValueError("too many request fields")
312
+ return data
313
+
314
+
315
+ class OutMsg(_Model):
316
+ """Exactly one of `body` (UTF-8 text), `body_b64` (base64 bytes) or `json` (any
317
+ JSON value, stored as its compact UTF-8 encoding)."""
318
+ body: Optional[str] = None
319
+ body_b64: Optional[str] = None
320
+ json_value: Any = Field(default=None, alias="json")
321
+
322
+ @pydantic.model_validator(mode="after")
323
+ def _one(self):
324
+ given = [f for f in ("body", "body_b64", "json_value") if f in self.model_fields_set]
325
+ if len(given) != 1:
326
+ raise ValueError("give exactly one of body, body_b64, json")
327
+ return self
328
+
329
+ def payload(self) -> bytes:
330
+ if "body" in self.model_fields_set:
331
+ if self.body is None:
332
+ raise ValueError("body must be a string")
333
+ return self.body.encode("utf-8")
334
+ if "body_b64" in self.model_fields_set:
335
+ if self.body_b64 is None:
336
+ raise ValueError("body_b64 must be a string")
337
+ try:
338
+ return base64.b64decode(self.body_b64, validate=True)
339
+ except (binascii.Error, ValueError):
340
+ raise ValueError("body_b64 is not valid base64")
341
+ return orjson.dumps(self.json_value)
342
+
343
+
344
+ class PublishBatchReq(_Model):
345
+ # fail_fast: stop at the first bad item instead of building one error per item.
346
+ messages: Annotated[List[OutMsg], Field(fail_fast=True)]
347
+
348
+
349
+ class GetReq(_Model):
350
+ max_messages: int = Field(1, ge=1)
351
+ lease_ms: Optional[LeaseMs] = None
352
+ wait_ms: int = Field(0, ge=0)
353
+ encoding: Literal["base64", "text", "json"] = "base64"
354
+
355
+
356
+ class SeqsReq(_Model):
357
+ seqs: Annotated[List[Seq], Field(fail_fast=True)]
358
+
359
+
360
+ class NackReq(SeqsReq):
361
+ requeue: bool = True
362
+
363
+
364
+ class ExtendReq(SeqsReq):
365
+ lease_ms: Optional[LeaseMs] = None
366
+
367
+
368
+ # ---- routes ----
369
+ @app.get("/health")
370
+ def health():
371
+ return {"ready": _svc is not None, "version": leanqueue.__version__, "limits": _guard.info()}
372
+
373
+
374
+ @app.get("/queues")
375
+ def list_queues(stats: bool = False):
376
+ s = svc()
377
+ names = _call(s.list)
378
+ if not stats:
379
+ return _json({"queues": names})
380
+ return _json({"queues": names, "stats": {n: _call(s.stats, n) for n in names}})
381
+
382
+
383
+ @app.put("/queues/{name}")
384
+ def declare(name: str):
385
+ return _json({"queue": name, "created": _call(svc().declare, name)})
386
+
387
+
388
+ @app.delete("/queues/{name}")
389
+ def delete(name: str):
390
+ if not _call(svc().delete, name):
391
+ raise HTTPException(404, f"queue {name[:128]!r} does not exist")
392
+ return _json({"deleted": True})
393
+
394
+
395
+ @app.get("/queues/{name}/stats")
396
+ def stats(name: str):
397
+ return _json(_call(svc().stats, name))
398
+
399
+
400
+ @app.post("/queues/{name}/publish")
401
+ def publish(name: str, msg: OutMsg):
402
+ body = _call(msg.payload)
403
+ return _json({"seq": _call(svc().publish, name, [body], False)[0]})
404
+
405
+
406
+ @app.post("/queues/{name}/publish_batch")
407
+ def publish_batch(name: str, req: PublishBatchReq):
408
+ s = svc()
409
+ _call(_guard.check_batch, len(req.messages))
410
+ bodies = [_call(m.payload) for m in req.messages]
411
+ return _json({"seqs": _call(s.publish, name, bodies, True)})
412
+
413
+
414
+ @app.post("/queues/{name}/get")
415
+ async def get(name: str, req: GetReq, request: Request):
416
+ s = svc()
417
+ wait_ms = _call(_guard.check_wait, req.wait_ms)
418
+ deadline = time.monotonic() + wait_ms / 1000.0
419
+ msgs = []
420
+ while True:
421
+ # Never lease for a client that is gone (checked before every attempt).
422
+ if await request.is_disconnected():
423
+ return Response(status_code=499)
424
+ try:
425
+ msgs = await anyio.to_thread.run_sync(s.get, name, req.max_messages, req.lease_ms)
426
+ except Exception as e:
427
+ raise _http_error(e)
428
+ if msgs or time.monotonic() >= deadline:
429
+ break
430
+ await anyio.sleep(min(POLL_SECONDS, max(0.0, deadline - time.monotonic())))
431
+ if msgs and wait_ms and await request.is_disconnected():
432
+ # Leased while the client went away: hand them straight back.
433
+ try:
434
+ await anyio.to_thread.run_sync(s.nack, name, [m.seq for m in msgs], True)
435
+ except Exception:
436
+ pass
437
+ return Response(status_code=499)
438
+ return _json({"messages": [message_dict(m, req.encoding) for m in msgs]})
439
+
440
+
441
+ @app.post("/queues/{name}/ack")
442
+ def ack(name: str, req: SeqsReq):
443
+ return _json({"acked": _call(svc().ack, name, req.seqs)})
444
+
445
+
446
+ @app.post("/queues/{name}/nack")
447
+ def nack(name: str, req: NackReq):
448
+ return _json({"nacked": _call(svc().nack, name, req.seqs, req.requeue)})
449
+
450
+
451
+ @app.post("/queues/{name}/extend")
452
+ def extend(name: str, req: ExtendReq):
453
+ return _json({"extended": _call(svc().extend, name, req.seqs, req.lease_ms)})
454
+
455
+
456
+ @app.post("/queues/{name}/states")
457
+ def states(name: str, req: SeqsReq):
458
+ return _json({"states": _call(svc().states, name, req.seqs)})
459
+
460
+
461
+ @app.post("/queues/{name}/purge")
462
+ def purge(name: str):
463
+ _call(svc().purge, name)
464
+ return _json({"purged": True})
465
+
466
+
467
+ def _header_timeout_protocol():
468
+ """uvicorn's HTTP protocol class with a header-read timeout.
469
+
470
+ uvicorn arms its keep-alive timer only after a response, so a connection that sends
471
+ a partial request line or header block and then stalls was held open forever (and
472
+ with enough of them the process ran out of descriptors). This subclass closes a
473
+ connection that has not completed a request's headers within
474
+ LEANQUEUE_HEADER_TIMEOUT_S of opening, or of the previous response.
475
+ """
476
+ try:
477
+ import httptools # noqa: F401
478
+ from uvicorn.protocols.http.httptools_impl import HttpToolsProtocol as Base
479
+ except ImportError:
480
+ from uvicorn.protocols.http.h11_impl import H11Protocol as Base
481
+
482
+ class HeaderTimeoutProtocol(Base):
483
+ def _lq_arm(self):
484
+ if getattr(self, "_lq_timer", None) is None and _HEADER_TIMEOUT_S > 0:
485
+ self._lq_cycle = self.cycle
486
+ self._lq_timer = self.loop.call_later(_HEADER_TIMEOUT_S, self._lq_fire)
487
+
488
+ def _lq_waiting_for_headers(self):
489
+ return self.cycle is None or getattr(self.cycle, "response_complete", False)
490
+
491
+ def _lq_fire(self):
492
+ self._lq_timer = None
493
+ if self.cycle is self._lq_cycle and self._lq_waiting_for_headers():
494
+ if not self.transport.is_closing():
495
+ self.transport.close()
496
+ elif self._lq_waiting_for_headers():
497
+ self._lq_arm()
498
+
499
+ def connection_made(self, transport):
500
+ super().connection_made(transport)
501
+ self._lq_timer = None
502
+ self._lq_arm()
503
+
504
+ def data_received(self, data):
505
+ super().data_received(data)
506
+ if self._lq_waiting_for_headers():
507
+ self._lq_arm()
508
+
509
+ def connection_lost(self, exc):
510
+ t = getattr(self, "_lq_timer", None)
511
+ if t is not None:
512
+ t.cancel()
513
+ self._lq_timer = None
514
+ super().connection_lost(exc)
515
+
516
+ return HeaderTimeoutProtocol
517
+
518
+
519
+ def main():
520
+ import uvicorn
521
+ check_trust_boundary(_HOST)
522
+ uvicorn.run(app, host=_HOST, port=_PORT, workers=1, loop="auto",
523
+ http=_header_timeout_protocol(), access_log=False,
524
+ timeout_keep_alive=_KEEPALIVE_S,
525
+ h11_max_incomplete_event_size=_MAX_HEADER_BYTES)
526
+
527
+
528
+ if __name__ == "__main__":
529
+ main()