volcano-sdk-python 0.13.0__py3-none-any.whl → 0.13.1__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.
volcano_sdk/realtime.py CHANGED
@@ -3,10 +3,10 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  import asyncio
6
- import importlib
7
6
  import inspect
8
- from collections.abc import Awaitable, Callable, Mapping
7
+ from collections.abc import Awaitable, Callable, Iterator, Mapping
9
8
  from dataclasses import dataclass, field, replace
9
+ from itertools import count
10
10
  from types import MappingProxyType
11
11
  from typing import (
12
12
  TYPE_CHECKING,
@@ -15,11 +15,11 @@ from typing import (
15
15
  Protocol,
16
16
  TypeAlias,
17
17
  TypeVar,
18
- cast,
19
18
  overload,
20
19
  )
21
- from urllib.parse import quote, urlsplit, urlunsplit
20
+ from urllib.parse import quote, urlencode, urlsplit, urlunsplit
22
21
 
22
+ from centrifuge import CentrifugeError, Client
23
23
  from typing_extensions import override
24
24
 
25
25
  from ._callbacks import require_callable
@@ -55,14 +55,10 @@ ChannelType: TypeAlias = Literal["broadcast", "presence", "postgres"]
55
55
  PostgresEvent: TypeAlias = Literal["INSERT", "UPDATE", "DELETE"]
56
56
  PostgresListenerEvent: TypeAlias = Literal["INSERT", "UPDATE", "DELETE", "*"]
57
57
  PostgresChangeCallback = Callable[["PostgresChange"], object]
58
- SUPPORTED_CHANNEL_TYPES = frozenset({"broadcast", "presence", "postgres"})
59
58
  POSTGRES_EVENTS = frozenset({"INSERT", "UPDATE", "DELETE"})
60
59
  POSTGRES_CHANNEL_SEGMENTS = 3
61
60
  POSTGRES_PUBLICATION_SEGMENTS = 5
62
- CENTRIFUGE_ERROR = cast(
63
- "type[Exception]",
64
- importlib.import_module("centrifuge").CentrifugeError,
65
- )
61
+ CENTRIFUGE_ERROR: type[Exception] = CentrifugeError
66
62
  CALLBACK_QUEUE_LIMIT = 128
67
63
  POSTGRES_QUEUE_LIMIT = 128
68
64
  POSTGRES_BATCH_WINDOW_MS = 20
@@ -93,16 +89,24 @@ def _empty_presence_data() -> Mapping[str, JSONValue]:
93
89
  return MappingProxyType({})
94
90
 
95
91
 
92
+ def _freeze_mapping(value: Mapping[str, JSONValue]) -> Mapping[str, JSONValue]:
93
+ return MappingProxyType({key: _freeze_json(item) for key, item in value.items()})
94
+
95
+
96
96
  def _consume_presence_result(task: asyncio.Task[object]) -> None:
97
97
  if not task.cancelled():
98
98
  _ = task.exception()
99
99
 
100
100
 
101
101
  def _validate_channel_type(channel_type: str) -> ChannelType:
102
- if channel_type not in SUPPORTED_CHANNEL_TYPES:
103
- message = f"unsupported realtime channel type: {channel_type}"
104
- raise ValueError(message)
105
- return cast("ChannelType", channel_type)
102
+ if channel_type == "broadcast":
103
+ return "broadcast"
104
+ if channel_type == "presence":
105
+ return "presence"
106
+ if channel_type == "postgres":
107
+ return "postgres"
108
+ message = f"unsupported realtime channel type: {channel_type}"
109
+ raise ValueError(message)
106
110
 
107
111
 
108
112
  def _postgres_route_matches(candidate: str, publication: str) -> bool:
@@ -153,8 +157,7 @@ class RealtimePresenceInfo:
153
157
 
154
158
  def __post_init__(self) -> None:
155
159
  """Defensively freeze nested connection metadata."""
156
- frozen = _freeze_json(cast("JSONValue", dict(self.data)))
157
- object.__setattr__(self, "data", cast("Mapping[str, JSONValue]", frozen))
160
+ object.__setattr__(self, "data", _freeze_mapping(self.data))
158
161
 
159
162
 
160
163
  @dataclass(frozen=True, slots=True)
@@ -174,11 +177,9 @@ class PostgresChange:
174
177
  def __post_init__(self) -> None:
175
178
  """Defensively freeze nested row and identifier values."""
176
179
  if self.record is not None:
177
- frozen_record = _freeze_json(cast("JSONValue", dict(self.record)))
178
- object.__setattr__(self, "record", frozen_record)
180
+ object.__setattr__(self, "record", _freeze_mapping(self.record))
179
181
  if self.old_record is not None:
180
- frozen_old_record = _freeze_json(cast("JSONValue", dict(self.old_record)))
181
- object.__setattr__(self, "old_record", frozen_old_record)
182
+ object.__setattr__(self, "old_record", _freeze_mapping(self.old_record))
182
183
  object.__setattr__(self, "id", _freeze_json(self.id))
183
184
 
184
185
 
@@ -246,7 +247,7 @@ def _postgres_fetch_config(
246
247
  @dataclass(frozen=True, slots=True)
247
248
  class _PostgresDeliveryIdentity:
248
249
  session_lineage: SessionOperations | None
249
- subscription_epoch: int
250
+ subscription_epoch: object
250
251
 
251
252
 
252
253
  @dataclass(frozen=True, slots=True)
@@ -260,51 +261,66 @@ class _CallbackDelivery:
260
261
  event: str
261
262
  data: object
262
263
  postgres_identity: _PostgresDeliveryIdentity | None = None
263
- delivery_epoch: int | None = None
264
+ delivery_epoch: object | None = None
265
+
266
+
267
+ def _is_postgres_event(value: object) -> TypeGuard[PostgresEvent]:
268
+ return isinstance(value, str) and value in POSTGRES_EVENTS
269
+
270
+
271
+ def _is_object_mapping(value: object) -> TypeGuard[Mapping[object, object]]:
272
+ return isinstance(value, Mapping)
273
+
274
+
275
+ def _is_object_dict(value: object) -> TypeGuard[dict[object, object]]:
276
+ return isinstance(value, dict)
277
+
278
+
279
+ def _is_object_sequence(value: object) -> TypeGuard[list[object] | tuple[object, ...]]:
280
+ return isinstance(value, (list, tuple))
264
281
 
265
282
 
266
283
  def _postgres_change(data: object) -> PostgresChange | None:
267
- if not isinstance(data, Mapping):
284
+ if not _is_object_mapping(data):
285
+ return None
286
+ event = data.get("type")
287
+ schema = data.get("schema")
288
+ table = data.get("table")
289
+ timestamp = data.get("timestamp")
290
+ mode = data.get("mode")
291
+ record = data.get("record")
292
+ old_record = data.get("old_record")
293
+ raw_columns = data.get("columns")
294
+ identifier = data.get("id")
295
+ if not _is_json_record_or_none(record) or not _is_json_record_or_none(old_record):
268
296
  return None
269
- typed_data = cast("Mapping[str, object]", data)
270
- event = typed_data.get("type")
271
- schema = typed_data.get("schema")
272
- table = typed_data.get("table")
273
- timestamp = typed_data.get("timestamp")
274
- mode = typed_data.get("mode")
275
- record = typed_data.get("record")
276
- old_record = typed_data.get("old_record")
277
- raw_columns = typed_data.get("columns")
278
297
  if (
279
- event not in POSTGRES_EVENTS
298
+ not _is_postgres_event(event)
280
299
  or not isinstance(schema, str)
281
300
  or not isinstance(table, str)
282
301
  or not isinstance(timestamp, str)
283
- or not _postgres_records_valid(record, old_record)
302
+ or not _is_json_value(identifier)
303
+ or not _postgres_mode(mode)
284
304
  ):
285
305
  return None
286
- if not _postgres_mode(mode):
287
- return None
288
306
  valid_columns, columns = _postgres_columns(raw_columns)
289
307
  if not valid_columns:
290
308
  return None
291
309
  return PostgresChange(
292
- type=cast("PostgresEvent", event),
310
+ type=event,
293
311
  schema=schema,
294
312
  table=table,
295
- record=cast("Mapping[str, JSONValue] | None", record),
296
- old_record=cast("Mapping[str, JSONValue] | None", old_record),
313
+ record=record,
314
+ old_record=old_record,
297
315
  columns=columns,
298
316
  timestamp=timestamp,
299
- id=cast("JSONValue", typed_data.get("id")),
317
+ id=identifier,
300
318
  mode=mode,
301
319
  )
302
320
 
303
321
 
304
- def _postgres_records_valid(record: object, old_record: object) -> bool:
305
- return (record is None or isinstance(record, Mapping)) and (
306
- old_record is None or isinstance(old_record, Mapping)
307
- )
322
+ def _is_json_record_or_none(value: object) -> TypeGuard[Mapping[str, JSONValue] | None]:
323
+ return value is None or _is_json_record(value)
308
324
 
309
325
 
310
326
  def _postgres_mode(value: object) -> TypeGuard[Literal["lightweight"] | None]:
@@ -314,10 +330,10 @@ def _postgres_mode(value: object) -> TypeGuard[Literal["lightweight"] | None]:
314
330
  def _postgres_columns(value: object) -> tuple[bool, tuple[str, ...] | None]:
315
331
  if value is None:
316
332
  return True, None
317
- if not isinstance(value, (list, tuple)):
333
+ if not _is_object_sequence(value):
318
334
  return False, None
319
335
  columns: list[str] = []
320
- for column in cast("list[object] | tuple[object, ...]", value):
336
+ for column in value:
321
337
  if not isinstance(column, str):
322
338
  return False, None
323
339
  columns.append(column)
@@ -407,15 +423,16 @@ class CentrifugeConnection(Protocol):
407
423
  def new_subscription(
408
424
  self,
409
425
  name: str,
426
+ /,
410
427
  *,
411
428
  events: object,
412
- join_leave: bool = False,
413
- recoverable: bool = False,
429
+ join_leave: bool,
430
+ recoverable: bool,
414
431
  ) -> CentrifugeSubscription:
415
432
  """Create a subscription for a remote channel."""
416
433
  ...
417
434
 
418
- def remove_subscription(self, subscription: CentrifugeSubscription) -> None:
435
+ def remove_subscription(self, subscription: CentrifugeSubscription, /) -> None:
419
436
  """Remove an unsubscribed channel from the connection registry."""
420
437
  ...
421
438
 
@@ -435,21 +452,6 @@ class CentrifugeFactory(Protocol):
435
452
  ...
436
453
 
437
454
 
438
- class CentrifugeConstructor(Protocol):
439
- """Describe the dynamically imported Centrifuge client constructor."""
440
-
441
- def __call__(
442
- self,
443
- address: str,
444
- *,
445
- events: object,
446
- token: str,
447
- get_token: Callable[[], Awaitable[str]],
448
- ) -> object:
449
- """Construct the dynamically imported Centrifuge client."""
450
- ...
451
-
452
-
453
455
  class Publication(Protocol):
454
456
  """Publication payload received from Centrifuge."""
455
457
 
@@ -463,14 +465,14 @@ class PublicationContext(Protocol):
463
465
 
464
466
 
465
467
  def _native_attribute(value: object, name: str, default: object = None) -> object:
466
- return cast("object", getattr(value, name, default))
468
+ return getattr(value, name, default)
467
469
 
468
470
 
469
471
  def _native_presence_clients(value: object) -> Mapping[str, object] | None:
470
- if not isinstance(value, Mapping):
472
+ if not _is_object_mapping(value):
471
473
  return None
472
474
  clients: dict[str, object] = {}
473
- for client_id, info in cast("Mapping[object, object]", value).items():
475
+ for client_id, info in value.items():
474
476
  if not isinstance(client_id, str):
475
477
  return None
476
478
  clients[client_id] = info
@@ -480,22 +482,19 @@ def _native_presence_clients(value: object) -> Mapping[str, object] | None:
480
482
  def _is_json_value(value: object) -> TypeGuard[JSONValue]:
481
483
  if value is None or isinstance(value, (str, int, float, bool)):
482
484
  return True
483
- if isinstance(value, (list, tuple)):
484
- values = cast("list[object] | tuple[object, ...]", value)
485
- return all(_is_json_value(item) for item in values)
486
- if isinstance(value, Mapping):
487
- entries = cast("Mapping[object, object]", value)
485
+ if _is_object_sequence(value):
486
+ return all(_is_json_value(item) for item in value)
487
+ if _is_object_mapping(value):
488
488
  return all(
489
- isinstance(key, str) and _is_json_value(item)
490
- for key, item in entries.items()
489
+ isinstance(key, str) and _is_json_value(item) for key, item in value.items()
491
490
  )
492
491
  return False
493
492
 
494
493
 
495
- def _is_json_record(
496
- value: Mapping[str, object],
497
- ) -> TypeGuard[Mapping[str, JSONValue]]:
498
- return all(_is_json_value(item) for item in value.values())
494
+ def _is_json_record(value: object) -> TypeGuard[Mapping[str, JSONValue]]:
495
+ return _is_object_mapping(value) and all(
496
+ isinstance(key, str) and _is_json_value(item) for key, item in value.items()
497
+ )
499
498
 
500
499
 
501
500
  def _checked_postgres_row(row: dict[str, object]) -> Mapping[str, JSONValue]:
@@ -511,12 +510,7 @@ def _centrifuge_client(
511
510
  token: str,
512
511
  get_token: Callable[[], Awaitable[str]],
513
512
  ) -> CentrifugeConnection:
514
- module = importlib.import_module("centrifuge")
515
- constructor = cast("CentrifugeConstructor", module.Client)
516
- return cast(
517
- "CentrifugeConnection",
518
- constructor(address, events=events, token=token, get_token=get_token),
519
- )
513
+ return Client(address, events=events, token=token, get_token=get_token)
520
514
 
521
515
 
522
516
  class _ProjectAwareSubscriptions(dict[str, _SubscriptionT]):
@@ -545,10 +539,10 @@ class _ProjectAwareSubscriptions(dict[str, _SubscriptionT]):
545
539
 
546
540
 
547
541
  def _project_subscriptions(value: object) -> _ProjectAwareSubscriptions[object]:
548
- if not isinstance(value, dict):
542
+ if not _is_object_dict(value):
549
543
  raise TypeError(SUBSCRIPTION_REGISTRY_UNAVAILABLE)
550
544
  subscriptions = _ProjectAwareSubscriptions[object]()
551
- for channel, subscription in cast("Mapping[object, object]", value).items():
545
+ for channel, subscription in value.items():
552
546
  if not isinstance(channel, str):
553
547
  raise TypeError(SUBSCRIPTION_REGISTRY_UNAVAILABLE)
554
548
  subscriptions[channel] = subscription
@@ -577,8 +571,8 @@ class _VolcanoCentrifugeConnection:
577
571
  name: str,
578
572
  *,
579
573
  events: object,
580
- join_leave: bool = False,
581
- recoverable: bool = False,
574
+ join_leave: bool,
575
+ recoverable: bool,
582
576
  ) -> CentrifugeSubscription:
583
577
  return self._connection.new_subscription(
584
578
  name,
@@ -700,11 +694,7 @@ class _ClientEvents:
700
694
  def _presence_info(info: object) -> RealtimePresenceInfo:
701
695
  data = _native_attribute(info, "conn_info")
702
696
  user = _native_attribute(info, "user")
703
- typed_data = (
704
- cast("Mapping[str, JSONValue]", data)
705
- if isinstance(data, Mapping)
706
- else _empty_presence_data()
707
- )
697
+ typed_data = data if _is_json_record(data) else _empty_presence_data()
708
698
  return RealtimePresenceInfo(
709
699
  client=str(_native_attribute(info, "client", "")),
710
700
  user=user if isinstance(user, str) else None,
@@ -754,14 +744,16 @@ class Channel:
754
744
  self._presence_syncing: bool = False
755
745
  self._tracked_state: Mapping[str, JSONValue] = MappingProxyType({})
756
746
  self._subscribe_lock: asyncio.Lock = asyncio.Lock()
757
- self._subscribe_generation: int = 0
747
+ # Fresh identities invalidate stale work without implying an order.
748
+ self._subscribe_generation: object
749
+ self._supersede_subscribe_intent()
758
750
  self._readiness_task: asyncio.Task[None] | None = None
759
751
  self._subscription: CentrifugeSubscription | None = None
760
752
  self._subscription_events: _ChannelEvents | None = None
761
- self._subscribed: bool = False
762
- self._paused: bool = True
763
- self._delivery_epoch: int = 0
764
- self._presence_epoch: int = 0
753
+ self._subscribed: bool
754
+ self._paused: bool
755
+ self._delivery_epoch: object
756
+ self._presence_epoch: object
765
757
  self._presence_lock: asyncio.Lock = asyncio.Lock()
766
758
  self._presence_sync_task: asyncio.Task[None] | None = None
767
759
  self._presence_sync_pending: bool = False
@@ -769,8 +761,9 @@ class Channel:
769
761
  maxsize=CALLBACK_QUEUE_LIMIT
770
762
  )
771
763
  self._callback_task: asyncio.Task[None] | None = None
772
- self._pending_presence_sync: object = NO_PENDING_CALLBACK
773
- self._postgres_epoch: int = 0
764
+ self._pending_presence_sync: object
765
+ self._postgres_epoch: object
766
+ self._rotate_postgres_epoch()
774
767
  self._postgres_session_lineage: SessionOperations | None = None
775
768
  self._postgres_lock: asyncio.Lock = asyncio.Lock()
776
769
  self._postgres_worker: PostgresFetchWorker[_PostgresDelivery] | None = None
@@ -778,6 +771,16 @@ class Channel:
778
771
  int,
779
772
  tuple[PostgresListenerEvent, str, str],
780
773
  ] = {}
774
+ self._pause_delivery()
775
+
776
+ def _supersede_subscribe_intent(self) -> None:
777
+ self._subscribe_generation = object()
778
+
779
+ def _rotate_postgres_epoch(self) -> None:
780
+ self._postgres_epoch = object()
781
+
782
+ def _clear_readiness_task(self) -> None:
783
+ self._readiness_task = None
781
784
 
782
785
  @property
783
786
  def name(self) -> str:
@@ -842,7 +845,7 @@ class Channel:
842
845
  self._postgres_filters[id(filtered)] = (event, schema, table)
843
846
 
844
847
  def unsubscribe() -> None:
845
- callbacks = self._callbacks.get("*", [])
848
+ callbacks = self._callbacks["*"]
846
849
  if filtered in callbacks:
847
850
  callbacks.remove(filtered)
848
851
  _ = self._postgres_filters.pop(id(filtered), None)
@@ -864,7 +867,7 @@ class Channel:
864
867
  self._callbacks.setdefault("presence_sync", []).append(callback)
865
868
 
866
869
  def unsubscribe() -> None:
867
- callbacks = self._callbacks.get("presence_sync", [])
870
+ callbacks = self._callbacks["presence_sync"]
868
871
  if callback in callbacks:
869
872
  callbacks.remove(callback)
870
873
 
@@ -884,8 +887,7 @@ class Channel:
884
887
  self._ensure_presence()
885
888
  if not self._subscribed:
886
889
  raise RuntimeError(CHANNEL_NOT_SUBSCRIBED)
887
- frozen = _freeze_json(cast("JSONValue", dict(state or {})))
888
- self._tracked_state = cast("Mapping[str, JSONValue]", frozen)
890
+ self._tracked_state = _freeze_mapping(state or {})
889
891
 
890
892
  def get_presence_state(self) -> Mapping[str, RealtimePresenceInfo]:
891
893
  """Read the clients currently present.
@@ -921,13 +923,13 @@ class Channel:
921
923
  if self._type != "postgres":
922
924
  return
923
925
  await self._stop_postgres_worker()
924
- self._postgres_epoch += 1
926
+ self._rotate_postgres_epoch()
925
927
  self._postgres_session_lineage = self._realtime._connection_lineage()
926
928
 
927
929
  async def _end_postgres_epoch(self) -> None:
928
930
  if self._type != "postgres":
929
931
  return
930
- self._postgres_epoch += 1
932
+ self._rotate_postgres_epoch()
931
933
  await self._stop_postgres_worker()
932
934
 
933
935
  async def _stop_postgres_worker(self) -> None:
@@ -947,7 +949,7 @@ class Channel:
947
949
  return (
948
950
  self._subscribed
949
951
  and session is not None
950
- and identity.subscription_epoch == self._postgres_epoch
952
+ and identity.subscription_epoch is self._postgres_epoch
951
953
  and identity.session_lineage == lineage
952
954
  )
953
955
 
@@ -1161,7 +1163,7 @@ class Channel:
1161
1163
  return
1162
1164
  for callback in tuple(self._callbacks.get(delivery.event, [])):
1163
1165
  if not self._callback_delivery_is_current(delivery):
1164
- break
1166
+ return
1165
1167
  # Isolate a callback's own cancellation from later delivery.
1166
1168
  (error,) = await asyncio.gather(
1167
1169
  self._run_callback(callback, delivery),
@@ -1180,11 +1182,11 @@ class Channel:
1180
1182
  if delivery.delivery_epoch is not None:
1181
1183
  return (
1182
1184
  not self._paused or delivery.event == "presence_sync"
1183
- ) and delivery.delivery_epoch == self._callback_epoch(delivery.event)
1185
+ ) and delivery.delivery_epoch is self._callback_epoch(delivery.event)
1184
1186
  identity = delivery.postgres_identity
1185
1187
  return identity is None or self._postgres_delivery_is_current(identity)
1186
1188
 
1187
- def _callback_epoch(self, event: str) -> int:
1189
+ def _callback_epoch(self, event: str) -> object:
1188
1190
  if event in {"join", "leave", "presence_sync"}:
1189
1191
  return self._presence_epoch
1190
1192
  return self._delivery_epoch
@@ -1255,7 +1257,7 @@ class Channel:
1255
1257
  ) -> None:
1256
1258
  if event == "join":
1257
1259
  self._presence_state[presence.client] = presence
1258
- else:
1260
+ if event == "leave":
1259
1261
  _ = self._presence_state.pop(presence.client, None)
1260
1262
 
1261
1263
  async def _presence_join(self, info: object) -> None:
@@ -1306,6 +1308,8 @@ class Channel:
1306
1308
  try:
1307
1309
  while self._subscribed:
1308
1310
  await self._realtime._sync_presence(self)
1311
+ # A synchronous native reply must not starve cancellation or callbacks.
1312
+ await asyncio.sleep(0)
1309
1313
  if not self._presence_sync_pending:
1310
1314
  return
1311
1315
  self._presence_sync_pending = False
@@ -1321,7 +1325,6 @@ class Channel:
1321
1325
  async def _cancel_presence_sync(self) -> None:
1322
1326
  task = self._presence_sync_task
1323
1327
  self._presence_sync_task = None
1324
- self._presence_sync_pending = False
1325
1328
  if task is None or task.done():
1326
1329
  return
1327
1330
  _ = task.cancel()
@@ -1349,9 +1352,9 @@ class Channel:
1349
1352
  self._discard_callbacks()
1350
1353
 
1351
1354
  def _discard_callbacks(self, *, presence_only: bool = False) -> None:
1352
- self._presence_epoch += 1
1355
+ self._presence_epoch = object()
1353
1356
  if not presence_only:
1354
- self._delivery_epoch += 1
1357
+ self._delivery_epoch = object()
1355
1358
  # Free capacity before recovered publications arrive behind a slow callback.
1356
1359
  for _ in range(self._callback_queue.qsize()):
1357
1360
  delivery = self._callback_queue.get_nowait()
@@ -1408,7 +1411,7 @@ class Realtime:
1408
1411
  "disconnect": {},
1409
1412
  "error": {},
1410
1413
  }
1411
- self._next_callback_id: int = 0
1414
+ self._callback_ids: Iterator[int] = count()
1412
1415
  self._connection_callback_queue: asyncio.Queue[
1413
1416
  tuple[str, object, tuple[int, ...]]
1414
1417
  ] = asyncio.Queue(maxsize=CALLBACK_QUEUE_LIMIT)
@@ -1494,8 +1497,7 @@ class Realtime:
1494
1497
  callback: RealtimeCallback,
1495
1498
  ) -> UnsubscribeCallback:
1496
1499
  require_callable(callback, CALLBACK_NOT_CALLABLE)
1497
- self._next_callback_id += 1
1498
- callback_id = self._next_callback_id
1500
+ callback_id = next(self._callback_ids)
1499
1501
  self._connection_callbacks[event][callback_id] = callback
1500
1502
 
1501
1503
  def unsubscribe() -> None:
@@ -1617,7 +1619,7 @@ class Realtime:
1617
1619
  self._removing_channels.add(wire_name)
1618
1620
  try:
1619
1621
  await self._remove_channel(channel)
1620
- _ = self._channels.pop(wire_name, None)
1622
+ del self._channels[wire_name]
1621
1623
  finally:
1622
1624
  self._removing_channels.remove(wire_name)
1623
1625
 
@@ -1649,7 +1651,7 @@ class Realtime:
1649
1651
  return None
1650
1652
 
1651
1653
  async def _remove_channel(self, channel: Channel) -> None:
1652
- channel._subscribe_generation += 1
1654
+ channel._supersede_subscribe_intent()
1653
1655
  await self._discard_subscription(channel)
1654
1656
  await channel._reset()
1655
1657
 
@@ -1696,7 +1698,9 @@ class Realtime:
1696
1698
  def _address(self) -> str:
1697
1699
  parsed = urlsplit(self._api_url)
1698
1700
  scheme = "wss" if parsed.scheme == "https" else "ws"
1699
- query = f"apikey={quote(self._client_context._anon_token(), safe='')}"
1701
+ query = urlencode(
1702
+ {"apikey": self._client_context._anon_token()}, quote_via=quote
1703
+ )
1700
1704
  return urlunsplit((scheme, parsed.netloc, "/realtime/v1/websocket", query, ""))
1701
1705
 
1702
1706
  async def _connect(self) -> _VolcanoCentrifugeConnection:
@@ -1772,7 +1776,7 @@ class Realtime:
1772
1776
  try:
1773
1777
  await channel._readiness_task
1774
1778
  finally:
1775
- channel._readiness_task = None
1779
+ channel._clear_readiness_task()
1776
1780
 
1777
1781
  async def _cleanup_failed_subscription(
1778
1782
  self,
@@ -1787,7 +1791,7 @@ class Realtime:
1787
1791
  ):
1788
1792
  # An explicit pause or removal owns the newer subscription intent.
1789
1793
  return
1790
- channel._subscribe_generation += 1
1794
+ channel._supersede_subscribe_intent()
1791
1795
  channel._subscription_events = None
1792
1796
  channel._pause_delivery()
1793
1797
  try:
@@ -1798,9 +1802,9 @@ class Realtime:
1798
1802
  error.add_note("Failed to clean up the realtime subscription")
1799
1803
 
1800
1804
  async def _prepare_subscription(
1801
- self, channel: Channel, generation: int
1805
+ self, channel: Channel, generation: object
1802
1806
  ) -> CentrifugeSubscription:
1803
- if generation != channel._subscribe_generation:
1807
+ if generation is not channel._subscribe_generation:
1804
1808
  raise asyncio.CancelledError
1805
1809
  if self._channels.get(channel._name) is not channel:
1806
1810
  raise RuntimeError(CHANNEL_NOT_MANAGED)
@@ -1821,34 +1825,41 @@ class Realtime:
1821
1825
  if channel._subscription is None:
1822
1826
  return
1823
1827
  await channel._begin_presence_sync()
1824
- query_succeeded = False
1825
1828
  try:
1826
1829
  # Native replies must settle even after the roster refresh is cancelled.
1827
1830
  query = asyncio.create_task(channel._subscription.presence())
1828
1831
  query.add_done_callback(_consume_presence_result)
1829
1832
  result = await asyncio.shield(query)
1830
- query_succeeded = True
1831
1833
  except CENTRIFUGE_ERROR as error:
1832
- await channel._fail_presence_sync()
1833
- query_succeeded = True
1834
- self._enqueue_connection_callbacks(
1835
- "error",
1836
- RealtimeErrorContext(
1837
- code=getattr(error, "code", None),
1838
- message=str(error),
1839
- error=error,
1840
- ),
1841
- )
1834
+ await self._report_presence_sync_failure(channel, error)
1842
1835
  return
1843
- finally:
1844
- if not query_succeeded:
1845
- await channel._abort_presence_sync()
1836
+ except BaseException:
1837
+ await channel._abort_presence_sync()
1838
+ raise
1846
1839
  clients = _native_presence_clients(_native_attribute(result, "clients"))
1847
1840
  if clients is not None:
1848
1841
  await channel._complete_presence_sync(clients)
1849
1842
  else:
1850
1843
  await channel._abort_presence_sync()
1851
1844
 
1845
+ async def _report_presence_sync_failure(
1846
+ self, channel: Channel, error: Exception
1847
+ ) -> None:
1848
+ try:
1849
+ await channel._fail_presence_sync()
1850
+ except BaseException:
1851
+ await channel._abort_presence_sync()
1852
+ raise
1853
+ code = _native_attribute(error, "code")
1854
+ self._enqueue_connection_callbacks(
1855
+ "error",
1856
+ RealtimeErrorContext(
1857
+ code=code if isinstance(code, int) else None,
1858
+ message=str(error),
1859
+ error=error,
1860
+ ),
1861
+ )
1862
+
1852
1863
  async def _publish(self, channel: Channel, data: object) -> None:
1853
1864
  async with self._connection_lock:
1854
1865
  if channel._type != "broadcast":
@@ -1860,7 +1871,7 @@ class Realtime:
1860
1871
 
1861
1872
  async def _unsubscribe(self, channel: Channel) -> None:
1862
1873
  async with self._connection_lock:
1863
- channel._subscribe_generation += 1
1874
+ channel._supersede_subscribe_intent()
1864
1875
  if not channel._paused:
1865
1876
  channel._pause_delivery()
1866
1877
  if channel._subscription is not None:
@@ -1873,9 +1884,8 @@ class Realtime:
1873
1884
  self._connection = None
1874
1885
  channels = tuple(self._channels.values())
1875
1886
  for channel in channels:
1876
- channel._subscribe_generation += 1
1887
+ channel._supersede_subscribe_intent()
1877
1888
  channel._invalidate()
1878
- cancelled: asyncio.CancelledError | None = None
1879
1889
  try:
1880
1890
  cancelled = await _reset_realtime_channels(channels)
1881
1891
  finally:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: volcano-sdk-python
3
- Version: 0.13.0
3
+ Version: 0.13.1
4
4
  Summary: Official Python SDK for Volcano
5
5
  Project-URL: Homepage, https://volcano.dev
6
6
  Project-URL: Repository, https://github.com/Kong/volcano-sdk-python
@@ -94,17 +94,22 @@ execution = client.durable.start(
94
94
  )
95
95
  print(execution.id, execution.status)
96
96
 
97
- execution = client.durable.get(
97
+ owner_client = VolcanoClient(
98
+ api_url="https://api.volcano.dev",
99
+ anon_key="your-anon-key",
100
+ access_token="your-platform-user-token",
101
+ )
102
+ execution = owner_client.durable.get(
98
103
  "00000000-0000-4000-8000-000000000001", "order-pipeline", execution.id
99
104
  )
100
105
  print(execution.is_terminal, execution.result)
101
106
 
102
- executions = client.durable.list(
107
+ executions = owner_client.durable.list(
103
108
  "00000000-0000-4000-8000-000000000001", "order-pipeline", status="running"
104
109
  )
105
110
  print(executions.total, executions.has_more)
106
111
 
107
- client.durable.stop(
112
+ owner_client.durable.stop(
108
113
  "00000000-0000-4000-8000-000000000001", "order-pipeline", execution.id
109
114
  )
110
115
 
@@ -264,18 +269,18 @@ A function's own response, HTTP 403, or a network failure never triggers this re
264
269
  Anonymous and service keys do not refresh.
265
270
 
266
271
  `durable.start()` begins an execution of a deployed durable function and returns
267
- a handle rather than a result: an execution can run for hours, so its result is
268
- read back with `durable.get()`. It takes the credential `functions.invoke()`
272
+ a handle rather than a result: an execution can run for up to 366 days, so its
273
+ result is read back with `durable.get()`. It takes the credential `functions.invoke()`
269
274
  takes, and is the only durable operation an application credential may perform.
270
275
  An `execution_name` makes the start idempotent — starting again under the same
271
276
  name returns the execution that already exists rather than beginning a second
272
277
  one, and is charged once.
273
278
 
274
279
  `durable.get()`, `durable.list()` and `durable.stop()` are owner-scoped and need
275
- the project's own platform token, because an execution is addressed by its id
276
- alone and an anonymous key is held by everyone who loads the page. Neither an
277
- auth-user session from `sign_in()` nor a service key is accepted -- the routes
278
- take a user token, and anything else is answered 401. Poll them from a backend.
280
+ the project owner's platform user token, because an execution is addressed by
281
+ its id alone and an anonymous key is held by everyone who loads the page.
282
+ Auth-user sessions from `sign_in()`, anonymous keys, service keys, and project
283
+ access tokens are not accepted. Poll them from a trusted backend.
279
284
  `get()` carries `result` once the execution has succeeded and `error` when it
280
285
  failed; `result_expired` separates a result the platform has discarded from a
281
286
  function that returned nothing. `is_terminal` reports whether the execution has
@@ -315,6 +320,31 @@ def handler(event, ctx):
315
320
  return {"charged": charge["id"], "packed": packed.results}
316
321
  ```
317
322
 
323
+ Use the function name for its source directory and manifest entry:
324
+
325
+ ```text
326
+ volcano/functions/order-pipeline/
327
+ ├── main.py
328
+ └── requirements.txt
329
+ ```
330
+
331
+ ```text
332
+ # volcano/functions/order-pipeline/requirements.txt
333
+ volcano-sdk-python
334
+ ```
335
+
336
+ ```yaml
337
+ # volcano-config.yaml
338
+ version: 1
339
+ project:
340
+ name: my-app
341
+ functions:
342
+ - name: order-pipeline
343
+ kind: durable
344
+ ```
345
+
346
+ The decorator defines handler behavior. The manifest declaration makes the function discoverable by `volcano durable deploy`.
347
+
318
348
  Every context operation is checkpointed: what finished is recorded, and a
319
349
  resumed execution replays that recorded outcome instead of doing the work again.
320
350
  That is the one rule the handler has to respect — the code between operations
@@ -356,6 +386,20 @@ nothing while it waits. Running the handler anywhere durable execution does not
356
386
  exist raises `DurableRuntimeMissingError` rather than an import error from an
357
387
  unfamiliar package.
358
388
 
389
+ Run the same handler through the local durable engine:
390
+
391
+ ```bash
392
+ volcano start
393
+ volcano durable deploy --all
394
+ volcano durable start order-pipeline --input '{"order_id":"order-9"}'
395
+ ```
396
+
397
+ Local waits resolve immediately by default while preserving checkpoint and replay
398
+ behavior. Set `LOCAL_DURABLE_REAL_TIME=true` before `volcano start` when wait
399
+ timing must match the deployed function. Local executions persist across
400
+ `volcano stop` and `volcano start`. Volcano does not expose externally completed
401
+ callbacks; use `ctx.wait_until` to poll application state instead.
402
+
359
403
  `logs.search()` returns an immutable page of retained runtime or deployment log
360
404
  events. Pass `next_cursor` back as `cursor` to continue a search. `logs.activity()`
361
405
  returns immutable time buckets using the same resource selector and query syntax.
@@ -21,7 +21,7 @@ volcano_sdk/locks.py,sha256=Zf2nBoolXK-zXeAJYdqbhmfkn3OiNUpX7XmmDhvGCmI,11779
21
21
  volcano_sdk/logs.py,sha256=CwtBpUGqoi82xIQBnq31LJ0XrfDEsMK9Tig1_qOL4d4,4368
22
22
  volcano_sdk/models.py,sha256=ZIo2YdZ-Ba7rCmHBo3eV9LGjpEftVTeVmrrfq-zGujs,11182
23
23
  volcano_sdk/py.typed,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
24
- volcano_sdk/realtime.py,sha256=CSIQZnAHXIYhwJdzaIpaULABUmi2TqmV_v8KS7xQCKk,66775
24
+ volcano_sdk/realtime.py,sha256=-mUVBwaon5qPFWOsWVyW0jRCeBKbeCd110wBBxD_YcY,66800
25
25
  volcano_sdk/storage.py,sha256=e5VVKixj2ho3DDrZ52lFDVYKHSdoZnuFlfRfdgA-gtY,33329
26
26
  volcano_sdk/_generated/__init__.py,sha256=ZlB8wMYdN6EjpUS5W_lX3jsxq9G1kOcmUr-j3Fccfn8,164
27
27
  volcano_sdk/_generated/client.py,sha256=GDzw6T2uRmPlUb1DImpBGxwy0dNbhmBknfvvIQW0GuU,12387
@@ -810,7 +810,7 @@ volcano_sdk/_generated/models/usage_data_point.py,sha256=d4U08JbVTiIMM_l2BmRILL1
810
810
  volcano_sdk/_generated/models/variable.py,sha256=t8XaBfTwIH42L8RL4DFDtdqbhVfDEnRS5Axq2q6Tpvk,6405
811
811
  volcano_sdk/_generated/models/variable_deploy_source.py,sha256=G_aCiFHzQx8WhJFs0GvYZEFclfTrfkDvd3kT1e3vty8,463
812
812
  volcano_sdk/_generated/models/variable_status.py,sha256=THSsKBSiAYG4kAtBzGA4TZqxjgx8hdL0Q4qCdZfOj00,391
813
- volcano_sdk_python-0.13.0.dist-info/METADATA,sha256=5ltgXFyk-kxqTe-MFbU5D8D-mzCywAnrcI8k0Swyzco,45775
814
- volcano_sdk_python-0.13.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
815
- volcano_sdk_python-0.13.0.dist-info/licenses/LICENSE,sha256=AIHJy-5MFqM8fHfuGFTTb9a8rvJGypcVgN4aZ-7XTWw,11387
816
- volcano_sdk_python-0.13.0.dist-info/RECORD,,
813
+ volcano_sdk_python-0.13.1.dist-info/METADATA,sha256=UoB9QKJZecL-HbHPdy1-keh6bSIhTpBrFHnEm5J0udI,46989
814
+ volcano_sdk_python-0.13.1.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
815
+ volcano_sdk_python-0.13.1.dist-info/licenses/LICENSE,sha256=AIHJy-5MFqM8fHfuGFTTb9a8rvJGypcVgN4aZ-7XTWw,11387
816
+ volcano_sdk_python-0.13.1.dist-info/RECORD,,