filament-api 0.8.2__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.
Files changed (75) hide show
  1. filament/__init__.py +79 -0
  2. filament/_client.py +2446 -0
  3. filament/_compression.py +229 -0
  4. filament/_condition_builder.py +517 -0
  5. filament/_exceptions.py +77 -0
  6. filament/_file_upload.py +156 -0
  7. filament/_serialization.py +831 -0
  8. filament/_specified_properties.py +79 -0
  9. filament/_wire_formats.py +113 -0
  10. filament/py.typed +0 -0
  11. filament/types/__init__.py +3 -0
  12. filament/types/conditions.py +668 -0
  13. filament/types/generated/__init__.py +8 -0
  14. filament/types/generated/api.py +218 -0
  15. filament/types/generated/base/__init__.py +2 -0
  16. filament/types/generated/base/base.py +90 -0
  17. filament/types/generated/connections/__init__.py +14 -0
  18. filament/types/generated/connections/api_key_service.py +15 -0
  19. filament/types/generated/connections/cast_service.py +60 -0
  20. filament/types/generated/connections/event_service.py +60 -0
  21. filament/types/generated/connections/generic.py +131 -0
  22. filament/types/generated/connections/note_service.py +22 -0
  23. filament/types/generated/connections/schedule_service.py +40 -0
  24. filament/types/generated/connections/scope_item_service.py +125 -0
  25. filament/types/generated/connections/scope_service.py +22 -0
  26. filament/types/generated/connections/scope_task_type_service.py +45 -0
  27. filament/types/generated/connections/scope_template_item_service.py +19 -0
  28. filament/types/generated/connections/specialty_service.py +15 -0
  29. filament/types/generated/connections/task_service.py +112 -0
  30. filament/types/generated/connections/user_service.py +24 -0
  31. filament/types/generated/entities/__init__.py +35 -0
  32. filament/types/generated/entities/actual_service.py +81 -0
  33. filament/types/generated/entities/api_key_service.py +34 -0
  34. filament/types/generated/entities/availability_service.py +55 -0
  35. filament/types/generated/entities/cast_service.py +28 -0
  36. filament/types/generated/entities/core.py +392 -0
  37. filament/types/generated/entities/currency_service.py +52 -0
  38. filament/types/generated/entities/current_instant_service.py +36 -0
  39. filament/types/generated/entities/event_service.py +108 -0
  40. filament/types/generated/entities/file_settings_service.py +31 -0
  41. filament/types/generated/entities/generic.py +107 -0
  42. filament/types/generated/entities/media_service.py +114 -0
  43. filament/types/generated/entities/note_service.py +60 -0
  44. filament/types/generated/entities/organization_service.py +109 -0
  45. filament/types/generated/entities/permissions_service.py +169 -0
  46. filament/types/generated/entities/review_group_service.py +32 -0
  47. filament/types/generated/entities/schedule_service.py +241 -0
  48. filament/types/generated/entities/schedule_settings_service.py +184 -0
  49. filament/types/generated/entities/scope_category_service.py +31 -0
  50. filament/types/generated/entities/scope_cost_service.py +55 -0
  51. filament/types/generated/entities/scope_group_service.py +76 -0
  52. filament/types/generated/entities/scope_item_service.py +175 -0
  53. filament/types/generated/entities/scope_milestone_service.py +47 -0
  54. filament/types/generated/entities/scope_service.py +70 -0
  55. filament/types/generated/entities/scope_task_type_service.py +99 -0
  56. filament/types/generated/entities/scope_template_item_service.py +44 -0
  57. filament/types/generated/entities/skill_service.py +102 -0
  58. filament/types/generated/entities/skill_type_service.py +30 -0
  59. filament/types/generated/entities/specialty_service.py +23 -0
  60. filament/types/generated/entities/task_service.py +233 -0
  61. filament/types/generated/entities/task_status_service.py +49 -0
  62. filament/types/generated/entities/time_log_service.py +47 -0
  63. filament/types/generated/entities/user_license_service.py +68 -0
  64. filament/types/generated/entities/user_service.py +152 -0
  65. filament/types/generated/entities/user_settings_service.py +37 -0
  66. filament/types/generated/enums.py +1264 -0
  67. filament/types/generated/misc.py +1343 -0
  68. filament/types/generated/shared.py +58 -0
  69. filament/types/options.py +286 -0
  70. filament/user_defined_properties.py +359 -0
  71. filament_api-0.8.2.dist-info/METADATA +290 -0
  72. filament_api-0.8.2.dist-info/RECORD +75 -0
  73. filament_api-0.8.2.dist-info/WHEEL +4 -0
  74. filament_api-0.8.2.dist-info/licenses/LICENSE +21 -0
  75. filament_mypy_plugin.py +242 -0
