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

Stop sub-classing object (#8249)

This commit is contained in:
Patrick Cloke 2020-09-04 06:54:56 -04:00 committed by GitHub
parent 9f8abdcc38
commit c619253db8
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
168 changed files with 293 additions and 292 deletions

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

@ -0,0 +1 @@
Stop sub-classing from object.

View file

@ -24,7 +24,7 @@ from twisted.web.client import Agent, readBody
from twisted.web.http_headers import Headers from twisted.web.http_headers import Headers
class HttpClient(object): class HttpClient:
""" Interface for talking json over http """ Interface for talking json over http
""" """
@ -169,7 +169,7 @@ class TwistedHttpClient(HttpClient):
return d return d
class _RawProducer(object): class _RawProducer:
def __init__(self, data): def __init__(self, data):
self.data = data self.data = data
self.body = data self.body = data
@ -186,7 +186,7 @@ class _RawProducer(object):
pass pass
class _JsonProducer(object): class _JsonProducer:
""" Used by the twisted http client to create the HTTP body from json """ Used by the twisted http client to create the HTTP body from json
""" """

View file

@ -141,7 +141,7 @@ class CursesStdIO:
curses.endwin() curses.endwin()
class Callback(object): class Callback:
def __init__(self, stdio): def __init__(self, stdio):
self.stdio = stdio self.stdio = stdio

View file

@ -55,7 +55,7 @@ def excpetion_errback(failure):
logging.exception(failure) logging.exception(failure)
class InputOutput(object): class InputOutput:
""" This is responsible for basic I/O so that a user can interact with """ This is responsible for basic I/O so that a user can interact with
the example app. the example app.
""" """
@ -132,7 +132,7 @@ class IOLoggerHandler(logging.Handler):
self.io.print_log(msg) self.io.print_log(msg)
class Room(object): class Room:
""" Used to store (in memory) the current membership state of a room, and """ Used to store (in memory) the current membership state of a room, and
which home servers we should send PDUs associated with the room to. which home servers we should send PDUs associated with the room to.
""" """

View file

@ -15,7 +15,7 @@ from synapse.storage.pdu import PduStore
from synapse.storage.signatures import SignatureStore from synapse.storage.signatures import SignatureStore
class Store(object): class Store:
_get_pdu_tuples = PduStore.__dict__["_get_pdu_tuples"] _get_pdu_tuples = PduStore.__dict__["_get_pdu_tuples"]
_get_pdu_content_hashes_txn = SignatureStore.__dict__["_get_pdu_content_hashes_txn"] _get_pdu_content_hashes_txn = SignatureStore.__dict__["_get_pdu_content_hashes_txn"]
_get_prev_pdu_hashes_txn = SignatureStore.__dict__["_get_prev_pdu_hashes_txn"] _get_prev_pdu_hashes_txn = SignatureStore.__dict__["_get_prev_pdu_hashes_txn"]

View file

@ -58,7 +58,7 @@ class _InvalidMacaroonException(Exception):
pass pass
class Auth(object): class Auth:
""" """
FIXME: This class contains a mix of functions for authenticating users FIXME: This class contains a mix of functions for authenticating users
of our client-server API and authenticating events added to room graphs. of our client-server API and authenticating events added to room graphs.

View file

@ -22,7 +22,7 @@ from synapse.config.server import is_threepid_reserved
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
class AuthBlocking(object): class AuthBlocking:
def __init__(self, hs): def __init__(self, hs):
self.store = hs.get_datastore() self.store = hs.get_datastore()

View file

@ -28,7 +28,7 @@ MAX_ALIAS_LENGTH = 255
MAX_USERID_LENGTH = 255 MAX_USERID_LENGTH = 255
class Membership(object): class Membership:
"""Represents the membership states of a user in a room.""" """Represents the membership states of a user in a room."""
@ -40,7 +40,7 @@ class Membership(object):
LIST = (INVITE, JOIN, KNOCK, LEAVE, BAN) LIST = (INVITE, JOIN, KNOCK, LEAVE, BAN)
class PresenceState(object): class PresenceState:
"""Represents the presence state of a user.""" """Represents the presence state of a user."""
OFFLINE = "offline" OFFLINE = "offline"
@ -48,14 +48,14 @@ class PresenceState(object):
ONLINE = "online" ONLINE = "online"
class JoinRules(object): class JoinRules:
PUBLIC = "public" PUBLIC = "public"
KNOCK = "knock" KNOCK = "knock"
INVITE = "invite" INVITE = "invite"
PRIVATE = "private" PRIVATE = "private"
class LoginType(object): class LoginType:
PASSWORD = "m.login.password" PASSWORD = "m.login.password"
EMAIL_IDENTITY = "m.login.email.identity" EMAIL_IDENTITY = "m.login.email.identity"
MSISDN = "m.login.msisdn" MSISDN = "m.login.msisdn"
@ -65,7 +65,7 @@ class LoginType(object):
DUMMY = "m.login.dummy" DUMMY = "m.login.dummy"
class EventTypes(object): class EventTypes:
Member = "m.room.member" Member = "m.room.member"
Create = "m.room.create" Create = "m.room.create"
Tombstone = "m.room.tombstone" Tombstone = "m.room.tombstone"
@ -96,17 +96,17 @@ class EventTypes(object):
Presence = "m.presence" Presence = "m.presence"
class RejectedReason(object): class RejectedReason:
AUTH_ERROR = "auth_error" AUTH_ERROR = "auth_error"
class RoomCreationPreset(object): class RoomCreationPreset:
PRIVATE_CHAT = "private_chat" PRIVATE_CHAT = "private_chat"
PUBLIC_CHAT = "public_chat" PUBLIC_CHAT = "public_chat"
TRUSTED_PRIVATE_CHAT = "trusted_private_chat" TRUSTED_PRIVATE_CHAT = "trusted_private_chat"
class ThirdPartyEntityKind(object): class ThirdPartyEntityKind:
USER = "user" USER = "user"
LOCATION = "location" LOCATION = "location"
@ -115,7 +115,7 @@ ServerNoticeMsgType = "m.server_notice"
ServerNoticeLimitReached = "m.server_notice.usage_limit_reached" ServerNoticeLimitReached = "m.server_notice.usage_limit_reached"
class UserTypes(object): class UserTypes:
"""Allows for user type specific behaviour. With the benefit of hindsight """Allows for user type specific behaviour. With the benefit of hindsight
'admin' and 'guest' users should also be UserTypes. Normal users are type None 'admin' and 'guest' users should also be UserTypes. Normal users are type None
""" """
@ -125,7 +125,7 @@ class UserTypes(object):
ALL_USER_TYPES = (SUPPORT, BOT) ALL_USER_TYPES = (SUPPORT, BOT)
class RelationTypes(object): class RelationTypes:
"""The types of relations known to this server. """The types of relations known to this server.
""" """
@ -134,14 +134,14 @@ class RelationTypes(object):
REFERENCE = "m.reference" REFERENCE = "m.reference"
class LimitBlockingTypes(object): class LimitBlockingTypes:
"""Reasons that a server may be blocked""" """Reasons that a server may be blocked"""
MONTHLY_ACTIVE_USER = "monthly_active_user" MONTHLY_ACTIVE_USER = "monthly_active_user"
HS_DISABLED = "hs_disabled" HS_DISABLED = "hs_disabled"
class EventContentFields(object): class EventContentFields:
"""Fields found in events' content, regardless of type.""" """Fields found in events' content, regardless of type."""
# Labels for the event, cf https://github.com/matrix-org/matrix-doc/pull/2326 # Labels for the event, cf https://github.com/matrix-org/matrix-doc/pull/2326
@ -152,6 +152,6 @@ class EventContentFields(object):
SELF_DESTRUCT_AFTER = "org.matrix.self_destruct_after" SELF_DESTRUCT_AFTER = "org.matrix.self_destruct_after"
class RoomEncryptionAlgorithms(object): class RoomEncryptionAlgorithms:
MEGOLM_V1_AES_SHA2 = "m.megolm.v1.aes-sha2" MEGOLM_V1_AES_SHA2 = "m.megolm.v1.aes-sha2"
DEFAULT = MEGOLM_V1_AES_SHA2 DEFAULT = MEGOLM_V1_AES_SHA2

View file

@ -31,7 +31,7 @@ if typing.TYPE_CHECKING:
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
class Codes(object): class Codes:
UNRECOGNIZED = "M_UNRECOGNIZED" UNRECOGNIZED = "M_UNRECOGNIZED"
UNAUTHORIZED = "M_UNAUTHORIZED" UNAUTHORIZED = "M_UNAUTHORIZED"
FORBIDDEN = "M_FORBIDDEN" FORBIDDEN = "M_FORBIDDEN"

View file

@ -130,7 +130,7 @@ def matrix_user_id_validator(user_id_str):
return UserID.from_string(user_id_str) return UserID.from_string(user_id_str)
class Filtering(object): class Filtering:
def __init__(self, hs): def __init__(self, hs):
super(Filtering, self).__init__() super(Filtering, self).__init__()
self.store = hs.get_datastore() self.store = hs.get_datastore()
@ -168,7 +168,7 @@ class Filtering(object):
raise SynapseError(400, str(e)) raise SynapseError(400, str(e))
class FilterCollection(object): class FilterCollection:
def __init__(self, filter_json): def __init__(self, filter_json):
self._filter_json = filter_json self._filter_json = filter_json
@ -249,7 +249,7 @@ class FilterCollection(object):
) )
class Filter(object): class Filter:
def __init__(self, filter_json): def __init__(self, filter_json):
self.filter_json = filter_json self.filter_json = filter_json

