desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Insert a receipt, either from local client or remote server.
Automatically does conversion between linearized and graph
representations.'
| @defer.inlineCallbacks
def insert_receipt(self, room_id, receipt_type, user_id, event_ids, data):
| if (not event_ids):
return
if (len(event_ids) == 1):
linearized_event_id = event_ids[0]
else:
def graph_to_linear(txn):
query = ('SELECT event_id WHERE room_id = ? AND stream_ordering IN ( SELECT max(stream_ordering) WHERE event_id ... |
'Have we already responded to a transaction with the same id and
origin?
Returns:
Deferred: Results in `None` if we have not previously responded to
this transaction or a 2-tuple of `(int, dict)` representing the
response code and response body.'
| @log_function
def have_responded(self, transaction):
| if (not transaction.transaction_id):
raise RuntimeError('Cannot persist a transaction with no transaction_id')
return self.store.get_received_txn_response(transaction.transaction_id, transaction.origin)
|
'Persist how we responded to a transaction.
Returns:
Deferred'
| @log_function
def set_response(self, transaction, code, response):
| if (not transaction.transaction_id):
raise RuntimeError('Cannot persist a transaction with no transaction_id')
return self.store.set_received_txn_response(transaction.transaction_id, transaction.origin, code, response)
|
'Persists the `Transaction` we are about to send and works out the
correct value for the `prev_ids` key.
Returns:
Deferred'
| @defer.inlineCallbacks
@log_function
def prepare_to_send(self, transaction):
| transaction.prev_ids = (yield self.store.prep_send_transaction(transaction.transaction_id, transaction.destination, transaction.origin_server_ts))
|
'Marks the given `Transaction` as having been successfully
delivered to the remote homeserver, and what the response was.
Returns:
Deferred'
| @log_function
def delivered(self, transaction, response_code, response_dict):
| return self.store.delivered_txn(transaction.transaction_id, transaction.destination, response_code, response_dict)
|
'Clear the queues for anything older than N minutes'
| def _clear_queue(self):
| FIVE_MINUTES_AGO = ((5 * 60) * 1000)
now = self.clock.time_msec()
keys = self.pos_time.keys()
time = keys.bisect_left((now - FIVE_MINUTES_AGO))
if (not keys[:time]):
return
position_to_delete = max(keys[:time])
for key in keys[:time]:
del self.pos_time[key]
self._clear_qu... |
'Clear all the queues from before a given position'
| def _clear_queue_before_pos(self, position_to_delete):
| with Measure(self.clock, 'send_queue._clear'):
keys = self.presence_changed.keys()
i = keys.bisect_left(position_to_delete)
for key in keys[:i]:
del self.presence_changed[key]
user_ids = set((user_id for uids in self.presence_changed.itervalues() for user_id in uids))
... |
'As per TransactionQueue'
| def notify_new_events(self, current_id):
| pass
|
'As per TransactionQueue'
| def send_edu(self, destination, edu_type, content, key=None):
| pos = self._next_pos()
edu = Edu(origin=self.server_name, destination=destination, edu_type=edu_type, content=content)
if key:
assert isinstance(key, tuple)
self.keyed_edu[(destination, key)] = edu
self.keyed_edu_changed[pos] = (destination, key)
else:
self.edus[pos] = ed... |
'As per TransactionQueue
Args:
states (list(UserPresenceState))'
| def send_presence(self, states):
| pos = self._next_pos()
local_states = filter((lambda s: self.is_mine_id(s.user_id)), states)
self.presence_map.update({state.user_id: state for state in local_states})
self.presence_changed[pos] = [state.user_id for state in local_states]
self.notifier.on_new_replication_data()
|
'As per TransactionQueue'
| def send_failure(self, failure, destination):
| pos = self._next_pos()
self.failures[pos] = (destination, str(failure))
self.notifier.on_new_replication_data()
|
'As per TransactionQueue'
| def send_device_messages(self, destination):
| pos = self._next_pos()
self.device_messages[pos] = destination
self.notifier.on_new_replication_data()
|
'Get rows to be sent over federation between the two tokens
Args:
from_token (int)
to_token(int)
limit (int)
federation_ack (int): Optional. The position where the worker is
explicitly acknowledged it has handled. Allows us to drop
data from before that point'
| def get_replication_rows(self, from_token, to_token, limit, federation_ack=None):
| if (from_token > self.pos):
from_token = (-1)
rows = []
if federation_ack:
self._clear_queue_before_pos(federation_ack)
keys = self.presence_changed.keys()
i = keys.bisect_right(from_token)
j = (keys.bisect_right(to_token) + 1)
dest_user_ids = [(pos, user_id) for pos in keys[... |
'Parse the data from the federation stream into a row.
Args:
data: The value of ``data`` from FederationStreamRow.data, type
depends on the type of stream'
| @staticmethod
def from_data(data):
| raise NotImplementedError()
|
'Serialize this row to be sent over the federation stream.
Returns:
The value to be sent in FederationStreamRow.data. The type depends
on the type of stream.'
| def to_data(self):
| raise NotImplementedError()
|
'Add this row to the appropriate field in the buffer ready for this
to be sent over federation.
We use a buffer so that we can batch up events that have come in at
the same time and send them all at once.
Args:
buff (BufferedToSend)'
| def add_to_buffer(self, buff):
| raise NotImplementedError()
|
'Can we send messages to the given server?
We can\'t send messages to ourselves. If we are running on localhost
then we can only federation with other servers running on localhost.
Otherwise we only federate with servers on a public domain.
Args:
destination(str): The server we are possibly trying to send to.
Returns:
... | def can_send_to(self, destination):
| if (destination == self.server_name):
return False
if self.server_name.startswith('localhost'):
return destination.startswith('localhost')
else:
return (not destination.startswith('localhost'))
|
'This gets called when we have some new events we might want to
send out to other servers.'
| @defer.inlineCallbacks
def notify_new_events(self, current_id):
| self._last_poked_id = max(current_id, self._last_poked_id)
if self._is_processing:
return
try:
self._is_processing = True
while True:
last_token = (yield self.store.get_federation_out_pos('events'))
(next_token, events) = (yield self.store.get_all_new_events_s... |
'Send the new presence states to the appropriate destinations.
This actually queues up the presence states ready for sending and
triggers a background task to process them and send out the transactions.
Args:
states (list(UserPresenceState))'
| @preserve_fn
@defer.inlineCallbacks
def send_presence(self, states):
| self.pending_presence.update({state.user_id: state for state in states if self.is_mine_id(state.user_id)})
if self._processing_pending_presence:
return
self._processing_pending_presence = True
try:
while True:
states_map = self.pending_presence
self.pending_presen... |
'Given a list of states populate self.pending_presence_by_dest and
poke to send a new transaction to each destination
Args:
states (list(UserPresenceState))'
| @measure_func('txnqueue._process_presence')
@defer.inlineCallbacks
def _process_presence_inner(self, states):
| hosts_and_states = (yield get_interested_remotes(self.store, states, self.state))
for (destinations, states) in hosts_and_states:
for destination in destinations:
if (not self.can_send_to(destination)):
continue
self.pending_presence_by_dest.setdefault(destination... |
'Takes a list of PDUs and checks the signatures and hashs of each
one. If a PDU fails its signature check then we check if we have it in
the database and if not then request if from the originating server of
that PDU.
If a PDU fails its content hash check then it is redacted.
The given list of PDUs are not modified, in... | @defer.inlineCallbacks
def _check_sigs_and_hash_and_fetch(self, origin, pdus, outlier=False, include_none=False):
| deferreds = self._check_sigs_and_hashes(pdus)
def callback(pdu):
return pdu
def errback(failure, pdu):
failure.trap(SynapseError)
return None
def try_local_db(res, pdu):
if (not res):
return self.store.get_event(pdu.event_id, allow_rejected=True, allow_none=Tr... |
'Throws a SynapseError if a PDU does not have the correct
signatures.
Returns:
FrozenEvent: Either the given event or it redacted if it failed the
content hash check.'
| def _check_sigs_and_hashes(self, pdus):
| redacted_pdus = [prune_event(pdu) for pdu in pdus]
deferreds = preserve_fn(self.keyring.verify_json_objects_for_server)([(p.origin, p.get_pdu_json()) for p in redacted_pdus])
def callback(_, pdu, redacted):
if (not check_event_content_hash(pdu)):
logger.warn('Event content has b... |
'If we include a list of pdus then we decode then as PDU\'s
automatically.'
| def __init__(self, transaction_id=None, pdus=[], **kwargs):
| if (('edus' in kwargs) and (not kwargs['edus'])):
del kwargs['edus']
super(Transaction, self).__init__(transaction_id=transaction_id, pdus=pdus, **kwargs)
|
'Used to create a new transaction. Will auto fill out
transaction_id and origin_server_ts keys.'
| @staticmethod
def create_new(pdus, **kwargs):
| if ('origin_server_ts' not in kwargs):
raise KeyError("Require 'origin_server_ts' to construct a Transaction")
if ('transaction_id' not in kwargs):
raise KeyError("Require 'transaction_id' to construct a Transaction")
for p in pdus:
p.transaction_id = kw... |
'Clear pdu_destination_tried cache'
| def _clear_tried_cache(self):
| now = self._clock.time_msec()
old_dict = self.pdu_destination_tried
self.pdu_destination_tried = {}
for (event_id, destination_dict) in old_dict.items():
destination_dict = {dest: time for (dest, time) in destination_dict.items() if ((time + PDU_RETRY_TIME_MS) > now)}
if destination_dict... |
'Sends a federation Query to a remote homeserver of the given type
and arguments.
Args:
destination (str): Domain name of the remote homeserver
query_type (str): Category of the query type; should match the
handler name used in register_query_handler().
args (dict): Mapping of strings to strings containing the details
... | @log_function
def make_query(self, destination, query_type, args, retry_on_dns_fail=False, ignore_backoff=False):
| sent_queries_counter.inc(query_type)
return self.transport_layer.make_query(destination, query_type, args, retry_on_dns_fail=retry_on_dns_fail, ignore_backoff=ignore_backoff)
|
'Query device keys for a device hosted on a remote server.
Args:
destination (str): Domain name of the remote homeserver
content (dict): The query content.
Returns:
a Deferred which will eventually yield a JSON object from the
response'
| @log_function
def query_client_keys(self, destination, content, timeout):
| sent_queries_counter.inc('client_device_keys')
return self.transport_layer.query_client_keys(destination, content, timeout)
|
'Query the device keys for a list of user ids hosted on a remote
server.'
| @log_function
def query_user_devices(self, destination, user_id, timeout=30000):
| sent_queries_counter.inc('user_devices')
return self.transport_layer.query_user_devices(destination, user_id, timeout)
|
'Claims one-time keys for a device hosted on a remote server.
Args:
destination (str): Domain name of the remote homeserver
content (dict): The query content.
Returns:
a Deferred which will eventually yield a JSON object from the
response'
| @log_function
def claim_client_keys(self, destination, content, timeout):
| sent_queries_counter.inc('client_one_time_keys')
return self.transport_layer.claim_client_keys(destination, content, timeout)
|
'Requests some more historic PDUs for the given context from the
given destination server.
Args:
dest (str): The remote home server to ask.
context (str): The context to backfill.
limit (int): The maximum number of PDUs to return.
extremities (list): List of PDU id and origins of the first pdus
we have seen from the co... | @defer.inlineCallbacks
@log_function
def backfill(self, dest, context, limit, extremities):
| logger.debug('backfill extrem=%s', extremities)
if (not extremities):
return
transaction_data = (yield self.transport_layer.backfill(dest, context, extremities, limit))
logger.debug('backfill transaction_data=%s', repr(transaction_data))
pdus = [self.event_from_pdu_json(p, outlier=Fals... |
'Requests the PDU with given origin and ID from the remote home
servers.
Will attempt to get the PDU from each destination in the list until
one succeeds.
This will persist the PDU locally upon receipt.
Args:
destinations (list): Which home servers to query
event_id (str): event to fetch
outlier (bool): Indicates wheth... | @defer.inlineCallbacks
@log_function
def get_pdu(self, destinations, event_id, outlier=False, timeout=None):
| if self._get_pdu_cache:
ev = self._get_pdu_cache.get(event_id)
if ev:
defer.returnValue(ev)
pdu_attempts = self.pdu_destination_tried.setdefault(event_id, {})
signed_pdu = None
for destination in destinations:
now = self._clock.time_msec()
last_attempt = pdu_a... |
'Requests all of the `current` state PDUs for a given room from
a remote home server.
Args:
destination (str): The remote homeserver to query for the state.
room_id (str): The id of the room we\'re interested in.
event_id (str): The id of the event we want the state at.
Returns:
Deferred: Results in a list of PDUs.'
| @defer.inlineCallbacks
@log_function
def get_state_for_room(self, destination, room_id, event_id):
| try:
result = (yield self.transport_layer.get_room_state_ids(destination, room_id, event_id=event_id))
state_event_ids = result['pdu_ids']
auth_event_ids = result.get('auth_chain_ids', [])
(fetched_events, failed_to_fetch) = (yield self.get_events([destination], room_id, set((state_e... |
'Fetch events from some remote destinations, checking if we already
have them.
Args:
destinations (list)
room_id (str)
event_ids (list)
return_local (bool): Whether to include events we already have in
the DB in the returned list of events
Returns:
Deferred: A deferred resolving to a 2-tuple where the first is a list o... | @defer.inlineCallbacks
def get_events(self, destinations, room_id, event_ids, return_local=True):
| if return_local:
seen_events = (yield self.store.get_events(event_ids, allow_rejected=True))
signed_events = seen_events.values()
else:
seen_events = (yield self.store.have_events(event_ids))
signed_events = []
failed_to_fetch = set()
missing_events = set(event_ids)
f... |
'Creates an m.room.member event, with context, without participating in the room.
Does so by asking one of the already participating servers to create an
event with proper context.
Note that this does not append any events to any graphs.
Args:
destinations (str): Candidate homeservers which are probably
participating i... | @defer.inlineCallbacks
def make_membership_event(self, destinations, room_id, user_id, membership, content={}):
| valid_memberships = {Membership.JOIN, Membership.LEAVE}
if (membership not in valid_memberships):
raise RuntimeError(("make_membership_event called with membership='%s', must be one of %s" % (membership, ','.join(valid_memberships))))
for destination in destinations:
... |
'Sends a join event to one of a list of homeservers.
Doing so will cause the remote server to add the event to the graph,
and send the event out to the rest of the federation.
Args:
destinations (str): Candidate homeservers which are probably
participating in the room.
pdu (BaseEvent): event to be sent
Return:
Deferred... | @defer.inlineCallbacks
def send_join(self, destinations, pdu):
| for destination in destinations:
if (destination == self.server_name):
continue
try:
time_now = self._clock.time_msec()
(_, content) = (yield self.transport_layer.send_join(destination=destination, room_id=pdu.room_id, event_id=pdu.event_id, content=pdu.get_pdu_js... |
'Sends a leave event to one of a list of homeservers.
Doing so will cause the remote server to add the event to the graph,
and send the event out to the rest of the federation.
This is mostly useful to reject received invites.
Args:
destinations (str): Candidate homeservers which are probably
participating in the room.... | @defer.inlineCallbacks
def send_leave(self, destinations, pdu):
| for destination in destinations:
if (destination == self.server_name):
continue
try:
time_now = self._clock.time_msec()
(_, content) = (yield self.transport_layer.send_leave(destination=destination, room_id=pdu.room_id, event_id=pdu.event_id, content=pdu.get_pdu_j... |
'Params:
destination (str)
event_it (str)
local_auth (list)'
| @defer.inlineCallbacks
def query_auth(self, destination, room_id, event_id, local_auth):
| time_now = self._clock.time_msec()
send_content = {'auth_chain': [e.get_pdu_json(time_now) for e in local_auth]}
(code, content) = (yield self.transport_layer.send_query_auth(destination=destination, room_id=room_id, event_id=event_id, content=send_content))
auth_chain = [self.event_from_pdu_json(e) for... |
'Tries to fetch events we are missing. This is called when we receive
an event without having received all of its ancestors.
Args:
destination (str)
room_id (str)
earliest_events_ids (list): List of event ids. Effectively the
events we expected to receive, but haven\'t. `get_missing_events`
should only return events th... | @defer.inlineCallbacks
def get_missing_events(self, destination, room_id, earliest_events_ids, latest_events, limit, min_depth, timeout):
| try:
content = (yield self.transport_layer.get_missing_events(destination=destination, room_id=room_id, earliest_events=earliest_events_ids, latest_events=[e.event_id for e in latest_events], limit=limit, min_depth=min_depth, timeout=timeout))
events = [self.event_from_pdu_json(e) for e in content.g... |
'Called on PUT /send/<transaction_id>/
Args:
request (twisted.web.http.Request): The HTTP request.
transaction_id (str): The transaction_id associated with this
request. This is *not* None.
Returns:
Deferred: Results in a tuple of `(code, response)`, where
`response` is a python dict to be converted into JSON that is
u... | @defer.inlineCallbacks
def on_PUT(self, origin, content, query, transaction_id):
| try:
transaction_data = content
logger.debug('Decoded %s: %s', transaction_id, str(transaction_data))
logger.info('Received txn %s from %s. (PDUs: %d, EDUs: %d, failures: %d)', transaction_id, origin, len(transaction_data.get('pdus', [])), len(transaction_... |
'Requests all state for a given room from the given server at the
given event.
Args:
destination (str): The host name of the remote home server we want
to get the state from.
context (str): The name of the context we want the state of
event_id (str): The event we want the context at.
Returns:
Deferred: Results in a dic... | @log_function
def get_room_state(self, destination, room_id, event_id):
| logger.debug('get_room_state dest=%s, room=%s', destination, room_id)
path = (PREFIX + ('/state/%s/' % room_id))
return self.client.get_json(destination, path=path, args={'event_id': event_id})
|
'Requests all state for a given room from the given server at the
given event. Returns the state\'s event_id\'s
Args:
destination (str): The host name of the remote home server we want
to get the state from.
context (str): The name of the context we want the state of
event_id (str): The event we want the context at.
Re... | @log_function
def get_room_state_ids(self, destination, room_id, event_id):
| logger.debug('get_room_state_ids dest=%s, room=%s', destination, room_id)
path = (PREFIX + ('/state_ids/%s/' % room_id))
return self.client.get_json(destination, path=path, args={'event_id': event_id})
|
'Requests the pdu with give id and origin from the given server.
Args:
destination (str): The host name of the remote home server we want
to get the state from.
event_id (str): The id of the event being requested.
timeout (int): How long to try (in ms) the destination for before
giving up. None indicates no timeout.
Re... | @log_function
def get_event(self, destination, event_id, timeout=None):
| logger.debug('get_pdu dest=%s, event_id=%s', destination, event_id)
path = (PREFIX + ('/event/%s/' % (event_id,)))
return self.client.get_json(destination, path=path, timeout=timeout)
|
'Requests `limit` previous PDUs in a given context before list of
PDUs.
Args:
dest (str)
room_id (str)
event_tuples (list)
limt (int)
Returns:
Deferred: Results in a dict received from the remote homeserver.'
| @log_function
def backfill(self, destination, room_id, event_tuples, limit):
| logger.debug('backfill dest=%s, room_id=%s, event_tuples=%s, limit=%s', destination, room_id, repr(event_tuples), str(limit))
if (not event_tuples):
return
path = (PREFIX + ('/backfill/%s/' % (room_id,)))
args = {'v': event_tuples, 'limit': [str(limit)]}
return self.client.get_js... |
'Sends the given Transaction to its destination
Args:
transaction (Transaction)
Returns:
Deferred: Results of the deferred is a tuple in the form of
(response_code, response_body) where the response_body is a
python dict decoded from json'
| @defer.inlineCallbacks
@log_function
def send_transaction(self, transaction, json_data_callback=None):
| logger.debug('send_data dest=%s, txid=%s', transaction.destination, transaction.transaction_id)
if (transaction.destination == self.server_name):
raise RuntimeError('Transport layer cannot send to itself!')
json_data = transaction.get_dict()
response = (yield self.client.put... |
'Asks a remote server to build and sign us a membership event
Note that this does not append any events to any graphs.
Args:
destination (str): address of remote homeserver
room_id (str): room to join/leave
user_id (str): user to be joined/left
membership (str): one of join/leave
Returns:
Deferred: Succeeds when we get... | @defer.inlineCallbacks
@log_function
def make_membership_event(self, destination, room_id, user_id, membership):
| valid_memberships = {Membership.JOIN, Membership.LEAVE}
if (membership not in valid_memberships):
raise RuntimeError(("make_membership_event called with membership='%s', must be one of %s" % (membership, ','.join(valid_memberships))))
path = (PREFIX + ('/make_%s/%s/%s' % (mem... |
'Query the device keys for a list of user ids hosted on a remote
server.
Request:
"device_keys": {
"<user_id>": ["<device_id>"]
Response:
"device_keys": {
"<user_id>": {
"<device_id>": {...}
Args:
destination(str): The server to query.
query_content(dict): The user ids to query.
Returns:
A dict containg the device keys... | @defer.inlineCallbacks
@log_function
def query_client_keys(self, destination, query_content, timeout):
| path = (PREFIX + '/user/keys/query')
content = (yield self.client.post_json(destination=destination, path=path, data=query_content, timeout=timeout))
defer.returnValue(content)
|
'Query the devices for a user id hosted on a remote server.
Response:
"stream_id": "...",
"devices": [ { ... } ]
Args:
destination(str): The server to query.
query_content(dict): The user ids to query.
Returns:
A dict containg the device keys.'
| @defer.inlineCallbacks
@log_function
def query_user_devices(self, destination, user_id, timeout):
| path = ((PREFIX + '/user/devices/') + user_id)
content = (yield self.client.get_json(destination=destination, path=path, timeout=timeout))
defer.returnValue(content)
|
'Claim one-time keys for a list of devices hosted on a remote server.
Request:
"one_time_keys": {
"<user_id>": {
"<device_id>": "<algorithm>"
Response:
"device_keys": {
"<user_id>": {
"<device_id>": {
"<algorithm>:<key_id>": "<key_base64>"
Args:
destination(str): The server to query.
query_content(dict): The user ids t... | @defer.inlineCallbacks
@log_function
def claim_client_keys(self, destination, query_content, timeout):
| path = (PREFIX + '/user/keys/claim')
content = (yield self.client.post_json(destination=destination, path=path, data=query_content, timeout=timeout))
defer.returnValue(content)
|
'Sets the handler that the replication layer will use to communicate
receipt of new PDUs from other home servers. The required methods are
documented on :py:class:`.ReplicationHandler`.'
| def set_handler(self, handler):
| self.handler = handler
|
'Sets the handler callable that will be used to handle an incoming
federation Query of the given type.
Args:
query_type (str): Category name of the query, which should match
the string used by make_query.
handler (callable): Invoked to handle incoming queries of this type
handler is invoked as:
result = handler(args)
w... | def register_query_handler(self, query_type, handler):
| if (query_type in self.query_handlers):
raise KeyError(('Already have a Query handler for %s' % (query_type,)))
self.query_handlers[query_type] = handler
|
'Content is a dict with keys::
auth_chain (list): A list of events that give the auth chain.
missing (list): A list of event_ids indicating what the other
side (`origin`) think we\'re missing.
rejects (dict): A mapping from event_id to a 2-tuple of reason
string and a proof (or None) of why the event was rejected.
The ... | @defer.inlineCallbacks
def on_query_auth_request(self, origin, content, room_id, event_id):
| with (yield self._server_linearizer.queue((origin, room_id))):
auth_chain = [self.event_from_pdu_json(e) for e in content['auth_chain']]
signed_auth = (yield self._check_sigs_and_hash_and_fetch(origin, auth_chain, outlier=True))
ret = (yield self.handler.on_query_auth(origin, event_id, signe... |
'Get a PDU from the database with given origin and id.
Returns:
Deferred: Results in a `Pdu`.'
| @log_function
def _get_persisted_pdu(self, origin, event_id, do_auth=True):
| return self.handler.get_persisted_pdu(origin, event_id, do_auth=do_auth)
|
'Returns a new Transaction containing the given PDUs suitable for
transmission.'
| def _transaction_from_pdus(self, pdu_list):
| time_now = self._clock.time_msec()
pdus = [p.get_pdu_json(time_now) for p in pdu_list]
return Transaction(origin=self.server_name, pdus=pdus, origin_server_ts=int(time_now), destination=None)
|
'Process a PDU received in a federation /send/ transaction.
Args:
origin (str): server which sent the pdu
pdu (FrozenEvent): received pdu
Returns (Deferred): completes with None
Raises: FederationError if the signatures / hash do not match'
| @defer.inlineCallbacks
def _handle_received_pdu(self, origin, pdu):
| try:
pdu = (yield self._check_sigs_and_hash(pdu))
except SynapseError as e:
raise FederationError('ERROR', e.code, e.msg, affected=pdu.event_id)
(yield self.handler.on_receive_pdu(origin, pdu, get_missing=True))
|
'Parse the string given by \'s\' into a structure object.'
| @classmethod
def from_string(cls, s):
| if ((len(s) < 1) or (s[0] != cls.SIGIL)):
raise SynapseError(400, ("Expected %s string to start with '%s'" % (cls.__name__, cls.SIGIL)))
parts = s[1:].split(':', 1)
if (len(parts) != 2):
raise SynapseError(400, ("Expected %s of the form '%slocalname:domain'" ... |
'Return a string encoding the fields of the structure object.'
| def to_string(self):
| return ('%s%s:%s' % (self.SIGIL, self.localpart, self.domain))
|
'Does this token contain events that the other doesn\'t?'
| def is_after(self, other):
| return ((other.room_stream_id < self.room_stream_id) or (int(other.presence_key) < int(self.presence_key)) or (int(other.typing_key) < int(self.typing_key)) or (int(other.receipt_key) < int(self.receipt_key)) or (int(other.account_data_key) < int(self.account_data_key)) or (int(other.push_rules_key) < int(self.push... |
'Advance the given key in the token to a new value if and only if the
new value is after the old value.'
| def copy_and_advance(self, key, new_value):
| new_token = self.copy_and_replace(key, new_value)
if (key == 'room_key'):
new_id = new_token.room_stream_id
old_id = self.room_stream_id
else:
new_id = int(getattr(new_token, key))
old_id = int(getattr(self, key))
if (old_id < new_id):
return new_token
else:
... |
'Looks the key up in the caches.
Args:
key(tuple)
default: What is returned if key is not in the caches. If not
specified then function throws KeyError instead
callback(fn): Gets called when the entry in the cache is invalidated
update_metrics (bool): whether to update the cache hit rate metrics
Returns:
Either a Defer... | def get(self, key, default=_CacheSentinel, callback=None, update_metrics=True):
| callbacks = ([callback] if callback else [])
val = self._pending_deferred_cache.get(key, _CacheSentinel)
if (val is not _CacheSentinel):
if (val.sequence == self.sequence):
val.callbacks.update(callbacks)
if update_metrics:
self.metrics.inc_hits()
... |
'Args:
orig (function)
cached_method_name (str): The name of the chached method.
list_name (str): Name of the argument which is the bulk lookup list
num_args (int): number of positional arguments (excluding ``self``,
but including list_name) to use as cache keys. Defaults to all
named args of the function.
inlineCallba... | def __init__(self, orig, cached_method_name, list_name, num_args=None, inlineCallbacks=False):
| super(CacheListDescriptor, self).__init__(orig, num_args=num_args, inlineCallbacks=inlineCallbacks)
self.list_name = list_name
self.list_pos = self.arg_names.index(self.list_name)
self.cached_method_name = cached_method_name
self.sentinel = object()
if (self.list_name not in self.arg_names):
... |
'Args:
cache_name (str): Name of this cache, used for logging.
clock (Clock)
max_len (int): Max size of dict. If the dict grows larger than this
then the oldest items get automatically evicted. Default is 0,
which indicates there is no max limit.
expiry_ms (int): How long before an item is evicted from the cache
in mil... | def __init__(self, cache_name, clock, max_len=0, expiry_ms=0, reset_expiry_on_get=False, iterable=False):
| self._cache_name = cache_name
self._clock = clock
self._max_len = max_len
self._expiry_ms = expiry_ms
self._reset_expiry_on_get = reset_expiry_on_get
self._cache = OrderedDict()
self.metrics = register_cache(cache_name, self)
self.iterable = iterable
self._size_estimate = 0
|
'Fetch an entry out of the cache
Args:
key
dict_key(list): If given a set of keys then return only those keys
that exist in the cache.
Returns:
DictionaryEntry'
| def get(self, key, dict_keys=None):
| entry = self.cache.get(key, self.sentinel)
if (entry is not self.sentinel):
self.metrics.inc_hits()
if (dict_keys is None):
return DictionaryEntry(entry.full, entry.known_absent, dict(entry.value))
else:
return DictionaryEntry(entry.full, entry.known_absent, {k: e... |
'Updates the entry in the cache
Args:
sequence
key
value (dict): The value to update the cache with.
full (bool): Whether the given value is the full dict, or just a
partial subset there of. If not full then any existing entries
for the key will be updated.
known_absent (set): Set of keys that we know don\'t exist in t... | def update(self, sequence, key, value, full=False, known_absent=None):
| self.check_thread()
if (self.sequence == sequence):
if (known_absent is None):
known_absent = set()
if full:
self._insert(key, value, known_absent)
else:
self._update_or_insert(key, value, known_absent)
|
'Returns True if the entity may have been updated since stream_pos'
| def has_entity_changed(self, entity, stream_pos):
| assert ((type(stream_pos) is int) or (type(stream_pos) is long))
if (stream_pos < self._earliest_known_stream_pos):
self.metrics.inc_misses()
return True
latest_entity_change_pos = self._entity_to_key.get(entity, None)
if (latest_entity_change_pos is None):
self.metrics.inc_hits(... |
'Returns subset of entities that have had new things since the
given position. If the position is too old it will just return the given list.'
| def get_entities_changed(self, entities, stream_pos):
| assert (type(stream_pos) is int)
if (stream_pos >= self._earliest_known_stream_pos):
keys = self._cache.keys()
i = keys.bisect_right(stream_pos)
result = set((self._cache[k] for k in keys[i:])).intersection(entities)
self.metrics.inc_hits()
else:
result = entities
... |
'Returns if any entity has changed'
| def has_any_entity_changed(self, stream_pos):
| assert (type(stream_pos) is int)
if (stream_pos >= self._earliest_known_stream_pos):
self.metrics.inc_hits()
keys = self._cache.keys()
i = keys.bisect_right(stream_pos)
return (i < len(keys))
else:
self.metrics.inc_misses()
return True
|
'Returns all entites that have had new things since the given
position. If the position is too old it will return None.'
| def get_all_entities_changed(self, stream_pos):
| assert (type(stream_pos) is int)
if (stream_pos >= self._earliest_known_stream_pos):
keys = self._cache.keys()
i = keys.bisect_right(stream_pos)
return [self._cache[k] for k in keys[i:]]
else:
return None
|
'Informs the cache that the entity has been changed at the given
position.'
| def entity_has_changed(self, entity, stream_pos):
| assert (type(stream_pos) is int)
if (stream_pos > self._earliest_known_stream_pos):
old_pos = self._entity_to_key.get(entity, None)
if (old_pos is not None):
stream_pos = max(stream_pos, old_pos)
self._cache.pop(old_pos, None)
self._cache[stream_pos] = entity
... |
'Returns an upper bound of the stream id of the last change to an
entity.'
| def get_max_pos_of_last_change(self, entity):
| return self._entity_to_key.get(entity, self._earliest_known_stream_pos)
|
'Get the current logging context from thread local storage'
| @classmethod
def current_context(cls):
| return getattr(cls.thread_local, 'current_context', cls.sentinel)
|
'Set the current logging context in thread local storage
Args:
context(LoggingContext): The context to activate.
Returns:
The context that was previously active'
| @classmethod
def set_current_context(cls, context):
| current = cls.current_context()
if (current is not context):
current.stop()
cls.thread_local.current_context = context
context.start()
return current
|
'Enters this logging context into thread local storage'
| def __enter__(self):
| old_context = self.set_current_context(self)
if (self.previous_context != old_context):
logger.warn('Expected previous context %r, found %r', self.previous_context, old_context)
self.alive = True
return self
|
'Restore the logging context in thread local storage to the state it
was before this context was entered.
Returns:
None to avoid suppressing any exeptions that were thrown.'
| def __exit__(self, type, value, traceback):
| current = self.set_current_context(self.previous_context)
if (current is not self):
if (current is self.sentinel):
logger.debug('Expected logging context %s has been lost', self)
else:
logger.warn('Current logging context %s is not expe... |
'Copy fields from this context to the record'
| def copy_to(self, record):
| for (key, value) in self.__dict__.items():
setattr(record, key, value)
(record.ru_utime, record.ru_stime) = self.get_resource_usage()
|
'Add each fields from the logging contexts to the record.
Returns:
True to include the record in the log output.'
| def filter(self, record):
| context = LoggingContext.current_context()
for (key, value) in self.defaults.items():
setattr(record, key, value)
context.copy_to(record)
return True
|
'Captures the current logging context'
| def __enter__(self):
| self.current_context = LoggingContext.set_current_context(self.new_context)
if self.current_context:
self.has_parent = (self.current_context.previous_context is not None)
if (not self.current_context.alive):
logger.debug('Entering dead context: %s', self.current_context)
|
'Restores the current logging context'
| def __exit__(self, type, value, traceback):
| context = LoggingContext.set_current_context(self.current_context)
if (context != self.new_context):
logger.debug('Unexpected logging context: %s is not %s', context, self.new_context)
if (self.current_context is not LoggingContext.sentinel):
if (not self.current_context.al... |
'Returns the current system time in seconds since epoch.'
| def time(self):
| return time.time()
|
'Returns the current system time in miliseconds since epoch.'
| def time_msec(self):
| return int((self.time() * 1000))
|
'Call a function repeatedly.
Waits `msec` initially before calling `f` for the first time.
Args:
f(function): The function to call repeatedly.
msec(float): How long to wait between calls in milliseconds.'
| def looping_call(self, f, msec):
| l = task.LoopingCall(f)
l.start((msec / 1000.0), now=False)
return l
|
'Call something later
Args:
delay(float): How long to wait in seconds.
callback(function): Function to call
*args: Postional arguments to pass to function.
**kwargs: Key arguments to pass to function.'
| def call_later(self, delay, callback, *args, **kwargs):
| def wrapped_callback(*args, **kwargs):
with PreserveLoggingContext():
callback(*args, **kwargs)
with PreserveLoggingContext():
return reactor.callLater(delay, wrapped_callback, *args, **kwargs)
|
'Marks the destination as "down" if an exception is thrown in the
context, except for CodeMessageException with code < 500.
If no exception is raised, marks the destination as "up".
Args:
destination (str)
clock (Clock)
store (DataStore)
retry_interval (int): The next retry interval taken from the
database in milliseco... | def __init__(self, destination, clock, store, retry_interval, min_retry_interval=((10 * 60) * 1000), max_retry_interval=(((24 * 60) * 60) * 1000), multiplier_retry_interval=5, backoff_on_404=False):
| self.clock = clock
self.store = store
self.destination = destination
self.retry_interval = retry_interval
self.min_retry_interval = min_retry_interval
self.max_retry_interval = max_retry_interval
self.multiplier_retry_interval = multiplier_retry_interval
self.backoff_on_404 = backoff_on_... |
'Args:
bucket_size (int): Size of buckets in ms. Corresponds roughly to the
accuracy of the timer.'
| def __init__(self, bucket_size=5000):
| self.bucket_size = bucket_size
self.entries = []
self.current_tick = 0
|
'Inserts object into timer.
Args:
now (int): Current time in msec
obj (object): Object to be inserted
then (int): When to return the object strictly after.'
| def insert(self, now, obj, then):
| then_key = (int((then / self.bucket_size)) + 1)
if self.entries:
min_key = self.entries[0].end_key
max_key = self.entries[(-1)].end_key
if (then_key <= max_key):
self.entries[(max(min_key, then_key) - min_key)].queue.append(obj)
return
next_key = (int((now / s... |
'Fetch any objects that have timed out
Args:
now (ms): Current time in msec
Returns:
list: List of objects that have timed out'
| def fetch(self, now):
| now_key = int((now / self.bucket_size))
ret = []
while (self.entries and (self.entries[0].end_key <= now_key)):
ret.extend(self.entries.pop(0).queue)
return ret
|
'Args:
clock (Clock)
window_size (int): The window size in milliseconds.
sleep_limit (int): The number of requests received in the last
`window_size` milliseconds before we artificially start
delaying processing of requests.
sleep_msec (int): The number of milliseconds to delay processing
of incoming requests by.
rejec... | def __init__(self, clock, window_size, sleep_limit, sleep_msec, reject_limit, concurrent_requests):
| self.clock = clock
self.window_size = window_size
self.sleep_limit = sleep_limit
self.sleep_msec = sleep_msec
self.reject_limit = reject_limit
self.concurrent_requests = concurrent_requests
self.ratelimiters = {}
|
'Used to ratelimit an incoming request from given host
Example usage:
with rate_limiter.ratelimit(origin) as wait_deferred:
yield wait_deferred
# Handle request ...
Args:
host (str): Origin of incoming request.
Returns:
_PerHostRatelimiter'
| def ratelimit(self, host):
| return self.ratelimiters.setdefault(host, _PerHostRatelimiter(clock=self.clock, window_size=self.window_size, sleep_limit=self.sleep_limit, sleep_msec=self.sleep_msec, reject_limit=self.reject_limit, concurrent_requests=self.concurrent_requests)).ratelimit()
|
'Observe the underlying deferred.
Can return either a deferred if the underlying deferred is still pending
(or has failed), or the actual value. Callers may need to use maybeDeferred.'
| def observe(self):
| if (not self._result):
d = defer.Deferred()
def remove(r):
self._observers.discard(d)
return r
d.addBoth(remove)
self._observers.add(d)
return d
else:
(success, res) = self._result
return (res if success else defer.fail(res))
|
'Args:
max_count(int): The maximum number of concurrent access'
| def __init__(self, max_count):
| self.max_count = max_count
self.key_to_defer = {}
|
'Takes the dict of `kwargs` and loads all keys that are *valid*
(i.e., are included in the `valid_keys` list) into the dictionary`
instance variable.
Any keys that aren\'t recognized are added to the `unrecognized_keys`
attribute.
Args:
**kwargs: Attributes associated with this protocol unit.'
| def __init__(self, **kwargs):
| for required_key in self.required_keys:
if (required_key not in kwargs):
raise RuntimeError(('Key %s is required' % required_key))
self.unrecognized_keys = {}
for (k, v) in kwargs.items():
if ((k in self.valid_keys) or (k in self.internal_keys)):
self.__dict_... |
'Converts this protocol unit into a :py:class:`dict`, ready to be
encoded as JSON.
The keys it encodes are: `valid_keys` - `internal_keys`
Returns
dict'
| def get_dict(self):
| d = {k: _encode(v) for (k, v) in self.__dict__.items() if ((k in self.valid_keys) and (k not in self.internal_keys))}
d.update(self.unrecognized_keys)
return d
|
'Adds a new callable to the observer list which will be invoked by
the \'fire\' method.
Each observer callable may return a Deferred.'
| def observe(self, observer):
| self.observers.append(observer)
|
'Invokes every callable in the observer list, passing in the args and
kwargs. Exceptions thrown by observers are logged but ignored. It is
not an error to fire a signal with no observers.
Returns a Deferred that will complete when all the observers have
completed.'
| @defer.inlineCallbacks
def fire(self, *args, **kwargs):
| def do(observer):
def eb(failure):
logger.warning('%s signal observer %s failed: %r', self.name, observer, failure, exc_info=(failure.type, failure.value, failure.getTracebackObject()))
if (not self.suppress_failures):
return failure
return defe... |
'A helper function for fetch_or_execute which extracts
a transaction key from the given request.
See:
fetch_or_execute'
| def fetch_or_execute_request(self, request, fn, *args, **kwargs):
| return self.fetch_or_execute(get_transaction_key(request), fn, *args, **kwargs)
|
'Fetches the response for this transaction, or executes the given function
to produce a response for this transaction.
Args:
txn_key (str): A key to ensure idempotency should fetch_or_execute be
called again at a later point in time.
fn (function): A function which returns a tuple of
(response_code, response_dict).
*ar... | def fetch_or_execute(self, txn_key, fn, *args, **kwargs):
| try:
return self.transactions[txn_key][0].observe()
except (KeyError, IndexError):
pass
deferred = fn(*args, **kwargs)
def remove_from_map(err):
self.transactions.pop(txn_key, None)
return err
deferred.addErrback(remove_from_map)
observable = ObservableDeferred(de... |
'Args:
hs (synapse.server.HomeServer): server'
| def __init__(self, hs):
| super(EmailRegisterRequestTokenRestServlet, self).__init__()
self.hs = hs
self.identity_handler = hs.get_handlers().identity_handler
|
'Args:
hs (synapse.server.HomeServer): server'
| def __init__(self, hs):
| super(MsisdnRegisterRequestTokenRestServlet, self).__init__()
self.hs = hs
self.identity_handler = hs.get_handlers().identity_handler
|
'Args:
hs (synapse.server.HomeServer): server'
| def __init__(self, hs):
| super(UsernameAvailabilityRestServlet, self).__init__()
self.hs = hs
self.registration_handler = hs.get_handlers().registration_handler
self.ratelimiter = FederationRateLimiter(hs.get_clock(), window_size=2000, sleep_limit=1, sleep_msec=1000, reject_limit=1, concurrent_requests=1)
|
'Args:
hs (synapse.server.HomeServer): server'
| def __init__(self, hs):
| super(RegisterRestServlet, self).__init__()
self.hs = hs
self.auth = hs.get_auth()
self.store = hs.get_datastore()
self.auth_handler = hs.get_auth_handler()
self.registration_handler = hs.get_handlers().registration_handler
self.identity_handler = hs.get_handlers().identity_handler
self.... |
'Add an email address as a 3pid identifier
Also adds an email pusher for the email address, if configured in the
HS config
Also optionally binds emails to the given user_id on the identity server
Args:
user_id (str): id of user
threepid (object): m.login.email.identity auth response
token (str): access_token for the us... | @defer.inlineCallbacks
def _register_email_threepid(self, user_id, threepid, token, bind_email):
| reqd = ('medium', 'address', 'validated_at')
if any(((x not in threepid) for x in reqd)):
logger.info("Can't add incomplete 3pid")
return
(yield self.auth_handler.add_threepid(user_id, threepid['medium'], threepid['address'], threepid['validated_at']))
if (self.hs.config.email_e... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.