filament/_client.py ADDED
@@ -0,0 +1,2446 @@
1
+ """Async Filament API client over SignalR."""
2
+ from __future__ import annotations
3
+
4
+ import asyncio
5
+ import base64
6
+ import contextlib
7
+ import functools
8
+ import inspect
9
+ import logging
10
+ import math
11
+ import re
12
+ from collections import deque
13
+ from collections.abc import Awaitable, Callable, Mapping, Sequence
14
+ from dataclasses import replace
15
+ from types import TracebackType
16
+ from typing import Any, Optional, Type, Union
17
+
18
+ import httpx
19
+ from pysignalr.client import SignalRClient
20
+ from pysignalr.exceptions import HubError
21
+ from pysignalr.messages import CompletionMessage, Message
22
+ from uuid_utils import UUID, uuid7
23
+
24
+ from ._exceptions import (
25
+ CompressedPropertyError,
26
+ FilamentAuthenticationError,
27
+ FilamentConnectionError,
28
+ FilamentError,
29
+ ResponseTooLargeError,
30
+ )
31
+ from ._condition_builder import Condition
32
+ from ._file_upload import build_upload_request, compute_checksum
33
+ from ._serialization import from_dict, to_dict
34
+ from .user_defined_properties import (
35
+ UserDefinedProperty,
36
+ build_user_defined_properties,
37
+ hydrate_user_defined_properties,
38
+ )
39
+ from .types.generated.entities.core import FileEntity, UserDefinedPropertyEntity
40
+ from .types.generated.misc import (
41
+ ClientHelloRequest,
42
+ CreateUserDefinedPropertyRequest,
43
+ DataUpdateRejectedNotification,
44
+ EntityPermissions,
45
+ EntityPropertyPermissions,
46
+ EntityServiceDataUpdate,
47
+ FileUploadCompletion,
48
+ FileUploadRequest,
49
+ GetFileUrlsRequest,
50
+ ModifyDataRequest,
51
+ ProcessingStatus,
52
+ ReadConnectedDataRequest,
53
+ ReadDataRequest,
54
+ RequestId,
55
+ ServerCapabilities,
56
+ ServiceDataRead,
57
+ ServiceDataReadConnected,
58
+ ServiceDataUpdate,
59
+ SubscriptionConfig,
60
+ SubscriptionId,
61
+ SuccessOrErrorPublic,
62
+ UpdateUserDefinedPropertyRequest,
63
+ UploadGrant,
64
+ UserDefinedPropertyInfo,
65
+ ValueOrErrorPublic_1,
66
+ WrappedEntity,
67
+ )
68
+ from .types.generated.enums import (
69
+ DataProcessingStatus,
70
+ DataRequestAction,
71
+ ErrorCodes,
72
+ FileChecksumAlgorithm,
73
+ ReadMode,
74
+ SubscriptionMode,
75
+ )
76
+ from .types.generated.shared import FileReference
77
+
78
+ logger = logging.getLogger(__name__)
79
+
80
+ # Type alias for user callbacks — may be sync or async.
81
+ Callback = Union[Callable[..., Any], Callable[..., Awaitable[Any]]]
82
+
83
+ _DEFAULT_SERVER = "https://backend.filament-software.com"
84
+ _DEFAULT_PORT = 443
85
+ _DEFAULT_PATH = "api/v0"
86
+ _DEFAULT_CONNECTION_TIMEOUT = 10.0
87
+ # Matches the websockets-library default that pysignalr uses; pass ``None`` for unlimited.
88
+ _DEFAULT_MAX_SIZE = 2**20 # 1 MiB
89
+ # Backoff, in seconds, before retrying a rejected UDP definition-change ``Subscribe``
90
+ # from a read. Doubles per consecutive rejection up to the maximum.
91
+ _UDP_SUBSCRIBE_RETRY_INITIAL = 5.0
92
+ _UDP_SUBSCRIBE_RETRY_MAX = 300.0
93
+
94
+ # Parses the byte counts out of a ``ResponseTooLarge`` error message. The backend
95
+ # formats it as ``"Response would be {actual:N0} bytes; client limit is {limit:N0}
96
+ # bytes."`` where ``:N0`` inserts thousands separators (e.g. ``1,234,567``), so the
97
+ # captured groups may contain commas which are stripped before ``int`` conversion.
98
+ _RESPONSE_TOO_LARGE_RE = re.compile(
99
+ r"would be ([\d,]+) bytes.*?limit is ([\d,]+) bytes"
100
+ )
101
+
102
+
103
+ class FilamentClient:
104
+ """Async client for the Filament SignalR API.
105
+
106
+ Usage::
107
+
108
+ async with FilamentClient(
109
+ organization_id="org-id", api_key_name="my-key", api_key="secret",
110
+ ) as f:
111
+ result = await f.read_data(request)
112
+ """
113
+
114
+ def __init__(
115
+ self,
116
+ organization_id: str,
117
+ api_key_name: str,
118
+ api_key: str,
119
+ server: str = _DEFAULT_SERVER,
120
+ port: int = _DEFAULT_PORT,
121
+ path: str = _DEFAULT_PATH,
122
+ connection_timeout: float = _DEFAULT_CONNECTION_TIMEOUT,
123
+ max_size: Optional[int] = _DEFAULT_MAX_SIZE,
124
+ ) -> None:
125
+ """Initialise the client.
126
+
127
+ :param organization_id: The Filament organization to connect to.
128
+ :param api_key_name: Name of the API key used for authentication.
129
+ :param api_key: Secret value of the API key.
130
+ :param server: Base URL of the Filament backend server.
131
+ :param port: Port number the backend listens on.
132
+ :param path: URL path prefix for the SignalR hub endpoint.
133
+ :param connection_timeout: Timeout in seconds for the initial
134
+ connection to the server (default 10).
135
+ :param max_size: Maximum size in bytes of an incoming SignalR
136
+ message (default 1 MiB). Pass ``None`` to remove the limit.
137
+ When the server sends a larger message the websocket is
138
+ closed with code 1009 and any in-flight invocation fails
139
+ with :class:`FilamentConnectionError`.
140
+ """
141
+ self._api_key_name = api_key_name
142
+ self._authentication_failed = False
143
+ self._auth_message: Optional[str] = None
144
+ self._connection_timeout = connection_timeout
145
+ self._max_size = max_size
146
+
147
+ # Capabilities the server advertises during ClientHello (e.g. the file
148
+ # store's checksum algorithm). Populated on connect; stays None against
149
+ # older servers that don't return them.
150
+ self._server_capabilities: Optional[ServerCapabilities] = None
151
+
152
+ # Subscription routing — supports multiple callbacks per backend
153
+ # subscription. The backend returns the same subscription ID when
154
+ # the same type+permissions are subscribed to more than once. We
155
+ # generate a unique *client* subscription ID for each ``subscribe``
156
+ # call so callers can unsubscribe independently.
157
+ #
158
+ # backend sub ID → set of client sub IDs
159
+ self._backend_to_client: dict[UUID, set[UUID]] = {}
160
+ # client sub ID → callback
161
+ self._client_callbacks: dict[UUID, Callback] = {}
162
+ # client sub ID → on_error callback for DataUpdateRejected
163
+ self._client_error_callbacks: dict[UUID, Callback] = {}
164
+ # client sub ID → backend sub ID (reverse lookup for unsubscribe)
165
+ self._client_to_backend: dict[UUID, UUID] = {}
166
+
167
+ self._user_defined_properties: dict[str, Mapping[str, UserDefinedProperty]] = {}
168
+ self._user_defined_property_tasks: dict[
169
+ str, asyncio.Task[Mapping[str, UserDefinedProperty]]
170
+ ] = {}
171
+ self._all_user_defined_property_tasks: set[
172
+ asyncio.Task[Mapping[str, UserDefinedProperty]]
173
+ ] = set()
174
+ self._user_defined_property_generations: dict[str, int] = {}
175
+ self._user_defined_subscription_id: Optional[UUID] = None
176
+ self._user_defined_subscription_types: frozenset[str] = frozenset()
177
+ self._user_defined_subscription_lock = asyncio.Lock()
178
+ self._user_defined_subscription_failures = 0
179
+ self._user_defined_subscription_retry_at = 0.0
180
+
181
+ # Reassembly buffers for chunked DataUpdated events.
182
+ # Key: (backend_subscription_id, sequence_idx) — the logical update being reassembled.
183
+ # Value: dict mapping part_idx → ServiceDataUpdate part.
184
+ self._part_buffers: dict[tuple[UUID, int], dict[int, ServiceDataUpdate]] = {}
185
+ # Keys whose multi-part reassembly is permanently poisoned: an inconsistent
186
+ # part_count was observed for the (backend_sub, sequence_idx). Any further
187
+ # frames for these keys are dropped with a warning rather than starting a
188
+ # fresh buffer (we cannot trust later parts of a sequence the backend has
189
+ # already proven inconsistent for). Cleared on close / unsubscribe.
190
+ self._poisoned_part_buffer_keys: set[tuple[UUID, int]] = set()
191
+ # Complete updates awaiting dispatch, drained in order by one worker task.
192
+ # Dispatch can await hub invocations (UDP discovery and hydration), whose
193
+ # completions arrive on the same receive loop that runs the DataUpdated
194
+ # handler, so it must never run inside the handler itself. Each entry
195
+ # carries the client subscriptions that existed when the update arrived,
196
+ # and whether it arrived on the private UDP-definition subscription.
197
+ self._data_update_queue: deque[
198
+ tuple[UUID, ServiceDataUpdate, frozenset[UUID], bool]
199
+ ] = deque()
200
+ self._data_update_worker: Optional[asyncio.Task[None]] = None
201
+
202
+ # User-registered event callbacks
203
+ self._on_processing_started_callbacks: list[Callback] = []
204
+ self._on_processing_completed_callbacks: list[Callback] = []
205
+ self._on_processing_failed_callbacks: list[Callback] = []
206
+
207
+ # Build SignalR connection
208
+ self._url = f"{server}:{port}/{path}"
209
+
210
+ token_raw = f"{api_key_name}:{organization_id}:{api_key}"
211
+ token = base64.b64encode(token_raw.encode()).decode()
212
+ headers = {
213
+ "Authorization": f"ApiKey {token}",
214
+ }
215
+ self._signalr_client: SignalRClient = SignalRClient(
216
+ url=self._url,
217
+ headers=headers,
218
+ connection_timeout=int(connection_timeout),
219
+ # Do NOT lower this to make dropped connections surface sooner. It is the
220
+ # *websockets* ping interval, and websockets enforces its own pong timeout on
221
+ # the same schedule: on a loop that is starved (a long synchronous pass on a
222
+ # shared loop), the pong would arrive late and websockets would tear the
223
+ # connection down from a second direction, earlier than the server would have.
224
+ # Keeping the transport off a busy loop is what actually fixes starvation;
225
+ # this number only decides how loudly it fails.
226
+ ping_interval=3600,
227
+ max_size=max_size,
228
+ )
229
+
230
+ # Register internal event handlers. pysignalr passes
231
+ # message.arguments (a list) to on() callbacks, so we wrap
232
+ # each handler to unpack the arguments list.
233
+ self._signalr_client.on("AuthenticationFailed", self._wrap_handler(self._handle_authentication_failed))
234
+ self._signalr_client.on("DataUpdated", self._wrap_handler(self._handle_data_updated))
235
+ self._signalr_client.on("DataUpdateRejected", self._wrap_handler(self._handle_data_update_rejected))
236
+ self._signalr_client.on("ProcessingStarted", self._wrap_handler(self._handle_processing_started))
237
+ self._signalr_client.on("ProcessingCompleted", self._wrap_handler(self._handle_processing_completed))
238
+ self._signalr_client.on("ProcessingFailed", self._wrap_handler(self._handle_processing_failed))
239
+ self._signalr_client.on("KeepAlive", self._wrap_handler(self._handle_keep_alive))
240
+
241
+ # pysignalr requires an error callback to avoid RuntimeError
242
+ # when a server invocation returns an error.
243
+ self._signalr_client.on_error(self._handle_signalr_error)
244
+
245
+ # In-flight invocation futures, tracked so they can be failed
246
+ # collectively if the SignalR connection drops before the
247
+ # server response arrives (e.g. websocket close 1009 when a
248
+ # response exceeds the client's max frame size — otherwise
249
+ # the awaiting caller would hang indefinitely).
250
+ self._pending_invocations: set[asyncio.Future[Any]] = set()
251
+ # The websocket connection object from the most recent open, kept only so a close
252
+ # can be *named* — see _close_detail. pysignalr clears its own reference before
253
+ # firing on_close, so this is the only place the close code survives.
254
+ self._last_connection: Any = None
255
+ # Bumped on every connection-ending event (close callback, run loop ending).
256
+ # pysignalr only fires on_close on a state change, so opens and closes
257
+ # alternate; _invoke compares this across send() to tell whether the socket
258
+ # its request was written to has since gone.
259
+ self._close_count = 0
260
+ self._signalr_client.on_close(self._handle_close)
261
+
262
+ # Background task for pysignalr's run() loop
263
+ self._run_task: Optional[asyncio.Task[None]] = None
264
+ self._connected: Optional[asyncio.Event] = None
265
+
266
+ # ------------------------------------------------------------------
267
+ # Context manager
268
+ # ------------------------------------------------------------------
269
+
270
+ async def __aenter__(self) -> FilamentClient:
271
+ """Open the SignalR connection.
272
+
273
+ Raises :class:`FilamentConnectionError` if the server cannot be
274
+ reached, and :class:`FilamentAuthenticationError` if the server
275
+ rejects the API key during the connection handshake.
276
+ """
277
+ self._connected = asyncio.Event()
278
+ self._signalr_client.on_open(self._on_open)
279
+
280
+ self._run_task = asyncio.create_task(self._signalr_client.run())
281
+ self._run_task.add_done_callback(self._handle_run_task_done)
282
+
283
+ # Wait for either: connection established, run() failing, or timeout
284
+ wait_connected = asyncio.ensure_future(self._connected.wait())
285
+ done, pending = await asyncio.wait(
286
+ {wait_connected, self._run_task},
287
+ timeout=self._connection_timeout,
288
+ return_when=asyncio.FIRST_COMPLETED,
289
+ )
290
+
291
+ # Cancel the wait future if still pending
292
+ for fut in pending:
293
+ if fut is wait_connected:
294
+ fut.cancel()
295
+
296
+ if wait_connected not in done:
297
+ # Either run_task failed or we timed out
298
+ self._run_task.cancel()
299
+ try:
300
+ await self._run_task
301
+ except Exception as exc:
302
+ raise FilamentConnectionError(
303
+ f"Failed to connect to {self._url}: {exc}"
304
+ ) from None
305
+ except asyncio.CancelledError:
306
+ pass
307
+
308
+ raise FilamentConnectionError(
309
+ f"Failed to connect to {self._url}: connection timed out"
310
+ ) from None
311
+
312
+ if self._authentication_failed:
313
+ self._run_task.cancel()
314
+ with contextlib.suppress(asyncio.CancelledError):
315
+ await self._run_task
316
+ raise FilamentAuthenticationError(
317
+ self._auth_message or "Authentication failed"
318
+ )
319
+
320
+ try:
321
+ await self._send_client_hello()
322
+ except BaseException:
323
+ # Mirror the auth-failure / timeout exit paths: cancel the background
324
+ # run loop before propagating, otherwise __aexit__ never runs and the
325
+ # task is orphaned with a "Task was destroyed but pending" warning.
326
+ self._run_task.cancel()
327
+ with contextlib.suppress(asyncio.CancelledError):
328
+ await self._run_task
329
+ raise
330
+ return self
331
+
332
+ async def __aexit__(
333
+ self,
334
+ exc_type: Optional[Type[BaseException]],
335
+ exc_val: Optional[BaseException],
336
+ exc_tb: Optional[TracebackType],
337
+ ) -> None:
338
+ """Close the SignalR connection.
339
+
340
+ A transport already broken at close time can surface its own error from the
341
+ cancelled run task (e.g. pysignalr's ``ConnectionError``). Closing must never
342
+ re-raise it: the caller is done with the connection, and pysignalr's exception
343
+ classes are frozen dataclasses that Python cannot even re-raise through a
344
+ ``@contextmanager`` (assigning ``__traceback__`` hits the frozen guard). Log
345
+ and swallow everything except the cancellation we requested.
346
+ """
347
+ if self._run_task is not None:
348
+ self._run_task.cancel()
349
+ try:
350
+ await self._run_task
351
+ except asyncio.CancelledError:
352
+ pass
353
+ except Exception:
354
+ logger.debug("SignalR run loop ended with an error at close", exc_info=True)
355
+ self._data_update_queue.clear()
356
+ worker = self._data_update_worker
357
+ self._data_update_worker = None
358
+ if worker is not None and not worker.done():
359
+ worker.cancel()
360
+ with contextlib.suppress(asyncio.CancelledError):
361
+ await worker
362
+ self._clear_user_defined_property_state(cancel_tasks=True)
363
+
364
+ # ------------------------------------------------------------------
365
+ # SignalR invoke helper
366
+ # ------------------------------------------------------------------
367
+
368
+ async def _invoke(self, method: str, *args: Any) -> Any:
369
+ """Send a hub invocation and await the server's response.
370
+
371
+ Wraps pysignalr's fire-and-forget ``send()`` with a
372
+ :class:`asyncio.Future` so callers can ``await`` the result.
373
+ If the SignalR connection drops before the server replies,
374
+ the future is failed with :class:`FilamentConnectionError`
375
+ so the caller sees an exception instead of hanging.
376
+ """
377
+ loop = asyncio.get_running_loop()
378
+ future: asyncio.Future[Any] = loop.create_future()
379
+
380
+ async def on_completion(message: Message) -> None:
381
+ if future.done():
382
+ return
383
+ if isinstance(message, CompletionMessage):
384
+ if message.error:
385
+ # Name the method: the server's error text alone ("Sequence contains no
386
+ # elements") says nothing about which invocation produced it. The class
387
+ # stays a bare ``Exception`` on purpose — ``_send_client_hello``
388
+ # distinguishes it from ``FilamentError`` to tolerate older servers.
389
+ future.set_exception(Exception(f"{method}: {message.error}"))
390
+ else:
391
+ future.set_result(message.result)
392
+
393
+ close_count = self._close_count
394
+ try:
395
+ await self._signalr_client.send(method, list(args), on_invocation=on_completion)
396
+ except (HubError, OSError, RuntimeError) as exc:
397
+ # Translate transport failures to this package's exception family. Besides
398
+ # giving callers one family to catch, this is load-bearing: pysignalr's
399
+ # exception classes are frozen dataclasses, and Python cannot re-raise a
400
+ # frozen exception through a ``@contextmanager`` (assigning __traceback__
401
+ # hits the frozen guard and masks the real error with FrozenInstanceError).
402
+ # RuntimeError is in the tuple because pysignalr's transport raises a bare
403
+ # ``RuntimeError('Connection is closed')`` for a send on a dead connection —
404
+ # left untranslated it slips past callers that reconnect on
405
+ # FilamentConnectionError, so one dropped websocket turns into an endless
406
+ # string of failed operations that look like generic, retryable errors.
407
+ if not future.done():
408
+ future.cancel()
409
+ raise FilamentConnectionError(
410
+ f"SignalR send failed: {exc} ({self._close_detail()})"
411
+ ) from exc
412
+ except BaseException:
413
+ if not future.done():
414
+ future.cancel()
415
+ raise
416
+
417
+ # Register only once send() has returned, i.e. the invocation is on a socket.
418
+ # pysignalr's send() waits for a connection while reconnecting and wakes just
419
+ # before on_open fires; registering earlier would let _on_open fail a future
420
+ # whose request then goes out on the new socket, so the caller would see an
421
+ # error for a write the server received (and a retry would duplicate it).
422
+ #
423
+ # The flip side: a close can land *during* send() (e.g. while it waits on
424
+ # flow control) and send() may still return normally. The close handler has
425
+ # then already failed the pending set, so registering would leave the caller
426
+ # waiting forever. A close during send() always means the socket the request
427
+ # went out on is gone: a send started while connected writes to that socket,
428
+ # and a send queued while disconnected starts after the preceding close was
429
+ # counted, so the next close is the one ending the socket it was written to.
430
+ # There is no await between this check and registering, so no close can slip
431
+ # in between.
432
+ if not future.done() and self._close_count != close_count:
433
+ future.cancel()
434
+ raise FilamentConnectionError(
435
+ "SignalR connection closed before the server response arrived "
436
+ f"({self._close_detail()})"
437
+ )
438
+ self._pending_invocations.add(future)
439
+ future.add_done_callback(self._pending_invocations.discard)
440
+ return await future
441
+
442
+ async def _send_client_hello(self) -> None:
443
+ """Advertise the negotiated maximum SignalR message size to the server.
444
+
445
+ Sent once per connection. Older backends that don't implement the
446
+ ``ClientHello`` hub method return an invocation error; we log it and
447
+ continue, since the client-side ``max_size`` cap still applies.
448
+
449
+ The invocation is bounded by ``connection_timeout``: if the server
450
+ accepts the socket but never sends a completion for ``ClientHello``,
451
+ we fail the connect with :class:`FilamentConnectionError` rather than
452
+ hang ``__aenter__`` indefinitely.
453
+ """
454
+ # Drop anything the previous connection advertised: every path out of
455
+ # this method below the invocation returns without setting them, so a
456
+ # reused client would otherwise carry stale capabilities (and a stale
457
+ # checksum algorithm) into a handshake that was rejected or unanswered.
458
+ self._server_capabilities = None
459
+ request = ClientHelloRequest(max_message_size_bytes=self._max_size)
460
+ try:
461
+ result_dict: Any = await asyncio.wait_for(
462
+ self._invoke("ClientHello", to_dict(request)),
463
+ timeout=self._connection_timeout,
464
+ )
465
+ except asyncio.TimeoutError as exc:
466
+ raise FilamentConnectionError(
467
+ f"ClientHello did not complete within {self._connection_timeout}s"
468
+ ) from exc
469
+ except FilamentError:
470
+ # Connection / authentication / other lifecycle errors bubble — only
471
+ # the "older server doesn't implement ClientHello" case gets swallowed.
472
+ raise
473
+ except Exception as exc:
474
+ logger.warning(
475
+ "ClientHello invocation failed (older server?): %s. "
476
+ "Continuing with client-side max_size enforcement only.",
477
+ exc,
478
+ )
479
+ return
480
+
481
+ try:
482
+ result = from_dict(result_dict, ValueOrErrorPublic_1[ServerCapabilities])
483
+ except (AttributeError, TypeError, ValueError, KeyError):
484
+ logger.warning(
485
+ "Failed to deserialize ClientHello response — continuing.",
486
+ )
487
+ return
488
+ if result is None or not result.success:
489
+ logger.warning(
490
+ "Server rejected ClientHello: %s",
491
+ result.message if result is not None else "no result",
492
+ )
493
+ return
494
+
495
+ # Capture advertised capabilities (e.g. the file store's checksum
496
+ # algorithm) so upload_file and callers can consult them without another
497
+ # round trip. ``data`` may be None on older servers that accept
498
+ # ClientHello but return no capabilities.
499
+ self._server_capabilities = result.data
500
+
501
+ # ------------------------------------------------------------------
502
+ # Internal event handlers
503
+ # ------------------------------------------------------------------
504
+
505
+ @staticmethod
506
+ def _wrap_handler(
507
+ handler: Callable[..., Awaitable[Any]],
508
+ ) -> Callable[[Any], Awaitable[None]]:
509
+ """Wrap an event handler to unpack pysignalr's arguments list."""
510
+ async def wrapper(arguments: Any) -> None:
511
+ if isinstance(arguments, list):
512
+ await handler(*arguments)
513
+ else:
514
+ await handler(arguments)
515
+ return wrapper
516
+
517
+ def _fail_pending_invocations(self, reason: str) -> None:
518
+ """Fail every in-flight :meth:`_invoke` future with :class:`FilamentConnectionError`.
519
+
520
+ An invocation cannot survive its connection: the server ties completions to
521
+ the socket they were requested on, so once that socket is gone the reply can
522
+ never arrive and the awaiting caller would hang forever. Only invocations
523
+ already written to a socket are pending; one still waiting in ``send()`` for a
524
+ connection is untouched and goes out on whichever socket comes up. Every connection
525
+ lifecycle edge that ends a socket's usefulness must call this — the close
526
+ callback, a successful *re*-connect (new socket, old invocations orphaned),
527
+ and the transport run loop ending without pysignalr firing ``on_close``.
528
+ """
529
+ if not self._pending_invocations:
530
+ return
531
+ error = FilamentConnectionError(reason)
532
+ for future in list(self._pending_invocations):
533
+ if not future.done():
534
+ future.set_exception(error)
535
+
536
+ def _handle_run_task_done(self, task: asyncio.Task[None]) -> None:
537
+ """Fail in-flight invocations when the transport's run loop ends.
538
+
539
+ pysignalr's ``run()`` can die with an exception (or be cancelled) without the
540
+ ``on_close`` callback ever firing — in that state no completion, close, or
541
+ reconnect event will ever arrive, and an awaiting :meth:`_invoke` hangs
542
+ indefinitely. Retrieving the task's exception here also keeps asyncio from
543
+ logging "Task exception was never retrieved" at teardown.
544
+ """
545
+ self._close_count += 1
546
+ if task.cancelled():
547
+ detail = "the connection was closed"
548
+ else:
549
+ exc = task.exception()
550
+ detail = f"the transport loop ended: {exc}" if exc else "the transport loop ended"
551
+ self._fail_pending_invocations(
552
+ f"SignalR connection lost before the server response arrived ({detail})"
553
+ )
554
+ # As in _handle_close: nothing will reconnect, so a queued update needing
555
+ # UDP hydration would wait on a hub reply that can never arrive.
556
+ if self._data_update_queue:
557
+ logger.warning(
558
+ "Discarding %d queued DataUpdated event(s) (%s)",
559
+ len(self._data_update_queue),
560
+ detail,
561
+ )
562
+ self._data_update_queue.clear()
563
+
564
+ async def _on_open(self) -> None:
565
+ """Called when the SignalR connection is established (first connect and reconnects)."""
566
+ # Stash the live websocket while it is still reachable. pysignalr sets its
567
+ # transport's ``_ws`` back to None *before* firing the close callback, so by
568
+ # the time _handle_close runs there is nothing left to ask for the close code.
569
+ # getattr-guarded because this reaches into pysignalr internals: a future
570
+ # version that renames the attribute must degrade to "close code unavailable",
571
+ # never break the connection lifecycle.
572
+ self._last_connection = getattr(
573
+ getattr(self._signalr_client, "_transport", None), "_ws", None
574
+ )
575
+
576
+ # A successful *re*-connect strands any invocation sent on the previous
577
+ # socket — the new connection knows nothing of it, so its completion will
578
+ # never arrive. Fail those callers now rather than letting them hang.
579
+ # On the first open the pending set is empty and this is a no-op.
580
+ self._fail_pending_invocations(
581
+ "SignalR connection was re-established before the server response arrived"
582
+ )
583
+
584
+ # Brief yield to let immediate server messages (e.g.
585
+ # AuthenticationFailed) arrive before we signal ready.
586
+ await asyncio.sleep(0.1)
587
+ if self._connected is not None:
588
+ self._connected.set()
589
+
590
+ async def _handle_signalr_error(self, message: CompletionMessage) -> None:
591
+ """Handle invocation errors from the server."""
592
+ logger.error("SignalR invocation error: %s", message.error)
593
+
594
+ def _close_detail(self) -> str:
595
+ """Describe the websocket close that just happened, for diagnostics.
596
+
597
+ The close code is the single most diagnostic fact about a dropped Filament
598
+ connection: 1006 (no close frame) is the keep-alive-starvation signature, 1009 is
599
+ the client's own frame cap, 1011 is a server error and 1000 an orderly shutdown.
600
+ Without it every drop reads the same in the logs.
601
+
602
+ Every lookup is guarded and the failure mode is a fixed string: this runs on the
603
+ failure path, where an AttributeError would mask the failure it is describing.
604
+ """
605
+ connection = getattr(self, "_last_connection", None)
606
+ code = getattr(connection, "close_code", None) if connection is not None else None
607
+ if code is None:
608
+ return "close code unavailable"
609
+ reason = getattr(connection, "close_reason", None)
610
+ return f"close {code} ({reason})" if reason else f"close {code}"
611
+
612
+ async def _handle_close(self) -> None:
613
+ """Tidy up in-flight state when the SignalR connection drops.
614
+
615
+ - Fails any awaiting :meth:`_invoke` futures with
616
+ :class:`FilamentConnectionError`, so callers see an exception
617
+ instead of hanging when the websocket closes (e.g. close code
618
+ 1009 — message too big). The close code travels in the failure
619
+ message (see :meth:`_close_detail`) so the caller's log names
620
+ *why* the socket went, not just that it did.
621
+ - Discards any in-progress multi-part :class:`ServiceDataUpdate`
622
+ reassemblies and any poisoned-sequence markers — the server has
623
+ no idea what we'd buffered and cannot resume across a reconnect.
624
+ - Drops complete updates still queued for dispatch, for the same reason.
625
+ An update already being dispatched finishes (or fails) on its own.
626
+ """
627
+ self._close_count += 1
628
+ detail = self._close_detail()
629
+ logger.warning("SignalR connection closed (%s)", detail)
630
+ self._fail_pending_invocations(
631
+ f"SignalR connection closed before the server response arrived ({detail})"
632
+ )
633
+
634
+ if self._part_buffers or self._poisoned_part_buffer_keys:
635
+ logger.info(
636
+ "Closing with %d in-flight partial reassemblies and %d poisoned sequence(s)",
637
+ len(self._part_buffers),
638
+ len(self._poisoned_part_buffer_keys),
639
+ )
640
+ for key, buffer in list(self._part_buffers.items()):
641
+ part_count = next(iter(buffer.values())).part_count if buffer else 0
642
+ logger.warning(
643
+ "Discarding %d/%d buffered parts for subscription %s seq %d (connection closed)",
644
+ len(buffer),
645
+ part_count,
646
+ key[0],
647
+ key[1],
648
+ )
649
+ # Cleanup runs unconditionally — clearing empty containers is a no-op,
650
+ # and decoupling it from the logging guard prevents a future edit to the
651
+ # `if` block from accidentally dropping the clears.
652
+ self._part_buffers.clear()
653
+ self._poisoned_part_buffer_keys.clear()
654
+ if self._data_update_queue:
655
+ logger.warning(
656
+ "Discarding %d queued DataUpdated event(s) (connection closed)",
657
+ len(self._data_update_queue),
658
+ )
659
+ self._data_update_queue.clear()
660
+ self._clear_user_defined_property_state()
661
+
662
+ def _clear_user_defined_property_state(self, *, cancel_tasks: bool = False) -> None:
663
+ """Discard UDP metadata and private-subscription state without I/O.
664
+
665
+ In-flight loaders are cancelled only when *cancel_tasks* is set (shutdown).
666
+ On a connection close their ``_invoke`` already fails with
667
+ :class:`FilamentConnectionError`; cancelling them as well would race that
668
+ error and hand their awaiting callers a ``CancelledError`` instead.
669
+ """
670
+ if cancel_tasks:
671
+ for task in self._all_user_defined_property_tasks:
672
+ task.cancel()
673
+ self._all_user_defined_property_tasks.clear()
674
+ # Bump rather than reset the generations: a loader left running whose reply
675
+ # landed just before the close must not publish into the cleared cache.
676
+ for name in set(self._user_defined_property_generations) | set(
677
+ self._user_defined_property_tasks
678
+ ):
679
+ self._user_defined_property_generations[name] = (
680
+ self._user_defined_property_generations.get(name, 0) + 1
681
+ )
682
+ self._user_defined_property_tasks.clear()
683
+ self._user_defined_properties.clear()
684
+ self._user_defined_subscription_id = None
685
+ self._user_defined_subscription_types = frozenset()
686
+ self._user_defined_subscription_failures = 0
687
+ self._user_defined_subscription_retry_at = 0.0
688
+
689
+ async def _handle_authentication_failed(self, message: str = "") -> None:
690
+ """Record an ``AuthenticationFailed`` event from the server."""
691
+ logger.error("Authentication failed: %s", message)
692
+ self._authentication_failed = True
693
+ self._auth_message = message
694
+ # Signal connected so __aenter__ can check the flag and raise
695
+ if self._connected is not None:
696
+ self._connected.set()
697
+
698
+ async def _handle_data_updated(self, data: Any) -> None:
699
+ """Deserialize a ``DataUpdated`` event and fan out to all matching callbacks.
700
+
701
+ Multi-part updates are buffered by ``(backend_sub, sequence_idx)`` and only
702
+ delivered to callbacks once every part has arrived. Single-part updates
703
+ (``part_count == 1``) bypass buffering entirely. Malformed metadata is dropped
704
+ with a WARNING before either path can mis-handle it.
705
+ """
706
+ try:
707
+ update = from_dict(data, ServiceDataUpdate)
708
+ except CompressedPropertyError as exc:
709
+ await self._handle_undecodable_data_update(data, exc)
710
+ return
711
+ except (AttributeError, TypeError, ValueError, KeyError):
712
+ logger.exception("Failed to deserialize DataUpdated payload")
713
+ return
714
+ if update is None:
715
+ logger.warning("Failed to deserialize DataUpdated payload")
716
+ return
717
+
718
+ backend_id = update.subscription_id.id
719
+
720
+ # 1. Drop updates for unknown subscriptions before any other work.
721
+ # Prevents post-unsubscribe parts from leaking into _part_buffers.
722
+ if (
723
+ backend_id not in self._backend_to_client
724
+ and backend_id != self._user_defined_subscription_id
725
+ ):
726
+ return
727
+
728
+ # 2. Reject malformed chunk metadata. A non-positive part_count is a backend
729
+ # bug; the fast path and the buffer would both mis-treat zero/negative values.
730
+ if update.part_count < 1:
731
+ logger.warning(
732
+ "Dropping DataUpdated with non-positive part_count %d for "
733
+ "subscription %s seq %d",
734
+ update.part_count, backend_id, update.sequence_idx,
735
+ )
736
+ return
737
+
738
+ # 3. Drop any frame — including single-part ones — for a poisoned (sub, seq).
739
+ # Once we've forfeited a sequence we never deliver a callback for it.
740
+ key = (backend_id, update.sequence_idx)
741
+ if key in self._poisoned_part_buffer_keys:
742
+ logger.warning(
743
+ "Dropping DataUpdated (part_idx=%d, part_count=%d) for poisoned "
744
+ "subscription %s seq %d",
745
+ update.part_idx, update.part_count, backend_id, update.sequence_idx,
746
+ )
747
+ return
748
+
749
+ # 4. Fast path: unchunked update, no buffering.
750
+ if update.part_count == 1:
751
+ self._enqueue_data_update(backend_id, update)
752
+ return
753
+
754
+ # 5. Multi-part: buffer until all parts arrive. Multiple sequence_idx values
755
+ # may be buffered concurrently for the same subscription; SignalR does not
756
+ # guarantee that parts of one logical update arrive contiguously across
757
+ # sequence_idx boundaries.
758
+ merged = self._buffer_part(backend_id, update)
759
+ if merged is not None:
760
+ self._enqueue_data_update(backend_id, merged)
761
+
762
+ async def _handle_undecodable_data_update(
763
+ self, data: Any, error: CompressedPropertyError,
764
+ ) -> None:
765
+ """Report a ``DataUpdated`` frame whose compressed property failed to decode.
766
+
767
+ The update can never be delivered, so the subscription's ``on_error``
768
+ callbacks receive *error* (as :meth:`_handle_data_update_rejected` does for
769
+ oversized updates); without one it is logged at WARNING. For a multi-part
770
+ update the sequence is poisoned so already-buffered parts are discarded
771
+ rather than waiting forever for a part that will never arrive.
772
+ """
773
+ try:
774
+ backend_id = UUID(data["subscriptionId"]["id"])
775
+ sequence_idx = int(data["sequenceIdx"])
776
+ part_count = int(data.get("partCount", 1))
777
+ except (AttributeError, TypeError, ValueError, KeyError):
778
+ logger.exception("Failed to deserialize DataUpdated payload")
779
+ return
780
+
781
+ client_ids = self._backend_to_client.get(backend_id)
782
+ if not client_ids and backend_id != self._user_defined_subscription_id:
783
+ return
784
+
785
+ if part_count > 1:
786
+ key = (backend_id, sequence_idx)
787
+ discarded = self._part_buffers.pop(key, {})
788
+ self._poisoned_part_buffer_keys.add(key)
789
+ logger.warning(
790
+ "Undecodable compressed property in DataUpdated for subscription %s "
791
+ "seq %d — discarding %d/%d buffered parts and poisoning the sequence",
792
+ backend_id, sequence_idx, len(discarded), part_count,
793
+ )
794
+
795
+ if not client_ids:
796
+ logger.error(
797
+ "Dropping UDP definition update for subscription %s: %s",
798
+ backend_id, error,
799
+ )
800
+ return
801
+
802
+ for client_id in list(client_ids):
803
+ on_error = self._client_error_callbacks.get(client_id)
804
+ if on_error is not None:
805
+ try:
806
+ await _invoke_callback(on_error, error)
807
+ except Exception:
808
+ logger.exception(
809
+ "Error in DataUpdated on_error callback for subscription %s"
810
+ " (client %s)",
811
+ backend_id,
812
+ client_id,
813
+ )
814
+ else:
815
+ logger.warning(
816
+ "Dropping DataUpdated for subscription %s (client %s) — "
817
+ "no on_error callback registered: %s",
818
+ backend_id,
819
+ client_id,
820
+ error,
821
+ )
822
+
823
+ def _enqueue_data_update(self, backend_id: UUID, update: ServiceDataUpdate) -> None:
824
+ """Queue a complete update for dispatch, starting the worker if it is idle.
825
+
826
+ pysignalr awaits each handler before reading the next frame, so awaiting a
827
+ hub invocation inside the handler would wait for a completion that can never
828
+ be read. One worker drains the queue, which keeps delivery in arrival order.
829
+
830
+ The recipients are fixed now, as inline dispatch would have fixed them: a
831
+ client that subscribes while the update waits must not receive it. So is
832
+ whether this is a UDP definition push: reconciliation may replace the private
833
+ subscription ID before the worker reaches it.
834
+ """
835
+ client_ids = frozenset(self._backend_to_client.get(backend_id, ()))
836
+ from_udp = backend_id == self._user_defined_subscription_id
837
+ self._data_update_queue.append((backend_id, update, client_ids, from_udp))
838
+ if self._data_update_worker is None or self._data_update_worker.done():
839
+ self._data_update_worker = asyncio.create_task(self._drain_data_updates())
840
+
841
+ async def _drain_data_updates(self) -> None:
842
+ """Dispatch queued updates in order; exit once the queue is empty."""
843
+ while self._data_update_queue:
844
+ backend_id, update, client_ids, from_udp = self._data_update_queue.popleft()
845
+ try:
846
+ await self._dispatch_data_update(
847
+ backend_id, update, client_ids,
848
+ from_user_defined_subscription=from_udp,
849
+ )
850
+ except Exception:
851
+ # E.g. FilamentConnectionError from UDP discovery when the connection
852
+ # drops mid-dispatch. Losing one update must not stop the worker.
853
+ logger.exception(
854
+ "Failed to dispatch DataUpdated for subscription %s", backend_id,
855
+ )
856
+
857
+ async def _dispatch_data_update(
858
+ self,
859
+ backend_id: UUID,
860
+ update: ServiceDataUpdate,
861
+ client_ids: frozenset[UUID],
862
+ *,
863
+ from_user_defined_subscription: bool,
864
+ ) -> None:
865
+ """Fan out a (possibly merged) ``ServiceDataUpdate`` to its client callbacks.
866
+
867
+ *client_ids* are the subscriptions that existed when the update arrived; any
868
+ that have since been unsubscribed are skipped.
869
+ *from_user_defined_subscription* marks a UDP definition push, which refreshes
870
+ the cached registries before any client callbacks run.
871
+ """
872
+ if from_user_defined_subscription:
873
+ await self._handle_user_defined_property_update(update)
874
+ # The backend returns the same subscription ID for duplicate
875
+ # type/permission combinations, so a caller who subscribes to
876
+ # UserDefinedPropertyEntity with a matching config shares this ID.
877
+ # Keep dispatching so their callback still runs.
878
+ if not client_ids:
879
+ return
880
+ if not await self._hydrate_data_update(update):
881
+ logger.error(
882
+ "Dropping DataUpdated for subscription %s because UDP hydration failed",
883
+ backend_id,
884
+ )
885
+ return
886
+ for client_id in client_ids:
887
+ callback = self._client_callbacks.get(client_id)
888
+ if callback is None:
889
+ continue
890
+ try:
891
+ await _invoke_callback(callback, update)
892
+ except Exception:
893
+ logger.exception(
894
+ "Error in DataUpdated callback for subscription %s (client %s)",
895
+ backend_id,
896
+ client_id,
897
+ )
898
+
899
+ async def _hydrate_entities_for_type(
900
+ self, entity_type_name: str, entities: list[Any],
901
+ ) -> bool:
902
+ """Hydrate a group of entities, refreshing once for unknown UDP names."""
903
+ try:
904
+ properties = await self._ensure_user_defined_properties(entity_type_name)
905
+ unknown: set[str] = set()
906
+ for entity in entities:
907
+ if entity is not None:
908
+ unknown.update(
909
+ hydrate_user_defined_properties(entity, properties)
910
+ )
911
+ if not unknown:
912
+ return True
913
+
914
+ self._evict_user_defined_properties({entity_type_name})
915
+ properties = await self._ensure_user_defined_properties(entity_type_name)
916
+ still_unknown: set[str] = set()
917
+ for entity in entities:
918
+ if entity is not None:
919
+ still_unknown.update(
920
+ hydrate_user_defined_properties(entity, properties)
921
+ )
922
+ if still_unknown:
923
+ logger.error(
924
+ "Backend returned unknown UDP properties for %s after refresh: %s",
925
+ entity_type_name,
926
+ ", ".join(sorted(still_unknown)),
927
+ )
928
+ return False
929
+ return True
930
+ except (TypeError, ValueError, _UserDefinedPropertyLoadError):
931
+ logger.exception(
932
+ "Could not hydrate UDP properties for %s", entity_type_name
933
+ )
934
+ return False
935
+
936
+ async def _hydrate_data_update(self, update: ServiceDataUpdate) -> bool:
937
+ for entity_type_name, changes in update.modified_entities.items():
938
+ entities: list[Any] = list(changes.created) + list(changes.deleted)
939
+ entities.extend(item.entity for item in changes.updated if item.entity is not None)
940
+ if not await self._hydrate_entities_for_type(entity_type_name, entities):
941
+ return False
942
+ return True
943
+
944
+ async def _handle_user_defined_property_update(
945
+ self, update: ServiceDataUpdate,
946
+ ) -> None:
947
+ """Refresh cached type registries affected by a definition push."""
948
+ affected: set[str] = set()
949
+ for type_name, changes in update.modified_entities.items():
950
+ if type_name.rsplit(".", 1)[-1] != "UserDefinedPropertyEntity":
951
+ continue
952
+ entities: list[Any] = list(changes.created) + list(changes.deleted)
953
+ entities.extend(item.entity for item in changes.updated if item.entity is not None)
954
+ for entity in entities:
955
+ if isinstance(entity, UserDefinedPropertyEntity) and entity.entity_type_name:
956
+ affected.add(entity.entity_type_name)
957
+ cached = affected.intersection(self._user_defined_properties)
958
+ if cached:
959
+ cached_names = sorted(cached)
960
+ self._evict_user_defined_properties(cached)
961
+ results = await asyncio.gather(
962
+ *(
963
+ self._ensure_user_defined_properties(name, reconcile=False)
964
+ for name in cached_names
965
+ ),
966
+ return_exceptions=True,
967
+ )
968
+ for name, result in zip(cached_names, results, strict=True):
969
+ if isinstance(result, BaseException):
970
+ logger.error(
971
+ "Could not refresh UDP definitions for %s: %s", name, result,
972
+ )
973
+ await self._reconcile_user_defined_property_subscription_or_warn(
974
+ ", ".join(cached_names),
975
+ )
976
+
977
+ def _buffer_part(
978
+ self, backend_id: UUID, part: ServiceDataUpdate,
979
+ ) -> Optional[ServiceDataUpdate]:
980
+ """Insert *part* into the reassembly buffer.
981
+
982
+ Returns the merged ``ServiceDataUpdate`` when all parts have arrived; otherwise None.
983
+ Validates malformed metadata up-front:
984
+
985
+ - Out-of-range ``part_idx`` (``< 0`` or ``>= part_count``) is dropped with a WARNING.
986
+ - A new part whose ``part_count`` disagrees with the buffered ones poisons the
987
+ ``(backend_id, sequence_idx)`` key and discards the buffer. All later frames for
988
+ the poisoned key are dropped by the caller's pre-check in
989
+ :meth:`_handle_data_updated`.
990
+ - Completeness requires both ``len(buffer) == part_count`` and the buffered keys to
991
+ form exactly ``{0, 1, ..., part_count - 1}``, so indexing during merge is safe.
992
+ """
993
+ if part.part_idx < 0 or part.part_idx >= part.part_count:
994
+ logger.warning(
995
+ "Dropping part with invalid part_idx %d (part_count %d) for "
996
+ "subscription %s seq %d",
997
+ part.part_idx, part.part_count, backend_id, part.sequence_idx,
998
+ )
999
+ return None
1000
+
1001
+ key = (backend_id, part.sequence_idx)
1002
+ # The poison check lives in _handle_data_updated (ahead of both the fast path and
1003
+ # this method), so by the time we get here the key is guaranteed non-poisoned.
1004
+
1005
+ buffer = self._part_buffers.get(key)
1006
+
1007
+ if buffer is not None and buffer:
1008
+ # Validate part_count agrees with what's already buffered. Any one stored
1009
+ # part's part_count is representative because we enforce agreement on insert.
1010
+ existing_part_count = next(iter(buffer.values())).part_count
1011
+ if existing_part_count != part.part_count:
1012
+ logger.warning(
1013
+ "Inconsistent part_count for subscription %s seq %d "
1014
+ "(buffer has part_count=%d, new part has part_count=%d) "
1015
+ "— discarding %d/%d buffered parts and poisoning the sequence; "
1016
+ "all further frames for this (sub, seq) will be dropped",
1017
+ backend_id, part.sequence_idx,
1018
+ existing_part_count, part.part_count,
1019
+ len(buffer), existing_part_count,
1020
+ )
1021
+ del self._part_buffers[key]
1022
+ self._poisoned_part_buffer_keys.add(key)
1023
+ return None
1024
+
1025
+ if buffer is None:
1026
+ buffer = {}
1027
+ self._part_buffers[key] = buffer
1028
+
1029
+ if part.part_idx in buffer:
1030
+ logger.warning(
1031
+ "Duplicate part_idx %d for subscription %s seq %d — overwriting",
1032
+ part.part_idx, backend_id, part.sequence_idx,
1033
+ )
1034
+ buffer[part.part_idx] = part
1035
+
1036
+ if len(buffer) != part.part_count:
1037
+ return None
1038
+ if set(buffer) != set(range(part.part_count)):
1039
+ # Right count but a gap somewhere — keep waiting.
1040
+ return None
1041
+
1042
+ merged = self._merge_parts(buffer, part.part_count)
1043
+ del self._part_buffers[key]
1044
+ return merged
1045
+
1046
+ @staticmethod
1047
+ def _merge_parts(
1048
+ buffer: dict[int, ServiceDataUpdate], part_count: int,
1049
+ ) -> ServiceDataUpdate:
1050
+ """Merge buffered parts into one logical :class:`ServiceDataUpdate`.
1051
+
1052
+ Envelope fields are taken from ``buffer[0]`` (they are identical across parts by
1053
+ contract). For ``modified_entities`` the parts may share entity-type keys (the
1054
+ backend can split a long ``created``/``updated``/``deleted`` list across parts), so
1055
+ on collision the inner lists are extended rather than overwritten. The merged
1056
+ result is rewritten with ``part_idx=0`` / ``part_count=1`` so the user-visible
1057
+ delivery looks like a single un-chunked update.
1058
+ """
1059
+ parts = [buffer[i] for i in range(part_count)]
1060
+ first = parts[0]
1061
+ merged_entities: dict[str, EntityServiceDataUpdate] = {}
1062
+ for part in parts:
1063
+ for type_name, entity_update in part.modified_entities.items():
1064
+ existing = merged_entities.get(type_name)
1065
+ if existing is None:
1066
+ merged_entities[type_name] = EntityServiceDataUpdate(
1067
+ created=list(entity_update.created),
1068
+ updated=list(entity_update.updated),
1069
+ deleted=list(entity_update.deleted),
1070
+ )
1071
+ else:
1072
+ existing.created.extend(entity_update.created)
1073
+ existing.updated.extend(entity_update.updated)
1074
+ existing.deleted.extend(entity_update.deleted)
1075
+
1076
+ return ServiceDataUpdate(
1077
+ scenario_id=first.scenario_id,
1078
+ status=first.status,
1079
+ request_ids=first.request_ids,
1080
+ subscription_id=first.subscription_id,
1081
+ modified_entities=merged_entities,
1082
+ progress=first.progress,
1083
+ progress_amount=first.progress_amount,
1084
+ sequence_idx=first.sequence_idx,
1085
+ part_idx=0,
1086
+ part_count=1,
1087
+ )
1088
+
1089
+ async def _handle_data_update_rejected(self, data: Any) -> None:
1090
+ """Route a ``DataUpdateRejected`` event to the subscription's ``on_error`` callback.
1091
+
1092
+ Sent by the server in place of ``DataUpdated`` when the update's serialised size
1093
+ would exceed the limit negotiated via :meth:`_send_client_hello`. If no
1094
+ ``on_error`` was registered for the subscription the rejection is logged so the
1095
+ dropped update is at least visible.
1096
+ """
1097
+ try:
1098
+ notification = from_dict(data, DataUpdateRejectedNotification)
1099
+ except (AttributeError, TypeError, ValueError, KeyError):
1100
+ logger.exception("Failed to deserialize DataUpdateRejected payload")
1101
+ return
1102
+ if notification is None:
1103
+ logger.warning("Failed to deserialize DataUpdateRejected payload")
1104
+ return
1105
+
1106
+ backend_id = notification.subscription_id.id
1107
+ client_ids = self._backend_to_client.get(backend_id)
1108
+ if not client_ids:
1109
+ logger.warning(
1110
+ "DataUpdateRejected for unknown subscription %s "
1111
+ "(%d bytes, limit %d): %s",
1112
+ backend_id,
1113
+ notification.actual_bytes,
1114
+ notification.limit_bytes,
1115
+ notification.reason,
1116
+ )
1117
+ return
1118
+
1119
+ for client_id in list(client_ids):
1120
+ on_error = self._client_error_callbacks.get(client_id)
1121
+ if on_error is not None:
1122
+ try:
1123
+ await _invoke_callback(on_error, notification)
1124
+ except Exception:
1125
+ logger.exception(
1126
+ "Error in DataUpdateRejected callback for subscription %s"
1127
+ " (client %s)",
1128
+ backend_id,
1129
+ client_id,
1130
+ )
1131
+ else:
1132
+ logger.warning(
1133
+ "DataUpdateRejected for subscription %s (client %s) — "
1134
+ "no on_error callback registered "
1135
+ "(%d bytes, limit %d): %s",
1136
+ backend_id,
1137
+ client_id,
1138
+ notification.actual_bytes,
1139
+ notification.limit_bytes,
1140
+ notification.reason,
1141
+ )
1142
+
1143
+ async def _handle_processing_started(self, data: Any) -> None:
1144
+ """Deserialize a ``ProcessingStarted`` event and invoke registered callbacks."""
1145
+ try:
1146
+ status = from_dict(data, ProcessingStatus)
1147
+ except (AttributeError, TypeError, ValueError, KeyError):
1148
+ logger.exception("Failed to deserialize %s payload", "ProcessingStarted")
1149
+ return
1150
+ if status is None:
1151
+ return
1152
+ for cb in self._on_processing_started_callbacks:
1153
+ try:
1154
+ await _invoke_callback(cb, status)
1155
+ except Exception:
1156
+ logger.exception("Error in ProcessingStarted callback")
1157
+
1158
+ async def _handle_processing_completed(self, data: Any) -> None:
1159
+ """Deserialize a ``ProcessingCompleted`` event and invoke registered callbacks."""
1160
+ try:
1161
+ status = from_dict(data, ProcessingStatus)
1162
+ except (AttributeError, TypeError, ValueError, KeyError):
1163
+ logger.exception("Failed to deserialize %s payload", "ProcessingCompleted")
1164
+ return
1165
+ if status is None:
1166
+ return
1167
+ for cb in self._on_processing_completed_callbacks:
1168
+ try:
1169
+ await _invoke_callback(cb, status)
1170
+ except Exception:
1171
+ logger.exception("Error in ProcessingCompleted callback")
1172
+
1173
+ async def _handle_processing_failed(self, data: Any) -> None:
1174
+ """Deserialize a ``ProcessingFailed`` event and invoke registered callbacks."""
1175
+ try:
1176
+ status = from_dict(data, ProcessingStatus)
1177
+ except (AttributeError, TypeError, ValueError, KeyError):
1178
+ logger.exception("Failed to deserialize %s payload", "ProcessingFailed")
1179
+ return
1180
+ if status is None:
1181
+ return
1182
+ for cb in self._on_processing_failed_callbacks:
1183
+ try:
1184
+ await _invoke_callback(cb, status)
1185
+ except Exception:
1186
+ logger.exception("Error in ProcessingFailed callback")
1187
+
1188
+ async def _handle_keep_alive(self, data: Any) -> None:
1189
+ """Handle a ``KeepAlive`` heartbeat from the server (no-op)."""
1190
+
1191
+ # ------------------------------------------------------------------
1192
+ # Event callback registration
1193
+ # ------------------------------------------------------------------
1194
+
1195
+ def on_processing_started(self, callback: Callback) -> None:
1196
+ """Register a callback for ``ProcessingStarted`` events."""
1197
+ self._on_processing_started_callbacks.append(callback)
1198
+
1199
+ def on_processing_completed(self, callback: Callback) -> None:
1200
+ """Register a callback for ``ProcessingCompleted`` events."""
1201
+ self._on_processing_completed_callbacks.append(callback)
1202
+
1203
+ def on_processing_failed(self, callback: Callback) -> None:
1204
+ """Register a callback for ``ProcessingFailed`` events."""
1205
+ self._on_processing_failed_callbacks.append(callback)
1206
+
1207
+ # ------------------------------------------------------------------
1208
+ # User-defined property metadata
1209
+ # ------------------------------------------------------------------
1210
+
1211
+ async def _get_entity_property_permissions_uncached(
1212
+ self, entity_type_name: str,
1213
+ ) -> ValueOrErrorPublic_1[EntityPropertyPermissions]:
1214
+ result_dict: Any = await self._invoke(
1215
+ "GetEntityPropertyPermissions", entity_type_name
1216
+ )
1217
+ try:
1218
+ result = from_dict(result_dict, ValueOrErrorPublic_1[EntityPropertyPermissions])
1219
+ except (AttributeError, TypeError, ValueError, KeyError):
1220
+ return _deserialization_error()
1221
+ return result if result is not None else _deserialization_error()
1222
+
1223
+ async def _load_user_defined_properties(
1224
+ self, entity_type_name: str, generation: int,
1225
+ ) -> Mapping[str, UserDefinedProperty]:
1226
+ permissions = await self._get_entity_property_permissions_uncached(entity_type_name)
1227
+ if not permissions.success or permissions.data is None:
1228
+ raise _UserDefinedPropertyLoadError(
1229
+ permissions.message or f"Could not load permissions for {entity_type_name}",
1230
+ permissions.error_code,
1231
+ )
1232
+ try:
1233
+ properties = build_user_defined_properties(
1234
+ entity_type_name, permissions.data
1235
+ )
1236
+ except (TypeError, ValueError) as exc:
1237
+ raise _UserDefinedPropertyLoadError(
1238
+ f"Invalid UDP definitions for {entity_type_name}: {exc}",
1239
+ ErrorCodes.InternalError,
1240
+ ) from exc
1241
+ if self._user_defined_property_generations.get(entity_type_name, 0) == generation:
1242
+ self._user_defined_properties[entity_type_name] = properties
1243
+ return properties
1244
+
1245
+ async def _ensure_user_defined_properties(
1246
+ self, entity_type_name: str, *, reconcile: bool = True,
1247
+ ) -> Mapping[str, UserDefinedProperty]:
1248
+ """Load and cache one type's UDP definitions.
1249
+
1250
+ Pass ``reconcile=False`` when loading a batch of types: each reconcile
1251
+ issues its own ``Subscribe`` plus an ``Unsubscribe`` for the superseded
1252
+ ID, so reconciling per type costs 2N hub calls and leaves every
1253
+ intermediate subscription covering only part of the desired set. The
1254
+ caller is then responsible for reconciling once after the batch.
1255
+ """
1256
+ cached = self._user_defined_properties.get(entity_type_name)
1257
+ if cached is not None:
1258
+ if reconcile and (
1259
+ entity_type_name not in self._user_defined_subscription_types
1260
+ or self._user_defined_subscription_id is None
1261
+ ):
1262
+ await self._reconcile_user_defined_property_subscription_or_warn(
1263
+ entity_type_name,
1264
+ )
1265
+ return cached
1266
+ task = self._user_defined_property_tasks.get(entity_type_name)
1267
+ if task is None:
1268
+ generation = self._user_defined_property_generations.get(entity_type_name, 0)
1269
+ task = asyncio.create_task(
1270
+ self._load_user_defined_properties(entity_type_name, generation)
1271
+ )
1272
+ self._user_defined_property_tasks[entity_type_name] = task
1273
+ self._all_user_defined_property_tasks.add(task)
1274
+ task.add_done_callback(
1275
+ functools.partial(self._forget_user_defined_property_task, entity_type_name)
1276
+ )
1277
+ try:
1278
+ # The loader is shared by every caller for this type, so one caller being
1279
+ # cancelled must not cancel it for the others. wait() neither cancels the
1280
+ # task nor raises its outcome, so a CancelledError here is always this
1281
+ # caller's own cancellation and propagates as-is.
1282
+ await asyncio.wait({task})
1283
+ if task.cancelled():
1284
+ # Only client shutdown cancels a loader. Its callers must see the
1285
+ # dead connection, not a CancelledError they did not ask for.
1286
+ raise FilamentConnectionError(
1287
+ f"Client closed while loading UDP definitions for {entity_type_name}"
1288
+ )
1289
+ task.result()
1290
+ finally:
1291
+ # A cancelled waiter leaves the loader running for the other callers, so
1292
+ # only a finished loader is deregistered here. The done callback also
1293
+ # deregisters it, but runs later than this waiter can retry.
1294
+ if task.done() and self._user_defined_property_tasks.get(entity_type_name) is task:
1295
+ del self._user_defined_property_tasks[entity_type_name]
1296
+ cached = self._user_defined_properties.get(entity_type_name)
1297
+ if cached is None:
1298
+ # The load was invalidated while in flight; retry under the new generation.
1299
+ return await self._ensure_user_defined_properties(
1300
+ entity_type_name, reconcile=reconcile,
1301
+ )
1302
+ if reconcile:
1303
+ await self._reconcile_user_defined_property_subscription_or_warn(
1304
+ entity_type_name,
1305
+ )
1306
+ return cached
1307
+
1308
+ async def _reconcile_user_defined_property_subscription_or_warn(
1309
+ self, entity_type_names: str,
1310
+ ) -> None:
1311
+ """Reconcile, keeping loaded definitions usable if the subscribe fails.
1312
+
1313
+ A failed reconcile leaves the subscription state untouched, so the type
1314
+ stays uncovered and a later ``_ensure_user_defined_properties`` call
1315
+ retries it once the rejection backoff has elapsed. *entity_type_names*
1316
+ only labels the warning.
1317
+ """
1318
+ try:
1319
+ await self._reconcile_user_defined_property_subscription(
1320
+ respect_backoff=True,
1321
+ )
1322
+ except _UserDefinedPropertyLoadError as exc:
1323
+ logger.warning(
1324
+ "Could not subscribe to UDP definition changes for %s: %s",
1325
+ entity_type_names,
1326
+ exc.message,
1327
+ )
1328
+
1329
+ def _forget_user_defined_property_task(
1330
+ self,
1331
+ entity_type_name: str,
1332
+ task: asyncio.Task[Mapping[str, UserDefinedProperty]],
1333
+ ) -> None:
1334
+ self._all_user_defined_property_tasks.discard(task)
1335
+ # Identity check: an eviction may already have registered a replacement.
1336
+ if self._user_defined_property_tasks.get(entity_type_name) is task:
1337
+ del self._user_defined_property_tasks[entity_type_name]
1338
+ # Every waiter re-raises the loader's failure itself; retrieving it here
1339
+ # keeps a loader whose waiters were all cancelled from logging "Task
1340
+ # exception was never retrieved".
1341
+ if not task.cancelled():
1342
+ task.exception()
1343
+
1344
+ async def _reconcile_user_defined_property_subscription(
1345
+ self, *, respect_backoff: bool = False,
1346
+ ) -> None:
1347
+ """Subscribe privately to definition changes for every cached type.
1348
+
1349
+ With *respect_backoff*, skip the attempt while a previous rejection's
1350
+ backoff is still running, so repeated or concurrent reads don't each
1351
+ re-issue a ``Subscribe`` the backend keeps rejecting.
1352
+ """
1353
+ async with self._user_defined_subscription_lock:
1354
+ # Include active refreshes so a temporarily evicted map does not
1355
+ # shrink the still-needed maintenance subscription mid-refresh.
1356
+ desired = frozenset(
1357
+ set(self._user_defined_properties) | set(self._user_defined_property_tasks)
1358
+ )
1359
+ old_id = self._user_defined_subscription_id
1360
+ if desired == self._user_defined_subscription_types and (
1361
+ old_id is not None or not desired
1362
+ ):
1363
+ return
1364
+ if (
1365
+ respect_backoff
1366
+ and asyncio.get_running_loop().time()
1367
+ < self._user_defined_subscription_retry_at
1368
+ ):
1369
+ return
1370
+
1371
+ new_id: Optional[UUID] = None
1372
+ if desired:
1373
+ config = SubscriptionConfig(
1374
+ scenario_id=UUID("00000000-0000-0000-0000-000000000000"),
1375
+ status=DataProcessingStatus.All,
1376
+ type_name="UserDefinedPropertyEntity",
1377
+ condition=Condition(UserDefinedPropertyEntity).prop(
1378
+ "entity_type_name"
1379
+ ).in_(sorted(desired)),
1380
+ mode=SubscriptionMode.Data,
1381
+ )
1382
+ response_dict: Any = await self._invoke("Subscribe", to_dict(config))
1383
+ response: Optional[ValueOrErrorPublic_1[SubscriptionId]]
1384
+ try:
1385
+ response = from_dict(
1386
+ response_dict, ValueOrErrorPublic_1[SubscriptionId]
1387
+ )
1388
+ except (AttributeError, TypeError, ValueError, KeyError):
1389
+ response = None
1390
+ if response is None or not response.success or response.data is None:
1391
+ self._user_defined_subscription_failures += 1
1392
+ self._user_defined_subscription_retry_at = (
1393
+ asyncio.get_running_loop().time()
1394
+ + min(
1395
+ _UDP_SUBSCRIBE_RETRY_INITIAL
1396
+ # Capped so a long run of rejections can't overflow the float.
1397
+ * 2 ** min(self._user_defined_subscription_failures - 1, 16),
1398
+ _UDP_SUBSCRIBE_RETRY_MAX,
1399
+ )
1400
+ )
1401
+ raise _UserDefinedPropertyLoadError(
1402
+ response.message if response is not None else (
1403
+ "Invalid response while subscribing to UDP definition changes"
1404
+ ),
1405
+ response.error_code if response is not None else (
1406
+ ErrorCodes.InternalError
1407
+ ),
1408
+ )
1409
+ new_id = response.data.id
1410
+
1411
+ self._user_defined_subscription_id = new_id
1412
+ self._user_defined_subscription_types = desired
1413
+ self._user_defined_subscription_failures = 0
1414
+ self._user_defined_subscription_retry_at = 0.0
1415
+ # A user subscription may share the superseded backend ID (the backend
1416
+ # dedupes identical subscriptions); unsubscribe() sends the backend
1417
+ # Unsubscribe once its last client is removed, so leave it alone here.
1418
+ # Known gap: subscribe() doesn't hold _user_defined_subscription_lock and
1419
+ # only registers in _backend_to_client after its Subscribe returns, so a
1420
+ # concurrent identical user subscribe can still be deduped onto old_id
1421
+ # and then cancelled by the Unsubscribe below.
1422
+ if (
1423
+ old_id is not None
1424
+ and old_id != new_id
1425
+ and old_id not in self._backend_to_client
1426
+ ):
1427
+ response_dict = await self._invoke(
1428
+ "Unsubscribe", to_dict(SubscriptionId(id=old_id)),
1429
+ )
1430
+ unsubscribe_response = from_dict(
1431
+ response_dict, SuccessOrErrorPublic
1432
+ )
1433
+ if unsubscribe_response is None or not unsubscribe_response.success:
1434
+ logger.warning(
1435
+ "Could not remove superseded UDP definition subscription %s",
1436
+ old_id,
1437
+ )
1438
+
1439
+ async def invalidate_user_defined_property_cache(
1440
+ self, entity_type_name: Optional[str] = None,
1441
+ ) -> None:
1442
+ """Invalidate one type's cached UDP definitions, or every cached type."""
1443
+ names = (
1444
+ {entity_type_name}
1445
+ if entity_type_name is not None
1446
+ else set(self._user_defined_properties) | set(self._user_defined_property_tasks)
1447
+ )
1448
+ self._evict_user_defined_properties(names)
1449
+ await self._reconcile_user_defined_property_subscription()
1450
+
1451
+ def _evict_user_defined_properties(self, names: set[str]) -> None:
1452
+ """Evict maps without changing the still-covering private subscription."""
1453
+ for name in names:
1454
+ self._user_defined_property_generations[name] = (
1455
+ self._user_defined_property_generations.get(name, 0) + 1
1456
+ )
1457
+ self._user_defined_properties.pop(name, None)
1458
+ # Detach rather than cancel: current callers may still be awaiting
1459
+ # the old generation. Its loader is forbidden from publishing and
1460
+ # those callers will transparently retry under the new generation.
1461
+ self._user_defined_property_tasks.pop(name, None)
1462
+
1463
+ async def get_user_defined_properties(
1464
+ self, entity_type_name: str,
1465
+ ) -> ValueOrErrorPublic_1[Mapping[str, UserDefinedProperty]]:
1466
+ """Return the cached/discovered UDP properties for an entity type."""
1467
+ try:
1468
+ properties = await self._ensure_user_defined_properties(entity_type_name)
1469
+ except _UserDefinedPropertyLoadError as exc:
1470
+ return _value_error(exc.message, exc.error_code)
1471
+ return ValueOrErrorPublic_1(
1472
+ success=True,
1473
+ message="",
1474
+ error_code=ErrorCodes.None_,
1475
+ error_id=None,
1476
+ data=properties,
1477
+ )
1478
+
1479
+ # Properties
1480
+ # ------------------------------------------------------------------
1481
+
1482
+ @property
1483
+ def server_capabilities(self) -> Optional[ServerCapabilities]:
1484
+ """Capabilities the server advertised during the ``ClientHello`` handshake.
1485
+
1486
+ ``None`` until the connection is established, or when connected to an
1487
+ older server that returns no capabilities. ``server_capabilities.files``
1488
+ (when present) carries the file store's checksum algorithm and
1489
+ server-side-checksum flag, which :meth:`upload_file` consults to decide
1490
+ whether and how to checksum before requesting an upload grant.
1491
+ """
1492
+ return self._server_capabilities
1493
+
1494
+ # ------------------------------------------------------------------
1495
+ # API methods
1496
+ # ------------------------------------------------------------------
1497
+
1498
+ async def get_entity_permissions(
1499
+ self,
1500
+ ) -> ValueOrErrorPublic_1[EntityPermissions]:
1501
+ """Retrieve entity-level permissions for the authenticated user."""
1502
+ result_dict: Any = await self._invoke("GetEntityPermissions")
1503
+ try:
1504
+ result = from_dict(result_dict, ValueOrErrorPublic_1[EntityPermissions])
1505
+ except (AttributeError, TypeError, ValueError, KeyError):
1506
+ return _deserialization_error()
1507
+ if result is not None:
1508
+ return result
1509
+ return _deserialization_error()
1510
+
1511
+ async def get_entity_property_permissions(
1512
+ self,
1513
+ entity_type_name: str,
1514
+ ) -> ValueOrErrorPublic_1[EntityPropertyPermissions]:
1515
+ """Retrieve permissions and refresh this type's UDP metadata cache."""
1516
+ result = await self._get_entity_property_permissions_uncached(entity_type_name)
1517
+ if result.success and result.data is not None:
1518
+ self._user_defined_property_generations[entity_type_name] = (
1519
+ self._user_defined_property_generations.get(entity_type_name, 0) + 1
1520
+ )
1521
+ try:
1522
+ self._user_defined_properties[entity_type_name] = (
1523
+ build_user_defined_properties(entity_type_name, result.data)
1524
+ )
1525
+ except (TypeError, ValueError) as exc:
1526
+ return _value_error(
1527
+ f"Invalid UDP definitions for {entity_type_name}: {exc}"
1528
+ )
1529
+ await self._reconcile_user_defined_property_subscription_or_warn(
1530
+ entity_type_name,
1531
+ )
1532
+ return result
1533
+
1534
+ async def read_data(
1535
+ self,
1536
+ request: ReadDataRequest,
1537
+ ) -> ValueOrErrorPublic_1[ServiceDataRead]:
1538
+ """Read entity data from the server.
1539
+
1540
+ If the server rejects the response as too large
1541
+ (:attr:`ErrorCodes.ResponseTooLarge` — returned when the serialised
1542
+ result would exceed the ``max_size`` negotiated at connect time),
1543
+ the request is automatically split into smaller pages. The number
1544
+ of pages is derived from the byte counts reported in the error
1545
+ message, and each page is read recursively so that a page which is
1546
+ *itself* too large (because the data is not spread evenly across the
1547
+ entities) is split again. The pages are then merged into a single
1548
+ :class:`ServiceDataRead`.
1549
+
1550
+ Recursion stops when a request for a single entity is still too
1551
+ large: in that case no further requests are made and a
1552
+ :class:`ResponseTooLargeError` is raised, carrying the size of the
1553
+ offending single-entity response and the size the full request would
1554
+ have produced.
1555
+ """
1556
+ entity_type_name = request.request.type_name
1557
+ try:
1558
+ await self._ensure_user_defined_properties(entity_type_name)
1559
+ except _UserDefinedPropertyLoadError as exc:
1560
+ return _value_error(exc.message, exc.error_code)
1561
+ result = await self._read_data_paged(request)
1562
+ if result.success and result.data is not None:
1563
+ entities = [wrapped.entity for wrapped in result.data.data]
1564
+ if not await self._hydrate_entities_for_type(entity_type_name, entities):
1565
+ return _value_error(
1566
+ f"Could not hydrate user-defined properties for {entity_type_name}"
1567
+ )
1568
+ return result
1569
+
1570
+ async def _read_data_once(
1571
+ self,
1572
+ request: ReadDataRequest,
1573
+ ) -> ValueOrErrorPublic_1[ServiceDataRead]:
1574
+ """Issue a single ``ReadData`` invocation without any paging."""
1575
+ request_dict = to_dict(request)
1576
+ result_dict: Any = await self._invoke("ReadData", request_dict)
1577
+ try:
1578
+ result = from_dict(result_dict, ValueOrErrorPublic_1[ServiceDataRead])
1579
+ except CompressedPropertyError as exc:
1580
+ # Name the field and header rather than the opaque generic error.
1581
+ return _value_error(str(exc), ErrorCodes.SerializationError)
1582
+ except (AttributeError, TypeError, ValueError, KeyError):
1583
+ return _deserialization_error()
1584
+ if result is not None:
1585
+ return result
1586
+ return _deserialization_error()
1587
+
1588
+ async def _read_data_paged(
1589
+ self,
1590
+ request: ReadDataRequest,
1591
+ full_request_bytes: Optional[int] = None,
1592
+ ) -> ValueOrErrorPublic_1[ServiceDataRead]:
1593
+ """Read data, splitting into smaller pages on ``ResponseTooLarge``.
1594
+
1595
+ See :meth:`read_data` for the user-facing contract.
1596
+
1597
+ :param full_request_bytes: Serialised size the original (top-level)
1598
+ request would have produced. Threaded through the recursion so a
1599
+ single-entity failure can report it; ``None`` at the top level,
1600
+ where it is taken from the first too-large response.
1601
+ """
1602
+ result = await self._read_data_once(request)
1603
+
1604
+ # Only a too-large response triggers paging; everything else (success
1605
+ # or any other error) is returned to the caller untouched.
1606
+ if result.success or result.error_code != ErrorCodes.ResponseTooLarge:
1607
+ return result
1608
+
1609
+ match = _RESPONSE_TOO_LARGE_RE.search(result.message)
1610
+ if match is None:
1611
+ # The error code says too large but the message isn't in the
1612
+ # expected format, so we can't size the pages — surface as-is.
1613
+ return result
1614
+ would_be = int(match.group(1).replace(",", ""))
1615
+ limit_bytes = int(match.group(2).replace(",", ""))
1616
+ # The first too-large response we see is the full, un-paged request.
1617
+ if full_request_bytes is None:
1618
+ full_request_bytes = would_be
1619
+ if limit_bytes <= 0:
1620
+ return result
1621
+
1622
+ type_request = request.request
1623
+
1624
+ # Resolve an unlimited request (``limit <= 0`` means "all matching
1625
+ # records") to a concrete entity count so the range can be divided
1626
+ # into pages. Only meaningful for a plain data read.
1627
+ limit = type_request.limit
1628
+ if limit <= 0:
1629
+ if type_request.mode != ReadMode.Data:
1630
+ return result
1631
+ count = await self._read_entity_count(request)
1632
+ if count is None:
1633
+ return result
1634
+ limit = count - type_request.offset
1635
+
1636
+ if limit <= 0:
1637
+ # No records remain in range — e.g. the count probe on an unlimited
1638
+ # read found ``offset >= entity_count`` and the response is all
1639
+ # envelope overhead. There is no single entity to blame, so surface
1640
+ # the original error rather than misreporting an overflowing entity.
1641
+ return result
1642
+
1643
+ if limit == 1:
1644
+ # A single entity is still too large — nothing left to split, so
1645
+ # stop making requests and report the failure.
1646
+ raise ResponseTooLargeError(
1647
+ entity_bytes=would_be,
1648
+ full_request_bytes=full_request_bytes,
1649
+ limit_bytes=limit_bytes,
1650
+ )
1651
+
1652
+ # Split the [offset, offset + limit) range into ``num_pages`` pages,
1653
+ # sized so each page is expected to fit within the byte limit. Always
1654
+ # at least two pages so the per-page limit is strictly smaller than the
1655
+ # current one, guaranteeing the recursion makes progress towards the
1656
+ # single-entity base case.
1657
+ num_pages = max(2, math.ceil(would_be / limit_bytes))
1658
+ page_size = max(1, math.ceil(limit / num_pages))
1659
+
1660
+ accumulated: list[WrappedEntity] = []
1661
+ template: Optional[ServiceDataRead] = None
1662
+ # Pending-request maps are keyed by entity ID, so each page contributes
1663
+ # its own entries — merge them rather than keeping only the first page's.
1664
+ pending_update_remove: dict[UUID, RequestId] = {}
1665
+ pending_delete: dict[UUID, RequestId] = {}
1666
+ saw_pending_update_remove = False
1667
+ saw_pending_delete = False
1668
+ offset = type_request.offset
1669
+ end = type_request.offset + limit
1670
+ more_data = False
1671
+
1672
+ while offset < end:
1673
+ page_limit = min(page_size, end - offset)
1674
+ page_request = replace(
1675
+ request,
1676
+ request=replace(type_request, offset=offset, limit=page_limit),
1677
+ )
1678
+ # A single-entity page that is still too large raises
1679
+ # ResponseTooLargeError, which propagates out without reading any
1680
+ # further pages.
1681
+ page_result = await self._read_data_paged(page_request, full_request_bytes)
1682
+ if not page_result.success or page_result.data is None:
1683
+ # Some other error (e.g. a deserialization failure) — surface it.
1684
+ return page_result
1685
+ page_data = page_result.data
1686
+ if template is None:
1687
+ template = page_data
1688
+ accumulated.extend(page_data.data)
1689
+ if page_data.pending_update_remove_request_ids is not None:
1690
+ pending_update_remove.update(page_data.pending_update_remove_request_ids)
1691
+ saw_pending_update_remove = True
1692
+ if page_data.pending_delete_request_ids is not None:
1693
+ pending_delete.update(page_data.pending_delete_request_ids)
1694
+ saw_pending_delete = True
1695
+ more_data = page_data.more_data
1696
+ offset += page_limit
1697
+ if not page_data.more_data:
1698
+ # No further records available within the requested range.
1699
+ break
1700
+
1701
+ if template is None: # pragma: no cover - unreachable while limit > 1
1702
+ return result
1703
+
1704
+ merged = ServiceDataRead(
1705
+ type_name=template.type_name,
1706
+ permissions=template.permissions,
1707
+ data=accumulated,
1708
+ pending_update_remove_request_ids=(
1709
+ pending_update_remove if saw_pending_update_remove else None
1710
+ ),
1711
+ pending_delete_request_ids=(
1712
+ pending_delete if saw_pending_delete else None
1713
+ ),
1714
+ entity_count=template.entity_count,
1715
+ more_data=more_data,
1716
+ )
1717
+ return ValueOrErrorPublic_1(
1718
+ success=True,
1719
+ message="",
1720
+ error_code=ErrorCodes.None_,
1721
+ error_id=None,
1722
+ data=merged,
1723
+ )
1724
+
1725
+ async def _read_entity_count(
1726
+ self,
1727
+ request: ReadDataRequest,
1728
+ ) -> Optional[int]:
1729
+ """Read the total entity count for *request* using ``ReadMode.Count``.
1730
+
1731
+ Used to give an unlimited (``limit <= 0``) read a finite range to
1732
+ page over. Returns ``None`` if the count read fails.
1733
+ """
1734
+ count_request = replace(
1735
+ request,
1736
+ request=replace(request.request, mode=ReadMode.Count),
1737
+ )
1738
+ result = await self._read_data_once(count_request)
1739
+ if result.success and result.data is not None:
1740
+ return result.data.entity_count
1741
+ return None
1742
+
1743
+ async def modify_data(
1744
+ self,
1745
+ request: ModifyDataRequest,
1746
+ ) -> ValueOrErrorPublic_1[RequestId]:
1747
+ """Create, update, or delete entity data."""
1748
+ try:
1749
+ properties_by_type = (
1750
+ dict(zip(
1751
+ request.data,
1752
+ await asyncio.gather(*(
1753
+ self._ensure_user_defined_properties(name) for name in request.data
1754
+ )),
1755
+ ))
1756
+ if request.action in (DataRequestAction.Create, DataRequestAction.Update)
1757
+ else {}
1758
+ )
1759
+ except _UserDefinedPropertyLoadError as exc:
1760
+ return _value_error(exc.message, exc.error_code)
1761
+ request_dict = to_dict(request)
1762
+ if request_dict is None:
1763
+ return _deserialization_error()
1764
+ request_dict["data"] = {
1765
+ type_name: [
1766
+ to_dict(entity, user_defined_properties=properties_by_type.get(type_name))
1767
+ for entity in entities
1768
+ ]
1769
+ for type_name, entities in request.data.items()
1770
+ }
1771
+ result_dict: Any = await self._invoke("ModifyData", request_dict)
1772
+ try:
1773
+ result = from_dict(result_dict, ValueOrErrorPublic_1[RequestId])
1774
+ except (AttributeError, TypeError, ValueError, KeyError):
1775
+ return _deserialization_error()
1776
+ if result is not None:
1777
+ return result
1778
+ return _deserialization_error()
1779
+
1780
+ async def read_connected_data(
1781
+ self,
1782
+ request: ReadConnectedDataRequest,
1783
+ ) -> ValueOrErrorPublic_1[ServiceDataReadConnected]:
1784
+ """Read connected data and hydrate both connection and entity UDPs."""
1785
+ connection_type = request.request.connection_type_name
1786
+ entity_type = request.request.entity_type_name
1787
+ try:
1788
+ await asyncio.gather(
1789
+ self._ensure_user_defined_properties(connection_type),
1790
+ self._ensure_user_defined_properties(entity_type),
1791
+ )
1792
+ except _UserDefinedPropertyLoadError as exc:
1793
+ return _value_error(exc.message, exc.error_code)
1794
+ result_dict: Any = await self._invoke("ReadConnectedData", to_dict(request))
1795
+ try:
1796
+ result = from_dict(
1797
+ result_dict, ValueOrErrorPublic_1[ServiceDataReadConnected]
1798
+ )
1799
+ except CompressedPropertyError as exc:
1800
+ # Name the field and header rather than the opaque generic error.
1801
+ return _value_error(str(exc), ErrorCodes.SerializationError)
1802
+ except (AttributeError, TypeError, ValueError, KeyError):
1803
+ return _deserialization_error()
1804
+ if result is None:
1805
+ return _deserialization_error()
1806
+ if result.success and result.data is not None:
1807
+ connections = [item.connection.entity for item in result.data.data]
1808
+ entities = [item.entity.entity for item in result.data.data]
1809
+ if not await self._hydrate_entities_for_type(connection_type, connections):
1810
+ return _value_error(
1811
+ f"Could not hydrate user-defined properties for {connection_type}"
1812
+ )
1813
+ if not await self._hydrate_entities_for_type(entity_type, entities):
1814
+ return _value_error(
1815
+ f"Could not hydrate user-defined properties for {entity_type}"
1816
+ )
1817
+ return result
1818
+
1819
+ async def create_user_defined_property(
1820
+ self,
1821
+ request: CreateUserDefinedPropertyRequest,
1822
+ ) -> ValueOrErrorPublic_1[UserDefinedPropertyInfo]:
1823
+ """Create a UDP definition and refresh its entity type's cache."""
1824
+ result_dict: Any = await self._invoke(
1825
+ "CreateUserDefinedProperty", to_dict(request),
1826
+ )
1827
+ try:
1828
+ result = from_dict(
1829
+ result_dict, ValueOrErrorPublic_1[UserDefinedPropertyInfo]
1830
+ )
1831
+ except (AttributeError, TypeError, ValueError, KeyError):
1832
+ return _deserialization_error()
1833
+ if result is None:
1834
+ return _deserialization_error()
1835
+ if result.success:
1836
+ self._evict_user_defined_properties({request.entity_type_name})
1837
+ try:
1838
+ await self._ensure_user_defined_properties(request.entity_type_name)
1839
+ except _UserDefinedPropertyLoadError as exc:
1840
+ return _value_error(exc.message, exc.error_code)
1841
+ return result
1842
+
1843
+ async def update_user_defined_property(
1844
+ self,
1845
+ request: UpdateUserDefinedPropertyRequest,
1846
+ ) -> ValueOrErrorPublic_1[UserDefinedPropertyInfo]:
1847
+ """Update a UDP definition and clear all caches on success."""
1848
+ result_dict: Any = await self._invoke(
1849
+ "UpdateUserDefinedProperty", to_dict(request),
1850
+ )
1851
+ try:
1852
+ result = from_dict(
1853
+ result_dict, ValueOrErrorPublic_1[UserDefinedPropertyInfo]
1854
+ )
1855
+ except (AttributeError, TypeError, ValueError, KeyError):
1856
+ return _deserialization_error()
1857
+ if result is None:
1858
+ return _deserialization_error()
1859
+ if result.success:
1860
+ await self.invalidate_user_defined_property_cache()
1861
+ return result
1862
+
1863
+ # ------------------------------------------------------------------
1864
+ # File methods
1865
+ # ------------------------------------------------------------------
1866
+ #
1867
+ # These are thin wrappers over the file-store hub methods. The bytes
1868
+ # themselves never pass through the hub: ``request_file_upload`` returns an
1869
+ # :class:`UploadGrant` locating a storage endpoint, the client POSTs the
1870
+ # bytes there directly (see :mod:`filament._file_upload`), then
1871
+ # ``complete_file_upload`` confirms arrival. A future ``upload_file``
1872
+ # helper will orchestrate the whole sequence.
1873
+
1874
+ async def request_file_upload(
1875
+ self,
1876
+ request: FileUploadRequest,
1877
+ ) -> ValueOrErrorPublic_1[UploadGrant]:
1878
+ """Request a grant to upload one file into one slot.
1879
+
1880
+ The returned :class:`UploadGrant` carries the storage URL, method, and
1881
+ policy fields the client submits the bytes with; it does **not** move any
1882
+ bytes itself. If the store advertises a checksum algorithm (see
1883
+ :attr:`server_capabilities`), set :attr:`FileUploadRequest.checksum`
1884
+ before calling so the upload is verified at completion.
1885
+ """
1886
+ result_dict: Any = await self._invoke("RequestFileUpload", to_dict(request))
1887
+ try:
1888
+ result = from_dict(result_dict, ValueOrErrorPublic_1[UploadGrant])
1889
+ except (AttributeError, TypeError, ValueError, KeyError):
1890
+ return _deserialization_error()
1891
+ if result is not None:
1892
+ return result
1893
+ return _deserialization_error()
1894
+
1895
+ async def refresh_file_upload_grant(
1896
+ self,
1897
+ file_id: UUID,
1898
+ ) -> ValueOrErrorPublic_1[UploadGrant]:
1899
+ """Re-sign the grant for an in-progress upload.
1900
+
1901
+ Use when a grant expires mid-transfer. Unlike
1902
+ :meth:`request_file_upload` this does **not** take a second reservation,
1903
+ so it is safe to call repeatedly for the same *file_id*.
1904
+ """
1905
+ result_dict: Any = await self._invoke("RefreshFileUploadGrant", str(file_id))
1906
+ try:
1907
+ result = from_dict(result_dict, ValueOrErrorPublic_1[UploadGrant])
1908
+ except (AttributeError, TypeError, ValueError, KeyError):
1909
+ return _deserialization_error()
1910
+ if result is not None:
1911
+ return result
1912
+ return _deserialization_error()
1913
+
1914
+ async def complete_file_upload(
1915
+ self,
1916
+ file_id: UUID,
1917
+ ) -> ValueOrErrorPublic_1[FileEntity]:
1918
+ """Confirm an upload's bytes arrived, returning the completed file.
1919
+
1920
+ The server verifies the stored object against what was declared (size,
1921
+ content type, and checksum where both sides have one). A checksum
1922
+ mismatch returns :attr:`ErrorCodes.ChecksumMismatch`; the file is marked
1923
+ failed and the caller should request a fresh upload rather than retry.
1924
+ """
1925
+ request = FileUploadCompletion(file_id=file_id)
1926
+ result_dict: Any = await self._invoke("CompleteFileUpload", to_dict(request))
1927
+ try:
1928
+ result = from_dict(result_dict, ValueOrErrorPublic_1[FileEntity])
1929
+ except (AttributeError, TypeError, ValueError, KeyError):
1930
+ return _deserialization_error()
1931
+ if result is not None:
1932
+ return result
1933
+ return _deserialization_error()
1934
+
1935
+ async def cancel_file_upload(
1936
+ self,
1937
+ file_id: UUID,
1938
+ ) -> SuccessOrErrorPublic:
1939
+ """Abandon an upload, releasing its reservation immediately.
1940
+
1941
+ Idempotent — safe to fire on abort without knowing whether the upload
1942
+ already completed.
1943
+ """
1944
+ result_dict: Any = await self._invoke("CancelFileUpload", str(file_id))
1945
+ try:
1946
+ result = from_dict(result_dict, SuccessOrErrorPublic)
1947
+ except (AttributeError, TypeError, ValueError, KeyError):
1948
+ return _error_result_public(
1949
+ "Failed to deserialize CancelFileUpload response"
1950
+ )
1951
+ if result is not None:
1952
+ return result
1953
+ return _error_result_public("Failed to deserialize CancelFileUpload response")
1954
+
1955
+ async def get_file_urls(
1956
+ self,
1957
+ file_ids: Sequence[UUID],
1958
+ ) -> ValueOrErrorPublic_1[dict[UUID, FileReference]]:
1959
+ """Mint read URLs for a batch of files.
1960
+
1961
+ Returns one :class:`FileReference` per requested id, keyed by file id.
1962
+ Results are per-file: a stale or unreadable id yields a failed
1963
+ :class:`FileReference` without failing the others. A file the caller
1964
+ cannot read and one that does not exist are indistinguishable, by design.
1965
+ """
1966
+ request = GetFileUrlsRequest(file_ids=list(file_ids))
1967
+ result_dict: Any = await self._invoke("GetFileUrls", to_dict(request))
1968
+ try:
1969
+ result = from_dict(
1970
+ result_dict, ValueOrErrorPublic_1[dict[UUID, FileReference]]
1971
+ )
1972
+ except (AttributeError, TypeError, ValueError, KeyError):
1973
+ return _deserialization_error()
1974
+ if result is not None:
1975
+ return result
1976
+ return _deserialization_error()
1977
+
1978
+ async def upload_file(
1979
+ self,
1980
+ *,
1981
+ name: str,
1982
+ content_type: str,
1983
+ data: bytes,
1984
+ reference_type: str,
1985
+ reference_id: UUID,
1986
+ reference_property: str,
1987
+ description: Optional[str] = None,
1988
+ http_client: Optional[httpx.AsyncClient] = None,
1989
+ ) -> ValueOrErrorPublic_1[FileEntity]:
1990
+ """Upload one file end-to-end and return the completed :class:`FileEntity`.
1991
+
1992
+ Orchestrates the full flow: compute whatever checksum the store requires
1993
+ (from :attr:`server_capabilities`), request an upload grant, POST the
1994
+ bytes directly to storage, then confirm completion. If the transfer
1995
+ fails the grant is refreshed once and retried (a likely cause is expiry,
1996
+ and refresh takes no new reservation); if it still fails the reservation
1997
+ is cancelled and a failed result is returned.
1998
+
1999
+ :param data: The file bytes. ``size`` and any checksum are derived from
2000
+ these, so the whole file must be in memory (streaming is a planned
2001
+ follow-up).
2002
+ :param http_client: Optional httpx client to reuse for the storage
2003
+ transfer. When omitted, a short-lived client is created and closed.
2004
+ """
2005
+ # 1. Checksum in the store's declared algorithm (None_ → no checksum).
2006
+ algorithm = FileChecksumAlgorithm.None_
2007
+ caps = self._server_capabilities
2008
+ if caps is not None and caps.files is not None:
2009
+ algorithm = caps.files.checksum_algorithm
2010
+ try:
2011
+ checksum = compute_checksum(data, algorithm)
2012
+ except (RuntimeError, ValueError) as exc:
2013
+ # Crc32cBase64 without the optional google-crc32c dependency, or an
2014
+ # algorithm this client does not know. Either way the upload cannot
2015
+ # be attempted — surface it as a result, not an exception, since no
2016
+ # reservation has been taken yet.
2017
+ return _value_error(str(exc), ErrorCodes.NotSupported)
2018
+
2019
+ # 2. Request the grant.
2020
+ grant_result = await self.request_file_upload(
2021
+ FileUploadRequest(
2022
+ name=name,
2023
+ content_type=content_type,
2024
+ size=len(data),
2025
+ reference_type=reference_type,
2026
+ reference_id=reference_id,
2027
+ reference_property=reference_property,
2028
+ description=description,
2029
+ checksum=checksum,
2030
+ )
2031
+ )
2032
+ if not grant_result.success or grant_result.data is None:
2033
+ return _propagate_failure(grant_result)
2034
+ grant = grant_result.data
2035
+ file_id = grant.file_id
2036
+
2037
+ # 3. Transfer the bytes, refreshing the grant once on failure.
2038
+ owns_client = http_client is None
2039
+ client = http_client if http_client is not None else httpx.AsyncClient()
2040
+ try:
2041
+ ok, message, error_code = await self._submit_upload(
2042
+ client, grant, data, content_type, name
2043
+ )
2044
+ if not ok:
2045
+ refresh = await self.refresh_file_upload_grant(file_id)
2046
+ if refresh.success and refresh.data is not None:
2047
+ grant = refresh.data
2048
+ ok, message, error_code = await self._submit_upload(
2049
+ client, grant, data, content_type, name
2050
+ )
2051
+ if not ok:
2052
+ await self._release_upload_reservation(file_id)
2053
+ return _value_error(message, error_code)
2054
+
2055
+ # 4. Confirm arrival; the server verifies size / type / checksum.
2056
+ # Inside the try so a cancellation or hub failure while completion
2057
+ # is in flight still releases the reservation below.
2058
+ return await self.complete_file_upload(file_id)
2059
+ except asyncio.CancelledError:
2060
+ # The reservation outlives the cancelled task and keeps consuming
2061
+ # quota, so release it before unwinding. Shielded so the in-flight
2062
+ # hub call is not itself cancelled.
2063
+ await self._release_upload_reservation(file_id, shielded=True)
2064
+ raise
2065
+ except Exception:
2066
+ # The grant refresh or the completion call raised rather than
2067
+ # returning a failed result — a dropped hub connection surfaces this
2068
+ # way. Same leak, but no shield needed: this task is not being
2069
+ # cancelled, so the cleanup call can run normally.
2070
+ await self._release_upload_reservation(file_id)
2071
+ raise
2072
+ finally:
2073
+ if owns_client:
2074
+ await client.aclose()
2075
+
2076
+ async def _release_upload_reservation(
2077
+ self,
2078
+ file_id: UUID,
2079
+ *,
2080
+ shielded: bool = False,
2081
+ ) -> None:
2082
+ """Best-effort release of an upload reservation.
2083
+
2084
+ Never raises: a failure here must not mask the error that prompted the
2085
+ release. Safe to call even when the upload may already have completed
2086
+ server-side, since :meth:`cancel_file_upload` is idempotent.
2087
+
2088
+ :param shielded: Protect the hub call from a cancellation already being
2089
+ delivered to this task, so the reservation is still released.
2090
+ """
2091
+ call = self.cancel_file_upload(file_id)
2092
+ try:
2093
+ await (asyncio.shield(call) if shielded else call)
2094
+ except Exception:
2095
+ logger.warning(
2096
+ "Failed to cancel upload reservation for %s",
2097
+ file_id,
2098
+ exc_info=True,
2099
+ )
2100
+
2101
+ async def _submit_upload(
2102
+ self,
2103
+ http_client: httpx.AsyncClient,
2104
+ grant: UploadGrant,
2105
+ data: bytes,
2106
+ content_type: str,
2107
+ filename: str,
2108
+ ) -> tuple[bool, str, ErrorCodes]:
2109
+ """POST *data* to the storage endpoint described by *grant*.
2110
+
2111
+ Returns ``(ok, message, error_code)``; ``message`` and ``error_code``
2112
+ are only meaningful when ``ok`` is False.
2113
+ """
2114
+ request = build_upload_request(
2115
+ url=grant.url,
2116
+ method=grant.method,
2117
+ fields=grant.fields,
2118
+ headers=grant.headers,
2119
+ data=data,
2120
+ content_type=content_type,
2121
+ filename=filename,
2122
+ )
2123
+ try:
2124
+ response = await http_client.send(request)
2125
+ except httpx.HTTPError as exc:
2126
+ return False, f"Upload transfer failed: {exc}", ErrorCodes.ConnectionError
2127
+ if response.is_success:
2128
+ return True, "", ErrorCodes.None_
2129
+ body = response.text[:500]
2130
+ return (
2131
+ False,
2132
+ f"Storage rejected upload ({response.status_code}): {body}",
2133
+ ErrorCodes.RequestError,
2134
+ )
2135
+
2136
+ async def download_file(
2137
+ self,
2138
+ file_id: UUID,
2139
+ http_client: Optional[httpx.AsyncClient] = None,
2140
+ ) -> ValueOrErrorPublic_1[bytes]:
2141
+ """Fetch one file's bytes via a freshly minted read URL.
2142
+
2143
+ Resolves a signed URL with :meth:`get_file_urls`, then GETs the bytes
2144
+ from storage. Returns the bytes on success, or a failed result carrying
2145
+ the reason the file could not be resolved or fetched. A file the caller
2146
+ cannot read and one that does not exist are indistinguishable, by design.
2147
+ """
2148
+ urls = await self.get_file_urls([file_id])
2149
+ if not urls.success or urls.data is None:
2150
+ return _propagate_failure(urls)
2151
+ reference = urls.data.get(file_id)
2152
+ if reference is None:
2153
+ return _value_error(
2154
+ f"No result returned for file {file_id}", ErrorCodes.NoData
2155
+ )
2156
+ return await self.download_file_reference(reference, http_client=http_client)
2157
+
2158
+ async def download_file_reference(
2159
+ self,
2160
+ reference: FileReference,
2161
+ http_client: Optional[httpx.AsyncClient] = None,
2162
+ ) -> ValueOrErrorPublic_1[bytes]:
2163
+ """Fetch the bytes for an already-resolved :class:`FileReference`.
2164
+
2165
+ Use this when you already hold a reference — e.g. ``UserEntity.image``,
2166
+ which is populated automatically from its ``[FileDataProperty]`` read
2167
+ projection (a raw projection string can also be parsed with
2168
+ :func:`filament.file_reference_from_json`) — to download directly,
2169
+ skipping the extra :meth:`get_file_urls` round trip. Returns the bytes,
2170
+ or a failed result if the reference did not resolve or the transfer
2171
+ failed.
2172
+ """
2173
+ if not reference.success or reference.url is None:
2174
+ return _value_error(
2175
+ reference.message or "File could not be resolved",
2176
+ reference.error_code,
2177
+ )
2178
+
2179
+ owns_client = http_client is None
2180
+ client = http_client if http_client is not None else httpx.AsyncClient()
2181
+ try:
2182
+ response = await client.get(reference.url)
2183
+ except httpx.HTTPError as exc:
2184
+ return _value_error(
2185
+ f"Download transfer failed: {exc}", ErrorCodes.ConnectionError
2186
+ )
2187
+ finally:
2188
+ if owns_client:
2189
+ await client.aclose()
2190
+
2191
+ if not response.is_success:
2192
+ return _value_error(
2193
+ f"Storage rejected download ({response.status_code})",
2194
+ ErrorCodes.RequestError,
2195
+ )
2196
+ return ValueOrErrorPublic_1(
2197
+ success=True,
2198
+ message="",
2199
+ error_code=ErrorCodes.None_,
2200
+ error_id=None,
2201
+ data=response.content,
2202
+ )
2203
+
2204
+ async def subscribe(
2205
+ self,
2206
+ subscription: SubscriptionConfig,
2207
+ callback: Callback,
2208
+ on_error: Optional[Callback] = None,
2209
+ ) -> ValueOrErrorPublic_1[SubscriptionId]:
2210
+ """Subscribe to data updates and register a callback.
2211
+
2212
+ The *callback* is called with a :class:`ServiceDataUpdate` argument
2213
+ whenever the server sends a ``DataUpdated`` event for this subscription.
2214
+ It may be a sync or async callable.
2215
+
2216
+ The optional *on_error* callback is called when an update for this
2217
+ subscription cannot be delivered: with a
2218
+ :class:`DataUpdateRejectedNotification` when the server drops it
2219
+ because it would exceed the client's negotiated ``max_size``, or with
2220
+ a :class:`~filament.CompressedPropertyError` when a compressed
2221
+ property in it fails to decode. If omitted, these are logged at
2222
+ WARNING level.
2223
+
2224
+ Returns a client-generated :class:`SubscriptionId`. Use this ID with
2225
+ :meth:`unsubscribe` to remove the callback. The backend is always
2226
+ called and may return the same subscription ID for duplicate
2227
+ type/permission combinations. The backend ``Unsubscribe`` is only
2228
+ sent when the last client subscription sharing a backend ID is removed.
2229
+ """
2230
+ try:
2231
+ await self._ensure_user_defined_properties(subscription.type_name)
2232
+ except _UserDefinedPropertyLoadError as exc:
2233
+ return _value_error(exc.message, exc.error_code)
2234
+ subscription_dict = to_dict(subscription)
2235
+ result_dict: Any = await self._invoke("Subscribe", subscription_dict)
2236
+ try:
2237
+ result = from_dict(result_dict, ValueOrErrorPublic_1[SubscriptionId])
2238
+ except (AttributeError, TypeError, ValueError, KeyError):
2239
+ return _deserialization_error()
2240
+ if result is None:
2241
+ return _deserialization_error()
2242
+
2243
+ if result.success and result.data is not None:
2244
+ backend_id = result.data.id
2245
+ client_id = uuid7()
2246
+
2247
+ # Track the mapping
2248
+ if backend_id not in self._backend_to_client:
2249
+ self._backend_to_client[backend_id] = set()
2250
+ self._backend_to_client[backend_id].add(client_id)
2251
+ self._client_callbacks[client_id] = callback
2252
+ if on_error is not None:
2253
+ self._client_error_callbacks[client_id] = on_error
2254
+ self._client_to_backend[client_id] = backend_id
2255
+
2256
+ # Return the client-generated subscription ID
2257
+ return ValueOrErrorPublic_1(
2258
+ success=result.success,
2259
+ message=result.message,
2260
+ error_code=result.error_code,
2261
+ error_id=None,
2262
+ data=SubscriptionId(id=client_id),
2263
+ )
2264
+
2265
+ return result
2266
+
2267
+ async def unsubscribe(
2268
+ self,
2269
+ subscription_id: SubscriptionId,
2270
+ ) -> SuccessOrErrorPublic:
2271
+ """Cancel a subscription by its client-generated ID.
2272
+
2273
+ The backend ``Unsubscribe`` call is only made when the last client
2274
+ subscription sharing the same backend subscription ID is removed.
2275
+ """
2276
+ client_id = subscription_id.id
2277
+ backend_id = self._client_to_backend.pop(client_id, None)
2278
+ self._client_callbacks.pop(client_id, None)
2279
+ self._client_error_callbacks.pop(client_id, None)
2280
+
2281
+ if backend_id is not None:
2282
+ client_ids = self._backend_to_client.get(backend_id)
2283
+ if client_ids is not None:
2284
+ client_ids.discard(client_id)
2285
+ if not client_ids:
2286
+ # Last client for this backend subscription — tell backend
2287
+ del self._backend_to_client[backend_id]
2288
+ if backend_id == self._user_defined_subscription_id:
2289
+ # The private UDP-definition subscription shares this
2290
+ # backend ID. Sending Unsubscribe would cancel it while
2291
+ # _user_defined_subscription_id still points at it, and
2292
+ # _reconcile_user_defined_property_subscription would
2293
+ # then early-return and never restore it. Leave the
2294
+ # backend subscription — and its in-flight buffers —
2295
+ # alone; once reconcile moves off this ID it sends the
2296
+ # deferred Unsubscribe itself.
2297
+ return SuccessOrErrorPublic(
2298
+ success=True,
2299
+ message="",
2300
+ error_code=ErrorCodes.None_,
2301
+ error_id=None,
2302
+ )
2303
+ # Drop any in-flight partial reassemblies / poisoned
2304
+ # sequences for this backend sub — nothing left to
2305
+ # dispatch them to.
2306
+ stale_buffer_keys = [
2307
+ k for k in self._part_buffers if k[0] == backend_id
2308
+ ]
2309
+ for k in stale_buffer_keys:
2310
+ del self._part_buffers[k]
2311
+ self._poisoned_part_buffer_keys = {
2312
+ k for k in self._poisoned_part_buffer_keys if k[0] != backend_id
2313
+ }
2314
+ # Likewise complete updates still queued for dispatch: hydrating
2315
+ # them would cost hub calls for a callback that no longer exists.
2316
+ # UDP definition pushes stay: this ID may be a private subscription
2317
+ # that reconciliation has since replaced, and the backend does not
2318
+ # resend the push on the new one.
2319
+ queued = [
2320
+ e for e in self._data_update_queue if e[0] != backend_id or e[3]
2321
+ ]
2322
+ self._data_update_queue.clear()
2323
+ self._data_update_queue.extend(queued)
2324
+ backend_sub = SubscriptionId(id=backend_id)
2325
+ result_dict = await self._invoke(
2326
+ "Unsubscribe", to_dict(backend_sub),
2327
+ )
2328
+ result = from_dict(result_dict, SuccessOrErrorPublic)
2329
+ if result is not None:
2330
+ return result
2331
+ return _error_result_public(
2332
+ "Failed to deserialize Unsubscribe response",
2333
+ )
2334
+
2335
+ # No backend call needed (or unknown client ID) — return success
2336
+ return SuccessOrErrorPublic(
2337
+ success=True,
2338
+ message="",
2339
+ error_code=ErrorCodes.None_,
2340
+ error_id=None,
2341
+ )
2342
+
2343
+ async def unsubscribe_all(self) -> SuccessOrErrorPublic:
2344
+ """Cancel all active subscriptions."""
2345
+ cached_type_names = list(self._user_defined_properties)
2346
+ result_dict = await self._invoke("UnsubscribeAll")
2347
+ self._backend_to_client.clear()
2348
+ self._client_callbacks.clear()
2349
+ self._client_error_callbacks.clear()
2350
+ self._client_to_backend.clear()
2351
+ self._part_buffers.clear()
2352
+ self._poisoned_part_buffer_keys.clear()
2353
+ self._data_update_queue.clear()
2354
+ self._user_defined_subscription_id = None
2355
+ self._user_defined_subscription_types = frozenset()
2356
+ result = from_dict(result_dict, SuccessOrErrorPublic)
2357
+ if result is None:
2358
+ return _error_result_public("Failed to deserialize UnsubscribeAll response")
2359
+ if result.success and cached_type_names:
2360
+ await self.invalidate_user_defined_property_cache()
2361
+ refreshes = await asyncio.gather(
2362
+ *(
2363
+ self._ensure_user_defined_properties(name, reconcile=False)
2364
+ for name in cached_type_names
2365
+ ),
2366
+ return_exceptions=True,
2367
+ )
2368
+ for name, refresh in zip(cached_type_names, refreshes, strict=True):
2369
+ if isinstance(refresh, BaseException):
2370
+ logger.error(
2371
+ "Could not restore UDP metadata subscription for %s: %s",
2372
+ name,
2373
+ refresh,
2374
+ )
2375
+ try:
2376
+ await self._reconcile_user_defined_property_subscription()
2377
+ except _UserDefinedPropertyLoadError:
2378
+ logger.exception(
2379
+ "Could not restore UDP definition subscription after "
2380
+ "UnsubscribeAll"
2381
+ )
2382
+ return result
2383
+
2384
+
2385
+ class _UserDefinedPropertyLoadError(Exception):
2386
+ """Internal error carrying the backend envelope details for a cache load."""
2387
+
2388
+ def __init__(self, message: str, error_code: ErrorCodes) -> None:
2389
+ super().__init__(message)
2390
+ self.message = message
2391
+ self.error_code = error_code
2392
+
2393
+ def _deserialization_error() -> ValueOrErrorPublic_1[Any]:
2394
+ """Return a failed ``ValueOrErrorPublic_1`` for deserialization failures."""
2395
+ return ValueOrErrorPublic_1(
2396
+ success=False,
2397
+ message="Failed to deserialize server response",
2398
+ error_code=ErrorCodes.InternalError,
2399
+ error_id=None,
2400
+ data=None,
2401
+ )
2402
+
2403
+
2404
+ def _value_error(
2405
+ message: str,
2406
+ error_code: ErrorCodes = ErrorCodes.InternalError,
2407
+ ) -> ValueOrErrorPublic_1[Any]:
2408
+ """Return a failed generic value envelope."""
2409
+ return ValueOrErrorPublic_1(
2410
+ success=False,
2411
+ message=message,
2412
+ error_code=error_code,
2413
+ error_id=None,
2414
+ data=None,
2415
+ )
2416
+
2417
+
2418
+ def _propagate_failure(
2419
+ source: ValueOrErrorPublic_1[Any],
2420
+ ) -> ValueOrErrorPublic_1[Any]:
2421
+ """Re-wrap a failed result under a different data type, dropping its payload."""
2422
+ return ValueOrErrorPublic_1(
2423
+ success=False,
2424
+ message=source.message,
2425
+ error_code=source.error_code,
2426
+ error_id=source.error_id,
2427
+ data=None,
2428
+ )
2429
+
2430
+
2431
+ def _error_result_public(message: str) -> SuccessOrErrorPublic:
2432
+ """Return a failed ``SuccessOrErrorPublic`` with the given message."""
2433
+ return SuccessOrErrorPublic(
2434
+ success=False,
2435
+ message=message,
2436
+ error_code=ErrorCodes.InternalError,
2437
+ error_id=None,
2438
+ )
2439
+
2440
+
2441
+ async def _invoke_callback(callback: Callback, *args: Any) -> None:
2442
+ """Invoke a callback that may be sync or async."""
2443
+ if inspect.iscoroutinefunction(callback):
2444
+ await callback(*args)
2445
+ else:
2446
+ callback(*args)