View file

@ -21,7 +21,7 @@ from synapse.types import Requester
from synapse.util import Clock from synapse.util import Clock
class Ratelimiter(object): class Ratelimiter:
""" """
Ratelimit actions marked by arbitrary keys. Ratelimit actions marked by arbitrary keys.

View file

@ -18,7 +18,7 @@ from typing import Dict
import attr import attr
class EventFormatVersions(object): class EventFormatVersions:
"""This is an internal enum for tracking the version of the event format, """This is an internal enum for tracking the version of the event format,
independently from the room version. independently from the room version.
""" """
@ -35,20 +35,20 @@ KNOWN_EVENT_FORMAT_VERSIONS = {
} }
class StateResolutionVersions(object): class StateResolutionVersions:
"""Enum to identify the state resolution algorithms""" """Enum to identify the state resolution algorithms"""
V1 = 1 # room v1 state res V1 = 1 # room v1 state res
V2 = 2 # MSC1442 state res: room v2 and later V2 = 2 # MSC1442 state res: room v2 and later
class RoomDisposition(object): class RoomDisposition:
STABLE = "stable" STABLE = "stable"
UNSTABLE = "unstable" UNSTABLE = "unstable"
@attr.s(slots=True, frozen=True) @attr.s(slots=True, frozen=True)
class RoomVersion(object): class RoomVersion:
"""An object which describes the unique attributes of a room version.""" """An object which describes the unique attributes of a room version."""
identifier = attr.ib() # str; the identifier for this version identifier = attr.ib() # str; the identifier for this version
@ -69,7 +69,7 @@ class RoomVersion(object):
limit_notifications_power_levels = attr.ib(type=bool) limit_notifications_power_levels = attr.ib(type=bool)
class RoomVersions(object): class RoomVersions:
V1 = RoomVersion( V1 = RoomVersion(
"1", "1",
RoomDisposition.STABLE, RoomDisposition.STABLE,

View file

@ -33,7 +33,7 @@ MEDIA_PREFIX = "/_matrix/media/r0"
LEGACY_MEDIA_PREFIX = "/_matrix/media/v1" LEGACY_MEDIA_PREFIX = "/_matrix/media/v1"
class ConsentURIBuilder(object): class ConsentURIBuilder:
def __init__(self, hs_config): def __init__(self, hs_config):
""" """
Args: Args:

View file

@ -349,7 +349,7 @@ def install_dns_limiter(reactor, max_dns_requests_in_flight=100):
reactor.installNameResolver(new_resolver) reactor.installNameResolver(new_resolver)
class _LimitedHostnameResolver(object): class _LimitedHostnameResolver:
"""Wraps a IHostnameResolver, limiting the number of in-flight DNS lookups. """Wraps a IHostnameResolver, limiting the number of in-flight DNS lookups.
""" """
@ -409,7 +409,7 @@ class _LimitedHostnameResolver(object):
yield deferred yield deferred
class _DeferredResolutionReceiver(object): class _DeferredResolutionReceiver:
"""Wraps a IResolutionReceiver and simply resolves the given deferred when """Wraps a IResolutionReceiver and simply resolves the given deferred when
resolution is complete resolution is complete
""" """

View file

@ -745,7 +745,7 @@ class GenericWorkerReplicationHandler(ReplicationDataHandler):
self.send_handler.wake_destination(server) self.send_handler.wake_destination(server)
class FederationSenderHandler(object): class FederationSenderHandler:
"""Processes the fedration replication stream """Processes the fedration replication stream
This class is only instantiate on the worker responsible for sending outbound This class is only instantiate on the worker responsible for sending outbound

View file

@ -27,12 +27,12 @@ if TYPE_CHECKING:
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
class ApplicationServiceState(object): class ApplicationServiceState:
DOWN = "down" DOWN = "down"
UP = "up" UP = "up"
class AppServiceTransaction(object): class AppServiceTransaction:
"""Represents an application service transaction.""" """Represents an application service transaction."""
def __init__(self, service, id, events): def __init__(self, service, id, events):
@ -64,7 +64,7 @@ class AppServiceTransaction(object):
await store.complete_appservice_txn(service=self.service, txn_id=self.id) await store.complete_appservice_txn(service=self.service, txn_id=self.id)
class ApplicationService(object): class ApplicationService:
"""Defines an application service. This definition is mostly what is """Defines an application service. This definition is mostly what is
provided to the /register AS API. provided to the /register AS API.

View file

@ -57,7 +57,7 @@ from synapse.metrics.background_process_metrics import run_as_background_process
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
class ApplicationServiceScheduler(object): class ApplicationServiceScheduler:
""" Public facing API for this module. Does the required DI to tie the """ Public facing API for this module. Does the required DI to tie the
components together. This also serves as the "event_pool", which in this components together. This also serves as the "event_pool", which in this
case is a simple array. case is a simple array.
@ -86,7 +86,7 @@ class ApplicationServiceScheduler(object):
self.queuer.enqueue(service, event) self.queuer.enqueue(service, event)
class _ServiceQueuer(object): class _ServiceQueuer:
"""Queue of events waiting to be sent to appservices. """Queue of events waiting to be sent to appservices.
Groups events into transactions per-appservice, and sends them on to the Groups events into transactions per-appservice, and sends them on to the
@ -133,7 +133,7 @@ class _ServiceQueuer(object):
self.requests_in_flight.discard(service.id) self.requests_in_flight.discard(service.id)
class _TransactionController(object): class _TransactionController:
"""Transaction manager. """Transaction manager.
Builds AppServiceTransactions and runs their lifecycle. Also starts a Recoverer Builds AppServiceTransactions and runs their lifecycle. Also starts a Recoverer
@ -209,7 +209,7 @@ class _TransactionController(object):
return state == ApplicationServiceState.UP or state is None return state == ApplicationServiceState.UP or state is None
class _Recoverer(object): class _Recoverer:
"""Manages retries and backoff for a DOWN appservice. """Manages retries and backoff for a DOWN appservice.
We have one of these for each appservice which is currently considered DOWN. We have one of these for each appservice which is currently considered DOWN.

View file

@ -88,7 +88,7 @@ def path_exists(file_path):
return False return False
class Config(object): class Config:
""" """
A configuration section, containing configuration keys and values. A configuration section, containing configuration keys and values.
@ -283,7 +283,7 @@ def _create_mxc_to_http_filter(public_baseurl: str) -> Callable:
return mxc_to_http_filter return mxc_to_http_filter
class RootConfig(object): class RootConfig:
""" """
Holder of an application's configuration. Holder of an application's configuration.

View file

@ -33,7 +33,7 @@ _DEFAULT_FACTOR_SIZE = 0.5
_DEFAULT_EVENT_CACHE_SIZE = "10K" _DEFAULT_EVENT_CACHE_SIZE = "10K"
class CacheProperties(object): class CacheProperties:
def __init__(self): def __init__(self):
# The default factor size for all caches # The default factor size for all caches
self.default_factor_size = float( self.default_factor_size = float(

View file

@ -82,7 +82,7 @@ logger = logging.getLogger(__name__)
@attr.s @attr.s
class TrustedKeyServer(object): class TrustedKeyServer:
# string: name of the server. # string: name of the server.
server_name = attr.ib() server_name = attr.ib()

View file

@ -22,7 +22,7 @@ from ._base import Config, ConfigError
@attr.s @attr.s
class MetricsFlags(object): class MetricsFlags:
known_servers = attr.ib(default=False, validator=attr.validators.instance_of(bool)) known_servers = attr.ib(default=False, validator=attr.validators.instance_of(bool))
@classmethod @classmethod

View file

@ -17,7 +17,7 @@ from typing import Dict
from ._base import Config from ._base import Config
class RateLimitConfig(object): class RateLimitConfig:
def __init__( def __init__(
self, self,
config: Dict[str, float], config: Dict[str, float],
@ -27,7 +27,7 @@ class RateLimitConfig(object):
self.burst_count = config.get("burst_count", defaults["burst_count"]) self.burst_count = config.get("burst_count", defaults["burst_count"])
class FederationRateLimitConfig(object): class FederationRateLimitConfig:
_items_and_default = { _items_and_default = {
"window_size": 1000, "window_size": 1000,
"sleep_limit": 10, "sleep_limit": 10,

View file

@ -22,7 +22,7 @@ from ._base import Config, ConfigError
logger = logging.Logger(__name__) logger = logging.Logger(__name__)
class RoomDefaultEncryptionTypes(object): class RoomDefaultEncryptionTypes:
"""Possible values for the encryption_enabled_by_default_for_room_type config option""" """Possible values for the encryption_enabled_by_default_for_room_type config option"""
ALL = "all" ALL = "all"

View file

@ -149,7 +149,7 @@ class RoomDirectoryConfig(Config):
return False return False
class _RoomDirectoryRule(object): class _RoomDirectoryRule:
"""Helper class to test whether a room directory action is allowed, like """Helper class to test whether a room directory action is allowed, like
creating an alias or publishing a room. creating an alias or publishing a room.
""" """

View file

@ -424,7 +424,7 @@ class ServerConfig(Config):
self.gc_thresholds = read_gc_thresholds(config.get("gc_thresholds", None)) self.gc_thresholds = read_gc_thresholds(config.get("gc_thresholds", None))
@attr.s @attr.s
class LimitRemoteRoomsConfig(object): class LimitRemoteRoomsConfig:
enabled = attr.ib( enabled = attr.ib(
validator=attr.validators.instance_of(bool), default=False validator=attr.validators.instance_of(bool), default=False
) )

View file

@ -83,7 +83,7 @@ class ServerContextFactory(ContextFactory):
@implementer(IPolicyForHTTPS) @implementer(IPolicyForHTTPS)
class FederationPolicyForHTTPS(object): class FederationPolicyForHTTPS:
"""Factory for Twisted SSLClientConnectionCreators that are used to make connections """Factory for Twisted SSLClientConnectionCreators that are used to make connections
to remote servers for federation. to remote servers for federation.
@ -152,7 +152,7 @@ class FederationPolicyForHTTPS(object):
@implementer(IPolicyForHTTPS) @implementer(IPolicyForHTTPS)
class RegularPolicyForHTTPS(object): class RegularPolicyForHTTPS:
"""Factory for Twisted SSLClientConnectionCreators that are used to make connections """Factory for Twisted SSLClientConnectionCreators that are used to make connections
to remote servers, for other than federation. to remote servers, for other than federation.
@ -189,7 +189,7 @@ def _context_info_cb(ssl_connection, where, ret):
@implementer(IOpenSSLClientConnectionCreator) @implementer(IOpenSSLClientConnectionCreator)
class SSLClientConnectionCreator(object): class SSLClientConnectionCreator:
"""Creates openssl connection objects for client connections. """Creates openssl connection objects for client connections.
Replaces twisted.internet.ssl.ClientTLSOptions Replaces twisted.internet.ssl.ClientTLSOptions
@ -214,7 +214,7 @@ class SSLClientConnectionCreator(object):
return connection return connection
class ConnectionVerifier(object): class ConnectionVerifier:
"""Set the SNI, and do cert verification """Set the SNI, and do cert verification
This is a thing which is attached to the TLSMemoryBIOProtocol, and is called by This is a thing which is attached to the TLSMemoryBIOProtocol, and is called by

View file

@ -57,7 +57,7 @@ logger = logging.getLogger(__name__)
@attr.s(slots=True, cmp=False) @attr.s(slots=True, cmp=False)
class VerifyJsonRequest(object): class VerifyJsonRequest:
""" """
A request to verify a JSON object. A request to verify a JSON object.
@ -96,7 +96,7 @@ class KeyLookupError(ValueError):
pass pass
class Keyring(object): class Keyring:
def __init__(self, hs, key_fetchers=None): def __init__(self, hs, key_fetchers=None):
self.clock = hs.get_clock() self.clock = hs.get_clock()
@ -420,7 +420,7 @@ class Keyring(object):
remaining_requests.difference_update(completed) remaining_requests.difference_update(completed)
class KeyFetcher(object): class KeyFetcher:
async def get_keys(self, keys_to_fetch): async def get_keys(self, keys_to_fetch):
""" """
Args: Args:
@ -456,7 +456,7 @@ class StoreKeyFetcher(KeyFetcher):
return keys return keys
class BaseV2KeyFetcher(object): class BaseV2KeyFetcher:
def __init__(self, hs): def __init__(self, hs):
self.store = hs.get_datastore() self.store = hs.get_datastore()
self.config = hs.get_config() self.config = hs.get_config()

View file

@ -96,7 +96,7 @@ class DefaultDictProperty(DictProperty):
return instance._dict.get(self.key, self.default) return instance._dict.get(self.key, self.default)
class _EventInternalMetadata(object): class _EventInternalMetadata:
__slots__ = ["_dict"] __slots__ = ["_dict"]
def __init__(self, internal_metadata_dict: JsonDict): def __init__(self, internal_metadata_dict: JsonDict):

View file

@ -36,7 +36,7 @@ from synapse.util.stringutils import random_string
@attr.s(slots=True, cmp=False, frozen=True) @attr.s(slots=True, cmp=False, frozen=True)
class EventBuilder(object): class EventBuilder:
"""A format independent event builder used to build up the event content """A format independent event builder used to build up the event content
before signing the event. before signing the event.
@ -164,7 +164,7 @@ class EventBuilder(object):
) )
class EventBuilderFactory(object): class EventBuilderFactory:
def __init__(self, hs): def __init__(self, hs):
self.clock = hs.get_clock() self.clock = hs.get_clock()
self.hostname = hs.hostname self.hostname = hs.hostname

View file

@ -25,7 +25,7 @@ if MYPY:
import synapse.server import synapse.server
class SpamChecker(object): class SpamChecker:
def __init__(self, hs: "synapse.server.HomeServer"): def __init__(self, hs: "synapse.server.HomeServer"):
self.spam_checkers = [] # type: List[Any] self.spam_checkers = [] # type: List[Any]

View file

@ -18,7 +18,7 @@ from synapse.events.snapshot import EventContext
from synapse.types import Requester from synapse.types import Requester
class ThirdPartyEventRules(object): class ThirdPartyEventRules:
"""Allows server admins to provide a Python module implementing an extra """Allows server admins to provide a Python module implementing an extra
set of rules to apply when processing events. set of rules to apply when processing events.

View file

@ -322,7 +322,7 @@ def serialize_event(
return d return d
class EventClientSerializer(object): class EventClientSerializer:
"""Serializes events that are to be sent to clients. """Serializes events that are to be sent to clients.
This is used for bundling extra information with any events to be sent to This is used for bundling extra information with any events to be sent to

View file

@ -20,7 +20,7 @@ from synapse.events.utils import validate_canonicaljson
from synapse.types import EventID, RoomID, UserID from synapse.types import EventID, RoomID, UserID
class EventValidator(object): class EventValidator:
def validate_new(self, event, config): def validate_new(self, event, config):
"""Validates the event has roughly the right format """Validates the event has roughly the right format

View file

@ -39,7 +39,7 @@ from synapse.types import JsonDict, get_domain_from_id
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
class FederationBase(object): class FederationBase:
def __init__(self, hs): def __init__(self, hs):
self.hs = hs self.hs = hs

View file

@ -785,7 +785,7 @@ def _acl_entry_matches(server_name: str, acl_entry: str) -> Match:
return regex.match(server_name) return regex.match(server_name)
class FederationHandlerRegistry(object): class FederationHandlerRegistry:
"""Allows classes to register themselves as handlers for a given EDU or """Allows classes to register themselves as handlers for a given EDU or
query type for incoming federation traffic. query type for incoming federation traffic.
""" """

View file

@ -29,7 +29,7 @@ from synapse.types import JsonDict
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
class TransactionActions(object): class TransactionActions:
""" Defines persistence actions that relate to handling Transactions. """ Defines persistence actions that relate to handling Transactions.
""" """

View file

@ -46,7 +46,7 @@ from .units import Edu
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
class FederationRemoteSendQueue(object): class FederationRemoteSendQueue:
"""A drop in replacement for FederationSender""" """A drop in replacement for FederationSender"""
def __init__(self, hs): def __init__(self, hs):
@ -365,7 +365,7 @@ class FederationRemoteSendQueue(object):
) )
class BaseFederationRow(object): class BaseFederationRow:
"""Base class for rows to be sent in the federation stream. """Base class for rows to be sent in the federation stream.
Specifies how to identify, serialize and deserialize the different types. Specifies how to identify, serialize and deserialize the different types.

View file

@ -56,7 +56,7 @@ sent_pdus_destination_dist_total = Counter(
) )
class FederationSender(object): class FederationSender:
def __init__(self, hs: "synapse.server.HomeServer"): def __init__(self, hs: "synapse.server.HomeServer"):
self.hs = hs self.hs = hs
self.server_name = hs.hostname self.server_name = hs.hostname

View file

@ -53,7 +53,7 @@ sent_edus_by_type = Counter(
) )
class PerDestinationQueue(object): class PerDestinationQueue:
""" """
Manages the per-destination transmission queues. Manages the per-destination transmission queues.

View file

@ -35,7 +35,7 @@ if TYPE_CHECKING:
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
class TransactionManager(object): class TransactionManager:
"""Helper class which handles building and sending transactions """Helper class which handles building and sending transactions
shared between PerDestinationQueue objects shared between PerDestinationQueue objects

View file

@ -30,7 +30,7 @@ from synapse.logging.utils import log_function
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
class TransportLayerClient(object): class TransportLayerClient:
"""Sends federation HTTP requests to other servers""" """Sends federation HTTP requests to other servers"""
def __init__(self, hs): def __init__(self, hs):

View file

@ -100,7 +100,7 @@ class NoAuthenticationError(AuthenticationError):
pass pass
class Authenticator(object): class Authenticator:
def __init__(self, hs: HomeServer): def __init__(self, hs: HomeServer):
self._clock = hs.get_clock() self._clock = hs.get_clock()
self.keyring = hs.get_keyring() self.keyring = hs.get_keyring()
@ -228,7 +228,7 @@ def _parse_auth_header(header_bytes):
) )
class BaseFederationServlet(object): class BaseFederationServlet:
"""Abstract base class for federation servlet classes. """Abstract base class for federation servlet classes.
The servlet object should have a PATH attribute which takes the form of a regexp to The servlet object should have a PATH attribute which takes the form of a regexp to

View file

@ -60,7 +60,7 @@ DEFAULT_ATTESTATION_JITTER = (0.9, 1.3)
UPDATE_ATTESTATION_TIME_MS = 1 * 24 * 60 * 60 * 1000 UPDATE_ATTESTATION_TIME_MS = 1 * 24 * 60 * 60 * 1000
class GroupAttestationSigning(object): class GroupAttestationSigning:
"""Creates and verifies group attestations. """Creates and verifies group attestations.
""" """
@ -124,7 +124,7 @@ class GroupAttestationSigning(object):
) )
class GroupAttestionRenewer(object): class GroupAttestionRenewer:
"""Responsible for sending and receiving attestation updates. """Responsible for sending and receiving attestation updates.
""" """

