Fix some comments and types in service notices (#7996)

This commit is contained in:
Patrick Cloke 2020-07-31 16:22:06 -04:00 committed by GitHub
parent 394be6a0e6
commit d1008fe949
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
7 changed files with 56 additions and 59 deletions

1
changelog.d/7996.bugfix Normal file
View file

@ -0,0 +1 @@
Fix various comments and minor discrepencies in server notices code.

View file

@ -13,6 +13,7 @@
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
import logging import logging
from typing import Any
from synapse.api.errors import SynapseError from synapse.api.errors import SynapseError
from synapse.api.urls import ConsentURIBuilder from synapse.api.urls import ConsentURIBuilder
@ -55,14 +56,11 @@ class ConsentServerNotices(object):
self._consent_uri_builder = ConsentURIBuilder(hs.config) self._consent_uri_builder = ConsentURIBuilder(hs.config)
async def maybe_send_server_notice_to_user(self, user_id): async def maybe_send_server_notice_to_user(self, user_id: str) -> None:
"""Check if we need to send a notice to this user, and does so if so """Check if we need to send a notice to this user, and does so if so
Args: Args:
user_id (str): user to check user_id: user to check
Returns:
Deferred
""" """
if self._server_notice_content is None: if self._server_notice_content is None:
# not enabled # not enabled
@ -105,7 +103,7 @@ class ConsentServerNotices(object):
self._users_in_progress.remove(user_id) self._users_in_progress.remove(user_id)
def copy_with_str_subst(x, substitutions): def copy_with_str_subst(x: Any, substitutions: Any) -> Any:
"""Deep-copy a structure, carrying out string substitions on any strings """Deep-copy a structure, carrying out string substitions on any strings
Args: Args:
@ -121,7 +119,7 @@ def copy_with_str_subst(x, substitutions):
if isinstance(x, dict): if isinstance(x, dict):
return {k: copy_with_str_subst(v, substitutions) for (k, v) in x.items()} return {k: copy_with_str_subst(v, substitutions) for (k, v) in x.items()}
if isinstance(x, (list, tuple)): if isinstance(x, (list, tuple)):
return [copy_with_str_subst(y) for y in x] return [copy_with_str_subst(y, substitutions) for y in x]
# assume it's uninterested and can be shallow-copied. # assume it's uninterested and can be shallow-copied.
return x return x

View file

@ -13,6 +13,7 @@
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
import logging import logging
from typing import List, Tuple
from synapse.api.constants import ( from synapse.api.constants import (
EventTypes, EventTypes,
@ -52,7 +53,7 @@ class ResourceLimitsServerNotices(object):
and not hs.config.hs_disabled and not hs.config.hs_disabled
) )
async def maybe_send_server_notice_to_user(self, user_id): async def maybe_send_server_notice_to_user(self, user_id: str) -> None:
"""Check if we need to send a notice to this user, this will be true in """Check if we need to send a notice to this user, this will be true in
two cases. two cases.
1. The server has reached its limit does not reflect this 1. The server has reached its limit does not reflect this
@ -60,10 +61,7 @@ class ResourceLimitsServerNotices(object):
actually the server is fine actually the server is fine
Args: Args:
user_id (str): user to check user_id: user to check
Returns:
Deferred
""" """
if not self._enabled: if not self._enabled:
return return
@ -115,18 +113,20 @@ class ResourceLimitsServerNotices(object):
elif not currently_blocked and limit_msg: elif not currently_blocked and limit_msg:
# Room is not notifying of a block, when it ought to be. # Room is not notifying of a block, when it ought to be.
await self._apply_limit_block_notification( await self._apply_limit_block_notification(
user_id, limit_msg, limit_type user_id, limit_msg, limit_type # type: ignore
) )
except SynapseError as e: except SynapseError as e:
logger.error("Error sending resource limits server notice: %s", e) logger.error("Error sending resource limits server notice: %s", e)
async def _remove_limit_block_notification(self, user_id, ref_events): async def _remove_limit_block_notification(
self, user_id: str, ref_events: List[str]
) -> None:
"""Utility method to remove limit block notifications from the server """Utility method to remove limit block notifications from the server
notices room. notices room.
Args: Args:
user_id (str): user to notify user_id: user to notify
ref_events (list[str]): The event_ids of pinned events that are unrelated to ref_events: The event_ids of pinned events that are unrelated to
limit blocking and need to be preserved. limit blocking and need to be preserved.
""" """
content = {"pinned": ref_events} content = {"pinned": ref_events}
@ -135,15 +135,15 @@ class ResourceLimitsServerNotices(object):
) )
async def _apply_limit_block_notification( async def _apply_limit_block_notification(
self, user_id, event_body, event_limit_type self, user_id: str, event_body: str, event_limit_type: str
): ) -> None:
"""Utility method to apply limit block notifications in the server """Utility method to apply limit block notifications in the server
notices room. notices room.
Args: Args:
user_id (str): user to notify user_id: user to notify
event_body(str): The human readable text that describes the block. event_body: The human readable text that describes the block.
event_limit_type(str): Specifies the type of block e.g. monthly active user event_limit_type: Specifies the type of block e.g. monthly active user
limit has been exceeded. limit has been exceeded.
""" """
content = { content = {
@ -162,7 +162,7 @@ class ResourceLimitsServerNotices(object):
user_id, content, EventTypes.Pinned, "" user_id, content, EventTypes.Pinned, ""
) )
async def _check_and_set_tags(self, user_id, room_id): async def _check_and_set_tags(self, user_id: str, room_id: str) -> None:
""" """
Since server notices rooms were originally not with tags, Since server notices rooms were originally not with tags,
important to check that tags have been set correctly important to check that tags have been set correctly
@ -182,17 +182,16 @@ class ResourceLimitsServerNotices(object):
) )
self._notifier.on_new_event("account_data_key", max_id, users=[user_id]) self._notifier.on_new_event("account_data_key", max_id, users=[user_id])
async def _is_room_currently_blocked(self, room_id): async def _is_room_currently_blocked(self, room_id: str) -> Tuple[bool, List[str]]:
""" """
Determines if the room is currently blocked Determines if the room is currently blocked
Args: Args:
room_id(str): The room id of the server notices room room_id: The room id of the server notices room
Returns: Returns:
Deferred[Tuple[bool, List]]:
bool: Is the room currently blocked bool: Is the room currently blocked
list: The list of pinned events that are unrelated to limit blocking list: The list of pinned event IDs that are unrelated to limit blocking
This list can be used as a convenience in the case where the block This list can be used as a convenience in the case where the block
is to be lifted and the remaining pinned event references need to be is to be lifted and the remaining pinned event references need to be
preserved preserved
@ -207,7 +206,7 @@ class ResourceLimitsServerNotices(object):
# The user has yet to join the server notices room # The user has yet to join the server notices room
pass pass
referenced_events = [] referenced_events = [] # type: List[str]
if pinned_state_event is not None: if pinned_state_event is not None:
referenced_events = list(pinned_state_event.content.get("pinned", [])) referenced_events = list(pinned_state_event.content.get("pinned", []))

