Skip to content
This repository was archived by the owner on Apr 26, 2024. It is now read-only.

Commit 23f262c

Browse files
committed
Merge commit 'a1e9bb9ea' into anoa/dinsic_release_1_21_x
* commit 'a1e9bb9ea': Add typing info to Notifier (#8058)
2 parents ff0170e + a1e9bb9 commit 23f262c

File tree

5 files changed

+91
-52
lines changed

5 files changed

+91
-52
lines changed

changelog.d/8058.misc

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Add type hints to `Notifier`.

synapse/handlers/events.py

-4
Original file line numberDiff line numberDiff line change
@@ -57,13 +57,10 @@ async def get_stream(
5757
timeout=0,
5858
as_client_event=True,
5959
affect_presence=True,
60-
only_keys=None,
6160
room_id=None,
6261
is_guest=False,
6362
):
6463
"""Fetches the events stream for a given user.
65-
66-
If `only_keys` is not None, events from keys will be sent down.
6764
"""
6865

6966
if room_id:
@@ -93,7 +90,6 @@ async def get_stream(
9390
auth_user,
9491
pagin_config,
9592
timeout,
96-
only_keys=only_keys,
9793
is_guest=is_guest,
9894
explicit_room_id=room_id,
9995
)

synapse/notifier.py

+83-48
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,17 @@
1515

1616
import logging
1717
from collections import namedtuple
18-
from typing import Callable, Iterable, List, TypeVar
18+
from typing import (
19+
Awaitable,
20+
Callable,
21+
Dict,
22+
Iterable,
23+
List,
24+
Optional,
25+
Set,
26+
Tuple,
27+
TypeVar,
28+
)
1929

2030
from prometheus_client import Counter
2131

@@ -24,12 +34,14 @@
2434
import synapse.server
2535
from synapse.api.constants import EventTypes, Membership
2636
from synapse.api.errors import AuthError
37+
from synapse.events import EventBase
2738
from synapse.handlers.presence import format_user_presence_state
2839
from synapse.logging.context import PreserveLoggingContext
2940
from synapse.logging.utils import log_function
3041
from synapse.metrics import LaterGauge
3142
from synapse.metrics.background_process_metrics import run_as_background_process
32-
from synapse.types import StreamToken
43+
from synapse.streams.config import PaginationConfig
44+
from synapse.types import Collection, StreamToken, UserID
3345
from synapse.util.async_helpers import ObservableDeferred, timeout_deferred
3446
from synapse.util.metrics import Measure
3547
from synapse.visibility import filter_events_for_client
@@ -77,7 +89,13 @@ class _NotifierUserStream(object):
7789
so that it can remove itself from the indexes in the Notifier class.
7890
"""
7991

80-
def __init__(self, user_id, rooms, current_token, time_now_ms):
92+
def __init__(
93+
self,
94+
user_id: str,
95+
rooms: Collection[str],
96+
current_token: StreamToken,
97+
time_now_ms: int,
98+
):
8199
self.user_id = user_id
82100
self.rooms = set(rooms)
83101
self.current_token = current_token
@@ -93,13 +111,13 @@ def __init__(self, user_id, rooms, current_token, time_now_ms):
93111
with PreserveLoggingContext():
94112
self.notify_deferred = ObservableDeferred(defer.Deferred())
95113

96-
def notify(self, stream_key, stream_id, time_now_ms):
114+
def notify(self, stream_key: str, stream_id: int, time_now_ms: int):
97115
"""Notify any listeners for this user of a new event from an
98116
event source.
99117
Args:
100-
stream_key(str): The stream the event came from.
101-
stream_id(str): The new id for the stream the event came from.
102-
time_now_ms(int): The current time in milliseconds.
118+
stream_key: The stream the event came from.
119+
stream_id: The new id for the stream the event came from.
120+
time_now_ms: The current time in milliseconds.
103121
"""
104122
self.current_token = self.current_token.copy_and_advance(stream_key, stream_id)
105123
self.last_notified_token = self.current_token
@@ -112,7 +130,7 @@ def notify(self, stream_key, stream_id, time_now_ms):
112130
self.notify_deferred = ObservableDeferred(defer.Deferred())
113131
noify_deferred.callback(self.current_token)
114132

115-
def remove(self, notifier):
133+
def remove(self, notifier: "Notifier"):
116134
""" Remove this listener from all the indexes in the Notifier
117135
it knows about.
118136
"""
@@ -123,10 +141,10 @@ def remove(self, notifier):
123141

124142
notifier.user_to_user_stream.pop(self.user_id)
125143

126-
def count_listeners(self):
144+
def count_listeners(self) -> int:
127145
return len(self.notify_deferred.observers())
128146

129-
def new_listener(self, token):
147+
def new_listener(self, token: StreamToken) -> _NotificationListener:
130148
"""Returns a deferred that is resolved when there is a new token
131149
greater than the given token.
132150
@@ -159,14 +177,16 @@ class Notifier(object):
159177
UNUSED_STREAM_EXPIRY_MS = 10 * 60 * 1000
160178

161179
def __init__(self, hs: "synapse.server.HomeServer"):
162-
self.user_to_user_stream = {}
163-
self.room_to_user_streams = {}
180+
self.user_to_user_stream = {} # type: Dict[str, _NotifierUserStream]
181+
self.room_to_user_streams = {} # type: Dict[str, Set[_NotifierUserStream]]
164182

165183
self.hs = hs
166184
self.storage = hs.get_storage()
167185
self.event_sources = hs.get_event_sources()
168186
self.store = hs.get_datastore()
169-
self.pending_new_room_events = []
187+
self.pending_new_room_events = (
188+
[]
189+
) # type: List[Tuple[int, EventBase, Collection[str]]]
170190

171191
# Called when there are new things to stream over replication
172192
self.replication_callbacks = [] # type: List[Callable[[], None]]
@@ -178,10 +198,9 @@ def __init__(self, hs: "synapse.server.HomeServer"):
178198
self.clock = hs.get_clock()
179199
self.appservice_handler = hs.get_application_service_handler()
180200

201+
self.federation_sender = None
181202
if hs.should_send_federation():
182203
self.federation_sender = hs.get_federation_sender()
183-
else:
184-
self.federation_sender = None
185204

186205
self.state_handler = hs.get_state_handler()
187206

@@ -193,12 +212,12 @@ def __init__(self, hs: "synapse.server.HomeServer"):
193212
# when rendering the metrics page, which is likely once per minute at
194213
# most when scraping it.
195214
def count_listeners():
196-
all_user_streams = set()
215+
all_user_streams = set() # type: Set[_NotifierUserStream]
197216

198-
for x in list(self.room_to_user_streams.values()):
199-
all_user_streams |= x
200-
for x in list(self.user_to_user_stream.values()):
201-
all_user_streams.add(x)
217+
for streams in list(self.room_to_user_streams.values()):
218+
all_user_streams |= streams
219+
for stream in list(self.user_to_user_stream.values()):
220+
all_user_streams.add(stream)
202221

203222
return sum(stream.count_listeners() for stream in all_user_streams)
204223

@@ -223,7 +242,11 @@ def add_replication_callback(self, cb: Callable[[], None]):
223242
self.replication_callbacks.append(cb)
224243

225244
def on_new_room_event(
226-
self, event, room_stream_id, max_room_stream_id, extra_users=[]
245+
self,
246+
event: EventBase,
247+
room_stream_id: int,
248+
max_room_stream_id: int,
249+
extra_users: Collection[str] = [],
227250
):
228251
""" Used by handlers to inform the notifier something has happened
229252
in the room, room event wise.
@@ -241,11 +264,11 @@ def on_new_room_event(
241264

242265
self.notify_replication()
243266

244-
def _notify_pending_new_room_events(self, max_room_stream_id):
267+
def _notify_pending_new_room_events(self, max_room_stream_id: int):
245268
"""Notify for the room events that were queued waiting for a previous
246269
event to be persisted.
247270
Args:
248-
max_room_stream_id(int): The highest stream_id below which all
271+
max_room_stream_id: The highest stream_id below which all
249272
events have been persisted.
250273
"""
251274
pending = self.pending_new_room_events
@@ -258,7 +281,9 @@ def _notify_pending_new_room_events(self, max_room_stream_id):
258281
else:
259282
self._on_new_room_event(event, room_stream_id, extra_users)
260283

261-
def _on_new_room_event(self, event, room_stream_id, extra_users=[]):
284+
def _on_new_room_event(
285+
self, event: EventBase, room_stream_id: int, extra_users: Collection[str] = []
286+
):
262287
"""Notify any user streams that are interested in this room event"""
263288
# poke any interested application service.
264289
run_as_background_process(
@@ -275,13 +300,19 @@ def _on_new_room_event(self, event, room_stream_id, extra_users=[]):
275300
"room_key", room_stream_id, users=extra_users, rooms=[event.room_id]
276301
)
277302

278-
async def _notify_app_services(self, room_stream_id):
303+
async def _notify_app_services(self, room_stream_id: int):
279304
try:
280305
await self.appservice_handler.notify_interested_services(room_stream_id)
281306
except Exception:
282307
logger.exception("Error notifying application services of event")
283308

284-
def on_new_event(self, stream_key, new_token, users=[], rooms=[]):
309+
def on_new_event(
310+
self,
311+
stream_key: str,
312+
new_token: int,
313+
users: Collection[str] = [],
314+
rooms: Collection[str] = [],
315+
):
285316
""" Used to inform listeners that something has happened event wise.
286317
287318
Will wake up all listeners for the given users and rooms.
@@ -307,14 +338,19 @@ def on_new_event(self, stream_key, new_token, users=[], rooms=[]):
307338

308339
self.notify_replication()
309340

310-
def on_new_replication_data(self):
341+
def on_new_replication_data(self) -> None:
311342
"""Used to inform replication listeners that something has happend
312343
without waking up any of the normal user event streams"""
313344
self.notify_replication()
314345

315346
async def wait_for_events(
316-
self, user_id, timeout, callback, room_ids=None, from_token=StreamToken.START
317-
):
347+
self,
348+
user_id: str,
349+
timeout: int,
350+
callback: Callable[[StreamToken, StreamToken], Awaitable[T]],
351+
room_ids=None,
352+
from_token=StreamToken.START,
353+
) -> T:
318354
"""Wait until the callback returns a non empty response or the
319355
timeout fires.
320356
"""
@@ -377,19 +413,16 @@ async def wait_for_events(
377413

378414
async def get_events_for(
379415
self,
380-
user,
381-
pagination_config,
382-
timeout,
383-
only_keys=None,
384-
is_guest=False,
385-
explicit_room_id=None,
386-
):
416+
user: UserID,
417+
pagination_config: PaginationConfig,
418+
timeout: int,
419+
is_guest: bool = False,
420+
explicit_room_id: str = None,
421+
) -> EventStreamResult:
387422
""" For the given user and rooms, return any new events for them. If
388423
there are no new events wait for up to `timeout` milliseconds for any
389424
new events to happen before returning.
390425
391-
If `only_keys` is not None, events from keys will be sent down.
392-
393426
If explicit_room_id is not set, the user's joined rooms will be polled
394427
for events.
395428
If explicit_room_id is set, that room will be polled for events only if
@@ -404,11 +437,13 @@ async def get_events_for(
404437
room_ids, is_joined = await self._get_room_ids(user, explicit_room_id)
405438
is_peeking = not is_joined
406439

407-
async def check_for_updates(before_token, after_token):
440+
async def check_for_updates(
441+
before_token: StreamToken, after_token: StreamToken
442+
) -> EventStreamResult:
408443
if not after_token.is_after(before_token):
409444
return EventStreamResult([], (from_token, from_token))
410445

411-
events = []
446+
events = [] # type: List[EventBase]
412447
end_token = from_token
413448

414449
for name, source in self.event_sources.sources.items():
@@ -417,8 +452,6 @@ async def check_for_updates(before_token, after_token):
417452
after_id = getattr(after_token, keyname)
418453
if before_id == after_id:
419454
continue
420-
if only_keys and name not in only_keys:
421-
continue
422455

423456
new_events, new_key = await source.get_new_events(
424457
user=user,
@@ -476,7 +509,9 @@ async def check_for_updates(before_token, after_token):
476509

477510
return result
478511

479-
async def _get_room_ids(self, user, explicit_room_id):
512+
async def _get_room_ids(
513+
self, user: UserID, explicit_room_id: Optional[str]
514+
) -> Tuple[Collection[str], bool]:
480515
joined_room_ids = await self.store.get_rooms_for_user(user.to_string())
481516
if explicit_room_id:
482517
if explicit_room_id in joined_room_ids:
@@ -486,7 +521,7 @@ async def _get_room_ids(self, user, explicit_room_id):
486521
raise AuthError(403, "Non-joined access not allowed")
487522
return joined_room_ids, True
488523

489-
async def _is_world_readable(self, room_id):
524+
async def _is_world_readable(self, room_id: str) -> bool:
490525
state = await self.state_handler.get_current_state(
491526
room_id, EventTypes.RoomHistoryVisibility, ""
492527
)
@@ -496,7 +531,7 @@ async def _is_world_readable(self, room_id):
496531
return False
497532

498533
@log_function
499-
def remove_expired_streams(self):
534+
def remove_expired_streams(self) -> None:
500535
time_now_ms = self.clock.time_msec()
501536
expired_streams = []
502537
expire_before_ts = time_now_ms - self.UNUSED_STREAM_EXPIRY_MS
@@ -510,21 +545,21 @@ def remove_expired_streams(self):
510545
expired_stream.remove(self)
511546

512547
@log_function
513-
def _register_with_keys(self, user_stream):
548+
def _register_with_keys(self, user_stream: _NotifierUserStream):
514549
self.user_to_user_stream[user_stream.user_id] = user_stream
515550

516551
for room in user_stream.rooms:
517552
s = self.room_to_user_streams.setdefault(room, set())
518553
s.add(user_stream)
519554

520-
def _user_joined_room(self, user_id, room_id):
555+
def _user_joined_room(self, user_id: str, room_id: str):
521556
new_user_stream = self.user_to_user_stream.get(user_id)
522557
if new_user_stream is not None:
523558
room_streams = self.room_to_user_streams.setdefault(room_id, set())
524559
room_streams.add(new_user_stream)
525560
new_user_stream.rooms.add(room_id)
526561

527-
def notify_replication(self):
562+
def notify_replication(self) -> None:
528563
"""Notify the any replication listeners that there's a new event"""
529564
for cb in self.replication_callbacks:
530565
cb()

synapse/server.pyi

+6
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,10 @@ import synapse.server_notices.server_notices_sender
3131
import synapse.state
3232
import synapse.storage
3333
from synapse.events.builder import EventBuilderFactory
34+
from synapse.handlers.appservice import ApplicationServicesHandler
3435
from synapse.handlers.typing import FollowerTypingHandler
3536
from synapse.replication.tcp.streams import Stream
37+
from synapse.streams.events import EventSources
3638

3739
class HomeServer(object):
3840
@property
@@ -153,3 +155,7 @@ class HomeServer(object):
153155
pass
154156
def get_typing_handler(self) -> FollowerTypingHandler:
155157
pass
158+
def get_event_sources(self) -> EventSources:
159+
pass
160+
def get_application_service_handler(self):
161+
return ApplicationServicesHandler(self)

tox.ini

+1
Original file line numberDiff line numberDiff line change
@@ -199,6 +199,7 @@ commands = mypy \
199199
synapse/logging/ \
200200
synapse/metrics \
201201
synapse/module_api \
202+
synapse/notifier.py \
202203
synapse/push/pusherpool.py \
203204
synapse/push/push_rule_evaluator.py \
204205
synapse/replication \

0 commit comments

Comments
 (0)