View file

@ -32,7 +32,7 @@ logger = logging.getLogger(__name__)
# TODO: Flairs # TODO: Flairs
class GroupsServerWorkerHandler(object): class GroupsServerWorkerHandler:
def __init__(self, hs): def __init__(self, hs):
self.hs = hs self.hs = hs
self.store = hs.get_datastore() self.store = hs.get_datastore()

View file

@ -20,7 +20,7 @@ from .identity import IdentityHandler
from .search import SearchHandler from .search import SearchHandler
class Handlers(object): class Handlers:
""" Deprecated. A collection of handlers. """ Deprecated. A collection of handlers.

View file

@ -25,7 +25,7 @@ from synapse.types import UserID
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
class BaseHandler(object): class BaseHandler:
""" """
Common base class for the event handlers. Common base class for the event handlers.
""" """

View file

@ -14,7 +14,7 @@
# limitations under the License. # limitations under the License.
class AccountDataEventSource(object): class AccountDataEventSource:
def __init__(self, hs): def __init__(self, hs):
self.store = hs.get_datastore() self.store = hs.get_datastore()

View file

@ -29,7 +29,7 @@ from synapse.util import stringutils
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
class AccountValidityHandler(object): class AccountValidityHandler:
def __init__(self, hs): def __init__(self, hs):
self.hs = hs self.hs = hs
self.config = hs.config self.config = hs.config

