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,441 @@
1
+ """Request guardrails for the LeanQueue servers (REST + gRPC).
2
+
3
+ Adapted from LeanText's `serve_guardrails.py`. Two layers:
4
+
5
+ 1. **Static caps** (env-overridable, prefix ``LEANQUEUE_``): request bytes, messages per
6
+ publish batch, messages per get / prefetch window, long-poll wait, concurrent
7
+ consume streams. They bound the request itself before it reaches the queue.
8
+
9
+ 2. **Memory-aware dynamic caps**: the number of messages one get may return and the
10
+ byte budget of one reply are derived from the memory available *now*
11
+ (``MemAvailable`` and the cgroup v1/v2 headroom, whichever is smaller), divided by
12
+ the worker count, refreshed at most once per ``LEANQUEUE_MEM_REFRESH_SECS``.
13
+ Permissive when RAM is plentiful, self-limiting under pressure.
14
+
15
+ REST request bodies are also admitted BEFORE they are parsed: a declared
16
+ Content-Length past the cap is refused (413), and every body reserves its estimated
17
+ parse memory against a shared budget as its bytes arrive (429 when it does not fit),
18
+ chunked bodies included.
19
+
20
+ Message bodies themselves are capped by the queue core (``LEANQUEUE_MAX_BODY_BYTES``,
21
+ read by the Rust layer); the request cap here is ``LEANQUEUE_MAX_REQUEST_BYTES``.
22
+ """
23
+ from __future__ import annotations
24
+
25
+ import ipaddress
26
+ import logging
27
+ import os
28
+ import re
29
+ import threading
30
+ import time
31
+
32
+ _log = logging.getLogger("leanqueue_server")
33
+
34
+
35
+ class GuardrailError(ValueError):
36
+ """A request over a static limit or the current dynamic cap: HTTP 429 /
37
+ gRPC RESOURCE_EXHAUSTED (well-formed; may succeed later or smaller)."""
38
+
39
+
40
+ class BodyTooLargeError(GuardrailError):
41
+ """A request body past ``max_body_bytes``: HTTP 413."""
42
+
43
+
44
+ class LimitError(ValueError):
45
+ """A request over a STATIC cap (batch size, prefetch, wait, seq count, lease length):
46
+ HTTP 400 / gRPC INVALID_ARGUMENT. The same request will never succeed, so it is not
47
+ reported as retryable; only the memory-aware and concurrency caps are (429)."""
48
+
49
+
50
+ # Parsed JSON costs ~4x its text in Python objects, more for token-dense input.
51
+ _BODY_EXPANSION = 4
52
+ _PARSE_BYTES_PER_COMMA = 64
53
+ _PARSE_BYTES_PER_OPENER = 128
54
+ _PARSE_BYTES_PER_COLON = 256
55
+
56
+
57
+ def scan_json_chunk(data: bytes):
58
+ """Structural ``(commas, openers, colons)`` of one chunk.
59
+
60
+ Counts every occurrence, inside strings too, so it can only OVER-estimate the parse
61
+ cost (a conservative reservation). Runs at C speed (``bytes.count``); base64 message
62
+ bodies contain none of these characters, so they never inflate it.
63
+ """
64
+ return data.count(b","), data.count(b"[") + data.count(b"{"), data.count(b":")
65
+
66
+
67
+ def body_weight(nbytes: int, commas: int = 0, openers: int = 0, colons: int = 0) -> int:
68
+ """Reservation of a JSON body in body-byte equivalents (parse memory / 4)."""
69
+ return max(nbytes, (_PARSE_BYTES_PER_COMMA * commas
70
+ + _PARSE_BYTES_PER_OPENER * openers
71
+ + _PARSE_BYTES_PER_COLON * colons) // _BODY_EXPANSION)
72
+
73
+
74
+ # ---------------------------------------------------------------------------
75
+ # Error classification shared by REST and gRPC (protocol-neutral kinds).
76
+ # ---------------------------------------------------------------------------
77
+ try: # pragma: no cover - import shape depends on the deployment
78
+ import leanqueue as _lq
79
+ except Exception: # pragma: no cover
80
+ _lq = None
81
+ _QueueClosedError = getattr(_lq, "QueueClosedError", None)
82
+ _CorruptionError = getattr(_lq, "CorruptionError", None)
83
+ _UnsupportedFormatError = getattr(_lq, "UnsupportedFormatError", None)
84
+ _DurabilityError = getattr(_lq, "DurabilityError", None)
85
+
86
+ NOT_FOUND = "not_found" # the queue does not exist
87
+ OVER_CAPACITY = "over_capacity" # well-formed, but over a server cap right now
88
+ UNAVAILABLE = "unavailable" # server-side and retryable (lock timeout, IO, closed)
89
+ INVALID = "invalid" # the request itself is wrong
90
+ INTERNAL = "internal" # needs an operator (corrupt log, failed fsync)
91
+
92
+
93
+ class QueueNotFound(KeyError):
94
+ """Operation on a queue that was never declared (or was deleted)."""
95
+
96
+ def __str__(self): # KeyError's repr-quoting is noise in an HTTP detail
97
+ return str(self.args[0]) if self.args else "queue not found"
98
+
99
+
100
+ def _is(exc, cls) -> bool:
101
+ return cls is not None and isinstance(exc, cls)
102
+
103
+
104
+ def classify(exc: BaseException) -> str:
105
+ """Which kind of failure ``exc`` is. Specific classes first: the queue's typed
106
+ errors subclass OSError/ValueError, GuardrailError is a ValueError, TimeoutError an
107
+ OSError."""
108
+ if isinstance(exc, GuardrailError):
109
+ return OVER_CAPACITY
110
+ if isinstance(exc, KeyError):
111
+ return NOT_FOUND
112
+ if _is(exc, _QueueClosedError):
113
+ return UNAVAILABLE # closed under us (deleted / shutting down); retry decides
114
+ if _is(exc, _CorruptionError) or _is(exc, _UnsupportedFormatError) or _is(exc, _DurabilityError):
115
+ return INTERNAL # an operator must look at the log / disk
116
+ if isinstance(exc, (TimeoutError, MemoryError)):
117
+ return UNAVAILABLE
118
+ if isinstance(exc, OSError):
119
+ return UNAVAILABLE # ENOSPC/EMFILE/EIO: ours to fix, not the caller's
120
+ if isinstance(exc, (ValueError, TypeError, OverflowError, RecursionError)):
121
+ return INVALID
122
+ return INTERNAL
123
+
124
+
125
+ _PATHISH = re.compile(r"(?:[A-Za-z]:)?[\\/][^\s'\"]*[\\/][^\s'\"]*")
126
+
127
+
128
+ def public_detail(exc: BaseException, limit: int = 512) -> str:
129
+ """The error text a client may see: bounded, and never a server filesystem path.
130
+
131
+ OS-level errors (including the queue's typed CorruptionError/DurabilityError, whose
132
+ messages name the log file) become a generic description plus the queue name; the
133
+ full message goes to the server log instead.
134
+ """
135
+ queue = getattr(exc, "lq_queue", None)
136
+ on = f" on queue {queue[:128]!r}" if isinstance(queue, str) else ""
137
+ if isinstance(exc, OSError) and not isinstance(exc, GuardrailError):
138
+ name = type(exc).__name__
139
+ _log.warning("LeanQueue server error%s: %s: %s", on, name, exc)
140
+ if _is(exc, _CorruptionError) or _is(exc, _UnsupportedFormatError):
141
+ msg = f"{name}{on}: the queue log needs operator attention (details in the server log)"
142
+ elif _is(exc, _DurabilityError):
143
+ msg = f"{name}{on}: an fsync failed; the queue must be reopened by an operator"
144
+ elif isinstance(exc, TimeoutError):
145
+ msg = f"{name}{on}: the queue is busy (process lock timeout); retry"
146
+ elif getattr(exc, "errno", None):
147
+ msg = f"{name}{on}: [Errno {exc.errno}] {os.strerror(exc.errno)}"
148
+ else:
149
+ msg = f"{name}{on}: I/O error (details in the server log)"
150
+ else:
151
+ msg = str(exc)
152
+ return _PATHISH.sub("<path>", msg)[:limit]
153
+
154
+
155
+ def is_loopback(host: str) -> bool:
156
+ """Is `host` a loopback bind address? `localhost`, 127.0.0.0/8, ::1 and IPv4-mapped
157
+ loopback (::ffff:127.x) are; a hostname such as `127.evil.example` is not."""
158
+ h = (host or "").strip()
159
+ if h.startswith("[") and h.endswith("]"):
160
+ h = h[1:-1]
161
+ if h.lower() == "localhost":
162
+ return True
163
+ try:
164
+ ip = ipaddress.ip_address(h.split("%", 1)[0])
165
+ except ValueError:
166
+ return False
167
+ if ip.version == 6 and ip.ipv4_mapped is not None:
168
+ ip = ip.ipv4_mapped
169
+ return ip.is_loopback
170
+
171
+
172
+ def _env_int(name: str, default: int) -> int:
173
+ try:
174
+ return int(os.environ[name])
175
+ except (KeyError, ValueError):
176
+ return default
177
+
178
+
179
+ def _env_float(name: str, default: float) -> float:
180
+ try:
181
+ return float(os.environ[name])
182
+ except (KeyError, ValueError):
183
+ return default
184
+
185
+
186
+ def _check_unsigned(value, name):
187
+ if value is not None and (not isinstance(value, int) or value < 0 or value > 2 ** 64 - 1):
188
+ raise ValueError(f"{name} must be a non-negative 64-bit integer")
189
+
190
+
191
+ class Guardrails:
192
+ def __init__(self, prefix: str, *, per_result_bytes: int, workers: int):
193
+ p = prefix.upper()
194
+ self.max_batch = _env_int(f"{p}_MAX_BATCH", 10_000) # messages per publish
195
+ self.max_prefetch = _env_int(f"{p}_MAX_PREFETCH", 1_000) # per get / consume window
196
+ self.max_wait_ms = _env_int(f"{p}_MAX_WAIT_MS", 30_000) # long-poll ceiling
197
+ self.max_seqs = _env_int(f"{p}_MAX_SEQS", 100_000) # per ack/nack/extend/states
198
+ self.max_lease_ms = _env_int(f"{p}_MAX_LEASE_MS", 86_400_000) # 24 h
199
+ self.max_open_queues = max(1, _env_int(f"{p}_MAX_OPEN_QUEUES", 256)) # open handles (2 fds each)
200
+ self.max_queues = max(1, _env_int(f"{p}_MAX_QUEUES", 10_000)) # declared queues
201
+ self.min_k = _env_int(f"{p}_MIN_GET", 16) # never cap a get below this
202
+ self.mem_fraction = _env_float(f"{p}_MEM_FRACTION", 0.5) # of *available* RAM
203
+ self.refresh_secs = _env_float(f"{p}_MEM_REFRESH_SECS", 1.0)
204
+ self.per_result_bytes = _env_int(f"{p}_PER_RESULT_BYTES", per_result_bytes)
205
+ self.workers = max(1, int(workers))
206
+ self.max_body_bytes = _env_int(f"{p}_MAX_REQUEST_BYTES", 128 * (1 << 20)) # 128 MiB
207
+ self.body_mem_fraction = _env_float(f"{p}_BODY_MEM_FRACTION", self.mem_fraction)
208
+ self._body_inflight = 0
209
+ self._body_lock = threading.Lock()
210
+ self._body_budget_cache = (0.0, 0.0)
211
+ self._lock = threading.Lock()
212
+ self._cache = (0.0, float(self.max_prefetch))
213
+ self._result_budget_cache = (0.0, 1)
214
+
215
+ # ---- memory probe (verbatim from LeanText) ----
216
+ @staticmethod
217
+ def _cgroup_headroom() -> "int | None":
218
+ """Bytes left in this container's memory allowance, or None outside one."""
219
+ v2_path = v1_path = ""
220
+ try:
221
+ with open("/proc/self/cgroup") as f:
222
+ for line in f:
223
+ hierarchy, controllers, path = line.rstrip("\n").split(":", 2)
224
+ if hierarchy == "0" and not controllers:
225
+ v2_path = path
226
+ elif "memory" in controllers.split(","):
227
+ v1_path = path
228
+ except (OSError, ValueError):
229
+ pass
230
+ headrooms = []
231
+ for base, path, limit_name, usage_name in (
232
+ ("/sys/fs/cgroup", v2_path, "memory.max", "memory.current"),
233
+ ("/sys/fs/cgroup/memory", v1_path, "memory.limit_in_bytes", "memory.usage_in_bytes"),
234
+ ):
235
+ parts = [p for p in path.split("/") if p and p not in (".", "..")]
236
+ for depth in range(len(parts), -1, -1):
237
+ directory = os.path.join(base, *parts[:depth])
238
+ try:
239
+ with open(os.path.join(directory, limit_name)) as f:
240
+ raw = f.read().strip()
241
+ if raw == "max":
242
+ continue
243
+ limit = int(raw)
244
+ if limit <= 0 or limit >= (1 << 62):
245
+ continue
246
+ with open(os.path.join(directory, usage_name)) as f:
247
+ usage = int(f.read().strip())
248
+ reclaimable = 0
249
+ try:
250
+ with open(os.path.join(directory, "memory.stat")) as f:
251
+ key = ("inactive_file" if limit_name == "memory.max"
252
+ else "total_inactive_file")
253
+ for line in f:
254
+ name, value = line.split(None, 1)
255
+ if name == key:
256
+ reclaimable = int(value)
257
+ break
258
+ except (OSError, ValueError):
259
+ pass
260
+ reclaimable = min(max(0, reclaimable), max(0, usage))
261
+ headrooms.append(min(limit, max(0, limit - usage + reclaimable)))
262
+ except (OSError, ValueError):
263
+ continue
264
+ return min(headrooms) if headrooms else None
265
+
266
+ @classmethod
267
+ def available_bytes(cls) -> int:
268
+ host = None
269
+ try:
270
+ with open("/proc/meminfo") as f:
271
+ for line in f:
272
+ if line.startswith("MemAvailable:"):
273
+ host = int(line.split()[1]) * 1024
274
+ break
275
+ except (OSError, ValueError):
276
+ host = None
277
+ if host is None:
278
+ try:
279
+ host = os.sysconf("SC_AVPHYS_PAGES") * os.sysconf("SC_PAGE_SIZE")
280
+ except (ValueError, OSError, AttributeError):
281
+ host = 2 << 30
282
+ cgroup = cls._cgroup_headroom()
283
+ return host if cgroup is None else min(host, cgroup)
284
+
285
+ # ---- dynamic caps ----
286
+ def dynamic_cap(self) -> int:
287
+ """Messages one get/consume window may hold, given the memory free now."""
288
+ now = time.monotonic()
289
+ ts, val = self._cache
290
+ if now - ts < self.refresh_secs:
291
+ return int(val)
292
+ with self._lock:
293
+ ts, val = self._cache
294
+ if now - ts < self.refresh_secs:
295
+ return int(val)
296
+ per_req = (self.available_bytes() * self.mem_fraction) / self.workers
297
+ affordable = int(per_req / max(1, self.per_result_bytes))
298
+ floor = min(self.min_k, max(1, affordable))
299
+ cap = min(self.max_prefetch, max(floor, affordable))
300
+ self._cache = (now, float(cap))
301
+ return cap
302
+
303
+ def result_byte_budget(self) -> int:
304
+ """Bytes of message bodies one reply may carry (memory-aware, per worker)."""
305
+ now = time.monotonic()
306
+ ts, budget = self._result_budget_cache
307
+ if now - ts < self.refresh_secs:
308
+ return budget
309
+ with self._lock:
310
+ ts, budget = self._result_budget_cache
311
+ if now - ts < self.refresh_secs:
312
+ return budget
313
+ budget = max(1, min(self.max_body_bytes,
314
+ int(self.available_bytes() * self.mem_fraction / self.workers)))
315
+ self._result_budget_cache = (now, budget)
316
+ return budget
317
+
318
+ # ---- checks (raise GuardrailError / ValueError) ----
319
+ def check_count(self, requested, what: str = "max_messages") -> int:
320
+ _check_unsigned(requested, what)
321
+ if requested > self.max_prefetch:
322
+ raise LimitError(f"{what}={requested} exceeds max {self.max_prefetch} "
323
+ f"(LEANQUEUE_MAX_PREFETCH)")
324
+ cap = self.dynamic_cap()
325
+ if requested > cap:
326
+ raise GuardrailError(
327
+ f"{what}={requested} exceeds the current server cap {cap} "
328
+ f"(the server is memory-limited right now); retry smaller or later")
329
+ return requested
330
+
331
+ def check_batch(self, n: int):
332
+ if n > self.max_batch:
333
+ raise LimitError(f"batch of {n} messages exceeds max {self.max_batch} "
334
+ f"(LEANQUEUE_MAX_BATCH)")
335
+
336
+ def check_seqs(self, n: int):
337
+ if n > self.max_seqs:
338
+ raise LimitError(f"{n} sequence ids exceed max {self.max_seqs} per request "
339
+ f"(LEANQUEUE_MAX_SEQS)")
340
+
341
+ def check_wait(self, wait_ms) -> int:
342
+ _check_unsigned(wait_ms, "wait_ms")
343
+ if wait_ms and wait_ms > self.max_wait_ms:
344
+ raise LimitError(f"wait_ms={wait_ms} exceeds max {self.max_wait_ms} "
345
+ f"(LEANQUEUE_MAX_WAIT_MS)")
346
+ return int(wait_ms or 0)
347
+
348
+ def check_lease(self, lease_ms):
349
+ _check_unsigned(lease_ms, "lease_ms")
350
+ if lease_ms is not None and lease_ms > self.max_lease_ms:
351
+ raise LimitError(f"lease_ms={lease_ms} exceeds max {self.max_lease_ms} "
352
+ f"(LEANQUEUE_MAX_LEASE_MS)")
353
+ return lease_ms
354
+
355
+ def check_body_bytes(self, n: int):
356
+ if n > self.max_body_bytes:
357
+ raise BodyTooLargeError(
358
+ f"request is {n} bytes, over the {self.max_body_bytes}-byte limit")
359
+
360
+ # ---- request-body memory budget ----
361
+ def _body_budget(self) -> float:
362
+ now = time.monotonic()
363
+ ts, available = self._body_budget_cache
364
+ if now - ts >= self.refresh_secs:
365
+ with self._lock:
366
+ ts, available = self._body_budget_cache
367
+ if now - ts >= self.refresh_secs:
368
+ available = self.available_bytes()
369
+ self._body_budget_cache = (now, available)
370
+ return available * self.body_mem_fraction / _BODY_EXPANSION
371
+
372
+ def check_body(self, n: int) -> None:
373
+ """Judge a DECLARED body size before reading it (reserves nothing)."""
374
+ if n > self.max_body_bytes:
375
+ raise BodyTooLargeError(f"request body exceeds {self.max_body_bytes} bytes")
376
+ if not n:
377
+ return
378
+ budget = self._body_budget()
379
+ if self._body_inflight + n > budget:
380
+ raise GuardrailError(
381
+ f"request body of {n} bytes does not fit the memory available now "
382
+ f"({int(budget)} bytes for bodies, {self._body_inflight} in use); retry later")
383
+
384
+ def reserve_body(self, n: int, held: int = 0, *, size: int = 0) -> int:
385
+ if size > self.max_body_bytes:
386
+ raise BodyTooLargeError(f"request body exceeds {self.max_body_bytes} bytes")
387
+ if n <= held:
388
+ return held
389
+ budget = self._body_budget()
390
+ with self._body_lock:
391
+ if self._body_inflight + (n - held) > budget:
392
+ raise GuardrailError(
393
+ f"request body needs ~{n * _BODY_EXPANSION} bytes to parse, which does not "
394
+ f"fit the memory available now; retry later or send smaller batches")
395
+ self._body_inflight += n - held
396
+ return n
397
+
398
+ def release_body(self, n: int) -> None:
399
+ if n:
400
+ with self._body_lock:
401
+ self._body_inflight -= n
402
+
403
+ def admit(self, weight: int) -> "_Admission":
404
+ """Hold one gRPC request's payload memory through the queue call."""
405
+ return _Admission(self, weight)
406
+
407
+ def info(self) -> dict:
408
+ return {"dynamic_cap": self.dynamic_cap(),
409
+ "available_mb": self.available_bytes() // (1 << 20),
410
+ "max_batch": self.max_batch, "max_prefetch": self.max_prefetch,
411
+ "max_wait_ms": self.max_wait_ms, "max_seqs": self.max_seqs,
412
+ "max_lease_ms": self.max_lease_ms, "max_open_queues": self.max_open_queues,
413
+ "max_queues": self.max_queues,
414
+ "max_request_bytes": self.max_body_bytes,
415
+ "result_byte_budget": self.result_byte_budget(),
416
+ "mem_fraction": self.mem_fraction,
417
+ "body_inflight_bytes": self._body_inflight, "workers": self.workers}
418
+
419
+
420
+ class _Admission:
421
+ __slots__ = ("_guard", "_weight", "_held")
422
+
423
+ def __init__(self, guard: Guardrails, weight: int):
424
+ self._guard = guard
425
+ self._weight = weight
426
+ self._held = 0
427
+
428
+ def __enter__(self):
429
+ if self._weight:
430
+ self._held = self._guard.reserve_body(self._weight, size=0)
431
+ return self
432
+
433
+ def __exit__(self, *exc):
434
+ self._guard.release_body(self._held)
435
+ self._held = 0
436
+ return False
437
+
438
+
439
+ def env_flag(name: str) -> bool:
440
+ return os.environ.get(name, "").lower() in ("1", "true", "yes", "on")
441
+