View file

@ -13,8 +13,10 @@
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
import logging import logging
from typing import Optional
from synapse.api.constants import EventTypes, Membership, RoomCreationPreset from synapse.api.constants import EventTypes, Membership, RoomCreationPreset
from synapse.events import EventBase
from synapse.types import UserID, create_requester from synapse.types import UserID, create_requester
from synapse.util.caches.descriptors import cached from synapse.util.caches.descriptors import cached
@ -50,20 +52,21 @@ class ServerNoticesManager(object):
return self._config.server_notices_mxid is not None return self._config.server_notices_mxid is not None
async def send_notice( async def send_notice(
self, user_id, event_content, type=EventTypes.Message, state_key=None self,
): user_id: str,
event_content: dict,
type: str = EventTypes.Message,
state_key: Optional[bool] = None,
) -> EventBase:
"""Send a notice to the given user """Send a notice to the given user
Creates the server notices room, if none exists. Creates the server notices room, if none exists.
Args: Args:
user_id (str): mxid of user to send event to. user_id: mxid of user to send event to.
event_content (dict): content of event to send event_content: content of event to send
type(EventTypes): type of event type: type of event
is_state_event(bool): Is the event a state event is_state_event: Is the event a state event
Returns:
Deferred[FrozenEvent]
""" """
room_id = await self.get_or_create_notice_room_for_user(user_id) room_id = await self.get_or_create_notice_room_for_user(user_id)
await self.maybe_invite_user_to_room(user_id, room_id) await self.maybe_invite_user_to_room(user_id, room_id)
@ -89,17 +92,17 @@ class ServerNoticesManager(object):
return event return event
@cached() @cached()
async def get_or_create_notice_room_for_user(self, user_id): async def get_or_create_notice_room_for_user(self, user_id: str) -> str:
"""Get the room for notices for a given user """Get the room for notices for a given user
If we have not yet created a notice room for this user, create it, but don't If we have not yet created a notice room for this user, create it, but don't
invite the user to it. invite the user to it.
Args: Args:
user_id (str): complete user id for the user we want a room for user_id: complete user id for the user we want a room for
Returns: Returns:
str: room id of notice room. room id of notice room.
""" """
if not self.is_enabled(): if not self.is_enabled():
raise Exception("Server notices not enabled") raise Exception("Server notices not enabled")
@ -163,7 +166,7 @@ class ServerNoticesManager(object):
logger.info("Created server notices room %s for %s", room_id, user_id) logger.info("Created server notices room %s for %s", room_id, user_id)
return room_id return room_id
async def maybe_invite_user_to_room(self, user_id: str, room_id: str): async def maybe_invite_user_to_room(self, user_id: str, room_id: str) -> None:
"""Invite the given user to the given server room, unless the user has already """Invite the given user to the given server room, unless the user has already
joined or been invited to it. joined or been invited to it.

