Пример #1
0
def application(environ: Mapping, start_response: Callable):
    response_code = '200 OK'
    headers = [('Content-Type', 'application/json'),
               ('Access-Control-Allow-Headers', ', '.join((
                   'accept',
                   'accept-encoding',
                   'content-type',
                   'origin',
                   'user-agent',
                   'x-requested-with',
               )))]

    # origin check
    origin = environ.get('HTTP_ORIGIN', '')
    if ONLY_ACCEPTED_ORIGIN and origin.find(ACCEPTED_ORIGIN) == -1:
        content = create_error_response(
            f'The ORIGIN, {ACCEPTED_ORIGIN}, is not accepted.')
    else:
        try:
            content = application_helper(environ)
        except Exception as e:
            content = create_error_response(
                f'An exception occurs in the server. Error: {e}')

    headers.append(('Access-Control-Allow-Origin', origin))
    start_response(response_code, headers)
    return [json.dumps(content, cls=StringEncoder).encode()]
Пример #2
0
def application_helper(environ: Mapping) -> Mapping:
    method = environ.get('REQUEST_METHOD')
    path = environ.get('PATH_INFO')

    # info page
    if method == 'GET' and path == '/env':
        return create_data_response(environ)

    # entry point check
    if method != 'POST' or path != '/run':
        return create_error_response('Bad Request: Wrong Methods.')

    # get request content
    request_body = environ['wsgi.input'].read(int(environ['CONTENT_LENGTH']))
    request_json_object = json.loads(request_body)
    if REQUEST_VERSION_NAME not in request_json_object or request_json_object[
            REQUEST_VERSION_NAME] != VERSION:
        return create_error_response(
            'The current version of your local server (%s) does not match version of the web '
            'app ("%s"). Please download the newest version at '
            'https://github.com/FlickerSoul/Graphery/releases.' %
            (VERSION, request_json_object.get(REQUEST_VERSION_NAME,
                                              'Not Exist')))

    if REQUEST_CODE_NAME not in request_json_object:
        return create_error_response(
            'No Code Snippets Embedded In The Request.')

    if REQUEST_GRAPH_NAME not in request_json_object:
        return create_error_response('No Graph Intel Embedded In The Request.')

    # execute program with timed out
    return time_out_execute(code=request_json_object[REQUEST_CODE_NAME],
                            graph_json=request_json_object[REQUEST_GRAPH_NAME])
Пример #3
0
def time_out_execute(*args, **kwargs) -> Mapping:
    with Pool(processes=1) as pool:
        try:
            result = pool.apply_async(func=execute, args=args, kwds=kwargs)

            code_hash, exec_result = result.get(timeout=TIMEOUT_SECONDS)

            response_dict = create_data_response({
                'codeHash': code_hash,
                'execResult': exec_result
            })
        except TimeoutError:
            response_dict = create_error_response(
                f'Timeout: Code running timed out after {TIMEOUT_SECONDS}s.')
        except ExecutionException as e:
            if e.empty:
                response_dict = create_error_response(
                    f'Unknown Exception: {e}')
            else:
                exec_info = e.related_exec_info[-1]
                response_dict = create_error_response(f'{e}\n' +
                                                      'At line {}: `{}`\n'
                                                      'in {}'.format(
                                                          *exec_info))
        except ExecutionServerException as e:
            response_dict = create_error_response(f'Server Exception: {e}')
        except Exception as e:
            response_dict = create_error_response(f'Unknown Exception: {e}.')

        print('Execution done.')
    return response_dict
Пример #4
0
    def execute(code: str, graph_json_obj: Mapping) -> Mapping:
        if code and graph_json_obj:
            response = post_request('http://localhost:7590/run',
                                    data={'code': code,
                                          'graph': graph_json_obj,
                                          'version': VERSION})
            if 'errors' in response:
                return create_error_response(response['errors'][0]['message'])

            return response

        return create_error_response('Cannot Read Code Or Graph Object')
Пример #5
0
def test_create_error_response():
    error_message = 'error_message'
    assert create_error_response(error_message) == {
        'errors': [{
            'message': error_message
        }]
    }
Пример #6
0
    def execute(code: str, graph_json_obj: Mapping) -> Mapping:
        if code and graph_json_obj:
            response = post_request(f'{_REMOTE_URL}:7590/run',
                                    data={
                                        'code': code,
                                        'graph': graph_json_obj,
                                        'version': VERSION
                                    })
            return response

        return create_error_response('Cannot Read Code Or Graph Object')
Пример #7
0
def time_out_execute(*args, **kwargs):
    with Pool(processes=1) as pool:
        try:
            result = pool.apply_async(func=execute, args=args, kwds=kwargs)

            code_hash, exec_result = result.get(timeout=TIMEOUT_SECONDS)

            response_dict = create_data_response({
                'codeHash': code_hash,
                'execResult': exec_result
            })
        except TimeoutError:
            response_dict = create_error_response(
                f'Timeout: Code running timed out after {TIMEOUT_SECONDS} s.')
        except ExecutionException as e:
            # TODO try to give detailed exception location feedback
            response_dict = create_error_response(f'Exception: {e}.')
        except Exception as e:
            response_dict = create_error_response(f'Unknown Exception: {e}.')

        print('Execution done.')
    return response_dict
Пример #8
0
                for edge in graph_object.V:
                    print(edge)
            ''')


@pytest.mark.parametrize(
    'env, response',
    [
        pytest.param(
            Env(REQUEST_METHOD='GET', PATH_INFO='/env').content,
            create_data_response(
                Env(REQUEST_METHOD='GET',
                    PATH_INFO='/env').content)),  # info page
        pytest.param(
            Env(REQUEST_METHOD='GET', PATH_INFO='/venv').content,
            create_error_response(
                'Bad Request: Wrong Methods.')),  # wrong request method
        pytest.param(
            Env(REQUEST_METHOD='POST', PATH_INFO='/env').content,
            create_error_response(
                'Bad Request: Wrong Methods.')),  # wrong entry point
        pytest.param(
            Env(REQUEST_METHOD='POST', PATH_INFO='/run',
                CONTENT_LENGTH='1').add_content({
                    'wsgi.input':
                    FileLikeObj(json.dumps({}))
                }).content,
            create_error_response(
                'The current version of your local server (%s) does not match version of the web '
                'app ("Not Exist"). Please download the newest version at '
                'https://github.com/FlickerSoul/Graphery/releases.' %
                VERSION)),  # no version
Пример #9
0
def generate_respond_error_message(
        err_message: Union[Exception, str]) -> Mapping:
    return generate_respond_message(response_type=ResponseType.STOPPED.value,
                                    response_mapping=create_error_response(
                                        str(err_message)))