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

Commit

Permalink
Use auto_attribs/native type hints for attrs classes. (#11692)
Browse files Browse the repository at this point in the history
  • Loading branch information
clokep authored Jan 13, 2022
1 parent b92a2ff commit 10a88ba
Show file tree
Hide file tree
Showing 40 changed files with 300 additions and 307 deletions.
1 change: 1 addition & 0 deletions changelog.d/11692.misc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Use `auto_attribs` and native type hints for attrs classes.
30 changes: 15 additions & 15 deletions synapse/api/room_versions.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,41 +46,41 @@ class RoomDisposition:
UNSTABLE = "unstable"


@attr.s(slots=True, frozen=True)
@attr.s(slots=True, frozen=True, auto_attribs=True)
class RoomVersion:
"""An object which describes the unique attributes of a room version."""

identifier = attr.ib(type=str) # the identifier for this version
disposition = attr.ib(type=str) # one of the RoomDispositions
event_format = attr.ib(type=int) # one of the EventFormatVersions
state_res = attr.ib(type=int) # one of the StateResolutionVersions
enforce_key_validity = attr.ib(type=bool)
identifier: str # the identifier for this version
disposition: str # one of the RoomDispositions
event_format: int # one of the EventFormatVersions
state_res: int # one of the StateResolutionVersions
enforce_key_validity: bool

# Before MSC2432, m.room.aliases had special auth rules and redaction rules
special_case_aliases_auth = attr.ib(type=bool)
special_case_aliases_auth: bool
# Strictly enforce canonicaljson, do not allow:
# * Integers outside the range of [-2 ^ 53 + 1, 2 ^ 53 - 1]
# * Floats
# * NaN, Infinity, -Infinity
strict_canonicaljson = attr.ib(type=bool)
strict_canonicaljson: bool
# MSC2209: Check 'notifications' key while verifying
# m.room.power_levels auth rules.
limit_notifications_power_levels = attr.ib(type=bool)
limit_notifications_power_levels: bool
# MSC2174/MSC2176: Apply updated redaction rules algorithm.
msc2176_redaction_rules = attr.ib(type=bool)
msc2176_redaction_rules: bool
# MSC3083: Support the 'restricted' join_rule.
msc3083_join_rules = attr.ib(type=bool)
msc3083_join_rules: bool
# MSC3375: Support for the proper redaction rules for MSC3083. This mustn't
# be enabled if MSC3083 is not.
msc3375_redaction_rules = attr.ib(type=bool)
msc3375_redaction_rules: bool
# MSC2403: Allows join_rules to be set to 'knock', changes auth rules to allow sending
# m.room.membership event with membership 'knock'.
msc2403_knocking = attr.ib(type=bool)
msc2403_knocking: bool
# MSC2716: Adds m.room.power_levels -> content.historical field to control
# whether "insertion", "chunk", "marker" events can be sent
msc2716_historical = attr.ib(type=bool)
msc2716_historical: bool
# MSC2716: Adds support for redacting "insertion", "chunk", and "marker" events
msc2716_redactions = attr.ib(type=bool)
msc2716_redactions: bool


class RoomVersions:
Expand Down
24 changes: 12 additions & 12 deletions synapse/config/emailconfig.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,19 +55,19 @@
---------------------------------------------------------------------------------------"""


@attr.s(slots=True, frozen=True)
@attr.s(slots=True, frozen=True, auto_attribs=True)
class EmailSubjectConfig:
message_from_person_in_room = attr.ib(type=str)
message_from_person = attr.ib(type=str)
messages_from_person = attr.ib(type=str)
messages_in_room = attr.ib(type=str)
messages_in_room_and_others = attr.ib(type=str)
messages_from_person_and_others = attr.ib(type=str)
invite_from_person = attr.ib(type=str)
invite_from_person_to_room = attr.ib(type=str)
invite_from_person_to_space = attr.ib(type=str)
password_reset = attr.ib(type=str)
email_validation = attr.ib(type=str)
message_from_person_in_room: str
message_from_person: str
messages_from_person: str
messages_in_room: str
messages_in_room_and_others: str
messages_from_person_and_others: str
invite_from_person: str
invite_from_person_to_room: str
invite_from_person_to_space: str
password_reset: str
email_validation: str


class EmailConfig(Config):
Expand Down
4 changes: 2 additions & 2 deletions synapse/config/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -200,8 +200,8 @@ class HttpListenerConfig:
"""Object describing the http-specific parts of the config of a listener"""

x_forwarded: bool = False
resources: List[HttpResourceConfig] = attr.ib(factory=list)
additional_resources: Dict[str, dict] = attr.ib(factory=dict)
resources: List[HttpResourceConfig] = attr.Factory(list)
additional_resources: Dict[str, dict] = attr.Factory(dict)
tag: Optional[str] = None


Expand Down
24 changes: 9 additions & 15 deletions synapse/config/workers.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,12 +51,12 @@ def _instance_to_list_converter(obj: Union[str, List[str]]) -> List[str]:
return obj


@attr.s
@attr.s(auto_attribs=True)
class InstanceLocationConfig:
"""The host and port to talk to an instance via HTTP replication."""

host = attr.ib(type=str)
port = attr.ib(type=int)
host: str
port: int


@attr.s
Expand All @@ -77,34 +77,28 @@ class WriterLocations:
can only be a single instance.
"""

events = attr.ib(
events: List[str] = attr.ib(
default=["master"],
type=List[str],
converter=_instance_to_list_converter,
)
typing = attr.ib(
typing: List[str] = attr.ib(
default=["master"],
type=List[str],
converter=_instance_to_list_converter,
)
to_device = attr.ib(
to_device: List[str] = attr.ib(
default=["master"],
type=List[str],
converter=_instance_to_list_converter,
)
account_data = attr.ib(
account_data: List[str] = attr.ib(
default=["master"],
type=List[str],
converter=_instance_to_list_converter,
)
receipts = attr.ib(
receipts: List[str] = attr.ib(
default=["master"],
type=List[str],
converter=_instance_to_list_converter,
)
presence = attr.ib(
presence: List[str] = attr.ib(
default=["master"],
type=List[str],
converter=_instance_to_list_converter,
)

Expand Down
18 changes: 9 additions & 9 deletions synapse/crypto/keyring.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@
logger = logging.getLogger(__name__)


@attr.s(slots=True, cmp=False)
@attr.s(slots=True, frozen=True, cmp=False, auto_attribs=True)
class VerifyJsonRequest:
"""
A request to verify a JSON object.
Expand All @@ -78,10 +78,10 @@ class VerifyJsonRequest:
key_ids: The set of key_ids to that could be used to verify the JSON object
"""

server_name = attr.ib(type=str)
get_json_object = attr.ib(type=Callable[[], JsonDict])
minimum_valid_until_ts = attr.ib(type=int)
key_ids = attr.ib(type=List[str])
server_name: str
get_json_object: Callable[[], JsonDict]
minimum_valid_until_ts: int
key_ids: List[str]

@staticmethod
def from_json_object(
Expand Down Expand Up @@ -124,7 +124,7 @@ class KeyLookupError(ValueError):
pass


@attr.s(slots=True)
@attr.s(slots=True, frozen=True, auto_attribs=True)
class _FetchKeyRequest:
"""A request for keys for a given server.
Expand All @@ -138,9 +138,9 @@ class _FetchKeyRequest:
key_ids: The IDs of the keys to attempt to fetch
"""

server_name = attr.ib(type=str)
minimum_valid_until_ts = attr.ib(type=int)
key_ids = attr.ib(type=List[str])
server_name: str
minimum_valid_until_ts: int
key_ids: List[str]


class Keyring:
Expand Down
18 changes: 9 additions & 9 deletions synapse/events/snapshot.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
from synapse.storage.databases.main import DataStore


@attr.s(slots=True)
@attr.s(slots=True, auto_attribs=True)
class EventContext:
"""
Holds information relevant to persisting an event
Expand Down Expand Up @@ -103,15 +103,15 @@ class EventContext:
accessed via get_prev_state_ids.
"""

rejected = attr.ib(default=False, type=Union[bool, str])
_state_group = attr.ib(default=None, type=Optional[int])
state_group_before_event = attr.ib(default=None, type=Optional[int])
prev_group = attr.ib(default=None, type=Optional[int])
delta_ids = attr.ib(default=None, type=Optional[StateMap[str]])
app_service = attr.ib(default=None, type=Optional[ApplicationService])
rejected: Union[bool, str] = False
_state_group: Optional[int] = None
state_group_before_event: Optional[int] = None
prev_group: Optional[int] = None
delta_ids: Optional[StateMap[str]] = None
app_service: Optional[ApplicationService] = None

_current_state_ids = attr.ib(default=None, type=Optional[StateMap[str]])
_prev_state_ids = attr.ib(default=None, type=Optional[StateMap[str]])
_current_state_ids: Optional[StateMap[str]] = None
_prev_state_ids: Optional[StateMap[str]] = None

@staticmethod
def with_state(
Expand Down
12 changes: 6 additions & 6 deletions synapse/federation/sender/per_destination_queue.py
Original file line number Diff line number Diff line change
Expand Up @@ -607,18 +607,18 @@ def _start_catching_up(self) -> None:
self._pending_pdus = []


@attr.s(slots=True)
@attr.s(slots=True, auto_attribs=True)
class _TransactionQueueManager:
"""A helper async context manager for pulling stuff off the queues and
tracking what was last successfully sent, etc.
"""

queue = attr.ib(type=PerDestinationQueue)
queue: PerDestinationQueue

_device_stream_id = attr.ib(type=Optional[int], default=None)
_device_list_id = attr.ib(type=Optional[int], default=None)
_last_stream_ordering = attr.ib(type=Optional[int], default=None)
_pdus = attr.ib(type=List[EventBase], factory=list)
_device_stream_id: Optional[int] = None
_device_list_id: Optional[int] = None
_last_stream_ordering: Optional[int] = None
_pdus: List[EventBase] = attr.Factory(list)

async def __aenter__(self) -> Tuple[List[EventBase], List[Edu]]:
# First we calculate the EDUs we want to send, if any.
Expand Down
14 changes: 7 additions & 7 deletions synapse/handlers/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,25 +168,25 @@ def login_id_phone_to_thirdparty(identifier: JsonDict) -> Dict[str, str]:
}


@attr.s(slots=True)
@attr.s(slots=True, auto_attribs=True)
class SsoLoginExtraAttributes:
"""Data we track about SAML2 sessions"""

# time the session was created, in milliseconds
creation_time = attr.ib(type=int)
extra_attributes = attr.ib(type=JsonDict)
creation_time: int
extra_attributes: JsonDict


@attr.s(slots=True, frozen=True)
@attr.s(slots=True, frozen=True, auto_attribs=True)
class LoginTokenAttributes:
"""Data we store in a short-term login token"""

user_id = attr.ib(type=str)
user_id: str

auth_provider_id = attr.ib(type=str)
auth_provider_id: str
"""The SSO Identity Provider that the user authenticated with, to get this token."""

auth_provider_session_id = attr.ib(type=Optional[str])
auth_provider_session_id: Optional[str]
"""The session ID advertised by the SSO Identity Provider."""


Expand Down
10 changes: 5 additions & 5 deletions synapse/handlers/e2e_keys.py
Original file line number Diff line number Diff line change
Expand Up @@ -1321,14 +1321,14 @@ def _one_time_keys_match(old_key_json: str, new_key: JsonDict) -> bool:
return old_key == new_key_copy


@attr.s(slots=True)
@attr.s(slots=True, auto_attribs=True)
class SignatureListItem:
"""An item in the signature list as used by upload_signatures_for_device_keys."""

signing_key_id = attr.ib(type=str)
target_user_id = attr.ib(type=str)
target_device_id = attr.ib(type=str)
signature = attr.ib(type=JsonDict)
signing_key_id: str
target_user_id: str
target_device_id: str
signature: JsonDict


class SigningKeyEduUpdater:
Expand Down
32 changes: 16 additions & 16 deletions synapse/handlers/sso.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,45 +126,45 @@ async def handle_redirect_request(
raise NotImplementedError()


@attr.s
@attr.s(auto_attribs=True)
class UserAttributes:
# the localpart of the mxid that the mapper has assigned to the user.
# if `None`, the mapper has not picked a userid, and the user should be prompted to
# enter one.
localpart = attr.ib(type=Optional[str])
display_name = attr.ib(type=Optional[str], default=None)
emails = attr.ib(type=Collection[str], default=attr.Factory(list))
localpart: Optional[str]
display_name: Optional[str] = None
emails: Collection[str] = attr.Factory(list)


@attr.s(slots=True)
@attr.s(slots=True, auto_attribs=True)
class UsernameMappingSession:
"""Data we track about SSO sessions"""

# A unique identifier for this SSO provider, e.g. "oidc" or "saml".
auth_provider_id = attr.ib(type=str)
auth_provider_id: str

# user ID on the IdP server
remote_user_id = attr.ib(type=str)
remote_user_id: str

# attributes returned by the ID mapper
display_name = attr.ib(type=Optional[str])
emails = attr.ib(type=Collection[str])
display_name: Optional[str]
emails: Collection[str]

# An optional dictionary of extra attributes to be provided to the client in the
# login response.
extra_login_attributes = attr.ib(type=Optional[JsonDict])
extra_login_attributes: Optional[JsonDict]

# where to redirect the client back to
client_redirect_url = attr.ib(type=str)
client_redirect_url: str

# expiry time for the session, in milliseconds
expiry_time_ms = attr.ib(type=int)
expiry_time_ms: int

# choices made by the user
chosen_localpart = attr.ib(type=Optional[str], default=None)
use_display_name = attr.ib(type=bool, default=True)
emails_to_use = attr.ib(type=Collection[str], default=())
terms_accepted_version = attr.ib(type=Optional[str], default=None)
chosen_localpart: Optional[str] = None
use_display_name: bool = True
emails_to_use: Collection[str] = ()
terms_accepted_version: Optional[str] = None


# the HTTP cookie used to track the mapping session id
Expand Down
4 changes: 2 additions & 2 deletions synapse/http/connectproxyclient.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,9 @@ class ProxyConnectError(ConnectError):
pass


@attr.s
@attr.s(auto_attribs=True)
class ProxyCredentials:
username_password = attr.ib(type=bytes)
username_password: bytes

def as_proxy_authorization_value(self) -> bytes:
"""
Expand Down
Loading

0 comments on commit 10a88ba

Please sign in to comment.