async def _async_render(self, request): """ 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. """ callback, servlet_classname, group_dict = self._get_handler_for_request(request) # Make sure we have a name for this handler in prometheus. request.request_metrics.name = servlet_classname # Now trigger the callback. If it returns a response, we send it # here. If it throws an exception, that is handled by the wrapper # installed by @request_handler. kwargs = intern_dict( { name: urllib.parse.unquote(value) if value else value for name, value in group_dict.items() } ) callback_return = callback(request, **kwargs) # Is it synchronous? We'll allow this for now. if isinstance(callback_return, (defer.Deferred, types.CoroutineType)): callback_return = await callback_return if callback_return is not None: code, response = callback_return self._send_response(request, code, response)
async def _async_render(self, request: SynapseRequest) -> Tuple[int, Any]: callback, servlet_classname, group_dict = self._get_handler_for_request(request) # Make sure we have an appropriate name for this handler in prometheus # (rather than the default of JsonResource). request.request_metrics.name = servlet_classname # Now trigger the callback. If it returns a response, we send it # here. If it throws an exception, that is handled by the wrapper # installed by @request_handler. kwargs = intern_dict( { name: urllib.parse.unquote(value) if value else value for name, value in group_dict.items() } ) raw_callback_return = callback(request, **kwargs) # Is it synchronous? We'll allow this for now. if isinstance(raw_callback_return, (defer.Deferred, types.CoroutineType)): callback_return = await raw_callback_return else: callback_return = raw_callback_return # type: ignore return callback_return
def _async_render(self, request, request_metrics): """ 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. """ callback, group_dict = self._get_handler_for_request(request) servlet_instance = getattr(callback, "__self__", None) if servlet_instance is not None: servlet_classname = servlet_instance.__class__.__name__ else: servlet_classname = "%r" % callback request_metrics.name = servlet_classname requests_counter.inc(request.method, servlet_classname) # Now trigger the callback. If it returns a response, we send it # here. If it throws an exception, that is handled by the wrapper # installed by @request_handler. kwargs = intern_dict({ name: urllib.unquote(value).decode("UTF-8") if value else value for name, value in group_dict.items() }) callback_return = yield callback(request, **kwargs) if callback_return is not None: code, response = callback_return self._send_response(request, code, response)
def __init__(self, event_dict, internal_metadata_dict={}, rejected_reason=None): event_dict = dict(event_dict) # Signatures is a dict of dicts, and this is faster than doing a # copy.deepcopy signatures = { name: {sig_id: sig for sig_id, sig in sigs.items()} for name, sigs in event_dict.pop("signatures", {}).items() } unsigned = dict(event_dict.pop("unsigned", {})) # We intern these strings because they turn up a lot (especially when # caching). event_dict = intern_dict(event_dict) if USE_FROZEN_DICTS: frozen_dict = freeze(event_dict) else: frozen_dict = event_dict super(FrozenEvent, self).__init__( frozen_dict, signatures=signatures, unsigned=unsigned, internal_metadata_dict=internal_metadata_dict, rejected_reason=rejected_reason, )
def __init__(self, event_dict, internal_metadata_dict={}, rejected_reason=None): event_dict = dict(event_dict) # Signatures is a dict of dicts, and this is faster than doing a # copy.deepcopy signatures = { name: {sig_id: sig for sig_id, sig in sigs.items()} for name, sigs in event_dict.pop("signatures", {}).items() } assert "event_id" not in event_dict unsigned = dict(event_dict.pop("unsigned", {})) # We intern these strings because they turn up a lot (especially when # caching). event_dict = intern_dict(event_dict) if USE_FROZEN_DICTS: frozen_dict = freeze(event_dict) else: frozen_dict = event_dict self._event_id = None self.type = event_dict["type"] if "state_key" in event_dict: self.state_key = event_dict["state_key"] super(FrozenEventV2, self).__init__( frozen_dict, signatures=signatures, unsigned=unsigned, internal_metadata_dict=internal_metadata_dict, rejected_reason=rejected_reason, )
def cursor_to_dict(cursor): """Converts a SQL cursor into an list of dicts. Args: cursor : The DBAPI cursor which has executed a query. Returns: A list of dicts where the key is the column header. """ col_headers = list(column[0] for column in cursor.description) results = list(intern_dict(dict(zip(col_headers, row))) for row in cursor.fetchall()) return results
def cursor_to_dict(cursor): """Converts a SQL cursor into an list of dicts. Args: cursor : The DBAPI cursor which has executed a query. Returns: A list of dicts where the key is the column header. """ col_headers = list(column[0] for column in cursor.description) results = list( intern_dict(dict(zip(col_headers, row))) for row in cursor.fetchall() ) return results
def _async_render(self, request): """ 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. """ if request.method == "OPTIONS": self._send_response(request, 200, {}) return request_metrics = RequestMetrics() request_metrics.start(self.clock) # Loop through all the registered callbacks to check if the method # and path regex match for path_entry in self.path_regexs.get(request.method, []): m = path_entry.pattern.match(request.path) if not m: continue # We found a match! Trigger callback and then return the # returned response. We pass both the request and any # matched groups from the regex to the callback. callback = path_entry.callback servlet_instance = getattr(callback, "__self__", None) if servlet_instance is not None: servlet_classname = servlet_instance.__class__.__name__ else: servlet_classname = "%r" % callback kwargs = intern_dict({ name: urllib.unquote(value).decode("UTF-8") if value else value for name, value in m.groupdict().items() }) callback_return = yield callback(request, **kwargs) if callback_return is not None: code, response = callback_return self._send_response(request, code, response) try: request_metrics.stop(self.clock, request, servlet_classname) except: pass return # Huh. No one wanted to handle that? Fiiiiiine. Send 400. raise UnrecognizedRequestError()
def __init__( self, event_dict: JsonDict, room_version: RoomVersion, internal_metadata_dict: Optional[JsonDict] = None, rejected_reason: Optional[str] = None, ): internal_metadata_dict = internal_metadata_dict or {} event_dict = dict(event_dict) # Signatures is a dict of dicts, and this is faster than doing a # copy.deepcopy signatures = { name: {sig_id: sig for sig_id, sig in sigs.items()} for name, sigs in event_dict.pop("signatures", {}).items() } assert "event_id" not in event_dict unsigned = dict(event_dict.pop("unsigned", {})) # We intern these strings because they turn up a lot (especially when # caching). event_dict = intern_dict(event_dict) if USE_FROZEN_DICTS: frozen_dict = freeze(event_dict) else: frozen_dict = event_dict self._event_id = None super().__init__( frozen_dict, room_version=room_version, signatures=signatures, unsigned=unsigned, internal_metadata_dict=internal_metadata_dict, rejected_reason=rejected_reason, )
def _async_render(self, request): """ 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. """ callback, group_dict = self._get_handler_for_request(request) servlet_instance = getattr(callback, "__self__", None) if servlet_instance is not None: servlet_classname = servlet_instance.__class__.__name__ else: servlet_classname = "%r" % callback request.request_metrics.name = servlet_classname # Now trigger the callback. If it returns a response, we send it # here. If it throws an exception, that is handled by the wrapper # installed by @request_handler. def _unquote(s): if PY3: # On Python 3, unquote is unicode -> unicode return urllib.parse.unquote(s) else: # On Python 2, unquote is bytes -> bytes We need to encode the # URL again (as it was decoded by _get_handler_for request), as # ASCII because it's a URL, and then decode it to get the UTF-8 # characters that were quoted. return urllib.parse.unquote(s.encode('ascii')).decode('utf8') kwargs = intern_dict({ name: _unquote(value) if value else value for name, value in group_dict.items() }) callback_return = yield callback(request, **kwargs) if callback_return is not None: code, response = callback_return self._send_response(request, code, response)
def _async_render(self, request): """ 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. """ start = self.clock.time_msec() if request.method == "OPTIONS": self._send_response(request, 200, {}) return start_context = LoggingContext.current_context() # Loop through all the registered callbacks to check if the method # and path regex match for path_entry in self.path_regexs.get(request.method, []): m = path_entry.pattern.match(request.path) if not m: continue # We found a match! Trigger callback and then return the # returned response. We pass both the request and any # matched groups from the regex to the callback. callback = path_entry.callback servlet_instance = getattr(callback, "__self__", None) if servlet_instance is not None: servlet_classname = servlet_instance.__class__.__name__ else: servlet_classname = "%r" % callback kwargs = intern_dict({ name: urllib.unquote(value).decode("UTF-8") if value else value for name, value in m.groupdict().items() }) callback_return = yield callback(request, **kwargs) if callback_return is not None: code, response = callback_return self._send_response(request, code, response) try: context = LoggingContext.current_context() tag = "" if context: tag = context.tag if context != start_context: logger.warn( "Context have unexpectedly changed %r, %r", context, self.start_context ) return incoming_requests_counter.inc(request.method, servlet_classname, tag) response_timer.inc_by( self.clock.time_msec() - start, request.method, servlet_classname, tag ) ru_utime, ru_stime = context.get_resource_usage() response_ru_utime.inc_by( ru_utime, request.method, servlet_classname, tag ) response_ru_stime.inc_by( ru_stime, request.method, servlet_classname, tag ) response_db_txn_count.inc_by( context.db_txn_count, request.method, servlet_classname, tag ) response_db_txn_duration.inc_by( context.db_txn_duration, request.method, servlet_classname, tag ) except: pass return # Huh. No one wanted to handle that? Fiiiiiine. Send 400. raise UnrecognizedRequestError()