desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'The number of seconds that the Instance has been idle. Will be 0.0 if the Instance has not started.'
@property def idle_seconds(self):
with self._condition: if self._num_outstanding_requests: return 0.0 elif (not self._started): return 0.0 else: return (time.time() - self._last_request_end_time)
'True if the Instance is handling or will be sent a ready request.'
@property def handling_ready_request(self):
return self._expecting_ready_request
'Returns the average request latency over the last 60s in seconds.'
def get_latency_60s(self):
with self._condition: self._trim_request_history_to_60s() if (not self._request_history): return 0.0 else: total_latency = sum(((end - start) for (start, end) in self._request_history)) return (total_latency / len(self._request_history))
'Returns the average queries-per-second over the last 60 seconds.'
def get_qps_60s(self):
with self._condition: self._trim_request_history_to_60s() if (not self._request_history): return 0.0 else: return (len(self._request_history) / 60.0)
'True if .handle() will accept requests. Does not consider outstanding request volume.'
@property def can_accept_requests(self):
with self._condition: return ((not self._quit) and (not self._quitting) and (not self._expecting_ready_request) and (not self._expecting_shutdown_request) and self._started)
'Removes obsolete entries from _outstanding_request_history.'
def _trim_request_history_to_60s(self):
window_start = (time.time() - 60) with self._condition: while self._request_history: (t, _) = self._request_history[0] if (t < window_start): self._request_history.popleft() else: break
'Start the instance and the RuntimeProxy. Returns: True if the Instance was started or False, if the Instance has already been quit.'
def start(self):
with self._condition: if self._quit: return False self._runtime_proxy.start() with self._condition: if self._quit: self._runtime_proxy.quit() return False self._last_request_end_time = time.time() self._started = True logging.debug('Sta...
'Quits the instance and the RuntimeProxy. Args: allow_async: Whether to enqueue the quit after all requests have completed if the instance cannot be quit immediately. force: Whether to force the instance to quit even if the instance is currently handling a request. This overrides allow_async if True. expect_shutdown: W...
def quit(self, allow_async=False, force=False, expect_shutdown=False):
with self._condition: if self._quit: return if (not self._started): self._quit = True return if expect_shutdown: self._expecting_shutdown_request = True return if (self._num_outstanding_requests or self._num_running_backgrou...
'Reserves a background thread slot. Raises: CannotAcceptRequests: if the Instance is already handling the maximum permissible number of background threads or is not in a state where it can handle background threads.'
def reserve_background_thread(self):
with self._condition: if self._quit: raise CannotAcceptRequests('Instance has been quit') if (not self._started): raise CannotAcceptRequests('Instance has not started') if (not self.remaining_background_thread_capacity): raise CannotAccep...
'Handles an HTTP request by forwarding it to the RuntimeProxy. Args: environ: An environ dict for the request as defined in PEP-333. start_response: A function with semantics defined in PEP-333. url_map: An appinfo.URLMap instance containing the configuration for the handler matching this request. match: A re.MatchObje...
def handle(self, environ, start_response, url_map, match, request_id, request_type):
start_time = time.time() with self._condition: if self._quit: raise CannotAcceptRequests('Instance has been quit') if (not self._started): raise CannotAcceptRequests('Instance has not started') if (request_type not in (BACKGROUND_REQUEST, SHUTDOW...
'Wait for this instance to have capacity to serve a request. Args: timeout_time: A float containing a time in seconds since the epoch to wait until before timing out. Returns: True if the instance has request capacity or False if the timeout time was reached or the instance has been quit.'
def wait(self, timeout_time):
with self._condition: while ((time.time() < timeout_time) and (not (self.remaining_request_capacity and self.can_accept_requests)) and (not self.has_quit)): self._condition.wait((timeout_time - time.time())) return bool((self.remaining_request_capacity and self.can_accept_requests))
'Initializer for InstanceFactory. Args: request_data: A wsgi_request_info.WSGIRequestInfo instance that will be populated with Instance data for use by the API stubs. max_concurrent_requests: The maximum number of concurrent requests that Instances created by this factory can handle. If the Instances do not support con...
def __init__(self, request_data, max_concurrent_requests, max_background_threads=0):
self.request_data = request_data self.max_concurrent_requests = max_concurrent_requests self.max_background_threads = max_background_threads
'Returns a list of directories changes in which should trigger a restart. Returns: A list of directory paths. Changes (i.e. files added, deleted or modified) in these directories will trigger the restart of all instances created with this factory.'
def get_restart_directories(self):
return []
'Create and return a new Instance. Args: instance_id: A string or integer representing the unique (per module) id of the instance. expect_ready_request: If True then the instance will be sent a special request (i.e. /_ah/warmup or /_ah/start) before it can handle external requests. Returns: The newly created instance.I...
def new_instance(self, instance_id, expect_ready_request=False):
raise NotImplementedError()
'Initializes an instance of the DiscoveryService. Args: config_manager: An instance of ApiConfigManager.'
def __init__(self, config_manager):
self._config_manager = config_manager self._discovery_proxy = discovery_api_proxy.DiscoveryApiProxy()
'Sends an HTTP 200 json success response. This calls start_response and returns the response body. Args: response: A string containing the response body to return. start_response: A function with semantics defined in PEP-333. Returns: A string, the response body.'
def _send_success_response(self, response, start_response):
headers = [('Content-Type', 'application/json; charset=UTF-8')] return util.send_wsgi_response('200', headers, response, start_response)
'Sends back HTTP response with API directory. This calls start_response and returns the response body. It will return the discovery doc for the requested api/version. Args: api_format: A string containing either \'rest\' or \'rpc\'. request: An ApiRequest, the transformed request sent to the Discovery SPI. start_respo...
def _get_rpc_or_rest(self, api_format, request, start_response):
api = request.body_json['api'] version = request.body_json['version'] lookup_key = (api, version) api_config = self._config_manager.configs.get(lookup_key) if (not api_config): logging.warn('No discovery doc for version %s of api %s', version, api) return util...
'Sends HTTP response containing the API directory. This calls start_response and returns the response body. Args: start_response: A function with semantics defined in PEP-333. Returns: A string containing the response body.'
def _list(self, start_response):
api_configs = [] for api_config in self._config_manager.configs.itervalues(): if (not (api_config == self.API_CONFIG)): api_configs.append(json.dumps(api_config)) directory = self._discovery_proxy.generate_directory(api_configs) if (not directory): logging.error('Failed to...
'Returns the result of a discovery service request. This calls start_response and returns the response body. Args: path: A string containing the SPI API path (the portion of the path after /_ah/spi/). request: An ApiRequest, the transformed request sent to the Discovery SPI. start_response: A function with semantics de...
def handle_discovery_request(self, path, request, start_response):
if (path == self._GET_REST_API): return self._get_rpc_or_rest('rest', request, start_response) elif (path == self._GET_RPC_API): return self._get_rpc_or_rest('rpc', request, start_response) elif (path == self._LIST_API): return self._list(start_response) return False
'Make ApiConfigManager with a few helpful fakes.'
def setUp(self):
self.config_manager = api_config_manager.ApiConfigManager()
'Test that the parsed API config has switched HTTPS to HTTP.'
def test_parse_api_config_convert_https(self):
config = json.dumps({'name': 'guestbook_api', 'version': 'X', 'adapter': {'bns': 'https://localhost/_ah/spi', 'type': 'lily'}, 'root': 'https://localhost/_ah/api', 'methods': {}}) self.config_manager.parse_api_config_response(json.dumps({'items': [config]})) self.assertEqual('http://localhost/_ah/spi', self...
'Test that the _convert_https_to_http function works.'
def test_convert_https_to_http(self):
config = {'name': 'guestbook_api', 'version': 'X', 'adapter': {'bns': 'https://tictactoe.appspot.com/_ah/spi', 'type': 'lily'}, 'root': 'https://tictactoe.appspot.com/_ah/api', 'methods': {}} self.config_manager._convert_https_to_http(config) self.assertEqual('http://tictactoe.appspot.com/_ah/spi', config['...
'Verify that we don\'t change non-HTTPS URLs.'
def test_dont_convert_non_https_to_http(self):
config = {'name': 'guestbook_api', 'version': 'X', 'adapter': {'bns': 'http://https.appspot.com/_ah/spi', 'type': 'lily'}, 'root': 'ios://https.appspot.com/_ah/api', 'methods': {}} self.config_manager._convert_https_to_http(config) self.assertEqual('http://https.appspot.com/_ah/spi', config['adapter']['bns'...
'Assert that the given path does not match param_path pattern. For example, /xyz/123 does not match /abc/{x}. Args: path: A string, the inbound request path. param_path: A string, the parameterized path pattern to match against this path.'
def assert_no_match(self, path, param_path):
config_manager = api_config_manager.ApiConfigManager params = config_manager._compile_path_pattern(param_path).match(path) self.assertEqual(None, params)
'Assert that the given path does match param_path pattern. For example, /abc/123 does not match /abc/{x}. Args: path: A string, the inbound request path. param_path: A string, the parameterized path pattern to match against this path. param_count: An int, the expected number of parameters to match in pattern. Returns: ...
def assert_match(self, path, param_path, param_count):
config_manager = api_config_manager.ApiConfigManager match = config_manager._compile_path_pattern(param_path).match(path) self.assertTrue((match is not None)) params = config_manager._get_path_params(match) self.assertEquals(param_count, len(params)) return params
'Assert that the path parameter value is not valid. For example, /abc/3!:2 is invalid for /abc/{x}. Args: value: A string containing a variable value to check for validity.'
def assert_invalid_value(self, value):
param_path = '/abc/{x}' path = ('/abc/%s' % value) config_manager = api_config_manager.ApiConfigManager params = config_manager._compile_path_pattern(param_path).match(path) self.assertEqual(None, params)
'Constructor. Args: environ: An environ dict for the request as defined in PEP-333. Raises: ValueError: If the path for the request is invalid.'
def __init__(self, environ):
self.headers = util.get_headers_from_environ(environ) self.http_method = environ['REQUEST_METHOD'] self.server = environ['SERVER_NAME'] self.port = environ['SERVER_PORT'] self.path = environ['PATH_INFO'] self.query = environ.get('QUERY_STRING') self.body = environ['wsgi.input'].read() se...
'Reconstruct the relative URL of this request. This is based on the URL reconstruction code in Python PEP 333: http://www.python.org/dev/peps/pep-0333/#url-reconstruction. Rebuild the URL from the pieces available in the environment. Args: environ: An environ dict for the request as defined in PEP-333. Returns: The po...
def _reconstruct_relative_url(self, environ):
url = urllib.quote(environ.get('SCRIPT_NAME', '')) url += urllib.quote(environ.get('PATH_INFO', '')) if environ.get('QUERY_STRING'): url += ('?' + environ['QUERY_STRING']) return url
'Constructor. Args: json_object: The JSON object to compare against.'
def __init__(self, json_object):
self._json_object = json_object
'Check if the given object matches our json object. This converts json_string from a string to a JSON object, then compares it against our json object. Args: json_string: A string containing a JSON object to be compared against. Returns: True if the object matches, False if not.'
def equals(self, json_string):
other_json = json.loads(json_string) return (self._json_object == other_json)
'Set up a dev Endpoints server.'
def setUp(self):
super(DevAppserverEndpointsServerTest, self).setUp() self.mox = mox.Mox() self.config_manager = api_config_manager.ApiConfigManager() self.mock_dispatcher = self.mox.CreateMock(dispatcher.Dispatcher) self.server = endpoints_server.EndpointsDispatcher(self.mock_dispatcher, self.config_manager)
'Assert that dispatching a request to the SPI works. Mock out the dispatcher.add_request and handle_spi_response, and use these to ensure that the correct request is being sent to the back end when Dispatch is called. Args: request: An ApiRequest, the request to dispatch. config: A dict containing the API configuration...
def assert_dispatch_to_spi(self, request, config, spi_path, expected_spi_body_json=None):
self.prepare_dispatch(config) spi_headers = [('Content-Type', 'application/json')] spi_body_json = (expected_spi_body_json or {}) spi_response = dispatcher.ResponseTuple('200 OK', [], 'Test') self.mock_dispatcher.add_request('POST', spi_path, spi_headers, JsonMatches(spi_body_json), request.sourc...
'Test that an error response still handles CORS headers.'
def test_handle_non_json_spi_response_cors(self):
server_response = dispatcher.ResponseTuple('200 OK', [('Content-type', 'text/plain')], 'This is an invalid response.') response = self.check_cors([('origin', 'test.com')], True, 'test.com', server_response=server_response) self.assertEqual({'error': {'message': 'Non-JSON reply: This ...
'Check that CORS headers are handled correctly. Args: request_headers: A list of (header, value), to be used as headers in the request. expect_response: A boolean, whether or not CORS headers are expected in the response. expected_origin: A string or None. If this is a string, this is the value that\'s expected in the...
def check_cors(self, request_headers, expect_response, expected_origin=None, expected_allow_headers=None, server_response=None):
orig_request = test_utils.build_request('/_ah/api/fake/path', http_headers=request_headers) spi_request = orig_request.copy() if (server_response is None): server_response = dispatcher.ResponseTuple('200 OK', [('Content-type', 'application/json')], '{}') response = self.server.handle_spi_resp...
'Test CORS support on a regular request.'
def test_handle_cors(self):
self.check_cors([('origin', 'test.com')], True, 'test.com')
'Test a CORS preflight request.'
def test_handle_cors_preflight(self):
self.check_cors([('origin', 'http://example.com'), ('Access-control-request-method', 'GET')], True, 'http://example.com')
'Test a CORS preflight request for an unaccepted OPTIONS request.'
def test_handle_cors_preflight_invalid(self):
self.check_cors([('origin', 'http://example.com'), ('Access-control-request-method', 'OPTIONS')], False)
'Test a CORS preflight request.'
def test_handle_cors_preflight_request_headers(self):
self.check_cors([('origin', 'http://example.com'), ('Access-control-request-method', 'GET'), ('Access-Control-Request-Headers', 'Date,Expires')], True, 'http://example.com', 'Date,Expires')
'Verify Lily protocol correctly uses python method name. This test verifies the fix to http://b/7189819'
def test_lily_uses_python_method_name(self):
config = json.dumps({'name': 'guestbook_api', 'version': 'X', 'methods': {'author.greeting.info.get': {'httpMethod': 'GET', 'path': 'authors/{aid}/greetings/{gid}/infos/{iid}', 'rosyMethod': 'InfoService.get'}}}) request = test_utils.build_request('/_ah/api/rpc', '{"method": "author.greeting.info.get", "a...
'Verify headers transformed, JsonRpc response transformed, written.'
def test_handle_spi_response_json_rpc(self):
orig_request = test_utils.build_request('/_ah/api/rpc', '{"method": "foo.bar", "apiVersion": "X"}') self.assertTrue(orig_request.is_rpc()) orig_request.request_id = 'Z' spi_request = orig_request.copy() spi_response = dispatcher.ResponseTuple('200 OK', [('a', 'b')], '{"some": "respons...
'Verify that batch requests have an appropriate batch response.'
def test_handle_spi_response_batch_json_rpc(self):
orig_request = test_utils.build_request('/_ah/api/rpc', '[{"method": "foo.bar", "apiVersion": "X"}]') self.assertTrue(orig_request.is_batch()) self.assertTrue(orig_request.is_rpc()) orig_request.request_id = 'Z' spi_request = orig_request.copy() spi_response = dispatcher.ResponseTuple('...
'Verify the response is reformatted correctly.'
def test_transform_rest_response(self):
orig_response = '{"sample": "test", "value1": {"value2": 2}}' expected_response = '{\n "sample": "test", \n "value1": {\n "value2": 2\n }\n}' self.assertEqual(expected_response, self.server.transform_rest_response(orig_response))
'Verify request_id inserted into the body, and body into body.result.'
def test_transform_json_rpc_response(self):
orig_request = test_utils.build_request('/_ah/api/rpc', '{"params": {"sample": "body"}, "id": "42"}') request = orig_request.copy() request.request_id = '42' response = self.server.transform_jsonrpc_response(request, '{"sample": "body"}') self.assertEqual({'result': {'sample': 'body'}...
'Verify request_id inserted into the body, and body into body.result.'
def test_transform_json_rpc_response_batch(self):
orig_request = test_utils.build_request('/_ah/api/rpc', '[{"params": {"sample": "body"}, "id": "42"}]') request = orig_request.copy() request.request_id = '42' response = self.server.transform_jsonrpc_response(request, '{"sample": "body"}') self.assertEqual([{'result': {'sample': 'bod...
'Set up a dev Endpoints server.'
def setUp(self):
super(TransformRequestTests, self).setUp() self.mox = mox.Mox() self.config_manager = api_config_manager.ApiConfigManager() self.mock_dispatcher = self.mox.CreateMock(dispatcher.Dispatcher) self.server = endpoints_server.EndpointsDispatcher(self.mock_dispatcher, self.config_manager)
'Verify path is method name after a request is transformed.'
def test_transform_request(self):
request = test_utils.build_request('/_ah/api/test/{gid}', '{"sample": "body"}') method_config = {'rosyMethod': 'GuestbookApi.greetings_get'} new_request = self.server.transform_request(request, {'gid': 'X'}, method_config) self.assertEqual({'sample': 'body', 'gid': 'X'}, json.loads(new_request.body))...
'Verify request_id is extracted and body is scoped to body.params.'
def test_transform_json_rpc_request(self):
orig_request = test_utils.build_request('/_ah/api/rpc', '{"params": {"sample": "body"}, "id": "42"}') new_request = self.server.transform_jsonrpc_request(orig_request) self.assertEqual({'sample': 'body'}, json.loads(new_request.body)) self.assertEqual('42', new_request.request_id)
'Takes body, query and path values from a rest request for testing. Args: path_parameters: A dict containing the parameters parsed from the path. For example if the request came through /a/b for the template /a/{x} then we\'d have {\'x\': \'b\'}. query_parameters: A dict containing the parameters parsed from the query ...
def _try_transform_rest_request(self, path_parameters, query_parameters, body_json, expected, method_params=None):
method_params = (method_params or {}) test_request = test_utils.build_request('/_ah/api/test') test_request.body_json = body_json test_request.body = json.dumps(body_json) test_request.parameters = query_parameters transformed_request = self.server.transform_rest_request(test_request, path_param...
'Test that a GET request to a REST API works.'
def test_rest_get(self):
(status, content, headers) = self.fetch_url('default', 'GET', '/_ah/api/test_service/v1/test') self.assertEqual(200, status) self.assertEqual('application/json', headers['Content-Type']) response_json = json.loads(content) self.assertEqual({'text': 'Test response'}, response_json)
'Test that a POST request to a REST API works.'
def test_rest_post(self):
body = json.dumps({'name': 'MyName', 'number': 23}) send_headers = {'content-type': 'application/json'} (status, content, headers) = self.fetch_url('default', 'POST', '/_ah/api/test_service/v1/t2path', body, send_headers) self.assertEqual(200, status) self.assertEqual('application/json', headers['Co...
'Test that CORS headers are handled properly.'
def test_cors(self):
send_headers = {'Origin': 'test.com', 'Access-control-request-method': 'GET', 'Access-Control-Request-Headers': 'Date,Expires'} (status, _, headers) = self.fetch_url('default', 'GET', '/_ah/api/test_service/v1/test', headers=send_headers) self.assertEqual(200, status) self.assertEqual(headers[endpoints_...
'Test that an RPC request works.'
def test_rpc(self):
body = json.dumps([{'jsonrpc': '2.0', 'id': 'gapiRpc', 'method': 'testservice.t2name', 'params': {'name': 'MyName', 'number': 23}, 'apiVersion': 'v1'}]) send_headers = {'content-type': 'application-rpc'} (status, content, headers) = self.fetch_url('default', 'POST', '/_ah/api/rpc', body, send_headers) s...
'Test sending and receiving a datetime.'
def test_echo_datetime_message(self):
body = json.dumps({'milliseconds': 5000, 'time_zone_offset': 60}) send_headers = {'content-type': 'application/json'} (status, content, headers) = self.fetch_url('default', 'POST', '/_ah/api/test_service/v1/echo_datetime_message', body, send_headers) self.assertEqual(200, status) self.assertEqual('a...
'Test sending and receiving a message that includes a datetime.'
def test_echo_datetime_field(self):
body_json = {'datetime_value': '2013-03-13T15:29:37.883000+08:00'} body = json.dumps(body_json) send_headers = {'content-type': 'application/json'} (status, content, headers) = self.fetch_url('default', 'POST', '/_ah/api/test_service/v1/echo_datetime_field', body, send_headers) self.assertEqual(200,...
'Test that the discovery configuration looks right.'
def test_discovery_config(self):
(status, content, headers) = self.fetch_url('default', 'GET', '/_ah/api/discovery/v1/apis/test_service/v1/rest') self.assertEqual(200, status) self.assertEqual('application/json; charset=UTF-8', headers['Content-Type']) response_json = json.loads(content) self.assertRegexpMatches(response_json['b...
'Proxies GET request to discovery service API. Args: path: A string containing the URL path relative to discovery service. body: A string containing the HTTP POST request body. Returns: HTTP response body or None if it failed.'
def _dispatch_request(self, path, body):
full_path = (self._DISCOVERY_API_PATH_PREFIX + path) headers = {'Content-type': 'application/json'} connection = httplib.HTTPSConnection(self._DISCOVERY_PROXY_HOST) try: connection.request('POST', full_path, body, headers) response = connection.getresponse() response_body = respo...
'Generates a discovery document from an API file. Args: api_config: A string containing the .api file contents. api_format: A string, either \'rest\' or \'rpc\' depending on the which kind of discvoery doc is requested. Returns: The discovery doc as JSON string. Raises: ValueError: When api_format is invalid.'
def generate_discovery_doc(self, api_config, api_format):
if (api_format not in ['rest', 'rpc']): raise ValueError('Invalid API format') path = ('apis/generate/' + api_format) request_dict = {'config': json.dumps(api_config)} request_body = json.dumps(request_dict) return self._dispatch_request(path, request_body)
'Generates an API directory from a list of API files. Args: api_configs: A list of strings which are the .api file contents. Returns: The API directory as JSON string.'
def generate_directory(self, api_configs):
request_dict = {'configs': api_configs} request_body = json.dumps(request_dict) return self._dispatch_request('apis/generate/directory', request_body)
'Returns static content via a GET request. Args: path: A string containing the URL path after the domain. Returns: A tuple of (response, response_body): response: A HTTPResponse object with the response from the static proxy host. response_body: A string containing the response body.'
def get_static_file(self, path):
connection = httplib.HTTPSConnection(self._STATIC_PROXY_HOST) try: connection.request('GET', path, None, {}) response = connection.getresponse() response_body = response.read() finally: connection.close() return (response, response_body)
'JSON string representing the rejected value. Calling this will fail on the base class since it relies on Message and Errors being implemented on the class. It is up to a subclass to implement these methods. Returns: JSON string representing the rejected value.'
def to_json(self):
return json.dumps({'error': {'errors': self.errors(), 'code': 400, 'message': self.message()}})
'Constructor for EnumRejectionError. Args: parameter_name: String; the name of the enum parameter which had a value rejected. value: The actual value passed in for the enum. Usually string. allowed_values: List of strings allowed for the enum.'
def __init__(self, parameter_name, value, allowed_values):
super(EnumRejectionError, self).__init__() self.parameter_name = parameter_name self.value = value self.allowed_values = allowed_values
'A descriptive message describing the error.'
def message(self):
return (_INVALID_ENUM_TEMPLATE % (self.value, self.allowed_values))
'A list containing the errors associated with the rejection. Intended to mimic those returned from an API in production in Google\'s API infrastructure. Returns: A list with a single element that is a dictionary containing the error information.'
def errors(self):
return [{'domain': 'global', 'reason': 'invalidParameter', 'message': self.message(), 'locationType': 'parameter', 'location': self.parameter_name}]
'Switch the URLs in one API configuration to use HTTP instead of HTTPS. When doing local development in the dev server, any requests to the API need to use HTTP rather than HTTPS. This converts the API configuration to use HTTP. With this change, client libraries that use the API configuration will now be able to com...
def _convert_https_to_http(self, config):
if (('adapter' in config) and ('bns' in config['adapter'])): bns_adapter = config['adapter']['bns'] if bns_adapter.startswith('https://'): config['adapter']['bns'] = bns_adapter.replace('https', 'http', 1) if (('root' in config) and config['root'].startswith('https://')): con...
'Parses a json api config and registers methods for dispatch. Side effects: Parses method name, etc for all methods and updates the indexing datastructures with the information. Args: body: A string, the JSON body of the getApiConfigs response.'
def parse_api_config_response(self, body):
try: response_obj = json.loads(body) except ValueError as unused_err: logging.error('Cannot parse BackendService.getApiConfigs response: %s', body) else: with self._config_lock: self._add_discovery_config() for api_config_json in response_obj.get('...
'Get a copy of \'methods\' sorted the way they would be on the live server. Args: methods: JSON configuration of an API\'s methods. Returns: The same configuration with the methods sorted based on what order they\'ll be checked by the server.'
def _get_sorted_methods(self, methods):
if (not methods): return methods def _sorted_methods_comparison(method_info1, method_info2): "Sort method info by path and http_method.\n\n Args:\n method_info1: Method name and info for the first met...
'Gets path parameters from a regular expression match. Args: match: A regular expression Match object for a path. Returns: A dictionary containing the variable names converted from base64.'
@staticmethod def _get_path_params(match):
result = {} for (var_name, value) in match.groupdict().iteritems(): actual_var_name = ApiConfigManager._from_safe_path_param_name(var_name) result[actual_var_name] = value return result
'Lookup the JsonRPC method at call time. The method is looked up in self._rpc_method_dict, the dictionary that it is saved in for SaveRpcMethod(). Args: method_name: A string containing the name of the method. version: A string containing the version of the API. Returns: Method descriptor as specified in the API config...
def lookup_rpc_method(self, method_name, version):
with self._config_lock: method = self._rpc_method_dict.get((method_name, version)) return method
'Look up the rest method at call time. The method is looked up in self._rest_methods, the list it is saved in for SaveRestMethod. Args: path: A string containing the path from the URL of the request. http_method: A string containing HTTP method of the request. Returns: Tuple of (<method name>, <method>, <params>) Where...
def lookup_rest_method(self, path, http_method):
with self._config_lock: for (compiled_path_pattern, unused_path, methods) in self._rest_methods: match = compiled_path_pattern.match(path) if match: params = self._get_path_params(match) version = match.group(2) method_key = (http_metho...
'Creates a safe string to be used as a regex group name. Only alphanumeric characters and underscore are allowed in variable name tokens, and numeric are not allowed as the first character. We cast the matched_parameter to base32 (since the alphabet is safe), strip the padding (= not safe) and prepend with _, since we ...
@staticmethod def _to_safe_path_param_name(matched_parameter):
return ('_' + base64.b32encode(matched_parameter).rstrip('='))
'Takes a safe regex group name and converts it back to the original value. Only alphanumeric characters and underscore are allowed in variable name tokens, and numeric are not allowed as the first character. The safe_parameter is a base32 representation of the actual value. Args: safe_parameter: A string that was gener...
@staticmethod def _from_safe_path_param_name(safe_parameter):
assert safe_parameter.startswith('_') safe_parameter_as_base32 = safe_parameter[1:] padding_length = ((- len(safe_parameter_as_base32)) % 8) padding = ('=' * padding_length) return base64.b32decode((safe_parameter_as_base32 + padding))
'Generates a compiled regex pattern for a path pattern. e.g. \'/{!name}/{!version}/notes/{id}\' returns re.compile(r\'/([^:/?#\[\]{}]*)\' r\'/([^:/?#\[\]{}]*)\' r\'/notes/(?P<id>[^:/?#\[\]{}]*)\') Note in this example that !name and !version are reserved variable names used to match the API name and version that should...
@staticmethod def _compile_path_pattern(pattern):
def replace_reserved_variable(match): 'Replaces a {!variable} with a regex to match it not by name.\n\n Args:\n match: A regex match object, the matching regex group as sent by\n ...
'Store JsonRpc api methods in a map for lookup at call time. (rpcMethodName, apiVersion) => method. Args: method_name: A string containing the name of the API method. version: A string containing the version of the API. method: A dict containing the method descriptor (as in the api config file).'
def _save_rpc_method(self, method_name, version, method):
self._rpc_method_dict[(method_name, version)] = method
'Store Rest api methods in a list for lookup at call time. The list is self._rest_methods, a list of tuples: [(<compiled_path>, <path_pattern>, <method_dict>), ...] where: <compiled_path> is a compiled regex to match against the incoming URL <path_pattern> is a string representing the original path pattern, checked on ...
def _save_rest_method(self, method_name, version, method):
path_pattern = (_API_REST_PATH_FORMAT % method.get('path', '')) http_method = method.get('httpMethod', '').lower() for (_, path, methods) in self._rest_methods: if (path == path_pattern): methods[(http_method, version)] = (method_name, method) break else: self._re...
'Verify that additional items are dropped if the batch size is > 1.'
def test_batch_too_large(self):
request = test_utils.build_request('/_ah/api/rpc', '[{"method": "foo", "apiVersion": "v1"},{"method": "bar", "apiversion": "v1"}]') self.assertTrue(request.is_batch()) self.assertEqual(json.loads('{"method": "foo", "apiVersion": "v1"}'), request.body_json)
'Test that the headers and body match.'
def assert_http_match(self, response, expected_status, expected_headers, expected_body):
self.assertEqual(str(expected_status), self.response_status) self.assertEqual(len(self.response_headers), len(expected_headers)) self.assertEqual(set(self.response_headers), set(expected_headers)) self.assertEqual(len(self.response_headers), len(set((header for (header, _) in self.response_headers)))) ...
'Constructor for EndpointsDispatcher. Args: dispatcher: A Dispatcher instance that can be used to make HTTP requests. config_manager: An ApiConfigManager instance that allows a caller to set up an existing configuration for testing.'
def __init__(self, dispatcher, config_manager=None):
self._dispatcher = dispatcher if (config_manager is None): config_manager = api_config_manager.ApiConfigManager() self.config_manager = config_manager self._dispatchers = [] self._add_dispatcher('/_ah/api/explorer/?$', self.handle_api_explorer_request) self._add_dispatcher('/_ah/api/stat...
'Add a request path and dispatch handler. Args: path_regex: A string regex, the path to match against incoming requests. dispatch_function: The function to call for these requests. The function should take (request, start_response) as arguments and return the contents of the response body.'
def _add_dispatcher(self, path_regex, dispatch_function):
self._dispatchers.append((re.compile(path_regex), dispatch_function))
'Handle an incoming request. Args: environ: An environ dict for the request as defined in PEP-333. start_response: A function used to begin the response to the caller. This follows the semantics defined in PEP-333. In particular, it\'s called with (status, response_headers, exc_info=None), and it returns an object wit...
def __call__(self, environ, start_response):
request = api_request.ApiRequest(environ) (yield self.dispatch(request, start_response))
'Handles dispatch to apiserver handlers. This typically ends up calling start_response and returning the entire body of the response. Args: request: An ApiRequest, the request from the user. start_response: A function with semantics defined in PEP-333. Returns: A string, the body of the response.'
def dispatch(self, request, start_response):
dispatched_response = self.dispatch_non_api_requests(request, start_response) if (dispatched_response is not None): return dispatched_response api_config_response = self.get_api_configs() if (not self.handle_get_api_configs_response(api_config_response)): return self.fail_request(request...
'Dispatch this request if this is a request to a reserved URL. If the request matches one of our reserved URLs, this calls start_response and returns the response body. Args: request: An ApiRequest, the request from the user. start_response: A function with semantics defined in PEP-333. Returns: None if the request doe...
def dispatch_non_api_requests(self, request, start_response):
for (path_regex, dispatch_function) in self._dispatchers: if path_regex.match(request.relative_url): return dispatch_function(request, start_response) return None
'Handler for requests to _ah/api/explorer. This calls start_response and returns the response body. Args: request: An ApiRequest, the request from the user. start_response: A function with semantics defined in PEP-333. Returns: A string containing the response body (which is empty, in this case).'
def handle_api_explorer_request(self, request, start_response):
base_url = ('http://%s:%s/_ah/api' % (request.server, request.port)) redirect_url = (self._API_EXPLORER_URL + base_url) return util.send_wsgi_redirect_response(redirect_url, start_response)
'Handler for requests to _ah/api/static/.*. This calls start_response and returns the response body. Args: request: An ApiRequest, the request from the user. start_response: A function with semantics defined in PEP-333. Returns: A string containing the response body.'
def handle_api_static_request(self, request, start_response):
discovery_api = discovery_api_proxy.DiscoveryApiProxy() (response, body) = discovery_api.get_static_file(request.relative_url) status_string = ('%d %s' % (response.status, response.reason)) if (response.status == 200): return util.send_wsgi_response(status_string, [('Content-Type', response.g...
'Makes a call to the BackendService.getApiConfigs endpoint. Returns: A ResponseTuple containing the response information from the HTTP request.'
def get_api_configs(self):
headers = [('Content-Type', 'application/json')] request_body = '{}' response = self._dispatcher.add_request('POST', '/_ah/spi/BackendService.getApiConfigs', headers, request_body, _SERVER_SOURCE_IP) return response
'Verifies that a response has the expected status and content type. Args: response: The ResponseTuple to be checked. status_code: An int, the HTTP status code to be compared with response status. content_type: A string with the acceptable Content-Type header value. None allows any content type. Returns: True if both st...
@staticmethod def verify_response(response, status_code, content_type=None):
status = int(response.status.split(' ', 1)[0]) if (status != status_code): return False if (content_type is None): return True for (header, value) in response.headers: if (header.lower() == 'content-type'): return (value == content_type) else: return Fa...
'Parses the result of GetApiConfigs and stores its information. Args: api_config_response: The ResponseTuple from the GetApiConfigs call. Returns: True on success, False on failure'
def handle_get_api_configs_response(self, api_config_response):
if self.verify_response(api_config_response, 200, 'application/json'): self.config_manager.parse_api_config_response(api_config_response.content) return True else: return False
'Generate SPI call (from earlier-saved request). This calls start_response and returns the response body. Args: orig_request: An ApiRequest, the original request from the user. start_response: A function with semantics defined in PEP-333. Returns: A string containing the response body.'
def call_spi(self, orig_request, start_response):
if orig_request.is_rpc(): method_config = self.lookup_rpc_method(orig_request) params = None else: (method_config, params) = self.lookup_rest_method(orig_request) if (not method_config): cors_handler = EndpointsDispatcher.__CheckCorsHeaders(orig_request) return util.s...
'Check for a CORS request, and see if it gets a CORS response.'
def __check_cors_request(self, request):
self.origin = request.headers[_CORS_HEADER_ORIGIN] self.cors_request_method = request.headers[_CORS_HEADER_REQUEST_METHOD] self.cors_request_headers = request.headers[_CORS_HEADER_REQUEST_HEADERS] if (self.origin and ((self.cors_request_method is None) or (self.cors_request_method.upper() in _CORS_ALLOW...
'Add CORS headers to the response, if needed.'
def update_headers(self, headers_in):
if (not self.allow_cors_request): return headers = wsgiref.headers.Headers(headers_in) headers[_CORS_HEADER_ALLOW_ORIGIN] = self.origin headers[_CORS_HEADER_ALLOW_METHODS] = ','.join(tuple(_CORS_ALLOWED_METHODS)) if (self.cors_request_headers is not None): headers[_CORS_HEADER_ALLOW_...
'Handle SPI response, transforming output as needed. This calls start_response and returns the response body. Args: orig_request: An ApiRequest, the original request from the user. spi_request: An ApiRequest, the transformed request that was sent to the SPI handler. response: A ResponseTuple, the response from the SPI ...
def handle_spi_response(self, orig_request, spi_request, response, start_response):
for (header, value) in response.headers: if ((header.lower() == 'content-type') and (not value.lower().startswith('application/json'))): return self.fail_request(orig_request, ('Non-JSON reply: %s' % response.content), start_response) body = response.content if orig_request.is_rpc(...
'Write an immediate failure response to outfile, no redirect. This calls start_response and returns the error body. Args: orig_request: An ApiRequest, the original request from the user. message: A string containing the error message to be displayed to user. start_response: A function with semantics defined in PEP-333....
def fail_request(self, orig_request, message, start_response):
cors_handler = EndpointsDispatcher.__CheckCorsHeaders(orig_request) return util.send_wsgi_error_response(message, start_response, cors_handler=cors_handler)
'Looks up and returns rest method for the currently-pending request. Args: orig_request: An ApiRequest, the original request from the user. Returns: A tuple of (method descriptor, parameters), or (None, None) if no method was found for the current request.'
def lookup_rest_method(self, orig_request):
(method_name, method, params) = self.config_manager.lookup_rest_method(orig_request.path, orig_request.http_method) orig_request.method_name = method_name return (method, params)
'Looks up and returns RPC method for the currently-pending request. Args: orig_request: An ApiRequest, the original request from the user. Returns: The RPC method descriptor that was found for the current request, or None if none was found.'
def lookup_rpc_method(self, orig_request):
if (not orig_request.body_json): return None method_name = orig_request.body_json.get('method', '') version = orig_request.body_json.get('apiVersion', '') orig_request.method_name = method_name return self.config_manager.lookup_rpc_method(method_name, version)
'Transforms orig_request to apiserving request. This method uses orig_request to determine the currently-pending request and returns a new transformed request ready to send to the SPI. This method accepts a rest-style or RPC-style request. Args: orig_request: An ApiRequest, the original request from the user. params: ...
def transform_request(self, orig_request, params, method_config):
if orig_request.is_rpc(): request = self.transform_jsonrpc_request(orig_request) else: method_params = method_config.get('request', {}).get('parameters', {}) request = self.transform_rest_request(orig_request, params, method_params) request.path = method_config.get('rosyMethod', '') ...
'Checks if the parameter value is valid if an enum. If the parameter is not an enum, does nothing. If it is, verifies that its value is valid. Args: parameter_name: A string containing the name of the parameter, which is either just a variable name or the name with the index appended. For example \'var\' or \'var[2]\'....
def _check_enum(self, parameter_name, value, field_parameter):
if ('enum' not in field_parameter): return enum_values = [enum['backendValue'] for enum in field_parameter['enum'].values() if ('backendValue' in enum)] if (value not in enum_values): raise errors.EnumRejectionError(parameter_name, value, enum_values)
'Checks if the parameter value is valid against all parameter rules. If the value is a list this will recursively call _check_parameter on the values in the list. Otherwise, it checks all parameter rules for the the current value. In the list case, \'[index-of-value]\' is appended to the parameter name for error report...
def _check_parameter(self, parameter_name, value, field_parameter):
if isinstance(value, list): for (index, element) in enumerate(value): parameter_name_index = ('%s[%d]' % (parameter_name, index)) self._check_parameter(parameter_name_index, element, field_parameter) return self._check_enum(parameter_name, value, field_parameter)
'Converts a . delimitied field name to a message field in parameters. This adds the field to the params dict, broken out so that message parameters appear as sub-dicts within the outer param. For example: {\'a.b.c\': [\'foo\']} becomes: {\'a\': {\'b\': {\'c\': [\'foo\']}}} Args: field_name: A string containing the \'.\...
def _add_message_field(self, field_name, value, params):
if ('.' not in field_name): params[field_name] = value return (root, remaining) = field_name.split('.', 1) sub_params = params.setdefault(root, {}) self._add_message_field(remaining, value, sub_params)
'Updates the dictionary for an API payload with the request body. The values from the body should override those already in the payload, but for nested fields (message objects) the values can be combined recursively. Args: destination: A dictionary containing an API payload parsed from the path and query parameters in ...
def _update_from_body(self, destination, source):
for (key, value) in source.iteritems(): destination_value = destination.get(key) if (isinstance(value, dict) and isinstance(destination_value, dict)): self._update_from_body(destination_value, value) else: destination[key] = value
'Translates a Rest request into an apiserving request. This makes a copy of orig_request and transforms it to apiserving format (moving request parameters to the body). The request can receive values from the path, query and body and combine them before sending them along to the SPI server. In cases of collision, objec...
def transform_rest_request(self, orig_request, params, method_parameters):
request = orig_request.copy() body_json = {} for (key, value) in params.iteritems(): body_json[key] = [value] if request.parameters: for (key, value) in request.parameters.iteritems(): if (key in body_json): body_json[key] = (value + body_json[key]) ...
'Translates a JsonRpc request/response into apiserving request/response. Args: orig_request: An ApiRequest, the original request from the user. Returns: A new request with the request_id updated and params moved to the body.'
def transform_jsonrpc_request(self, orig_request):
request = orig_request.copy() request.request_id = request.body_json.get('id') request.body_json = request.body_json.get('params', {}) request.body = json.dumps(request.body_json) return request