View file

@ -34,7 +34,7 @@ solutions, please read https://github.com/matrix-org/synapse/blob/master/docs/AC
--------------------------------------------------------------------------------""" --------------------------------------------------------------------------------"""
class AcmeHandler(object): class AcmeHandler:
def __init__(self, hs): def __init__(self, hs):
self.hs = hs self.hs = hs
self.reactor = hs.get_reactor() self.reactor = hs.get_reactor()

View file

@ -78,7 +78,7 @@ def create_issuing_service(reactor, acme_url, account_key_file, well_known_resou
@attr.s @attr.s
@implementer(ICertificateStore) @implementer(ICertificateStore)
class ErsatzStore(object): class ErsatzStore:
""" """
A store that only stores in memory. A store that only stores in memory.
""" """

View file

@ -197,7 +197,7 @@ class AdminHandler(BaseHandler):
return writer.finished() return writer.finished()
class ExfiltrationWriter(object): class ExfiltrationWriter:
"""Interface used to specify how to write exported data. """Interface used to specify how to write exported data.
""" """

View file

@ -34,7 +34,7 @@ logger = logging.getLogger(__name__)
events_processed_counter = Counter("synapse_handlers_appservice_events_processed", "") events_processed_counter = Counter("synapse_handlers_appservice_events_processed", "")
class ApplicationServicesHandler(object): class ApplicationServicesHandler:
def __init__(self, hs): def __init__(self, hs):
self.store = hs.get_datastore() self.store = hs.get_datastore()
self.is_mine_id = hs.is_mine_id self.is_mine_id = hs.is_mine_id

View file

@ -1236,7 +1236,7 @@ class AuthHandler(BaseHandler):
@attr.s @attr.s
class MacaroonGenerator(object): class MacaroonGenerator:
hs = attr.ib() hs = attr.ib()

View file

@ -497,7 +497,7 @@ def _update_device_from_client_ips(device, client_ips):
device.update({"last_seen_ts": ip.get("last_seen"), "last_seen_ip": ip.get("ip")}) device.update({"last_seen_ts": ip.get("last_seen"), "last_seen_ip": ip.get("ip")})
class DeviceListUpdater(object): class DeviceListUpdater:
"Handles incoming device list updates from federation and updates the DB" "Handles incoming device list updates from federation and updates the DB"
def __init__(self, hs, device_handler): def __init__(self, hs, device_handler):

View file

@ -31,7 +31,7 @@ from synapse.util.stringutils import random_string
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
class DeviceMessageHandler(object): class DeviceMessageHandler:
def __init__(self, hs): def __init__(self, hs):
""" """
Args: Args:

View file

@ -43,7 +43,7 @@ from synapse.util.retryutils import NotRetryingDestination
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
class E2eKeysHandler(object): class E2eKeysHandler:
def __init__(self, hs): def __init__(self, hs):
self.store = hs.get_datastore() self.store = hs.get_datastore()
self.federation = hs.get_federation_client() self.federation = hs.get_federation_client()
@ -1212,7 +1212,7 @@ class SignatureListItem:
signature = attr.ib() signature = attr.ib()
class SigningKeyEduUpdater(object): class SigningKeyEduUpdater:
"""Handles incoming signing key updates from federation and updates the DB""" """Handles incoming signing key updates from federation and updates the DB"""
def __init__(self, hs, e2e_keys_handler): def __init__(self, hs, e2e_keys_handler):

View file

@ -29,7 +29,7 @@ from synapse.util.async_helpers import Linearizer
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
class E2eRoomKeysHandler(object): class E2eRoomKeysHandler:
""" """
Implements an optional realtime backup mechanism for encrypted E2E megolm room keys. Implements an optional realtime backup mechanism for encrypted E2E megolm room keys.
This gives a way for users to store and recover their megolm keys if they lose all This gives a way for users to store and recover their megolm keys if they lose all

View file

@ -52,7 +52,7 @@ def _create_rerouter(func_name):
return f return f
class GroupsLocalWorkerHandler(object): class GroupsLocalWorkerHandler:
def __init__(self, hs): def __init__(self, hs):
self.hs = hs self.hs = hs
self.store = hs.get_datastore() self.store = hs.get_datastore()

View file

@ -64,7 +64,7 @@ if TYPE_CHECKING:
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
class MessageHandler(object): class MessageHandler:
"""Contains some read only APIs to get state about a room """Contains some read only APIs to get state about a room
""" """
@ -361,7 +361,7 @@ class MessageHandler(object):
_DUMMY_EVENT_ROOM_EXCLUSION_EXPIRY = 7 * 24 * 60 * 60 * 1000 _DUMMY_EVENT_ROOM_EXCLUSION_EXPIRY = 7 * 24 * 60 * 60 * 1000
class EventCreationHandler(object): class EventCreationHandler:
def __init__(self, hs: "HomeServer"): def __init__(self, hs: "HomeServer"):
self.hs = hs self.hs = hs
self.auth = hs.get_auth() self.auth = hs.get_auth()

View file

@ -37,7 +37,7 @@ if TYPE_CHECKING:
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
class PurgeStatus(object): class PurgeStatus:
"""Object tracking the status of a purge request """Object tracking the status of a purge request
This class contains information on the progress of a purge request, for This class contains information on the progress of a purge request, for
@ -65,7 +65,7 @@ class PurgeStatus(object):
return {"status": PurgeStatus.STATUS_TEXT[self.status]} return {"status": PurgeStatus.STATUS_TEXT[self.status]}
class PaginationHandler(object): class PaginationHandler:
"""Handles pagination and purge history requests. """Handles pagination and purge history requests.
These are in the same handler due to the fact we need to block clients These are in the same handler due to the fact we need to block clients

View file

@ -22,7 +22,7 @@ from synapse.api.errors import Codes, PasswordRefusedError
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
class PasswordPolicyHandler(object): class PasswordPolicyHandler:
def __init__(self, hs): def __init__(self, hs):
self.policy = hs.config.password_policy self.policy = hs.config.password_policy
self.enabled = hs.config.password_policy_enabled self.enabled = hs.config.password_policy_enabled

View file

@ -1010,7 +1010,7 @@ def format_user_presence_state(state, now, include_user_id=True):
return content return content
class PresenceEventSource(object): class PresenceEventSource:
def __init__(self, hs): def __init__(self, hs):
# We can't call get_presence_handler here because there's a cycle: # We can't call get_presence_handler here because there's a cycle:
# #

View file

@ -123,7 +123,7 @@ class ReceiptsHandler(BaseHandler):
await self.federation.send_read_receipt(receipt) await self.federation.send_read_receipt(receipt)
class ReceiptEventSource(object): class ReceiptEventSource:
def __init__(self, hs): def __init__(self, hs):
self.store = hs.get_datastore() self.store = hs.get_datastore()

View file

@ -974,7 +974,7 @@ class RoomCreationHandler(BaseHandler):
raise StoreError(500, "Couldn't generate a room ID.") raise StoreError(500, "Couldn't generate a room ID.")
class RoomContextHandler(object): class RoomContextHandler:
def __init__(self, hs: "HomeServer"): def __init__(self, hs: "HomeServer"):
self.hs = hs self.hs = hs
self.store = hs.get_datastore() self.store = hs.get_datastore()
@ -1084,7 +1084,7 @@ class RoomContextHandler(object):
return results return results
class RoomEventSource(object): class RoomEventSource:
def __init__(self, hs: "HomeServer"): def __init__(self, hs: "HomeServer"):
self.store = hs.get_datastore() self.store = hs.get_datastore()
@ -1146,7 +1146,7 @@ class RoomEventSource(object):
return self.store.get_room_events_max_id(room_id) return self.store.get_room_events_max_id(room_id)
class RoomShutdownHandler(object): class RoomShutdownHandler:
DEFAULT_MESSAGE = ( DEFAULT_MESSAGE = (
"Sharing illegal content on this server is not permitted and rooms in" "Sharing illegal content on this server is not permitted and rooms in"

View file

@ -51,7 +51,7 @@ if TYPE_CHECKING:
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
class RoomMemberHandler(object): class RoomMemberHandler:
# TODO(paul): This handler currently contains a messy conflation of # TODO(paul): This handler currently contains a messy conflation of
# low-level API that works on UserID objects and so on, and REST-level # low-level API that works on UserID objects and so on, and REST-level
# API that takes ID strings and returns pagination chunks. These concerns # API that takes ID strings and returns pagination chunks. These concerns

View file

@ -360,12 +360,12 @@ MXID_MAPPER_MAP = {
@attr.s @attr.s
class SamlConfig(object): class SamlConfig:
mxid_source_attribute = attr.ib() mxid_source_attribute = attr.ib()
mxid_mapper = attr.ib() mxid_mapper = attr.ib()
class DefaultSamlMappingProvider(object): class DefaultSamlMappingProvider:
__version__ = "0.0.1" __version__ = "0.0.1"
def __init__(self, parsed_config: SamlConfig, module_api: ModuleApi): def __init__(self, parsed_config: SamlConfig, module_api: ModuleApi):

View file

@ -18,7 +18,7 @@ import logging
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
class StateDeltasHandler(object): class StateDeltasHandler:
def __init__(self, hs): def __init__(self, hs):
self.store = hs.get_datastore() self.store = hs.get_datastore()

View file

@ -246,7 +246,7 @@ class SyncResult:
__bool__ = __nonzero__ # python3 __bool__ = __nonzero__ # python3
class SyncHandler(object): class SyncHandler:
def __init__(self, hs: "HomeServer"): def __init__(self, hs: "HomeServer"):
self.hs_config = hs.config self.hs_config = hs.config
self.store = hs.get_datastore() self.store = hs.get_datastore()
@ -2075,7 +2075,7 @@ class SyncResultBuilder:
@attr.s @attr.s
class RoomSyncResultBuilder(object): class RoomSyncResultBuilder:
"""Stores information needed to create either a `JoinedSyncResult` or """Stores information needed to create either a `JoinedSyncResult` or
`ArchivedSyncResult`. `ArchivedSyncResult`.

View file

@ -412,7 +412,7 @@ class TypingWriterHandler(FollowerTypingHandler):
raise Exception("Typing writer instance got typing info over replication") raise Exception("Typing writer instance got typing info over replication")
class TypingNotificationEventSource(object): class TypingNotificationEventSource:
def __init__(self, hs): def __init__(self, hs):
self.hs = hs self.hs = hs
self.clock = hs.get_clock() self.clock = hs.get_clock()

View file

@ -86,7 +86,7 @@ def _make_scheduler(reactor):
return _scheduler return _scheduler
class IPBlacklistingResolver(object): class IPBlacklistingResolver:
""" """
A proxy for reactor.nameResolver which only produces non-blacklisted IP A proxy for reactor.nameResolver which only produces non-blacklisted IP
addresses, preventing DNS rebinding attacks on URL preview. addresses, preventing DNS rebinding attacks on URL preview.
@ -133,7 +133,7 @@ class IPBlacklistingResolver(object):
r.resolutionComplete() r.resolutionComplete()
@provider(IResolutionReceiver) @provider(IResolutionReceiver)
class EndpointReceiver(object): class EndpointReceiver:
@staticmethod @staticmethod
def resolutionBegan(resolutionInProgress): def resolutionBegan(resolutionInProgress):
pass pass
@ -192,7 +192,7 @@ class BlacklistingAgentWrapper(Agent):
) )
class SimpleHttpClient(object): class SimpleHttpClient:
""" """
A simple, no-frills HTTP client with methods that wrap up common ways of A simple, no-frills HTTP client with methods that wrap up common ways of
using HTTP in Matrix using HTTP in Matrix
@ -244,7 +244,7 @@ class SimpleHttpClient(object):
) )
@implementer(IReactorPluggableNameResolver) @implementer(IReactorPluggableNameResolver)
class Reactor(object): class Reactor:
def __getattr__(_self, attr): def __getattr__(_self, attr):
if attr == "nameResolver": if attr == "nameResolver":
return nameResolver return nameResolver

