interpret content-type header #296

Merged
cmo merged 4 commits from content-type into master 2026-11-10 10:21:09 +00:00
12 changed files with 217 additions and 88 deletions

View file

@ -1,3 +1,14 @@
# 6.X.X (2026-XX-XX)
## New features
- Use the content-type header to determine the format of the request body
in the `POST /<collection>/record/<class>`-endpoint and the
`POST /<collection>/validate/record/<class>`-endpoint. For backward
compatibility, the `format`-query parameter is still supported, it overrides
the type information specified in the content-type header.
# 6.7.1 (2026-11-05) # 6.7.1 (2026-11-05)
## Bugfixes ## Bugfixes

View file

@ -344,7 +344,7 @@ def check_collection(
if collection in g_recoverable_error: if collection in g_recoverable_error:
msg = ( msg = (
f"Collection '{collection}' has a recoverable configuration error. " f"Collection '{collection}' has a recoverable configuration error. "
"Please check the server logs for more information." 'Please check the server logs for more information.'
) )
logger.warning(msg) logger.warning(msg)
raise HTTPException( raise HTTPException(
@ -352,6 +352,7 @@ def check_collection(
detail=msg, detail=msg,
) )
def check_label( def check_label(
store_path: Path, store_path: Path,
abstract_config: Configuration, abstract_config: Configuration,
@ -568,7 +569,7 @@ def get_conflicting_paths(
abstract_config: Configuration, abstract_config: Configuration,
) -> list[tuple[PurePosixPath, str, set[str], PurePosixPath, str, set[str]]]: ) -> list[tuple[PurePosixPath, str, set[str], PurePosixPath, str, set[str]]]:
"""Check that the incoming and curated areas of different collections """Check that the incoming and curated areas of different collections
are disjunct subtrees.""" are disjunct subtrees."""
# Collect all paths. # Collect all paths.
all_paths = set() all_paths = set()
@ -577,8 +578,7 @@ def get_conflicting_paths(
# If incoming and curated paths are not disjunct, the containing path # If incoming and curated paths are not disjunct, the containing path
# is added. # is added.
containing_path, _ = _get_containing_path( containing_path, _ = _get_containing_path(
collection_config.incoming, collection_config.incoming, collection_config.curated
collection_config.curated
) )
if containing_path: if containing_path:
all_paths.add((containing_path, collection_name)) all_paths.add((containing_path, collection_name))
@ -597,9 +597,27 @@ def get_conflicting_paths(
containing_path, index = _get_containing_path(current_path, other_path) containing_path, index = _get_containing_path(current_path, other_path)
if containing_path: if containing_path:
if index == 0: if index == 0:
result.append((current_path, current_collection, usage_info[current_path], other_path, other_collection, usage_info[other_path])) result.append(
(
current_path,
current_collection,
usage_info[current_path],
other_path,
other_collection,
usage_info[other_path],
)
)
else: else:
result.append((other_path, other_collection, usage_info[other_path], current_path, current_collection, usage_info[current_path])) result.append(
(
other_path,
other_collection,
usage_info[other_path],
current_path,
current_collection,
usage_info[current_path],
)
)
return result return result
@ -610,8 +628,8 @@ def _get_containing_path(
"""Return the containing path if one of the paths is a subtree of the other.""" """Return the containing path if one of the paths is a subtree of the other."""
for container, contained, position in ( for container, contained, position in (
(path_0, path_1, 0), (path_0, path_1, 0),
(path_1, path_0, 1), (path_1, path_0, 1),
): ):
try: try:
contained.relative_to(container) contained.relative_to(container)

View file

@ -403,7 +403,7 @@ def refresh_collection_state(
print('refresh_collection_state called with argument:', a) print('refresh_collection_state called with argument:', a)
if a % 100 >= 10: if a % 100 >= 10:
return None return None
return (), dict(a=a+1) return (), dict(a=a + 1)
def check_recoverable_errors( def check_recoverable_errors(
@ -420,7 +420,5 @@ def check_recoverable_errors(
configuration=abstract_configuration, configuration=abstract_configuration,
) )
except Exception as e: except Exception as e:
logger.info( logger.info(f'Error recovery failed: {e}')
f'Error recovery failed: {e}'
)
return (abstract_configuration, instance_state), {} return (abstract_configuration, instance_state), {}

View file

@ -21,6 +21,7 @@ from fastapi import (
APIRouter, APIRouter,
Depends, Depends,
HTTPException, HTTPException,
Request,
Response, Response,
) )
from fastapi_pagination import ( from fastapi_pagination import (
@ -67,6 +68,7 @@ from dump_things_service.model import (
from dump_things_service.utils import ( from dump_things_service.utils import (
authenticate_token, authenticate_token,
check_bounds, check_bounds,
check_content_type,
combine_ttl, combine_ttl,
get_token_store, get_token_store,
join_default_token_permissions, join_default_token_permissions,
@ -121,10 +123,9 @@ async def server() -> ServerResponse:
ServerCollectionResponse( ServerCollectionResponse(
name=collection_name, name=collection_name,
schema=configuration.collections[collection_name].schema_location, schema=configuration.collections[collection_name].schema_location,
classes= classes=(
(
instance_state.schema_info[ instance_state.schema_info[
configuration.collections[collection_name].schema_location configuration.collections[collection_name].schema_location
].classes ].classes
if collection_name not in g_recoverable_error if collection_name not in g_recoverable_error
else ['??? (recoverable error in schema location)'] else ['??? (recoverable error in schema location)']
@ -237,22 +238,15 @@ async def store_record(
body: dict | str, body: dict | str,
collection: str, collection: str,
class_name: str, class_name: str,
request: Request,
api_key: str = Depends(api_key_header_scheme), api_key: str = Depends(api_key_header_scheme),
add_submission_tag: bool = False, add_submission_tag: bool = False,
format: Format = Format.json, format: Format | None = None,
): ):
format_, body = check_content_type(request, format, body)
configuration = get_config() configuration = get_config()
if format == Format.json and isinstance(body, str):
raise HTTPException(
status_code=HTTP_400_BAD_REQUEST, detail='Invalid JSON data provided.'
)
if format == Format.ttl and not isinstance(body, str):
raise HTTPException(
status_code=HTTP_400_BAD_REQUEST, detail='Invalid ttl data provided.'
)
instance_state = get_instance_state() instance_state = get_instance_state()
check_collection(configuration, collection) check_collection(configuration, collection)
@ -290,7 +284,7 @@ async def store_record(
detail=f"No class named '{class_name}' found in collection '{collection}'.", detail=f"No class named '{class_name}' found in collection '{collection}'.",
) )
if format == Format.ttl: if format_ == Format.ttl:
with wrap_http_exception( with wrap_http_exception(
ValueError, ValueError,
status_code=HTTP_422_UNPROCESSABLE_CONTENT, status_code=HTTP_422_UNPROCESSABLE_CONTENT,
@ -318,7 +312,7 @@ async def store_record(
submitter=user_id if add_submission_tag else None, submitter=user_id if add_submission_tag else None,
) )
if format == Format.ttl: if format_ == Format.ttl:
format_converter = FormatConverter( format_converter = FormatConverter(
configuration.collections[collection].schema_location, configuration.collections[collection].schema_location,
input_format=Format.json, input_format=Format.json,

View file

@ -4,6 +4,7 @@ from fastapi import (
APIRouter, APIRouter,
Depends, Depends,
HTTPException, HTTPException,
Request,
) )
from pydantic import ( from pydantic import (
TypeAdapter, TypeAdapter,
@ -12,7 +13,6 @@ from pydantic import (
from starlette.responses import JSONResponse from starlette.responses import JSONResponse
from dump_things_service import ( from dump_things_service import (
HTTP_400_BAD_REQUEST,
HTTP_403_FORBIDDEN, HTTP_403_FORBIDDEN,
HTTP_422_UNPROCESSABLE_CONTENT, HTTP_422_UNPROCESSABLE_CONTENT,
Format, Format,
@ -27,6 +27,7 @@ from dump_things_service.converter import FormatConverter
from dump_things_service.instance_state import get_instance_state from dump_things_service.instance_state import get_instance_state
from dump_things_service.model import get_model_for_schema from dump_things_service.model import get_model_for_schema
from dump_things_service.utils import ( from dump_things_service.utils import (
check_content_type,
dict_to_base_model, dict_to_base_model,
get_token_store, get_token_store,
join_default_token_permissions, join_default_token_permissions,
@ -56,30 +57,15 @@ def validate_record(
body: dict | str, body: dict | str,
collection: str, collection: str,
class_name: str, class_name: str,
format: Format = Format.json, request: Request,
format: Format | None = None,
api_key: str | None = Depends(api_key_header_scheme), api_key: str | None = Depends(api_key_header_scheme),
) -> JSONResponse: ) -> JSONResponse:
logger.info( format_, body = check_content_type(request, format, body)
'validate_record(%s, %s, %s, %s, *)',
repr(body),
collection,
repr(class_name),
repr(format),
)
instance_state = get_instance_state() instance_state = get_instance_state()
abstract_config = get_config() abstract_config = get_config()
if format == Format.json and isinstance(body, str):
raise HTTPException(
status_code=HTTP_400_BAD_REQUEST, detail='Invalid JSON data provided.'
)
if format == Format.ttl and not isinstance(body, str):
raise HTTPException(
status_code=HTTP_400_BAD_REQUEST, detail='Invalid ttl data provided.'
)
check_collection(abstract_config, collection) check_collection(abstract_config, collection)
token = ( token = (
@ -105,7 +91,7 @@ def validate_record(
detail=f"Not authorized to validate records for collection '{collection}'.", detail=f"Not authorized to validate records for collection '{collection}'.",
) )
if format == Format.ttl: if format_ == Format.ttl:
with wrap_http_exception( with wrap_http_exception(
ValueError, ValueError,
status_code=HTTP_422_UNPROCESSABLE_CONTENT, status_code=HTTP_422_UNPROCESSABLE_CONTENT,

View file

@ -101,9 +101,9 @@ parser.add_argument(
type=int, type=int,
default=60, default=60,
help='Set the retry interval for recoverable errors in seconds. After the ' help='Set the retry interval for recoverable errors in seconds. After the '
'retry interval, the server will try to manifest collections ' 'retry interval, the server will try to manifest collections '
'configurations that have recoverable errors, e.g., failing URLs. ' 'configurations that have recoverable errors, e.g., failing URLs. '
'The default is 60 seconds.', 'The default is 60 seconds.',
) )
parser.add_argument( parser.add_argument(
'store', 'store',
@ -178,20 +178,20 @@ disable_installed_extensions_check()
# Define the tag-order # Define the tag-order
openapi_tags = [ openapi_tags = [
{"name": 'default'}, {'name': 'default'},
{"name": 'Read records'}, {'name': 'Read records'},
{"name": 'Store records'}, {'name': 'Store records'},
{"name": 'Validate records'}, {'name': 'Validate records'},
{"name": 'Delete records'}, {'name': 'Delete records'},
{"name": 'Curated area: read records'}, {'name': 'Curated area: read records'},
{"name": 'Curated area: store records'}, {'name': 'Curated area: store records'},
{"name": 'Curated area: delete records'}, {'name': 'Curated area: delete records'},
{"name": 'Incoming area: read records'}, {'name': 'Incoming area: read records'},
{"name": 'Incoming area: read labels'}, {'name': 'Incoming area: read labels'},
{"name": 'Incoming area: store records'}, {'name': 'Incoming area: store records'},
{"name": 'Incoming area: delete records'}, {'name': 'Incoming area: delete records'},
{"name": 'Server management'}, {'name': 'Server management'},
{"name": 'Administration interface'}, {'name': 'Administration interface'},
] ]
@ -329,7 +329,7 @@ try:
instance_state=g_instance_state, instance_state=g_instance_state,
) )
except ConfigError as e: except ConfigError as e:
logger.error("There were errors manifesting configuration: %s", e) logger.error('There were errors manifesting configuration: %s', e)
# Add a periodic task that tries to recover from recoverable errors in the # Add a periodic task that tries to recover from recoverable errors in the

View file

@ -3,7 +3,7 @@ from typing import cast
from dump_things_service.abstract_config import ( from dump_things_service.abstract_config import (
Configuration, Configuration,
TokenConfig, g_recoverable_error, TokenConfig,
) )
from dump_things_service.collection import create_collection from dump_things_service.collection import create_collection
from dump_things_service.exceptions import ( from dump_things_service.exceptions import (
@ -103,7 +103,6 @@ def manifest_configuration(
a collection. a collection.
""" """
from dump_things_service.abstract_config import g_recoverable_error from dump_things_service.abstract_config import g_recoverable_error
global g_recoverable_error
# Determine the changes in collections. # Determine the changes in collections.
existing_collections = set(instance_state.collections) existing_collections = set(instance_state.collections)
@ -176,14 +175,13 @@ def manifest_configuration(
# indicate that the configuration is not fully valid. # indicate that the configuration is not fully valid.
if faulty_collections: if faulty_collections:
for collection in faulty_collections: for collection in faulty_collections:
logger.info('removing fault-inducing configuration for collection "%s"', collection) logger.info(
configuration.collections.pop(collection, None) 'removing fault-inducing configuration for collection "%s"', collection
msg = (
'Collection creation errors occurred:\n'
+ '\n'.join(
f'creating collection "{collection_name}" failed due to: {error}'
for collection_name, error in collection_errors.items()
) )
configuration.collections.pop(collection, None)
msg = 'Collection creation errors occurred:\n' + '\n'.join(
f'creating collection "{collection_name}" failed due to: {error}'
for collection_name, error in collection_errors.items()
) )
raise ConfigError(msg) raise ConfigError(msg)

View file

@ -24,10 +24,10 @@ async def periodic_worker():
def add_task_to_queue( def add_task_to_queue(
interval: int, interval: int,
callable_: Callable, callable_: Callable,
*args, *args,
**kwargs, **kwargs,
): ):
g_task_list.append((interval, interval, callable_, args, kwargs)) g_task_list.append((interval, interval, callable_, args, kwargs))
g_task_list.sort(key=lambda x: x[0]) g_task_list.sort(key=lambda x: x[0])

View file

@ -7,8 +7,7 @@ from shutil import copyfile
import pytest import pytest
import yaml import yaml
from starlette.status import HTTP_400_BAD_REQUEST, \ from starlette.status import HTTP_400_BAD_REQUEST, HTTP_422_UNPROCESSABLE_CONTENT
HTTP_422_UNPROCESSABLE_CONTENT
from dump_things_service import ( from dump_things_service import (
HTTP_200_OK, HTTP_200_OK,
@ -26,12 +25,12 @@ from dump_things_service.abstract_config import (
get_conflicting_paths, get_conflicting_paths,
read_config, read_config,
) )
from dump_things_service.abstract_config import g_recoverable_error
from dump_things_service.collection import check_recoverable_errors from dump_things_service.collection import check_recoverable_errors
from dump_things_service.endpoints.v0.collection_endpoints import CollectionRequest from dump_things_service.endpoints.v0.collection_endpoints import CollectionRequest
from dump_things_service.endpoints.v0.token_endpoints import TokenRequest from dump_things_service.endpoints.v0.token_endpoints import TokenRequest
from dump_things_service.exceptions import ConfigError from dump_things_service.exceptions import ConfigError
from dump_things_service.instance_state import get_instance_state from dump_things_service.instance_state import get_instance_state
from dump_things_service.manifest import g_recoverable_error
from dump_things_service.tests import schema_file from dump_things_service.tests import schema_file
reference_config_file = Path(__file__).parent / 'assets' / 'reference_config.yaml' reference_config_file = Path(__file__).parent / 'assets' / 'reference_config.yaml'
@ -340,7 +339,6 @@ def test_config_structure_error_detection(fastapi_client_simple):
def test_is_directory_configuration_valid(): def test_is_directory_configuration_valid():
setup_info = ( setup_info = (
('c0.0', 'curated/c1', 'incoming/c1'), ('c0.0', 'curated/c1', 'incoming/c1'),
('c0.1', 'curated/c1/c2', 'incoming/c2'), ('c0.1', 'curated/c1/c2', 'incoming/c2'),
@ -364,7 +362,7 @@ def test_is_directory_configuration_valid():
'default_token': '', 'default_token': '',
} }
for collection_name, curated, incoming in setup_info for collection_name, curated, incoming in setup_info
} },
) )
conflicts = get_conflicting_paths(abstract_config) conflicts = get_conflicting_paths(abstract_config)
assert len(conflicts) == 17 assert len(conflicts) == 17
@ -386,6 +384,6 @@ def test_is_directory_configuration_valid():
'default_token': '', 'default_token': '',
} }
for collection_name, curated, incoming in setup_info for collection_name, curated, incoming in setup_info
} },
) )
assert not get_conflicting_paths(abstract_config) assert not get_conflicting_paths(abstract_config)

View file

@ -0,0 +1,81 @@
import json
import pytest
from dump_things_service import (
HTTP_200_OK,
HTTP_400_BAD_REQUEST,
HTTP_422_UNPROCESSABLE_CONTENT,
)
json_record = {'given_name': 'Henry', 'pid': 'xyz:henry'}
ttl_record = """
@prefix abc: <http://example.org/person-schema/abc/> .
@prefix xyz: <https://www.example.com/xyz/> .
xyz:henry a abc:Person ;
abc:given_name "Henry" .
"""
@pytest.mark.parametrize('path_part', ['record', 'validate/record'])
def test_content_type_handling(fastapi_client_simple, path_part):
test_client, _, _ = fastapi_client_simple
# Check that format-parameter overrides content-type-header
response = test_client.post(
f'/collection_1/{path_part}/Person?format=ttl',
headers={
'x-dumpthings-token': 'token-1',
},
json=json_record,
)
# Returns bad request because a JSON body is provided while the
# format query-parameter specifies TTL
assert response.status_code == HTTP_400_BAD_REQUEST
# Check that content-type is used when format-parameter is not provided
response = test_client.post(
f'/collection_1/{path_part}/Person',
headers={
'x-dumpthings-token': 'token-1',
'content-type': 'text/turtle',
},
data=ttl_record,
)
assert response.status_code == HTTP_200_OK
# Check that content-type is used when format-parameter is not provided
response = test_client.post(
f'/collection_1/{path_part}/Person',
headers={
'x-dumpthings-token': 'token-1',
'content-type': 'application/json',
},
data=json.dumps(json_record),
)
assert response.status_code == HTTP_200_OK
# Check that faulty content is detected (JSON string provided while
# content-type is text/turtle)
response = test_client.post(
f'/collection_1/{path_part}/Person',
headers={
'x-dumpthings-token': 'token-1',
'content-type': 'text/turtle',
},
data=json.dumps(json_record),
)
assert response.status_code == HTTP_422_UNPROCESSABLE_CONTENT
# Check that format override works (format=json, which overrides
# content-type is text/turtle)
response = test_client.post(
f'/collection_1/{path_part}/Person?format=json',
headers={
'x-dumpthings-token': 'token-1',
'content-type': 'text/turtle',
},
data=json.dumps(json_record),
)
assert response.status_code == HTTP_200_OK

View file

@ -1,4 +1,3 @@
from dump_things_service import ( from dump_things_service import (
HTTP_201_CREATED, HTTP_201_CREATED,
HTTP_404_NOT_FOUND, HTTP_404_NOT_FOUND,

View file

@ -9,6 +9,7 @@ To speed up processing, multiple indices could be introduced, e.g.:
from __future__ import annotations from __future__ import annotations
import json
import logging import logging
import sys import sys
from contextlib import contextmanager from contextlib import contextmanager
@ -20,20 +21,24 @@ from typing import (
import fsspec import fsspec
import yaml import yaml
from fastapi import HTTPException from fastapi import (
HTTPException,
Request,
)
from pydantic import ( from pydantic import (
BaseModel, BaseModel,
TypeAdapter, TypeAdapter,
ValidationError, ValidationError,
) )
from rdflib import Graph from rdflib import Graph
from starlette.status import HTTP_422_UNPROCESSABLE_CONTENT
from dump_things_service import ( from dump_things_service import (
Format,
HTTP_400_BAD_REQUEST, HTTP_400_BAD_REQUEST,
HTTP_401_UNAUTHORIZED, HTTP_401_UNAUTHORIZED,
HTTP_403_FORBIDDEN, HTTP_403_FORBIDDEN,
HTTP_413_CONTENT_TOO_LARGE, HTTP_413_CONTENT_TOO_LARGE,
HTTP_422_UNPROCESSABLE_CONTENT,
HTTP_503_SERVICE_UNAVAILABLE, HTTP_503_SERVICE_UNAVAILABLE,
) )
from dump_things_service.abstract_config import ( from dump_things_service.abstract_config import (
@ -664,3 +669,44 @@ def dict_to_base_model(
header='Validation error', header='Validation error',
): ):
return TypeAdapter(getattr(model, class_name)).validate_python(data) return TypeAdapter(getattr(model, class_name)).validate_python(data)
def check_content_type(
request: Request,
format_override: Format | None,
body: str | dict,
) -> tuple[Format, str | dict]:
"""Check that the content type is JSON or TTL
Content-type is determined by the content-type header of the request, unless
the format_ parameter is provided. In that case the format_ parameter
determines the format.
"""
if not format_override:
content_type = request.headers.get('content-type', '').strip()
if content_type not in ('application/json', 'text/turtle'):
raise HTTPException(
status_code=HTTP_400_BAD_REQUEST,
detail='Invalid content type provided.',
)
specified_format = (
Format.json if content_type == 'application/json' else Format.ttl
)
else:
specified_format = format_override
if specified_format == Format.json:
if isinstance(body, str):
if format_override:
# We don't care about the content-type and try to convert the
# body into a JSON object.
with wrap_http_exception(Exception):
return Format.json, json.loads(body)
raise HTTPException(
status_code=HTTP_400_BAD_REQUEST, detail='Invalid JSON data provided.'
)
elif not isinstance(body, str):
raise HTTPException(
status_code=HTTP_400_BAD_REQUEST, detail='Invalid ttl data provided.'
)
return specified_format, body