0
0
Fork 1
mirror of https://mau.dev/maunium/synapse.git synced 2024-12-20 23:43:51 +01:00

Additional constants for EDU types. (#12884)

Instead of hard-coding strings in many places.
This commit is contained in:
Patrick Cloke 2022-05-27 07:14:36 -04:00 committed by GitHub
parent d9f092285b
commit c52abc1cfd
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
35 changed files with 146 additions and 96 deletions

1
changelog.d/12884.misc Normal file
View file

@ -0,0 +1 @@
Use constants for EDU types.

View file

@ -137,7 +137,13 @@ class DeviceKeyAlgorithms:
class EduTypes: class EduTypes:
Presence: Final = "m.presence" PRESENCE: Final = "m.presence"
TYPING: Final = "m.typing"
RECEIPT: Final = "m.receipt"
DEVICE_LIST_UPDATE: Final = "m.device_list_update"
SIGNING_KEY_UPDATE: Final = "m.signing_key_update"
UNSTABLE_SIGNING_KEY_UPDATE: Final = "org.matrix.signing_key_update"
DIRECT_TO_DEVICE: Final = "m.direct_to_device"
class RejectedReason: class RejectedReason:

View file

@ -33,7 +33,7 @@ from typing import (
import jsonschema import jsonschema
from jsonschema import FormatChecker from jsonschema import FormatChecker
from synapse.api.constants import EventContentFields from synapse.api.constants import EduTypes, EventContentFields
from synapse.api.errors import SynapseError from synapse.api.errors import SynapseError
from synapse.api.presence import UserPresenceState from synapse.api.presence import UserPresenceState
from synapse.events import EventBase from synapse.events import EventBase
@ -347,7 +347,7 @@ class Filter:
user_id = event.user_id user_id = event.user_id
field_matchers = { field_matchers = {
"senders": lambda v: user_id == v, "senders": lambda v: user_id == v,
"types": lambda v: "m.presence" == v, "types": lambda v: EduTypes.PRESENCE == v,
} }
return self._check_fields(field_matchers) return self._check_fields(field_matchers)
else: else:

View file

@ -1353,7 +1353,7 @@ class FederationHandlerRegistry:
self._edu_type_to_instance[edu_type] = instance_names self._edu_type_to_instance[edu_type] = instance_names
async def on_edu(self, edu_type: str, origin: str, content: dict) -> None: async def on_edu(self, edu_type: str, origin: str, content: dict) -> None:
if not self.config.server.use_presence and edu_type == EduTypes.Presence: if not self.config.server.use_presence and edu_type == EduTypes.PRESENCE:
return return
# Check if we have a handler on this instance # Check if we have a handler on this instance

View file

@ -21,6 +21,7 @@ from typing import TYPE_CHECKING, Dict, Hashable, Iterable, List, Optional, Tupl
import attr import attr
from prometheus_client import Counter from prometheus_client import Counter
from synapse.api.constants import EduTypes
from synapse.api.errors import ( from synapse.api.errors import (
FederationDeniedError, FederationDeniedError,
HttpResponseException, HttpResponseException,
@ -542,7 +543,7 @@ class PerDestinationQueue:
edu = Edu( edu = Edu(
origin=self._server_name, origin=self._server_name,
destination=self._destination, destination=self._destination,
edu_type="m.receipt", edu_type=EduTypes.RECEIPT,
content=self._pending_rrs, content=self._pending_rrs,
) )
self._pending_rrs = {} self._pending_rrs = {}
@ -592,7 +593,7 @@ class PerDestinationQueue:
Edu( Edu(
origin=self._server_name, origin=self._server_name,
destination=self._destination, destination=self._destination,
edu_type="m.direct_to_device", edu_type=EduTypes.DIRECT_TO_DEVICE,
content=content, content=content,
) )
for content in contents for content in contents
@ -670,7 +671,7 @@ class _TransactionQueueManager:
Edu( Edu(
origin=self.queue._server_name, origin=self.queue._server_name,
destination=self.queue._destination, destination=self.queue._destination,
edu_type="m.presence", edu_type=EduTypes.PRESENCE,
content={ content={
"push": [ "push": [
format_user_presence_state( format_user_presence_state(

View file

@ -16,6 +16,7 @@ from typing import TYPE_CHECKING, List
from prometheus_client import Gauge from prometheus_client import Gauge
from synapse.api.constants import EduTypes
from synapse.api.errors import HttpResponseException from synapse.api.errors import HttpResponseException
from synapse.events import EventBase from synapse.events import EventBase
from synapse.federation.persistence import TransactionActions from synapse.federation.persistence import TransactionActions
@ -126,7 +127,10 @@ class TransactionManager:
len(edus), len(edus),
) )
if issue_8631_logger.isEnabledFor(logging.DEBUG): if issue_8631_logger.isEnabledFor(logging.DEBUG):
DEVICE_UPDATE_EDUS = {"m.device_list_update", "m.signing_key_update"} DEVICE_UPDATE_EDUS = {
EduTypes.DEVICE_LIST_UPDATE,
EduTypes.SIGNING_KEY_UPDATE,
}
device_list_updates = [ device_list_updates = [
edu.content for edu in edus if edu.edu_type in DEVICE_UPDATE_EDUS edu.content for edu in edus if edu.edu_type in DEVICE_UPDATE_EDUS
] ]

View file

@ -27,6 +27,7 @@ from typing import (
from matrix_common.versionstring import get_distribution_version_string from matrix_common.versionstring import get_distribution_version_string
from typing_extensions import Literal from typing_extensions import Literal
from synapse.api.constants import EduTypes
from synapse.api.errors import Codes, SynapseError from synapse.api.errors import Codes, SynapseError
from synapse.api.room_versions import RoomVersions from synapse.api.room_versions import RoomVersions
from synapse.api.urls import FEDERATION_UNSTABLE_PREFIX, FEDERATION_V2_PREFIX from synapse.api.urls import FEDERATION_UNSTABLE_PREFIX, FEDERATION_V2_PREFIX
@ -108,7 +109,10 @@ class FederationSendServlet(BaseFederationServerServlet):
) )
if issue_8631_logger.isEnabledFor(logging.DEBUG): if issue_8631_logger.isEnabledFor(logging.DEBUG):
DEVICE_UPDATE_EDUS = ["m.device_list_update", "m.signing_key_update"] DEVICE_UPDATE_EDUS = [
EduTypes.DEVICE_LIST_UPDATE,
EduTypes.SIGNING_KEY_UPDATE,
]
device_list_updates = [ device_list_updates = [
edu.get("content", {}) edu.get("content", {})
for edu in transaction_data.get("edus", []) for edu in transaction_data.get("edus", [])

View file

@ -19,7 +19,7 @@ from prometheus_client import Counter
from twisted.internet import defer from twisted.internet import defer
import synapse import synapse
from synapse.api.constants import EventTypes from synapse.api.constants import EduTypes, EventTypes
from synapse.appservice import ApplicationService from synapse.appservice import ApplicationService
from synapse.events import EventBase from synapse.events import EventBase
from synapse.handlers.presence import format_user_presence_state from synapse.handlers.presence import format_user_presence_state
@ -503,7 +503,7 @@ class ApplicationServicesHandler:
time_now = self.clock.time_msec() time_now = self.clock.time_msec()
events.extend( events.extend(
{ {
"type": "m.presence", "type": EduTypes.PRESENCE,
"sender": event.user_id, "sender": event.user_id,
"content": format_user_presence_state( "content": format_user_presence_state(
event, time_now, include_user_id=False event, time_now, include_user_id=False

View file

@ -28,7 +28,7 @@ from typing import (
) )
from synapse.api import errors from synapse.api import errors
from synapse.api.constants import EventTypes from synapse.api.constants import EduTypes, EventTypes
from synapse.api.errors import ( from synapse.api.errors import (
Codes, Codes,
FederationDeniedError, FederationDeniedError,
@ -279,7 +279,8 @@ class DeviceHandler(DeviceWorkerHandler):
federation_registry = hs.get_federation_registry() federation_registry = hs.get_federation_registry()
federation_registry.register_edu_handler( federation_registry.register_edu_handler(
"m.device_list_update", self.device_list_updater.incoming_device_list_update EduTypes.DEVICE_LIST_UPDATE,
self.device_list_updater.incoming_device_list_update,
) )
hs.get_distributor().observe("user_left_room", self.user_left_room) hs.get_distributor().observe("user_left_room", self.user_left_room)

View file

@ -15,7 +15,7 @@
import logging import logging
from typing import TYPE_CHECKING, Any, Dict from typing import TYPE_CHECKING, Any, Dict
from synapse.api.constants import ToDeviceEventTypes from synapse.api.constants import EduTypes, ToDeviceEventTypes
from synapse.api.errors import SynapseError from synapse.api.errors import SynapseError
from synapse.api.ratelimiting import Ratelimiter from synapse.api.ratelimiting import Ratelimiter
from synapse.logging.context import run_in_background from synapse.logging.context import run_in_background
@ -59,11 +59,11 @@ class DeviceMessageHandler:
# to the appropriate worker. # to the appropriate worker.
if hs.get_instance_name() in hs.config.worker.writers.to_device: if hs.get_instance_name() in hs.config.worker.writers.to_device:
hs.get_federation_registry().register_edu_handler( hs.get_federation_registry().register_edu_handler(
"m.direct_to_device", self.on_direct_to_device_edu EduTypes.DIRECT_TO_DEVICE, self.on_direct_to_device_edu
) )
else: else:
hs.get_federation_registry().register_instances_for_edu( hs.get_federation_registry().register_instances_for_edu(
"m.direct_to_device", EduTypes.DIRECT_TO_DEVICE,
hs.config.worker.writers.to_device, hs.config.worker.writers.to_device,
) )

View file

@ -25,6 +25,7 @@ from unpaddedbase64 import decode_base64
from twisted.internet import defer from twisted.internet import defer
from synapse.api.constants import EduTypes
from synapse.api.errors import CodeMessageException, Codes, NotFoundError, SynapseError from synapse.api.errors import CodeMessageException, Codes, NotFoundError, SynapseError
from synapse.logging.context import make_deferred_yieldable, run_in_background from synapse.logging.context import make_deferred_yieldable, run_in_background
from synapse.logging.opentracing import log_kv, set_tag, tag_args, trace from synapse.logging.opentracing import log_kv, set_tag, tag_args, trace
@ -66,13 +67,13 @@ class E2eKeysHandler:
# Only register this edu handler on master as it requires writing # Only register this edu handler on master as it requires writing
# device updates to the db # device updates to the db
federation_registry.register_edu_handler( federation_registry.register_edu_handler(
"m.signing_key_update", EduTypes.SIGNING_KEY_UPDATE,
self._edu_updater.incoming_signing_key_update, self._edu_updater.incoming_signing_key_update,
) )
# also handle the unstable version # also handle the unstable version
# FIXME: remove this when enough servers have upgraded # FIXME: remove this when enough servers have upgraded
federation_registry.register_edu_handler( federation_registry.register_edu_handler(
"org.matrix.signing_key_update", EduTypes.UNSTABLE_SIGNING_KEY_UPDATE,
self._edu_updater.incoming_signing_key_update, self._edu_updater.incoming_signing_key_update,
) )

View file

@ -113,7 +113,7 @@ class EventStreamHandler:
states = await presence_handler.get_states(users) states = await presence_handler.get_states(users)
to_add.extend( to_add.extend(
{ {
"type": EduTypes.Presence, "type": EduTypes.PRESENCE,
"content": format_user_presence_state(state, time_now), "content": format_user_presence_state(state, time_now),
} }
for state in states for state in states

View file

@ -274,7 +274,7 @@ class InitialSyncHandler:
"rooms": rooms_ret, "rooms": rooms_ret,
"presence": [ "presence": [
{ {
"type": "m.presence", "type": EduTypes.PRESENCE,
"content": format_user_presence_state(event, now), "content": format_user_presence_state(event, now),
} }
for event in presence for event in presence
@ -439,7 +439,7 @@ class InitialSyncHandler:
return [ return [
{ {
"type": EduTypes.Presence, "type": EduTypes.PRESENCE,
"content": format_user_presence_state(s, time_now), "content": format_user_presence_state(s, time_now),
} }
for s in states for s in states

View file

@ -49,7 +49,7 @@ from prometheus_client import Counter
from typing_extensions import ContextManager from typing_extensions import ContextManager
import synapse.metrics import synapse.metrics
from synapse.api.constants import EventTypes, Membership, PresenceState from synapse.api.constants import EduTypes, EventTypes, Membership, PresenceState
from synapse.api.errors import SynapseError from synapse.api.errors import SynapseError
from synapse.api.presence import UserPresenceState from synapse.api.presence import UserPresenceState
from synapse.appservice import ApplicationService from synapse.appservice import ApplicationService
@ -394,7 +394,7 @@ class WorkerPresenceHandler(BasePresenceHandler):
# Route presence EDUs to the right worker # Route presence EDUs to the right worker
hs.get_federation_registry().register_instances_for_edu( hs.get_federation_registry().register_instances_for_edu(
"m.presence", EduTypes.PRESENCE,
hs.config.worker.writers.presence, hs.config.worker.writers.presence,
) )
@ -649,7 +649,9 @@ class PresenceHandler(BasePresenceHandler):
federation_registry = hs.get_federation_registry() federation_registry = hs.get_federation_registry()
federation_registry.register_edu_handler("m.presence", self.incoming_presence) federation_registry.register_edu_handler(
EduTypes.PRESENCE, self.incoming_presence
)
LaterGauge( LaterGauge(
"synapse_handlers_presence_user_to_current_state_size", "synapse_handlers_presence_user_to_current_state_size",

View file

@ -14,7 +14,7 @@
import logging import logging
from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple
from synapse.api.constants import ReceiptTypes from synapse.api.constants import EduTypes, ReceiptTypes
from synapse.appservice import ApplicationService from synapse.appservice import ApplicationService
from synapse.streams import EventSource from synapse.streams import EventSource
from synapse.types import ( from synapse.types import (
@ -52,11 +52,11 @@ class ReceiptsHandler:
# to the appropriate worker. # to the appropriate worker.
if hs.get_instance_name() in hs.config.worker.writers.receipts: if hs.get_instance_name() in hs.config.worker.writers.receipts:
hs.get_federation_registry().register_edu_handler( hs.get_federation_registry().register_edu_handler(
"m.receipt", self._received_remote_receipt EduTypes.RECEIPT, self._received_remote_receipt
) )
else: else:
hs.get_federation_registry().register_instances_for_edu( hs.get_federation_registry().register_instances_for_edu(
"m.receipt", EduTypes.RECEIPT,
hs.config.worker.writers.receipts, hs.config.worker.writers.receipts,
) )

View file

@ -17,6 +17,7 @@ from typing import TYPE_CHECKING, Dict, Iterable, List, Optional, Set, Tuple
import attr import attr
from synapse.api.constants import EduTypes
from synapse.api.errors import AuthError, ShadowBanError, SynapseError from synapse.api.errors import AuthError, ShadowBanError, SynapseError
from synapse.appservice import ApplicationService from synapse.appservice import ApplicationService
from synapse.metrics.background_process_metrics import ( from synapse.metrics.background_process_metrics import (
@ -68,7 +69,7 @@ class FollowerTypingHandler:
if hs.get_instance_name() not in hs.config.worker.writers.typing: if hs.get_instance_name() not in hs.config.worker.writers.typing:
hs.get_federation_registry().register_instances_for_edu( hs.get_federation_registry().register_instances_for_edu(
"m.typing", EduTypes.TYPING,
hs.config.worker.writers.typing, hs.config.worker.writers.typing,
) )
@ -143,7 +144,7 @@ class FollowerTypingHandler:
logger.debug("sending typing update to %s", domain) logger.debug("sending typing update to %s", domain)
self.federation.build_and_send_edu( self.federation.build_and_send_edu(
destination=domain, destination=domain,
edu_type="m.typing", edu_type=EduTypes.TYPING,
content={ content={
"room_id": member.room_id, "room_id": member.room_id,
"user_id": member.user_id, "user_id": member.user_id,
@ -218,7 +219,9 @@ class TypingWriterHandler(FollowerTypingHandler):
self.hs = hs self.hs = hs
hs.get_federation_registry().register_edu_handler("m.typing", self._recv_edu) hs.get_federation_registry().register_edu_handler(
EduTypes.TYPING, self._recv_edu
)
hs.get_distributor().observe("user_left_room", self.user_left_room) hs.get_distributor().observe("user_left_room", self.user_left_room)
@ -458,7 +461,7 @@ class TypingNotificationEventSource(EventSource[int, JsonDict]):
def _make_event_for(self, room_id: str) -> JsonDict: def _make_event_for(self, room_id: str) -> JsonDict:
typing = self.get_typing_handler()._room_typing[room_id] typing = self.get_typing_handler()._room_typing[room_id]
return { return {
"type": "m.typing", "type": EduTypes.TYPING,
"room_id": room_id, "room_id": room_id,
"content": {"user_ids": list(typing)}, "content": {"user_ids": list(typing)},
} }

View file

@ -33,7 +33,7 @@ from prometheus_client import Counter
from twisted.internet import defer from twisted.internet import defer
from synapse.api.constants import EventTypes, HistoryVisibility, Membership from synapse.api.constants import EduTypes, EventTypes, HistoryVisibility, Membership
from synapse.api.errors import AuthError from synapse.api.errors import AuthError
from synapse.events import EventBase from synapse.events import EventBase
from synapse.handlers.presence import format_user_presence_state from synapse.handlers.presence import format_user_presence_state
@ -632,7 +632,7 @@ class Notifier:
now = self.clock.time_msec() now = self.clock.time_msec()
new_events[:] = [ new_events[:] = [
{ {
"type": "m.presence", "type": EduTypes.PRESENCE,
"content": format_user_presence_state(event, now), "content": format_user_presence_state(event, now),
} }
for event in new_events for event in new_events

View file

@ -16,7 +16,7 @@ import logging
from collections import defaultdict from collections import defaultdict
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union
from synapse.api.constants import Membership, PresenceState from synapse.api.constants import EduTypes, Membership, PresenceState
from synapse.api.errors import Codes, StoreError, SynapseError from synapse.api.errors import Codes, StoreError, SynapseError
from synapse.api.filtering import FilterCollection from synapse.api.filtering import FilterCollection
from synapse.api.presence import UserPresenceState from synapse.api.presence import UserPresenceState
@ -305,7 +305,7 @@ class SyncRestServlet(RestServlet):
return { return {
"events": [ "events": [
{ {
"type": "m.presence", "type": EduTypes.PRESENCE,
"sender": event.user_id, "sender": event.user_id,
"content": format_user_presence_state( "content": format_user_presence_state(
event, time_now, include_user_id=False event, time_now, include_user_id=False

View file

@ -28,6 +28,7 @@ from typing import (
cast, cast,
) )
from synapse.api.constants import EduTypes
from synapse.api.errors import Codes, StoreError from synapse.api.errors import Codes, StoreError
from synapse.logging.opentracing import ( from synapse.logging.opentracing import (
get_active_span_text_map, get_active_span_text_map,
@ -419,7 +420,7 @@ class DeviceWorkerStore(SQLBaseStore):
# Add the updated cross-signing keys to the results list # Add the updated cross-signing keys to the results list
for user_id, result in cross_signing_keys_by_user.items(): for user_id, result in cross_signing_keys_by_user.items():
result["user_id"] = user_id result["user_id"] = user_id
results.append(("m.signing_key_update", result)) results.append((EduTypes.SIGNING_KEY_UPDATE, result))
# also send the unstable version # also send the unstable version
# FIXME: remove this when enough servers have upgraded # FIXME: remove this when enough servers have upgraded
# and remove the length budgeting above. # and remove the length budgeting above.
@ -545,7 +546,7 @@ class DeviceWorkerStore(SQLBaseStore):
else: else:
result["deleted"] = True result["deleted"] = True
results.append(("m.device_list_update", result)) results.append((EduTypes.DEVICE_LIST_UPDATE, result))
return results return results

View file

@ -26,7 +26,7 @@ from typing import (
cast, cast,
) )
from synapse.api.constants import ReceiptTypes from synapse.api.constants import EduTypes, ReceiptTypes
from synapse.replication.slave.storage._slaved_id_tracker import SlavedIdTracker from synapse.replication.slave.storage._slaved_id_tracker import SlavedIdTracker
from synapse.replication.tcp.streams import ReceiptsStream from synapse.replication.tcp.streams import ReceiptsStream
from synapse.storage._base import SQLBaseStore, db_to_json, make_in_list_sql_clause from synapse.storage._base import SQLBaseStore, db_to_json, make_in_list_sql_clause
@ -363,7 +363,7 @@ class ReceiptsWorkerStore(SQLBaseStore):
row["user_id"] row["user_id"]
] = db_to_json(row["data"]) ] = db_to_json(row["data"])
return [{"type": "m.receipt", "room_id": room_id, "content": content}] return [{"type": EduTypes.RECEIPT, "room_id": room_id, "content": content}]
@cachedList( @cachedList(
cached_method_name="_get_linearized_receipts_for_room", cached_method_name="_get_linearized_receipts_for_room",
@ -411,7 +411,7 @@ class ReceiptsWorkerStore(SQLBaseStore):
# receipts by room, event and type. # receipts by room, event and type.
room_event = results.setdefault( room_event = results.setdefault(
row["room_id"], row["room_id"],
{"type": "m.receipt", "room_id": row["room_id"], "content": {}}, {"type": EduTypes.RECEIPT, "room_id": row["room_id"], "content": {}},
) )
# The content is of the form: # The content is of the form:
@ -476,7 +476,7 @@ class ReceiptsWorkerStore(SQLBaseStore):
# receipts by room, event and type. # receipts by room, event and type.
room_event = results.setdefault( room_event = results.setdefault(
row["room_id"], row["room_id"],
{"type": "m.receipt", "room_id": row["room_id"], "content": {}}, {"type": EduTypes.RECEIPT, "room_id": row["room_id"], "content": {}},
) )
# The content is of the form: # The content is of the form:

View file

@ -20,7 +20,7 @@ from unittest.mock import patch
import jsonschema import jsonschema
from frozendict import frozendict from frozendict import frozendict
from synapse.api.constants import EventContentFields from synapse.api.constants import EduTypes, EventContentFields
from synapse.api.errors import SynapseError from synapse.api.errors import SynapseError
from synapse.api.filtering import Filter from synapse.api.filtering import Filter
from synapse.events import make_event_from_dict from synapse.events import make_event_from_dict
@ -85,13 +85,13 @@ class FilteringTestCase(unittest.HomeserverTestCase):
"org.matrix.not_labels": ["#work"], "org.matrix.not_labels": ["#work"],
}, },
"ephemeral": { "ephemeral": {
"types": ["m.receipt", "m.typing"], "types": [EduTypes.RECEIPT, EduTypes.TYPING],
"not_rooms": ["!726s6s6q:example.com"], "not_rooms": ["!726s6s6q:example.com"],
"not_senders": ["@spam:example.com"], "not_senders": ["@spam:example.com"],
}, },
}, },
"presence": { "presence": {
"types": ["m.presence"], "types": [EduTypes.PRESENCE],
"not_senders": ["@alice:example.com"], "not_senders": ["@alice:example.com"],
}, },
"event_format": "client", "event_format": "client",

View file

@ -439,7 +439,7 @@ class PresenceRouterTestCase(FederatingHomeserverTestCase):
for edu in edus: for edu in edus:
# Make sure we're only checking presence-type EDUs # Make sure we're only checking presence-type EDUs
if edu["edu_type"] != EduTypes.Presence: if edu["edu_type"] != EduTypes.PRESENCE:
continue continue
# EDUs can contain multiple presence updates # EDUs can contain multiple presence updates

View file

@ -19,7 +19,7 @@ from signedjson.types import BaseKey, SigningKey
from twisted.internet import defer from twisted.internet import defer
from synapse.api.constants import RoomEncryptionAlgorithms from synapse.api.constants import EduTypes, RoomEncryptionAlgorithms
from synapse.rest import admin from synapse.rest import admin
from synapse.rest.client import login from synapse.rest.client import login
from synapse.types import JsonDict, ReadReceipt from synapse.types import JsonDict, ReadReceipt
@ -63,7 +63,7 @@ class FederationSenderReceiptsTestCases(HomeserverTestCase):
data["edus"], data["edus"],
[ [
{ {
"edu_type": "m.receipt", "edu_type": EduTypes.RECEIPT,
"content": { "content": {
"room_id": { "room_id": {
"m.read": { "m.read": {
@ -103,7 +103,7 @@ class FederationSenderReceiptsTestCases(HomeserverTestCase):
data["edus"], data["edus"],
[ [
{ {
"edu_type": "m.receipt", "edu_type": EduTypes.RECEIPT,
"content": { "content": {
"room_id": { "room_id": {
"m.read": { "m.read": {
@ -138,7 +138,7 @@ class FederationSenderReceiptsTestCases(HomeserverTestCase):
data["edus"], data["edus"],
[ [
{ {
"edu_type": "m.receipt", "edu_type": EduTypes.RECEIPT,
"content": { "content": {
"room_id": { "room_id": {
"m.read": { "m.read": {
@ -322,8 +322,10 @@ class FederationSenderDevicesTestCases(HomeserverTestCase):
# expect signing key update edu # expect signing key update edu
self.assertEqual(len(self.edus), 2) self.assertEqual(len(self.edus), 2)
self.assertEqual(self.edus.pop(0)["edu_type"], "m.signing_key_update") self.assertEqual(self.edus.pop(0)["edu_type"], EduTypes.SIGNING_KEY_UPDATE)
self.assertEqual(self.edus.pop(0)["edu_type"], "org.matrix.signing_key_update") self.assertEqual(
self.edus.pop(0)["edu_type"], EduTypes.UNSTABLE_SIGNING_KEY_UPDATE
)
# sign the devices # sign the devices
d1_json = build_device_dict(u1, "D1", device1_signing_key) d1_json = build_device_dict(u1, "D1", device1_signing_key)
@ -348,7 +350,7 @@ class FederationSenderDevicesTestCases(HomeserverTestCase):
self.assertEqual(len(self.edus), 2) self.assertEqual(len(self.edus), 2)
stream_id = None # FIXME: there is a discontinuity in the stream IDs: see #7142 stream_id = None # FIXME: there is a discontinuity in the stream IDs: see #7142
for edu in self.edus: for edu in self.edus:
self.assertEqual(edu["edu_type"], "m.device_list_update") self.assertEqual(edu["edu_type"], EduTypes.DEVICE_LIST_UPDATE)
c = edu["content"] c = edu["content"]
if stream_id is not None: if stream_id is not None:
self.assertEqual(c["prev_id"], [stream_id]) self.assertEqual(c["prev_id"], [stream_id])
@ -388,7 +390,7 @@ class FederationSenderDevicesTestCases(HomeserverTestCase):
# expect three edus, in an unknown order # expect three edus, in an unknown order
self.assertEqual(len(self.edus), 3) self.assertEqual(len(self.edus), 3)
for edu in self.edus: for edu in self.edus:
self.assertEqual(edu["edu_type"], "m.device_list_update") self.assertEqual(edu["edu_type"], EduTypes.DEVICE_LIST_UPDATE)
c = edu["content"] c = edu["content"]
self.assertGreaterEqual( self.assertGreaterEqual(
c.items(), c.items(),
@ -435,7 +437,7 @@ class FederationSenderDevicesTestCases(HomeserverTestCase):
self.assertEqual(len(self.edus), 3) self.assertEqual(len(self.edus), 3)
stream_id = None stream_id = None
for edu in self.edus: for edu in self.edus:
self.assertEqual(edu["edu_type"], "m.device_list_update") self.assertEqual(edu["edu_type"], EduTypes.DEVICE_LIST_UPDATE)
c = edu["content"] c = edu["content"]
self.assertEqual(c["prev_id"], [stream_id] if stream_id is not None else []) self.assertEqual(c["prev_id"], [stream_id] if stream_id is not None else [])
if stream_id is not None: if stream_id is not None:
@ -487,7 +489,7 @@ class FederationSenderDevicesTestCases(HomeserverTestCase):
# there should be a single update for this user. # there should be a single update for this user.
self.assertEqual(len(self.edus), 1) self.assertEqual(len(self.edus), 1)
edu = self.edus.pop(0) edu = self.edus.pop(0)
self.assertEqual(edu["edu_type"], "m.device_list_update") self.assertEqual(edu["edu_type"], EduTypes.DEVICE_LIST_UPDATE)
c = edu["content"] c = edu["content"]
# synapse uses an empty prev_id list to indicate "needs a full resync". # synapse uses an empty prev_id list to indicate "needs a full resync".
@ -544,7 +546,7 @@ class FederationSenderDevicesTestCases(HomeserverTestCase):
# ... and we should get a single update for this user. # ... and we should get a single update for this user.
self.assertEqual(len(self.edus), 1) self.assertEqual(len(self.edus), 1)
edu = self.edus.pop(0) edu = self.edus.pop(0)
self.assertEqual(edu["edu_type"], "m.device_list_update") self.assertEqual(edu["edu_type"], EduTypes.DEVICE_LIST_UPDATE)
c = edu["content"] c = edu["content"]
# synapse uses an empty prev_id list to indicate "needs a full resync". # synapse uses an empty prev_id list to indicate "needs a full resync".
@ -560,7 +562,7 @@ class FederationSenderDevicesTestCases(HomeserverTestCase):
"""Check that the given EDU is an update for the given device """Check that the given EDU is an update for the given device
Returns the stream_id. Returns the stream_id.
""" """
self.assertEqual(edu["edu_type"], "m.device_list_update") self.assertEqual(edu["edu_type"], EduTypes.DEVICE_LIST_UPDATE)
content = edu["content"] content = edu["content"]
expected = { expected = {

View file

@ -12,6 +12,8 @@
# 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 synapse.api.constants import EduTypes
from tests import unittest from tests import unittest
from tests.unittest import DEBUG, override_config from tests.unittest import DEBUG, override_config
@ -50,7 +52,7 @@ class RoomDirectoryFederationTests(unittest.FederatingHomeserverTestCase):
"/_matrix/federation/v1/send/txn_id_1234/", "/_matrix/federation/v1/send/txn_id_1234/",
content={ content={
"edus": [ "edus": [
{"edu_type": "m.device_list_update", "content": {"foo": "bar"}} {"edu_type": EduTypes.DEVICE_LIST_UPDATE, "content": {"foo": "bar"}}
], ],
"pdus": [], "pdus": [],
}, },

View file

@ -22,6 +22,7 @@ from twisted.test.proto_helpers import MemoryReactor
import synapse.rest.admin import synapse.rest.admin
import synapse.storage import synapse.storage
from synapse.api.constants import EduTypes
from synapse.appservice import ( from synapse.appservice import (
ApplicationService, ApplicationService,
TransactionOneTimeKeyCounts, TransactionOneTimeKeyCounts,
@ -476,7 +477,7 @@ class ApplicationServicesHandlerSendEventsTestCase(unittest.HomeserverTestCase):
# Check that the ephemeral event is a read receipt with the expected structure # Check that the ephemeral event is a read receipt with the expected structure
latest_read_receipt = all_ephemeral_events[-1] latest_read_receipt = all_ephemeral_events[-1]
self.assertEqual(latest_read_receipt["type"], "m.receipt") self.assertEqual(latest_read_receipt["type"], EduTypes.RECEIPT)
event_id = list(latest_read_receipt["content"].keys())[0] event_id = list(latest_read_receipt["content"].keys())[0]
self.assertEqual( self.assertEqual(

View file

@ -15,7 +15,7 @@
from copy import deepcopy from copy import deepcopy
from typing import List from typing import List
from synapse.api.constants import ReceiptTypes from synapse.api.constants import EduTypes, ReceiptTypes
from synapse.types import JsonDict from synapse.types import JsonDict
from tests import unittest from tests import unittest
@ -39,7 +39,7 @@ class ReceiptsTestCase(unittest.HomeserverTestCase):
} }
}, },
"room_id": "!jEsUZKDJdhlrceRyVU:example.org", "room_id": "!jEsUZKDJdhlrceRyVU:example.org",
"type": "m.receipt", "type": EduTypes.RECEIPT,
} }
], ],
[], [],
@ -64,7 +64,7 @@ class ReceiptsTestCase(unittest.HomeserverTestCase):
}, },
}, },
"room_id": "!jEsUZKDJdhlrceRyVU:example.org", "room_id": "!jEsUZKDJdhlrceRyVU:example.org",
"type": "m.receipt", "type": EduTypes.RECEIPT,
} }
], ],
[ [
@ -79,7 +79,7 @@ class ReceiptsTestCase(unittest.HomeserverTestCase):
} }
}, },
"room_id": "!jEsUZKDJdhlrceRyVU:example.org", "room_id": "!jEsUZKDJdhlrceRyVU:example.org",
"type": "m.receipt", "type": EduTypes.RECEIPT,
} }
], ],
) )
@ -105,7 +105,7 @@ class ReceiptsTestCase(unittest.HomeserverTestCase):
}, },
}, },
"room_id": "!jEsUZKDJdhlrceRyVU:example.org", "room_id": "!jEsUZKDJdhlrceRyVU:example.org",
"type": "m.receipt", "type": EduTypes.RECEIPT,
} }
], ],
[ [
@ -120,7 +120,7 @@ class ReceiptsTestCase(unittest.HomeserverTestCase):
} }
}, },
"room_id": "!jEsUZKDJdhlrceRyVU:example.org", "room_id": "!jEsUZKDJdhlrceRyVU:example.org",
"type": "m.receipt", "type": EduTypes.RECEIPT,
} }
], ],
) )
@ -140,7 +140,7 @@ class ReceiptsTestCase(unittest.HomeserverTestCase):
}, },
}, },
"room_id": "!jEsUZKDJdhlrceRyVU:example.org", "room_id": "!jEsUZKDJdhlrceRyVU:example.org",
"type": "m.receipt", "type": EduTypes.RECEIPT,
} }
], ],
[ [
@ -155,7 +155,7 @@ class ReceiptsTestCase(unittest.HomeserverTestCase):
}, },
}, },
"room_id": "!jEsUZKDJdhlrceRyVU:example.org", "room_id": "!jEsUZKDJdhlrceRyVU:example.org",
"type": "m.receipt", "type": EduTypes.RECEIPT,
} }
], ],
) )
@ -174,7 +174,7 @@ class ReceiptsTestCase(unittest.HomeserverTestCase):
}, },
}, },
"room_id": "!jEsUZKDJdhlrceRyVU:example.org", "room_id": "!jEsUZKDJdhlrceRyVU:example.org",
"type": "m.receipt", "type": EduTypes.RECEIPT,
}, },
{ {
"content": { "content": {
@ -187,7 +187,7 @@ class ReceiptsTestCase(unittest.HomeserverTestCase):
}, },
}, },
"room_id": "!jEsUZKDJdhlrceRyVU:example.org", "room_id": "!jEsUZKDJdhlrceRyVU:example.org",
"type": "m.receipt", "type": EduTypes.RECEIPT,
}, },
], ],
[ [
@ -202,7 +202,7 @@ class ReceiptsTestCase(unittest.HomeserverTestCase):
} }
}, },
"room_id": "!jEsUZKDJdhlrceRyVU:example.org", "room_id": "!jEsUZKDJdhlrceRyVU:example.org",
"type": "m.receipt", "type": EduTypes.RECEIPT,
} }
], ],
) )
@ -224,7 +224,7 @@ class ReceiptsTestCase(unittest.HomeserverTestCase):
}, },
}, },
"room_id": "!jEsUZKDJdhlrceRyVU:example.org", "room_id": "!jEsUZKDJdhlrceRyVU:example.org",
"type": "m.receipt", "type": EduTypes.RECEIPT,
}, },
], ],
[ [
@ -237,7 +237,7 @@ class ReceiptsTestCase(unittest.HomeserverTestCase):
}, },
}, },
"room_id": "!jEsUZKDJdhlrceRyVU:example.org", "room_id": "!jEsUZKDJdhlrceRyVU:example.org",
"type": "m.receipt", "type": EduTypes.RECEIPT,
}, },
], ],
) )
@ -266,7 +266,7 @@ class ReceiptsTestCase(unittest.HomeserverTestCase):
}, },
}, },
"room_id": "!jEsUZKDJdhlrceRyVU:example.org", "room_id": "!jEsUZKDJdhlrceRyVU:example.org",
"type": "m.receipt", "type": EduTypes.RECEIPT,
} }
], ],
[ [
@ -291,7 +291,7 @@ class ReceiptsTestCase(unittest.HomeserverTestCase):
} }
}, },
"room_id": "!jEsUZKDJdhlrceRyVU:example.org", "room_id": "!jEsUZKDJdhlrceRyVU:example.org",
"type": "m.receipt", "type": EduTypes.RECEIPT,
} }
], ],
) )
@ -310,7 +310,7 @@ class ReceiptsTestCase(unittest.HomeserverTestCase):
} }
}, },
"room_id": "!jEsUZKDJdhlrceRyVU:example.org", "room_id": "!jEsUZKDJdhlrceRyVU:example.org",
"type": "m.receipt", "type": EduTypes.RECEIPT,
} }
] ]
original_events = deepcopy(events) original_events = deepcopy(events)