View file

@ -31,7 +31,7 @@ class ProxyConnectError(ConnectError):
@implementer(IStreamClientEndpoint) @implementer(IStreamClientEndpoint)
class HTTPConnectProxyEndpoint(object): class HTTPConnectProxyEndpoint:
"""An Endpoint implementation which will send a CONNECT request to an http proxy """An Endpoint implementation which will send a CONNECT request to an http proxy
Wraps an existing HostnameEndpoint for the proxy. Wraps an existing HostnameEndpoint for the proxy.

View file

@ -36,7 +36,7 @@ logger = logging.getLogger(__name__)
@implementer(IAgent) @implementer(IAgent)
class MatrixFederationAgent(object): class MatrixFederationAgent:
"""An Agent-like thing which provides a `request` method which correctly """An Agent-like thing which provides a `request` method which correctly
handles resolving matrix server names when using matrix://. Handles standard handles resolving matrix server names when using matrix://. Handles standard
https URIs as normal. https URIs as normal.
@ -175,7 +175,7 @@ class MatrixFederationAgent(object):
@implementer(IAgentEndpointFactory) @implementer(IAgentEndpointFactory)
class MatrixHostnameEndpointFactory(object): class MatrixHostnameEndpointFactory:
"""Factory for MatrixHostnameEndpoint for parsing to an Agent. """Factory for MatrixHostnameEndpoint for parsing to an Agent.
""" """
@ -198,7 +198,7 @@ class MatrixHostnameEndpointFactory(object):
@implementer(IStreamClientEndpoint) @implementer(IStreamClientEndpoint)
class MatrixHostnameEndpoint(object): class MatrixHostnameEndpoint:
"""An endpoint that resolves matrix:// URLs using Matrix server name """An endpoint that resolves matrix:// URLs using Matrix server name
resolution (i.e. via SRV). Does not check for well-known delegation. resolution (i.e. via SRV). Does not check for well-known delegation.