View file

@ -12,6 +12,8 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
from typing import Iterable, Union
from synapse.server_notices.consent_server_notices import ConsentServerNotices from synapse.server_notices.consent_server_notices import ConsentServerNotices
from synapse.server_notices.resource_limits_server_notices import ( from synapse.server_notices.resource_limits_server_notices import (
ResourceLimitsServerNotices, ResourceLimitsServerNotices,
@ -32,22 +34,22 @@ class ServerNoticesSender(object):
self._server_notices = ( self._server_notices = (
ConsentServerNotices(hs), ConsentServerNotices(hs),
ResourceLimitsServerNotices(hs), ResourceLimitsServerNotices(hs),
) ) # type: Iterable[Union[ConsentServerNotices, ResourceLimitsServerNotices]]
async def on_user_syncing(self, user_id): async def on_user_syncing(self, user_id: str) -> None:
"""Called when the user performs a sync operation. """Called when the user performs a sync operation.
Args: Args:
user_id (str): mxid of user who synced user_id: mxid of user who synced
""" """
for sn in self._server_notices: for sn in self._server_notices:
await sn.maybe_send_server_notice_to_user(user_id) await sn.maybe_send_server_notice_to_user(user_id)
async def on_user_ip(self, user_id): async def on_user_ip(self, user_id: str) -> None:
"""Called on the master when a worker process saw a client request. """Called on the master when a worker process saw a client request.
Args: Args:
user_id (str): mxid user_id: mxid
""" """
# The synchrotrons use a stubbed version of ServerNoticesSender, so # The synchrotrons use a stubbed version of ServerNoticesSender, so
# we check for notices to send to the user in on_user_ip as well as # we check for notices to send to the user in on_user_ip as well as

View file

@ -12,7 +12,6 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
from twisted.internet import defer
class WorkerServerNoticesSender(object): class WorkerServerNoticesSender(object):
@ -24,24 +23,18 @@ class WorkerServerNoticesSender(object):
hs (synapse.server.HomeServer): hs (synapse.server.HomeServer):
""" """
def on_user_syncing(self, user_id): async def on_user_syncing(self, user_id: str) -> None:
"""Called when the user performs a sync operation. """Called when the user performs a sync operation.
Args: Args:
user_id (str): mxid of user who synced user_id: mxid of user who synced
Returns:
Deferred
""" """
return defer.succeed(None) return None
def on_user_ip(self, user_id): async def on_user_ip(self, user_id: str) -> None:
"""Called on the master when a worker process saw a client request. """Called on the master when a worker process saw a client request.
Args: Args:
user_id (str): mxid user_id: mxid
Returns:
Deferred
""" """
raise AssertionError("on_user_ip unexpectedly called on worker") raise AssertionError("on_user_ip unexpectedly called on worker")

View file

@ -202,6 +202,7 @@ commands = mypy \
synapse/push/push_rule_evaluator.py \ synapse/push/push_rule_evaluator.py \
synapse/replication \ synapse/replication \
synapse/rest \ synapse/rest \
synapse/server_notices \
synapse/spam_checker_api \ synapse/spam_checker_api \
synapse/storage/data_stores/main/ui_auth.py \ synapse/storage/data_stores/main/ui_auth.py \
synapse/storage/database.py \ synapse/storage/database.py \