_transport.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. # mypy: disable-error-code="no-any-return"
  2. """Shared plumbing for the ConnectRPC-based transport.
  3. Chatto's public API is a ConnectRPC service surface. ``chattolib.client``
  4. speaks to it through generated service stubs (see ``chattolib._pb``) driven
  5. by chattolib's own hand-rolled Connect transport (``chattolib._connect``),
  6. so the library has no third-party Connect dependency.
  7. This module exposes:
  8. * :func:`build_service_clients` — one call, one ``base_url`` argument,
  9. returns a ``ServiceClients`` object with a typed field per Chatto service.
  10. * :func:`translate_connect_error` — translates a
  11. ``chattolib._connect.ConnectError`` into the library's public exception
  12. hierarchy (:class:`chattolib.exceptions.ChattoAuthError` /
  13. :class:`chattolib.exceptions.ChattoConnectError`).
  14. * :func:`pb_to_dict` — turns a protobuf response into the camelCase JSON
  15. shape that the existing ``types.py`` dataclass parsers already accept.
  16. Keeping the parsers dict-driven means the migration from Connect-JSON to
  17. Connect-binary transport doesn't ripple through the entire public API.
  18. """
  19. from __future__ import annotations
  20. from dataclasses import dataclass
  21. from typing import Any
  22. from google.protobuf.json_format import MessageToDict
  23. from google.protobuf.message import Message
  24. from chattolib._connect import Code, ConnectError, google_protobuf_binary_codec
  25. from chattolib._pb.chatto.admin.v1.diagnostics_connect import (
  26. AdminDiagnosticsServiceClient,
  27. )
  28. from chattolib._pb.chatto.admin.v1.event_log_connect import AdminEventLogServiceClient
  29. from chattolib._pb.chatto.admin.v1.members_connect import AdminUserServiceClient
  30. from chattolib._pb.chatto.admin.v1.permissions_connect import (
  31. AdminPermissionServiceClient,
  32. )
  33. from chattolib._pb.chatto.admin.v1.roles_connect import AdminRoleServiceClient
  34. from chattolib._pb.chatto.admin.v1.room_layout_connect import (
  35. AdminRoomLayoutServiceClient,
  36. )
  37. from chattolib._pb.chatto.admin.v1.server_connect import AdminServerServiceClient
  38. from chattolib._pb.chatto.api.v1.account_connect import MyAccountServiceClient
  39. from chattolib._pb.chatto.api.v1.asset_uploads_connect import AssetUploadServiceClient
  40. from chattolib._pb.chatto.api.v1.attachments_connect import AssetServiceClient
  41. from chattolib._pb.chatto.api.v1.messages_connect import MessageServiceClient
  42. from chattolib._pb.chatto.api.v1.notification_preferences_connect import (
  43. NotificationPreferencesServiceClient,
  44. )
  45. from chattolib._pb.chatto.api.v1.notifications_connect import (
  46. NotificationPolicyServiceClient,
  47. NotificationServiceClient,
  48. )
  49. from chattolib._pb.chatto.api.v1.permissions_connect import PermissionServiceClient
  50. from chattolib._pb.chatto.api.v1.push_notifications_connect import (
  51. PushNotificationServiceClient,
  52. )
  53. from chattolib._pb.chatto.api.v1.roles_connect import RoleServiceClient
  54. from chattolib._pb.chatto.api.v1.room_directory_connect import (
  55. RoomDirectoryServiceClient,
  56. )
  57. from chattolib._pb.chatto.api.v1.rooms_connect import RoomServiceClient
  58. from chattolib._pb.chatto.api.v1.server_state_connect import ServerServiceClient
  59. from chattolib._pb.chatto.api.v1.threads_connect import ThreadServiceClient
  60. from chattolib._pb.chatto.api.v1.viewer_connect import ViewerServiceClient
  61. from chattolib._pb.chatto.api.v1.voice_calls_connect import VoiceCallServiceClient
  62. from chattolib._pb.chatto.discovery.v1.server_connect import (
  63. ServerDiscoveryServiceClient,
  64. )
  65. from chattolib.exceptions import ChattoAuthError, ChattoConnectError
  66. CONNECT_PREFIX = "/api/connect"
  67. @dataclass
  68. class ServiceClients:
  69. """Typed bundle of ConnectRPC service clients used by ``ChattoClient``."""
  70. server_discovery: ServerDiscoveryServiceClient
  71. server: ServerServiceClient
  72. viewer: ViewerServiceClient
  73. account: MyAccountServiceClient
  74. roles: RoleServiceClient
  75. room_directory: RoomDirectoryServiceClient
  76. rooms: RoomServiceClient
  77. messages: MessageServiceClient
  78. threads: ThreadServiceClient
  79. notifications: NotificationServiceClient
  80. notification_policy: NotificationPolicyServiceClient
  81. notification_prefs: NotificationPreferencesServiceClient
  82. permissions: PermissionServiceClient
  83. push: PushNotificationServiceClient
  84. assets: AssetServiceClient
  85. asset_uploads: AssetUploadServiceClient
  86. voice_calls: VoiceCallServiceClient
  87. admin_server: AdminServerServiceClient
  88. admin_room_layout: AdminRoomLayoutServiceClient
  89. admin_users: AdminUserServiceClient
  90. admin_roles: AdminRoleServiceClient
  91. admin_event_log: AdminEventLogServiceClient
  92. admin_diagnostics: AdminDiagnosticsServiceClient
  93. admin_permissions: AdminPermissionServiceClient
  94. async def close(self) -> None:
  95. for name in self.__dataclass_fields__:
  96. client = getattr(self, name)
  97. await client.close()
  98. def build_service_clients(base_url: str) -> ServiceClients:
  99. """Instantiate one service client per Chatto Connect service.
  100. ``base_url`` is the server root (e.g. ``https://chat.chatto.run``); the
  101. ConnectRPC prefix is appended by this function.
  102. """
  103. address = f"{base_url.rstrip('/')}{CONNECT_PREFIX}"
  104. codec = google_protobuf_binary_codec()
  105. def make(cls: Any) -> Any:
  106. return cls(address, codec=codec)
  107. return ServiceClients(
  108. server_discovery=make(ServerDiscoveryServiceClient),
  109. server=make(ServerServiceClient),
  110. viewer=make(ViewerServiceClient),
  111. account=make(MyAccountServiceClient),
  112. roles=make(RoleServiceClient),
  113. room_directory=make(RoomDirectoryServiceClient),
  114. rooms=make(RoomServiceClient),
  115. messages=make(MessageServiceClient),
  116. threads=make(ThreadServiceClient),
  117. notifications=make(NotificationServiceClient),
  118. notification_policy=make(NotificationPolicyServiceClient),
  119. notification_prefs=make(NotificationPreferencesServiceClient),
  120. permissions=make(PermissionServiceClient),
  121. push=make(PushNotificationServiceClient),
  122. assets=make(AssetServiceClient),
  123. asset_uploads=make(AssetUploadServiceClient),
  124. voice_calls=make(VoiceCallServiceClient),
  125. admin_server=make(AdminServerServiceClient),
  126. admin_room_layout=make(AdminRoomLayoutServiceClient),
  127. admin_users=make(AdminUserServiceClient),
  128. admin_roles=make(AdminRoleServiceClient),
  129. admin_event_log=make(AdminEventLogServiceClient),
  130. admin_diagnostics=make(AdminDiagnosticsServiceClient),
  131. admin_permissions=make(AdminPermissionServiceClient),
  132. )
  133. def translate_connect_error(exc: ConnectError) -> Exception:
  134. """Convert a Connect transport error into chattolib's exception hierarchy."""
  135. if exc.code == Code.UNAUTHENTICATED:
  136. return ChattoAuthError(str(exc))
  137. return ChattoConnectError(
  138. code=exc.code.name.lower(),
  139. message=str(exc),
  140. )
  141. def pb_to_dict(message: Message | None) -> dict[str, Any]:
  142. """Convert a protobuf message to the camelCase dict shape the parsers accept.
  143. ``preserving_proto_field_name=False`` gives us JSON-mapping camelCase
  144. keys (e.g. ``created_at`` → ``createdAt``), matching what the
  145. ``types.py`` dataclass parsers already consume.
  146. """
  147. if message is None:
  148. return {}
  149. return MessageToDict(
  150. message,
  151. preserving_proto_field_name=False,
  152. use_integers_for_enums=False,
  153. )