View file

@ -33,7 +33,7 @@ SERVER_CACHE = {}
@attr.s(slots=True, frozen=True) @attr.s(slots=True, frozen=True)
class Server(object): class Server:
""" """
Our record of an individual server which can be tried to reach a destination. Our record of an individual server which can be tried to reach a destination.
@ -96,7 +96,7 @@ def _sort_server_list(server_list):
return results return results
class SrvResolver(object): class SrvResolver:
"""Interface to the dns client to do SRV lookups, with result caching. """Interface to the dns client to do SRV lookups, with result caching.
The default resolver in twisted.names doesn't do any caching (it has a CacheResolver, The default resolver in twisted.names doesn't do any caching (it has a CacheResolver,

View file

@ -71,11 +71,11 @@ _had_valid_well_known_cache = TTLCache("had-valid-well-known")
@attr.s(slots=True, frozen=True) @attr.s(slots=True, frozen=True)
class WellKnownLookupResult(object): class WellKnownLookupResult:
delegated_server = attr.ib() delegated_server = attr.ib()
class WellKnownResolver(object): class WellKnownResolver:
"""Handles well-known lookups for matrix servers. """Handles well-known lookups for matrix servers.
""" """

View file

@ -76,7 +76,7 @@ _next_id = 1
@attr.s(frozen=True) @attr.s(frozen=True)
class MatrixFederationRequest(object): class MatrixFederationRequest:
method = attr.ib() method = attr.ib()
"""HTTP method """HTTP method
:type: str :type: str
@ -203,7 +203,7 @@ async def _handle_json_response(
return body return body
class MatrixFederationHttpClient(object): class MatrixFederationHttpClient:
"""HTTP client used to talk to other homeservers over the federation """HTTP client used to talk to other homeservers over the federation
protocol. Send client certificates and signs requests. protocol. Send client certificates and signs requests.
@ -226,7 +226,7 @@ class MatrixFederationHttpClient(object):
) )
@implementer(IReactorPluggableNameResolver) @implementer(IReactorPluggableNameResolver)
class Reactor(object): class Reactor:
def __getattr__(_self, attr): def __getattr__(_self, attr):
if attr == "nameResolver": if attr == "nameResolver":
return nameResolver return nameResolver

View file

@ -145,7 +145,7 @@ LaterGauge(
) )
class RequestMetrics(object): class RequestMetrics:
def start(self, time_sec, name, method): def start(self, time_sec, name, method):
self.start = time_sec self.start = time_sec
self.start_context = current_context() self.start_context = current_context()

View file

@ -174,7 +174,7 @@ def wrap_async_request_handler(h):
return preserve_fn(wrapped_async_request_handler) return preserve_fn(wrapped_async_request_handler)
class HttpServer(object): class HttpServer:
""" Interface for registering callbacks on a HTTP server """ Interface for registering callbacks on a HTTP server
""" """

