ws_sync.sync
1import asyncio 2import base64 3import logging 4import warnings 5import weakref 6from collections.abc import Awaitable, Callable, Iterable, Mapping 7from contextlib import suppress 8from contextvars import ContextVar, Token 9from copy import deepcopy 10from inspect import Parameter, signature 11from logging import Logger 12from time import time 13from types import EllipsisType 14from typing import Any, Literal, Protocol, Self, cast, get_type_hints 15 16import jsonpatch 17from pydantic import ( 18 AliasGenerator, 19 BaseModel, 20 ConfigDict, 21 PydanticSchemaGenerationError, 22 TypeAdapter, 23 create_model, 24) 25from pydantic.alias_generators import to_camel, to_pascal 26 27from ws_sync.decorators import ( 28 find_remote_actions, 29 find_remote_task_cancellers, 30 find_remote_tasks, 31) 32from ws_sync.utils import get_alias_function_for_class, nonblock_call 33 34from .session import session_context 35 36logger = logging.getLogger(__name__) 37 38 39# Sync Key Prefix Context 40_sync_key_prefix_stack: ContextVar[list[str] | None] = ContextVar( 41 "_sync_key_prefix_stack", default=None 42) 43"""Per-task sync key prefix stack. Allows nested prefix scopes.""" 44 45 46class sync_key_scope: # noqa: N801 47 """ 48 Context manager for scoping sync keys with a prefix. 49 50 All Sync objects created within this context will have their keys prefixed. 51 Supports nesting - nested scopes will create hierarchical prefixes with '/' separator. 52 53 Example: 54 ```python 55 with sync_key_scope("user123"): 56 obj1 = MyObject() # key: "user123/MY_KEY" 57 58 with sync_key_scope("session456"): 59 obj2 = MyObject() # key: "user123/session456/MY_KEY" 60 ``` 61 62 Args: 63 prefix: The prefix to add. Empty strings and None are ignored (no prefix added). 64 """ 65 66 def __init__(self, prefix: str | None): 67 self.prefix = prefix 68 self.token: Token[list[str] | None] | None = None 69 70 def __enter__(self) -> Self: 71 # Only add non-empty prefixes 72 if self.prefix: 73 # Get current stack (creates a copy to avoid mutation issues) 74 current_stack = _sync_key_prefix_stack.get() 75 current_stack = [] if current_stack is None else current_stack.copy() 76 current_stack.append(self.prefix) 77 self.token = _sync_key_prefix_stack.set(current_stack) 78 return self 79 80 def __exit__( 81 self, 82 exc_type: type[BaseException] | None, 83 exc_value: BaseException | None, 84 traceback: object, 85 ) -> None: 86 if self.token is not None: 87 _sync_key_prefix_stack.reset(self.token) 88 self.token = None 89 90 91def get_current_sync_key_prefix() -> str | None: 92 """ 93 Get the current sync key prefix from nested scopes. 94 95 Returns: 96 The full hierarchical prefix string (e.g., "abc/nested/deep"), 97 or None if no prefix scope is active. 98 99 Example: 100 ```python 101 with sync_key_scope("abc"): 102 with sync_key_scope("nested"): 103 prefix = get_current_sync_key_prefix() # "abc/nested" 104 ``` 105 """ 106 stack = _sync_key_prefix_stack.get() 107 if not stack: 108 return None 109 return "/".join(stack) 110 111 112def _apply_sync_key_prefix(key: str) -> str: 113 """ 114 Apply the current prefix stack to a sync key. 115 116 Args: 117 key: The base sync key. 118 119 Returns: 120 The prefixed key (e.g., "abc/nested/MY_KEY"), or the original key if no prefix is active. 121 """ 122 prefix = get_current_sync_key_prefix() 123 if prefix: 124 return f"{prefix}/{key}" 125 return key 126 127 128# Event Type Helpers 129def set_event(key: str): 130 """State has been set""" 131 return f"_SET:{key}" 132 133 134def get_event(key: str): 135 """State has been requested""" 136 return f"_GET:{key}" 137 138 139def patch_event(key: str): 140 """State has been patched""" 141 return f"_PATCH:{key}" 142 143 144def action_event(key: str): 145 """Action has been dispatched""" 146 return f"_ACTION:{key}" 147 148 149def task_start_event(key: str): 150 """Task has been started""" 151 return f"_TASK_START:{key}" 152 153 154def task_cancel_event(key: str): 155 """Task has been cancelled""" 156 return f"_TASK_CANCEL:{key}" 157 158 159def toast_event(): 160 """Toast message has been sent""" 161 return "_TOAST" 162 163 164# FIXME: OBSOLETE 165def download_event(): 166 """File has been sent for download""" 167 return "_DOWNLOAD" 168 169 170# TODO: for key-space, global key prefix and context manager function in Sync 171 172ToastType = Literal["default", "message", "info", "success", "warning", "error"] 173 174 175class SchemaTitleGenerator(Protocol): 176 def __call__(self, class_name: str, key: str) -> str: ... 177 178 179default_action_title_generator: SchemaTitleGenerator = ( # noqa: E731 180 lambda class_name, key: f"{class_name}Action{to_pascal(key)}" 181) 182default_task_title_generator: SchemaTitleGenerator = ( # noqa: E731 183 lambda class_name, key: f"{class_name}Task{to_pascal(key)}" 184) 185 186 187class Sync: 188 """ 189 Register an object's attributes to this class to sync them with the frontend. 190 """ 191 192 @classmethod 193 def all( 194 cls, 195 obj: object, 196 key: str, 197 *, 198 include: dict[str, str | EllipsisType] | list[str] | None = None, 199 exclude: list[str] | None = None, 200 toCamelCase: bool | None = None, # noqa: N803 201 send_on_init: bool = True, 202 expose_running_tasks: bool = False, 203 logger: Logger | None = None, 204 actions: Mapping[str, Callable[..., Any]] | None = None, 205 tasks: Mapping[str, Callable[..., Awaitable[Any]]] | None = None, 206 task_cancels: Mapping[str, Callable[..., Awaitable[Any]]] | None = None, 207 ) -> "Sync": 208 return cls( 209 obj=obj, 210 key=key, 211 sync_all=True, 212 include=include, 213 exclude=exclude or [], 214 toCamelCase=toCamelCase, 215 send_on_init=send_on_init, 216 expose_running_tasks=expose_running_tasks, 217 logger=logger, 218 actions=actions, 219 tasks=tasks, 220 task_cancels=task_cancels, 221 ) 222 223 @classmethod 224 def only( 225 cls, 226 _obj: object, 227 _key: str, 228 *, 229 _toCamelCase: bool | None = None, # noqa: N803 230 _send_on_init: bool = True, 231 _expose_running_tasks: bool = False, 232 _logger: Logger | None = None, 233 _actions: Mapping[str, Callable[..., Any]] | None = None, 234 _tasks: Mapping[str, Callable[..., Awaitable[Any]]] | None = None, 235 _task_cancels: Mapping[str, Callable[..., Awaitable[Any]]] | None = None, 236 **sync_attributes: str | EllipsisType, 237 ) -> "Sync": 238 return cls( 239 obj=_obj, 240 key=_key, 241 sync_all=False, 242 include=sync_attributes, 243 exclude=[], 244 toCamelCase=_toCamelCase, 245 send_on_init=_send_on_init, 246 expose_running_tasks=_expose_running_tasks, 247 logger=_logger, 248 actions=_actions, 249 tasks=_tasks, 250 task_cancels=_task_cancels, 251 ) 252 253 @staticmethod 254 def resolve_attributes( 255 obj_or_cls: object | type, 256 *, 257 include: dict[str, str | EllipsisType] | None = None, 258 exclude: list[str] | None = None, 259 sync_all: bool = False, 260 casing_func: Callable[[str], str] | None = None, 261 ) -> dict[str, str]: 262 """ 263 Resolve which attributes to sync based on configuration. 264 265 Returns: 266 Dict mapping attribute name to sync key (alias). 267 """ 268 include = include or {} 269 exclude = exclude or [] 270 sync_attributes: dict[str, str] = {} 271 272 is_class = isinstance(obj_or_cls, type) 273 cls = obj_or_cls if is_class else type(obj_or_cls) 274 275 def casing(attr: str) -> str: 276 return casing_func(attr) if casing_func else attr 277 278 # observe all non-private attributes 279 if sync_all: 280 if issubclass(cls, BaseModel): 281 # Include regular fields 282 for field in cls.model_fields: 283 if field in exclude: 284 continue 285 sync_attributes[field] = casing(field) 286 287 # Include computed fields 288 for field in cls.model_computed_fields: 289 if field in exclude: 290 continue 291 sync_attributes[field] = casing(field) 292 # For regular classes, we need an instance to check dir() reliably for instance attrs, 293 # but we can check class attrs if we only have a class. 294 # However, if we only have a class, we can't know instance attributes that are set in __init__. 295 # So sync_all=True for plain classes really works best with an instance. 296 # If we have a class, we can only guess based on annotations or class attributes. 297 elif is_class: 298 # Best effort for static analysis of plain classes 299 # We can check type hints 300 for attr_name in get_type_hints(cls): 301 if attr_name in exclude or attr_name.startswith("_"): 302 continue 303 sync_attributes[attr_name] = casing(attr_name) 304 else: 305 for attr_name in dir(obj_or_cls): 306 try: 307 attr = getattr(obj_or_cls, attr_name) 308 except AttributeError: 309 continue 310 if ( 311 attr_name in exclude 312 or attr_name.startswith("_") 313 or callable(attr) 314 or isinstance(attr, Sync) 315 ): 316 continue 317 318 sync_attributes[attr_name] = casing(attr_name) 319 320 # observe specific attributes 321 for attr_name, sync_key in include.items(): 322 sync_attributes[attr_name] = ( 323 casing(attr_name) if sync_key is ... else cast(str, sync_key) 324 ) 325 326 return sync_attributes 327 328 def __init__( 329 self, 330 obj: object, 331 key: str, 332 *, 333 sync_all: bool = False, 334 include: dict[str, str | EllipsisType] | list[str] | None = None, 335 exclude: list[str] | None = None, 336 toCamelCase: bool | None = None, # noqa: N803 337 send_on_init: bool = True, 338 expose_running_tasks: bool = False, 339 logger: Logger | None = None, 340 actions: Mapping[str, Callable[..., Any]] | None = None, 341 tasks: Mapping[str, Callable[..., Awaitable[Any]]] | None = None, 342 task_cancels: Mapping[str, Callable[..., Awaitable[Any]]] | None = None, 343 ): 344 """ 345 Register the attributes that should be synced with the frontend. 346 347 Args: 348 obj: the object whose attributes should be synced 349 key: unique key for this object 350 351 sync_all: whether to sync all non-private attributes 352 include: attribute names to sync, value being either ... 353 or a string of the key of the attribute 354 exclude: list of attributes to exclude from syncing 355 356 toCamelCase: convert attribute names to camelCase. Must be ``None`` for 357 Pydantic models, which should configure ``alias_generator`` 358 send_on_init: whether to send the state on connection init 359 expose_running_tasks: whether to expose the running tasks to the frontend 360 logger: logger to use for logging 361 362 actions: action handlers for each action type, each taking the data of the action as keyword arguments 363 tasks: either a dict of task factories for each task type, each returning a coroutine to be used as a task, or a tuple of (task_start_handler, task_cancel_handler) 364 task_cancels: a dict of task cancel handlers for each task type 365 366 367 """ 368 self.obj = obj 369 self.key = _apply_sync_key_prefix(key) 370 self.send_on_init = send_on_init 371 self.casing_func = ( 372 get_alias_function_for_class(type(self.obj)) 373 if isinstance(self.obj, BaseModel) 374 else (to_camel if toCamelCase else None) 375 ) 376 self.task_exposure = ( 377 self.casing("running_tasks") if expose_running_tasks else None 378 ) 379 self.logger = logger 380 381 # Convert list[str] include to dict format 382 if isinstance(include, list): 383 include = dict.fromkeys(include, ...) 384 include = include or {} 385 exclude = exclude or [] 386 387 # Validate that BaseModel objects don't use custom sync keys 388 if isinstance(obj, BaseModel) and include: 389 for attr_name, sync_key in include.items(): 390 assert sync_key is ..., ( 391 f"Custom sync key '{sync_key}' for attribute '{attr_name}' is not allowed for Pydantic models. Use pydantic's alias_generator in model_config instead." 392 ) 393 394 self.session = session_context.get() 395 assert self.session, "No session set, use the session.session_context variable!" 396 397 # ========== Create Action Validators (cached) ========== # 398 actions = dict(actions or {}) | find_remote_actions(type(self.obj)) 399 self.action_validators: dict[str, TypeAdapter[Any]] = ( 400 self.build_action_validators( 401 target_cls=type(self.obj), 402 actions=actions, 403 param_alias_generator=self.casing_func, 404 ) 405 ) 406 # Create action handler after validators are ready 407 self.actions = self._create_action_handler(obj, actions) 408 409 # ========== Create Task Validators (cached) ========== # 410 tasks = dict(tasks or {}) | find_remote_tasks(type(self.obj)) 411 task_cancels = dict(task_cancels or {}) | find_remote_task_cancellers( 412 type(self.obj) 413 ) 414 self.task_validators: dict[str, TypeAdapter[Any]] = self.build_task_validators( 415 target_cls=type(self.obj), 416 tasks=tasks, 417 param_alias_generator=self.casing_func, 418 ) 419 self.tasks, self.task_cancels = self._create_task_handlers( 420 obj, tasks, task_cancels 421 ) 422 423 # store running tasks 424 self.running_tasks: dict[str, asyncio.Task[Any]] = {} 425 426 # ========== Find attributes to sync ========== # 427 self.sync_attributes: dict[str, str] = {} 428 429 # observe all non-private attributes 430 if sync_all: 431 if isinstance(obj, BaseModel): 432 # Include regular fields 433 for field in type(obj).model_fields: 434 if field in exclude: 435 continue 436 self.sync_attributes[field] = self.casing(field) 437 438 # Include computed fields 439 for field in type(obj).model_computed_fields: 440 if field in exclude: 441 continue 442 self.sync_attributes[field] = self.casing(field) 443 else: 444 for attr_name in dir(obj): 445 try: 446 attr = getattr(obj, attr_name) 447 except AttributeError: 448 continue 449 if ( 450 attr_name in exclude 451 or attr_name.startswith("_") 452 or callable(attr) 453 or isinstance(attr, Sync) 454 ): 455 continue 456 457 self.sync_attributes[attr_name] = self.casing(attr_name) 458 459 # observe specific attributes 460 for attr_name, sync_key in include.items(): 461 self.sync_attributes[attr_name] = ( 462 self.casing(attr_name) if sync_key is ... else sync_key 463 ) 464 465 # create reverse-lookup for patching 466 self.key_to_attr: dict[str, str] = { 467 key: attr for attr, key in self.sync_attributes.items() 468 } 469 470 # ========== Debugging ========== # 471 if self.logger: 472 self.logger.debug("%s: Syncing %s", self.key, self.sync_attributes) 473 self.logger.debug("%s: Actions %s", self.key, actions) 474 self.logger.debug("%s: Tasks %s", self.key, tasks) 475 self.logger.debug("%s: Task Cancels %s", self.key, task_cancels) 476 477 assert include.keys().isdisjoint(exclude), "Attribute in both include & exclude" 478 assert all(a in dir(obj) for a in self.sync_attributes), "Attribute not found" 479 assert all(e in dir(obj) for e in exclude), "Excluded attribute not found" 480 # assert ( 481 # len(self.sync_attributes) + expose_running_tasks > 0 482 # ), "No attributes to sync" 483 484 # ========== Field Type Adapters (cached) ========== # 485 self.type_adapters: dict[str, TypeAdapter[Any]] = self.build_field_validators( 486 type(obj), field_whitelist=self.sync_attributes.keys() 487 ) 488 489 # ========== State Management ========== # 490 # the snapshot is the exact state that the frontend has, for patching 491 self.state_snapshot: dict[str, Any] = self._snapshot() 492 self._last_sync: float | None = None # timestamp of last sync 493 494 # ========== Weak Reference Cleanup State ========== # 495 self._closed = False 496 self._init_wrapper: Callable[..., Any] | None = None 497 self._registered_handlers: dict[str, Callable[..., Any]] = {} 498 self._weak_self_ref: weakref.ref[Sync] | None = None 499 self._register_event_handlers() 500 501 # ========== High-Level: Sync and Actions ========== # 502 async def sync(self, if_since_last: float | None = None): 503 """ 504 Sync all registered attributes. 505 506 Args: 507 if_since_last: only sync if the last sync was before this many seconds 508 """ 509 if not self.session.is_connected: 510 return 511 t = time() 512 if if_since_last and self._last_sync and t - self._last_sync < if_since_last: 513 return 514 515 # calculate patch 516 prev = self.state_snapshot 517 self.state_snapshot = self._snapshot() 518 patch = jsonpatch.make_patch(prev, self.state_snapshot).patch 519 520 if len(patch) > 0: 521 await self.session.send(patch_event(self.key), patch) 522 self._last_sync = t 523 524 async def __call__( 525 self, 526 if_since_last: float | None = None, 527 toast: str | None = None, 528 type: ToastType = "default", # noqa: A002 529 ): 530 """ 531 Sync all registered attributes. 532 533 Args: 534 if_since_last: only sync if the last sync was before this many seconds 535 toast: toast message to send after syncing 536 type: toast type 537 """ 538 await self.sync(if_since_last=if_since_last) 539 if toast: 540 await self.toast(toast, type=type) 541 542 async def send_action(self, action: dict[str, Any]): 543 """ 544 Send an action to the frontend. 545 """ 546 await self.session.send(action_event(self.key), action) 547 548 async def send_binary(self, metadata: dict[str, Any], data: bytes): 549 """ 550 Send binary data to the frontend, along with metadata. 551 552 This is a subset of an action, but with bytes data always included. 553 """ 554 await self.session.send_binary(action_event(self.key), metadata, data) 555 556 async def toast( 557 self, 558 *messages, 559 type: ToastType = "default", # noqa: A002 560 logger: Logger | None = None, 561 ) -> str: 562 """ 563 Send a toast message to the frontend. 564 565 Returns the sent message content, so that you can easily return or print it. 566 """ 567 messages = " ".join(str(message) for message in messages) 568 569 if lg := (logger or self.logger): 570 match type: 571 case "default": 572 lg.debug(messages) 573 case "message" | "info" | "success": 574 lg.info(messages) 575 case "warning": 576 lg.warning(messages) 577 case "error": 578 lg.error(messages) 579 case _: 580 lg.debug(messages) 581 582 await self.session.send(toast_event(), {"type": type, "message": messages}) 583 return messages 584 585 async def download(self, filename: str, binary: bytes) -> None: 586 """ 587 Send a file to the frontend for download. 588 """ 589 data = base64.b64encode(binary).decode("utf-8") 590 await self.session.send(download_event(), {"filename": filename, "data": data}) 591 592 def observe(self, obj: object, **sync_attributes: str | EllipsisType) -> None: 593 """ 594 Observe additional attributes, useful for when you're extending/subclassing an already Synced object, or when you want to observe multiple objects. 595 """ 596 # TODO: append, deregister, re-register 597 598 # ========== Low-Level: State Management ========== # 599 def _snapshot(self) -> dict[str, Any]: 600 result = {} 601 602 if isinstance(self.obj, BaseModel): 603 # TODO: maybe always explicitly serialize using TypeAdapters like below, since the model maybe be configured for other serialization use cases? 604 result = self.obj.model_dump( 605 mode="json", 606 include=set(self.sync_attributes.keys()), 607 warnings=False, 608 ) 609 else: 610 for attr, key in self.sync_attributes.items(): 611 value = getattr(self.obj, attr) 612 if attr in self.type_adapters: 613 # Use TypeAdapter to serialize with warnings disabled 614 result[key] = self.type_adapters[attr].dump_python( 615 value, mode="json", warnings=False 616 ) 617 else: 618 result[key] = deepcopy(value) 619 620 if self.task_exposure: 621 result[self.task_exposure] = list(self.running_tasks.keys()) 622 623 return result 624 625 # ========== Low-Level: Register Event Callbacks ========== # 626 def _register_event_handlers(self): 627 """ 628 Register event handlers with the session using weak references. 629 630 This allows the Sync object (and its target object) to be garbage collected 631 when no longer referenced, automatically cleaning up the handlers. 632 """ 633 # Capture values needed for cleanup callback (avoid capturing 'self') 634 session = self.session 635 key = self.key 636 send_on_init = self.send_on_init 637 638 # Create weak reference to self for use in wrappers 639 weak_self: weakref.ref[Sync] = weakref.ref(self) 640 641 # Factory to create async wrappers that check if Sync is still alive 642 def make_method_wrapper(method_name: str): 643 async def wrapper(data: Any = None) -> None: 644 sync = weak_self() 645 if sync is None: 646 return # Sync was garbage collected 647 method = getattr(sync, method_name) 648 if data is not None: 649 await method(data) 650 else: 651 await method() 652 653 return wrapper 654 655 # Create wrappers for the core state handlers 656 send_state_wrapper = make_method_wrapper("_send_state") 657 set_state_wrapper = make_method_wrapper("_set_state") 658 patch_state_wrapper = make_method_wrapper("_patch_state") 659 660 # Create wrappers for action/task handlers if they exist 661 actions_wrapper = None 662 if self.actions: 663 original_actions = self.actions 664 665 async def _actions_wrapper(data: Any): 666 sync = weak_self() 667 if sync is None: 668 return 669 await original_actions(data) 670 671 actions_wrapper = _actions_wrapper 672 673 tasks_wrapper = None 674 if self.tasks: 675 original_tasks = self.tasks 676 677 async def _tasks_wrapper(data: Any): 678 sync = weak_self() 679 if sync is None: 680 return 681 await original_tasks(data) 682 683 tasks_wrapper = _tasks_wrapper 684 685 task_cancels_wrapper = None 686 if self.task_cancels: 687 original_task_cancels = self.task_cancels 688 689 async def _task_cancels_wrapper(data: Any): 690 sync = weak_self() 691 if sync is None: 692 return 693 await original_task_cancels(data) 694 695 task_cancels_wrapper = _task_cancels_wrapper 696 697 # Register handlers with session 698 session.register_event(get_event(key), send_state_wrapper) 699 session.register_event(set_event(key), set_state_wrapper) 700 session.register_event(patch_event(key), patch_state_wrapper) 701 702 if send_on_init: 703 session.register_init(send_state_wrapper) 704 705 if actions_wrapper: 706 session.register_event(action_event(key), actions_wrapper) 707 708 if tasks_wrapper: 709 session.register_event(task_start_event(key), tasks_wrapper) 710 711 if task_cancels_wrapper: 712 session.register_event(task_cancel_event(key), task_cancels_wrapper) 713 714 # Store wrapper references for cleanup - we need to check identity before removing 715 # to avoid removing handlers that were overwritten by a newer Sync with same key 716 registered_handlers: dict[str, Callable[..., Any]] = { 717 get_event(key): send_state_wrapper, 718 set_event(key): set_state_wrapper, 719 patch_event(key): patch_state_wrapper, 720 } 721 if actions_wrapper: 722 registered_handlers[action_event(key)] = actions_wrapper 723 if tasks_wrapper: 724 registered_handlers[task_start_event(key)] = tasks_wrapper 725 if task_cancels_wrapper: 726 registered_handlers[task_cancel_event(key)] = task_cancels_wrapper 727 728 init_wrapper_to_remove = send_state_wrapper if send_on_init else None 729 730 # Create cleanup callback that runs when Sync is garbage collected 731 # This callback must NOT capture 'self' - only the variables above 732 def _weak_cleanup_callback(_dead_ref: weakref.ref[Sync]): 733 # Handle mock sessions gracefully (used in tests) 734 if not hasattr(session, "event_handlers"): 735 return 736 737 # Only deregister handlers if they're still ours (not overwritten by newer Sync) 738 for event_key, our_handler in registered_handlers.items(): 739 current_handler = session.event_handlers.get(event_key) 740 if current_handler is our_handler: 741 session.deregister_event(event_key) 742 743 # Remove from init_handlers list if applicable 744 if init_wrapper_to_remove is not None: 745 with suppress(ValueError): 746 session.init_handlers.remove(init_wrapper_to_remove) 747 748 # Store the weak reference with cleanup callback 749 # This ref must be stored to prevent immediate GC of the ref object itself 750 self._weak_self_ref = weakref.ref(self, _weak_cleanup_callback) 751 752 # Store references for manual deregistration via close() 753 self._init_wrapper = init_wrapper_to_remove 754 self._registered_handlers = registered_handlers 755 self._closed = False 756 757 def _deregister(self): 758 """ 759 Remove all event handlers from the session. 760 761 This is called automatically when the Sync is garbage collected, 762 but can also be called manually via close() for immediate cleanup. 763 """ 764 if self._closed: 765 return 766 self._closed = True 767 768 # Only deregister handlers if they're still ours (not overwritten by newer Sync) 769 for event_key, our_handler in self._registered_handlers.items(): 770 current_handler = self.session.event_handlers.get(event_key) 771 if current_handler is our_handler: 772 self.session.deregister_event(event_key) 773 774 # Remove from init_handlers list if applicable 775 if self._init_wrapper is not None: 776 with suppress(ValueError): 777 self.session.init_handlers.remove(self._init_wrapper) 778 779 def close(self): 780 """ 781 Explicitly close this Sync and deregister all handlers. 782 783 Call this when you're done with a Sync object to immediately release 784 resources. If not called, cleanup happens automatically when the 785 Sync is garbage collected. 786 787 This is idempotent - calling it multiple times is safe. 788 """ 789 self._deregister() 790 791 async def _send_state(self, _: Any = None): 792 self.state_snapshot = self._snapshot() 793 await self.session.send(set_event(self.key), self.state_snapshot) 794 795 async def _set_state(self, new_state: dict[str, Any]): 796 for key, val in new_state.items(): 797 if key == self.task_exposure: 798 continue 799 800 attr_name = self.key_to_attr[key] 801 value = deepcopy(val) 802 803 # if isinstance(self.obj, BaseModel): 804 # value = validate_model_field(type(self.obj), attr_name, value) 805 if attr_name in self.type_adapters: 806 value = self.type_adapters[attr_name].validate_python(value) 807 808 try: 809 setattr(self.obj, attr_name, value) 810 except AttributeError: 811 # Check if this is a computed field without setter - if so, skip silently 812 if ( 813 isinstance(self.obj, BaseModel) 814 and attr_name in type(self.obj).model_computed_fields 815 ): 816 computed_field = type(self.obj).model_computed_fields[attr_name] 817 if computed_field.wrapped_property.fset is None: 818 # Read-only computed field - skip setting, it will be recalculated 819 continue 820 821 # For other readonly attributes, skip setting 822 # Don't assert value equality because dependent properties may have changed 823 # when other attributes were set earlier in this loop 824 825 self.state_snapshot = new_state # update latest snapshot 826 827 async def _patch_state(self, patch: list[dict[str, Any]]): 828 # Apply patch to the snapshot first to update state tracking 829 self.state_snapshot = jsonpatch.apply_patch( 830 self.state_snapshot, patch, in_place=True 831 ) 832 833 # Extract the keys that were actually modified by the patch 834 modified_keys = set() 835 for patch_op in patch: 836 path = patch_op["path"] 837 if path.startswith("/"): 838 # Extract the top-level key from the path 839 key = path.split("/")[1] 840 if key in self.key_to_attr: 841 modified_keys.add(key) 842 843 # Only set attributes that were actually modified by the patch 844 for key in modified_keys: 845 if key == self.task_exposure: 846 continue 847 848 attr_name = self.key_to_attr[key] 849 value = deepcopy(self.state_snapshot[key]) 850 851 # if isinstance(self.obj, BaseModel): 852 # value = validate_model_field(type(self.obj), attr_name, value) 853 if attr_name in self.type_adapters: 854 value = self.type_adapters[attr_name].validate_python(value) 855 856 try: 857 setattr(self.obj, attr_name, value) 858 except AttributeError: 859 # Check if this is a computed field without setter - if so, skip silently 860 if ( 861 isinstance(self.obj, BaseModel) 862 and attr_name in type(self.obj).model_computed_fields 863 ): 864 computed_field = type(self.obj).model_computed_fields[attr_name] 865 if computed_field.wrapped_property.fset is None: 866 # Read-only computed field - skip setting, it will be recalculated 867 continue 868 869 # For other readonly attributes, skip setting 870 # Don't assert value equality because dependent properties may have changed 871 # when other attributes were set earlier in this loop 872 873 def _create_action_handler( 874 self, 875 obj: object, 876 handlers: Mapping[str, Callable[..., Any]], 877 ) -> Callable[[dict[str, Any]], Awaitable[None]]: 878 # Use weakrefs to avoid preventing GC of self and obj 879 weak_self: weakref.ref[Sync] = weakref.ref(self) 880 weak_obj: weakref.ref[object] = weakref.ref(obj) 881 882 async def _handle_action(action: dict): 883 sync = weak_self() 884 target = weak_obj() 885 if sync is None or target is None: 886 return # Already garbage collected 887 888 action_type = action.pop("type") 889 if handler := handlers.get(action_type): 890 # Validate action parameters, including converting to python 891 if validator := sync.action_validators.get(action_type): 892 validated = validator.validate_python(action) 893 if isinstance(validated, BaseModel): 894 # Extract native Python objects (BaseModel/dataclass/etc.) 895 kwargs = { 896 name: getattr(validated, name) 897 for name in type(validated).model_fields 898 } 899 else: 900 kwargs = validated # already a dict-like structure 901 else: 902 kwargs = action 903 904 # Call the underlying action handler 905 if getattr(handler, "__self__", None) is None: 906 await nonblock_call( 907 handler, target, **kwargs 908 ) # handler is unbound to an instance 909 else: 910 await nonblock_call( 911 handler, **kwargs 912 ) # handler is bound to an instance 913 else: 914 warnings.warn(f"No handler for action {action_type}", stacklevel=1) 915 916 return _handle_action 917 918 def _create_task_handlers( 919 self, 920 obj: object, 921 factories: Mapping[str, Callable[..., Awaitable[Any]]], 922 on_cancel: Mapping[str, Callable[..., Awaitable[Any]]] | None, 923 ) -> tuple[ 924 Callable[[dict[str, Any]], Awaitable[None]], 925 Callable[[dict[str, Any]], Awaitable[None]], 926 ]: 927 # Use weakrefs to avoid preventing GC of self and obj 928 weak_self: weakref.ref[Sync] = weakref.ref(self) 929 weak_obj: weakref.ref[object] = weakref.ref(obj) 930 931 async def _run_and_pop(task: Awaitable, task_type: str): 932 sync = weak_self() 933 try: 934 await task 935 except asyncio.CancelledError: 936 if sync and sync.logger: 937 sync.logger.info("Task %s cancelled", task_type) 938 if on_cancel and task_type in on_cancel: 939 await on_cancel[task_type]() 940 raise 941 finally: 942 if sync: 943 sync.running_tasks.pop(task_type, None) 944 if sync.task_exposure: 945 await sync.sync() 946 947 async def _create_task(task_args: dict): 948 sync = weak_self() 949 target = weak_obj() 950 if sync is None or target is None: 951 return # Already garbage collected 952 953 task_type = task_args.pop("type") 954 if factory := factories.get(task_type): 955 if task_type in sync.running_tasks: 956 if sync.logger: 957 sync.logger.warning("Task %s already running", task_type) 958 return 959 960 if validator := sync.task_validators.get(task_type): 961 validated = validator.validate_python(task_args) 962 if isinstance(validated, BaseModel): 963 # Extract native Python objects (BaseModel/dataclass/etc.) 964 kwargs = { 965 name: getattr(validated, name) 966 for name in type(validated).model_fields 967 } 968 else: 969 kwargs = validated # already a dict-like structure 970 else: 971 kwargs = task_args 972 973 # Create the task 974 if getattr(factory, "__self__", None) is None: 975 todo = nonblock_call( 976 factory, target, **kwargs 977 ) # factory is unbound to an instance 978 else: 979 todo = nonblock_call( 980 factory, **kwargs 981 ) # factory is bound to an instance 982 983 task = asyncio.create_task(_run_and_pop(todo, task_type)) 984 sync.running_tasks[task_type] = task 985 if sync.task_exposure: 986 await sync.sync() 987 else: 988 warnings.warn(f"No factory for task {task_type}", stacklevel=1) 989 990 async def _cancel_task(task_args: dict): 991 sync = weak_self() 992 if sync is None: 993 return # Already garbage collected 994 995 task_type = task_args.pop("type") 996 if running_task := sync.running_tasks.get(task_type): 997 running_task.cancel() 998 elif sync.logger: 999 sync.logger.warning("Task %s not running", task_type) 1000 1001 return _create_task, _cancel_task 1002 1003 # ========== Utils ========== # 1004 def casing(self, attr: str) -> str: 1005 return self.casing_func(attr) if self.casing_func else attr 1006 1007 # ========== Static validator builders with caching ========== # 1008 _field_validators_cache: dict[type, dict[str, TypeAdapter[Any]]] = {} 1009 """{class: {field: TypeAdapter}}; Dynamically registered fields may be added at runtime""" 1010 _action_validators_cache: dict[type, dict[str, TypeAdapter[Any]]] = {} 1011 """{class: {action_key: TypeAdapter}}; Dynamically registered actions may be added at runtime""" 1012 _task_validators_cache: dict[type, dict[str, TypeAdapter[Any]]] = {} 1013 """{class: {task_key: TypeAdapter}}; Dynamically registered tasks may be added at runtime""" 1014 1015 @staticmethod 1016 def build_kwargs_model( 1017 target_cls: type, 1018 model_name: str, 1019 func: Callable[..., Any], 1020 alias_generator: Callable[[str], str] | AliasGenerator | None, 1021 ) -> type[BaseModel]: 1022 """ 1023 Build a Pydantic model to validate the kwargs of a function. 1024 """ 1025 sig = signature(func) 1026 fields: dict[str, tuple[Any, Any]] = {} 1027 for idx, (param_name, param) in enumerate(sig.parameters.items()): 1028 if idx == 0 and param_name == "self": 1029 continue 1030 if param.kind in (Parameter.VAR_POSITIONAL, Parameter.VAR_KEYWORD): 1031 continue 1032 annotation = ( 1033 param.annotation if param.annotation is not Parameter.empty else Any 1034 ) 1035 default = param.default if param.default is not Parameter.empty else ... 1036 fields[param_name] = (annotation, default) 1037 1038 cfg = ConfigDict( 1039 alias_generator=alias_generator, 1040 validate_by_name=True, # Python -> Python (TODO: when?) 1041 validate_by_alias=True, # JSON -> Python 1042 ) 1043 model = create_model( 1044 model_name, 1045 __config__=cfg, 1046 __module__=target_cls.__module__, 1047 **cast("dict[str, Any]", fields), 1048 ) 1049 return model 1050 1051 @staticmethod 1052 def build_field_validators( 1053 target_cls: type, 1054 *, 1055 field_whitelist: Iterable[str] | None = None, 1056 use_cache: bool = True, 1057 ) -> dict[str, TypeAdapter[Any]]: 1058 """ 1059 Build a dictionary of field validators for a given class. 1060 1061 Args: 1062 target_cls: The class to build validators for. 1063 field_whitelist: A list of field names to include in the validators. If None, all fields are included. 1064 use_cache: Whether to use the cache. 1065 """ 1066 if use_cache and target_cls in Sync._field_validators_cache: 1067 return Sync._field_validators_cache[target_cls] 1068 1069 validators: dict[str, TypeAdapter[Any]] = {} 1070 if issubclass(target_cls, BaseModel): 1071 for name, field in target_cls.model_fields.items(): 1072 validators[name] = TypeAdapter(field.annotation) 1073 for name, field in target_cls.model_computed_fields.items(): 1074 validators[name] = TypeAdapter(field.return_type) 1075 1076 else: 1077 type_hints = get_type_hints(target_cls) 1078 if field_whitelist is not None: 1079 type_hints = { 1080 field: annotation 1081 for field in field_whitelist 1082 if (annotation := type_hints.get(field)) 1083 } 1084 for name, annotation in type_hints.items(): 1085 try: 1086 validators[name] = TypeAdapter(annotation) 1087 except PydanticSchemaGenerationError: 1088 logger.exception("Error building validator for %s", name) 1089 1090 if use_cache: 1091 Sync._field_validators_cache[target_cls] = validators 1092 return validators 1093 1094 @staticmethod 1095 def build_action_validators( 1096 target_cls: type, 1097 *, 1098 actions: dict[str, Callable[..., Any]] | None = None, 1099 schema_title_generator: SchemaTitleGenerator = default_action_title_generator, 1100 param_alias_generator: Callable[[str], str] | AliasGenerator | None = None, 1101 use_cache: bool = True, 1102 ) -> dict[str, TypeAdapter[Any]]: 1103 """ 1104 Build a dictionary of action validators for a given class. 1105 1106 Args: 1107 target_cls: The class whose actions to build validators for. 1108 actions: A dictionary of action names to functions. If None, all actions are included. 1109 schema_title_generator: A function to set the JSON schema title for each action. 1110 param_alias_generator: A function to set the JSON schema alias for the action *parameter names*. 1111 use_cache: Whether to use the cache for the validator objects. 1112 """ 1113 if param_alias_generator is None: 1114 param_alias_generator = get_alias_function_for_class(target_cls) 1115 1116 validators: dict[str, TypeAdapter[Any]] = {} 1117 1118 cache_key = target_cls 1119 if use_cache and cache_key in Sync._action_validators_cache: 1120 validators = Sync._action_validators_cache[cache_key] 1121 1122 actions = actions or find_remote_actions(target_cls) 1123 for key, func in actions.items(): 1124 if key in validators: 1125 continue 1126 1127 model = Sync.build_kwargs_model( 1128 target_cls=target_cls, 1129 model_name=schema_title_generator( 1130 class_name=target_cls.__name__, key=key 1131 ), 1132 func=func, 1133 alias_generator=param_alias_generator, 1134 ) 1135 validators[key] = TypeAdapter(model) 1136 1137 if use_cache: 1138 Sync._action_validators_cache[cache_key] = validators 1139 return validators 1140 1141 @staticmethod 1142 def build_task_validators( 1143 target_cls: type, 1144 *, 1145 tasks: dict[str, Callable[..., Any]] | None = None, 1146 schema_title_generator: SchemaTitleGenerator = default_task_title_generator, 1147 param_alias_generator: Callable[[str], str] | AliasGenerator | None = None, 1148 use_cache: bool = True, 1149 ) -> dict[str, TypeAdapter[Any]]: 1150 """ 1151 Build a dictionary of task validators for a given class. 1152 1153 Args: 1154 target_cls: The class whose tasks to build validators for. 1155 tasks: A dictionary of task names to functions. If None, all tasks are included. 1156 schema_title_generator: A function to set the JSON schema title for each task. 1157 param_alias_generator: A function to set the JSON schema alias for the task *parameter names*. 1158 use_cache: Whether to use the cache for the validator objects. 1159 """ 1160 if param_alias_generator is None: 1161 param_alias_generator = get_alias_function_for_class(target_cls) 1162 1163 validators: dict[str, TypeAdapter[Any]] = {} 1164 1165 cache_key = target_cls 1166 if use_cache and cache_key in Sync._task_validators_cache: 1167 validators = Sync._task_validators_cache[cache_key] 1168 1169 tasks = tasks or find_remote_tasks(target_cls) 1170 for key, func in tasks.items(): 1171 if key in validators: 1172 continue 1173 1174 model = Sync.build_kwargs_model( 1175 target_cls=target_cls, 1176 model_name=schema_title_generator( 1177 class_name=target_cls.__name__, key=key 1178 ), 1179 func=func, 1180 alias_generator=param_alias_generator, 1181 ) 1182 validators[key] = TypeAdapter(model) 1183 1184 if use_cache: 1185 Sync._task_validators_cache[cache_key] = validators 1186 return validators
47class sync_key_scope: # noqa: N801 48 """ 49 Context manager for scoping sync keys with a prefix. 50 51 All Sync objects created within this context will have their keys prefixed. 52 Supports nesting - nested scopes will create hierarchical prefixes with '/' separator. 53 54 Example: 55 ```python 56 with sync_key_scope("user123"): 57 obj1 = MyObject() # key: "user123/MY_KEY" 58 59 with sync_key_scope("session456"): 60 obj2 = MyObject() # key: "user123/session456/MY_KEY" 61 ``` 62 63 Args: 64 prefix: The prefix to add. Empty strings and None are ignored (no prefix added). 65 """ 66 67 def __init__(self, prefix: str | None): 68 self.prefix = prefix 69 self.token: Token[list[str] | None] | None = None 70 71 def __enter__(self) -> Self: 72 # Only add non-empty prefixes 73 if self.prefix: 74 # Get current stack (creates a copy to avoid mutation issues) 75 current_stack = _sync_key_prefix_stack.get() 76 current_stack = [] if current_stack is None else current_stack.copy() 77 current_stack.append(self.prefix) 78 self.token = _sync_key_prefix_stack.set(current_stack) 79 return self 80 81 def __exit__( 82 self, 83 exc_type: type[BaseException] | None, 84 exc_value: BaseException | None, 85 traceback: object, 86 ) -> None: 87 if self.token is not None: 88 _sync_key_prefix_stack.reset(self.token) 89 self.token = None
Context manager for scoping sync keys with a prefix.
All Sync objects created within this context will have their keys prefixed. Supports nesting - nested scopes will create hierarchical prefixes with '/' separator.
Example:
with sync_key_scope("user123"): obj1 = MyObject() # key: "user123/MY_KEY" with sync_key_scope("session456"): obj2 = MyObject() # key: "user123/session456/MY_KEY"
Arguments:
- prefix: The prefix to add. Empty strings and None are ignored (no prefix added).
92def get_current_sync_key_prefix() -> str | None: 93 """ 94 Get the current sync key prefix from nested scopes. 95 96 Returns: 97 The full hierarchical prefix string (e.g., "abc/nested/deep"), 98 or None if no prefix scope is active. 99 100 Example: 101 ```python 102 with sync_key_scope("abc"): 103 with sync_key_scope("nested"): 104 prefix = get_current_sync_key_prefix() # "abc/nested" 105 ``` 106 """ 107 stack = _sync_key_prefix_stack.get() 108 if not stack: 109 return None 110 return "/".join(stack)
Get the current sync key prefix from nested scopes.
Returns:
The full hierarchical prefix string (e.g., "abc/nested/deep"), or None if no prefix scope is active.
Example:
with sync_key_scope("abc"): with sync_key_scope("nested"): prefix = get_current_sync_key_prefix() # "abc/nested"
State has been set
State has been requested
State has been patched
Action has been dispatched
Task has been started
155def task_cancel_event(key: str): 156 """Task has been cancelled""" 157 return f"_TASK_CANCEL:{key}"
Task has been cancelled
Toast message has been sent
File has been sent for download
176class SchemaTitleGenerator(Protocol): 177 def __call__(self, class_name: str, key: str) -> str: ...
Base class for protocol classes.
Protocol classes are defined as::
class Proto(Protocol):
def meth(self) -> int:
...
Such classes are primarily used with static type checkers that recognize structural subtyping (static duck-typing).
For example::
class C:
def meth(self) -> int:
return 0
def func(x: Proto) -> int:
return x.meth()
func(C()) # Passes static type check
See PEP 544 for details. Protocol classes decorated with @typing.runtime_checkable act as simple-minded runtime protocols that check only the presence of given attributes, ignoring their type signatures. Protocol classes can be generic, they are defined as::
class GenProto[T](Protocol):
def meth(self) -> T:
...
1771def _no_init_or_replace_init(self, *args, **kwargs): 1772 cls = type(self) 1773 1774 if cls._is_protocol: 1775 raise TypeError('Protocols cannot be instantiated') 1776 1777 # Already using a custom `__init__`. No need to calculate correct 1778 # `__init__` to call. This can lead to RecursionError. See bpo-45121. 1779 if cls.__init__ is not _no_init_or_replace_init: 1780 return 1781 1782 # Initially, `__init__` of a protocol subclass is set to `_no_init_or_replace_init`. 1783 # The first instantiation of the subclass will call `_no_init_or_replace_init` which 1784 # searches for a proper new `__init__` in the MRO. The new `__init__` 1785 # replaces the subclass' old `__init__` (ie `_no_init_or_replace_init`). Subsequent 1786 # instantiation of the protocol subclass will thus use the new 1787 # `__init__` and no longer call `_no_init_or_replace_init`. 1788 for base in cls.__mro__: 1789 init = base.__dict__.get('__init__', _no_init_or_replace_init) 1790 if init is not _no_init_or_replace_init: 1791 cls.__init__ = init 1792 break 1793 else: 1794 # should not happen 1795 cls.__init__ = object.__init__ 1796 1797 cls.__init__(self, *args, **kwargs)
181 lambda class_name, key: f"{class_name}Action{to_pascal(key)}"
184 lambda class_name, key: f"{class_name}Task{to_pascal(key)}"
188class Sync: 189 """ 190 Register an object's attributes to this class to sync them with the frontend. 191 """ 192 193 @classmethod 194 def all( 195 cls, 196 obj: object, 197 key: str, 198 *, 199 include: dict[str, str | EllipsisType] | list[str] | None = None, 200 exclude: list[str] | None = None, 201 toCamelCase: bool | None = None, # noqa: N803 202 send_on_init: bool = True, 203 expose_running_tasks: bool = False, 204 logger: Logger | None = None, 205 actions: Mapping[str, Callable[..., Any]] | None = None, 206 tasks: Mapping[str, Callable[..., Awaitable[Any]]] | None = None, 207 task_cancels: Mapping[str, Callable[..., Awaitable[Any]]] | None = None, 208 ) -> "Sync": 209 return cls( 210 obj=obj, 211 key=key, 212 sync_all=True, 213 include=include, 214 exclude=exclude or [], 215 toCamelCase=toCamelCase, 216 send_on_init=send_on_init, 217 expose_running_tasks=expose_running_tasks, 218 logger=logger, 219 actions=actions, 220 tasks=tasks, 221 task_cancels=task_cancels, 222 ) 223 224 @classmethod 225 def only( 226 cls, 227 _obj: object, 228 _key: str, 229 *, 230 _toCamelCase: bool | None = None, # noqa: N803 231 _send_on_init: bool = True, 232 _expose_running_tasks: bool = False, 233 _logger: Logger | None = None, 234 _actions: Mapping[str, Callable[..., Any]] | None = None, 235 _tasks: Mapping[str, Callable[..., Awaitable[Any]]] | None = None, 236 _task_cancels: Mapping[str, Callable[..., Awaitable[Any]]] | None = None, 237 **sync_attributes: str | EllipsisType, 238 ) -> "Sync": 239 return cls( 240 obj=_obj, 241 key=_key, 242 sync_all=False, 243 include=sync_attributes, 244 exclude=[], 245 toCamelCase=_toCamelCase, 246 send_on_init=_send_on_init, 247 expose_running_tasks=_expose_running_tasks, 248 logger=_logger, 249 actions=_actions, 250 tasks=_tasks, 251 task_cancels=_task_cancels, 252 ) 253 254 @staticmethod 255 def resolve_attributes( 256 obj_or_cls: object | type, 257 *, 258 include: dict[str, str | EllipsisType] | None = None, 259 exclude: list[str] | None = None, 260 sync_all: bool = False, 261 casing_func: Callable[[str], str] | None = None, 262 ) -> dict[str, str]: 263 """ 264 Resolve which attributes to sync based on configuration. 265 266 Returns: 267 Dict mapping attribute name to sync key (alias). 268 """ 269 include = include or {} 270 exclude = exclude or [] 271 sync_attributes: dict[str, str] = {} 272 273 is_class = isinstance(obj_or_cls, type) 274 cls = obj_or_cls if is_class else type(obj_or_cls) 275 276 def casing(attr: str) -> str: 277 return casing_func(attr) if casing_func else attr 278 279 # observe all non-private attributes 280 if sync_all: 281 if issubclass(cls, BaseModel): 282 # Include regular fields 283 for field in cls.model_fields: 284 if field in exclude: 285 continue 286 sync_attributes[field] = casing(field) 287 288 # Include computed fields 289 for field in cls.model_computed_fields: 290 if field in exclude: 291 continue 292 sync_attributes[field] = casing(field) 293 # For regular classes, we need an instance to check dir() reliably for instance attrs, 294 # but we can check class attrs if we only have a class. 295 # However, if we only have a class, we can't know instance attributes that are set in __init__. 296 # So sync_all=True for plain classes really works best with an instance. 297 # If we have a class, we can only guess based on annotations or class attributes. 298 elif is_class: 299 # Best effort for static analysis of plain classes 300 # We can check type hints 301 for attr_name in get_type_hints(cls): 302 if attr_name in exclude or attr_name.startswith("_"): 303 continue 304 sync_attributes[attr_name] = casing(attr_name) 305 else: 306 for attr_name in dir(obj_or_cls): 307 try: 308 attr = getattr(obj_or_cls, attr_name) 309 except AttributeError: 310 continue 311 if ( 312 attr_name in exclude 313 or attr_name.startswith("_") 314 or callable(attr) 315 or isinstance(attr, Sync) 316 ): 317 continue 318 319 sync_attributes[attr_name] = casing(attr_name) 320 321 # observe specific attributes 322 for attr_name, sync_key in include.items(): 323 sync_attributes[attr_name] = ( 324 casing(attr_name) if sync_key is ... else cast(str, sync_key) 325 ) 326 327 return sync_attributes 328 329 def __init__( 330 self, 331 obj: object, 332 key: str, 333 *, 334 sync_all: bool = False, 335 include: dict[str, str | EllipsisType] | list[str] | None = None, 336 exclude: list[str] | None = None, 337 toCamelCase: bool | None = None, # noqa: N803 338 send_on_init: bool = True, 339 expose_running_tasks: bool = False, 340 logger: Logger | None = None, 341 actions: Mapping[str, Callable[..., Any]] | None = None, 342 tasks: Mapping[str, Callable[..., Awaitable[Any]]] | None = None, 343 task_cancels: Mapping[str, Callable[..., Awaitable[Any]]] | None = None, 344 ): 345 """ 346 Register the attributes that should be synced with the frontend. 347 348 Args: 349 obj: the object whose attributes should be synced 350 key: unique key for this object 351 352 sync_all: whether to sync all non-private attributes 353 include: attribute names to sync, value being either ... 354 or a string of the key of the attribute 355 exclude: list of attributes to exclude from syncing 356 357 toCamelCase: convert attribute names to camelCase. Must be ``None`` for 358 Pydantic models, which should configure ``alias_generator`` 359 send_on_init: whether to send the state on connection init 360 expose_running_tasks: whether to expose the running tasks to the frontend 361 logger: logger to use for logging 362 363 actions: action handlers for each action type, each taking the data of the action as keyword arguments 364 tasks: either a dict of task factories for each task type, each returning a coroutine to be used as a task, or a tuple of (task_start_handler, task_cancel_handler) 365 task_cancels: a dict of task cancel handlers for each task type 366 367 368 """ 369 self.obj = obj 370 self.key = _apply_sync_key_prefix(key) 371 self.send_on_init = send_on_init 372 self.casing_func = ( 373 get_alias_function_for_class(type(self.obj)) 374 if isinstance(self.obj, BaseModel) 375 else (to_camel if toCamelCase else None) 376 ) 377 self.task_exposure = ( 378 self.casing("running_tasks") if expose_running_tasks else None 379 ) 380 self.logger = logger 381 382 # Convert list[str] include to dict format 383 if isinstance(include, list): 384 include = dict.fromkeys(include, ...) 385 include = include or {} 386 exclude = exclude or [] 387 388 # Validate that BaseModel objects don't use custom sync keys 389 if isinstance(obj, BaseModel) and include: 390 for attr_name, sync_key in include.items(): 391 assert sync_key is ..., ( 392 f"Custom sync key '{sync_key}' for attribute '{attr_name}' is not allowed for Pydantic models. Use pydantic's alias_generator in model_config instead." 393 ) 394 395 self.session = session_context.get() 396 assert self.session, "No session set, use the session.session_context variable!" 397 398 # ========== Create Action Validators (cached) ========== # 399 actions = dict(actions or {}) | find_remote_actions(type(self.obj)) 400 self.action_validators: dict[str, TypeAdapter[Any]] = ( 401 self.build_action_validators( 402 target_cls=type(self.obj), 403 actions=actions, 404 param_alias_generator=self.casing_func, 405 ) 406 ) 407 # Create action handler after validators are ready 408 self.actions = self._create_action_handler(obj, actions) 409 410 # ========== Create Task Validators (cached) ========== # 411 tasks = dict(tasks or {}) | find_remote_tasks(type(self.obj)) 412 task_cancels = dict(task_cancels or {}) | find_remote_task_cancellers( 413 type(self.obj) 414 ) 415 self.task_validators: dict[str, TypeAdapter[Any]] = self.build_task_validators( 416 target_cls=type(self.obj), 417 tasks=tasks, 418 param_alias_generator=self.casing_func, 419 ) 420 self.tasks, self.task_cancels = self._create_task_handlers( 421 obj, tasks, task_cancels 422 ) 423 424 # store running tasks 425 self.running_tasks: dict[str, asyncio.Task[Any]] = {} 426 427 # ========== Find attributes to sync ========== # 428 self.sync_attributes: dict[str, str] = {} 429 430 # observe all non-private attributes 431 if sync_all: 432 if isinstance(obj, BaseModel): 433 # Include regular fields 434 for field in type(obj).model_fields: 435 if field in exclude: 436 continue 437 self.sync_attributes[field] = self.casing(field) 438 439 # Include computed fields 440 for field in type(obj).model_computed_fields: 441 if field in exclude: 442 continue 443 self.sync_attributes[field] = self.casing(field) 444 else: 445 for attr_name in dir(obj): 446 try: 447 attr = getattr(obj, attr_name) 448 except AttributeError: 449 continue 450 if ( 451 attr_name in exclude 452 or attr_name.startswith("_") 453 or callable(attr) 454 or isinstance(attr, Sync) 455 ): 456 continue 457 458 self.sync_attributes[attr_name] = self.casing(attr_name) 459 460 # observe specific attributes 461 for attr_name, sync_key in include.items(): 462 self.sync_attributes[attr_name] = ( 463 self.casing(attr_name) if sync_key is ... else sync_key 464 ) 465 466 # create reverse-lookup for patching 467 self.key_to_attr: dict[str, str] = { 468 key: attr for attr, key in self.sync_attributes.items() 469 } 470 471 # ========== Debugging ========== # 472 if self.logger: 473 self.logger.debug("%s: Syncing %s", self.key, self.sync_attributes) 474 self.logger.debug("%s: Actions %s", self.key, actions) 475 self.logger.debug("%s: Tasks %s", self.key, tasks) 476 self.logger.debug("%s: Task Cancels %s", self.key, task_cancels) 477 478 assert include.keys().isdisjoint(exclude), "Attribute in both include & exclude" 479 assert all(a in dir(obj) for a in self.sync_attributes), "Attribute not found" 480 assert all(e in dir(obj) for e in exclude), "Excluded attribute not found" 481 # assert ( 482 # len(self.sync_attributes) + expose_running_tasks > 0 483 # ), "No attributes to sync" 484 485 # ========== Field Type Adapters (cached) ========== # 486 self.type_adapters: dict[str, TypeAdapter[Any]] = self.build_field_validators( 487 type(obj), field_whitelist=self.sync_attributes.keys() 488 ) 489 490 # ========== State Management ========== # 491 # the snapshot is the exact state that the frontend has, for patching 492 self.state_snapshot: dict[str, Any] = self._snapshot() 493 self._last_sync: float | None = None # timestamp of last sync 494 495 # ========== Weak Reference Cleanup State ========== # 496 self._closed = False 497 self._init_wrapper: Callable[..., Any] | None = None 498 self._registered_handlers: dict[str, Callable[..., Any]] = {} 499 self._weak_self_ref: weakref.ref[Sync] | None = None 500 self._register_event_handlers() 501 502 # ========== High-Level: Sync and Actions ========== # 503 async def sync(self, if_since_last: float | None = None): 504 """ 505 Sync all registered attributes. 506 507 Args: 508 if_since_last: only sync if the last sync was before this many seconds 509 """ 510 if not self.session.is_connected: 511 return 512 t = time() 513 if if_since_last and self._last_sync and t - self._last_sync < if_since_last: 514 return 515 516 # calculate patch 517 prev = self.state_snapshot 518 self.state_snapshot = self._snapshot() 519 patch = jsonpatch.make_patch(prev, self.state_snapshot).patch 520 521 if len(patch) > 0: 522 await self.session.send(patch_event(self.key), patch) 523 self._last_sync = t 524 525 async def __call__( 526 self, 527 if_since_last: float | None = None, 528 toast: str | None = None, 529 type: ToastType = "default", # noqa: A002 530 ): 531 """ 532 Sync all registered attributes. 533 534 Args: 535 if_since_last: only sync if the last sync was before this many seconds 536 toast: toast message to send after syncing 537 type: toast type 538 """ 539 await self.sync(if_since_last=if_since_last) 540 if toast: 541 await self.toast(toast, type=type) 542 543 async def send_action(self, action: dict[str, Any]): 544 """ 545 Send an action to the frontend. 546 """ 547 await self.session.send(action_event(self.key), action) 548 549 async def send_binary(self, metadata: dict[str, Any], data: bytes): 550 """ 551 Send binary data to the frontend, along with metadata. 552 553 This is a subset of an action, but with bytes data always included. 554 """ 555 await self.session.send_binary(action_event(self.key), metadata, data) 556 557 async def toast( 558 self, 559 *messages, 560 type: ToastType = "default", # noqa: A002 561 logger: Logger | None = None, 562 ) -> str: 563 """ 564 Send a toast message to the frontend. 565 566 Returns the sent message content, so that you can easily return or print it. 567 """ 568 messages = " ".join(str(message) for message in messages) 569 570 if lg := (logger or self.logger): 571 match type: 572 case "default": 573 lg.debug(messages) 574 case "message" | "info" | "success": 575 lg.info(messages) 576 case "warning": 577 lg.warning(messages) 578 case "error": 579 lg.error(messages) 580 case _: 581 lg.debug(messages) 582 583 await self.session.send(toast_event(), {"type": type, "message": messages}) 584 return messages 585 586 async def download(self, filename: str, binary: bytes) -> None: 587 """ 588 Send a file to the frontend for download. 589 """ 590 data = base64.b64encode(binary).decode("utf-8") 591 await self.session.send(download_event(), {"filename": filename, "data": data}) 592 593 def observe(self, obj: object, **sync_attributes: str | EllipsisType) -> None: 594 """ 595 Observe additional attributes, useful for when you're extending/subclassing an already Synced object, or when you want to observe multiple objects. 596 """ 597 # TODO: append, deregister, re-register 598 599 # ========== Low-Level: State Management ========== # 600 def _snapshot(self) -> dict[str, Any]: 601 result = {} 602 603 if isinstance(self.obj, BaseModel): 604 # TODO: maybe always explicitly serialize using TypeAdapters like below, since the model maybe be configured for other serialization use cases? 605 result = self.obj.model_dump( 606 mode="json", 607 include=set(self.sync_attributes.keys()), 608 warnings=False, 609 ) 610 else: 611 for attr, key in self.sync_attributes.items(): 612 value = getattr(self.obj, attr) 613 if attr in self.type_adapters: 614 # Use TypeAdapter to serialize with warnings disabled 615 result[key] = self.type_adapters[attr].dump_python( 616 value, mode="json", warnings=False 617 ) 618 else: 619 result[key] = deepcopy(value) 620 621 if self.task_exposure: 622 result[self.task_exposure] = list(self.running_tasks.keys()) 623 624 return result 625 626 # ========== Low-Level: Register Event Callbacks ========== # 627 def _register_event_handlers(self): 628 """ 629 Register event handlers with the session using weak references. 630 631 This allows the Sync object (and its target object) to be garbage collected 632 when no longer referenced, automatically cleaning up the handlers. 633 """ 634 # Capture values needed for cleanup callback (avoid capturing 'self') 635 session = self.session 636 key = self.key 637 send_on_init = self.send_on_init 638 639 # Create weak reference to self for use in wrappers 640 weak_self: weakref.ref[Sync] = weakref.ref(self) 641 642 # Factory to create async wrappers that check if Sync is still alive 643 def make_method_wrapper(method_name: str): 644 async def wrapper(data: Any = None) -> None: 645 sync = weak_self() 646 if sync is None: 647 return # Sync was garbage collected 648 method = getattr(sync, method_name) 649 if data is not None: 650 await method(data) 651 else: 652 await method() 653 654 return wrapper 655 656 # Create wrappers for the core state handlers 657 send_state_wrapper = make_method_wrapper("_send_state") 658 set_state_wrapper = make_method_wrapper("_set_state") 659 patch_state_wrapper = make_method_wrapper("_patch_state") 660 661 # Create wrappers for action/task handlers if they exist 662 actions_wrapper = None 663 if self.actions: 664 original_actions = self.actions 665 666 async def _actions_wrapper(data: Any): 667 sync = weak_self() 668 if sync is None: 669 return 670 await original_actions(data) 671 672 actions_wrapper = _actions_wrapper 673 674 tasks_wrapper = None 675 if self.tasks: 676 original_tasks = self.tasks 677 678 async def _tasks_wrapper(data: Any): 679 sync = weak_self() 680 if sync is None: 681 return 682 await original_tasks(data) 683 684 tasks_wrapper = _tasks_wrapper 685 686 task_cancels_wrapper = None 687 if self.task_cancels: 688 original_task_cancels = self.task_cancels 689 690 async def _task_cancels_wrapper(data: Any): 691 sync = weak_self() 692 if sync is None: 693 return 694 await original_task_cancels(data) 695 696 task_cancels_wrapper = _task_cancels_wrapper 697 698 # Register handlers with session 699 session.register_event(get_event(key), send_state_wrapper) 700 session.register_event(set_event(key), set_state_wrapper) 701 session.register_event(patch_event(key), patch_state_wrapper) 702 703 if send_on_init: 704 session.register_init(send_state_wrapper) 705 706 if actions_wrapper: 707 session.register_event(action_event(key), actions_wrapper) 708 709 if tasks_wrapper: 710 session.register_event(task_start_event(key), tasks_wrapper) 711 712 if task_cancels_wrapper: 713 session.register_event(task_cancel_event(key), task_cancels_wrapper) 714 715 # Store wrapper references for cleanup - we need to check identity before removing 716 # to avoid removing handlers that were overwritten by a newer Sync with same key 717 registered_handlers: dict[str, Callable[..., Any]] = { 718 get_event(key): send_state_wrapper, 719 set_event(key): set_state_wrapper, 720 patch_event(key): patch_state_wrapper, 721 } 722 if actions_wrapper: 723 registered_handlers[action_event(key)] = actions_wrapper 724 if tasks_wrapper: 725 registered_handlers[task_start_event(key)] = tasks_wrapper 726 if task_cancels_wrapper: 727 registered_handlers[task_cancel_event(key)] = task_cancels_wrapper 728 729 init_wrapper_to_remove = send_state_wrapper if send_on_init else None 730 731 # Create cleanup callback that runs when Sync is garbage collected 732 # This callback must NOT capture 'self' - only the variables above 733 def _weak_cleanup_callback(_dead_ref: weakref.ref[Sync]): 734 # Handle mock sessions gracefully (used in tests) 735 if not hasattr(session, "event_handlers"): 736 return 737 738 # Only deregister handlers if they're still ours (not overwritten by newer Sync) 739 for event_key, our_handler in registered_handlers.items(): 740 current_handler = session.event_handlers.get(event_key) 741 if current_handler is our_handler: 742 session.deregister_event(event_key) 743 744 # Remove from init_handlers list if applicable 745 if init_wrapper_to_remove is not None: 746 with suppress(ValueError): 747 session.init_handlers.remove(init_wrapper_to_remove) 748 749 # Store the weak reference with cleanup callback 750 # This ref must be stored to prevent immediate GC of the ref object itself 751 self._weak_self_ref = weakref.ref(self, _weak_cleanup_callback) 752 753 # Store references for manual deregistration via close() 754 self._init_wrapper = init_wrapper_to_remove 755 self._registered_handlers = registered_handlers 756 self._closed = False 757 758 def _deregister(self): 759 """ 760 Remove all event handlers from the session. 761 762 This is called automatically when the Sync is garbage collected, 763 but can also be called manually via close() for immediate cleanup. 764 """ 765 if self._closed: 766 return 767 self._closed = True 768 769 # Only deregister handlers if they're still ours (not overwritten by newer Sync) 770 for event_key, our_handler in self._registered_handlers.items(): 771 current_handler = self.session.event_handlers.get(event_key) 772 if current_handler is our_handler: 773 self.session.deregister_event(event_key) 774 775 # Remove from init_handlers list if applicable 776 if self._init_wrapper is not None: 777 with suppress(ValueError): 778 self.session.init_handlers.remove(self._init_wrapper) 779 780 def close(self): 781 """ 782 Explicitly close this Sync and deregister all handlers. 783 784 Call this when you're done with a Sync object to immediately release 785 resources. If not called, cleanup happens automatically when the 786 Sync is garbage collected. 787 788 This is idempotent - calling it multiple times is safe. 789 """ 790 self._deregister() 791 792 async def _send_state(self, _: Any = None): 793 self.state_snapshot = self._snapshot() 794 await self.session.send(set_event(self.key), self.state_snapshot) 795 796 async def _set_state(self, new_state: dict[str, Any]): 797 for key, val in new_state.items(): 798 if key == self.task_exposure: 799 continue 800 801 attr_name = self.key_to_attr[key] 802 value = deepcopy(val) 803 804 # if isinstance(self.obj, BaseModel): 805 # value = validate_model_field(type(self.obj), attr_name, value) 806 if attr_name in self.type_adapters: 807 value = self.type_adapters[attr_name].validate_python(value) 808 809 try: 810 setattr(self.obj, attr_name, value) 811 except AttributeError: 812 # Check if this is a computed field without setter - if so, skip silently 813 if ( 814 isinstance(self.obj, BaseModel) 815 and attr_name in type(self.obj).model_computed_fields 816 ): 817 computed_field = type(self.obj).model_computed_fields[attr_name] 818 if computed_field.wrapped_property.fset is None: 819 # Read-only computed field - skip setting, it will be recalculated 820 continue 821 822 # For other readonly attributes, skip setting 823 # Don't assert value equality because dependent properties may have changed 824 # when other attributes were set earlier in this loop 825 826 self.state_snapshot = new_state # update latest snapshot 827 828 async def _patch_state(self, patch: list[dict[str, Any]]): 829 # Apply patch to the snapshot first to update state tracking 830 self.state_snapshot = jsonpatch.apply_patch( 831 self.state_snapshot, patch, in_place=True 832 ) 833 834 # Extract the keys that were actually modified by the patch 835 modified_keys = set() 836 for patch_op in patch: 837 path = patch_op["path"] 838 if path.startswith("/"): 839 # Extract the top-level key from the path 840 key = path.split("/")[1] 841 if key in self.key_to_attr: 842 modified_keys.add(key) 843 844 # Only set attributes that were actually modified by the patch 845 for key in modified_keys: 846 if key == self.task_exposure: 847 continue 848 849 attr_name = self.key_to_attr[key] 850 value = deepcopy(self.state_snapshot[key]) 851 852 # if isinstance(self.obj, BaseModel): 853 # value = validate_model_field(type(self.obj), attr_name, value) 854 if attr_name in self.type_adapters: 855 value = self.type_adapters[attr_name].validate_python(value) 856 857 try: 858 setattr(self.obj, attr_name, value) 859 except AttributeError: 860 # Check if this is a computed field without setter - if so, skip silently 861 if ( 862 isinstance(self.obj, BaseModel) 863 and attr_name in type(self.obj).model_computed_fields 864 ): 865 computed_field = type(self.obj).model_computed_fields[attr_name] 866 if computed_field.wrapped_property.fset is None: 867 # Read-only computed field - skip setting, it will be recalculated 868 continue 869 870 # For other readonly attributes, skip setting 871 # Don't assert value equality because dependent properties may have changed 872 # when other attributes were set earlier in this loop 873 874 def _create_action_handler( 875 self, 876 obj: object, 877 handlers: Mapping[str, Callable[..., Any]], 878 ) -> Callable[[dict[str, Any]], Awaitable[None]]: 879 # Use weakrefs to avoid preventing GC of self and obj 880 weak_self: weakref.ref[Sync] = weakref.ref(self) 881 weak_obj: weakref.ref[object] = weakref.ref(obj) 882 883 async def _handle_action(action: dict): 884 sync = weak_self() 885 target = weak_obj() 886 if sync is None or target is None: 887 return # Already garbage collected 888 889 action_type = action.pop("type") 890 if handler := handlers.get(action_type): 891 # Validate action parameters, including converting to python 892 if validator := sync.action_validators.get(action_type): 893 validated = validator.validate_python(action) 894 if isinstance(validated, BaseModel): 895 # Extract native Python objects (BaseModel/dataclass/etc.) 896 kwargs = { 897 name: getattr(validated, name) 898 for name in type(validated).model_fields 899 } 900 else: 901 kwargs = validated # already a dict-like structure 902 else: 903 kwargs = action 904 905 # Call the underlying action handler 906 if getattr(handler, "__self__", None) is None: 907 await nonblock_call( 908 handler, target, **kwargs 909 ) # handler is unbound to an instance 910 else: 911 await nonblock_call( 912 handler, **kwargs 913 ) # handler is bound to an instance 914 else: 915 warnings.warn(f"No handler for action {action_type}", stacklevel=1) 916 917 return _handle_action 918 919 def _create_task_handlers( 920 self, 921 obj: object, 922 factories: Mapping[str, Callable[..., Awaitable[Any]]], 923 on_cancel: Mapping[str, Callable[..., Awaitable[Any]]] | None, 924 ) -> tuple[ 925 Callable[[dict[str, Any]], Awaitable[None]], 926 Callable[[dict[str, Any]], Awaitable[None]], 927 ]: 928 # Use weakrefs to avoid preventing GC of self and obj 929 weak_self: weakref.ref[Sync] = weakref.ref(self) 930 weak_obj: weakref.ref[object] = weakref.ref(obj) 931 932 async def _run_and_pop(task: Awaitable, task_type: str): 933 sync = weak_self() 934 try: 935 await task 936 except asyncio.CancelledError: 937 if sync and sync.logger: 938 sync.logger.info("Task %s cancelled", task_type) 939 if on_cancel and task_type in on_cancel: 940 await on_cancel[task_type]() 941 raise 942 finally: 943 if sync: 944 sync.running_tasks.pop(task_type, None) 945 if sync.task_exposure: 946 await sync.sync() 947 948 async def _create_task(task_args: dict): 949 sync = weak_self() 950 target = weak_obj() 951 if sync is None or target is None: 952 return # Already garbage collected 953 954 task_type = task_args.pop("type") 955 if factory := factories.get(task_type): 956 if task_type in sync.running_tasks: 957 if sync.logger: 958 sync.logger.warning("Task %s already running", task_type) 959 return 960 961 if validator := sync.task_validators.get(task_type): 962 validated = validator.validate_python(task_args) 963 if isinstance(validated, BaseModel): 964 # Extract native Python objects (BaseModel/dataclass/etc.) 965 kwargs = { 966 name: getattr(validated, name) 967 for name in type(validated).model_fields 968 } 969 else: 970 kwargs = validated # already a dict-like structure 971 else: 972 kwargs = task_args 973 974 # Create the task 975 if getattr(factory, "__self__", None) is None: 976 todo = nonblock_call( 977 factory, target, **kwargs 978 ) # factory is unbound to an instance 979 else: 980 todo = nonblock_call( 981 factory, **kwargs 982 ) # factory is bound to an instance 983 984 task = asyncio.create_task(_run_and_pop(todo, task_type)) 985 sync.running_tasks[task_type] = task 986 if sync.task_exposure: 987 await sync.sync() 988 else: 989 warnings.warn(f"No factory for task {task_type}", stacklevel=1) 990 991 async def _cancel_task(task_args: dict): 992 sync = weak_self() 993 if sync is None: 994 return # Already garbage collected 995 996 task_type = task_args.pop("type") 997 if running_task := sync.running_tasks.get(task_type): 998 running_task.cancel() 999 elif sync.logger: 1000 sync.logger.warning("Task %s not running", task_type) 1001 1002 return _create_task, _cancel_task 1003 1004 # ========== Utils ========== # 1005 def casing(self, attr: str) -> str: 1006 return self.casing_func(attr) if self.casing_func else attr 1007 1008 # ========== Static validator builders with caching ========== # 1009 _field_validators_cache: dict[type, dict[str, TypeAdapter[Any]]] = {} 1010 """{class: {field: TypeAdapter}}; Dynamically registered fields may be added at runtime""" 1011 _action_validators_cache: dict[type, dict[str, TypeAdapter[Any]]] = {} 1012 """{class: {action_key: TypeAdapter}}; Dynamically registered actions may be added at runtime""" 1013 _task_validators_cache: dict[type, dict[str, TypeAdapter[Any]]] = {} 1014 """{class: {task_key: TypeAdapter}}; Dynamically registered tasks may be added at runtime""" 1015 1016 @staticmethod 1017 def build_kwargs_model( 1018 target_cls: type, 1019 model_name: str, 1020 func: Callable[..., Any], 1021 alias_generator: Callable[[str], str] | AliasGenerator | None, 1022 ) -> type[BaseModel]: 1023 """ 1024 Build a Pydantic model to validate the kwargs of a function. 1025 """ 1026 sig = signature(func) 1027 fields: dict[str, tuple[Any, Any]] = {} 1028 for idx, (param_name, param) in enumerate(sig.parameters.items()): 1029 if idx == 0 and param_name == "self": 1030 continue 1031 if param.kind in (Parameter.VAR_POSITIONAL, Parameter.VAR_KEYWORD): 1032 continue 1033 annotation = ( 1034 param.annotation if param.annotation is not Parameter.empty else Any 1035 ) 1036 default = param.default if param.default is not Parameter.empty else ... 1037 fields[param_name] = (annotation, default) 1038 1039 cfg = ConfigDict( 1040 alias_generator=alias_generator, 1041 validate_by_name=True, # Python -> Python (TODO: when?) 1042 validate_by_alias=True, # JSON -> Python 1043 ) 1044 model = create_model( 1045 model_name, 1046 __config__=cfg, 1047 __module__=target_cls.__module__, 1048 **cast("dict[str, Any]", fields), 1049 ) 1050 return model 1051 1052 @staticmethod 1053 def build_field_validators( 1054 target_cls: type, 1055 *, 1056 field_whitelist: Iterable[str] | None = None, 1057 use_cache: bool = True, 1058 ) -> dict[str, TypeAdapter[Any]]: 1059 """ 1060 Build a dictionary of field validators for a given class. 1061 1062 Args: 1063 target_cls: The class to build validators for. 1064 field_whitelist: A list of field names to include in the validators. If None, all fields are included. 1065 use_cache: Whether to use the cache. 1066 """ 1067 if use_cache and target_cls in Sync._field_validators_cache: 1068 return Sync._field_validators_cache[target_cls] 1069 1070 validators: dict[str, TypeAdapter[Any]] = {} 1071 if issubclass(target_cls, BaseModel): 1072 for name, field in target_cls.model_fields.items(): 1073 validators[name] = TypeAdapter(field.annotation) 1074 for name, field in target_cls.model_computed_fields.items(): 1075 validators[name] = TypeAdapter(field.return_type) 1076 1077 else: 1078 type_hints = get_type_hints(target_cls) 1079 if field_whitelist is not None: 1080 type_hints = { 1081 field: annotation 1082 for field in field_whitelist 1083 if (annotation := type_hints.get(field)) 1084 } 1085 for name, annotation in type_hints.items(): 1086 try: 1087 validators[name] = TypeAdapter(annotation) 1088 except PydanticSchemaGenerationError: 1089 logger.exception("Error building validator for %s", name) 1090 1091 if use_cache: 1092 Sync._field_validators_cache[target_cls] = validators 1093 return validators 1094 1095 @staticmethod 1096 def build_action_validators( 1097 target_cls: type, 1098 *, 1099 actions: dict[str, Callable[..., Any]] | None = None, 1100 schema_title_generator: SchemaTitleGenerator = default_action_title_generator, 1101 param_alias_generator: Callable[[str], str] | AliasGenerator | None = None, 1102 use_cache: bool = True, 1103 ) -> dict[str, TypeAdapter[Any]]: 1104 """ 1105 Build a dictionary of action validators for a given class. 1106 1107 Args: 1108 target_cls: The class whose actions to build validators for. 1109 actions: A dictionary of action names to functions. If None, all actions are included. 1110 schema_title_generator: A function to set the JSON schema title for each action. 1111 param_alias_generator: A function to set the JSON schema alias for the action *parameter names*. 1112 use_cache: Whether to use the cache for the validator objects. 1113 """ 1114 if param_alias_generator is None: 1115 param_alias_generator = get_alias_function_for_class(target_cls) 1116 1117 validators: dict[str, TypeAdapter[Any]] = {} 1118 1119 cache_key = target_cls 1120 if use_cache and cache_key in Sync._action_validators_cache: 1121 validators = Sync._action_validators_cache[cache_key] 1122 1123 actions = actions or find_remote_actions(target_cls) 1124 for key, func in actions.items(): 1125 if key in validators: 1126 continue 1127 1128 model = Sync.build_kwargs_model( 1129 target_cls=target_cls, 1130 model_name=schema_title_generator( 1131 class_name=target_cls.__name__, key=key 1132 ), 1133 func=func, 1134 alias_generator=param_alias_generator, 1135 ) 1136 validators[key] = TypeAdapter(model) 1137 1138 if use_cache: 1139 Sync._action_validators_cache[cache_key] = validators 1140 return validators 1141 1142 @staticmethod 1143 def build_task_validators( 1144 target_cls: type, 1145 *, 1146 tasks: dict[str, Callable[..., Any]] | None = None, 1147 schema_title_generator: SchemaTitleGenerator = default_task_title_generator, 1148 param_alias_generator: Callable[[str], str] | AliasGenerator | None = None, 1149 use_cache: bool = True, 1150 ) -> dict[str, TypeAdapter[Any]]: 1151 """ 1152 Build a dictionary of task validators for a given class. 1153 1154 Args: 1155 target_cls: The class whose tasks to build validators for. 1156 tasks: A dictionary of task names to functions. If None, all tasks are included. 1157 schema_title_generator: A function to set the JSON schema title for each task. 1158 param_alias_generator: A function to set the JSON schema alias for the task *parameter names*. 1159 use_cache: Whether to use the cache for the validator objects. 1160 """ 1161 if param_alias_generator is None: 1162 param_alias_generator = get_alias_function_for_class(target_cls) 1163 1164 validators: dict[str, TypeAdapter[Any]] = {} 1165 1166 cache_key = target_cls 1167 if use_cache and cache_key in Sync._task_validators_cache: 1168 validators = Sync._task_validators_cache[cache_key] 1169 1170 tasks = tasks or find_remote_tasks(target_cls) 1171 for key, func in tasks.items(): 1172 if key in validators: 1173 continue 1174 1175 model = Sync.build_kwargs_model( 1176 target_cls=target_cls, 1177 model_name=schema_title_generator( 1178 class_name=target_cls.__name__, key=key 1179 ), 1180 func=func, 1181 alias_generator=param_alias_generator, 1182 ) 1183 validators[key] = TypeAdapter(model) 1184 1185 if use_cache: 1186 Sync._task_validators_cache[cache_key] = validators 1187 return validators
Register an object's attributes to this class to sync them with the frontend.
329 def __init__( 330 self, 331 obj: object, 332 key: str, 333 *, 334 sync_all: bool = False, 335 include: dict[str, str | EllipsisType] | list[str] | None = None, 336 exclude: list[str] | None = None, 337 toCamelCase: bool | None = None, # noqa: N803 338 send_on_init: bool = True, 339 expose_running_tasks: bool = False, 340 logger: Logger | None = None, 341 actions: Mapping[str, Callable[..., Any]] | None = None, 342 tasks: Mapping[str, Callable[..., Awaitable[Any]]] | None = None, 343 task_cancels: Mapping[str, Callable[..., Awaitable[Any]]] | None = None, 344 ): 345 """ 346 Register the attributes that should be synced with the frontend. 347 348 Args: 349 obj: the object whose attributes should be synced 350 key: unique key for this object 351 352 sync_all: whether to sync all non-private attributes 353 include: attribute names to sync, value being either ... 354 or a string of the key of the attribute 355 exclude: list of attributes to exclude from syncing 356 357 toCamelCase: convert attribute names to camelCase. Must be ``None`` for 358 Pydantic models, which should configure ``alias_generator`` 359 send_on_init: whether to send the state on connection init 360 expose_running_tasks: whether to expose the running tasks to the frontend 361 logger: logger to use for logging 362 363 actions: action handlers for each action type, each taking the data of the action as keyword arguments 364 tasks: either a dict of task factories for each task type, each returning a coroutine to be used as a task, or a tuple of (task_start_handler, task_cancel_handler) 365 task_cancels: a dict of task cancel handlers for each task type 366 367 368 """ 369 self.obj = obj 370 self.key = _apply_sync_key_prefix(key) 371 self.send_on_init = send_on_init 372 self.casing_func = ( 373 get_alias_function_for_class(type(self.obj)) 374 if isinstance(self.obj, BaseModel) 375 else (to_camel if toCamelCase else None) 376 ) 377 self.task_exposure = ( 378 self.casing("running_tasks") if expose_running_tasks else None 379 ) 380 self.logger = logger 381 382 # Convert list[str] include to dict format 383 if isinstance(include, list): 384 include = dict.fromkeys(include, ...) 385 include = include or {} 386 exclude = exclude or [] 387 388 # Validate that BaseModel objects don't use custom sync keys 389 if isinstance(obj, BaseModel) and include: 390 for attr_name, sync_key in include.items(): 391 assert sync_key is ..., ( 392 f"Custom sync key '{sync_key}' for attribute '{attr_name}' is not allowed for Pydantic models. Use pydantic's alias_generator in model_config instead." 393 ) 394 395 self.session = session_context.get() 396 assert self.session, "No session set, use the session.session_context variable!" 397 398 # ========== Create Action Validators (cached) ========== # 399 actions = dict(actions or {}) | find_remote_actions(type(self.obj)) 400 self.action_validators: dict[str, TypeAdapter[Any]] = ( 401 self.build_action_validators( 402 target_cls=type(self.obj), 403 actions=actions, 404 param_alias_generator=self.casing_func, 405 ) 406 ) 407 # Create action handler after validators are ready 408 self.actions = self._create_action_handler(obj, actions) 409 410 # ========== Create Task Validators (cached) ========== # 411 tasks = dict(tasks or {}) | find_remote_tasks(type(self.obj)) 412 task_cancels = dict(task_cancels or {}) | find_remote_task_cancellers( 413 type(self.obj) 414 ) 415 self.task_validators: dict[str, TypeAdapter[Any]] = self.build_task_validators( 416 target_cls=type(self.obj), 417 tasks=tasks, 418 param_alias_generator=self.casing_func, 419 ) 420 self.tasks, self.task_cancels = self._create_task_handlers( 421 obj, tasks, task_cancels 422 ) 423 424 # store running tasks 425 self.running_tasks: dict[str, asyncio.Task[Any]] = {} 426 427 # ========== Find attributes to sync ========== # 428 self.sync_attributes: dict[str, str] = {} 429 430 # observe all non-private attributes 431 if sync_all: 432 if isinstance(obj, BaseModel): 433 # Include regular fields 434 for field in type(obj).model_fields: 435 if field in exclude: 436 continue 437 self.sync_attributes[field] = self.casing(field) 438 439 # Include computed fields 440 for field in type(obj).model_computed_fields: 441 if field in exclude: 442 continue 443 self.sync_attributes[field] = self.casing(field) 444 else: 445 for attr_name in dir(obj): 446 try: 447 attr = getattr(obj, attr_name) 448 except AttributeError: 449 continue 450 if ( 451 attr_name in exclude 452 or attr_name.startswith("_") 453 or callable(attr) 454 or isinstance(attr, Sync) 455 ): 456 continue 457 458 self.sync_attributes[attr_name] = self.casing(attr_name) 459 460 # observe specific attributes 461 for attr_name, sync_key in include.items(): 462 self.sync_attributes[attr_name] = ( 463 self.casing(attr_name) if sync_key is ... else sync_key 464 ) 465 466 # create reverse-lookup for patching 467 self.key_to_attr: dict[str, str] = { 468 key: attr for attr, key in self.sync_attributes.items() 469 } 470 471 # ========== Debugging ========== # 472 if self.logger: 473 self.logger.debug("%s: Syncing %s", self.key, self.sync_attributes) 474 self.logger.debug("%s: Actions %s", self.key, actions) 475 self.logger.debug("%s: Tasks %s", self.key, tasks) 476 self.logger.debug("%s: Task Cancels %s", self.key, task_cancels) 477 478 assert include.keys().isdisjoint(exclude), "Attribute in both include & exclude" 479 assert all(a in dir(obj) for a in self.sync_attributes), "Attribute not found" 480 assert all(e in dir(obj) for e in exclude), "Excluded attribute not found" 481 # assert ( 482 # len(self.sync_attributes) + expose_running_tasks > 0 483 # ), "No attributes to sync" 484 485 # ========== Field Type Adapters (cached) ========== # 486 self.type_adapters: dict[str, TypeAdapter[Any]] = self.build_field_validators( 487 type(obj), field_whitelist=self.sync_attributes.keys() 488 ) 489 490 # ========== State Management ========== # 491 # the snapshot is the exact state that the frontend has, for patching 492 self.state_snapshot: dict[str, Any] = self._snapshot() 493 self._last_sync: float | None = None # timestamp of last sync 494 495 # ========== Weak Reference Cleanup State ========== # 496 self._closed = False 497 self._init_wrapper: Callable[..., Any] | None = None 498 self._registered_handlers: dict[str, Callable[..., Any]] = {} 499 self._weak_self_ref: weakref.ref[Sync] | None = None 500 self._register_event_handlers()
Register the attributes that should be synced with the frontend.
Arguments:
- obj: the object whose attributes should be synced
- key: unique key for this object
- sync_all: whether to sync all non-private attributes
- include: attribute names to sync, value being either ... or a string of the key of the attribute
- exclude: list of attributes to exclude from syncing
- toCamelCase: convert attribute names to camelCase. Must be
Nonefor Pydantic models, which should configurealias_generator - send_on_init: whether to send the state on connection init
- expose_running_tasks: whether to expose the running tasks to the frontend
- logger: logger to use for logging
- actions: action handlers for each action type, each taking the data of the action as keyword arguments
- tasks: either a dict of task factories for each task type, each returning a coroutine to be used as a task, or a tuple of (task_start_handler, task_cancel_handler)
- task_cancels: a dict of task cancel handlers for each task type
193 @classmethod 194 def all( 195 cls, 196 obj: object, 197 key: str, 198 *, 199 include: dict[str, str | EllipsisType] | list[str] | None = None, 200 exclude: list[str] | None = None, 201 toCamelCase: bool | None = None, # noqa: N803 202 send_on_init: bool = True, 203 expose_running_tasks: bool = False, 204 logger: Logger | None = None, 205 actions: Mapping[str, Callable[..., Any]] | None = None, 206 tasks: Mapping[str, Callable[..., Awaitable[Any]]] | None = None, 207 task_cancels: Mapping[str, Callable[..., Awaitable[Any]]] | None = None, 208 ) -> "Sync": 209 return cls( 210 obj=obj, 211 key=key, 212 sync_all=True, 213 include=include, 214 exclude=exclude or [], 215 toCamelCase=toCamelCase, 216 send_on_init=send_on_init, 217 expose_running_tasks=expose_running_tasks, 218 logger=logger, 219 actions=actions, 220 tasks=tasks, 221 task_cancels=task_cancels, 222 )
224 @classmethod 225 def only( 226 cls, 227 _obj: object, 228 _key: str, 229 *, 230 _toCamelCase: bool | None = None, # noqa: N803 231 _send_on_init: bool = True, 232 _expose_running_tasks: bool = False, 233 _logger: Logger | None = None, 234 _actions: Mapping[str, Callable[..., Any]] | None = None, 235 _tasks: Mapping[str, Callable[..., Awaitable[Any]]] | None = None, 236 _task_cancels: Mapping[str, Callable[..., Awaitable[Any]]] | None = None, 237 **sync_attributes: str | EllipsisType, 238 ) -> "Sync": 239 return cls( 240 obj=_obj, 241 key=_key, 242 sync_all=False, 243 include=sync_attributes, 244 exclude=[], 245 toCamelCase=_toCamelCase, 246 send_on_init=_send_on_init, 247 expose_running_tasks=_expose_running_tasks, 248 logger=_logger, 249 actions=_actions, 250 tasks=_tasks, 251 task_cancels=_task_cancels, 252 )
254 @staticmethod 255 def resolve_attributes( 256 obj_or_cls: object | type, 257 *, 258 include: dict[str, str | EllipsisType] | None = None, 259 exclude: list[str] | None = None, 260 sync_all: bool = False, 261 casing_func: Callable[[str], str] | None = None, 262 ) -> dict[str, str]: 263 """ 264 Resolve which attributes to sync based on configuration. 265 266 Returns: 267 Dict mapping attribute name to sync key (alias). 268 """ 269 include = include or {} 270 exclude = exclude or [] 271 sync_attributes: dict[str, str] = {} 272 273 is_class = isinstance(obj_or_cls, type) 274 cls = obj_or_cls if is_class else type(obj_or_cls) 275 276 def casing(attr: str) -> str: 277 return casing_func(attr) if casing_func else attr 278 279 # observe all non-private attributes 280 if sync_all: 281 if issubclass(cls, BaseModel): 282 # Include regular fields 283 for field in cls.model_fields: 284 if field in exclude: 285 continue 286 sync_attributes[field] = casing(field) 287 288 # Include computed fields 289 for field in cls.model_computed_fields: 290 if field in exclude: 291 continue 292 sync_attributes[field] = casing(field) 293 # For regular classes, we need an instance to check dir() reliably for instance attrs, 294 # but we can check class attrs if we only have a class. 295 # However, if we only have a class, we can't know instance attributes that are set in __init__. 296 # So sync_all=True for plain classes really works best with an instance. 297 # If we have a class, we can only guess based on annotations or class attributes. 298 elif is_class: 299 # Best effort for static analysis of plain classes 300 # We can check type hints 301 for attr_name in get_type_hints(cls): 302 if attr_name in exclude or attr_name.startswith("_"): 303 continue 304 sync_attributes[attr_name] = casing(attr_name) 305 else: 306 for attr_name in dir(obj_or_cls): 307 try: 308 attr = getattr(obj_or_cls, attr_name) 309 except AttributeError: 310 continue 311 if ( 312 attr_name in exclude 313 or attr_name.startswith("_") 314 or callable(attr) 315 or isinstance(attr, Sync) 316 ): 317 continue 318 319 sync_attributes[attr_name] = casing(attr_name) 320 321 # observe specific attributes 322 for attr_name, sync_key in include.items(): 323 sync_attributes[attr_name] = ( 324 casing(attr_name) if sync_key is ... else cast(str, sync_key) 325 ) 326 327 return sync_attributes
Resolve which attributes to sync based on configuration.
Returns:
Dict mapping attribute name to sync key (alias).
503 async def sync(self, if_since_last: float | None = None): 504 """ 505 Sync all registered attributes. 506 507 Args: 508 if_since_last: only sync if the last sync was before this many seconds 509 """ 510 if not self.session.is_connected: 511 return 512 t = time() 513 if if_since_last and self._last_sync and t - self._last_sync < if_since_last: 514 return 515 516 # calculate patch 517 prev = self.state_snapshot 518 self.state_snapshot = self._snapshot() 519 patch = jsonpatch.make_patch(prev, self.state_snapshot).patch 520 521 if len(patch) > 0: 522 await self.session.send(patch_event(self.key), patch) 523 self._last_sync = t
Sync all registered attributes.
Arguments:
- if_since_last: only sync if the last sync was before this many seconds
543 async def send_action(self, action: dict[str, Any]): 544 """ 545 Send an action to the frontend. 546 """ 547 await self.session.send(action_event(self.key), action)
Send an action to the frontend.
549 async def send_binary(self, metadata: dict[str, Any], data: bytes): 550 """ 551 Send binary data to the frontend, along with metadata. 552 553 This is a subset of an action, but with bytes data always included. 554 """ 555 await self.session.send_binary(action_event(self.key), metadata, data)
Send binary data to the frontend, along with metadata.
This is a subset of an action, but with bytes data always included.
557 async def toast( 558 self, 559 *messages, 560 type: ToastType = "default", # noqa: A002 561 logger: Logger | None = None, 562 ) -> str: 563 """ 564 Send a toast message to the frontend. 565 566 Returns the sent message content, so that you can easily return or print it. 567 """ 568 messages = " ".join(str(message) for message in messages) 569 570 if lg := (logger or self.logger): 571 match type: 572 case "default": 573 lg.debug(messages) 574 case "message" | "info" | "success": 575 lg.info(messages) 576 case "warning": 577 lg.warning(messages) 578 case "error": 579 lg.error(messages) 580 case _: 581 lg.debug(messages) 582 583 await self.session.send(toast_event(), {"type": type, "message": messages}) 584 return messages
Send a toast message to the frontend.
Returns the sent message content, so that you can easily return or print it.
586 async def download(self, filename: str, binary: bytes) -> None: 587 """ 588 Send a file to the frontend for download. 589 """ 590 data = base64.b64encode(binary).decode("utf-8") 591 await self.session.send(download_event(), {"filename": filename, "data": data})
Send a file to the frontend for download.
593 def observe(self, obj: object, **sync_attributes: str | EllipsisType) -> None: 594 """ 595 Observe additional attributes, useful for when you're extending/subclassing an already Synced object, or when you want to observe multiple objects. 596 """ 597 # TODO: append, deregister, re-register
Observe additional attributes, useful for when you're extending/subclassing an already Synced object, or when you want to observe multiple objects.
780 def close(self): 781 """ 782 Explicitly close this Sync and deregister all handlers. 783 784 Call this when you're done with a Sync object to immediately release 785 resources. If not called, cleanup happens automatically when the 786 Sync is garbage collected. 787 788 This is idempotent - calling it multiple times is safe. 789 """ 790 self._deregister()
Explicitly close this Sync and deregister all handlers.
Call this when you're done with a Sync object to immediately release resources. If not called, cleanup happens automatically when the Sync is garbage collected.
This is idempotent - calling it multiple times is safe.
1016 @staticmethod 1017 def build_kwargs_model( 1018 target_cls: type, 1019 model_name: str, 1020 func: Callable[..., Any], 1021 alias_generator: Callable[[str], str] | AliasGenerator | None, 1022 ) -> type[BaseModel]: 1023 """ 1024 Build a Pydantic model to validate the kwargs of a function. 1025 """ 1026 sig = signature(func) 1027 fields: dict[str, tuple[Any, Any]] = {} 1028 for idx, (param_name, param) in enumerate(sig.parameters.items()): 1029 if idx == 0 and param_name == "self": 1030 continue 1031 if param.kind in (Parameter.VAR_POSITIONAL, Parameter.VAR_KEYWORD): 1032 continue 1033 annotation = ( 1034 param.annotation if param.annotation is not Parameter.empty else Any 1035 ) 1036 default = param.default if param.default is not Parameter.empty else ... 1037 fields[param_name] = (annotation, default) 1038 1039 cfg = ConfigDict( 1040 alias_generator=alias_generator, 1041 validate_by_name=True, # Python -> Python (TODO: when?) 1042 validate_by_alias=True, # JSON -> Python 1043 ) 1044 model = create_model( 1045 model_name, 1046 __config__=cfg, 1047 __module__=target_cls.__module__, 1048 **cast("dict[str, Any]", fields), 1049 ) 1050 return model
Build a Pydantic model to validate the kwargs of a function.
1052 @staticmethod 1053 def build_field_validators( 1054 target_cls: type, 1055 *, 1056 field_whitelist: Iterable[str] | None = None, 1057 use_cache: bool = True, 1058 ) -> dict[str, TypeAdapter[Any]]: 1059 """ 1060 Build a dictionary of field validators for a given class. 1061 1062 Args: 1063 target_cls: The class to build validators for. 1064 field_whitelist: A list of field names to include in the validators. If None, all fields are included. 1065 use_cache: Whether to use the cache. 1066 """ 1067 if use_cache and target_cls in Sync._field_validators_cache: 1068 return Sync._field_validators_cache[target_cls] 1069 1070 validators: dict[str, TypeAdapter[Any]] = {} 1071 if issubclass(target_cls, BaseModel): 1072 for name, field in target_cls.model_fields.items(): 1073 validators[name] = TypeAdapter(field.annotation) 1074 for name, field in target_cls.model_computed_fields.items(): 1075 validators[name] = TypeAdapter(field.return_type) 1076 1077 else: 1078 type_hints = get_type_hints(target_cls) 1079 if field_whitelist is not None: 1080 type_hints = { 1081 field: annotation 1082 for field in field_whitelist 1083 if (annotation := type_hints.get(field)) 1084 } 1085 for name, annotation in type_hints.items(): 1086 try: 1087 validators[name] = TypeAdapter(annotation) 1088 except PydanticSchemaGenerationError: 1089 logger.exception("Error building validator for %s", name) 1090 1091 if use_cache: 1092 Sync._field_validators_cache[target_cls] = validators 1093 return validators
Build a dictionary of field validators for a given class.
Arguments:
- target_cls: The class to build validators for.
- field_whitelist: A list of field names to include in the validators. If None, all fields are included.
- use_cache: Whether to use the cache.
1095 @staticmethod 1096 def build_action_validators( 1097 target_cls: type, 1098 *, 1099 actions: dict[str, Callable[..., Any]] | None = None, 1100 schema_title_generator: SchemaTitleGenerator = default_action_title_generator, 1101 param_alias_generator: Callable[[str], str] | AliasGenerator | None = None, 1102 use_cache: bool = True, 1103 ) -> dict[str, TypeAdapter[Any]]: 1104 """ 1105 Build a dictionary of action validators for a given class. 1106 1107 Args: 1108 target_cls: The class whose actions to build validators for. 1109 actions: A dictionary of action names to functions. If None, all actions are included. 1110 schema_title_generator: A function to set the JSON schema title for each action. 1111 param_alias_generator: A function to set the JSON schema alias for the action *parameter names*. 1112 use_cache: Whether to use the cache for the validator objects. 1113 """ 1114 if param_alias_generator is None: 1115 param_alias_generator = get_alias_function_for_class(target_cls) 1116 1117 validators: dict[str, TypeAdapter[Any]] = {} 1118 1119 cache_key = target_cls 1120 if use_cache and cache_key in Sync._action_validators_cache: 1121 validators = Sync._action_validators_cache[cache_key] 1122 1123 actions = actions or find_remote_actions(target_cls) 1124 for key, func in actions.items(): 1125 if key in validators: 1126 continue 1127 1128 model = Sync.build_kwargs_model( 1129 target_cls=target_cls, 1130 model_name=schema_title_generator( 1131 class_name=target_cls.__name__, key=key 1132 ), 1133 func=func, 1134 alias_generator=param_alias_generator, 1135 ) 1136 validators[key] = TypeAdapter(model) 1137 1138 if use_cache: 1139 Sync._action_validators_cache[cache_key] = validators 1140 return validators
Build a dictionary of action validators for a given class.
Arguments:
- target_cls: The class whose actions to build validators for.
- actions: A dictionary of action names to functions. If None, all actions are included.
- schema_title_generator: A function to set the JSON schema title for each action.
- param_alias_generator: A function to set the JSON schema alias for the action parameter names.
- use_cache: Whether to use the cache for the validator objects.
1142 @staticmethod 1143 def build_task_validators( 1144 target_cls: type, 1145 *, 1146 tasks: dict[str, Callable[..., Any]] | None = None, 1147 schema_title_generator: SchemaTitleGenerator = default_task_title_generator, 1148 param_alias_generator: Callable[[str], str] | AliasGenerator | None = None, 1149 use_cache: bool = True, 1150 ) -> dict[str, TypeAdapter[Any]]: 1151 """ 1152 Build a dictionary of task validators for a given class. 1153 1154 Args: 1155 target_cls: The class whose tasks to build validators for. 1156 tasks: A dictionary of task names to functions. If None, all tasks are included. 1157 schema_title_generator: A function to set the JSON schema title for each task. 1158 param_alias_generator: A function to set the JSON schema alias for the task *parameter names*. 1159 use_cache: Whether to use the cache for the validator objects. 1160 """ 1161 if param_alias_generator is None: 1162 param_alias_generator = get_alias_function_for_class(target_cls) 1163 1164 validators: dict[str, TypeAdapter[Any]] = {} 1165 1166 cache_key = target_cls 1167 if use_cache and cache_key in Sync._task_validators_cache: 1168 validators = Sync._task_validators_cache[cache_key] 1169 1170 tasks = tasks or find_remote_tasks(target_cls) 1171 for key, func in tasks.items(): 1172 if key in validators: 1173 continue 1174 1175 model = Sync.build_kwargs_model( 1176 target_cls=target_cls, 1177 model_name=schema_title_generator( 1178 class_name=target_cls.__name__, key=key 1179 ), 1180 func=func, 1181 alias_generator=param_alias_generator, 1182 ) 1183 validators[key] = TypeAdapter(model) 1184 1185 if use_cache: 1186 Sync._task_validators_cache[cache_key] = validators 1187 return validators
Build a dictionary of task validators for a given class.
Arguments:
- target_cls: The class whose tasks to build validators for.
- tasks: A dictionary of task names to functions. If None, all tasks are included.
- schema_title_generator: A function to set the JSON schema title for each task.
- param_alias_generator: A function to set the JSON schema alias for the task parameter names.
- use_cache: Whether to use the cache for the validator objects.