desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Returns:
int'
| def get_current_token(self):
| return self._current
|
'Helper method to start a replication connection to the remote server
using TCP.'
| def start_replication(self, hs):
| client_name = hs.config.worker_name
factory = ReplicationClientFactory(hs, client_name, self)
host = hs.config.worker_replication_host
port = hs.config.worker_replication_port
reactor.connectTCP(host, port, factory)
|
'Called when we get new replication data. By default this just pokes
the slave store.
Can be overriden in subclasses to handle more.'
| def on_rdata(self, stream_name, token, rows):
| logger.info('Received rdata %s -> %s', stream_name, token)
self.store.process_replication_rows(stream_name, token, rows)
|
'Called when we get new position data. By default this just pokes
the slave store.
Can be overriden in subclasses to handle more.'
| def on_position(self, stream_name, token):
| self.store.process_replication_rows(stream_name, token, [])
|
'When we received a SYNC we wake up any deferreds that were waiting
for the sync with the given data.
Used by tests.'
| def on_sync(self, data):
| d = self.awaiting_syncs.pop(data, None)
if d:
d.callback(data)
|
'Called when a new connection has been established and we need to
subscribe to streams.
Returns a dictionary of stream name to token.'
| def get_streams_to_replicate(self):
| args = self.store.stream_positions()
user_account_data = args.pop('user_account_data', None)
room_account_data = args.pop('room_account_data', None)
if user_account_data:
args['account_data'] = user_account_data
elif room_account_data:
args['account_data'] = room_account_data
ret... |
'Get the list of currently syncing users (if any). This is called
when a connection has been established and we need to send the
currently syncing users. (Overriden by the synchrotron\'s only)'
| def get_currently_syncing_users(self):
| return []
|
'Send a command to master (when we get establish a connection if we
don\'t have one already.)'
| def send_command(self, cmd):
| if self.connection:
self.connection.send_command(cmd)
else:
logger.warn('Queuing command as not connected: %r', cmd.NAME)
self.pending_commands.append(cmd)
|
'Ack data for the federation stream. This allows the master to drop
data stored purely in memory.'
| def send_federation_ack(self, token):
| self.send_command(FederationAckCommand(token))
|
'Poke the master that a user has started/stopped syncing.'
| def send_user_sync(self, user_id, is_syncing, last_sync_ms):
| self.send_command(UserSyncCommand(user_id, is_syncing, last_sync_ms))
|
'Poke the master to remove a pusher for a user'
| def send_remove_pusher(self, app_id, push_key, user_id):
| cmd = RemovePusherCommand(app_id, push_key, user_id)
self.send_command(cmd)
|
'Poke the master to invalidate a cache.'
| def send_invalidate_cache(self, cache_func, keys):
| cmd = InvalidateCacheCommand(cache_func.__name__, keys)
self.send_command(cmd)
|
'Tell the master that the user made a request.'
| def send_user_ip(self, user_id, access_token, ip, user_agent, device_id, last_seen):
| cmd = UserIpCommand(user_id, access_token, ip, user_agent, device_id, last_seen)
self.send_command(cmd)
|
'Returns a deferred that is resolved when we receive a SYNC command
with given data.
Used by tests.'
| def await_sync(self, data):
| return self.awaiting_syncs.setdefault(data, defer.Deferred())
|
'Called when a connection has been established (or lost with None).'
| def update_connection(self, connection):
| self.connection = connection
if connection:
for cmd in self.pending_commands:
connection.send_command(cmd)
self.pending_commands = []
|
'Periodically sends a ping and checks if we should close the connection
due to the other side timing out.'
| def send_ping(self):
| now = self.clock.time_msec()
if self.time_we_closed:
if ((now - self.time_we_closed) > PING_TIMEOUT_MS):
logger.info('[%s] Failed to close connection gracefully, aborting', self.id())
self.transport.abortConnection()
else:
if ((now - self.last_sent_c... |
'Called when we\'ve received a line'
| def lineReceived(self, line):
| if (line.strip() == ''):
return
line = line.decode('utf-8')
(cmd_name, rest_of_line) = line.split(' ', 1)
if (cmd_name not in self.VALID_INBOUND_COMMANDS):
logger.error('[%s] invalid command %s', self.id(), cmd_name)
self.send_error('invalid command: %s', cmd_na... |
'Send an error to remote and close the connection.'
| def send_error(self, error_string, *args):
| self.send_command(ErrorCommand((error_string % args)))
self.close()
|
'Send a command if connection has been established.
Args:
cmd (Command)
do_buffer (bool): Whether to buffer the message or always attempt
to send the command. This is mostly used to send an error
message if we\'re about to close the connection due our buffers
becoming full.'
| def send_command(self, cmd, do_buffer=True):
| if (self.state == ConnectionStates.CLOSED):
logger.info('[%s] Not sending, connection closed', self.id())
return
if (do_buffer and (self.state != ConnectionStates.ESTABLISHED)):
self._queue_command(cmd)
return
self.outbound_commands_counter.inc(cmd.NAME)
strin... |
'Queue the command until the connection is ready to write to again.'
| def _queue_command(self, cmd):
| logger.info('[%s] Queing as conn %r, cmd: %r', self.id(), self.state, cmd)
self.pending_commands.append(cmd)
if (len(self.pending_commands) > self.max_line_buffer):
logger.error('[%s] Remote failed to keep up', self.id())
self.send_command(ErrorCommand('Faile... |
'Send any queued commandes'
| def _send_pending_commands(self):
| pending = self.pending_commands
self.pending_commands = []
for cmd in pending:
self.send_command(cmd)
|
'This is called when both the kernel send buffer and the twisted
tcp connection send buffers have become full.
We don\'t actually have any control over those sizes, so we buffer some
commands ourselves before knifing the connection due to the remote
failing to keep up.'
| def pauseProducing(self):
| logger.info('[%s] Pause producing', self.id())
self.state = ConnectionStates.PAUSED
|
'The remote has caught up after we started buffering!'
| def resumeProducing(self):
| logger.info('[%s] Resume producing', self.id())
self.state = ConnectionStates.ESTABLISHED
self._send_pending_commands()
|
'We\'re never going to send any more data (normally because either
we or the remote has closed the connection)'
| def stopProducing(self):
| logger.info('[%s] Stop producing', self.id())
self.on_connection_closed()
|
'Subscribe the remote to a streams.
This invloves checking if they\'ve missed anything and sending those
updates down if they have. During that time new updates for the stream
are queued and sent once we\'ve sent down any missed updates.'
| @defer.inlineCallbacks
def subscribe_to_stream(self, stream_name, token):
| self.replication_streams.discard(stream_name)
self.connecting_streams.add(stream_name)
try:
(updates, current_token) = (yield self.streamer.get_stream_updates(stream_name, token))
for update in updates:
(token, row) = (update[0], update[1])
self.send_command(RdataComm... |
'Called when a new update is available to stream to clients.
We need to check if the client is interested in the stream or not'
| def stream_update(self, stream_name, token, data):
| if (stream_name in self.replication_streams):
self.send_command(RdataCommand(stream_name, token, data))
elif (stream_name in self.connecting_streams):
logger.debug('[%s] Queuing RDATA %r %r', self.id(), stream_name, token)
self.pending_rdata.setdefault(stream_name, []).append... |
'Send the subscription request to the server'
| def replicate(self, stream_name, token):
| if (stream_name not in STREAMS_MAP):
raise Exception(('Invalid stream name %r' % (stream_name,)))
logger.info('[%s] Subscribing to replication stream: %r from %r', self.id(), stream_name, token)
self.send_command(ReplicateCommand(stream_name, token))
|
'Updates `upto_token` to "now", which updates up until which point
get_updates[_since] will fetch rows till.'
| def advance_current_token(self):
| self.upto_token = self.current_token()
|
'Called when the stream should advance but the updates would be discarded,
e.g. when there are no currently connected workers.'
| def discard_updates_and_advance(self):
| self.upto_token = self.current_token()
self.last_token = self.upto_token
|
'Gets all updates since the last time this function was called (or
since the stream was constructed if it hadn\'t been called before),
until the `upto_token`
Returns:
(list(ROW_TYPE), int): list of updates plus the token used as an
upper bound of the updates (i.e. the "current token")'
| @defer.inlineCallbacks
def get_updates(self):
| (updates, current_token) = (yield self.get_updates_since(self.last_token))
self.last_token = current_token
defer.returnValue((updates, current_token))
|
'Like get_updates except allows specifying from when we should
stream updates
Returns:
(list(ROW_TYPE), int): list of updates plus the token used as an
upper bound of the updates (i.e. the "current token")'
| @defer.inlineCallbacks
def get_updates_since(self, from_token):
| if (from_token in ('NOW', 'now')):
defer.returnValue(([], self.upto_token))
current_token = self.upto_token
from_token = int(from_token)
if (from_token == current_token):
defer.returnValue(([], current_token))
if self._LIMITED:
rows = (yield self.update_function(from_token, c... |
'Gets the current token of the underlying streams. Should be provided
by the sub classes
Returns:
int'
| def current_token(self):
| raise NotImplementedError()
|
'Get updates between from_token and to_token. If Stream._LIMITED is
True then limit is provided, otherwise it\'s not.
Returns:
Deferred(list(tuple)): the first entry in the tuple is the token for
that update, and the rest of the tuple gets used to construct
a ``ROW_TYPE`` instance'
| def update_function(self, from_token, current_token, limit=None):
| raise NotImplementedError()
|
'Deserialises a line from the wire into this command. `line` does not
include the command.'
| @classmethod
def from_line(cls, line):
| return cls(line)
|
'Serialises the comamnd for the wire. Does not include the command
prefix.'
| def to_line(self):
| return self.data
|
'Checks if there is actually any new data and sends it to the
connections if there are.
This should get called each time new data is available, even if it
is currently being executed, so that nothing gets missed'
| @defer.inlineCallbacks
def on_notifier_poke(self):
| if (not self.connections):
for stream in self.streams:
stream.discard_updates_and_advance()
return
if self.is_looping:
logger.debug('Noitifier poke loop already running')
self.pending_updates = True
return
self.pending_updates = True
self.i... |
'For a given stream get all updates since token. This is called when
a client first subscribes to a stream.'
| @measure_func('repl.get_stream_updates')
def get_stream_updates(self, stream_name, token):
| stream = self.streams_by_name.get(stream_name, None)
if (not stream):
raise Exception('unknown stream %s', stream_name)
return stream.get_updates_since(token)
|
'We\'ve received an ack for federation stream from a client.'
| @measure_func('repl.federation_ack')
def federation_ack(self, token):
| federation_ack_counter.inc()
if self.federation_sender:
self.federation_sender.federation_ack(token)
|
'A client has started/stopped syncing on a worker.'
| @measure_func('repl.on_user_sync')
def on_user_sync(self, conn_id, user_id, is_syncing, last_sync_ms):
| user_sync_counter.inc()
self.presence_handler.update_external_syncs_row(conn_id, user_id, is_syncing, last_sync_ms)
|
'A client has asked us to remove a pusher'
| @measure_func('repl.on_remove_pusher')
@defer.inlineCallbacks
def on_remove_pusher(self, app_id, push_key, user_id):
| remove_pusher_counter.inc()
(yield self.store.delete_pusher_by_app_id_pushkey_user_id(app_id=app_id, pushkey=push_key, user_id=user_id))
self.notifier.on_new_replication_data()
|
'The client has asked us to invalidate a cache'
| @measure_func('repl.on_invalidate_cache')
def on_invalidate_cache(self, cache_func, keys):
| invalidate_cache_counter.inc()
getattr(self.store, cache_func).invalidate(tuple(keys))
|
'The client saw a user request'
| @measure_func('repl.on_user_ip')
def on_user_ip(self, user_id, access_token, ip, user_agent, device_id, last_seen):
| user_ip_cache_counter.inc()
self.store.insert_client_ip(user_id, access_token, ip, user_agent, device_id, last_seen)
|
'Sends a SYNC command to all clients.
Used in tests.'
| def send_sync_to_all_connections(self, data):
| for conn in self.connections:
conn.send_sync(data)
|
'A new client connection has been established'
| def new_connection(self, connection):
| self.connections.append(connection)
|
'A client connection has been lost'
| def lost_connection(self, connection):
| try:
self.connections.remove(connection)
except ValueError:
pass
self.presence_handler.update_external_syncs_clear(connection.conn_id)
|
'Creates and sends a request to the given server
Args:
destination (str): The remote server to send the HTTP request to.
method (str): HTTP method
path (str): The HTTP path
ignore_backoff (bool): true to ignore the historical backoff data
and try the request anyway.
backoff_on_404 (bool): Back off if we get a 404
Retur... | @defer.inlineCallbacks
def _request(self, destination, method, path, body_callback, headers_dict={}, param_bytes='', query_bytes='', retry_on_dns_fail=True, timeout=None, long_retries=False, ignore_backoff=False, backoff_on_404=False):
| limiter = (yield synapse.util.retryutils.get_retry_limiter(destination, self.clock, self._store, backoff_on_404=backoff_on_404, ignore_backoff=ignore_backoff))
destination = destination.encode('ascii')
path_bytes = path.encode('ascii')
with limiter:
headers_dict['User-Agent'] = [self.version_str... |
'Sends the specifed json data using PUT
Args:
destination (str): The remote server to send the HTTP request
to.
path (str): The HTTP path.
data (dict): A dict containing the data that will be used as
the request body. This will be encoded as JSON.
json_data_callback (callable): A callable returning the dict to
use as t... | @defer.inlineCallbacks
def put_json(self, destination, path, data={}, json_data_callback=None, long_retries=False, timeout=None, ignore_backoff=False, backoff_on_404=False):
| if (not json_data_callback):
def json_data_callback():
return data
def body_callback(method, url_bytes, headers_dict):
json_data = json_data_callback()
self.sign_request(destination, method, url_bytes, headers_dict, json_data)
producer = _JsonProducer(json_data)
... |
'Sends the specifed json data using POST
Args:
destination (str): The remote server to send the HTTP request
to.
path (str): The HTTP path.
data (dict): A dict containing the data that will be used as
the request body. This will be encoded as JSON.
long_retries (bool): A boolean that indicates whether we should
retry f... | @defer.inlineCallbacks
def post_json(self, destination, path, data={}, long_retries=False, timeout=None, ignore_backoff=False):
| def body_callback(method, url_bytes, headers_dict):
self.sign_request(destination, method, url_bytes, headers_dict, data)
return _JsonProducer(data)
response = (yield self._request(destination, 'POST', path, body_callback=body_callback, headers_dict={'Content-Type': ['application/json']}, long_r... |
'GETs some json from the given host homeserver and path
Args:
destination (str): The remote server to send the HTTP request
to.
path (str): The HTTP path.
args (dict): A dictionary used to create query strings, defaults to
None.
timeout (int): How long to try (in ms) the destination for before
giving up. None indicates... | @defer.inlineCallbacks
def get_json(self, destination, path, args={}, retry_on_dns_fail=True, timeout=None, ignore_backoff=False):
| logger.debug('get_json args: %s', args)
encoded_args = {}
for (k, vs) in args.items():
if isinstance(vs, basestring):
vs = [vs]
encoded_args[k] = [v.encode('UTF-8') for v in vs]
query_bytes = urllib.urlencode(encoded_args, True)
logger.debug('Query bytes: %s ... |
'GETs a file from a given homeserver
Args:
destination (str): The remote server to send the HTTP request to.
path (str): The HTTP path to GET.
output_stream (file): File to write the response body to.
args (dict): Optional dictionary used to create the query string.
ignore_backoff (bool): true to ignore the historical ... | @defer.inlineCallbacks
def get_file(self, destination, path, output_stream, args={}, retry_on_dns_fail=True, max_size=None, ignore_backoff=False):
| encoded_args = {}
for (k, vs) in args.items():
if isinstance(vs, basestring):
vs = [vs]
encoded_args[k] = [v.encode('UTF-8') for v in vs]
query_bytes = urllib.urlencode(encoded_args, True)
logger.debug('Query bytes: %s Retry DNS: %s', query_bytes, retry_on_dns_... |
'@return: The client address (the first address) in the value of the
I{X-Forwarded-For header}. If the header is not present, return
C{b"-"}.'
| def getClientIP(self):
| return self.requestHeaders.getRawHeaders('x-forwarded-for', ['-'])[0].split(',')[0].strip()
|
'Register a callback that gets fired if we receive a http request
with the given method for a path that matches the given regex.
If the regex contains groups these gets passed to the calback via
an unpacked tuple.
Args:
method (str): The method to listen to.
path_patterns (list<SRE_Pattern>): The regex used to match re... | def register_paths(self, method, path_patterns, callback):
| pass
|
'This gets called by twisted every time someone sends us a request.'
| def render(self, request):
| self._async_render(request)
return server.NOT_DONE_YET
|
'This gets called from render() every time someone sends us a request.
This checks if anyone has registered a callback for that method and
path.'
| @request_handler(include_metrics=True)
@defer.inlineCallbacks
def _async_render(self, request, request_metrics):
| if (request.method == 'OPTIONS'):
self._send_response(request, 200, {})
return
for path_entry in self.path_regexs.get(request.method, []):
m = path_entry.pattern.match(request.path)
if (not m):
continue
callback = path_entry.callback
kwargs = intern_di... |
'Gets some json from the given URI.
Args:
uri (str): The URI to request, not including query parameters
args (dict): A dictionary used to create query strings, defaults to
None.
**Note**: The value of each key is assumed to be an iterable
and *not* a string.
Returns:
Deferred: Succeeds when we get *any* 2xx HTTP respon... | @defer.inlineCallbacks
def get_json(self, uri, args={}):
| try:
body = (yield self.get_raw(uri, args))
defer.returnValue(json.loads(body))
except CodeMessageException as e:
raise self._exceptionFromFailedRequest(e.code, e.msg)
|
'Puts some json to the given URI.
Args:
uri (str): The URI to request, not including query parameters
json_body (dict): The JSON to put in the HTTP body,
args (dict): A dictionary used to create query strings, defaults to
None.
**Note**: The value of each key is assumed to be an iterable
and *not* a string.
Returns:
De... | @defer.inlineCallbacks
def put_json(self, uri, json_body, args={}):
| if len(args):
query_bytes = urllib.urlencode(args, True)
uri = ('%s?%s' % (uri, query_bytes))
json_str = encode_canonical_json(json_body)
response = (yield self.request('PUT', uri.encode('ascii'), headers=Headers({'User-Agent': [self.user_agent], 'Content-Type': ['application/json']}), bodyP... |
'Gets raw text from the given URI.
Args:
uri (str): The URI to request, not including query parameters
args (dict): A dictionary used to create query strings, defaults to
None.
**Note**: The value of each key is assumed to be an iterable
and *not* a string.
Returns:
Deferred: Succeeds when we get *any* 2xx HTTP respons... | @defer.inlineCallbacks
def get_raw(self, uri, args={}):
| if len(args):
query_bytes = urllib.urlencode(args, True)
uri = ('%s?%s' % (uri, query_bytes))
response = (yield self.request('GET', uri.encode('ascii'), headers=Headers({'User-Agent': [self.user_agent]})))
body = (yield preserve_context_over_fn(readBody, response))
if (200 <= response.co... |
'GETs a file from a given URL
Args:
url (str): The URL to GET
output_stream (file): File to write the response body to.
Returns:
A (int,dict,string,int) tuple of the file length, dict of the response
headers, absolute URI of the response and HTTP response code.'
| @defer.inlineCallbacks
def get_file(self, url, output_stream, max_size=None):
| response = (yield self.request('GET', url.encode('ascii'), headers=Headers({'User-Agent': [self.user_agent]})))
headers = dict(response.headers.getAllRawHeaders())
if (('Content-Length' in headers) and (headers['Content-Length'] > max_size)):
logger.warn(('Requested URL is too large >... |
'Register this servlet with the given HTTP server.'
| def register(self, http_server):
| if hasattr(self, 'PATTERNS'):
patterns = self.PATTERNS
for method in ('GET', 'PUT', 'POST', 'OPTIONS', 'DELETE'):
if hasattr(self, ('on_%s' % (method,))):
method_handler = getattr(self, ('on_%s' % (method,)))
http_server.register_paths(method, patterns, me... |
'Retrieves the current state for the room. This is done by
calling `get_latest_events_in_room` to get the leading edges of the
event graph and then resolving any of the state conflicts.
This is equivalent to getting the state of an event that were to send
next before receiving any new events.
If `event_type` is specifi... | @defer.inlineCallbacks
def get_current_state(self, room_id, event_type=None, state_key='', latest_event_ids=None):
| if (not latest_event_ids):
latest_event_ids = (yield self.store.get_latest_event_ids_in_room(room_id))
logger.debug('calling resolve_state_groups from get_current_state')
ret = (yield self.resolve_state_groups(room_id, latest_event_ids))
state = ret.state
if event_type:
even... |
'Build an EventContext structure for the event.
Args:
event (synapse.events.EventBase):
Returns:
synapse.events.snapshot.EventContext:'
| @defer.inlineCallbacks
def compute_event_context(self, event, old_state=None):
| if event.internal_metadata.is_outlier():
context = EventContext()
if old_state:
context.prev_state_ids = {(s.type, s.state_key): s.event_id for s in old_state}
if event.is_state():
context.current_state_ids = dict(context.prev_state_ids)
key = ... |
'Given a list of event_ids this method fetches the state at each
event, resolves conflicts between them and returns them.
Returns:
a Deferred tuple of (`state_group`, `state`, `prev_state`).
`state_group` is the name of a state group if one and only one is
involved. `state` is a map from (type, state_key) to event, and... | @defer.inlineCallbacks
@log_function
def resolve_state_groups(self, room_id, event_ids):
| logger.debug('resolve_state_groups event_ids %s', event_ids)
state_groups_ids = (yield self.store.get_state_groups_ids(room_id, event_ids))
logger.debug('resolve_state_groups state_groups %s', state_groups_ids.keys())
group_names = frozenset(state_groups_ids.keys())
if (len(group_names) ... |
'Whether this server should send the event on behalf of another server.
This is used by the federation "send_join" API to forward the initial join
event for a server in the room.
returns a str with the name of the server this event is sent on behalf of.'
| def get_send_on_behalf_of(self):
| return getattr(self, 'send_on_behalf_of', None)
|
'Add events to the queue, with the given persist_event options.
Args:
room_id (str):
events_and_contexts (list[(EventBase, EventContext)]):
backfilled (bool):'
| def add_to_queue(self, room_id, events_and_contexts, backfilled):
| queue = self._event_persist_queues.setdefault(room_id, deque())
if queue:
end_item = queue[(-1)]
if (end_item.backfilled == backfilled):
end_item.events_and_contexts.extend(events_and_contexts)
return end_item.deferred.observe()
deferred = ObservableDeferred(defer.Def... |
'Attempts to handle the queue for a room if not already being handled.
The given callback will be invoked with for each item in the queue,1
of type _EventPersistQueueItem. The per_item_callback will continuously
be called with new items, unless the queue becomnes empty. The return
value of the function will be given to... | def handle_queue(self, room_id, per_item_callback):
| if (room_id in self._currently_persisting_rooms):
return
self._currently_persisting_rooms.add(room_id)
@defer.inlineCallbacks
def handle_queue_loop():
try:
queue = self._get_drainining_queue(room_id)
for item in queue:
try:
ret ... |
'Write events to the database
Args:
events_and_contexts: list of tuples of (event, context)
backfilled: ?'
| def persist_events(self, events_and_contexts, backfilled=False):
| partitioned = {}
for (event, ctx) in events_and_contexts:
partitioned.setdefault(event.room_id, []).append((event, ctx))
deferreds = []
for (room_id, evs_ctxs) in partitioned.iteritems():
d = preserve_fn(self._event_persist_queue.add_to_queue)(room_id, evs_ctxs, backfilled=backfilled)
... |
'Args:
event (EventBase):
context (EventContext):
backfilled (bool):
Returns:
Deferred: resolves to (int, int): the stream ordering of ``event``,
and the stream ordering of the latest persisted event'
| @defer.inlineCallbacks
@log_function
def persist_event(self, event, context, backfilled=False):
| deferred = self._event_persist_queue.add_to_queue(event.room_id, [(event, context)], backfilled=backfilled)
self._maybe_start_persisting(event.room_id)
(yield preserve_context_over_deferred(deferred))
max_persisted_id = (yield self._stream_id_gen.get_current_token())
defer.returnValue((event.interna... |
'Persist events to db
Args:
events_and_contexts (list[(EventBase, EventContext)]):
backfilled (bool):
delete_existing (bool):
Returns:
Deferred: resolves when the events have been persisted'
| @_retry_on_integrity_error
@defer.inlineCallbacks
def _persist_events(self, events_and_contexts, backfilled=False, delete_existing=False):
| if (not events_and_contexts):
return
if backfilled:
stream_ordering_manager = self._backfill_id_gen.get_next_mult(len(events_and_contexts))
else:
stream_ordering_manager = self._stream_id_gen.get_next_mult(len(events_and_contexts))
with stream_ordering_manager as stream_orderings... |
'Calculates the new forward extremeties for a room given events to
persist.
Assumes that we are only persisting events for one room at a time.'
| @defer.inlineCallbacks
def _calculate_new_extremeties(self, room_id, event_contexts, latest_event_ids):
| new_latest_event_ids = set(latest_event_ids)
new_latest_event_ids.update((event.event_id for (event, ctx) in event_contexts if ((not event.internal_metadata.is_outlier()) and (not ctx.rejected))))
new_latest_event_ids.difference_update((e_id for (event, ctx) in event_contexts for (e_id, _) in event.prev_eve... |
'Calculate the new state deltas for a room.
Assumes that we are only persisting events for one room at a time.
Returns:
3-tuple (to_delete, to_insert, new_state) where both are state dicts,
i.e. (type, state_key) -> event_id. `to_delete` are the entries to
first be deleted from current_state_events, `to_insert` are ent... | @defer.inlineCallbacks
def _calculate_state_delta(self, room_id, events_context, new_latest_event_ids):
| state_sets = []
state_groups = set()
missing_event_ids = []
was_updated = False
for event_id in new_latest_event_ids:
for (ev, ctx) in events_context:
if (event_id == ev.event_id):
if (ctx.current_state_ids is None):
raise Exception('Unknown ... |
'Get an event from the database by event_id.
Args:
event_id (str): The event_id of the event to fetch
check_redacted (bool): If True, check if event has been redacted
and redact it.
get_prev_content (bool): If True and event is a state event,
include the previous states content in the unsigned field.
allow_rejected (bo... | @defer.inlineCallbacks
def get_event(self, event_id, check_redacted=True, get_prev_content=False, allow_rejected=False, allow_none=False):
| events = (yield self._get_events([event_id], check_redacted=check_redacted, get_prev_content=get_prev_content, allow_rejected=allow_rejected))
if ((not events) and (not allow_none)):
raise SynapseError(404, ('Could not find event %s' % (event_id,)))
defer.returnValue((events[0] if events... |
'Get events from the database
Args:
event_ids (list): The event_ids of the events to fetch
check_redacted (bool): If True, check if event has been redacted
and redact it.
get_prev_content (bool): If True and event is a state event,
include the previous states content in the unsigned field.
allow_rejected (bool): If Tru... | @defer.inlineCallbacks
def get_events(self, event_ids, check_redacted=True, get_prev_content=False, allow_rejected=False):
| events = (yield self._get_events(event_ids, check_redacted=check_redacted, get_prev_content=get_prev_content, allow_rejected=allow_rejected))
defer.returnValue({e.event_id: e for e in events})
|
'Insert some number of room events into the necessary database tables.
Rejected events are only inserted into the events table, the events_json table,
and the rejections table. Things reading from those table will need to check
whether the event was rejected.
Args:
txn (twisted.enterprise.adbapi.Connection): db connect... | @log_function
def _persist_events_txn(self, txn, events_and_contexts, backfilled, delete_existing=False, current_state_for_room={}, new_forward_extremeties={}):
| max_stream_order = events_and_contexts[(-1)][0].internal_metadata.stream_ordering
self._update_current_state_txn(txn, current_state_for_room, max_stream_order)
self._update_forward_extremities_txn(txn, new_forward_extremities=new_forward_extremeties, max_stream_order=max_stream_order)
events_and_context... |
'Ensure that we don\'t have the same event twice.
Pick the earliest non-outlier if there is one, else the earliest one.
Args:
events_and_contexts (list[(EventBase, EventContext)]):
Returns:
list[(EventBase, EventContext)]: filtered list'
| @classmethod
def _filter_events_and_contexts_for_duplicates(cls, events_and_contexts):
| new_events_and_contexts = OrderedDict()
for (event, context) in events_and_contexts:
prev_event_context = new_events_and_contexts.get(event.event_id)
if prev_event_context:
if (not event.internal_metadata.is_outlier()):
if prev_event_context[0].internal_metadata.is_ou... |
'Update min_depth for each room
Args:
txn (twisted.enterprise.adbapi.Connection): db connection
events_and_contexts (list[(EventBase, EventContext)]): events
we are persisting
backfilled (bool): True if the events were backfilled'
| def _update_room_depths_txn(self, txn, events_and_contexts, backfilled):
| depth_updates = {}
for (event, context) in events_and_contexts:
txn.call_after(self._invalidate_get_event_cache, event.event_id)
if (not backfilled):
txn.call_after(self._events_stream_cache.entity_has_changed, event.room_id, event.internal_metadata.stream_ordering)
if ((not ... |
'Update any outliers with new event info.
This turns outliers into ex-outliers (unless the new event was
rejected).
Args:
txn (twisted.enterprise.adbapi.Connection): db connection
events_and_contexts (list[(EventBase, EventContext)]): events
we are persisting
Returns:
list[(EventBase, EventContext)] new list, without e... | def _update_outliers_txn(self, txn, events_and_contexts):
| txn.execute(('SELECT event_id, outlier FROM events WHERE event_id in (%s)' % (','.join((['?'] * len(events_and_contexts))),)), [event.event_id for (event, _) in events_and_contexts])
have_persisted = {event_id: outlier for (event_id, outlier) in txn}
to_remove = set()
for (event,... |
'Insert new events into the event and event_json tables
Args:
txn (twisted.enterprise.adbapi.Connection): db connection
events_and_contexts (list[(EventBase, EventContext)]): events
we are persisting'
| def _store_event_txn(self, txn, events_and_contexts):
| if (not events_and_contexts):
return
def event_dict(event):
d = event.get_dict()
d.pop('redacted', None)
d.pop('redacted_because', None)
return d
self._simple_insert_many_txn(txn, table='event_json', values=[{'event_id': event.event_id, 'room_id': event.room_id, 'inte... |
'Add rows to the \'rejections\' table for received events which were
rejected
Args:
txn (twisted.enterprise.adbapi.Connection): db connection
events_and_contexts (list[(EventBase, EventContext)]): events
we are persisting
Returns:
list[(EventBase, EventContext)] new list, without the rejected
events.'
| def _store_rejected_events_txn(self, txn, events_and_contexts):
| to_remove = set()
for (event, context) in events_and_contexts:
if context.rejected:
self._store_rejections_txn(txn, event.event_id, context.rejected)
to_remove.add(event)
return [ec for ec in events_and_contexts if (ec[0] not in to_remove)]
|
'Update all the miscellaneous tables for new events
Args:
txn (twisted.enterprise.adbapi.Connection): db connection
events_and_contexts (list[(EventBase, EventContext)]): events
we are persisting
backfilled (bool): True if the events were backfilled'
| def _update_metadata_tables_txn(self, txn, events_and_contexts, backfilled):
| if (not events_and_contexts):
return
for (event, context) in events_and_contexts:
if context.push_actions:
self._set_push_actions_for_event_and_users_txn(txn, event, context.push_actions)
if ((event.type == EventTypes.Redaction) and (event.redacts is not None)):
s... |
'Given a list of event ids, check if we have already processed and
stored them as non outliers.'
| @defer.inlineCallbacks
def have_events_in_timeline(self, event_ids):
| rows = (yield self._simple_select_many_batch(table='events', retcols=('event_id',), column='event_id', iterable=list(event_ids), keyvalues={'outlier': False}, desc='have_events_in_timeline'))
defer.returnValue(set((r['event_id'] for r in rows)))
|
'Given a list of event ids, check if we have already processed them.
Returns:
dict: Has an entry for each event id we already have seen. Maps to
the rejected reason string if we rejected the event, else maps to
None.'
| def have_events(self, event_ids):
| if (not event_ids):
return defer.succeed({})
def f(txn):
sql = 'SELECT e.event_id, reason FROM events as e LEFT JOIN rejections as r ON e.event_id = r.event_id WHERE e.event_id = ?'
res = {}
for event_id in event_ids:
... |
'Fetch events from the caches
Args:
events (list(str)): list of event_ids to fetch
allow_rejected (bool): Whether to teturn events that were rejected
update_metrics (bool): Whether to update the cache hit ratio metrics
Returns:
dict of event_id -> _EventCacheEntry for each event_id in cache. If
allow_rejected is `False... | def _get_events_from_cache(self, events, allow_rejected, update_metrics=True):
| event_map = {}
for event_id in events:
ret = self._get_event_cache.get((event_id,), None, update_metrics=update_metrics)
if (not ret):
continue
if (allow_rejected or (not ret.event.rejected_reason)):
event_map[event_id] = ret
else:
event_map[ev... |
'Takes a database connection and waits for requests for events from
the _event_fetch_list queue.'
| def _do_fetch(self, conn):
| event_list = []
i = 0
while True:
try:
with self._event_fetch_lock:
event_list = self._event_fetch_list
self._event_fetch_list = []
if (not event_list):
single_threaded = self.database_engine.single_threaded
... |
'Fetches events from the database using the _event_fetch_list. This
allows batch and bulk fetching of events - it allows us to fetch events
without having to create a new transaction for each request for events.'
| @defer.inlineCallbacks
def _enqueue_events(self, events, check_redacted=True, allow_rejected=False):
| if (not events):
defer.returnValue({})
events_d = defer.Deferred()
with self._event_fetch_lock:
self._event_fetch_list.append((events, events_d))
self._event_fetch_lock.notify()
if (self._event_fetch_ongoing < EVENT_QUEUE_THREADS):
self._event_fetch_ongoing += 1
... |
'Returns an estimate of the number of messages sent in the last day.
If it has been significantly less or more than one day since the last
call to this function, it will return None.'
| @defer.inlineCallbacks
def count_daily_messages(self):
| def _count_messages(txn):
sql = "\n SELECT COALESCE(COUNT(*), 0) FROM events\n WHERE type = 'm.room.message'\n ... |
'The current minimum token that backfilled events have reached'
| def get_current_backfill_token(self):
| return (- self._backfill_id_gen.get_current_token())
|
'The current maximum token that events have reached'
| def get_current_events_token(self):
| return self._stream_id_gen.get_current_token()
|
'Get all the new events that have arrived at the server either as
new events or as backfilled events'
| @cached(num_args=5, max_entries=10)
def get_all_new_events(self, last_backfill_id, last_forward_id, current_backfill_id, current_forward_id, limit):
| have_backfill_events = (last_backfill_id != current_backfill_id)
have_forward_events = (last_forward_id != current_forward_id)
if ((not have_backfill_events) and (not have_forward_events)):
return defer.succeed(AllNewEventsResult([], [], [], [], []))
def get_all_new_events_txn(txn):
sql ... |
'Deletes old room state'
| def _delete_old_state_txn(self, txn, room_id, topological_ordering):
| txn.execute('SELECT e.event_id, e.depth FROM events as e INNER JOIN event_forward_extremities as f ON e.event_id = f.event_id AND e.room_id = f.room_id WHERE f.room_id = ?', (room_id,))
rows = txn.fetchall()
max_depth = max((row[0] for row... |
'Returns True if event_id1 is after event_id2 in the stream'
| @defer.inlineCallbacks
def is_event_after(self, event_id1, event_id2):
| (to_1, so_1) = (yield self._get_event_ordering(event_id1))
(to_2, so_2) = (yield self._get_event_ordering(event_id2))
defer.returnValue(((to_1, so_1) > (to_2, so_2)))
|
'Stores device keys for a device. Returns whether there was a change
or the keys were already in the database.'
| def set_e2e_device_keys(self, user_id, device_id, time_now, device_keys):
| def _set_e2e_device_keys_txn(txn):
old_key_json = self._simple_select_one_onecol_txn(txn, table='e2e_device_keys_json', keyvalues={'user_id': user_id, 'device_id': device_id}, retcol='key_json', allow_none=True)
new_key_json = encode_canonical_json(device_keys)
if (old_key_json == new_key_js... |
'Fetch a list of device keys.
Args:
query_list(list): List of pairs of user_ids and device_ids.
include_all_devices (bool): whether to include entries for devices
that don\'t have device keys
Returns:
Dict mapping from user-id to dict mapping from device_id to
dict containing "key_json", "device_display_name".'
| @defer.inlineCallbacks
def get_e2e_device_keys(self, query_list, include_all_devices=False):
| if (not query_list):
defer.returnValue({})
results = (yield self.runInteraction('get_e2e_device_keys', self._get_e2e_device_keys_txn, query_list, include_all_devices))
for (user_id, device_keys) in results.iteritems():
for (device_id, device_info) in device_keys.iteritems():
devi... |
'Retrieve a number of one-time keys for a user
Args:
user_id(str): id of user to get keys for
device_id(str): id of device to get keys for
key_ids(list[str]): list of key ids (excluding algorithm) to
retrieve
Returns:
deferred resolving to Dict[(str, str), str]: map from (algorithm,
key_id) to json string for key'
| @defer.inlineCallbacks
def get_e2e_one_time_keys(self, user_id, device_id, key_ids):
| rows = (yield self._simple_select_many_batch(table='e2e_one_time_keys_json', column='key_id', iterable=key_ids, retcols=('algorithm', 'key_id', 'key_json'), keyvalues={'user_id': user_id, 'device_id': device_id}, desc='add_e2e_one_time_keys_check'))
defer.returnValue({(row['algorithm'], row['key_id']): row['key... |
'Insert some new one time keys for a device. Errors if any of the
keys already exist.
Args:
user_id(str): id of user to get keys for
device_id(str): id of device to get keys for
time_now(long): insertion time to record (ms since epoch)
new_keys(iterable[(str, str, str)]: keys to add - each a tuple of
(algorithm, key_id... | @defer.inlineCallbacks
def add_e2e_one_time_keys(self, user_id, device_id, time_now, new_keys):
| def _add_e2e_one_time_keys(txn):
self._simple_insert_many_txn(txn, table='e2e_one_time_keys_json', values=[{'user_id': user_id, 'device_id': device_id, 'algorithm': algorithm, 'key_id': key_id, 'ts_added_ms': time_now, 'key_json': json_bytes} for (algorithm, key_id, json_bytes) in new_keys])
self._i... |
'Count the number of one time keys the server has for a device
Returns:
Dict mapping from algorithm to number of keys for that algorithm.'
| @cached(max_entries=10000)
def count_e2e_one_time_keys(self, user_id, device_id):
| def _count_e2e_one_time_keys(txn):
sql = 'SELECT algorithm, COUNT(key_id) FROM e2e_one_time_keys_json WHERE user_id = ? AND device_id = ? GROUP BY algorithm'
txn.execute(sql, (user_id, device_id))
result = {}
for (algorithm, key_count) in ... |
'Take a list of one time keys out of the database'
| def claim_e2e_one_time_keys(self, query_list):
| def _claim_e2e_one_time_keys(txn):
sql = 'SELECT key_id, key_json FROM e2e_one_time_keys_json WHERE user_id = ? AND device_id = ? AND algorithm = ? LIMIT 1'
result = {}
delete = []
for (user_id, device_id, algorithm) in query_list... |
'For an incoming transaction from a given origin, check if we have
already responded to it. If so, return the response code and response
body (as a dict).
Args:
transaction_id (str)
origin(str)
Returns:
tuple: None if we have not previously responded to
this transaction or a 2-tuple of (int, dict)'
| def get_received_txn_response(self, transaction_id, origin):
| return self.runInteraction('get_received_txn_response', self._get_received_txn_response, transaction_id, origin)
|
'Persist the response we returened for an incoming transaction, and
should return for subsequent transactions with the same transaction_id
and origin.
Args:
txn
transaction_id (str)
origin (str)
code (int)
response_json (str)'
| def set_received_txn_response(self, transaction_id, origin, code, response_dict):
| return self._simple_insert(table='received_transactions', values={'transaction_id': transaction_id, 'origin': origin, 'response_code': code, 'response_json': buffer(encode_canonical_json(response_dict)), 'ts': self._clock.time_msec()}, or_ignore=True, desc='set_received_txn_response')
|
'Persists an outgoing transaction and calculates the values for the
previous transaction id list.
This should be called before sending the transaction so that it has the
correct value for the `prev_ids` key.
Args:
transaction_id (str)
destination (str)
origin_server_ts (int)
Returns:
list: A list of previous transactio... | def prep_send_transaction(self, transaction_id, destination, origin_server_ts):
| return defer.succeed([])
|
'Persists the response for an outgoing transaction.
Args:
transaction_id (str)
destination (str)
code (int)
response_json (str)'
| def delivered_txn(self, transaction_id, destination, code, response_dict):
| pass
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.