View file

@ -256,7 +256,7 @@ def assert_params_in_dict(body, required):
raise SynapseError(400, "Missing params: %r" % absent, Codes.MISSING_PARAM) raise SynapseError(400, "Missing params: %r" % absent, Codes.MISSING_PARAM)
class RestServlet(object): class RestServlet:
""" A Synapse REST Servlet. """ A Synapse REST Servlet.

View file

@ -55,7 +55,7 @@ def stdlib_log_level_to_twisted(level: str) -> LogLevel:
@attr.s @attr.s
@implementer(ILogObserver) @implementer(ILogObserver)
class LogContextObserver(object): class LogContextObserver:
""" """
An ILogObserver which adds Synapse-specific log context information. An ILogObserver which adds Synapse-specific log context information.
@ -169,7 +169,7 @@ class OutputPipeType(Values):
@attr.s @attr.s
class DrainConfiguration(object): class DrainConfiguration:
name = attr.ib() name = attr.ib()
type = attr.ib() type = attr.ib()
location = attr.ib() location = attr.ib()
@ -177,7 +177,7 @@ class DrainConfiguration(object):
@attr.s @attr.s
class NetworkJSONTerseOptions(object): class NetworkJSONTerseOptions:
maximum_buffer = attr.ib(type=int) maximum_buffer = attr.ib(type=int)

View file

@ -152,7 +152,7 @@ def TerseJSONToConsoleLogObserver(outFile: IO[str], metadata: dict) -> FileLogOb
@attr.s @attr.s
@implementer(IPushProducer) @implementer(IPushProducer)
class LogProducer(object): class LogProducer:
""" """
An IPushProducer that writes logs from its buffer to its transport when it An IPushProducer that writes logs from its buffer to its transport when it
is resumed. is resumed.
@ -190,7 +190,7 @@ class LogProducer(object):
@attr.s @attr.s
@implementer(ILogObserver) @implementer(ILogObserver)
class TerseJSONToTCPLogObserver(object): class TerseJSONToTCPLogObserver:
""" """
An IObserver that writes JSON logs to a TCP target. An IObserver that writes JSON logs to a TCP target.

View file

@ -74,7 +74,7 @@ except Exception:
get_thread_id = threading.get_ident get_thread_id = threading.get_ident
class ContextResourceUsage(object): class ContextResourceUsage:
"""Object for tracking the resources used by a log context """Object for tracking the resources used by a log context
Attributes: Attributes:
@ -179,7 +179,7 @@ class ContextResourceUsage(object):
LoggingContextOrSentinel = Union["LoggingContext", "_Sentinel"] LoggingContextOrSentinel = Union["LoggingContext", "_Sentinel"]
class _Sentinel(object): class _Sentinel:
"""Sentinel to represent the root context""" """Sentinel to represent the root context"""
__slots__ = ["previous_context", "finished", "request", "scope", "tag"] __slots__ = ["previous_context", "finished", "request", "scope", "tag"]
@ -226,7 +226,7 @@ class _Sentinel(object):
SENTINEL_CONTEXT = _Sentinel() SENTINEL_CONTEXT = _Sentinel()
class LoggingContext(object): class LoggingContext:
"""Additional context for log formatting. Contexts are scoped within a """Additional context for log formatting. Contexts are scoped within a
"with" block. "with" block.

View file

@ -185,7 +185,7 @@ if TYPE_CHECKING:
# Helper class # Helper class
class _DummyTagNames(object): class _DummyTagNames:
"""wrapper of opentracings tags. We need to have them if we """wrapper of opentracings tags. We need to have them if we
want to reference them without opentracing around. Clearly they want to reference them without opentracing around. Clearly they
should never actually show up in a trace. `set_tags` overwrites should never actually show up in a trace. `set_tags` overwrites

View file

