_transport.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  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.member_directory_connect import UserServiceClient
  42. from chattolib._pb.chatto.api.v1.messages_connect import MessageServiceClient
  43. from chattolib._pb.chatto.api.v1.notification_preferences_connect import (
  44. NotificationPreferencesServiceClient,
  45. )
  46. from chattolib._pb.chatto.api.v1.notifications_connect import (
  47. NotificationServiceClient,
  48. )
  49. from chattolib._pb.chatto.api.v1.push_notifications_connect import (
  50. PushNotificationServiceClient,
  51. )
  52. from chattolib._pb.chatto.api.v1.roles_connect import RoleServiceClient
  53. from chattolib._pb.chatto.api.v1.room_directory_connect import (
  54. RoomDirectoryServiceClient,
  55. )
  56. from chattolib._pb.chatto.api.v1.rooms_connect import RoomServiceClient
  57. from chattolib._pb.chatto.api.v1.server_state_connect import ServerServiceClient
  58. from chattolib._pb.chatto.api.v1.threads_connect import ThreadServiceClient
  59. from chattolib._pb.chatto.api.v1.viewer_connect import ViewerServiceClient
  60. from chattolib._pb.chatto.api.v1.voice_calls_connect import VoiceCallServiceClient
  61. from chattolib._pb.chatto.discovery.v1.server_connect import (
  62. ServerDiscoveryServiceClient,
  63. )
  64. from chattolib.exceptions import ChattoAuthError, ChattoConnectError
  65. CONNECT_PREFIX = "/api/connect"
  66. @dataclass
  67. class ServiceClients:
  68. """Typed bundle of ConnectRPC service clients used by ``ChattoClient``."""
  69. server_discovery: ServerDiscoveryServiceClient
  70. server: ServerServiceClient
  71. viewer: ViewerServiceClient
  72. account: MyAccountServiceClient
  73. users: UserServiceClient
  74. roles: RoleServiceClient
  75. room_directory: RoomDirectoryServiceClient
  76. rooms: RoomServiceClient
  77. messages: MessageServiceClient
  78. threads: ThreadServiceClient
  79. notifications: NotificationServiceClient
  80. notification_prefs: NotificationPreferencesServiceClient
  81. push: PushNotificationServiceClient
  82. assets: AssetServiceClient
  83. asset_uploads: AssetUploadServiceClient
  84. voice_calls: VoiceCallServiceClient
  85. admin_server: AdminServerServiceClient
  86. admin_room_layout: AdminRoomLayoutServiceClient
  87. admin_users: AdminUserServiceClient
  88. admin_roles: AdminRoleServiceClient
  89. admin_event_log: AdminEventLogServiceClient
  90. admin_diagnostics: AdminDiagnosticsServiceClient
  91. admin_permissions: AdminPermissionServiceClient
  92. async def close(self) -> None:
  93. for name in self.__dataclass_fields__:
  94. client = getattr(self, name)
  95. await client.close()
  96. def build_service_clients(base_url: str) -> ServiceClients:
  97. """Instantiate one service client per Chatto Connect service.
  98. ``base_url`` is the server root (e.g. ``https://chat.chatto.run``); the
  99. ConnectRPC prefix is appended by this function.
  100. """
  101. address = f"{base_url.rstrip('/')}{CONNECT_PREFIX}"
  102. codec = google_protobuf_binary_codec()
  103. def make(cls: Any) -> Any:
  104. return cls(address, codec=codec)
  105. return ServiceClients(
  106. server_discovery=make(ServerDiscoveryServiceClient),
  107. server=make(ServerServiceClient),
  108. viewer=make(ViewerServiceClient),
  109. account=make(MyAccountServiceClient),
  110. users=make(UserServiceClient),
  111. roles=make(RoleServiceClient),
  112. room_directory=make(RoomDirectoryServiceClient),
  113. rooms=make(RoomServiceClient),
  114. messages=make(MessageServiceClient),
  115. threads=make(ThreadServiceClient),
  116. notifications=make(NotificationServiceClient),
  117. notification_prefs=make(NotificationPreferencesServiceClient),
  118. push=make(PushNotificationServiceClient),
  119. assets=make(AssetServiceClient),
  120. asset_uploads=make(AssetUploadServiceClient),
  121. voice_calls=make(VoiceCallServiceClient),
  122. admin_server=make(AdminServerServiceClient),
  123. admin_room_layout=make(AdminRoomLayoutServiceClient),
  124. admin_users=make(AdminUserServiceClient),
  125. admin_roles=make(AdminRoleServiceClient),
  126. admin_event_log=make(AdminEventLogServiceClient),
  127. admin_diagnostics=make(AdminDiagnosticsServiceClient),
  128. admin_permissions=make(AdminPermissionServiceClient),
  129. )
  130. def translate_connect_error(exc: ConnectError) -> Exception:
  131. """Convert a Connect transport error into chattolib's exception hierarchy."""
  132. if exc.code == Code.UNAUTHENTICATED:
  133. return ChattoAuthError(str(exc))
  134. return ChattoConnectError(
  135. code=exc.code.name.lower(),
  136. message=str(exc),
  137. )
  138. def pb_to_dict(message: Message | None) -> dict[str, Any]:
  139. """Convert a protobuf message to the camelCase dict shape the parsers accept.
  140. ``preserving_proto_field_name=False`` gives us JSON-mapping camelCase
  141. keys (e.g. ``created_at`` → ``createdAt``), matching what the
  142. ``types.py`` dataclass parsers already consume.
  143. """
  144. if message is None:
  145. return {}
  146. return MessageToDict(
  147. message,
  148. preserving_proto_field_name=False,
  149. use_integers_for_enums=False,
  150. )