plasmite 2.0.0__py3-none-win_arm64.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.
plasmite/__init__.py ADDED
@@ -0,0 +1,1545 @@
1
+ """Read, write and manage Plasmite pools from Python."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from base64 import b64encode
6
+ from dataclasses import dataclass
7
+ from ctypes import (
8
+ CDLL,
9
+ POINTER,
10
+ Structure,
11
+ byref,
12
+ c_bool,
13
+ c_char_p,
14
+ c_int,
15
+ c_size_t,
16
+ c_uint32,
17
+ c_uint64,
18
+ c_uint8,
19
+ c_void_p,
20
+ cast,
21
+ sizeof,
22
+ string_at,
23
+ )
24
+ from datetime import datetime, timedelta, timezone
25
+ from enum import IntEnum
26
+ from functools import wraps
27
+ from threading import Event, Lock, RLock
28
+ import json
29
+ from json import loads as _load_json
30
+ import os
31
+ import re
32
+ import sys
33
+ from pathlib import Path
34
+ from typing import Callable, Generator, Iterable, Literal, ParamSpec, TypeVar, TypedDict, cast as type_cast
35
+ from urllib.parse import unquote, urlsplit
36
+
37
+
38
+ class ErrorKind(IntEnum):
39
+ INTERNAL = 1
40
+ USAGE = 2
41
+ NOT_FOUND = 3
42
+ ALREADY_EXISTS = 4
43
+ BUSY = 5
44
+ PERMISSION = 6
45
+ CORRUPT = 7
46
+ IO = 8
47
+ RETENTION_GAP = 9
48
+
49
+
50
+ class Durability(IntEnum):
51
+ FAST = 0
52
+ FLUSH = 1
53
+
54
+
55
+ class PlasmiteError(RuntimeError):
56
+ def __init__(
57
+ self,
58
+ kind: ErrorKind,
59
+ message: str,
60
+ path: str | None = None,
61
+ seq: int | None = None,
62
+ offset: int | None = None,
63
+ ) -> None:
64
+ super().__init__(message)
65
+ self.kind = kind
66
+ self.path = path
67
+ self.seq = seq
68
+ self.offset = offset
69
+
70
+
71
+ class NotFoundError(PlasmiteError, LookupError):
72
+ pass
73
+
74
+
75
+ class AlreadyExistsError(PlasmiteError):
76
+ pass
77
+
78
+
79
+ class BusyError(PlasmiteError):
80
+ pass
81
+
82
+
83
+ class PermissionDeniedError(PlasmiteError):
84
+ pass
85
+
86
+
87
+ class CorruptError(PlasmiteError):
88
+ pass
89
+
90
+
91
+ class IoError(PlasmiteError):
92
+ pass
93
+
94
+
95
+ class UsageError(PlasmiteError, ValueError):
96
+ pass
97
+
98
+
99
+ class InternalError(PlasmiteError):
100
+ pass
101
+
102
+
103
+ class RetentionGapError(PlasmiteError):
104
+ def __init__(self, *args, missing: int | None = None, next_seq: int | None = None):
105
+ super().__init__(*args)
106
+ self.missing = missing
107
+ self.next_seq = next_seq
108
+
109
+
110
+ class _OptionalMessageMeta(TypedDict, total=False):
111
+ sender: str
112
+ source: str
113
+
114
+
115
+ class MessageMeta(_OptionalMessageMeta):
116
+ tags: list[str]
117
+
118
+
119
+ class PoolBounds(TypedDict, total=False):
120
+ oldest: int
121
+ newest: int
122
+
123
+
124
+ class _OptionalPoolInfo(TypedDict, total=False):
125
+ name: str
126
+ metrics: dict[str, object]
127
+ about: str
128
+ example: dict[str, object]
129
+ warning: str
130
+
131
+
132
+ class PoolInfo(_OptionalPoolInfo):
133
+ path: str
134
+ file_size: int
135
+ index_offset: int
136
+ index_capacity: int
137
+ index_size_bytes: int
138
+ ring_offset: int
139
+ ring_size: int
140
+ bounds: PoolBounds
141
+
142
+
143
+ @dataclass(frozen=True)
144
+ class Receipt:
145
+ """A committed sequence and its time in Unix nanoseconds."""
146
+
147
+ seq: int
148
+ time: int
149
+
150
+
151
+ class Message:
152
+ """One stored message. Its bytes outlive the pool and reader that returned it."""
153
+
154
+ __slots__ = ("_view", "_data")
155
+
156
+ def __init__(self, view) -> None:
157
+ self._view = view
158
+ self._data = None
159
+
160
+ @property
161
+ def seq(self) -> int:
162
+ return self._view.seq
163
+
164
+ @property
165
+ def time(self) -> int:
166
+ """The time the pool stored this message, in Unix nanoseconds."""
167
+ return self._view.time
168
+
169
+ @property
170
+ def tags(self) -> list[str]:
171
+ return list(self._view.tags)
172
+
173
+ @property
174
+ def sender(self) -> str | None:
175
+ return self._view.meta.get("sender")
176
+
177
+ @property
178
+ def source(self) -> str | None:
179
+ return self._view.meta.get("source")
180
+
181
+ @property
182
+ def meta(self) -> MessageMeta:
183
+ result: MessageMeta = {"tags": self.tags}
184
+ if (sender := self.sender) is not None:
185
+ result["sender"] = sender
186
+ if (source := self.source) is not None:
187
+ result["source"] = source
188
+ return result
189
+
190
+ @property
191
+ def datetime(self) -> datetime:
192
+ """UTC time rounded down to the nearest microsecond."""
193
+ return datetime(1970, 1, 1, tzinfo=timezone.utc) + timedelta(microseconds=self.time // 1000)
194
+
195
+ @property
196
+ def json(self) -> str:
197
+ return type_cast(str, self._view._json())
198
+
199
+ def __str__(self) -> str:
200
+ return self.json
201
+
202
+ def _snapshot(self) -> memoryview:
203
+ native_export = getattr(self._view, "_snapshot", None)
204
+ return native_export() if native_export else memoryview(self._view)
205
+
206
+ @property
207
+ def data(self) -> dict[str, object]:
208
+ """Decode the application's object on first access."""
209
+ if self._data is None:
210
+ self._data = self._view._data_native(_load_json)
211
+ return self._data
212
+
213
+ def field(self, name: str, default=None):
214
+ """Read one data field without decoding the rest of the object."""
215
+ if self._data is not None:
216
+ return self._data.get(name, default)
217
+ try:
218
+ value = self._view.data[name]
219
+ except KeyError:
220
+ return default
221
+ if value is None or type(value) in (bool, int, float, str):
222
+ return value
223
+ from ._views import to_native
224
+
225
+ return to_native(value)
226
+
227
+ def __repr__(self) -> str:
228
+ return f"<plasmite.Message seq={self.seq}>"
229
+
230
+
231
+ class pls_client_t(Structure):
232
+ pass
233
+
234
+
235
+ class pls_pool_t(Structure):
236
+ pass
237
+
238
+
239
+ class pls_reader_t(Structure):
240
+ pass
241
+
242
+
243
+ class pls_udp_client_t(Structure):
244
+ pass
245
+
246
+
247
+ class pls_udp_pool_t(Structure):
248
+ pass
249
+
250
+
251
+ class pls_udp_follow_t(Structure):
252
+ pass
253
+
254
+
255
+ class pls_buf_t(Structure):
256
+ _fields_ = [
257
+ ("data", c_void_p),
258
+ ("len", c_size_t),
259
+ ]
260
+
261
+
262
+ class pls_udp_event_t(Structure):
263
+ _fields_ = [
264
+ ("kind", c_uint32),
265
+ ("reason", c_uint32),
266
+ ("seq", c_uint64),
267
+ ("time", c_uint64),
268
+ ("first", c_uint64),
269
+ ("last", c_uint64),
270
+ ("start_seq", c_uint64),
271
+ ("next_seq", c_uint64),
272
+ ("end_seq", c_uint64),
273
+ ("has_end", c_uint8),
274
+ ("terminal", c_uint8),
275
+ ("reserved", c_uint8),
276
+ ("payload", pls_buf_t),
277
+ ]
278
+
279
+
280
+ class pls_error_t(Structure):
281
+ _fields_ = [
282
+ ("kind", c_int),
283
+ ("message", c_char_p),
284
+ ("path", c_char_p),
285
+ ("seq", c_uint64),
286
+ ("offset", c_uint64),
287
+ ("has_seq", c_uint8),
288
+ ("has_offset", c_uint8),
289
+ ("missing", c_uint64),
290
+ ("next_seq", c_uint64),
291
+ ]
292
+
293
+
294
+ class pls_text_t(Structure):
295
+ _fields_ = [("data", c_char_p), ("len", c_size_t)]
296
+
297
+
298
+ class pls_open_options_t(Structure):
299
+ _fields_ = [
300
+ ("struct_size", c_uint32),
301
+ ("create", c_uint32),
302
+ ("source", c_char_p),
303
+ ]
304
+
305
+
306
+ class pls_read_options_t(Structure):
307
+ _fields_ = [
308
+ ("struct_size", c_uint32),
309
+ ("start_kind", c_uint32),
310
+ ("start_value", c_uint64),
311
+ ("tags", POINTER(pls_text_t)),
312
+ ("tags_len", c_size_t),
313
+ ]
314
+
315
+
316
+ class pls_feed_options_t(Structure):
317
+ _fields_ = [
318
+ ("struct_size", c_uint32),
319
+ ("durability", c_uint32),
320
+ ("tags", POINTER(pls_text_t)),
321
+ ("tags_len", c_size_t),
322
+ ]
323
+
324
+
325
+
326
+ class _NativeReceipt(Structure):
327
+ _fields_ = [("seq", c_uint64), ("time", c_uint64)]
328
+
329
+
330
+ def _load_lib() -> CDLL:
331
+ if sys.platform == "win32":
332
+ versioned = "plasmite2.dll"
333
+ elif sys.platform == "darwin":
334
+ versioned = "libplasmite.2.dylib"
335
+ else:
336
+ versioned = "libplasmite.so.2"
337
+ candidate = Path(__file__).resolve().parent / "_native" / versioned
338
+ if candidate.is_file():
339
+ return _check_abi(CDLL(str(candidate)))
340
+ return _check_abi(CDLL(versioned))
341
+
342
+
343
+ def _check_abi(lib: CDLL) -> CDLL:
344
+ try:
345
+ major = lib.pls_abi_major
346
+ except AttributeError as exc:
347
+ raise ImportError("Plasmite requires ABI major 2; library does not report its ABI") from exc
348
+ major.argtypes = []
349
+ major.restype = c_uint32
350
+ actual = major()
351
+ if actual != 2:
352
+ raise ImportError(f"Plasmite requires ABI major 2; found {actual}")
353
+ return lib
354
+
355
+
356
+ _LIB = _load_lib()
357
+ _LIB.pls_internal_pool_feed_many_builders.argtypes = [
358
+ POINTER(pls_pool_t), POINTER(c_void_p), c_size_t, POINTER(pls_feed_options_t),
359
+ POINTER(_NativeReceipt), POINTER(POINTER(pls_error_t)),
360
+ ]
361
+ _LIB.pls_internal_pool_feed_many_builders.restype = c_int
362
+
363
+
364
+ DEFAULT_POOL_SIZE_BYTES = 1024 * 1024
365
+ _UINT64_MAX = (1 << 64) - 1
366
+
367
+
368
+ def default_pool_dir() -> str:
369
+ if os.name == "nt":
370
+ home = os.environ.get("USERPROFILE", "")
371
+ if not os.path.isabs(home):
372
+ import ctypes
373
+ import uuid
374
+ profile_id = ctypes.create_string_buffer(uuid.UUID("5e6c858f-0e22-4760-9afe-ea3317b67173").bytes_le)
375
+ directory = ctypes.c_void_p()
376
+ shell = ctypes.WinDLL("shell32")
377
+ shell.SHGetKnownFolderPath.argtypes = [ctypes.c_void_p, ctypes.c_uint32, ctypes.c_void_p, ctypes.POINTER(ctypes.c_void_p)]
378
+ shell.SHGetKnownFolderPath.restype = ctypes.c_long
379
+ status = shell.SHGetKnownFolderPath(profile_id, 0, None, ctypes.byref(directory))
380
+ home = ""
381
+ if status >= 0 and directory.value:
382
+ try:
383
+ home = ctypes.wstring_at(directory)
384
+ finally:
385
+ ole = ctypes.WinDLL("ole32")
386
+ ole.CoTaskMemFree.argtypes = [ctypes.c_void_p]
387
+ ole.CoTaskMemFree(directory)
388
+ else:
389
+ home = os.environ.get("HOME", "")
390
+ if not os.path.isabs(home):
391
+ import pwd
392
+ try:
393
+ home = pwd.getpwuid(os.getuid()).pw_dir
394
+ except (KeyError, OSError):
395
+ home = ""
396
+ if not home or not os.path.isabs(home):
397
+ raise ValueError("cannot determine the user home directory; supply an explicit pool directory")
398
+ return os.path.join(home, ".plasmite", "pools")
399
+
400
+
401
+ try:
402
+ DEFAULT_POOL_DIR = default_pool_dir()
403
+ except ValueError:
404
+ DEFAULT_POOL_DIR = None
405
+
406
+ _LIB.pls_client_new.argtypes = [c_char_p, POINTER(POINTER(pls_client_t)), POINTER(POINTER(pls_error_t))]
407
+ _LIB.pls_client_new.restype = c_int
408
+ _LIB.pls_client_free.argtypes = [POINTER(pls_client_t)]
409
+ _LIB.pls_client_free.restype = None
410
+
411
+ _LIB.pls_pool_create.argtypes = [
412
+ POINTER(pls_client_t),
413
+ c_char_p,
414
+ c_uint64,
415
+ POINTER(POINTER(pls_pool_t)),
416
+ POINTER(POINTER(pls_error_t)),
417
+ ]
418
+ _LIB.pls_pool_create.restype = c_int
419
+ _LIB.pls_pool_create_described.argtypes = [
420
+ POINTER(pls_client_t), c_char_p, c_uint64, c_char_p, c_size_t,
421
+ POINTER(POINTER(pls_pool_t)), POINTER(POINTER(pls_error_t)),
422
+ ]
423
+ _LIB.pls_pool_create_described.restype = c_int
424
+ _LIB.pls_pool_set_description.argtypes = [
425
+ POINTER(pls_pool_t), c_char_p, c_size_t, POINTER(POINTER(pls_error_t)),
426
+ ]
427
+ _LIB.pls_pool_set_description.restype = c_int
428
+ _LIB.pls_pool_open.argtypes = [
429
+ POINTER(pls_client_t), c_char_p, POINTER(pls_open_options_t),
430
+ POINTER(POINTER(pls_pool_t)), POINTER(POINTER(pls_error_t)),
431
+ ]
432
+ _LIB.pls_pool_open.restype = c_int
433
+ _LIB.pls_pool_feed_json.argtypes = [
434
+ POINTER(pls_pool_t), c_char_p, c_size_t, POINTER(pls_feed_options_t),
435
+ POINTER(_NativeReceipt), POINTER(POINTER(pls_error_t)),
436
+ ]
437
+ _LIB.pls_pool_feed_json.restype = c_int
438
+ for _open_reader in (
439
+ _LIB.pls_pool_follow, _LIB.pls_pool_fetch,
440
+ ):
441
+ _open_reader.argtypes = [
442
+ POINTER(pls_pool_t), POINTER(pls_read_options_t),
443
+ POINTER(POINTER(pls_reader_t)), POINTER(POINTER(pls_error_t)),
444
+ ]
445
+ _open_reader.restype = c_int
446
+
447
+ _LIB.pls_internal_pool_info_json.argtypes = [POINTER(pls_pool_t), POINTER(pls_buf_t), POINTER(POINTER(pls_error_t))]
448
+ _LIB.pls_internal_pool_info_json.restype = c_int
449
+ _LIB.pls_internal_pool_list_json.argtypes = [POINTER(pls_client_t), POINTER(pls_buf_t), POINTER(POINTER(pls_error_t))]
450
+ _LIB.pls_internal_pool_list_json.restype = c_int
451
+ _LIB.pls_pool_delete.argtypes = [POINTER(pls_client_t), c_char_p, POINTER(POINTER(pls_error_t))]
452
+ _LIB.pls_pool_delete.restype = c_int
453
+
454
+ _LIB.pls_pool_free.argtypes = [POINTER(pls_pool_t)]
455
+ _LIB.pls_pool_free.restype = None
456
+
457
+
458
+ _LIB.pls_reader_cancel.argtypes = [POINTER(pls_reader_t)]
459
+ _LIB.pls_reader_cancel.restype = None
460
+ _LIB.pls_reader_free.argtypes = [POINTER(pls_reader_t)]
461
+ _LIB.pls_reader_free.restype = None
462
+
463
+ _LIB.pls_buf_free.argtypes = [POINTER(pls_buf_t)]
464
+ _LIB.pls_buf_free.restype = None
465
+
466
+ _LIB.pls_error_free.argtypes = [POINTER(pls_error_t)]
467
+ _LIB.pls_error_free.restype = None
468
+
469
+ _LIB.pls_udp_client_new.argtypes = [
470
+ c_char_p,
471
+ POINTER(POINTER(pls_udp_client_t)),
472
+ POINTER(POINTER(pls_error_t)),
473
+ ]
474
+ _LIB.pls_udp_client_new.restype = c_int
475
+ _LIB.pls_udp_client_free.argtypes = [POINTER(pls_udp_client_t)]
476
+ _LIB.pls_udp_client_free.restype = None
477
+ _LIB.pls_udp_client_open_pool.argtypes = [
478
+ POINTER(pls_udp_client_t),
479
+ c_char_p,
480
+ POINTER(POINTER(pls_udp_pool_t)),
481
+ POINTER(POINTER(pls_error_t)),
482
+ ]
483
+ _LIB.pls_udp_client_open_pool.restype = c_int
484
+ _LIB.pls_udp_pool_free.argtypes = [POINTER(pls_udp_pool_t)]
485
+ _LIB.pls_udp_pool_free.restype = None
486
+ _LIB.pls_udp_pool_follow.argtypes = _LIB.pls_udp_pool_fetch.argtypes = [
487
+ POINTER(pls_udp_pool_t), POINTER(pls_read_options_t),
488
+ POINTER(POINTER(pls_udp_follow_t)), POINTER(POINTER(pls_error_t)),
489
+ ]
490
+ _LIB.pls_udp_pool_follow.restype = _LIB.pls_udp_pool_fetch.restype = c_int
491
+ _LIB.pls_internal_udp_pool_feed_device.argtypes = [
492
+ POINTER(pls_udp_pool_t), c_char_p, c_size_t, POINTER(POINTER(pls_error_t)),
493
+ ]
494
+ _LIB.pls_internal_udp_pool_feed_device.restype = c_int
495
+ _LIB.pls_internal_udp_pool_feed_view.argtypes = [
496
+ POINTER(pls_udp_pool_t), c_void_p, c_bool, POINTER(POINTER(pls_error_t)),
497
+ ]
498
+ _LIB.pls_internal_udp_pool_feed_view.restype = c_int
499
+ _LIB.pls_udp_follow_next_view.argtypes = [
500
+ POINTER(pls_udp_follow_t), c_uint64, POINTER(pls_udp_event_t),
501
+ POINTER(c_void_p), POINTER(POINTER(pls_error_t)),
502
+ ]
503
+ _LIB.pls_udp_follow_next_view.restype = c_int
504
+ _LIB.pls_udp_follow_cancel.argtypes = [POINTER(pls_udp_follow_t)]
505
+ _LIB.pls_udp_follow_cancel.restype = None
506
+ _LIB.pls_udp_follow_free.argtypes = [POINTER(pls_udp_follow_t)]
507
+ _LIB.pls_udp_follow_free.restype = None
508
+ _LIB.pls_udp_event_free.argtypes = [POINTER(pls_udp_event_t)]
509
+ _LIB.pls_udp_event_free.restype = None
510
+ _ERROR_KIND_TO_CLASS: dict[ErrorKind, type[PlasmiteError]] = {
511
+ ErrorKind.INTERNAL: InternalError,
512
+ ErrorKind.USAGE: UsageError,
513
+ ErrorKind.NOT_FOUND: NotFoundError,
514
+ ErrorKind.ALREADY_EXISTS: AlreadyExistsError,
515
+ ErrorKind.BUSY: BusyError,
516
+ ErrorKind.PERMISSION: PermissionDeniedError,
517
+ ErrorKind.CORRUPT: CorruptError,
518
+ ErrorKind.IO: IoError,
519
+ ErrorKind.RETENTION_GAP: RetentionGapError,
520
+ }
521
+
522
+
523
+ def _take_error(err_ptr: POINTER(pls_error_t) | None) -> PlasmiteError:
524
+ if not err_ptr:
525
+ return PlasmiteError(ErrorKind.INTERNAL, "plasmite: unknown error")
526
+ err = err_ptr.contents
527
+ raw_kind = int(err.kind)
528
+ message = err.message.decode("utf-8") if err.message else ""
529
+ path = err.path.decode("utf-8") if err.path else None
530
+ seq = int(err.seq) if err.has_seq else None
531
+ offset = int(err.offset) if err.has_offset else None
532
+ missing = int(err.missing) or None
533
+ next_seq = int(err.next_seq) or None
534
+ _LIB.pls_error_free(err_ptr)
535
+ try:
536
+ kind = ErrorKind(raw_kind)
537
+ except ValueError:
538
+ kind = ErrorKind.INTERNAL
539
+ if not message:
540
+ message = _default_error_message(kind)
541
+ if kind == ErrorKind.RETENTION_GAP:
542
+ return RetentionGapError(kind, message, path, seq, offset, missing=missing, next_seq=next_seq)
543
+ error_cls = _ERROR_KIND_TO_CLASS.get(kind, PlasmiteError)
544
+ return error_cls(kind, message, path, seq, offset)
545
+
546
+
547
+ def _default_error_message(kind: ErrorKind) -> str:
548
+ mapping = {
549
+ ErrorKind.INTERNAL: "internal error",
550
+ ErrorKind.USAGE: "usage error",
551
+ ErrorKind.NOT_FOUND: "not found",
552
+ ErrorKind.ALREADY_EXISTS: "already exists",
553
+ ErrorKind.BUSY: "busy",
554
+ ErrorKind.PERMISSION: "permission denied",
555
+ ErrorKind.CORRUPT: "corrupt",
556
+ ErrorKind.IO: "io error",
557
+ ErrorKind.RETENTION_GAP: "retention gap",
558
+ }
559
+ return mapping.get(kind, "error")
560
+
561
+
562
+ def _buf_to_bytes(buf: pls_buf_t) -> bytes:
563
+ if not buf.data or buf.len == 0:
564
+ _LIB.pls_buf_free(byref(buf))
565
+ return b""
566
+ out = string_at(buf.data, buf.len)
567
+ _LIB.pls_buf_free(byref(buf))
568
+ return out
569
+
570
+
571
+ def _pool_info(inspect, handle):
572
+ buf = pls_buf_t()
573
+ error = POINTER(pls_error_t)()
574
+ if inspect(handle, byref(buf), byref(error)) != 0:
575
+ raise _take_error(error)
576
+ return json.loads(_buf_to_bytes(buf))
577
+
578
+
579
+ def _tag_array(values: Iterable[str]):
580
+ encoded = [_ensure_bytes(value.encode("utf-8"), "tag") for value in values]
581
+ if not encoded:
582
+ return POINTER(pls_text_t)(), encoded
583
+ array = (pls_text_t * len(encoded))(*(pls_text_t(value, len(value)) for value in encoded))
584
+ return array, encoded
585
+
586
+
587
+ def _closed_error(target: str) -> PlasmiteError:
588
+ return UsageError(ErrorKind.USAGE, f"plasmite: {target} is closed")
589
+
590
+
591
+ def _require_open(ptr: object, target: str) -> None:
592
+ if not ptr:
593
+ raise _closed_error(target)
594
+
595
+
596
+ _P = ParamSpec("_P")
597
+ _T = TypeVar("_T")
598
+
599
+
600
+ def _serialized_handle(method: Callable[_P, _T]) -> Callable[_P, _T]:
601
+ """Keep handle checks, native calls, and owned-result cleanup together."""
602
+ @wraps(method)
603
+ def locked(self, *args, **kwargs):
604
+ with self._lock:
605
+ return method(self, *args, **kwargs)
606
+
607
+ return type_cast(Callable[_P, _T], locked)
608
+
609
+
610
+ def _ensure_bytes(payload: bytes | bytearray | memoryview, name: str) -> bytes:
611
+ if isinstance(payload, bytes):
612
+ return payload if type(payload) is bytes else bytes.__getitem__(payload, slice(None))
613
+ if isinstance(payload, (bytearray, memoryview)):
614
+ encoded = bytes(payload)
615
+ return encoded if type(encoded) is bytes else bytes.__getitem__(encoded, slice(None))
616
+ raise TypeError(f"{name} must be bytes-like")
617
+
618
+
619
+ def _feed_input(value, format, tags):
620
+ if format not in (None, "json"):
621
+ raise UsageError(ErrorKind.USAGE, "feed accepts JSON input")
622
+ if isinstance(value, (bytes, bytearray, memoryview)):
623
+ if format is None:
624
+ raise TypeError("encoded input requires format='json'")
625
+ return _ensure_bytes(value, "payload")
626
+ if format is not None:
627
+ raise TypeError("format requires a bytes-like value")
628
+ if isinstance(value, Message):
629
+ if tags is not None:
630
+ raise UsageError(ErrorKind.USAGE, "cannot supply tags when forwarding a message")
631
+ elif not isinstance(value, dict):
632
+ raise UsageError(ErrorKind.USAGE, "feed data must be an object")
633
+ return value
634
+
635
+
636
+ def _description_json(about, example) -> bytes:
637
+ if about is not None and not isinstance(about, str):
638
+ raise TypeError("about must be a string")
639
+ if example is not None and not isinstance(example, dict):
640
+ raise TypeError("example must be a JSON object")
641
+ fields = {key: value for key, value in (("about", about), ("example", example)) if value is not None}
642
+ return json.dumps(fields, ensure_ascii=False, allow_nan=False).encode("utf-8")
643
+
644
+
645
+ def _encode_c_string(value: str, name: str) -> bytes:
646
+ encoded = _ensure_bytes(value.encode("utf-8"), name)
647
+ if b"\0" in encoded:
648
+ raise UsageError(ErrorKind.USAGE, f"{name} must not contain NUL")
649
+ return encoded
650
+
651
+
652
+ def _ensure_non_negative_int(value: int, name: str) -> int:
653
+ if not isinstance(value, int):
654
+ raise TypeError(f"{name} must be an int")
655
+ if value < 0:
656
+ raise UsageError(ErrorKind.USAGE, f"{name} must be >= 0")
657
+ if value > _UINT64_MAX:
658
+ raise UsageError(ErrorKind.USAGE, f"{name} must fit an unsigned 64-bit integer")
659
+ return value
660
+
661
+
662
+ @dataclass(frozen=True)
663
+ class _Instant:
664
+ nanoseconds: int
665
+
666
+
667
+ def at(nanoseconds: int) -> _Instant:
668
+ """Select a Unix nanosecond instant instead of a sequence."""
669
+ return _Instant(_ensure_non_negative_int(nanoseconds, "time"))
670
+
671
+
672
+ _DURATION_UNITS = dict(ns=1, us=1000, ms=1000000, s=10**9, m=60*10**9,
673
+ h=3600*10**9, d=86400*10**9)
674
+
675
+
676
+ def _timedelta_ns(value: timedelta) -> int:
677
+ return ((value.days * 86400 + value.seconds) * 10**6 + value.microseconds) * 1000
678
+
679
+
680
+ def _wait_deadline(wait):
681
+ if wait is None:
682
+ return None
683
+
684
+ from math import isfinite
685
+ from time import monotonic_ns
686
+
687
+ if isinstance(wait, timedelta):
688
+ nanos = _timedelta_ns(wait)
689
+ elif type(wait) is int or type(wait) is float and isfinite(wait * 10**9):
690
+ nanos = int(wait * 10**9)
691
+ else:
692
+ raise UsageError(ErrorKind.USAGE, "wait must be a duration in seconds or a timedelta")
693
+ if nanos < 0:
694
+ raise UsageError(ErrorKind.USAGE, "wait must be non-negative")
695
+ return monotonic_ns() + nanos
696
+
697
+
698
+ def _wait_ms(deadline, cancel):
699
+ limit = 50 if cancel is not None else _UINT64_MAX
700
+ if deadline is None:
701
+ return limit
702
+
703
+ from time import monotonic_ns
704
+
705
+ return min(limit, max(0, (deadline - monotonic_ns() + 999_999) // 1_000_000))
706
+
707
+
708
+ def _parse_time_ns(text: str) -> int:
709
+ pattern = r"(\d{4}-\d{2}-\d{2}[Tt]\d{2}:\d{2}:\d{2})(?:\.(\d+))?([Zz]|[+-]\d{2}:\d{2})"
710
+ parsed = re.fullmatch(pattern, text.strip(), re.ASCII)
711
+ if parsed is None:
712
+ raise ValueError("expected an RFC 3339 timestamp")
713
+ seconds, fraction, zone = parsed.groups()
714
+ whole = datetime.fromisoformat(seconds + ("+00:00" if zone.upper() == "Z" else zone))
715
+ epoch = datetime(1970, 1, 1, tzinfo=timezone.utc)
716
+ return _timedelta_ns(whole - epoch) + int((fraction or "")[:9].ljust(9, "0"))
717
+
718
+
719
+ ReadStart = int | str | datetime | timedelta | _Instant
720
+ FeedValue = dict[str, object] | Message | bytes | bytearray | memoryview
721
+ FeedDurability = Durability | Literal["fast", "flush"]
722
+ FeedFormat = Literal["json"]
723
+
724
+
725
+ def _durability_code(durability: FeedDurability) -> int:
726
+ if durability == "fast":
727
+ return Durability.FAST
728
+ if durability == "flush":
729
+ return Durability.FLUSH
730
+ try:
731
+ return int(durability)
732
+ except (TypeError, ValueError) as exc:
733
+ raise UsageError(ErrorKind.USAGE, "durability must be 'fast' or 'flush'") from exc
734
+
735
+
736
+ def _read_start(since: ReadStart | None, last: int | None, after: int | None = None) -> tuple[int, int]:
737
+ try:
738
+ if sum(value is not None for value in (since, last, after)) > 1:
739
+ raise ValueError("since, after and last are mutually exclusive")
740
+ if after is not None:
741
+ return 6, _ensure_non_negative_int(after, "after")
742
+ if last is not None:
743
+ return 5, _ensure_non_negative_int(last, "last")
744
+ if since is None:
745
+ return 0, 0
746
+ if isinstance(since, _Instant):
747
+ return 3, since.nanoseconds
748
+ if isinstance(since, datetime):
749
+ if since.utcoffset() is None:
750
+ raise ValueError("since datetime requires a timezone")
751
+ nanos = _timedelta_ns(since - datetime(1970, 1, 1, tzinfo=timezone.utc))
752
+ return 3, max(0, min(_UINT64_MAX, nanos))
753
+ if isinstance(since, timedelta):
754
+ return 4, _ensure_non_negative_int(_timedelta_ns(since), "since")
755
+ if isinstance(since, int):
756
+ return 2, _ensure_non_negative_int(since, "since")
757
+ if isinstance(since, str):
758
+ if since == "oldest":
759
+ return 1, 0
760
+ if duration := re.fullmatch(r"([0-9]+)(ns|us|ms|s|m|h|d)", since.strip(), re.I):
761
+ value = int(duration[1]) * _DURATION_UNITS[duration[2].lower()]
762
+ return 4, min(_UINT64_MAX, value)
763
+ return 3, max(0, min(_UINT64_MAX, _parse_time_ns(since)))
764
+ raise ValueError("since must be oldest, a sequence, an instant or a duration")
765
+ except ValueError as exc:
766
+ raise UsageError(ErrorKind.USAGE, str(exc)) from exc
767
+
768
+
769
+ class Client:
770
+ def __init__(self, pool_dir: str | None = None) -> None:
771
+ self._lock = RLock()
772
+ self._ptr = None
773
+ if pool_dir is None:
774
+ pool_dir = default_pool_dir()
775
+ if not pool_dir:
776
+ raise UsageError(ErrorKind.USAGE, "pool_dir is required")
777
+ out_client = POINTER(pls_client_t)()
778
+ out_err = POINTER(pls_error_t)()
779
+ rc = _LIB.pls_client_new(_encode_c_string(pool_dir, "pool_dir"), byref(out_client), byref(out_err))
780
+ if rc != 0:
781
+ raise _take_error(out_err)
782
+ self._ptr = out_client
783
+
784
+ @_serialized_handle
785
+ def create_pool(
786
+ self,
787
+ pool_ref: str,
788
+ size_bytes: int = DEFAULT_POOL_SIZE_BYTES,
789
+ *,
790
+ about: str | None = None,
791
+ example: dict | None = None,
792
+ ) -> Pool:
793
+ _require_open(self._ptr, "client")
794
+ if not pool_ref:
795
+ raise UsageError(ErrorKind.USAGE, "pool_ref is required")
796
+ size_bytes = _ensure_non_negative_int(size_bytes, "size_bytes")
797
+ out_pool = POINTER(pls_pool_t)()
798
+ out_err = POINTER(pls_error_t)()
799
+ encoded_ref = _encode_c_string(pool_ref, "pool_ref")
800
+ native_size = c_uint64(size_bytes)
801
+ description = None if about is None and example is None else _description_json(about, example)
802
+ create = _LIB.pls_pool_create if description is None else _LIB.pls_pool_create_described
803
+ fields = () if description is None else (description, len(description))
804
+ _require_open(self._ptr, "client")
805
+ rc = create(
806
+ self._ptr,
807
+ encoded_ref,
808
+ native_size,
809
+ *fields,
810
+ byref(out_pool),
811
+ byref(out_err),
812
+ )
813
+ if rc != 0:
814
+ raise _take_error(out_err)
815
+ return Pool(out_pool)
816
+
817
+ @_serialized_handle
818
+ def open(self, pool_ref: str, *, create: bool = False, source: str | None = None) -> Pool | UdpPool:
819
+ _require_open(self._ptr, "client")
820
+ if not pool_ref:
821
+ raise UsageError(ErrorKind.USAGE, "pool_ref is required")
822
+ if pool_ref.lower().startswith("udp://"):
823
+ return _open_udp_pool(pool_ref, create, source)
824
+ out_pool = POINTER(pls_pool_t)()
825
+ out_err = POINTER(pls_error_t)()
826
+ encoded_ref = _encode_c_string(pool_ref, "pool_ref")
827
+ encoded_source = None if source is None else _encode_c_string(source, "source")
828
+ options = pls_open_options_t(sizeof(pls_open_options_t), int(create), encoded_source)
829
+ _require_open(self._ptr, "client")
830
+ rc = _LIB.pls_pool_open(
831
+ self._ptr, encoded_ref, byref(options), byref(out_pool), byref(out_err),
832
+ )
833
+ if rc != 0:
834
+ raise _take_error(out_err)
835
+ return Pool(out_pool)
836
+
837
+ @_serialized_handle
838
+ def list_pools(self) -> list[PoolInfo]:
839
+ _require_open(self._ptr, "client")
840
+ return type_cast(list[PoolInfo], _pool_info(_LIB.pls_internal_pool_list_json, self._ptr))
841
+
842
+ @_serialized_handle
843
+ def delete_pool(self, pool_ref: str) -> None:
844
+ _require_open(self._ptr, "client")
845
+ error = POINTER(pls_error_t)()
846
+ encoded = _encode_c_string(pool_ref, "pool_ref")
847
+ _require_open(self._ptr, "client")
848
+ if _LIB.pls_pool_delete(self._ptr, encoded, byref(error)) != 0:
849
+ raise _take_error(error)
850
+
851
+ @_serialized_handle
852
+ def close(self) -> None:
853
+ if getattr(self, "_ptr", None):
854
+ _LIB.pls_client_free(self._ptr)
855
+ self._ptr = None
856
+
857
+ def __enter__(self) -> Client:
858
+ with self._lock:
859
+ _require_open(self._ptr, "client")
860
+ return self
861
+
862
+ def __exit__(self, _exc_type, _exc, _tb) -> None:
863
+ self.close()
864
+
865
+ def __del__(self) -> None:
866
+ self.close()
867
+
868
+
869
+ def _append_native(append, address, value, tags, durability):
870
+ try:
871
+ return append(address, value, tags, durability)
872
+ except OverflowError:
873
+ def oversized(item, path, active):
874
+ if type(item) is int and not -(1 << 63) <= item < 1 << 63:
875
+ return item, path
876
+ if type(item) not in (dict, list, tuple) or id(item) in active:
877
+ return None
878
+ active.add(id(item))
879
+ children = item.items() if type(item) is dict else enumerate(item)
880
+ try:
881
+ for key, child in children:
882
+ segment = str(key).replace("~", "~0").replace("/", "~1")
883
+ result = oversized(child, f"{path}/{segment}", active)
884
+ if result is not None:
885
+ return result
886
+ finally:
887
+ active.remove(id(item))
888
+ return None
889
+
890
+ result = oversized(value, "/data", set())
891
+ if result is None:
892
+ raise
893
+ number, path = result
894
+ raise UsageError(
895
+ ErrorKind.USAGE,
896
+ f"integer {number} at {path} is outside the signed 64-bit range; send it as a string",
897
+ ) from None
898
+
899
+
900
+ class Pool:
901
+ def __init__(self, ptr: POINTER(pls_pool_t)) -> None:
902
+ from ._views import backend
903
+
904
+ self._lock = RLock()
905
+ self._ptr = ptr
906
+ self._address = cast(ptr, c_void_p).value
907
+ self._backend = backend
908
+
909
+ @_serialized_handle
910
+ def info(self) -> PoolInfo:
911
+ _require_open(self._ptr, "pool")
912
+ return type_cast(PoolInfo, _pool_info(_LIB.pls_internal_pool_info_json, self._ptr))
913
+
914
+ @_serialized_handle
915
+ def set_description(self, *, about: str | None = None, example: dict | None = None) -> None:
916
+ """Replace the pool's description and example. Omitted fields are cleared."""
917
+ _require_open(self._ptr, "pool")
918
+ description = _description_json(about, example)
919
+ out_err = POINTER(pls_error_t)()
920
+ _require_open(self._ptr, "pool")
921
+ if _LIB.pls_pool_set_description(self._ptr, description, len(description), byref(out_err)):
922
+ raise _take_error(out_err)
923
+
924
+ def feed(
925
+ self, value: FeedValue, tags: Iterable[str] | None = None,
926
+ durability: FeedDurability = Durability.FAST,
927
+ *, format: FeedFormat | None = None,
928
+ ) -> Receipt:
929
+ """Store a message and return its assigned sequence and time."""
930
+ return self._feed_receipt(value, tags, durability, format=format)
931
+
932
+ def _try_fast_feed(self, value, tags):
933
+ append = getattr(self._backend, "try_append_receipt", None)
934
+ if append is None or not self._lock.acquire(blocking=False):
935
+ return None
936
+ try:
937
+ _require_open(self._ptr, "pool")
938
+ try:
939
+ result = _append_native(append, self._address, value, tags, Durability.FAST)
940
+ except TypeError:
941
+ return None
942
+ return Receipt(*result) if type(result) is tuple else result
943
+ finally:
944
+ self._lock.release()
945
+
946
+ @_serialized_handle
947
+ def _finish_fast_feed(self, pending):
948
+ _require_open(self._ptr, "pool")
949
+ return Receipt(*self._backend.commit_pending_builder(self._address, pending))
950
+
951
+ @_serialized_handle
952
+ def feed_many(
953
+ self, values: Iterable[dict[str, object]], tags: Iterable[str] | None = None,
954
+ durability: FeedDurability = Durability.FAST,
955
+ ) -> list[Receipt]:
956
+ """Validate a batch of objects and publish all its receipts together."""
957
+ _require_open(self._ptr, "pool")
958
+ labels = None if tags is None else list(tags)
959
+ policy = _durability_code(durability)
960
+ inputs = []
961
+ capture = self._backend.capture_batch_builder
962
+ for value in values:
963
+ if not isinstance(value, dict):
964
+ raise UsageError(ErrorKind.USAGE, "batch values must be objects")
965
+ try:
966
+ pending = _append_native(capture, None, value, labels, policy)
967
+ except TypeError:
968
+ pending = _append_native(capture, None, json.loads(json.dumps(value)), labels, policy)
969
+ inputs.append(pending)
970
+ if not inputs:
971
+ return []
972
+ builders = (c_void_p * len(inputs))(*(address for address, _ in inputs))
973
+ options = pls_feed_options_t(sizeof(pls_feed_options_t), policy, None, 0)
974
+ receipts = (_NativeReceipt * len(inputs))()
975
+ error = POINTER(pls_error_t)()
976
+ _require_open(self._ptr, "pool")
977
+ rc = _LIB.pls_internal_pool_feed_many_builders(
978
+ self._ptr, builders, len(inputs), byref(options), receipts, byref(error),
979
+ )
980
+ if rc != 0:
981
+ raise _take_error(error)
982
+ return [Receipt(receipt.seq, receipt.time) for receipt in receipts]
983
+
984
+ @_serialized_handle
985
+ def _feed_receipt(
986
+ self, value: FeedValue, tags: Iterable[str] | None = None,
987
+ durability: FeedDurability = Durability.FAST,
988
+ *, format: FeedFormat | None = None,
989
+ ) -> Receipt:
990
+ """Store an object or forward a message with a new sequence and time."""
991
+ _require_open(self._ptr, "pool")
992
+ if type(value) is not dict or format is not None:
993
+ value = _feed_input(value, format, tags)
994
+ # Normalize callbacks before using the handle they can close.
995
+ tags = None if tags is None else list(tags)
996
+ durability_code = _durability_code(durability)
997
+ if format is None:
998
+ _require_open(self._ptr, "pool")
999
+ if isinstance(value, Message):
1000
+ view = self._backend.append(self._address, value._view, None, durability_code)
1001
+ return Receipt(view.seq, view.time)
1002
+ try:
1003
+ append_receipt = getattr(self._backend, "append_receipt", None)
1004
+ if type(value) is dict and append_receipt is not None:
1005
+ return Receipt(*_append_native(
1006
+ append_receipt, self._address, value, tags, durability_code
1007
+ ))
1008
+ view = _append_native(
1009
+ self._backend.append, self._address, value, tags, durability_code
1010
+ )
1011
+ return Receipt(view.seq, view.time)
1012
+ except TypeError:
1013
+ # The native builder uses exact builtins. Python's JSON encoder
1014
+ # also accepts subclasses that feed has always supported.
1015
+ value, format = json.dumps(value).encode("utf-8"), "json"
1016
+ encoded_tags, keepalive = _tag_array([] if tags is None else tags)
1017
+ options = pls_feed_options_t(sizeof(pls_feed_options_t), durability_code,
1018
+ encoded_tags, len(keepalive))
1019
+ receipt, error = _NativeReceipt(), POINTER(pls_error_t)()
1020
+ _require_open(self._ptr, "pool")
1021
+ if _LIB.pls_pool_feed_json(self._ptr, value, len(value),
1022
+ byref(options), byref(receipt), byref(error)):
1023
+ raise _take_error(error)
1024
+ return Receipt(receipt.seq, receipt.time)
1025
+
1026
+ @_serialized_handle
1027
+ def _open_reader(self, open_native, since, after, last, tags, cancel):
1028
+ _require_open(self._ptr, "pool")
1029
+ kind, value = _read_start(since, last, after)
1030
+ tag_array, encoded_tags = _tag_array([] if tags is None else tags)
1031
+ options = pls_read_options_t(sizeof(pls_read_options_t), kind, value,
1032
+ tag_array, len(encoded_tags))
1033
+ from ._views import ViewStream
1034
+
1035
+ native = POINTER(pls_reader_t)()
1036
+ error = POINTER(pls_error_t)()
1037
+ _require_open(self._ptr, "pool")
1038
+ if open_native(self._ptr, byref(options), byref(native), byref(error)) != 0:
1039
+ raise _take_error(error)
1040
+ return Reader(ViewStream(_Stream(native), cancel))
1041
+
1042
+ def fetch(self, *, since: ReadStart | None = None, after: int | None = None, last: int | None = None,
1043
+ tags: Iterable[str] | None = None, cancel: Event | None = None) -> Reader:
1044
+ """Read through the last sequence present when this call opens the reader."""
1045
+ return self._open_reader(_LIB.pls_pool_fetch, since, after, last, tags, cancel)
1046
+
1047
+ def follow(self, *, since: ReadStart | None = None, after: int | None = None, last: int | None = None,
1048
+ tags: Iterable[str] | None = None, cancel: Event | None = None) -> Reader:
1049
+ """Open a live reader now. With no selection, read new messages."""
1050
+ return self._open_reader(_LIB.pls_pool_follow, since, after, last, tags, cancel)
1051
+
1052
+ @_serialized_handle
1053
+ def close(self) -> None:
1054
+ if getattr(self, "_ptr", None):
1055
+ _LIB.pls_pool_free(self._ptr)
1056
+ self._ptr = None
1057
+
1058
+ def __enter__(self) -> Pool:
1059
+ with self._lock:
1060
+ _require_open(self._ptr, "pool")
1061
+ return self
1062
+
1063
+ def __exit__(self, _exc_type, _exc, _tb) -> None:
1064
+ self.close()
1065
+
1066
+ def __del__(self) -> None:
1067
+ self.close()
1068
+
1069
+
1070
+ class _Stream:
1071
+ def __init__(self, ptr: POINTER(pls_reader_t)) -> None:
1072
+ self._lock = RLock()
1073
+ self._state_lock = RLock()
1074
+ self._ptr = ptr
1075
+
1076
+ def cancel(self) -> None:
1077
+ """Permanently cancel a read, including one running on another thread."""
1078
+ with self._state_lock:
1079
+ if self._ptr:
1080
+ _LIB.pls_reader_cancel(self._ptr)
1081
+
1082
+ def close(self) -> None:
1083
+ if not hasattr(self, "_state_lock"):
1084
+ return
1085
+ self.cancel()
1086
+ with self._lock:
1087
+ with self._state_lock:
1088
+ if self._ptr:
1089
+ _LIB.pls_reader_free(self._ptr)
1090
+ self._ptr = None
1091
+
1092
+ def __enter__(self) -> _Stream:
1093
+ with self._lock:
1094
+ _require_open(self._ptr, "stream")
1095
+ return self
1096
+
1097
+ def __exit__(self, _exc_type, _exc, _tb) -> None:
1098
+ self.close()
1099
+
1100
+ def __del__(self) -> None:
1101
+ self.close()
1102
+
1103
+
1104
+ class Reader:
1105
+ """Read messages, bound a wait, or close the reader to stop it."""
1106
+
1107
+ def __init__(self, reader) -> None:
1108
+ self._reader = reader
1109
+ self._read_lock = Lock()
1110
+
1111
+ def __iter__(self) -> Reader:
1112
+ return self
1113
+
1114
+ def __next__(self) -> Message:
1115
+ message = self.get()
1116
+ assert message is not None
1117
+ return message
1118
+
1119
+ def get(self, *, timeout: timedelta | float | None = None) -> Message | None:
1120
+ """Return a message, or None if the wait expires."""
1121
+ if not self._read_lock.acquire(blocking=False):
1122
+ raise BusyError(ErrorKind.BUSY, "a read is already in progress")
1123
+ try:
1124
+ view = self._reader.next(timeout)
1125
+ except StopIteration:
1126
+ self.close()
1127
+ raise
1128
+ finally:
1129
+ self._read_lock.release()
1130
+ return None if view is None else Message(view)
1131
+
1132
+ def get_many(self, *, max: int, timeout: timedelta | float | None = None) -> list[Message] | None:
1133
+ """Return up to max messages, None on timeout, or [] at the end."""
1134
+ try:
1135
+ return self._get_many(max, timeout) or None
1136
+ except StopIteration:
1137
+ return []
1138
+
1139
+ def _get_many(self, max: int, timeout: timedelta | float | None) -> list[Message]:
1140
+ import sys
1141
+
1142
+ if not self._read_lock.acquire(blocking=False):
1143
+ raise BusyError(ErrorKind.BUSY, "a read is already in progress")
1144
+ try:
1145
+ return [Message(view) for view in self._reader.next_batch(max, sys.maxsize, timeout)]
1146
+ except StopIteration:
1147
+ self.close()
1148
+ raise
1149
+ finally:
1150
+ self._read_lock.release()
1151
+
1152
+ def next(self, wait: timedelta | float | None = None) -> Message | None:
1153
+ return self.get(timeout=wait)
1154
+
1155
+ def cancel(self) -> None:
1156
+ self._reader.cancel()
1157
+
1158
+ def close(self) -> None:
1159
+ self._reader.close()
1160
+
1161
+ def __enter__(self) -> Reader:
1162
+ self._reader.__enter__()
1163
+ return self
1164
+
1165
+ def __exit__(self, _exc_type, _exc, _tb) -> None:
1166
+ self.close()
1167
+
1168
+
1169
+ @dataclass(frozen=True)
1170
+ class UdpSkip:
1171
+ """A range the server explicitly skipped."""
1172
+
1173
+ first: int
1174
+ last: int
1175
+ reason: str
1176
+
1177
+
1178
+ @dataclass(frozen=True)
1179
+ class UdpProgress:
1180
+ start_seq: int
1181
+ next_seq: int
1182
+ end_seq: int | None
1183
+ terminal: bool
1184
+
1185
+
1186
+ UdpEvent = Message | UdpSkip | UdpProgress
1187
+
1188
+
1189
+ class UdpClient:
1190
+ """Client for one explicit UDP endpoint."""
1191
+
1192
+ def __init__(self, endpoint: str) -> None:
1193
+ self._lock = RLock()
1194
+ self._ptr = None
1195
+ if not endpoint:
1196
+ raise UsageError(ErrorKind.USAGE, "endpoint is required")
1197
+ out_client = POINTER(pls_udp_client_t)()
1198
+ out_err = POINTER(pls_error_t)()
1199
+ rc = _LIB.pls_udp_client_new(_encode_c_string(endpoint, "endpoint"), byref(out_client), byref(out_err))
1200
+ if rc != 0:
1201
+ raise _take_error(out_err)
1202
+ self._ptr = out_client
1203
+
1204
+ @_serialized_handle
1205
+ def open(self, pool_name: str, *, source: str | None = None) -> UdpPool:
1206
+ _require_open(self._ptr, "UDP client")
1207
+ if not pool_name:
1208
+ raise UsageError(ErrorKind.USAGE, "pool_name is required")
1209
+ if source is not None:
1210
+ encoded = _encode_c_string(source, "source")
1211
+ if not 1 <= len(encoded) <= 64 or any(ord(char) < 32 or 127 <= ord(char) <= 159 for char in source):
1212
+ raise UsageError(ErrorKind.USAGE, "source must be 1 to 64 UTF-8 bytes without control characters")
1213
+ out_pool = POINTER(pls_udp_pool_t)()
1214
+ out_err = POINTER(pls_error_t)()
1215
+ encoded_name = _encode_c_string(pool_name, "pool_name")
1216
+ _require_open(self._ptr, "UDP client")
1217
+ rc = _LIB.pls_udp_client_open_pool(
1218
+ self._ptr,
1219
+ encoded_name,
1220
+ byref(out_pool),
1221
+ byref(out_err),
1222
+ )
1223
+ if rc != 0:
1224
+ raise _take_error(out_err)
1225
+ return UdpPool(out_pool, source)
1226
+
1227
+ @_serialized_handle
1228
+ def close(self) -> None:
1229
+ if self._ptr:
1230
+ _LIB.pls_udp_client_free(self._ptr)
1231
+ self._ptr = None
1232
+
1233
+ def __enter__(self) -> UdpClient:
1234
+ with self._lock:
1235
+ _require_open(self._ptr, "UDP client")
1236
+ return self
1237
+
1238
+ def __exit__(self, _exc_type, _exc, _tb) -> None:
1239
+ self.close()
1240
+
1241
+ def __del__(self) -> None:
1242
+ self.close()
1243
+
1244
+
1245
+ class UdpPool:
1246
+ """A named pool on one UDP endpoint."""
1247
+
1248
+ def __init__(self, ptr: POINTER(pls_udp_pool_t), source: str | None = None) -> None:
1249
+ self._lock = RLock()
1250
+ self._ptr = ptr
1251
+ self._source = source
1252
+
1253
+ @_serialized_handle
1254
+ def feed(
1255
+ self, value: FeedValue, tags: Iterable[str] | None = None,
1256
+ durability: FeedDurability = Durability.FAST,
1257
+ *, format: FeedFormat | Literal["raw"] | None = None,
1258
+ ) -> None:
1259
+ _require_open(self._ptr, "UDP pool")
1260
+ if _durability_code(durability) != Durability.FAST:
1261
+ raise UsageError(ErrorKind.USAGE, "UDP feed supports fast durability only")
1262
+ labels = [] if tags is None else list(tags)
1263
+ _tag_array(labels)
1264
+ meta: dict[str, object] = {}
1265
+ if self._source is not None:
1266
+ meta["source"] = self._source
1267
+ if format == "raw":
1268
+ data = _ensure_bytes(value, "payload")
1269
+ if not labels and not meta:
1270
+ return self._send_device(b"\0" + data)
1271
+ meta["types"] = {"/data/bytes": "bytes/base64"}
1272
+ value = {"bytes": b64encode(data).decode("ascii")}
1273
+ format = None
1274
+ value = _feed_input(value, format, tags)
1275
+ if isinstance(value, Message):
1276
+ view = value._view
1277
+ owner = view._owner_address
1278
+ error = POINTER(pls_error_t)()
1279
+ _require_open(self._ptr, "UDP pool")
1280
+ if _LIB.pls_internal_udp_pool_feed_view(self._ptr, owner, False, byref(error)) != 0:
1281
+ raise _take_error(error)
1282
+ return
1283
+ payload = value if format == "json" else json.dumps(value).encode("utf-8")
1284
+ envelope = json.dumps({"tags": labels, "meta": meta}, separators=(",", ":")).encode("utf-8")
1285
+ self._send_device(envelope[:-1] + b',"data":' + payload + b"}")
1286
+
1287
+ def _send_device(self, body: bytes) -> None:
1288
+ error = POINTER(pls_error_t)()
1289
+ _require_open(self._ptr, "UDP pool")
1290
+ if _LIB.pls_internal_udp_pool_feed_device(self._ptr, body, len(body), byref(error)) != 0:
1291
+ raise _take_error(error)
1292
+
1293
+ def follow(self, *, since: ReadStart | None = None, after: int | None = None, last: int | None = None,
1294
+ tags: Iterable[str] | None = None, cancel: Event | None = None) -> UdpFollow:
1295
+ return self._read(True, since, after, last, tags, cancel)
1296
+
1297
+ def fetch(self, *, since: ReadStart | None = None, after: int | None = None, last: int | None = None,
1298
+ tags: Iterable[str] | None = None, cancel: Event | None = None) -> UdpFollow:
1299
+ return self._read(False, since, after, last, tags, cancel)
1300
+
1301
+ @_serialized_handle
1302
+ def _read(self, live, since, after, last, tags, cancel) -> UdpFollow:
1303
+ _require_open(self._ptr, "UDP pool")
1304
+ kind, value = _read_start(since, last, after)
1305
+ encoded, values = _tag_array([] if tags is None else tags)
1306
+ options = pls_read_options_t(sizeof(pls_read_options_t), kind, value, encoded, len(values))
1307
+ native = POINTER(pls_udp_follow_t)()
1308
+ error = POINTER(pls_error_t)()
1309
+ _require_open(self._ptr, "UDP pool")
1310
+ open_read = _LIB.pls_udp_pool_follow if live else _LIB.pls_udp_pool_fetch
1311
+ if open_read(self._ptr, byref(options), byref(native), byref(error)) != 0:
1312
+ raise _take_error(error)
1313
+ return UdpFollow(native, cancel=cancel)
1314
+
1315
+ @_serialized_handle
1316
+ def close(self) -> None:
1317
+ if self._ptr:
1318
+ _LIB.pls_udp_pool_free(self._ptr)
1319
+ self._ptr = None
1320
+
1321
+ def __enter__(self) -> UdpPool:
1322
+ with self._lock:
1323
+ _require_open(self._ptr, "UDP pool")
1324
+ return self
1325
+
1326
+ def __exit__(self, _exc_type, _exc, _tb) -> None:
1327
+ self.close()
1328
+
1329
+ def __del__(self) -> None:
1330
+ self.close()
1331
+
1332
+
1333
+ class UdpFollow:
1334
+ """Best-effort UDP event stream. Close cancels a blocked wait."""
1335
+
1336
+ def __init__(self, ptr: POINTER(pls_udp_follow_t), *, cancel=None) -> None:
1337
+ from ._views import backend
1338
+
1339
+ self._state_lock = RLock()
1340
+ self._read_lock = Lock()
1341
+ self._ptr = ptr
1342
+ self._closing = False
1343
+ self._cancelled = False
1344
+ self._adopt_owner = backend.adopt_owner
1345
+ self._cancel = cancel
1346
+ self._finished = False
1347
+
1348
+ def next_event(self, wait: timedelta | float | None = None) -> UdpEvent | None:
1349
+ """Read a message or a UDP skip or progress event."""
1350
+ return self._next_event(_wait_deadline(wait))
1351
+
1352
+ def _next_event(self, deadline) -> UdpEvent | None:
1353
+ from time import monotonic_ns
1354
+
1355
+ if not self._read_lock.acquire(blocking=False):
1356
+ raise BusyError(ErrorKind.BUSY, "a read is already in progress")
1357
+ try:
1358
+ with self._state_lock:
1359
+ if not self._ptr or self._closing or self._cancelled or self._finished:
1360
+ return None
1361
+ ptr = self._ptr
1362
+ while True:
1363
+ if self._cancel is not None and self._cancel.is_set():
1364
+ self.cancel()
1365
+ return None
1366
+ event = pls_udp_event_t()
1367
+ out_err = POINTER(pls_error_t)()
1368
+ wait_ms = _wait_ms(deadline, self._cancel)
1369
+ owner = c_void_p()
1370
+ rc = _LIB.pls_udp_follow_next_view(
1371
+ ptr, c_uint64(wait_ms), byref(event), byref(owner), byref(out_err)
1372
+ )
1373
+ if rc == 1:
1374
+ if event.kind == 1:
1375
+ try:
1376
+ return Message(self._adopt_owner(owner.value))
1377
+ finally:
1378
+ _LIB.pls_udp_event_free(byref(event))
1379
+ return _udp_event_to_python(event)
1380
+ if rc == 2 or rc == 3:
1381
+ with self._state_lock:
1382
+ self._finished = True
1383
+ return None
1384
+ if rc < 0:
1385
+ raise _take_error(out_err)
1386
+ if deadline is not None and monotonic_ns() >= deadline:
1387
+ return None
1388
+ finally:
1389
+ self._read_lock.release()
1390
+
1391
+ def get(self, *, timeout: timedelta | float | None = None) -> Message | None:
1392
+ """Read the next message. Use next_event to include UDP controls."""
1393
+ deadline = _wait_deadline(timeout)
1394
+ while True:
1395
+ event = self._next_event(deadline)
1396
+ if isinstance(event, Message):
1397
+ return event
1398
+ if event is None:
1399
+ if self._finished or self._closing or self._cancelled or not self._ptr:
1400
+ raise StopIteration
1401
+ return None
1402
+
1403
+ def next(self, wait: timedelta | float | None = None) -> Message | None:
1404
+ return self.get(timeout=wait)
1405
+
1406
+ def events(self) -> Generator[UdpEvent, None, None]:
1407
+ while True:
1408
+ event = self.next_event()
1409
+ if event is None:
1410
+ return
1411
+ yield event
1412
+
1413
+ def __iter__(self) -> UdpFollow:
1414
+ return self
1415
+
1416
+ def __next__(self) -> Message:
1417
+ message = self.get()
1418
+ assert message is not None
1419
+ return message
1420
+
1421
+ def cancel(self) -> None:
1422
+ with self._state_lock:
1423
+ if self._ptr and not self._cancelled:
1424
+ _LIB.pls_udp_follow_cancel(self._ptr)
1425
+ self._cancelled = True
1426
+
1427
+ def close(self) -> None:
1428
+ with self._state_lock:
1429
+ ptr = self._ptr
1430
+ if not ptr:
1431
+ return
1432
+ self._closing = True
1433
+ _LIB.pls_udp_follow_cancel(ptr)
1434
+ with self._read_lock:
1435
+ with self._state_lock:
1436
+ if self._ptr:
1437
+ _LIB.pls_udp_follow_free(self._ptr)
1438
+ self._ptr = None
1439
+ self._cancelled = True
1440
+
1441
+ def __enter__(self) -> UdpFollow:
1442
+ with self._state_lock:
1443
+ _require_open(self._ptr, "UDP follow")
1444
+ return self
1445
+
1446
+ def __exit__(self, _exc_type, _exc, _tb) -> None:
1447
+ self.close()
1448
+
1449
+ def __del__(self) -> None:
1450
+ self.close()
1451
+
1452
+
1453
+ def _udp_event_to_python(event: pls_udp_event_t) -> UdpEvent:
1454
+ try:
1455
+ if event.kind == 2:
1456
+ reasons = {0: "unknown", 1: "oversized", 2: "retention", 3: "pressure"}
1457
+ return UdpSkip(int(event.first), int(event.last), reasons.get(int(event.reason), "unknown"))
1458
+ if event.kind == 3:
1459
+ return UdpProgress(
1460
+ int(event.start_seq),
1461
+ int(event.next_seq),
1462
+ int(event.end_seq) if event.has_end else None,
1463
+ bool(event.terminal),
1464
+ )
1465
+ raise PlasmiteError(ErrorKind.INTERNAL, f"plasmite: unknown UDP event kind {event.kind}")
1466
+ finally:
1467
+ _LIB.pls_udp_event_free(byref(event))
1468
+
1469
+
1470
+ def create_pool(
1471
+ pool_ref: str, size_bytes: int = DEFAULT_POOL_SIZE_BYTES, *,
1472
+ about: str | None = None, example: dict | None = None,
1473
+ ) -> Pool:
1474
+ with Client() as client:
1475
+ return client.create_pool(pool_ref, size_bytes, about=about, example=example)
1476
+
1477
+
1478
+ def _open_udp_pool(pool_ref: str, create: bool, source: str | None) -> UdpPool:
1479
+ if create:
1480
+ raise UsageError(ErrorKind.USAGE, "pool creation requires local or HTTP access")
1481
+ try:
1482
+ url = urlsplit(pool_ref)
1483
+ _, separator, path = url.path.partition("/")
1484
+ name = unquote(path, errors="strict")
1485
+ if (not url.hostname or not url.port or url.username is not None or "?" in pool_ref
1486
+ or "#" in pool_ref or not separator or not name or any(c in name for c in "/\\\0")):
1487
+ raise ValueError("expected udp://HOST:PORT/POOL")
1488
+ except ValueError as exc:
1489
+ raise UsageError(ErrorKind.USAGE, f"invalid UDP pool reference: {exc}") from exc
1490
+ with UdpClient(f"udp://{url.netloc}") as client:
1491
+ return client.open(name, source=source)
1492
+
1493
+
1494
+ def open(pool_ref: str, *, create: bool = False, source: str | None = None) -> Pool | UdpPool:
1495
+ if pool_ref.lower().startswith("udp://"):
1496
+ return _open_udp_pool(pool_ref, create, source)
1497
+ with Client() as client:
1498
+ return client.open(pool_ref, create=create, source=source)
1499
+
1500
+
1501
+ def list_pools() -> list[PoolInfo]:
1502
+ with Client() as client:
1503
+ return client.list_pools()
1504
+
1505
+
1506
+ def delete_pool(pool_ref: str) -> None:
1507
+ with Client() as client:
1508
+ client.delete_pool(pool_ref)
1509
+
1510
+
1511
+ __all__ = [
1512
+ "Client",
1513
+ "Pool",
1514
+ "Message",
1515
+ "Receipt",
1516
+ "MessageMeta",
1517
+ "PoolInfo",
1518
+ "PoolBounds",
1519
+ "Reader",
1520
+ "at",
1521
+ "create_pool",
1522
+ "open",
1523
+ "list_pools",
1524
+ "delete_pool",
1525
+ "UdpClient",
1526
+ "UdpPool",
1527
+ "UdpFollow",
1528
+ "UdpSkip",
1529
+ "UdpProgress",
1530
+ "Durability",
1531
+ "ErrorKind",
1532
+ "PlasmiteError",
1533
+ "NotFoundError",
1534
+ "AlreadyExistsError",
1535
+ "BusyError",
1536
+ "PermissionDeniedError",
1537
+ "CorruptError",
1538
+ "IoError",
1539
+ "UsageError",
1540
+ "InternalError",
1541
+ "RetentionGapError",
1542
+ "DEFAULT_POOL_DIR",
1543
+ "DEFAULT_POOL_SIZE_BYTES",
1544
+ "default_pool_dir",
1545
+ ]