@ -51,7 +51,7 @@ all_gauges = {} # type: Dict[str, Union[LaterGauge, InFlightGauge, BucketCollec
HAVE_PROC_SELF_STAT = os.path.exists("/proc/self/stat") HAVE_PROC_SELF_STAT = os.path.exists("/proc/self/stat")
class RegistryProxy(object): class RegistryProxy:
@staticmethod @staticmethod
def collect(): def collect():
for metric in REGISTRY.collect(): for metric in REGISTRY.collect():
@ -60,7 +60,7 @@ class RegistryProxy(object):
@attr.s(hash=True) @attr.s(hash=True)
class LaterGauge(object): class LaterGauge:
name = attr.ib(type=str) name = attr.ib(type=str)
desc = attr.ib(type=str) desc = attr.ib(type=str)
@ -100,7 +100,7 @@ class LaterGauge(object):
all_gauges[self.name] = self all_gauges[self.name] = self
class InFlightGauge(object): class InFlightGauge:
"""Tracks number of things (e.g. requests, Measure blocks, etc) in flight """Tracks number of things (e.g. requests, Measure blocks, etc) in flight
at any given time. at any given time.
@ -206,7 +206,7 @@ class InFlightGauge(object):
@attr.s(hash=True) @attr.s(hash=True)
class BucketCollector(object): class BucketCollector:
""" """
Like a Histogram, but allows buckets to be point-in-time instead of Like a Histogram, but allows buckets to be point-in-time instead of
incrementally added to. incrementally added to.
@ -269,7 +269,7 @@ class BucketCollector(object):
# #
class CPUMetrics(object): class CPUMetrics:
def __init__(self): def __init__(self):
ticks_per_sec = 100 ticks_per_sec = 100
try: try:
@ -329,7 +329,7 @@ gc_time = Histogram(
) )
class GCCounts(object): class GCCounts:
def collect(self): def collect(self):
cm = GaugeMetricFamily("python_gc_counts", "GC object counts", labels=["gen"]) cm = GaugeMetricFamily("python_gc_counts", "GC object counts", labels=["gen"])
for n, m in enumerate(gc.get_count()): for n, m in enumerate(gc.get_count()):
@ -347,7 +347,7 @@ if not running_on_pypy:
# #
class PyPyGCStats(object): class PyPyGCStats:
def collect(self): def collect(self):
# @stats is a pretty-printer object with __str__() returning a nice table, # @stats is a pretty-printer object with __str__() returning a nice table,
@ -482,7 +482,7 @@ build_info.labels(
last_ticked = time.time() last_ticked = time.time()
class ReactorLastSeenMetric(object): class ReactorLastSeenMetric:
def collect(self): def collect(self):
cm = GaugeMetricFamily( cm = GaugeMetricFamily(
"python_twisted_reactor_last_seen", "python_twisted_reactor_last_seen",

View file

@ -105,7 +105,7 @@ _background_processes_active_since_last_scrape = set() # type: Set[_BackgroundP
_bg_metrics_lock = threading.Lock() _bg_metrics_lock = threading.Lock()
class _Collector(object): class _Collector:
"""A custom metrics collector for the background process metrics. """A custom metrics collector for the background process metrics.
Ensures that all of the metrics are up-to-date with any in-flight processes Ensures that all of the metrics are up-to-date with any in-flight processes
@ -140,7 +140,7 @@ class _Collector(object):
REGISTRY.register(_Collector()) REGISTRY.register(_Collector())
class _BackgroundProcess(object): class _BackgroundProcess:
def __init__(self, desc, ctx): def __init__(self, desc, ctx):
self.desc = desc self.desc = desc
self._context = ctx self._context = ctx

View file

@ -31,7 +31,7 @@ __all__ = ["errors", "make_deferred_yieldable", "run_in_background", "ModuleApi"
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
class ModuleApi(object): class ModuleApi:
"""A proxy object that gets passed to various plugin modules so they """A proxy object that gets passed to various plugin modules so they
can register new users etc if necessary. can register new users etc if necessary.
""" """

View file

@ -68,7 +68,7 @@ def count(func: Callable[[T], bool], it: Iterable[T]) -> int:
return n return n
class _NotificationListener(object): class _NotificationListener:
""" This represents a single client connection to the events stream. """ This represents a single client connection to the events stream.
The events stream handler will have yielded to the deferred, so to The events stream handler will have yielded to the deferred, so to
notify the handler it is sufficient to resolve the deferred. notify the handler it is sufficient to resolve the deferred.
@ -80,7 +80,7 @@ class _NotificationListener(object):
self.deferred = deferred self.deferred = deferred
class _NotifierUserStream(object): class _NotifierUserStream:
"""This represents a user connected to the event stream. """This represents a user connected to the event stream.
It tracks the most recent stream token for that user. It tracks the most recent stream token for that user.
At a given point a user may have a number of streams listening for At a given point a user may have a number of streams listening for
@ -168,7 +168,7 @@ class EventStreamResult(namedtuple("EventStreamResult", ("events", "tokens"))):
__bool__ = __nonzero__ # python3 __bool__ = __nonzero__ # python3
class Notifier(object): class Notifier:
""" This class is responsible for notifying any listeners when there are """ This class is responsible for notifying any listeners when there are
new events available for it. new events available for it.

View file

@ -22,7 +22,7 @@ from .bulk_push_rule_evaluator import BulkPushRuleEvaluator
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
class ActionGenerator(object): class ActionGenerator:
def __init__(self, hs): def __init__(self, hs):
self.hs = hs self.hs = hs
self.clock = hs.get_clock() self.clock = hs.get_clock()

View file

@ -95,7 +95,7 @@ def _should_count_as_unread(event: EventBase, context: EventContext) -> bool:
return False return False
class BulkPushRuleEvaluator(object): class BulkPushRuleEvaluator:
"""Calculates the outcome of push rules for an event for all users in the """Calculates the outcome of push rules for an event for all users in the
room at once. room at once.
""" """
@ -263,7 +263,7 @@ def _condition_checker(evaluator, conditions, uid, display_name, cache):
return True return True
class RulesForRoom(object): class RulesForRoom:
"""Caches push rules for users in a room. """Caches push rules for users in a room.
This efficiently handles users joining/leaving the room by not invalidating This efficiently handles users joining/leaving the room by not invalidating

View file

@ -45,7 +45,7 @@ THROTTLE_RESET_AFTER_MS = 12 * 60 * 60 * 1000
INCLUDE_ALL_UNREAD_NOTIFS = False INCLUDE_ALL_UNREAD_NOTIFS = False
class EmailPusher(object): class EmailPusher:
""" """
A pusher that sends email notifications about events (approximately) A pusher that sends email notifications about events (approximately)
when they happen. when they happen.

View file

@ -49,7 +49,7 @@ http_badges_failed_counter = Counter(
) )
class HttpPusher(object): class HttpPusher:
INITIAL_BACKOFF_SEC = 1 # in seconds because that's what Twisted takes INITIAL_BACKOFF_SEC = 1 # in seconds because that's what Twisted takes
MAX_BACKOFF_SEC = 60 * 60 MAX_BACKOFF_SEC = 60 * 60

View file

@ -92,7 +92,7 @@ ALLOWED_ATTRS = {
# ALLOWED_SCHEMES = ["http", "https", "ftp", "mailto"] # ALLOWED_SCHEMES = ["http", "https", "ftp", "mailto"]
class Mailer(object): class Mailer:
def __init__(self, hs, app_name, template_html, template_text): def __init__(self, hs, app_name, template_html, template_text):
self.hs = hs self.hs = hs
self.template_html = template_html self.template_html = template_html

View file

@ -105,7 +105,7 @@ def tweaks_for_actions(actions: List[Union[str, Dict]]) -> Dict[str, Any]:
return tweaks return tweaks
class PushRuleEvaluatorForEvent(object): class PushRuleEvaluatorForEvent:
def __init__( def __init__(
self, self,
event: EventBase, event: EventBase,

View file

@ -23,7 +23,7 @@ from .httppusher import HttpPusher
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
class PusherFactory(object): class PusherFactory:
def __init__(self, hs): def __init__(self, hs):
self.hs = hs self.hs = hs
self.config = hs.config self.config = hs.config

View file

@ -33,7 +33,7 @@ from synapse.util.stringutils import random_string
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
class ReplicationEndpoint(object): class ReplicationEndpoint:
"""Helper base class for defining new replication HTTP endpoints. """Helper base class for defining new replication HTTP endpoints.
This creates an endpoint under `/_synapse/replication/:NAME/:PATH_ARGS..` This creates an endpoint under `/_synapse/replication/:NAME/:PATH_ARGS..`

View file

@ -16,7 +16,7 @@
from synapse.storage.util.id_generators import _load_current_id from synapse.storage.util.id_generators import _load_current_id
class SlavedIdTracker(object): class SlavedIdTracker:
def __init__(self, db_conn, table, column, extra_tables=[], step=1): def __init__(self, db_conn, table, column, extra_tables=[], step=1):
self.step = step self.step = step
self._current = _load_current_id(db_conn, table, column, step) self._current = _load_current_id(db_conn, table, column, step)

View file

@ -113,7 +113,7 @@ PING_TIMEOUT_MULTIPLIER = 5
PING_TIMEOUT_MS = PING_TIME * PING_TIMEOUT_MULTIPLIER PING_TIMEOUT_MS = PING_TIME * PING_TIMEOUT_MULTIPLIER
class ConnectionStates(object): class ConnectionStates:
CONNECTING = "connecting" CONNECTING = "connecting"
ESTABLISHED = "established" ESTABLISHED = "established"
PAUSED = "paused" PAUSED = "paused"

View file

@ -58,7 +58,7 @@ class ReplicationStreamProtocolFactory(Factory):
) )
class ReplicationStreamer(object): class ReplicationStreamer:
"""Handles replication connections. """Handles replication connections.
This needs to be poked when new replication data may be available. When new This needs to be poked when new replication data may be available. When new

View file

@ -79,7 +79,7 @@ StreamUpdateResult = Tuple[List[Tuple[Token, StreamRow]], Token, bool]
UpdateFunction = Callable[[str, Token, Token, int], Awaitable[StreamUpdateResult]] UpdateFunction = Callable[[str, Token, Token, int], Awaitable[StreamUpdateResult]]
class Stream(object): class Stream:
"""Base class for the streams. """Base class for the streams.
Provides a `get_updates()` function that returns new updates since the last Provides a `get_updates()` function that returns new updates since the last

View file

@ -49,14 +49,14 @@ data part are:
@attr.s(slots=True, frozen=True) @attr.s(slots=True, frozen=True)
class EventsStreamRow(object): class EventsStreamRow:
"""A parsed row from the events replication stream""" """A parsed row from the events replication stream"""
type = attr.ib() # str: the TypeId of one of the *EventsStreamRows type = attr.ib() # str: the TypeId of one of the *EventsStreamRows
data = attr.ib() # BaseEventsStreamRow data = attr.ib() # BaseEventsStreamRow
class BaseEventsStreamRow(object): class BaseEventsStreamRow:
"""Base class for rows to be sent in the events stream. """Base class for rows to be sent in the events stream.
Specifies how to identify, serialize and deserialize the different types. Specifies how to identify, serialize and deserialize the different types.

View file

@ -25,7 +25,7 @@ logger = logging.getLogger(__name__)
CLEANUP_PERIOD_MS = 1000 * 60 * 30 # 30 mins CLEANUP_PERIOD_MS = 1000 * 60 * 30 # 30 mins
class HttpTransactionCache(object): class HttpTransactionCache:
def __init__(self, hs): def __init__(self, hs):
self.hs = hs self.hs = hs
self.auth = self.hs.get_auth() self.auth = self.hs.get_auth()

Some files were not shown because too many files have changed in this diff Show more