1- # Copyright (c) 2022 Tulir Asokan
1+ # Copyright (c) 2023 Tulir Asokan
22#
33# This Source Code Form is subject to the terms of the Mozilla Public
44# License, v. 2.0. If a copy of the MPL was not distributed with this
88
99from typing import Any , Awaitable , Callable
1010from json import JSONDecodeError
11- import asyncio
1211import json
1312import logging
1413
3332
3433
3534class AppServiceServerMixin :
36- loop : asyncio .AbstractEventLoop
3735 log : logging .Logger
3836
3937 hs_token : str
4038 ephemeral_events : bool
4139 encryption_events : bool
40+ synchronous_handlers : bool
4241
4342 query_user : Callable [[UserID ], JSON ]
4443 query_alias : Callable [[RoomAlias ], JSON ]
@@ -57,6 +56,7 @@ def __init__(self, ephemeral_events: bool = False, encryption_events: bool = Fal
5756 self .device_list_handler = None
5857 self .ephemeral_events = ephemeral_events
5958 self .encryption_events = encryption_events
59+ self .synchronous_handlers = False
6060
6161 async def default_query_handler (_ ):
6262 return None
@@ -309,18 +309,18 @@ async def handle_transaction(
309309 except SerializerError :
310310 self .log .exception ("Failed to deserialize ephemeral event %s" , raw_edu )
311311 else :
312- self .handle_matrix_event (edu , ephemeral = True )
312+ await self .handle_matrix_event (edu , ephemeral = True )
313313 for raw_event in events :
314314 try :
315315 self ._fix_prev_content (raw_event )
316316 event = Event .deserialize (raw_event )
317317 except SerializerError :
318318 self .log .exception ("Failed to deserialize event %s" , raw_event )
319319 else :
320- self .handle_matrix_event (event )
320+ await self .handle_matrix_event (event )
321321 return {}
322322
323- def handle_matrix_event (self , event : Event , ephemeral : bool = False ) -> None :
323+ async def handle_matrix_event (self , event : Event , ephemeral : bool = False ) -> None :
324324 if ephemeral :
325325 event .type = event .type .with_class (EventType .Class .EPHEMERAL )
326326 elif getattr (event , "state_key" , None ) is not None :
@@ -334,9 +334,12 @@ async def try_handle(handler_func: HandlerFunc):
334334 except Exception :
335335 self .log .exception ("Exception in Matrix event handler" )
336336
337- for handler in self .event_handlers :
338- # TODO add option to handle events synchronously
339- background_task .create (try_handle (handler ))
337+ if self .synchronous_handlers :
338+ for handler in self .event_handlers :
339+ await handler (event )
340+ else :
341+ for handler in self .event_handlers :
342+ background_task .create (try_handle (handler ))
340343
341344 def matrix_event_handler (self , func : HandlerFunc ) -> HandlerFunc :
342345 self .event_handlers .append (func )
0 commit comments