chat-client-sdk 0.1.0__py3-none-any.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,111 @@
1
+ Metadata-Version: 2.4
2
+ Name: chat-client-sdk
3
+ Version: 0.1.0
4
+ Summary: Python wrapper for the Rust chat client C ABI
5
+ License: MIT
6
+ Requires-Python: >=3.9
7
+ Description-Content-Type: text/markdown
8
+
9
+ # Python Chat SDK
10
+
11
+ This package wraps the Rust `chat-client-sdk` C ABI using only the Python standard library. It supports Windows, Linux, and macOS on x86-64 and ARM64. Download the native build for your platform separately; the SDK detects it in a `builds/` folder.
12
+
13
+ ## Install
14
+
15
+ ```sh
16
+ python -m pip install .
17
+ ```
18
+
19
+ Place the native library for each platform you distribute in an OS/architecture subfolder beneath the application's `builds/` directory:
20
+
21
+ ```text
22
+ your-project/
23
+ builds/
24
+ windows-x86_64/chat_client_sdk.dll
25
+ windows-aarch64/chat_client_sdk.dll
26
+ linux-x86_64/libchat_client_sdk.so
27
+ linux-aarch64/libchat_client_sdk.so
28
+ darwin-x86_64/libchat_client_sdk.dylib
29
+ darwin-aarch64/libchat_client_sdk.dylib
30
+ app.py
31
+ ```
32
+
33
+ The SDK chooses the matching subfolder automatically. A library placed directly in `builds/` is also accepted. When using this source checkout, `python-sdk/builds/` is checked too. Advanced users can override discovery with `CHAT_SDK_LIBRARY` or `library_path`:
34
+
35
+ ```powershell
36
+ $env:CHAT_SDK_LIBRARY = "C:\path\to\chat_client_sdk.dll"
37
+ ```
38
+
39
+ ```sh
40
+ export CHAT_SDK_LIBRARY=/path/to/libchat_client_sdk.so
41
+ ```
42
+
43
+ ## Use
44
+
45
+ ```python
46
+ from chat_sdk import ChatClient
47
+
48
+ with ChatClient(url="ws://127.0.0.1:8080/ws", bearer_token="alice-token") as chat:
49
+ request, accepted = chat.send_message_and_wait(
50
+ "<conversation-uuid>",
51
+ "Hello from Python",
52
+ )
53
+ print("persisted as:", accepted["data"]["message_id"])
54
+ print("correlation key:", request.idempotency_key)
55
+ ```
56
+
57
+ Passing `url` and `bearer_token` connects immediately and starts the event pump for you. `send_message_and_wait()` returns after persistence is acknowledged. `send_event(event_type, data)` sends any version 1 event from the protocol. `receive()` returns a decoded server event dictionary or `None` when no event arrives before its timeout. The background pump is the only native socket reader; concurrent `receive()` and `wait_for_ack()` calls are routed safely. Concurrent sends are serialized through a bounded queue. If the event queue fills, the pump applies backpressure instead of dropping events. `receive()` calls distribute events between concurrent consumers. Retrying a message after a timeout must reuse its `idempotency_key`; duplicate live message events are deduplicated by conversation sequence within a bounded cache of the most recent 8,192 messages per client instance. WSS connections use the Rust SDK's bundled WebPKI root certificates.
58
+
59
+ Create a conversation with `create_conversation(user_ids)` after connecting as one of its participants. It returns the server-generated `conversation_id`; save that ID in your application's database and reuse it when reopening the chat. An async version, `create_conversation_async(user_ids)`, is also available. In production, your backend should call this endpoint after it has decided that the participants are allowed to chat.
60
+
61
+ The synchronous API can also be used from asyncio without blocking the event loop:
62
+
63
+ ```python
64
+ import asyncio
65
+ from chat_sdk import ChatClient
66
+
67
+ async def main():
68
+ async with ChatClient() as chat:
69
+ await chat.aconnect("wss://chat.example.com/ws", "alice-token")
70
+ sent, accepted = await chat.send_message_and_wait_async(
71
+ "<conversation-uuid>", "Hello from asyncio"
72
+ )
73
+ print(sent.idempotency_key, accepted["data"]["sequence"])
74
+ event = await chat.receive_async(timeout_ms=1000)
75
+
76
+ asyncio.run(main())
77
+ ```
78
+
79
+ These async methods run the blocking C ABI and HTTP calls in worker threads; they keep the asyncio loop responsive but do not turn the native C ABI into a nonblocking socket API. Network errors and server slow-consumer disconnects are reported to the caller. Reconnect explicitly with `await chat.aconnect(...)`, then request missed conversation history using the protocol's `history` event and your last confirmed sequence.
80
+
81
+ For a short-lived token refresh, ask your backend for a new token after a connection error, then call `chat.reconnect(url, new_token, {conversation_id: last_saved_sequence})`. The helper reconnects and sends one history request per conversation. Use `await chat.areconnect(...)` from asyncio. Save your sequence only after your app has handled the corresponding message.
82
+
83
+ Conversation setup is repeat-safe with `ensure_conversation(external_key, user_ids)`. Choose a stable key from your app record, such as `tenant-12:support-ticket:4812`, and save the returned ID. Calling it again with the same participants returns the same conversation. Using that key with different participants returns a conflict.
84
+
85
+ ## Attachments
86
+
87
+ The native library handles WebSocket traffic. Attachment bytes use the server's HTTP endpoints and are handled by Python's standard library:
88
+
89
+ ```python
90
+ with ChatClient(url="wss://chat.example.com/ws", bearer_token="alice-token") as chat:
91
+ attachment = chat.upload_attachment(
92
+ "<conversation-uuid>", "photo.jpg", content_type="image/jpeg"
93
+ )
94
+ send, _accepted = chat.send_message_and_wait(
95
+ "<conversation-uuid>",
96
+ "Photo",
97
+ attachments=[attachment["attachment_id"]],
98
+ )
99
+ # For a received message, use its attachment reference's `download` path:
100
+ # chat.download_attachment(reference["download"], "downloads/photo.jpg")
101
+ ```
102
+
103
+ Uploads and downloads follow the server's 10 MiB limit and membership checks. Upload MIME type is inferred from the filename unless supplied explicitly.
104
+
105
+ ## Native runtime requirements
106
+
107
+ - Linux `.so`: GitHub Actions builds target glibc 2.35 on x86-64 and ARM64. The checked-in x86-64 library in this workspace was built on glibc 2.39 and requires glibc 2.39 or newer; use the CI artifact for older distributions.
108
+ - Windows `.dll`: x64 or ARM64 Windows and the matching Microsoft Visual C++ runtime.
109
+ - macOS `.dylib`: x86-64 or ARM64 macOS.
110
+
111
+ See `../crates/client-sdk/include/chat_sdk.h` for the underlying C ABI.
@@ -0,0 +1,5 @@
1
+ chat_sdk/__init__.py,sha256=y00xPjNPKreVr6ePm-b0fD19BGBglh6xu3ir8kXvOV4,34233
2
+ chat_client_sdk-0.1.0.dist-info/METADATA,sha256=gVSsmDP9gASHPvoICG9-xGU5Xj34_i--3WMqRELNO6E,6198
3
+ chat_client_sdk-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
4
+ chat_client_sdk-0.1.0.dist-info/top_level.txt,sha256=MR6HAUyRz5eYDeH1flvaCdr-6Y2PZUuX6mTHPOP22WQ,9
5
+ chat_client_sdk-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ chat_sdk
chat_sdk/__init__.py ADDED
@@ -0,0 +1,841 @@
1
+ """Python wrapper for the Rust chat client's version 1 C ABI."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import ctypes
7
+ import json
8
+ import mimetypes
9
+ import os
10
+ import platform
11
+ import queue
12
+ import threading
13
+ import time
14
+ import urllib.error
15
+ import urllib.parse
16
+ import urllib.request
17
+ import uuid
18
+ from collections import OrderedDict, deque
19
+ from dataclasses import dataclass
20
+ from pathlib import Path
21
+ from typing import Any, Deque, Mapping, Optional, Union
22
+
23
+ __all__ = ["ChatClient", "ChatSDKError", "MessageSend"]
24
+
25
+ _ABI_VERSION = 1
26
+ _MAX_EVENT_BYTES = 16 * 1024
27
+ _DEFAULT_RECEIVE_BUFFER = 1024 * 1024
28
+ _MAX_RECEIVE_BUFFER = 16 * 1024 * 1024
29
+ _MAX_UPLOAD_BYTES = 10 * 1024 * 1024
30
+ _MAX_QUEUED_COMMANDS = 256
31
+ _MAX_QUEUED_EVENTS = 4096
32
+ _MAX_CACHED_ACKS = 2048
33
+ _MAX_SEEN_MESSAGES = 8192
34
+ _COMMAND_ENQUEUE_TIMEOUT = 5.0
35
+ _COMMAND_SEND_TIMEOUT = 15.0
36
+
37
+
38
+ class ChatSDKError(RuntimeError):
39
+ """An error returned by the native client or attachment HTTP API."""
40
+
41
+ def __init__(self, message: str, code: Optional[int] = None) -> None:
42
+ super().__init__(message)
43
+ self.code = code
44
+
45
+
46
+ @dataclass(frozen=True)
47
+ class MessageSend:
48
+ """Identifiers for a sent message request and its idempotency key."""
49
+
50
+ request_id: str
51
+ idempotency_key: str
52
+
53
+
54
+ @dataclass
55
+ class _PendingWaiter:
56
+ predicate: Any
57
+ ready: threading.Event
58
+ result: Optional[dict[str, Any]] = None
59
+ error: Optional[BaseException] = None
60
+
61
+
62
+ def _native_architecture() -> str:
63
+ machine = platform.machine().lower()
64
+ architectures = {
65
+ "amd64": "x86_64",
66
+ "x86_64": "x86_64",
67
+ "arm64": "aarch64",
68
+ "aarch64": "aarch64",
69
+ }
70
+ architecture = architectures.get(machine)
71
+ if architecture is None:
72
+ raise ChatSDKError("native SDK builds are currently available for x86_64 and ARM64")
73
+ return architecture
74
+
75
+
76
+ def _native_filename() -> str:
77
+ system = platform.system()
78
+ architecture = _native_architecture()
79
+ if system == "Windows":
80
+ return "chat_client_sdk.dll"
81
+ if system == "Linux":
82
+ return "libchat_client_sdk.so"
83
+ if system == "Darwin":
84
+ return "libchat_client_sdk.dylib"
85
+ raise ChatSDKError("the native SDK currently supports Windows, Linux, and macOS")
86
+
87
+
88
+ def _library_candidates() -> list[Path]:
89
+ filename = _native_filename()
90
+ package_dir = Path(__file__).resolve().parent
91
+ sdk_dir = Path(__file__).resolve().parents[2]
92
+ system_dir = "{}-{}".format(platform.system().lower(), _native_architecture())
93
+ filename = _native_filename()
94
+ candidates = [
95
+ Path.cwd() / "builds" / system_dir / filename,
96
+ Path.cwd() / "builds" / filename,
97
+ package_dir / "builds" / system_dir / filename,
98
+ package_dir / "builds" / filename,
99
+ sdk_dir / "builds" / system_dir / filename,
100
+ sdk_dir / "builds" / filename,
101
+ ]
102
+ return candidates
103
+
104
+
105
+ def _load_library(library_path: Optional[Union[str, os.PathLike[str]]]) -> ctypes.CDLL:
106
+ configured_path = library_path or os.environ.get("CHAT_SDK_LIBRARY")
107
+ if configured_path:
108
+ path = Path(configured_path).expanduser()
109
+ if not path.is_file():
110
+ raise ChatSDKError("native library does not exist: {}".format(path))
111
+ try:
112
+ return ctypes.CDLL(str(path.resolve()))
113
+ except OSError as exc:
114
+ raise ChatSDKError("could not load native library {}: {}".format(path, exc)) from exc
115
+
116
+ candidates = _library_candidates()
117
+ for path in candidates:
118
+ if path.is_file():
119
+ try:
120
+ return ctypes.CDLL(str(path))
121
+ except OSError as exc:
122
+ raise ChatSDKError("could not load native library {}: {}".format(path, exc)) from exc
123
+
124
+ checked = "\n".join(" - {}".format(path) for path in candidates)
125
+ raise ChatSDKError(
126
+ "native chat SDK library not found. Download the matching platform build "
127
+ "and place it in ./builds/ ({}). You can also set CHAT_SDK_LIBRARY or "
128
+ "pass library_path. Checked:\n{}".format(_native_filename(), checked)
129
+ )
130
+
131
+
132
+ class ChatClient:
133
+ """WebSocket client backed by ``chat-client-sdk`` with a background event pump.
134
+
135
+ The SDK automatically selects the native library for the current operating
136
+ system and architecture from ``./builds/``. ``library_path`` and
137
+ ``CHAT_SDK_LIBRARY`` can override discovery. ``url`` and ``bearer_token``
138
+ can be provided to connect immediately; native operations are serialized
139
+ by the event pump.
140
+ """
141
+
142
+ def __init__(
143
+ self,
144
+ library_path: Optional[Union[str, os.PathLike[str]]] = None,
145
+ *,
146
+ url: Optional[str] = None,
147
+ bearer_token: Optional[str] = None,
148
+ receive_buffer_size: int = _DEFAULT_RECEIVE_BUFFER,
149
+ ) -> None:
150
+ if not 2 <= receive_buffer_size <= _MAX_RECEIVE_BUFFER:
151
+ raise ValueError(
152
+ "receive_buffer_size must be between 2 and {} bytes".format(
153
+ _MAX_RECEIVE_BUFFER
154
+ )
155
+ )
156
+ self._receive_buffer_size = receive_buffer_size
157
+ self._library = _load_library(library_path)
158
+ self._bind_functions()
159
+ abi = self._library.chat_sdk_abi_version()
160
+ if abi != _ABI_VERSION:
161
+ raise ChatSDKError(
162
+ "native ABI version {} is incompatible with Python SDK ABI {}".format(
163
+ abi, _ABI_VERSION
164
+ )
165
+ )
166
+ self._handle = self._library.chat_client_create()
167
+ if not self._handle:
168
+ raise ChatSDKError("native SDK could not create a client handle")
169
+ self._token: Optional[str] = None
170
+ self._http_base: Optional[str] = None
171
+ self._commands: Optional[queue.Queue[dict[str, Any]]] = None
172
+ self._event_condition = threading.Condition()
173
+ self._incoming: Deque[dict[str, Any]] = deque()
174
+ self._ack_events: OrderedDict[str, dict[str, Any]] = OrderedDict()
175
+ self._seen_messages: OrderedDict[tuple[str, int], None] = OrderedDict()
176
+ self._waiters: list[_PendingWaiter] = []
177
+ self._worker: Optional[threading.Thread] = None
178
+ self._ready: Optional[threading.Event] = None
179
+ self._worker_error: Optional[BaseException] = None
180
+ self._stop = threading.Event()
181
+ if (url is None) != (bearer_token is None):
182
+ self.close()
183
+ raise ValueError("provide both url and bearer_token, or neither")
184
+ if url is not None and bearer_token is not None:
185
+ self._start_background(url, bearer_token)
186
+
187
+ def _bind_functions(self) -> None:
188
+ lib = self._library
189
+ lib.chat_sdk_abi_version.argtypes = []
190
+ lib.chat_sdk_abi_version.restype = ctypes.c_uint32
191
+ lib.chat_client_create.argtypes = []
192
+ lib.chat_client_create.restype = ctypes.c_void_p
193
+ lib.chat_client_connect.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_char_p]
194
+ lib.chat_client_connect.restype = ctypes.c_int32
195
+ lib.chat_client_send.argtypes = [ctypes.c_void_p, ctypes.c_char_p]
196
+ lib.chat_client_send.restype = ctypes.c_int32
197
+ lib.chat_client_receive.argtypes = [
198
+ ctypes.c_void_p,
199
+ ctypes.POINTER(ctypes.c_char),
200
+ ctypes.c_size_t,
201
+ ctypes.c_uint32,
202
+ ]
203
+ lib.chat_client_receive.restype = ctypes.c_int32
204
+ lib.chat_client_destroy.argtypes = [ctypes.c_void_p]
205
+ lib.chat_client_destroy.restype = None
206
+ lib.chat_sdk_error_string.argtypes = [
207
+ ctypes.c_int32,
208
+ ctypes.POINTER(ctypes.c_char),
209
+ ctypes.c_size_t,
210
+ ]
211
+ lib.chat_sdk_error_string.restype = ctypes.c_int32
212
+
213
+ def _ensure_open(self) -> None:
214
+ if not self._handle:
215
+ raise ChatSDKError("client is closed")
216
+
217
+ def _error(self, code: int) -> ChatSDKError:
218
+ buffer = ctypes.create_string_buffer(256)
219
+ self._library.chat_sdk_error_string(code, buffer, len(buffer))
220
+ message = buffer.value.decode("utf-8", errors="replace") or "native SDK error"
221
+ return ChatSDKError(message, code)
222
+
223
+ @staticmethod
224
+ def _cstring(value: str, label: str) -> bytes:
225
+ if not isinstance(value, str):
226
+ raise TypeError("{} must be str".format(label))
227
+ if "\x00" in value:
228
+ raise ValueError("{} must not contain a NUL character".format(label))
229
+ return value.encode("utf-8")
230
+
231
+ def connect(self, url: str, bearer_token: str) -> "ChatClient":
232
+ """Connect to a ``ws://`` or ``wss://`` endpoint."""
233
+ if self._worker is not None and self._worker.is_alive():
234
+ raise ChatSDKError("client is already connected")
235
+ if self._worker is not None:
236
+ self._worker.join()
237
+ self._worker = None
238
+ self._worker_error = None
239
+ if not self._handle:
240
+ self._handle = self._library.chat_client_create()
241
+ if not self._handle:
242
+ raise ChatSDKError("native SDK could not create a client handle")
243
+ self._start_background(url, bearer_token)
244
+ return self
245
+
246
+ async def aconnect(self, url: str, bearer_token: str) -> "ChatClient":
247
+ """Connect without blocking an asyncio event loop."""
248
+ return await asyncio.to_thread(self.connect, url, bearer_token)
249
+
250
+ def reconnect(
251
+ self,
252
+ url: str,
253
+ bearer_token: str,
254
+ last_sequences: Optional[Mapping[str, int]] = None,
255
+ ) -> list[str]:
256
+ """Reconnect with a fresh token and request missed history for known chats.
257
+
258
+ The mapping contains conversation IDs and the last sequence your app has
259
+ safely saved for each conversation. Call this after a connection error.
260
+ """
261
+ self.close()
262
+ self.connect(url, bearer_token)
263
+ requests = []
264
+ for conversation_id, sequence in (last_sequences or {}).items():
265
+ requests.append(
266
+ self.send_event(
267
+ "history",
268
+ {
269
+ "conversation_id": str(uuid.UUID(conversation_id)),
270
+ "after_sequence": int(sequence),
271
+ "limit": 200,
272
+ },
273
+ )
274
+ )
275
+ return requests
276
+
277
+ async def areconnect(
278
+ self,
279
+ url: str,
280
+ bearer_token: str,
281
+ last_sequences: Optional[Mapping[str, int]] = None,
282
+ ) -> list[str]:
283
+ """Asyncio-friendly reconnect and history recovery helper."""
284
+ return await asyncio.to_thread(
285
+ self.reconnect, url, bearer_token, last_sequences
286
+ )
287
+
288
+ def _connect_native(self, url: str, bearer_token: str) -> "ChatClient":
289
+ self._ensure_open()
290
+ url_bytes = self._cstring(url, "url")
291
+ token_bytes = self._cstring(bearer_token, "bearer_token")
292
+ parsed = urllib.parse.urlsplit(url)
293
+ if parsed.scheme not in ("ws", "wss") or not parsed.netloc:
294
+ raise ValueError("url must be an absolute ws:// or wss:// URL")
295
+ code = self._library.chat_client_connect(self._handle, url_bytes, token_bytes)
296
+ if code != 0:
297
+ raise self._error(code)
298
+ http_scheme = "https" if parsed.scheme == "wss" else "http"
299
+ self._http_base = "{}://{}".format(http_scheme, parsed.netloc)
300
+ self._token = bearer_token
301
+ return self
302
+
303
+ def _start_background(self, url: str, bearer_token: str) -> None:
304
+ self._commands = queue.Queue(maxsize=_MAX_QUEUED_COMMANDS)
305
+ self._ready = threading.Event()
306
+ self._worker_error = None
307
+ self._stop = threading.Event()
308
+ self._worker = threading.Thread(
309
+ target=self._background_main,
310
+ args=(url, bearer_token),
311
+ name="chat-sdk-events",
312
+ daemon=True,
313
+ )
314
+ self._worker.start()
315
+ self._ready.wait()
316
+ if self._worker_error is not None:
317
+ error = self._worker_error
318
+ self.close()
319
+ if isinstance(error, Exception):
320
+ raise error
321
+ raise ChatSDKError("native connection failed")
322
+
323
+ def _background_main(self, url: str, bearer_token: str) -> None:
324
+ assert self._ready is not None
325
+ assert self._commands is not None
326
+ try:
327
+ self._connect_native(url, bearer_token)
328
+ self._ready.set()
329
+ while not self._stop.is_set():
330
+ try:
331
+ command = self._commands.get(timeout=0.01)
332
+ except queue.Empty:
333
+ command = None
334
+ if command is not None:
335
+ try:
336
+ code = self._library.chat_client_send(self._handle, command["raw"])
337
+ if code != 0:
338
+ command["error"] = self._error(code)
339
+ except BaseException as exc:
340
+ command["error"] = exc
341
+ finally:
342
+ command["done"].set()
343
+ event = self._receive_raw(10)
344
+ if event is not None:
345
+ self._route_event(event)
346
+ except BaseException as exc:
347
+ self._worker_error = exc
348
+ self._ready.set()
349
+ finally:
350
+ while True:
351
+ try:
352
+ command = self._commands.get_nowait()
353
+ except queue.Empty:
354
+ break
355
+ command["error"] = ChatSDKError("client event worker has stopped")
356
+ command["done"].set()
357
+ if self._handle:
358
+ self._library.chat_client_destroy(self._handle)
359
+ self._handle = None
360
+ stopped = ChatSDKError("background client has stopped")
361
+ with self._event_condition:
362
+ for waiter in self._waiters:
363
+ waiter.error = self._worker_error or stopped
364
+ waiter.ready.set()
365
+ self._waiters.clear()
366
+ self._event_condition.notify_all()
367
+
368
+ def _route_event(self, event: dict[str, Any]) -> None:
369
+ with self._event_condition:
370
+ event_type = event.get("type")
371
+ data = event.get("data") or {}
372
+ if event_type == "message":
373
+ message = data.get("message") or {}
374
+ conversation = message.get("conversation_id")
375
+ sequence = message.get("sequence")
376
+ if conversation is not None and isinstance(sequence, int):
377
+ key = (conversation, sequence)
378
+ if key in self._seen_messages:
379
+ return
380
+ self._seen_messages[key] = None
381
+ while len(self._seen_messages) > _MAX_SEEN_MESSAGES:
382
+ self._seen_messages.popitem(last=False)
383
+ request_id = data.get("request_id")
384
+ if event_type in ("accepted", "error") and request_id:
385
+ self._ack_events[request_id] = event
386
+ self._ack_events.move_to_end(request_id)
387
+ while len(self._ack_events) > _MAX_CACHED_ACKS:
388
+ self._ack_events.popitem(last=False)
389
+ for waiter in tuple(self._waiters):
390
+ try:
391
+ matches = waiter.predicate(event)
392
+ except BaseException as exc:
393
+ self._waiters.remove(waiter)
394
+ waiter.error = exc
395
+ waiter.ready.set()
396
+ continue
397
+ if matches:
398
+ self._waiters.remove(waiter)
399
+ waiter.result = event
400
+ waiter.ready.set()
401
+ self._event_condition.notify_all()
402
+ return
403
+ while len(self._incoming) >= _MAX_QUEUED_EVENTS and not self._stop.is_set():
404
+ # Backpressure the socket reader instead of dropping events or growing
405
+ # memory without a bound. Receiving an event wakes this producer.
406
+ self._event_condition.wait(timeout=0.1)
407
+ if not self._stop.is_set():
408
+ self._incoming.append(event)
409
+ self._event_condition.notify_all()
410
+
411
+ def send_event(
412
+ self,
413
+ event_type: str,
414
+ data: Mapping[str, Any],
415
+ *,
416
+ request_id: Optional[str] = None,
417
+ ) -> str:
418
+ """Send one version 1 protocol event and return its request ID."""
419
+ self._ensure_open()
420
+ if not isinstance(data, Mapping):
421
+ raise TypeError("data must be a mapping")
422
+ rid = str(uuid.UUID(request_id)) if request_id is not None else str(uuid.uuid4())
423
+ envelope = {
424
+ "version": _ABI_VERSION,
425
+ "request_id": rid,
426
+ "event": {"type": event_type, "data": dict(data)},
427
+ }
428
+ encoded = json.dumps(envelope, ensure_ascii=False, separators=(",", ":"), allow_nan=False)
429
+ raw = encoded.encode("utf-8")
430
+ if len(raw) > _MAX_EVENT_BYTES:
431
+ raise ValueError("encoded event exceeds the 16 KiB protocol limit")
432
+ if b"\x00" in raw:
433
+ raise ValueError("encoded event must not contain a NUL byte")
434
+ worker = self._worker
435
+ commands = self._commands
436
+ if worker is None or not worker.is_alive() or commands is None:
437
+ detail = ": {}".format(self._worker_error) if self._worker_error else ""
438
+ raise ChatSDKError("client is not connected{}".format(detail))
439
+ done = threading.Event()
440
+ command: dict[str, Any] = {"raw": raw, "done": done}
441
+ try:
442
+ commands.put(command, timeout=_COMMAND_ENQUEUE_TIMEOUT)
443
+ except queue.Full as exc:
444
+ raise TimeoutError("client send queue remained full") from exc
445
+ if not done.wait(_COMMAND_SEND_TIMEOUT):
446
+ raise TimeoutError(
447
+ "timed out waiting for the native client send; retry with the same idempotency key"
448
+ )
449
+ if "error" in command:
450
+ raise command["error"]
451
+ return rid
452
+
453
+ def send_message(
454
+ self,
455
+ conversation_id: str,
456
+ body: str,
457
+ *,
458
+ idempotency_key: Optional[str] = None,
459
+ reply_to: Optional[str] = None,
460
+ attachments: Optional[list[str]] = None,
461
+ ) -> MessageSend:
462
+ """Send a chat message; attachment IDs come from ``upload_attachment``."""
463
+ key = str(uuid.UUID(idempotency_key)) if idempotency_key else str(uuid.uuid4())
464
+ data: dict[str, Any] = {
465
+ "conversation_id": str(uuid.UUID(conversation_id)),
466
+ "idempotency_key": key,
467
+ "body": body,
468
+ "reply_to": str(uuid.UUID(reply_to)) if reply_to else None,
469
+ "attachments": [str(uuid.UUID(item)) for item in (attachments or [])],
470
+ }
471
+ request_id = self.send_event("send_message", data)
472
+ return MessageSend(request_id=request_id, idempotency_key=key)
473
+
474
+ def send_message_and_wait(
475
+ self,
476
+ conversation_id: str,
477
+ body: str,
478
+ *,
479
+ timeout: float = 10.0,
480
+ idempotency_key: Optional[str] = None,
481
+ reply_to: Optional[str] = None,
482
+ attachments: Optional[list[str]] = None,
483
+ ) -> tuple[MessageSend, dict[str, Any]]:
484
+ """Send a message and wait until the server confirms it was persisted."""
485
+ sent = self.send_message(
486
+ conversation_id,
487
+ body,
488
+ idempotency_key=idempotency_key,
489
+ reply_to=reply_to,
490
+ attachments=attachments,
491
+ )
492
+ return sent, self.wait_for_ack(sent.request_id, timeout=timeout)
493
+
494
+ def receive(self, timeout_ms: int = 1000) -> Optional[dict[str, Any]]:
495
+ """Receive one event, or return ``None`` on timeout.
496
+
497
+ Concurrent calls are safe: each queued event is delivered to one reader.
498
+ """
499
+ if not isinstance(timeout_ms, int) or not 0 <= timeout_ms <= 0xFFFFFFFF:
500
+ raise ValueError("timeout_ms must be an integer from 0 to 2^32-1")
501
+ deadline = time.monotonic() + timeout_ms / 1000.0
502
+ with self._event_condition:
503
+ while not self._incoming:
504
+ if self._worker_error is not None:
505
+ raise ChatSDKError("background client failed: {}".format(self._worker_error))
506
+ worker = self._worker
507
+ if worker is None or not worker.is_alive():
508
+ raise ChatSDKError("client is not connected")
509
+ remaining = deadline - time.monotonic()
510
+ if remaining <= 0:
511
+ return None
512
+ self._event_condition.wait(remaining)
513
+ event = self._incoming.popleft()
514
+ self._event_condition.notify_all()
515
+ return event
516
+
517
+ def _receive_raw(self, timeout_ms: int) -> Optional[dict[str, Any]]:
518
+ self._ensure_open()
519
+ buffer = ctypes.create_string_buffer(self._receive_buffer_size)
520
+ result = self._library.chat_client_receive(
521
+ self._handle, buffer, self._receive_buffer_size, timeout_ms
522
+ )
523
+ if result < 0:
524
+ raise self._error(result)
525
+ if result == 0:
526
+ return None
527
+ if result >= self._receive_buffer_size - 1:
528
+ raise ChatSDKError(
529
+ "received event may exceed the configured buffer; increase receive_buffer_size"
530
+ )
531
+ try:
532
+ return json.loads(buffer.raw[:result].decode("utf-8"))
533
+ except (UnicodeDecodeError, json.JSONDecodeError) as exc:
534
+ raise ChatSDKError("native SDK returned an invalid or truncated JSON event") from exc
535
+
536
+ def wait_for(self, predicate: Any, *, timeout: float = 10.0) -> dict[str, Any]:
537
+ """Wait for a matching event without competing with other event readers."""
538
+ if timeout < 0:
539
+ raise ValueError("timeout must be non-negative")
540
+ deadline = time.monotonic() + timeout
541
+ with self._event_condition:
542
+ for request_id, event in tuple(self._ack_events.items()):
543
+ if predicate(event):
544
+ self._ack_events.pop(request_id, None)
545
+ try:
546
+ self._incoming.remove(event)
547
+ except ValueError:
548
+ pass
549
+ return event
550
+ for index, event in enumerate(self._incoming):
551
+ if predicate(event):
552
+ del self._incoming[index]
553
+ self._event_condition.notify_all()
554
+ return event
555
+ worker = self._worker
556
+ if worker is None or not worker.is_alive():
557
+ if self._worker_error is not None:
558
+ raise ChatSDKError("background client failed: {}".format(self._worker_error))
559
+ raise ChatSDKError("client is not connected")
560
+ waiter = _PendingWaiter(predicate=predicate, ready=threading.Event())
561
+ self._waiters.append(waiter)
562
+ while not waiter.ready.is_set():
563
+ remaining = deadline - time.monotonic()
564
+ if remaining <= 0:
565
+ if waiter in self._waiters:
566
+ self._waiters.remove(waiter)
567
+ raise TimeoutError("timed out waiting for a chat event")
568
+ self._event_condition.wait(remaining)
569
+ if waiter.error is not None:
570
+ raise waiter.error
571
+ assert waiter.result is not None
572
+ event = waiter.result
573
+ data = event.get("data") or {}
574
+ request_id = data.get("request_id")
575
+ if request_id:
576
+ self._ack_events.pop(request_id, None)
577
+ return event
578
+
579
+ def wait_for_ack(self, request_id: str, *, timeout: float = 10.0) -> dict[str, Any]:
580
+ """Wait for the persisted-message acknowledgement or raise on server error."""
581
+ rid = str(uuid.UUID(request_id))
582
+
583
+ def matches(event: dict[str, Any]) -> bool:
584
+ data = event.get("data") or {}
585
+ return (
586
+ event.get("type") == "accepted" and data.get("request_id") == rid
587
+ ) or (event.get("type") == "error" and data.get("request_id") == rid)
588
+
589
+ event = self.wait_for(matches, timeout=timeout)
590
+ if event.get("type") == "error":
591
+ data = event.get("data") or {}
592
+ raise ChatSDKError(data.get("message", data.get("code", "request failed")))
593
+ return event
594
+
595
+ def upload_attachment(
596
+ self,
597
+ conversation_id: str,
598
+ file_path: Union[str, os.PathLike[str]],
599
+ *,
600
+ content_type: Optional[str] = None,
601
+ ) -> dict[str, Any]:
602
+ """Upload a file using the server HTTP API and return its attachment metadata."""
603
+ self._require_http_auth()
604
+ path = Path(file_path)
605
+ payload = path.read_bytes()
606
+ if len(payload) > _MAX_UPLOAD_BYTES:
607
+ raise ValueError("attachment exceeds the server's 10 MiB upload limit")
608
+ media_type = content_type or mimetypes.guess_type(path.name)[0] or "application/octet-stream"
609
+ query = urllib.parse.urlencode({"name": path.name, "content_type": media_type})
610
+ conv = str(uuid.UUID(conversation_id))
611
+ url = "{}/conversations/{}/upload?{}".format(self._http_base, conv, query)
612
+ request = urllib.request.Request(
613
+ url,
614
+ data=payload,
615
+ method="POST",
616
+ headers={
617
+ "Authorization": "Bearer {}".format(self._token),
618
+ "Content-Type": media_type,
619
+ },
620
+ )
621
+ try:
622
+ with urllib.request.urlopen(request, timeout=30) as response:
623
+ return json.loads(response.read().decode("utf-8"))
624
+ except (urllib.error.URLError, urllib.error.HTTPError) as exc:
625
+ raise ChatSDKError("attachment upload failed: {}".format(exc)) from exc
626
+
627
+ def download_attachment(self, download_url: str, destination: Union[str, os.PathLike[str]]) -> Path:
628
+ """Download an attachment reference from a server message to ``destination``."""
629
+ self._require_http_auth()
630
+ target = urllib.parse.urljoin(self._http_base + "/", download_url)
631
+ base_parts = urllib.parse.urlsplit(self._http_base)
632
+ target_parts = urllib.parse.urlsplit(target)
633
+ if (target_parts.scheme, target_parts.netloc) != (base_parts.scheme, base_parts.netloc):
634
+ raise ValueError("attachment URL must belong to the connected chat server")
635
+ request = urllib.request.Request(
636
+ target, headers={"Authorization": "Bearer {}".format(self._token)}
637
+ )
638
+ try:
639
+ with urllib.request.urlopen(request, timeout=30) as response:
640
+ payload = response.read(_MAX_UPLOAD_BYTES + 1)
641
+ if len(payload) > _MAX_UPLOAD_BYTES:
642
+ raise ChatSDKError("downloaded attachment exceeds the 10 MiB server limit")
643
+ path = Path(destination)
644
+ path.parent.mkdir(parents=True, exist_ok=True)
645
+ path.write_bytes(payload)
646
+ return path
647
+ except (urllib.error.URLError, urllib.error.HTTPError) as exc:
648
+ raise ChatSDKError("attachment download failed: {}".format(exc)) from exc
649
+
650
+ async def send_event_async(
651
+ self,
652
+ event_type: str,
653
+ data: Mapping[str, Any],
654
+ *,
655
+ request_id: Optional[str] = None,
656
+ ) -> str:
657
+ """Asyncio-friendly form of ``send_event``."""
658
+ return await asyncio.to_thread(
659
+ self.send_event, event_type, data, request_id=request_id
660
+ )
661
+
662
+ async def send_message_async(
663
+ self,
664
+ conversation_id: str,
665
+ body: str,
666
+ *,
667
+ idempotency_key: Optional[str] = None,
668
+ reply_to: Optional[str] = None,
669
+ attachments: Optional[list[str]] = None,
670
+ ) -> MessageSend:
671
+ """Asyncio-friendly form of ``send_message``."""
672
+ return await asyncio.to_thread(
673
+ self.send_message,
674
+ conversation_id,
675
+ body,
676
+ idempotency_key=idempotency_key,
677
+ reply_to=reply_to,
678
+ attachments=attachments,
679
+ )
680
+
681
+ async def send_message_and_wait_async(
682
+ self,
683
+ conversation_id: str,
684
+ body: str,
685
+ *,
686
+ timeout: float = 10.0,
687
+ idempotency_key: Optional[str] = None,
688
+ reply_to: Optional[str] = None,
689
+ attachments: Optional[list[str]] = None,
690
+ ) -> tuple[MessageSend, dict[str, Any]]:
691
+ """Asyncio-friendly form that waits for the durable server acknowledgement."""
692
+ return await asyncio.to_thread(
693
+ self.send_message_and_wait,
694
+ conversation_id,
695
+ body,
696
+ timeout=timeout,
697
+ idempotency_key=idempotency_key,
698
+ reply_to=reply_to,
699
+ attachments=attachments,
700
+ )
701
+
702
+ async def receive_async(self, timeout_ms: int = 1000) -> Optional[dict[str, Any]]:
703
+ """Asyncio-friendly form of ``receive``."""
704
+ return await asyncio.to_thread(self.receive, timeout_ms)
705
+
706
+ async def upload_attachment_async(
707
+ self,
708
+ conversation_id: str,
709
+ file_path: Union[str, os.PathLike[str]],
710
+ *,
711
+ content_type: Optional[str] = None,
712
+ ) -> dict[str, Any]:
713
+ """Asyncio-friendly form of ``upload_attachment``."""
714
+ return await asyncio.to_thread(
715
+ self.upload_attachment,
716
+ conversation_id,
717
+ file_path,
718
+ content_type=content_type,
719
+ )
720
+
721
+ async def download_attachment_async(
722
+ self,
723
+ download_url: str,
724
+ destination: Union[str, os.PathLike[str]],
725
+ ) -> Path:
726
+ """Asyncio-friendly form of ``download_attachment``."""
727
+ return await asyncio.to_thread(
728
+ self.download_attachment, download_url, destination
729
+ )
730
+
731
+ async def create_conversation_async(self, user_ids: list[str]) -> dict[str, Any]:
732
+ """Create a conversation through the server's authenticated HTTP API."""
733
+ return await asyncio.to_thread(self.create_conversation, user_ids)
734
+
735
+ async def ensure_conversation_async(
736
+ self, external_key: str, user_ids: list[str]
737
+ ) -> dict[str, Any]:
738
+ """Reuse a conversation for a stable application key, or create it."""
739
+ return await asyncio.to_thread(
740
+ self.ensure_conversation, external_key, user_ids
741
+ )
742
+
743
+ async def aclose(self) -> None:
744
+ """Close the client without blocking the current asyncio event loop."""
745
+ await asyncio.to_thread(self.close)
746
+
747
+ def _require_http_auth(self) -> None:
748
+ self._ensure_open()
749
+ if not self._http_base or not self._token:
750
+ raise ChatSDKError("connect the client before using authenticated HTTP methods")
751
+
752
+ def create_conversation(self, user_ids: list[str]) -> dict[str, Any]:
753
+ """Create a conversation and return its server-generated conversation ID."""
754
+ self._require_http_auth()
755
+ if not isinstance(user_ids, list) or any(
756
+ not isinstance(user_id, str) or not user_id.strip() for user_id in user_ids
757
+ ):
758
+ raise ValueError("user_ids must be a list of non-empty strings")
759
+ payload = json.dumps(user_ids, separators=(",", ":")).encode("utf-8")
760
+ request = urllib.request.Request(
761
+ "{}/conversations".format(self._http_base),
762
+ data=payload,
763
+ method="POST",
764
+ headers={
765
+ "Authorization": "Bearer {}".format(self._token),
766
+ "Content-Type": "application/json",
767
+ },
768
+ )
769
+ try:
770
+ with urllib.request.urlopen(request, timeout=30) as response:
771
+ return json.loads(response.read().decode("utf-8"))
772
+ except (urllib.error.URLError, urllib.error.HTTPError) as exc:
773
+ raise ChatSDKError("conversation creation failed: {}".format(exc)) from exc
774
+
775
+ def ensure_conversation(
776
+ self, external_key: str, user_ids: list[str]
777
+ ) -> dict[str, Any]:
778
+ """Return the same conversation for this user's stable application key."""
779
+ self._require_http_auth()
780
+ if not isinstance(external_key, str) or not external_key.strip():
781
+ raise ValueError("external_key must be a non-empty string")
782
+ if not isinstance(user_ids, list) or any(
783
+ not isinstance(user_id, str) or not user_id.strip() for user_id in user_ids
784
+ ):
785
+ raise ValueError("user_ids must be a list of non-empty strings")
786
+ payload = json.dumps(
787
+ {"external_key": external_key, "user_ids": user_ids},
788
+ separators=(",", ":"),
789
+ ).encode("utf-8")
790
+ request = urllib.request.Request(
791
+ "{}/conversations/ensure".format(self._http_base),
792
+ data=payload,
793
+ method="POST",
794
+ headers={
795
+ "Authorization": "Bearer {}".format(self._token),
796
+ "Content-Type": "application/json",
797
+ },
798
+ )
799
+ try:
800
+ with urllib.request.urlopen(request, timeout=30) as response:
801
+ return json.loads(response.read().decode("utf-8"))
802
+ except urllib.error.HTTPError as exc:
803
+ if exc.code == 409:
804
+ raise ChatSDKError(
805
+ "conversation key is already linked to different participants",
806
+ exc.code,
807
+ ) from exc
808
+ raise ChatSDKError("conversation setup failed: {}".format(exc)) from exc
809
+ except urllib.error.URLError as exc:
810
+ raise ChatSDKError("conversation setup failed: {}".format(exc)) from exc
811
+
812
+ def close(self) -> None:
813
+ """Close the native handle. Safe to call more than once."""
814
+ if self._worker is not None:
815
+ self._stop.set()
816
+ if threading.current_thread() is not self._worker:
817
+ self._worker.join()
818
+ self._worker = None
819
+ elif self._handle:
820
+ self._library.chat_client_destroy(self._handle)
821
+ self._handle = None
822
+
823
+ def __enter__(self) -> "ChatClient":
824
+ self._ensure_open()
825
+ return self
826
+
827
+ def __exit__(self, exc_type: Any, exc: Any, traceback: Any) -> None:
828
+ self.close()
829
+
830
+ async def __aenter__(self) -> "ChatClient":
831
+ self._ensure_open()
832
+ return self
833
+
834
+ async def __aexit__(self, exc_type: Any, exc: Any, traceback: Any) -> None:
835
+ await self.aclose()
836
+
837
+ def __del__(self) -> None:
838
+ try:
839
+ self.close()
840
+ except Exception:
841
+ pass