diff --git a/CHANGELOG.md b/CHANGELOG.md index b225472..f92e88e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 //record/`-endpoint and the + `POST //validate/record/`-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) ## Bugfixes diff --git a/dump_things_service/abstract_config.py b/dump_things_service/abstract_config.py index 9319b87..1852e46 100644 --- a/dump_things_service/abstract_config.py +++ b/dump_things_service/abstract_config.py @@ -344,7 +344,7 @@ def check_collection( if collection in g_recoverable_error: msg = ( 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) raise HTTPException( @@ -352,6 +352,7 @@ def check_collection( detail=msg, ) + def check_label( store_path: Path, abstract_config: Configuration, @@ -568,7 +569,7 @@ def get_conflicting_paths( abstract_config: Configuration, ) -> list[tuple[PurePosixPath, str, set[str], PurePosixPath, str, set[str]]]: """Check that the incoming and curated areas of different collections - are disjunct subtrees.""" + are disjunct subtrees.""" # Collect all paths. all_paths = set() @@ -577,8 +578,7 @@ def get_conflicting_paths( # If incoming and curated paths are not disjunct, the containing path # is added. containing_path, _ = _get_containing_path( - collection_config.incoming, - collection_config.curated + collection_config.incoming, collection_config.curated ) if containing_path: 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) if containing_path: 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: - 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 @@ -610,8 +628,8 @@ def _get_containing_path( """Return the containing path if one of the paths is a subtree of the other.""" for container, contained, position in ( - (path_0, path_1, 0), - (path_1, path_0, 1), + (path_0, path_1, 0), + (path_1, path_0, 1), ): try: contained.relative_to(container) diff --git a/dump_things_service/collection.py b/dump_things_service/collection.py index eff4f5a..4e2ea51 100644 --- a/dump_things_service/collection.py +++ b/dump_things_service/collection.py @@ -403,7 +403,7 @@ def refresh_collection_state( print('refresh_collection_state called with argument:', a) if a % 100 >= 10: return None - return (), dict(a=a+1) + return (), dict(a=a + 1) def check_recoverable_errors( @@ -420,7 +420,5 @@ def check_recoverable_errors( configuration=abstract_configuration, ) except Exception as e: - logger.info( - f'Error recovery failed: {e}' - ) + logger.info(f'Error recovery failed: {e}') return (abstract_configuration, instance_state), {} diff --git a/dump_things_service/endpoints/v0/base_endpoints.py b/dump_things_service/endpoints/v0/base_endpoints.py index f54262f..36d4131 100644 --- a/dump_things_service/endpoints/v0/base_endpoints.py +++ b/dump_things_service/endpoints/v0/base_endpoints.py @@ -21,6 +21,7 @@ from fastapi import ( APIRouter, Depends, HTTPException, + Request, Response, ) from fastapi_pagination import ( @@ -67,6 +68,7 @@ from dump_things_service.model import ( from dump_things_service.utils import ( authenticate_token, check_bounds, + check_content_type, combine_ttl, get_token_store, join_default_token_permissions, @@ -121,10 +123,9 @@ async def server() -> ServerResponse: ServerCollectionResponse( name=collection_name, schema=configuration.collections[collection_name].schema_location, - classes= - ( + classes=( instance_state.schema_info[ - configuration.collections[collection_name].schema_location + configuration.collections[collection_name].schema_location ].classes if collection_name not in g_recoverable_error else ['??? (recoverable error in schema location)'] @@ -237,22 +238,15 @@ async def store_record( body: dict | str, collection: str, class_name: str, + request: Request, api_key: str = Depends(api_key_header_scheme), add_submission_tag: bool = False, - format: Format = Format.json, + format: Format | None = None, ): + format_, body = check_content_type(request, format, body) + 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() check_collection(configuration, collection) @@ -290,7 +284,7 @@ async def store_record( detail=f"No class named '{class_name}' found in collection '{collection}'.", ) - if format == Format.ttl: + if format_ == Format.ttl: with wrap_http_exception( ValueError, status_code=HTTP_422_UNPROCESSABLE_CONTENT, @@ -318,7 +312,7 @@ async def store_record( submitter=user_id if add_submission_tag else None, ) - if format == Format.ttl: + if format_ == Format.ttl: format_converter = FormatConverter( configuration.collections[collection].schema_location, input_format=Format.json, diff --git a/dump_things_service/endpoints/v0/validate.py b/dump_things_service/endpoints/v0/validate.py index ba9a813..0740204 100644 --- a/dump_things_service/endpoints/v0/validate.py +++ b/dump_things_service/endpoints/v0/validate.py @@ -4,6 +4,7 @@ from fastapi import ( APIRouter, Depends, HTTPException, + Request, ) from pydantic import ( TypeAdapter, @@ -12,7 +13,6 @@ from pydantic import ( from starlette.responses import JSONResponse from dump_things_service import ( - HTTP_400_BAD_REQUEST, HTTP_403_FORBIDDEN, HTTP_422_UNPROCESSABLE_CONTENT, 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.model import get_model_for_schema from dump_things_service.utils import ( + check_content_type, dict_to_base_model, get_token_store, join_default_token_permissions, @@ -56,30 +57,15 @@ def validate_record( body: dict | str, collection: str, class_name: str, - format: Format = Format.json, + request: Request, + format: Format | None = None, api_key: str | None = Depends(api_key_header_scheme), ) -> JSONResponse: - logger.info( - 'validate_record(%s, %s, %s, %s, *)', - repr(body), - collection, - repr(class_name), - repr(format), - ) + format_, body = check_content_type(request, format, body) instance_state = get_instance_state() 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) token = ( @@ -105,7 +91,7 @@ def validate_record( detail=f"Not authorized to validate records for collection '{collection}'.", ) - if format == Format.ttl: + if format_ == Format.ttl: with wrap_http_exception( ValueError, status_code=HTTP_422_UNPROCESSABLE_CONTENT, diff --git a/dump_things_service/main.py b/dump_things_service/main.py index 84c1b0d..79ebc24 100644 --- a/dump_things_service/main.py +++ b/dump_things_service/main.py @@ -101,9 +101,9 @@ parser.add_argument( type=int, default=60, help='Set the retry interval for recoverable errors in seconds. After the ' - 'retry interval, the server will try to manifest collections ' - 'configurations that have recoverable errors, e.g., failing URLs. ' - 'The default is 60 seconds.', + 'retry interval, the server will try to manifest collections ' + 'configurations that have recoverable errors, e.g., failing URLs. ' + 'The default is 60 seconds.', ) parser.add_argument( 'store', @@ -178,20 +178,20 @@ disable_installed_extensions_check() # Define the tag-order openapi_tags = [ - {"name": 'default'}, - {"name": 'Read records'}, - {"name": 'Store records'}, - {"name": 'Validate records'}, - {"name": 'Delete records'}, - {"name": 'Curated area: read records'}, - {"name": 'Curated area: store records'}, - {"name": 'Curated area: delete records'}, - {"name": 'Incoming area: read records'}, - {"name": 'Incoming area: read labels'}, - {"name": 'Incoming area: store records'}, - {"name": 'Incoming area: delete records'}, - {"name": 'Server management'}, - {"name": 'Administration interface'}, + {'name': 'default'}, + {'name': 'Read records'}, + {'name': 'Store records'}, + {'name': 'Validate records'}, + {'name': 'Delete records'}, + {'name': 'Curated area: read records'}, + {'name': 'Curated area: store records'}, + {'name': 'Curated area: delete records'}, + {'name': 'Incoming area: read records'}, + {'name': 'Incoming area: read labels'}, + {'name': 'Incoming area: store records'}, + {'name': 'Incoming area: delete records'}, + {'name': 'Server management'}, + {'name': 'Administration interface'}, ] @@ -329,7 +329,7 @@ try: instance_state=g_instance_state, ) 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 diff --git a/dump_things_service/manifest.py b/dump_things_service/manifest.py index beafd43..169052a 100644 --- a/dump_things_service/manifest.py +++ b/dump_things_service/manifest.py @@ -3,7 +3,7 @@ from typing import cast from dump_things_service.abstract_config import ( Configuration, - TokenConfig, g_recoverable_error, + TokenConfig, ) from dump_things_service.collection import create_collection from dump_things_service.exceptions import ( @@ -103,7 +103,6 @@ def manifest_configuration( a collection. """ from dump_things_service.abstract_config import g_recoverable_error - global g_recoverable_error # Determine the changes in collections. existing_collections = set(instance_state.collections) @@ -176,14 +175,13 @@ def manifest_configuration( # indicate that the configuration is not fully valid. if faulty_collections: for collection in faulty_collections: - logger.info('removing fault-inducing configuration for collection "%s"', collection) - 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() + logger.info( + 'removing fault-inducing configuration for collection "%s"', collection ) + 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) diff --git a/dump_things_service/periodic.py b/dump_things_service/periodic.py index 2fbd795..b761e6c 100644 --- a/dump_things_service/periodic.py +++ b/dump_things_service/periodic.py @@ -24,10 +24,10 @@ async def periodic_worker(): def add_task_to_queue( - interval: int, - callable_: Callable, - *args, - **kwargs, + interval: int, + callable_: Callable, + *args, + **kwargs, ): g_task_list.append((interval, interval, callable_, args, kwargs)) g_task_list.sort(key=lambda x: x[0]) diff --git a/dump_things_service/tests/test_config.py b/dump_things_service/tests/test_config.py index 30a47cd..b1a43f0 100644 --- a/dump_things_service/tests/test_config.py +++ b/dump_things_service/tests/test_config.py @@ -7,8 +7,7 @@ from shutil import copyfile import pytest import yaml -from starlette.status import HTTP_400_BAD_REQUEST, \ - HTTP_422_UNPROCESSABLE_CONTENT +from starlette.status import HTTP_400_BAD_REQUEST, HTTP_422_UNPROCESSABLE_CONTENT from dump_things_service import ( HTTP_200_OK, @@ -26,12 +25,12 @@ from dump_things_service.abstract_config import ( get_conflicting_paths, 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.endpoints.v0.collection_endpoints import CollectionRequest from dump_things_service.endpoints.v0.token_endpoints import TokenRequest from dump_things_service.exceptions import ConfigError 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 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(): - setup_info = ( ('c0.0', 'curated/c1', 'incoming/c1'), ('c0.1', 'curated/c1/c2', 'incoming/c2'), @@ -364,7 +362,7 @@ def test_is_directory_configuration_valid(): 'default_token': '', } for collection_name, curated, incoming in setup_info - } + }, ) conflicts = get_conflicting_paths(abstract_config) assert len(conflicts) == 17 @@ -386,6 +384,6 @@ def test_is_directory_configuration_valid(): 'default_token': '', } for collection_name, curated, incoming in setup_info - } + }, ) assert not get_conflicting_paths(abstract_config) diff --git a/dump_things_service/tests/test_content_type.py b/dump_things_service/tests/test_content_type.py new file mode 100644 index 0000000..5efe134 --- /dev/null +++ b/dump_things_service/tests/test_content_type.py @@ -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: . +@prefix 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 diff --git a/dump_things_service/tests/test_token_endpoints.py b/dump_things_service/tests/test_token_endpoints.py index e731a73..f9113c8 100644 --- a/dump_things_service/tests/test_token_endpoints.py +++ b/dump_things_service/tests/test_token_endpoints.py @@ -1,4 +1,3 @@ - from dump_things_service import ( HTTP_201_CREATED, HTTP_404_NOT_FOUND, diff --git a/dump_things_service/utils.py b/dump_things_service/utils.py index 396126d..46e163e 100644 --- a/dump_things_service/utils.py +++ b/dump_things_service/utils.py @@ -9,6 +9,7 @@ To speed up processing, multiple indices could be introduced, e.g.: from __future__ import annotations +import json import logging import sys from contextlib import contextmanager @@ -20,20 +21,24 @@ from typing import ( import fsspec import yaml -from fastapi import HTTPException +from fastapi import ( + HTTPException, + Request, +) from pydantic import ( BaseModel, TypeAdapter, ValidationError, ) from rdflib import Graph -from starlette.status import HTTP_422_UNPROCESSABLE_CONTENT from dump_things_service import ( + Format, HTTP_400_BAD_REQUEST, HTTP_401_UNAUTHORIZED, HTTP_403_FORBIDDEN, HTTP_413_CONTENT_TOO_LARGE, + HTTP_422_UNPROCESSABLE_CONTENT, HTTP_503_SERVICE_UNAVAILABLE, ) from dump_things_service.abstract_config import ( @@ -664,3 +669,44 @@ def dict_to_base_model( header='Validation error', ): 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