refactor: extract request and notification handling into separate methods

This commit is contained in:
David Soria Parra
2025-01-23 19:08:23 +00:00
parent bd742272ab
commit 0a93799068

View File

@@ -433,14 +433,28 @@ class Server:
match message: match message:
case RequestResponder(request=types.ClientRequest(root=req)): case RequestResponder(request=types.ClientRequest(root=req)):
logger.info( await self._handle_request(
f"Processing request of type {type(req).__name__}" message, req, session, raise_exceptions
) )
case types.ClientNotification(root=notify):
await self._handle_notification(notify)
for warning in w:
logger.info(
f"Warning: {warning.category.__name__}: {warning.message}"
)
async def _handle_request(
self,
message: RequestResponder,
req: Any,
session: ServerSession,
raise_exceptions: bool,
):
logger.info(f"Processing request of type {type(req).__name__}")
if type(req) in self.request_handlers: if type(req) in self.request_handlers:
handler = self.request_handlers[type(req)] handler = self.request_handlers[type(req)]
logger.debug( logger.debug(f"Dispatching request of type {type(req).__name__}")
f"Dispatching request of type {type(req).__name__}"
)
token = None token = None
try: try:
@@ -459,9 +473,7 @@ class Server:
except Exception as err: except Exception as err:
if raise_exceptions: if raise_exceptions:
raise err raise err
response = types.ErrorData( response = types.ErrorData(code=0, message=str(err), data=None)
code=0, message=str(err), data=None
)
finally: finally:
# Reset the global state after we are done # Reset the global state after we are done
if token is not None: if token is not None:
@@ -477,28 +489,20 @@ class Server:
) )
logger.debug("Response sent") logger.debug("Response sent")
case types.ClientNotification(root=notify):
async def _handle_notification(self, notify: Any):
if type(notify) in self.notification_handlers: if type(notify) in self.notification_handlers:
assert type(notify) in self.notification_handlers assert type(notify) in self.notification_handlers
handler = self.notification_handlers[type(notify)] handler = self.notification_handlers[type(notify)]
logger.debug( logger.debug(
f"Dispatching notification of type " f"Dispatching notification of type " f"{type(notify).__name__}"
f"{type(notify).__name__}"
) )
try: try:
await handler(notify) await handler(notify)
except Exception as err: except Exception as err:
logger.error( logger.error(f"Uncaught exception in notification handler: " f"{err}")
f"Uncaught exception in notification handler: "
f"{err}"
)
for warning in w:
logger.info(
f"Warning: {warning.category.__name__}: {warning.message}"
)
async def _ping_handler(request: types.PingRequest) -> types.ServerResult: async def _ping_handler(request: types.PingRequest) -> types.ServerResult: