def record_put(request):
    collection_name = request.matchdict['collection_name']

    assert_endpoint_enabled(request, collection_name)

    record_id = request.matchdict['record_id']
    sync_id = record_id

    headers = import_headers(request)
    record = request.validated['data']
    record['id'] = sync_id

    # Remove read-only fields
    record.pop('last_modified', None)

    sync_client = build_sync_client(request)
    last_modified = sync_client.put_record(collection_name,
                                           record,
                                           headers=headers)
    record['last_modified'] = int(last_modified * 1000)
    record['id'] = record_id

    # Configure headers
    export_headers(sync_client.raw_resp, request)

    statsd_count(request, "syncclient.status_code.200")

    return {'data': record}
Example #2
0
def record_put(request):
    collection_name = request.matchdict['collection_name']

    assert_endpoint_enabled(request, collection_name)

    record_id = request.matchdict['record_id']
    sync_id = record_id

    headers = import_headers(request)
    record = request.validated['data']
    record['id'] = sync_id

    # Remove read-only fields
    record.pop('last_modified', None)

    sync_client = build_sync_client(request)
    last_modified = sync_client.put_record(collection_name, record,
                                           headers=headers)
    record['last_modified'] = int(last_modified * 1000)
    record['id'] = record_id

    # Configure headers
    export_headers(sync_client.raw_resp, request)

    statsd_count(request, "syncclient.status_code.200")

    return {'data': record}
Example #3
0
def collection_get(request):
    collection_name = request.matchdict['collection_name']
    sync_client = build_sync_client(request)

    headers = import_headers(request)

    params = {}
    if '_since' in request.GET:
        try:
            params['newer'] = '%.2f' % (int(request.GET['_since']) / 1000.0)
        except ValueError:
            error_msg = ("_since should be a number.")
            raise_invalid(request,
                          location="querystring",
                          name="_since",
                          description=error_msg)

    if '_limit' in request.GET:
        params['limit'] = request.GET['_limit']

    if '_token' in request.GET:
        params['offset'] = request.GET['_token']

    if '_sort' in request.GET:
        if request.GET['_sort'] in ('-last_modified', 'newest'):
            params['sort'] = 'newest'

        elif request.GET['_sort'] in ('-sortindex', 'index'):
            params['sort'] = 'index'

        elif request.GET['_sort'] in ('last_modified', 'oldest'):
            params['sort'] = 'oldest'

        else:
            error_msg = ("_sort should be one of ('-last_modified', 'newest', "
                         "'-sortindex', 'index', 'last_modified', 'oldest')")
            raise_invalid(request,
                          location="querystring",
                          name="_sort",
                          description=error_msg)

    if 'in_ids' in request.GET:
        params['ids'] = [record_id.strip() for record_id in
                         request.GET['in_ids'].split(',') if record_id]

    records = sync_client.get_records(collection_name, full=True,
                                      headers=headers, **params)

    statsd_count(request, "syncclient.status_code.200")

    for r in records:
        r['last_modified'] = int(r.pop('modified') * 1000)

    # Configure headers
    export_headers(sync_client.raw_resp, request)

    if '_limit' in request.GET and 'Total-Records' in request.response.headers:
        del request.response.headers['Total-Records']

    return {'data': records or []}
def response_error(context, request):
    """Catch response error from Sync and trace them."""
    message = '%s %s: %s' % (context.response.status_code,
                             context.response.reason,
                             context.response.text)

    # XXX: Make sure these HTTPError exception are coming from SyncClient.
    statsd_count(request, "syncclient.status_code.%s" %
                 context.response.status_code)

    if context.response.status_code in (400, 401, 403, 404):
        # For this code we also want to log the info about the error.
        logger.info(context, exc_info=True)

    # For this specific code we do not want to log the error.
    if context.response.status_code == 304:
        response = httpexceptions.HTTPNotModified()
    elif context.response.status_code == 400:
        response = http_error(httpexceptions.HTTPBadRequest(),
                              errno=ERRORS.INVALID_PARAMETERS,
                              message=message)
    elif context.response.status_code == 401:
        response = http_error(httpexceptions.HTTPUnauthorized(),
                              errno=ERRORS.INVALID_AUTH_TOKEN,
                              message=message)
        # Forget the current user credentials.
        response.headers.extend(forget(request))
    elif context.response.status_code == 403:
        response = http_error(httpexceptions.HTTPForbidden(),
                              errno=ERRORS.FORBIDDEN,
                              message=message)
    elif context.response.status_code == 404:
        response = http_error(httpexceptions.HTTPNotFound(),
                              errno=ERRORS.INVALID_RESOURCE_ID,
                              message=message)
    elif context.response.status_code == 412:
        message = 'Resource was modified meanwhile'
        response = http_error(httpexceptions.HTTPPreconditionFailed(),
                              errno=ERRORS.MODIFIED_MEANWHILE,
                              message=message)
    else:
        # For this code we also want to log the error.
        logger.error(context, exc_info=True)
        response = service_unavailable(
            httpexceptions.HTTPServiceUnavailable(),
            request)

    request.response = response
    export_headers(context.response, request)

    return reapply_cors(request, response)
Example #5
0
def record_get(request):
    collection_name = request.matchdict['collection_name']
    record_id = request.matchdict['record_id']

    sync_client = build_sync_client(request)
    headers = import_headers(request)
    record = sync_client.get_record(collection_name, record_id,
                                    headers=headers)

    record['last_modified'] = int(record.pop('modified') * 1000)

    # Configure headers
    export_headers(sync_client.raw_resp, request)

    statsd_count(request, "syncclient.status_code.200")

    return {'data': record}
Example #6
0
def record_delete(request):
    collection_name = request.matchdict['collection_name']

    assert_endpoint_enabled(request, collection_name)

    record_id = request.matchdict['record_id']
    sync_id = record_id

    headers = import_headers(request)
    sync_client = build_sync_client(request)
    sync_client.delete_record(collection_name, sync_id, headers=headers)

    statsd_count(request, "syncclient.status_code.204")

    request.response.status_code = 204
    del request.response.headers['Content-Type']
    return request.response
def record_delete(request):
    collection_name = request.matchdict['collection_name']

    assert_endpoint_enabled(request, collection_name)

    record_id = request.matchdict['record_id']
    sync_id = record_id

    headers = import_headers(request)
    sync_client = build_sync_client(request)
    sync_client.delete_record(collection_name, sync_id, headers=headers)

    statsd_count(request, "syncclient.status_code.204")

    request.response.status_code = 204
    del request.response.headers['Content-Type']
    return request.response
def record_get(request):
    collection_name = request.matchdict['collection_name']
    record_id = request.matchdict['record_id']

    sync_client = build_sync_client(request)
    headers = import_headers(request)
    record = sync_client.get_record(collection_name,
                                    record_id,
                                    headers=headers)

    record['last_modified'] = int(record.pop('modified') * 1000)

    # Configure headers
    export_headers(sync_client.raw_resp, request)

    statsd_count(request, "syncclient.status_code.200")

    return {'data': record}
Example #9
0
 def test_statsd_count_call_the_client_if_configured(self):
     request = mock.MagicMock()
     request.registry.statsd = self.mocked_client
     statsd.statsd_count(request, 'toto')
     self.mocked_client.count.assert_called_with('toto')
Example #10
0
 def test_statsd_count_handle_unconfigured_statsd_client(self):
     request = mock.MagicMock()
     request.registry.statsd = None
     statsd.statsd_count(request, 'toto')  # Doesn't raise
Example #11
0
 def test_statsd_count_call_the_client_if_configured(self):
     request = mock.MagicMock()
     request.registry.statsd = self.mocked_client
     statsd.statsd_count(request, 'toto')
     self.mocked_client.count.assert_called_with('toto')
Example #12
0
 def test_statsd_count_handle_unconfigured_statsd_client(self):
     request = mock.MagicMock()
     request.registry.statsd = None
     statsd.statsd_count(request, 'toto')  # Doesn't raise
Example #13
0
def collection_get(request):
    collection_name = request.matchdict['collection_name']
    sync_client = build_sync_client(request)

    headers = import_headers(request)

    params = {}
    if '_since' in request.GET:
        try:
            params['newer'] = '%.2f' % (int(request.GET['_since']) / 1000.0)
        except ValueError:
            error_msg = ("_since should be a number.")
            raise_invalid(request,
                          location="querystring",
                          name="_since",
                          description=error_msg)

    if '_limit' in request.GET:
        params['limit'] = request.GET['_limit']

    if '_token' in request.GET:
        params['offset'] = request.GET['_token']

    if '_sort' in request.GET:
        if request.GET['_sort'] in ('-last_modified', 'newest'):
            params['sort'] = 'newest'

        elif request.GET['_sort'] in ('-sortindex', 'index'):
            params['sort'] = 'index'

        elif request.GET['_sort'] in ('last_modified', 'oldest'):
            params['sort'] = 'oldest'

        else:
            error_msg = ("_sort should be one of ('-last_modified', 'newest', "
                         "'-sortindex', 'index', 'last_modified', 'oldest')")
            raise_invalid(request,
                          location="querystring",
                          name="_sort",
                          description=error_msg)

    if 'in_ids' in request.GET:
        params['ids'] = [
            record_id.strip() for record_id in request.GET['in_ids'].split(',')
            if record_id
        ]

    records = sync_client.get_records(collection_name,
                                      full=True,
                                      headers=headers,
                                      **params)

    statsd_count(request, "syncclient.status_code.200")

    for r in records:
        r['last_modified'] = int(r.pop('modified') * 1000)

    # Configure headers
    export_headers(sync_client.raw_resp, request)

    if '_limit' in request.GET and 'Total-Records' in request.response.headers:
        del request.response.headers['Total-Records']

    return {'data': records or []}