View file

@ -21,6 +21,7 @@ from twisted.internet import defer
from twisted.test.proto_helpers import MemoryReactor from twisted.test.proto_helpers import MemoryReactor
from twisted.web.resource import Resource from twisted.web.resource import Resource
from synapse.api.constants import EduTypes
from synapse.api.errors import AuthError from synapse.api.errors import AuthError
from synapse.federation.transport.server import TransportLayerServer from synapse.federation.transport.server import TransportLayerServer
from synapse.server import HomeServer from synapse.server import HomeServer
@ -184,7 +185,7 @@ class TypingNotificationsTestCase(unittest.HomeserverTestCase):
events[0], events[0],
[ [
{ {
"type": "m.typing", "type": EduTypes.TYPING,
"room_id": ROOM_ID, "room_id": ROOM_ID,
"content": {"user_ids": [U_APPLE.to_string()]}, "content": {"user_ids": [U_APPLE.to_string()]},
} }
@ -209,7 +210,7 @@ class TypingNotificationsTestCase(unittest.HomeserverTestCase):
"farm", "farm",
path="/_matrix/federation/v1/send/1000000", path="/_matrix/federation/v1/send/1000000",
data=_expect_edu_transaction( data=_expect_edu_transaction(
"m.typing", EduTypes.TYPING,
content={ content={
"room_id": ROOM_ID, "room_id": ROOM_ID,
"user_id": U_APPLE.to_string(), "user_id": U_APPLE.to_string(),
@ -231,7 +232,7 @@ class TypingNotificationsTestCase(unittest.HomeserverTestCase):
"PUT", "PUT",
"/_matrix/federation/v1/send/1000000", "/_matrix/federation/v1/send/1000000",
_make_edu_transaction_json( _make_edu_transaction_json(
"m.typing", EduTypes.TYPING,
content={ content={
"room_id": ROOM_ID, "room_id": ROOM_ID,
"user_id": U_ONION.to_string(), "user_id": U_ONION.to_string(),
@ -254,7 +255,7 @@ class TypingNotificationsTestCase(unittest.HomeserverTestCase):
events[0], events[0],
[ [
{ {
"type": "m.typing", "type": EduTypes.TYPING,
"room_id": ROOM_ID, "room_id": ROOM_ID,
"content": {"user_ids": [U_ONION.to_string()]}, "content": {"user_ids": [U_ONION.to_string()]},
} }
@ -270,7 +271,7 @@ class TypingNotificationsTestCase(unittest.HomeserverTestCase):
"PUT", "PUT",
"/_matrix/federation/v1/send/1000000", "/_matrix/federation/v1/send/1000000",
_make_edu_transaction_json( _make_edu_transaction_json(
"m.typing", EduTypes.TYPING,
content={ content={
"room_id": OTHER_ROOM_ID, "room_id": OTHER_ROOM_ID,
"user_id": U_ONION.to_string(), "user_id": U_ONION.to_string(),
@ -324,7 +325,7 @@ class TypingNotificationsTestCase(unittest.HomeserverTestCase):
"farm", "farm",
path="/_matrix/federation/v1/send/1000000", path="/_matrix/federation/v1/send/1000000",
data=_expect_edu_transaction( data=_expect_edu_transaction(
"m.typing", EduTypes.TYPING,
content={ content={
"room_id": ROOM_ID, "room_id": ROOM_ID,
"user_id": U_APPLE.to_string(), "user_id": U_APPLE.to_string(),
@ -345,7 +346,13 @@ class TypingNotificationsTestCase(unittest.HomeserverTestCase):
) )
self.assertEqual( self.assertEqual(
events[0], events[0],
[{"type": "m.typing", "room_id": ROOM_ID, "content": {"user_ids": []}}], [
{
"type": EduTypes.TYPING,
"room_id": ROOM_ID,
"content": {"user_ids": []},
}
],
) )
def test_typing_timeout(self) -> None: def test_typing_timeout(self) -> None:
@ -379,7 +386,7 @@ class TypingNotificationsTestCase(unittest.HomeserverTestCase):
events[0], events[0],
[ [
{ {
"type": "m.typing", "type": EduTypes.TYPING,
"room_id": ROOM_ID, "room_id": ROOM_ID,
"content": {"user_ids": [U_APPLE.to_string()]}, "content": {"user_ids": [U_APPLE.to_string()]},
} }
@ -402,7 +409,13 @@ class TypingNotificationsTestCase(unittest.HomeserverTestCase):
) )
self.assertEqual( self.assertEqual(
events[0], events[0],
[{"type": "m.typing", "room_id": ROOM_ID, "content": {"user_ids": []}}], [
{
"type": EduTypes.TYPING,
"room_id": ROOM_ID,
"content": {"user_ids": []},
}
],
) )
# SYN-230 - see if we can still set after timeout # SYN-230 - see if we can still set after timeout
@ -433,7 +446,7 @@ class TypingNotificationsTestCase(unittest.HomeserverTestCase):
events[0], events[0],
[ [
{ {
"type": "m.typing", "type": EduTypes.TYPING,
"room_id": ROOM_ID, "room_id": ROOM_ID,
"content": {"user_ids": [U_APPLE.to_string()]}, "content": {"user_ids": [U_APPLE.to_string()]},
} }

View file

@ -399,7 +399,7 @@ class ModuleApiTestCase(HomeserverTestCase):
for edu in edus: for edu in edus:
# Make sure we're only checking presence-type EDUs # Make sure we're only checking presence-type EDUs
if edu["edu_type"] != EduTypes.Presence: if edu["edu_type"] != EduTypes.PRESENCE:
continue continue
# EDUs can contain multiple presence updates # EDUs can contain multiple presence updates

View file

@ -19,6 +19,7 @@ from unittest.mock import Mock
from twisted.test.proto_helpers import MemoryReactor from twisted.test.proto_helpers import MemoryReactor
import synapse.rest.admin import synapse.rest.admin
from synapse.api.constants import EduTypes
from synapse.rest.client import events, login, room from synapse.rest.client import events, login, room
from synapse.server import HomeServer from synapse.server import HomeServer
from synapse.util import Clock from synapse.util import Clock
@ -103,7 +104,7 @@ class EventStreamPermissionsTestCase(unittest.HomeserverTestCase):
c c
for c in channel.json_body["chunk"] for c in channel.json_body["chunk"]
if not ( if not (
c.get("type") == "m.presence" c.get("type") == EduTypes.PRESENCE
and c["content"].get("user_id") == self.user_id and c["content"].get("user_id") == self.user_id
) )
] ]

View file

@ -26,6 +26,7 @@ from twisted.test.proto_helpers import MemoryReactor
import synapse.rest.admin import synapse.rest.admin
from synapse.api.constants import ( from synapse.api.constants import (
EduTypes,
EventContentFields, EventContentFields,
EventTypes, EventTypes,
Membership, Membership,
@ -1412,7 +1413,7 @@ class RoomInitialSyncTestCase(RoomBase):
e["content"]["user_id"]: e for e in channel.json_body["presence"] e["content"]["user_id"]: e for e in channel.json_body["presence"]
} }
self.assertTrue(self.user_id in presence_by_user) self.assertTrue(self.user_id in presence_by_user)
self.assertEqual("m.presence", presence_by_user[self.user_id]["type"]) self.assertEqual(EduTypes.PRESENCE, presence_by_user[self.user_id]["type"])
class RoomMessageListTestCase(RoomBase): class RoomMessageListTestCase(RoomBase):

View file

@ -12,6 +12,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.
from synapse.api.constants import EduTypes
from synapse.rest import admin from synapse.rest import admin
from synapse.rest.client import login, sendtodevice, sync from synapse.rest.client import login, sendtodevice, sync
@ -139,7 +140,7 @@ class SendToDeviceTestCase(HomeserverTestCase):
for i in range(3): for i in range(3):
self.get_success( self.get_success(
federation_registry.on_edu( federation_registry.on_edu(
"m.direct_to_device", EduTypes.DIRECT_TO_DEVICE,
"remote_server", "remote_server",
{ {
"sender": "@user:remote_server", "sender": "@user:remote_server",
@ -172,7 +173,7 @@ class SendToDeviceTestCase(HomeserverTestCase):
# and we can send more messages # and we can send more messages
self.get_success( self.get_success(
federation_registry.on_edu( federation_registry.on_edu(
"m.direct_to_device", EduTypes.DIRECT_TO_DEVICE,
"remote_server", "remote_server",
{ {
"sender": "@user:remote_server", "sender": "@user:remote_server",

View file

@ -17,7 +17,7 @@ from unittest.mock import Mock, patch
from twisted.test.proto_helpers import MemoryReactor from twisted.test.proto_helpers import MemoryReactor
import synapse.rest.admin import synapse.rest.admin
from synapse.api.constants import EventTypes from synapse.api.constants import EduTypes, EventTypes
from synapse.rest.client import ( from synapse.rest.client import (
directory, directory,
login, login,
@ -226,7 +226,7 @@ class RoomTestCase(_ShadowBannedBase):
events[0], events[0],
[ [
{ {
"type": "m.typing", "type": EduTypes.TYPING,
"room_id": room_id, "room_id": room_id,
"content": {"user_ids": [self.other_user_id]}, "content": {"user_ids": [self.other_user_id]},
} }

View file

@ -22,6 +22,7 @@ from twisted.test.proto_helpers import MemoryReactor
import synapse.rest.admin import synapse.rest.admin
from synapse.api.constants import ( from synapse.api.constants import (
EduTypes,
EventContentFields, EventContentFields,
EventTypes, EventTypes,
ReceiptTypes, ReceiptTypes,
@ -504,7 +505,7 @@ class ReadReceiptsTestCase(unittest.HomeserverTestCase):
# Checks if event is a read receipt # Checks if event is a read receipt
def is_read_receipt(event: JsonDict) -> bool: def is_read_receipt(event: JsonDict) -> bool:
return event["type"] == "m.receipt" return event["type"] == EduTypes.RECEIPT
# Sync # Sync
channel = self.make_request( channel = self.make_request(

View file

@ -17,6 +17,7 @@
from twisted.test.proto_helpers import MemoryReactor from twisted.test.proto_helpers import MemoryReactor
from synapse.api.constants import EduTypes
from synapse.rest.client import room from synapse.rest.client import room
from synapse.server import HomeServer from synapse.server import HomeServer
from synapse.types import UserID from synapse.types import UserID
@ -67,7 +68,7 @@ class RoomTypingTestCase(unittest.HomeserverTestCase):
events[0], events[0],
[ [
{ {
"type": "m.typing", "type": EduTypes.TYPING,
"room_id": self.room_id, "room_id": self.room_id,
"content": {"user_ids": [self.user_id]}, "content": {"user_ids": [self.user_id]},
} }

View file

@ -13,6 +13,7 @@
# limitations under the License. # limitations under the License.
import synapse.api.errors import synapse.api.errors
from synapse.api.constants import EduTypes
from tests.unittest import HomeserverTestCase from tests.unittest import HomeserverTestCase
@ -266,10 +267,12 @@ class DeviceStoreTestCase(HomeserverTestCase):
# (This is a temporary arrangement for backwards compatibility!) # (This is a temporary arrangement for backwards compatibility!)
self.assertEqual(len(device_updates), 2, device_updates) self.assertEqual(len(device_updates), 2, device_updates)
self.assertEqual( self.assertEqual(
device_updates[0][0], "m.signing_key_update", device_updates[0] device_updates[0][0], EduTypes.SIGNING_KEY_UPDATE, device_updates[0]
) )
self.assertEqual( self.assertEqual(
device_updates[1][0], "org.matrix.signing_key_update", device_updates[1] device_updates[1][0],
EduTypes.UNSTABLE_SIGNING_KEY_UPDATE,
device_updates[1],
) )
# Check there are no more device updates left. # Check there are no more device updates left.