From df83cf8d9a9904ecd89ad3fc4ad373dda01008f0 Mon Sep 17 00:00:00 2001 From: Christian Monch Date: Mon, 5 Oct 2026 14:32:48 +0200 Subject: [PATCH 01/20] fix: ensure backward compatible policy declarations This commit reintroduces the policy configuration keys to the collection configuration record. This ensures that existing 6.5 configurations can be read. If an external policy configuration source is defined for a collection (via `policy_info_location`), it will be used. In this case, if the configuration defines a policy inline (via `policy_annotation_tag`, `default_policy`, and `policy_mapping`), the latter will be ignored and a warning will be issued. If the configuration does not define an external policy source, but defines a policy inline (via `policy_annotation_tag`, `default_policy`, and `policy_mapping`), the inlined policy definition will be used. --- CHANGELOG.md | 10 +++++++ dump_things_service/__init__.py | 3 +- dump_things_service/abstract_config.py | 6 ++++ dump_things_service/collection.py | 39 +++++++++++++++++++++++--- dump_things_service/tests/fixtures.py | 13 +++++++++ 5 files changed, 65 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5280657..20f6246 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,13 @@ +# 6.6.1 (2026-10-05) + +## Changes + +- Configuration is now backward compatible with configuration from version 6.5, + i.e., the configuration properties `default_policy`, `policy_annotation_tag`, + and `policy_mapping` can be used in version 6.6.1 . They will be ignored and + a warning will be logged. + + # 6.6.0 (2026-10-01) ## New features diff --git a/dump_things_service/__init__.py b/dump_things_service/__init__.py index 1ca2721..6a3b028 100644 --- a/dump_things_service/__init__.py +++ b/dump_things_service/__init__.py @@ -60,7 +60,6 @@ reserved_collection_names = ( 'tokens', 'admin_tokens', 'api', + 'v1', dump_things_private_collection_name, ) - -policy_annotation = 'https://example.org/dumpthings/policy_set' diff --git a/dump_things_service/abstract_config.py b/dump_things_service/abstract_config.py index 7c45038..762cb88 100644 --- a/dump_things_service/abstract_config.py +++ b/dump_things_service/abstract_config.py @@ -128,6 +128,11 @@ class CollectionConfig(BaseModel): ignore_classes: list[str] = [] policy_info_location: str | None = None + # The following keys are ignored + default_policy: str | None = None + policy_mapping: list[PolicyMapping] = [] + policy_annotation_tag: str | None = None + class RecordDirConfigFileContent(BaseModel): model_config = ConfigDict(extra='forbid') @@ -267,6 +272,7 @@ def read_config( except ValidationError as ve: msg = f'Faulty configuration at {config_backend.root}: {ve}' raise ConfigError(msg) from ve + return g_abstract_configuration diff --git a/dump_things_service/collection.py b/dump_things_service/collection.py index e4b9104..74c626e 100644 --- a/dump_things_service/collection.py +++ b/dump_things_service/collection.py @@ -245,10 +245,41 @@ def create_collection( if collection_configuration.ignore_classes: active_classes -= set(collection_configuration.ignore_classes) - default_policy, policy_mapping, policy_annotation_tag = load_policy_info( - configuration, - collection_name, - ) + # If external policy information is specified, load it, otherwise use + # the policy information from the collection configuration. + if collection_configuration.policy_info_location: + default_policy, policy_mapping, policy_annotation_tag = load_policy_info( + configuration, + collection_name, + ) + # If there is a local configuration, issue a warning + if (collection_configuration.default_policy + or collection_configuration.policy_mapping + or collection_configuration.policy_annotation_tag + ): + logger.warning( + "Collection '%s' specifies policy information in its " + "configuration (via `policy_annotation_tag`, `default_policy`, " + "and `policy_mapping`) as well as in an external source (via " + "`policy_info_location`). The policy information specified in " + "the configuration will be ignored and the externally sourced " + "policy information will be used.", + collection_name, + ) + else: + default_policy = collection_configuration.default_policy + policy_mapping = collection_configuration.policy_mapping + policy_annotation_tag = collection_configuration.policy_annotation_tag + + if not policy_annotation_tag and (default_policy or policy_mapping): + logger.warning( + "Collection '%s' specifies policy information in its configuration " + "(via `default_policy` and/or `policy_mapping`) but does not specify " + "a `policy_annotation_tag`. The policy information will be ignored " + "and no policy enforcement will be performed.", + collection_name, + ) + instance_state.collections[collection_name] = InstanceStateCollectionInfo( active_classes=active_classes, tag_info={}, diff --git a/dump_things_service/tests/fixtures.py b/dump_things_service/tests/fixtures.py index b49b9c7..0f1ce9e 100644 --- a/dump_things_service/tests/fixtures.py +++ b/dump_things_service/tests/fixtures.py @@ -11,6 +11,7 @@ from fastapi.testclient import TestClient from dump_things_service.abstract_config import ( GitAuditBackendConfig, + PolicyMapping, SQLiteBackendConfig, TagSpec, TokenCollectionConfig, @@ -87,6 +88,18 @@ g_default_collections.append( submission_time_tag='no_default_time_tag', ), policy_info_location=policy_info_file_location, + policy_annotation_tag='abc:policy_set', + default_policy='policy_1', + policy_mapping=[ + PolicyMapping( + auth_source='config', + user_id='abc', + authorized_by=[ + 'test_user_8_policy_1', + 'test_user_8_default_policy', + ], + ), + ] ) ) -- 2.54.1 From 5aa9d91d82310f0e87e2c42bdda1c3694487222d Mon Sep 17 00:00:00 2001 From: Christian Monch Date: Tue, 6 Oct 2026 12:01:38 +0200 Subject: [PATCH 02/20] tests: add backward compatibility test for configurations --- .../tests/test_backward_compatibility.py | 172 ++++++++++++++++++ 1 file changed, 172 insertions(+) create mode 100644 dump_things_service/tests/test_backward_compatibility.py diff --git a/dump_things_service/tests/test_backward_compatibility.py b/dump_things_service/tests/test_backward_compatibility.py new file mode 100644 index 0000000..54571e3 --- /dev/null +++ b/dump_things_service/tests/test_backward_compatibility.py @@ -0,0 +1,172 @@ +import yaml + +config_version_1 = """ +type: collections +version: 1 + +collections: + penguins: + default_token: no_access + curated: penguins/curated + incoming: penguins/incoming-v1 + backend: + type: sqlite + schema: https://concepts.datalad.org/s/flat-study/unreleased.yaml + +tokens: + no_access: + user_id: nobody + collections: + penguins: + mode: NOTHING + incoming_label: '' + + token_1: + user_id: cristian + # The collections for which the token holds rights are defined in "collections" + collections: + penguins: + mode: WRITE_COLLECTION + incoming_label: 'cristian' + + token_c: + user_id: curator + # The collections for which the token holds rights are defined in "collections" + collections: + penguins: + mode: CURATOR + incoming_label: 'curator' +""" + +config_version_2_inlined_only_policy = """ +pid: dump_things:config +version: 2 +type: collections +collections: + dfg-survey-2026-main: + curated: dfg-survey/2026/main/curated + default_policy: policy_1 + default_token: noaccess + incoming: dfg-survey/2026/main/inboxes + policy_annotation_tag: abc + policy_mapping: + - auth_source: config + authorized_by: + - policy_1 + - policy_2 + - policy_3 + user_id: cmo + - auth_source: trr379hub + authorized_by: + - policy_3 + - policy_4 + - policy_5 + user_id: mih + schema: https://concepts.datalad.org/s/things/v2.yaml +tokens: + no_access: + user_id: nobody + collections: + dfg-survey-2026-main: + mode: NOTHING + incoming_label: '' +admin_tokens: {} +""" + +config_version_2_external_only_policy = """ +pid: dump_things:config +version: 2 +type: collections +collections: + dfg-survey-2026-main: + audit_backends: [] + auth_sources: + - instance_id: trr379hub + label_type: user + organization: dfg-survey + team: 2026-participants + type: forgejo + url: https://hub.trr379.de/api/v1 + backend: + type: sqlite + curated: dfg-survey/2026/main/curated + policy_info_location: https://concepts.datalad.org/s/things/v2-policies.yaml + default_token: noaccess + ignore_classes: [] + incoming: dfg-survey/2026/main/inboxes + schema: https://concepts.datalad.org/s/things/v2.yaml + submission_tags: + submission_time_tag: http://semanticscience.org/resource/SIO_001083 + submitter_id_tag: http://purl.obolibrary.org/obo/NCIT_C54269 +tokens: + no_access: + user_id: nobody + collections: + dfg-survey-2026-main: + mode: NOTHING + incoming_label: '' +admin_tokens: {} +""" + +config_version_2_inlined_and_external_policy = """ +pid: dump_things:config +version: 2 +type: collections +collections: + dfg-survey-2026-main: + curated: dfg-survey/2026/main/curated + default_policy: policy_1 + default_token: noaccess + ignore_classes: [] + incoming: dfg-survey/2026/main/inboxes + policy_annotation_tag: abc + policy_mapping: + - auth_source: config + authorized_by: + - policy_1 + - policy_2 + - policy_3 + user_id: cmo + - auth_source: trr379hub + authorized_by: + - policy_3 + - policy_4 + - policy_5 + user_id: mih + policy_info_location: https://concepts.datalad.org/s/things/v2-policies.yaml + schema: https://concepts.datalad.org/s/things/v2.yaml + submission_tags: + submission_time_tag: http://semanticscience.org/resource/SIO_001083 + submitter_id_tag: http://purl.obolibrary.org/obo/NCIT_C54269 +tokens: +tokens: + no_access: + user_id: nobody + collections: + dfg-survey-2026-main: + mode: NOTHING + incoming_label: '' +admin_tokens: {} +""" + +all_configurations = [ + config_version_1, + config_version_2_inlined_only_policy, + config_version_2_external_only_policy, + config_version_2_inlined_and_external_policy, +] + + +# Check that old configurations can be read by the current Configuration class +def test_config_backward_compatiblity(): + from dump_things_service.abstract_config import Configuration + from dump_things_service.commands.upload_config import convert_config_1_to_config_2 + + for config_yaml in all_configurations: + config_dict = yaml.safe_load(config_yaml) + if config_dict['version'] == 1: + config_dict = convert_config_1_to_config_2( + config_dict, + None, + ) + _ = Configuration(**config_dict) -- 2.54.1 From ce707669bb1bb8a97501bc6bf3dbb492c1b4c6cb Mon Sep 17 00:00:00 2001 From: Christian Monch Date: Tue, 6 Oct 2026 12:18:03 +0200 Subject: [PATCH 03/20] chore: update changelog --- CHANGELOG.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 20f6246..caf4903 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,11 +1,13 @@ -# 6.6.1 (2026-10-05) +# 6.6.1 (2026-10-06) ## Changes - Configuration is now backward compatible with configuration from version 6.5, i.e., the configuration properties `default_policy`, `policy_annotation_tag`, - and `policy_mapping` can be used in version 6.6.1 . They will be ignored and - a warning will be logged. + and `policy_mapping` can be used in version 6.6.1 . If the property + `policy_info_location` is set, this will be used to configure policy handling. + In this case the properties `default_policy`, `policy_annotation_tag`, + and `policy_mapping` will be ignored and a warning will be issued. # 6.6.0 (2026-10-01) -- 2.54.1 From 4ed49289a5511aea0a18e1a36a251509b660486c Mon Sep 17 00:00:00 2001 From: Christian Monch Date: Thu, 1 Oct 2026 09:32:25 +0200 Subject: [PATCH 04/20] [temp] start non-generated code --- dump_things_service/collection.py | 16 +-- dump_things_service/main.py | 167 +++++++++++++++++++++++++++++- dump_things_service/manifest.py | 3 +- 3 files changed, 173 insertions(+), 13 deletions(-) diff --git a/dump_things_service/collection.py b/dump_things_service/collection.py index 74c626e..59c1b0f 100644 --- a/dump_things_service/collection.py +++ b/dump_things_service/collection.py @@ -540,14 +540,14 @@ def create_endpoints_for_collection( tag_group, tag_name, ) in ( - ( - 'store', - 'record', - _endpoint_template, - 'store_record', - 'write', - f'Write records to collection "{collection_name}"', - ), + #( + # 'store', + # 'record', + # _endpoint_template, + # 'store_record', + # 'write', + # f'Write records to collection "{collection_name}"', + #), ( 'validate', 'validate/record', diff --git a/dump_things_service/main.py b/dump_things_service/main.py index 4b3c6d3..67f89fc 100644 --- a/dump_things_service/main.py +++ b/dump_things_service/main.py @@ -7,11 +7,14 @@ import sys from pathlib import Path from typing import TYPE_CHECKING, Annotated -from starlette.status import HTTP_200_OK - +from dump_things_service import ( + HTTP_200_OK, + HTTP_422_UNPROCESSABLE_CONTENT, +) from dump_things_service.abstract_config import store_config from dump_things_service.collection import reload_policy from dump_things_service.commands.upload_config import convert_config_1_to_config_2 +from dump_things_service.instance_state import get_instance_state from dump_things_service.manifest import manifest_configuration # Perform the patching before importing any third-party libraries @@ -20,6 +23,7 @@ from dump_things_service.patches import enabled # noqa: F401 -- used by generat import yaml import uvicorn from fastapi import ( + Body, Depends, FastAPI, HTTPException, @@ -35,8 +39,11 @@ from fastapi_pagination.utils import disable_installed_extensions_check from pydantic import ( BaseModel, Field, + TypeAdapter, + ValidationError, ) from starlette.responses import ( + JSONResponse, PlainTextResponse, RedirectResponse, ) @@ -62,14 +69,20 @@ from dump_things_service.converter import ( ConvertingList, ) from dump_things_service.curated import router as curated_router -from dump_things_service.exceptions import CurieResolutionError, ConfigError +from dump_things_service.exceptions import ( + CurieResolutionError, + ConfigError, +) from dump_things_service.incoming import router as incoming_router from dump_things_service.instance_state import create_instance_state, InstanceState from dump_things_service.lazy_list import ( PriorityList, ModifierList, ) -from dump_things_service.model import get_subclasses +from dump_things_service.model import ( + get_model_for_schema, + get_subclasses, +) from dump_things_service.collection_endpoints import router as collection_router from dump_things_service.token_endpoints import ( hash_matcher, @@ -78,6 +91,10 @@ from dump_things_service.token_endpoints import ( from dump_things_service.utils import ( authenticate_token, check_bounds, + combine_ttl, + get_token_store, + join_default_token_permissions, + order_dict, process_token, simple_process_token, wrap_http_exception, @@ -443,6 +460,148 @@ async def maintenance( g_instance_state.maintenance_mode.remove(collection) +@app.post( + '/{collection}/record/{class_name}', + tags=['Store records'], + name='Write record of class {class_name} to collection {collection}', + openapi_extra={ + "requestBody": { + "required": True, + "content": { + "application/json": { + "schema": { + "type": "object" + } + }, + "text/turtle": { + "schema": { + "type": "string" + } + }, + }, + } + }, +) +async def store_record( + body: dict | str, + collection: str, + class_name: str, + api_key: str = Depends(api_key_header_scheme), + add_submission_tag: bool = False, + format: Format = Format.json, +): + logger.warning('store_record(%s, %s, %s, %s, %s, %s)', type(body), repr(body), repr(collection), repr(class_name), repr(add_submission_tag), repr(format)) + + if format == Format.json: + if 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(g_configuration, collection) + + # Get the token permissions and extend them by the default permissions. + # This call will also convert plaintext tokens into the hashed version of + # the token, if the token is hashed. This is necessary because we do not + # store the plaintext token, so all token-information is associated with + # the hashed representation of the token. + token_representation = ( + g_configuration.collections[collection].default_token + if api_key is None + else api_key + ) + store, token_permissions, user_id = get_token_store( + g_configuration, + instance_state, + collection, + token_representation, + is_token_name=api_key is None, + ) + final_permissions = join_default_token_permissions( + g_configuration, + token_permissions, + collection, + ) + if not final_permissions.incoming_write: + raise HTTPException( + status_code=HTTP_403_FORBIDDEN, + detail=f"Not authorized to submit to collection '{collection}'.", + ) + + model, classes, model_var_name = get_model_for_schema( + g_configuration.collections[collection].schema_location + ) + if class_name not in g_instance_state.collections[collection].active_classes: + raise HTTPException( + status_code=HTTP_404_NOT_FOUND, + detail=f"No class named '{class_name}' found in collection '{collection}'.", + ) + + if format == Format.ttl: + with wrap_http_exception( + ValueError, + status_code=HTTP_422_UNPROCESSABLE_CONTENT, + header='Conversion error', + ): + json_object = FormatConverter( + g_configuration.collections[collection].schema_location, + input_format=Format.ttl, + output_format=Format.json, + ).convert(body, class_name) + else: + json_object = body + + with wrap_http_exception( + ValidationError, + status_code=HTTP_422_UNPROCESSABLE_CONTENT, + header='Validation error', + ): + record = TypeAdapter(getattr(model, class_name)).validate_python( + json_object + ) + + with wrap_http_exception( + ValueError, + status_code=HTTP_422_UNPROCESSABLE_CONTENT, + header='Validation error', + ): + instance_state.validators[collection].validate(record) + + sorted_record = order_dict(record) + with wrap_http_exception(CurieResolutionError): + stored_records = store.store_object( + obj=sorted_record, + submitter=user_id if add_submission_tag else None, + ) + + if format == Format.ttl: + format_converter = FormatConverter( + g_configuration.collections[collection].schema_location, + input_format=Format.json, + output_format=Format.ttl, + ) + with wrap_http_exception(ValueError, header='Conversion error'): + return PlainTextResponse( + combine_ttl( + [ + format_converter.convert( + record, + class_name, + ) + for class_name, record in stored_records + ] + ), + media_type='text/turtle', + ) + return JSONResponse([order_dict(record) for _, record in stored_records]) + + @app.get( '/{collection}/record', tags=['Read records'], diff --git a/dump_things_service/manifest.py b/dump_things_service/manifest.py index 5bad5b5..528f0fb 100644 --- a/dump_things_service/manifest.py +++ b/dump_things_service/manifest.py @@ -31,7 +31,7 @@ openapi_tags_template: list[dict | str] = [ 'name': 'Read records', 'description': 'Read records from the given collection', }, - 'write', + #'write', 'validate', { 'name': 'Delete records', @@ -197,6 +197,7 @@ def create_openapi_tags( instance_state: InstanceState, openapi_tags_template_: list[dict | str], ) -> list[dict]: + return [] # Collect tag name lists for all tag groups that we have defined. tag_group_info = { tag_group: sorted( -- 2.54.1 From e38d7cc8a2d66639c417d26957ef1ada8b18e8e1 Mon Sep 17 00:00:00 2001 From: Christian Monch Date: Sun, 4 Oct 2026 06:46:01 +0200 Subject: [PATCH 05/20] refactor: move enpoint out of `main.py` The implementation of the "base"-user endpoints, i.e., all enpoints that were implemented in `main.py` are moved to `base_endpoint.py`. --- dump_things_service/base_endpoints.py | 733 ++++++++++++++++++++++++++ dump_things_service/main.py | 689 +----------------------- 2 files changed, 737 insertions(+), 685 deletions(-) create mode 100644 dump_things_service/base_endpoints.py diff --git a/dump_things_service/base_endpoints.py b/dump_things_service/base_endpoints.py new file mode 100644 index 0000000..d7c5d51 --- /dev/null +++ b/dump_things_service/base_endpoints.py @@ -0,0 +1,733 @@ +from __future__ import annotations # noqa: I001 -- the patches have to be imported early + +import logging +from typing import TYPE_CHECKING, Annotated + +from dump_things_service import ( + HTTP_200_OK, + HTTP_422_UNPROCESSABLE_CONTENT, +) +from dump_things_service.abstract_config import get_config +from dump_things_service.collection import reload_policy +from dump_things_service.instance_state import get_instance_state + +# Perform the patching before importing any third-party libraries +from dump_things_service.patches import enabled # noqa: F401 -- used by generated code + +from fastapi import ( + APIRouter, + Depends, + HTTPException, + Response, +) +from fastapi_pagination import ( + Page, + paginate, +) +from pydantic import ( + BaseModel, + Field, + TypeAdapter, + ValidationError, +) +from starlette.responses import ( + JSONResponse, + PlainTextResponse, + RedirectResponse, +) + +from dump_things_service import ( + HTTP_400_BAD_REQUEST, + HTTP_403_FORBIDDEN, + HTTP_404_NOT_FOUND, + Format, +) +from dump_things_service import __version__ +from dump_things_service.abstract_config import ( + check_collection, +) +from dump_things_service.api_key import api_key_header_scheme +from dump_things_service.converter import ( + FormatConverter, + ConvertingList, +) +from dump_things_service.exceptions import ( + CurieResolutionError, + ConfigError, +) +from dump_things_service.instance_state import InstanceState +from dump_things_service.lazy_list import ( + PriorityList, + ModifierList, +) +from dump_things_service.model import ( + get_model_for_schema, + get_subclasses, +) +from dump_things_service.utils import ( + authenticate_token, + check_bounds, + combine_ttl, + get_token_store, + join_default_token_permissions, + order_dict, + process_token, + simple_process_token, + wrap_http_exception, +) + +if TYPE_CHECKING: + from dump_things_service.lazy_list import LazyList + + +class MaintenanceRequest(BaseModel): + collection: str + active: bool + + +class ServerCollectionResponse(BaseModel): + name: str + schema_location: str = Field(alias='schema') + classes: list[str] + + +class ServerCollectionCountedResponse(ServerCollectionResponse): + records: int + + +class ServerResponse(BaseModel): + version: str + collections: list[ServerCollectionResponse | ServerCollectionCountedResponse] + + +router = APIRouter() + +logger = logging.getLogger('dump_things_service') + + +@router.get('/', response_class=RedirectResponse) +async def root() -> RedirectResponse: + return RedirectResponse('/docs') + + +@router.get('/server', tags=['Server management'], name='get server information') +async def server() -> ServerResponse: + configuration = get_config() + instance_state = get_instance_state() + return ServerResponse( + version=__version__, + collections=[ + ServerCollectionResponse( + name=collection_name, + schema=configuration.collections[collection_name].schema_location, + classes=instance_state.schema_info[ + configuration.collections[collection_name].schema_location + ].classes, + ) + for collection_name in configuration.collections + ], + ) + + +@router.get( + '/management/reload/policy_info/{collection}', + tags=['Server management'], + name='reload policy information from configured location ', +) +async def reload_configured_policy( + collection: str, + api_key: Annotated[str | None, Depends(api_key_header_scheme)], + url: str | None = None, +): + configuration = get_config() + instance_state = get_instance_state() + + check_collection(configuration, collection) + + final_permissions = await simple_process_token( + configuration, instance_state, api_key, collection + ) + + if not final_permissions.curated_write: + raise HTTPException( + status_code=HTTP_403_FORBIDDEN, + detail=f'CURATOR token is required to reload policy information in collection {collection}.', + ) + + if not url: + url = configuration.collections[collection].policy_info_location + + if not url: + raise HTTPException( + status_code=HTTP_400_BAD_REQUEST, + detail=f"No policy_info_location configured for collection '{collection}' and no URL provided.", + ) + + with wrap_http_exception(ConfigError): + reload_policy( + abstract_configuration=configuration, + instance_state=instance_state, + collection_name=collection, + override_policy_info_location=url, + ) + return Response(status_code=HTTP_200_OK) + + +@router.post( + '/maintenance', + tags=['Server management'], + name='put a collection in maintenance mode', +) +async def maintenance( + body: MaintenanceRequest, + api_key: Annotated[str | None, Depends(api_key_header_scheme)], +): + if api_key is None: + raise HTTPException( + status_code=HTTP_400_BAD_REQUEST, + detail='Token required for this operation', + ) + + collection = body.collection + active = body.active + + configuration = get_config() + instance_state = get_instance_state() + + # Try to authenticate the token with the authentication providers that + # are associated with the collection. + check_collection(configuration, collection) + auth_info = authenticate_token(instance_state, collection, api_key) + permissions = auth_info.token_permission + + if not ( + permissions.curated_write + and permissions.curated_read + and permissions.zones_access + ): + raise HTTPException( + status_code=HTTP_400_BAD_REQUEST, + detail='Curator permissions required for this operation', + ) + + if active: + instance_state.maintenance_mode.add(collection) + else: + instance_state.maintenance_mode.remove(collection) + + +@router.post( + '/{collection}/record/{class_name}', + tags=['Store records'], + name='Write record of class {class_name} to collection {collection}', + openapi_extra={ + "requestBody": { + "required": True, + "content": { + "application/json": { + "schema": { + "type": "object" + } + }, + "text/turtle": { + "schema": { + "type": "string" + } + }, + }, + } + }, +) +async def store_record( + body: dict | str, + collection: str, + class_name: str, + api_key: str = Depends(api_key_header_scheme), + add_submission_tag: bool = False, + format: Format = Format.json, +): + logger.warning('store_record(%s, %s, %s, %s, %s, %s)', type(body), repr(body), repr(collection), repr(class_name), repr(add_submission_tag), repr(format)) + + configuration = get_config() + + if format == Format.json: + if 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) + + # Get the token permissions and extend them by the default permissions. + # This call will also convert plaintext tokens into the hashed version of + # the token, if the token is hashed. This is necessary because we do not + # store the plaintext token, so all token-information is associated with + # the hashed representation of the token. + token_representation = ( + configuration.collections[collection].default_token + if api_key is None + else api_key + ) + store, token_permissions, user_id = get_token_store( + configuration, + instance_state, + collection, + token_representation, + is_token_name=api_key is None, + ) + final_permissions = join_default_token_permissions( + configuration, + token_permissions, + collection, + ) + if not final_permissions.incoming_write: + raise HTTPException( + status_code=HTTP_403_FORBIDDEN, + detail=f"Not authorized to submit to collection '{collection}'.", + ) + + model, classes, model_var_name = get_model_for_schema( + configuration.collections[collection].schema_location + ) + if class_name not in instance_state.collections[collection].active_classes: + raise HTTPException( + status_code=HTTP_404_NOT_FOUND, + detail=f"No class named '{class_name}' found in collection '{collection}'.", + ) + + if format == Format.ttl: + with wrap_http_exception( + ValueError, + status_code=HTTP_422_UNPROCESSABLE_CONTENT, + header='Conversion error', + ): + json_object = FormatConverter( + configuration.collections[collection].schema_location, + input_format=Format.ttl, + output_format=Format.json, + ).convert(body, class_name) + else: + json_object = body + + with wrap_http_exception( + ValidationError, + status_code=HTTP_422_UNPROCESSABLE_CONTENT, + header='Validation error', + ): + record = TypeAdapter(getattr(model, class_name)).validate_python( + json_object + ) + + with wrap_http_exception( + ValueError, + status_code=HTTP_422_UNPROCESSABLE_CONTENT, + header='Validation error', + ): + instance_state.validators[collection].validate(record) + + sorted_record = order_dict(record) + with wrap_http_exception(CurieResolutionError): + stored_records = store.store_object( + obj=sorted_record, + submitter=user_id if add_submission_tag else None, + ) + + if format == Format.ttl: + format_converter = FormatConverter( + configuration.collections[collection].schema_location, + input_format=Format.json, + output_format=Format.ttl, + ) + with wrap_http_exception(ValueError, header='Conversion error'): + return PlainTextResponse( + combine_ttl( + [ + format_converter.convert( + record, + class_name, + ) + for class_name, record in stored_records + ] + ), + media_type='text/turtle', + ) + return JSONResponse([order_dict(record) for _, record in stored_records]) + + +@router.get( + '/{collection}/record', + tags=['Read records'], + name='Read the record with the given PID from the given collection', +) +async def read_record_with_pid( + collection: str, + pid: str, + api_key: Annotated[str, Depends(api_key_header_scheme)], + format: Format = Format.json, # noqa: A002 +): + configuration = get_config() + instance_state = get_instance_state() + + check_collection(configuration, collection) + + final_permissions, token_store, user_info = await process_token( + configuration, instance_state, api_key, collection + ) + + policy_annotation_tag, default_policy, policies = _get_policy_information( + instance_state, collection, user_info + ) + + class_name, json_object = None, None + if final_permissions.incoming_read: + with wrap_http_exception(CurieResolutionError, header='CURIE error:'): + class_name, json_object = token_store.get_object_by_pid( + pid, + policy_annotation_tag=policy_annotation_tag, + default_policy=default_policy, + active_policies=policies, + ) + + if not json_object and final_permissions.curated_read: + with wrap_http_exception(CurieResolutionError, header='CURIE error:'): + class_name, json_object = instance_state.curated_stores[ + collection + ].get_object_by_pid( + pid, + policy_annotation_tag=policy_annotation_tag, + default_policy=default_policy, + active_policies=policies, + ) + + if not json_object: + return None + + if format == Format.ttl: + converter = FormatConverter( + schema=configuration.collections[collection].schema_location, + input_format=Format.json, + output_format=format, + ) + with wrap_http_exception(ValueError, header='Conversion error'): + ttl_record = converter.convert(json_object, class_name) + return PlainTextResponse(ttl_record, media_type='text/turtle') + return json_object + + +def _get_policy_information( + instance_state: InstanceState, + collection_name: str, + user_info: tuple[str, str], +) -> tuple[str | None, str | None, set[str] | None]: + from itertools import chain + + collection_state = instance_state.collections[collection_name] + policy_mapping = collection_state.policy_mapping + if not policy_mapping: + return None, None, None + + policies = set( + chain( + *[ + policy_mapping.authorized_by + for policy_mapping in policy_mapping + if (policy_mapping.auth_source, policy_mapping.user_id) == user_info + ] + ) + ) + return ( + collection_state.policy_annotation_tag, + collection_state.default_policy, + policies, + ) + + +@router.get( + '/{collection}/records/', + tags=['Read records'], + name='Read all records from the given collection', +) +async def read_all_records( + collection: str, + api_key: Annotated[str, Depends(api_key_header_scheme)], + matching: str | None = None, + format: Format = Format.json, # noqa: A002 +): + return await _read_all_records( + collection=collection, + matching=matching, + format=format, + api_key=api_key, + # Set an upper limit for the number of non-paginated result records to + # keep processing time for individual requests short and avoid + # overloading the server. + bound=1000, + ) + + +@router.get( + '/{collection}/records/p/', + tags=['Read records'], + name='Read all records from the given collection with pagination', +) +async def read_all_records_paginated( + collection: str, + api_key: Annotated[str, Depends(api_key_header_scheme)], + matching: str | None = None, + format: Format = Format.json, # noqa: A002 +) -> Page[dict | str]: + result_list = await _read_all_records( + collection=collection, + matching=matching, + format=format, + api_key=api_key, + bound=None, + ) + return paginate(result_list) + + +@router.get( + '/{collection}/records/{class_name}', + tags=['Read records'], + name='Read records of the given class (or subclass) from the given collection', +) +async def read_records_of_type( + collection: str, + class_name: str, + api_key: Annotated[str, Depends(api_key_header_scheme)], + matching: str | None = None, + format: Format = Format.json, # noqa: A002 +): + return await _read_records_of_type( + collection=collection, + class_name=class_name, + matching=matching, + format=format, + api_key=api_key, + # Set an upper limit for the number of non-paginated result records to + # keep processing time for individual requests short and avoid + # overloading the server. + bound=1000, + ) + + +@router.get( + '/{collection}/records/p/{class_name}', + tags=['Read records'], + name='Read records of the given class (or subclass) from the given collection with pagination', +) +async def read_records_of_type_paginated( + collection: str, + class_name: str, + api_key: Annotated[str, Depends(api_key_header_scheme)], + matching: str | None = None, + format: Format = Format.json, # noqa: A002 +) -> Page[dict | str]: + result_list = await _read_records_of_type( + collection=collection, + class_name=class_name, + matching=matching, + format=format, + api_key=api_key, + bound=None, + ) + return paginate(result_list) + + +async def _read_all_records( + collection: str, + matching: str | None = None, + format: Format = Format.json, # noqa: A002 + api_key: str = Depends(api_key_header_scheme), + bound: int | None = None, +) -> LazyList: + def convert_to_http_exception(e: BaseException): + raise HTTPException( + status_code=HTTP_400_BAD_REQUEST, + detail=f'Conversion error: {e}', + ) from e + + configuration = get_config() + instance_state = get_instance_state() + + check_collection(configuration, collection) + final_permissions, token_store, user_info = await process_token( + configuration, instance_state, api_key, collection + ) + + policy_annotation_tag, default_policy, policies = _get_policy_information( + instance_state, collection, user_info + ) + + result_list = PriorityList() + if final_permissions.incoming_read: + token_store_list = token_store.get_all_objects( + matching=matching, + policy_annotation_tag=policy_annotation_tag, + default_policy=default_policy, + active_policies=policies, + ) + if bound: + check_bounds(len(token_store_list), bound, collection, 'records/p/') + result_list.add_list(token_store_list) + + if final_permissions.curated_read: + curated_store_list = instance_state.curated_stores[ + collection + ].get_all_objects( + matching=matching, + policy_annotation_tag=policy_annotation_tag, + default_policy=default_policy, + active_policies=policies, + ) + if bound: + check_bounds(len(curated_store_list), bound, collection, 'records/p/') + result_list.add_list(curated_store_list) + + # Sort the result list. + result_list.sort(key=result_list.sort_key) + + if format == Format.ttl: + result_list = ConvertingList( + result_list, + configuration.collections[collection].schema_location, + input_format=Format.json, + output_format=format, + exception_handler=convert_to_http_exception, + ) + else: + result_list = ModifierList( + result_list, + lambda record_info: record_info.json_object, + ) + return result_list + + +async def _read_records_of_type( + collection: str, + class_name: str, + matching: str | None = None, + format: Format = Format.json, # noqa: A002 + api_key: str = Depends(api_key_header_scheme), + bound: int | None = None, +) -> LazyList: + def convert_to_http_exception(e: BaseException): + raise HTTPException( + status_code=HTTP_400_BAD_REQUEST, + detail=f'Conversion error: {e}', + ) from e + + configuration = get_config() + instance_state = get_instance_state() + + check_collection(configuration, collection) + schema_location = configuration.collections[collection].schema_location + model = instance_state.schema_info[schema_location].pydantic_module_info.module + if class_name not in instance_state.collections[collection].active_classes: + raise HTTPException( + status_code=HTTP_404_NOT_FOUND, + detail=f"No '{class_name}'-class in collection '{collection}'.", + ) + + final_permissions, token_store, user_info = await process_token( + configuration, instance_state, api_key, collection + ) + + policy_annotation_tag, default_policy, policies = _get_policy_information( + instance_state, collection, user_info + ) + + result_list = PriorityList() + if final_permissions.incoming_read: + for search_class_name in get_subclasses(model, class_name): + token_store_list = token_store.get_objects_of_class( + class_name=search_class_name, + matching=matching, + policy_annotation_tag=policy_annotation_tag, + default_policy=default_policy, + active_policies=policies, + ) + if bound: + check_bounds( + len(token_store_list), bound, collection, f'/records/p/{class_name}' + ) + result_list.add_list(token_store_list) + + if final_permissions.curated_read: + for search_class_name in get_subclasses(model, class_name): + curated_store_list = instance_state.curated_stores[ + collection + ].get_objects_of_class( + class_name=search_class_name, + matching=matching, + policy_annotation_tag=policy_annotation_tag, + default_policy=default_policy, + active_policies=policies, + ) + if bound: + check_bounds( + len(curated_store_list), + bound, + collection, + f'/records/p/{class_name}', + ) + result_list.add_list(curated_store_list) + + # Sort the result list. + result_list.sort(key=result_list.sort_key) + + if format == Format.ttl: + result_list = ConvertingList( + result_list, + schema_location, + input_format=Format.json, + output_format=format, + exception_handler=convert_to_http_exception, + ) + else: + result_list = ModifierList( + result_list, + lambda record_info: record_info.json_object, + ) + return result_list + + +@router.delete( + '/{collection}/record', + tags=['Delete records'], + name='Delete record with the given pid from the given collection', +) +async def delete_record( + collection: str, + pid: str, + api_key: Annotated[str, Depends(api_key_header_scheme)], +): + configuration = get_config() + instance_state = get_instance_state() + + check_collection(configuration, collection) + final_permissions, token_store, user_info = await process_token( + configuration, instance_state, api_key, collection + ) + + if not final_permissions.incoming_write: + raise HTTPException( + status_code=HTTP_403_FORBIDDEN, + detail=f"No write access to incoming data in collection '{collection}'.", + ) + with wrap_http_exception(Exception): + result = token_store.delete_object(pid) + if not result: + raise HTTPException( + status_code=HTTP_404_NOT_FOUND, + detail=f"Could not remove record with PID '{pid}' from the " + 'token associated incoming area of collection ' + f"'{collection}'.", + ) + return True diff --git a/dump_things_service/main.py b/dump_things_service/main.py index 67f89fc..571010b 100644 --- a/dump_things_service/main.py +++ b/dump_things_service/main.py @@ -5,16 +5,9 @@ import logging import os import sys from pathlib import Path -from typing import TYPE_CHECKING, Annotated -from dump_things_service import ( - HTTP_200_OK, - HTTP_422_UNPROCESSABLE_CONTENT, -) from dump_things_service.abstract_config import store_config -from dump_things_service.collection import reload_policy from dump_things_service.commands.upload_config import convert_config_1_to_config_2 -from dump_things_service.instance_state import get_instance_state from dump_things_service.manifest import manifest_configuration # Perform the patching before importing any third-party libraries @@ -22,86 +15,31 @@ from dump_things_service.patches import enabled # noqa: F401 -- used by generat import yaml import uvicorn -from fastapi import ( - Body, - Depends, - FastAPI, - HTTPException, - Response, -) +from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware -from fastapi_pagination import ( - Page, - add_pagination, - paginate, -) +from fastapi_pagination import add_pagination from fastapi_pagination.utils import disable_installed_extensions_check from pydantic import ( BaseModel, Field, - TypeAdapter, - ValidationError, -) -from starlette.responses import ( - JSONResponse, - PlainTextResponse, - RedirectResponse, -) - -from dump_things_service import ( - HTTP_400_BAD_REQUEST, - HTTP_403_FORBIDDEN, - HTTP_404_NOT_FOUND, - Format, ) from dump_things_service import __version__ from dump_things_service.abstract_config import ( Configuration, - check_collection, hash_token_representation, read_config, CONFIG_VERSION_1_ID, CONFIG_VERSION_2_ID, ) -from dump_things_service.api_key import api_key_header_scheme -from dump_things_service.converter import ( - FormatConverter, - ConvertingList, -) +from dump_things_service.base_endpoints import router as base_router from dump_things_service.curated import router as curated_router -from dump_things_service.exceptions import ( - CurieResolutionError, - ConfigError, -) from dump_things_service.incoming import router as incoming_router from dump_things_service.instance_state import create_instance_state, InstanceState -from dump_things_service.lazy_list import ( - PriorityList, - ModifierList, -) -from dump_things_service.model import ( - get_model_for_schema, - get_subclasses, -) from dump_things_service.collection_endpoints import router as collection_router from dump_things_service.token_endpoints import ( hash_matcher, router as token_router, ) -from dump_things_service.utils import ( - authenticate_token, - check_bounds, - combine_ttl, - get_token_store, - join_default_token_permissions, - order_dict, - process_token, - simple_process_token, - wrap_http_exception, -) - -if TYPE_CHECKING: - from dump_things_service.lazy_list import LazyList class MaintenanceRequest(BaseModel): @@ -245,6 +183,7 @@ app.include_router(curated_router) app.include_router(incoming_router) app.include_router(token_router) app.include_router(collection_router) +app.include_router(base_router) # Add CORS origins app.add_middleware( @@ -357,626 +296,6 @@ g_instance_state.fastapi_app.setup() add_pagination(g_instance_state.fastapi_app) -@app.get('/', response_class=RedirectResponse) -async def root() -> RedirectResponse: - return RedirectResponse('/docs') - - -@app.get('/server', tags=['Server management'], name='get server information') -async def server() -> ServerResponse: - return ServerResponse( - version=__version__, - collections=[ - ServerCollectionResponse( - name=collection_name, - schema=g_configuration.collections[collection_name].schema_location, - classes=g_instance_state.schema_info[ - g_configuration.collections[collection_name].schema_location - ].classes, - ) - for collection_name in g_configuration.collections - ], - ) - - -@app.get( - '/management/reload/policy_info/{collection}', - tags=['Server management'], - name='reload policy information from configured location ', -) -async def reload_configured_policy( - collection: str, - api_key: Annotated[str | None, Depends(api_key_header_scheme)], - url: str | None = None, -): - check_collection(g_configuration, collection) - - final_permissions = await simple_process_token( - g_configuration, g_instance_state, api_key, collection - ) - - if not final_permissions.curated_write: - raise HTTPException( - status_code=HTTP_403_FORBIDDEN, - detail=f'CURATOR token is required to reload policy information in collection {collection}.', - ) - - if not url: - url = g_configuration.collections[collection].policy_info_location - - if not url: - raise HTTPException( - status_code=HTTP_400_BAD_REQUEST, - detail=f"No policy_info_location configured for collection '{collection}' and no URL provided.", - ) - - with wrap_http_exception(ConfigError): - reload_policy( - abstract_configuration=g_configuration, - instance_state=g_instance_state, - collection_name=collection, - override_policy_info_location=url, - ) - return Response(status_code=HTTP_200_OK) - - -@app.post( - '/maintenance', - tags=['Server management'], - name='put a collection in maintenance mode', -) -async def maintenance( - body: MaintenanceRequest, - api_key: Annotated[str | None, Depends(api_key_header_scheme)], -): - if api_key is None: - raise HTTPException( - status_code=HTTP_400_BAD_REQUEST, - detail='Token required for this operation', - ) - - collection = body.collection - active = body.active - - # Try to authenticate the token with the authentication providers that - # are associated with the collection. - check_collection(g_configuration, collection) - auth_info = authenticate_token(g_instance_state, collection, api_key) - permissions = auth_info.token_permission - - if not ( - permissions.curated_write - and permissions.curated_read - and permissions.zones_access - ): - raise HTTPException( - status_code=HTTP_400_BAD_REQUEST, - detail='Curator permissions required for this operation', - ) - - if active: - g_instance_state.maintenance_mode.add(collection) - else: - g_instance_state.maintenance_mode.remove(collection) - - -@app.post( - '/{collection}/record/{class_name}', - tags=['Store records'], - name='Write record of class {class_name} to collection {collection}', - openapi_extra={ - "requestBody": { - "required": True, - "content": { - "application/json": { - "schema": { - "type": "object" - } - }, - "text/turtle": { - "schema": { - "type": "string" - } - }, - }, - } - }, -) -async def store_record( - body: dict | str, - collection: str, - class_name: str, - api_key: str = Depends(api_key_header_scheme), - add_submission_tag: bool = False, - format: Format = Format.json, -): - logger.warning('store_record(%s, %s, %s, %s, %s, %s)', type(body), repr(body), repr(collection), repr(class_name), repr(add_submission_tag), repr(format)) - - if format == Format.json: - if 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(g_configuration, collection) - - # Get the token permissions and extend them by the default permissions. - # This call will also convert plaintext tokens into the hashed version of - # the token, if the token is hashed. This is necessary because we do not - # store the plaintext token, so all token-information is associated with - # the hashed representation of the token. - token_representation = ( - g_configuration.collections[collection].default_token - if api_key is None - else api_key - ) - store, token_permissions, user_id = get_token_store( - g_configuration, - instance_state, - collection, - token_representation, - is_token_name=api_key is None, - ) - final_permissions = join_default_token_permissions( - g_configuration, - token_permissions, - collection, - ) - if not final_permissions.incoming_write: - raise HTTPException( - status_code=HTTP_403_FORBIDDEN, - detail=f"Not authorized to submit to collection '{collection}'.", - ) - - model, classes, model_var_name = get_model_for_schema( - g_configuration.collections[collection].schema_location - ) - if class_name not in g_instance_state.collections[collection].active_classes: - raise HTTPException( - status_code=HTTP_404_NOT_FOUND, - detail=f"No class named '{class_name}' found in collection '{collection}'.", - ) - - if format == Format.ttl: - with wrap_http_exception( - ValueError, - status_code=HTTP_422_UNPROCESSABLE_CONTENT, - header='Conversion error', - ): - json_object = FormatConverter( - g_configuration.collections[collection].schema_location, - input_format=Format.ttl, - output_format=Format.json, - ).convert(body, class_name) - else: - json_object = body - - with wrap_http_exception( - ValidationError, - status_code=HTTP_422_UNPROCESSABLE_CONTENT, - header='Validation error', - ): - record = TypeAdapter(getattr(model, class_name)).validate_python( - json_object - ) - - with wrap_http_exception( - ValueError, - status_code=HTTP_422_UNPROCESSABLE_CONTENT, - header='Validation error', - ): - instance_state.validators[collection].validate(record) - - sorted_record = order_dict(record) - with wrap_http_exception(CurieResolutionError): - stored_records = store.store_object( - obj=sorted_record, - submitter=user_id if add_submission_tag else None, - ) - - if format == Format.ttl: - format_converter = FormatConverter( - g_configuration.collections[collection].schema_location, - input_format=Format.json, - output_format=Format.ttl, - ) - with wrap_http_exception(ValueError, header='Conversion error'): - return PlainTextResponse( - combine_ttl( - [ - format_converter.convert( - record, - class_name, - ) - for class_name, record in stored_records - ] - ), - media_type='text/turtle', - ) - return JSONResponse([order_dict(record) for _, record in stored_records]) - - -@app.get( - '/{collection}/record', - tags=['Read records'], - name='Read the record with the given PID from the given collection', -) -async def read_record_with_pid( - collection: str, - pid: str, - api_key: Annotated[str, Depends(api_key_header_scheme)], - format: Format = Format.json, # noqa: A002 -): - check_collection(g_configuration, collection) - - final_permissions, token_store, user_info = await process_token( - g_configuration, g_instance_state, api_key, collection - ) - - policy_annotation_tag, default_policy, policies = _get_policy_information( - g_instance_state, collection, user_info - ) - - class_name, json_object = None, None - if final_permissions.incoming_read: - with wrap_http_exception(CurieResolutionError, header='CURIE error:'): - class_name, json_object = token_store.get_object_by_pid( - pid, - policy_annotation_tag=policy_annotation_tag, - default_policy=default_policy, - active_policies=policies, - ) - - if not json_object and final_permissions.curated_read: - with wrap_http_exception(CurieResolutionError, header='CURIE error:'): - class_name, json_object = g_instance_state.curated_stores[ - collection - ].get_object_by_pid( - pid, - policy_annotation_tag=policy_annotation_tag, - default_policy=default_policy, - active_policies=policies, - ) - - if not json_object: - return None - - if format == Format.ttl: - converter = FormatConverter( - schema=g_configuration.collections[collection].schema_location, - input_format=Format.json, - output_format=format, - ) - with wrap_http_exception(ValueError, header='Conversion error'): - ttl_record = converter.convert(json_object, class_name) - return PlainTextResponse(ttl_record, media_type='text/turtle') - return json_object - - -def _get_policy_information( - instance_state: InstanceState, - collection_name: str, - user_info: tuple[str, str], -) -> tuple[str | None, str | None, set[str] | None]: - from itertools import chain - - collection_state = instance_state.collections[collection_name] - policy_mapping = collection_state.policy_mapping - if not policy_mapping: - return None, None, None - - policies = set( - chain( - *[ - policy_mapping.authorized_by - for policy_mapping in policy_mapping - if (policy_mapping.auth_source, policy_mapping.user_id) == user_info - ] - ) - ) - return ( - collection_state.policy_annotation_tag, - collection_state.default_policy, - policies, - ) - - -@app.get( - '/{collection}/records/', - tags=['Read records'], - name='Read all records from the given collection', -) -async def read_all_records( - collection: str, - api_key: Annotated[str, Depends(api_key_header_scheme)], - matching: str | None = None, - format: Format = Format.json, # noqa: A002 -): - return await _read_all_records( - collection=collection, - matching=matching, - format=format, - api_key=api_key, - # Set an upper limit for the number of non-paginated result records to - # keep processing time for individual requests short and avoid - # overloading the server. - bound=1000, - ) - - -@app.get( - '/{collection}/records/p/', - tags=['Read records'], - name='Read all records from the given collection with pagination', -) -async def read_all_records_paginated( - collection: str, - api_key: Annotated[str, Depends(api_key_header_scheme)], - matching: str | None = None, - format: Format = Format.json, # noqa: A002 -) -> Page[dict | str]: - result_list = await _read_all_records( - collection=collection, - matching=matching, - format=format, - api_key=api_key, - bound=None, - ) - return paginate(result_list) - - -@app.get( - '/{collection}/records/{class_name}', - tags=['Read records'], - name='Read records of the given class (or subclass) from the given collection', -) -async def read_records_of_type( - collection: str, - class_name: str, - api_key: Annotated[str, Depends(api_key_header_scheme)], - matching: str | None = None, - format: Format = Format.json, # noqa: A002 -): - return await _read_records_of_type( - collection=collection, - class_name=class_name, - matching=matching, - format=format, - api_key=api_key, - # Set an upper limit for the number of non-paginated result records to - # keep processing time for individual requests short and avoid - # overloading the server. - bound=1000, - ) - - -@app.get( - '/{collection}/records/p/{class_name}', - tags=['Read records'], - name='Read records of the given class (or subclass) from the given collection with pagination', -) -async def read_records_of_type_paginated( - collection: str, - class_name: str, - api_key: Annotated[str, Depends(api_key_header_scheme)], - matching: str | None = None, - format: Format = Format.json, # noqa: A002 -) -> Page[dict | str]: - result_list = await _read_records_of_type( - collection=collection, - class_name=class_name, - matching=matching, - format=format, - api_key=api_key, - bound=None, - ) - return paginate(result_list) - - -async def _read_all_records( - collection: str, - matching: str | None = None, - format: Format = Format.json, # noqa: A002 - api_key: str = Depends(api_key_header_scheme), - bound: int | None = None, -) -> LazyList: - def convert_to_http_exception(e: BaseException): - raise HTTPException( - status_code=HTTP_400_BAD_REQUEST, - detail=f'Conversion error: {e}', - ) from e - - check_collection(g_configuration, collection) - final_permissions, token_store, user_info = await process_token( - g_configuration, g_instance_state, api_key, collection - ) - - policy_annotation_tag, default_policy, policies = _get_policy_information( - g_instance_state, collection, user_info - ) - - result_list = PriorityList() - if final_permissions.incoming_read: - token_store_list = token_store.get_all_objects( - matching=matching, - policy_annotation_tag=policy_annotation_tag, - default_policy=default_policy, - active_policies=policies, - ) - if bound: - check_bounds(len(token_store_list), bound, collection, 'records/p/') - result_list.add_list(token_store_list) - - if final_permissions.curated_read: - curated_store_list = g_instance_state.curated_stores[ - collection - ].get_all_objects( - matching=matching, - policy_annotation_tag=policy_annotation_tag, - default_policy=default_policy, - active_policies=policies, - ) - if bound: - check_bounds(len(curated_store_list), bound, collection, 'records/p/') - result_list.add_list(curated_store_list) - - # Sort the result list. - result_list.sort(key=result_list.sort_key) - - if format == Format.ttl: - result_list = ConvertingList( - result_list, - g_configuration.collections[collection].schema_location, - input_format=Format.json, - output_format=format, - exception_handler=convert_to_http_exception, - ) - else: - result_list = ModifierList( - result_list, - lambda record_info: record_info.json_object, - ) - return result_list - - -async def _read_records_of_type( - collection: str, - class_name: str, - matching: str | None = None, - format: Format = Format.json, # noqa: A002 - api_key: str = Depends(api_key_header_scheme), - bound: int | None = None, -) -> LazyList: - def convert_to_http_exception(e: BaseException): - raise HTTPException( - status_code=HTTP_400_BAD_REQUEST, - detail=f'Conversion error: {e}', - ) from e - - check_collection(g_configuration, collection) - schema_location = g_configuration.collections[collection].schema_location - model = g_instance_state.schema_info[schema_location].pydantic_module_info.module - if class_name not in g_instance_state.collections[collection].active_classes: - raise HTTPException( - status_code=HTTP_404_NOT_FOUND, - detail=f"No '{class_name}'-class in collection '{collection}'.", - ) - - final_permissions, token_store, user_info = await process_token( - g_configuration, g_instance_state, api_key, collection - ) - - policy_annotation_tag, default_policy, policies = _get_policy_information( - g_instance_state, collection, user_info - ) - - result_list = PriorityList() - if final_permissions.incoming_read: - for search_class_name in get_subclasses(model, class_name): - token_store_list = token_store.get_objects_of_class( - class_name=search_class_name, - matching=matching, - policy_annotation_tag=policy_annotation_tag, - default_policy=default_policy, - active_policies=policies, - ) - if bound: - check_bounds( - len(token_store_list), bound, collection, f'/records/p/{class_name}' - ) - result_list.add_list(token_store_list) - - if final_permissions.curated_read: - for search_class_name in get_subclasses(model, class_name): - curated_store_list = g_instance_state.curated_stores[ - collection - ].get_objects_of_class( - class_name=search_class_name, - matching=matching, - policy_annotation_tag=policy_annotation_tag, - default_policy=default_policy, - active_policies=policies, - ) - if bound: - check_bounds( - len(curated_store_list), - bound, - collection, - f'/records/p/{class_name}', - ) - result_list.add_list(curated_store_list) - - # Sort the result list. - result_list.sort(key=result_list.sort_key) - - if format == Format.ttl: - result_list = ConvertingList( - result_list, - schema_location, - input_format=Format.json, - output_format=format, - exception_handler=convert_to_http_exception, - ) - else: - result_list = ModifierList( - result_list, - lambda record_info: record_info.json_object, - ) - return result_list - - -@app.delete( - '/{collection}/record', - tags=['Delete records'], - name='Delete record with the given pid from the given collection', -) -async def delete_record( - collection: str, - pid: str, - api_key: Annotated[str, Depends(api_key_header_scheme)], -): - check_collection(g_configuration, collection) - final_permissions, token_store, user_info = await process_token( - g_configuration, g_instance_state, api_key, collection - ) - - if not final_permissions.incoming_write: - raise HTTPException( - status_code=HTTP_403_FORBIDDEN, - detail=f"No write access to incoming data in collection '{collection}'.", - ) - with wrap_http_exception(Exception): - result = token_store.delete_object(pid) - if not result: - raise HTTPException( - status_code=HTTP_404_NOT_FOUND, - detail=f"Could not remove record with PID '{pid}' from the " - 'token associated incoming area of collection ' - f"'{collection}'.", - ) - return True - - -def _get_user_policies( - instance_state: InstanceState, - collection_name: str, - authenticator_id: str, - user_id: str, -) -> set[str]: - return set( - instance_state.policy_mappings[collection_name].get( - (authenticator_id, user_id), - set(), - ) - ) - - def main(): uvicorn.run( app, -- 2.54.1 From 59e67e74981d021b32ffa7ed934dd17ab00ea0d0 Mon Sep 17 00:00:00 2001 From: Christian Monch Date: Sun, 4 Oct 2026 22:14:02 +0200 Subject: [PATCH 06/20] fix: fix logger configuration This commit isolates the dump_things_service logger from the uvicorn-logger, by adding a private handler. This ensuring that the configured log-level for dump_things_service is actually active. --- dump_things_service/base_endpoints.py | 2 +- dump_things_service/main.py | 6 ++++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/dump_things_service/base_endpoints.py b/dump_things_service/base_endpoints.py index d7c5d51..3f69b1d 100644 --- a/dump_things_service/base_endpoints.py +++ b/dump_things_service/base_endpoints.py @@ -246,7 +246,7 @@ async def store_record( add_submission_tag: bool = False, format: Format = Format.json, ): - logger.warning('store_record(%s, %s, %s, %s, %s, %s)', type(body), repr(body), repr(collection), repr(class_name), repr(add_submission_tag), repr(format)) + logger.info('store_record(%s, %s, %s, %s, %s, %s)', type(body), repr(body), repr(collection), repr(class_name), repr(add_submission_tag), repr(format)) configuration = get_config() diff --git a/dump_things_service/main.py b/dump_things_service/main.py index 571010b..d77b719 100644 --- a/dump_things_service/main.py +++ b/dump_things_service/main.py @@ -163,6 +163,12 @@ if not isinstance(numeric_level, int): ) else: logger.setLevel(level=numeric_level) + logger.propagate = False + console_handler = logging.StreamHandler(sys.stdout) + console_handler.setLevel(numeric_level) + formatter = logging.Formatter('%(levelname)s:dump_things_service:%(message)s') + console_handler.setFormatter(formatter) + logger.addHandler(console_handler) store_path = Path(arguments.store).resolve() if not store_path.exists(): -- 2.54.1 From fa1d628176c936b752185d5061a52c744c07387f Mon Sep 17 00:00:00 2001 From: Christian Monch Date: Mon, 5 Oct 2026 06:31:08 +0200 Subject: [PATCH 07/20] refactor: move existing endpoints to endpoints.v0 Endpoints are now organized in packages in `dump_things_service.`. The currently existing endpoints are added as version `v0`. That means they are moved to `endpoints.v0`. --- dump_things_service/collection.py | 8 ++-- dump_things_service/endpoints/__init__.py | 0 dump_things_service/endpoints/v0/__init__.py | 0 .../{ => endpoints/v0}/base_endpoints.py | 0 .../v0}/collection_endpoints.py | 0 .../{ => endpoints/v0}/curated.py | 0 .../{ => endpoints/v0}/incoming.py | 0 .../{ => endpoints/v0}/token_endpoints.py | 0 dump_things_service/main.py | 37 ++++--------------- dump_things_service/tests/fixtures.py | 4 +- .../tests/test_collection_administration.py | 6 +-- dump_things_service/tests/test_config.py | 4 +- dump_things_service/tests/test_paths.py | 2 +- 13 files changed, 19 insertions(+), 42 deletions(-) create mode 100644 dump_things_service/endpoints/__init__.py create mode 100644 dump_things_service/endpoints/v0/__init__.py rename dump_things_service/{ => endpoints/v0}/base_endpoints.py (100%) rename dump_things_service/{ => endpoints/v0}/collection_endpoints.py (100%) rename dump_things_service/{ => endpoints/v0}/curated.py (100%) rename dump_things_service/{ => endpoints/v0}/incoming.py (100%) rename dump_things_service/{ => endpoints/v0}/token_endpoints.py (100%) diff --git a/dump_things_service/collection.py b/dump_things_service/collection.py index 59c1b0f..0308338 100644 --- a/dump_things_service/collection.py +++ b/dump_things_service/collection.py @@ -59,17 +59,17 @@ from dump_things_service.auth.config import ConfigAuthenticationSource from dump_things_service.auth.forgejo import ForgejoAuthenticationSource from dump_things_service.backends.record_dir_index import index_file_name from dump_things_service.converter import FormatConverter -from dump_things_service.curated import ( +from dump_things_service.endpoints.v0.curated import ( store_curated_record, # noqa: F401 -- used by autogenerated code ) +from dump_things_service.endpoints.v0.incoming import ( + store_incoming_record, # noqa: F401 -- used by autogenerated code +) from dump_things_service.exceptions import ( ConfigCollisionError, ConfigError, CurieResolutionError, ) -from dump_things_service.incoming import ( - store_incoming_record, # noqa: F401 -- used by autogenerated code -) from dump_things_service.instance_state import ( InstanceState, InstanceStateCollectionInfo, diff --git a/dump_things_service/endpoints/__init__.py b/dump_things_service/endpoints/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/dump_things_service/endpoints/v0/__init__.py b/dump_things_service/endpoints/v0/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/dump_things_service/base_endpoints.py b/dump_things_service/endpoints/v0/base_endpoints.py similarity index 100% rename from dump_things_service/base_endpoints.py rename to dump_things_service/endpoints/v0/base_endpoints.py diff --git a/dump_things_service/collection_endpoints.py b/dump_things_service/endpoints/v0/collection_endpoints.py similarity index 100% rename from dump_things_service/collection_endpoints.py rename to dump_things_service/endpoints/v0/collection_endpoints.py diff --git a/dump_things_service/curated.py b/dump_things_service/endpoints/v0/curated.py similarity index 100% rename from dump_things_service/curated.py rename to dump_things_service/endpoints/v0/curated.py diff --git a/dump_things_service/incoming.py b/dump_things_service/endpoints/v0/incoming.py similarity index 100% rename from dump_things_service/incoming.py rename to dump_things_service/endpoints/v0/incoming.py diff --git a/dump_things_service/token_endpoints.py b/dump_things_service/endpoints/v0/token_endpoints.py similarity index 100% rename from dump_things_service/token_endpoints.py rename to dump_things_service/endpoints/v0/token_endpoints.py diff --git a/dump_things_service/main.py b/dump_things_service/main.py index d77b719..df6ec6d 100644 --- a/dump_things_service/main.py +++ b/dump_things_service/main.py @@ -19,10 +19,7 @@ from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from fastapi_pagination import add_pagination from fastapi_pagination.utils import disable_installed_extensions_check -from pydantic import ( - BaseModel, - Field, -) + from dump_things_service import __version__ from dump_things_service.abstract_config import ( Configuration, @@ -31,35 +28,15 @@ from dump_things_service.abstract_config import ( CONFIG_VERSION_1_ID, CONFIG_VERSION_2_ID, ) -from dump_things_service.base_endpoints import router as base_router -from dump_things_service.curated import router as curated_router -from dump_things_service.incoming import router as incoming_router -from dump_things_service.instance_state import create_instance_state, InstanceState -from dump_things_service.collection_endpoints import router as collection_router -from dump_things_service.token_endpoints import ( +from dump_things_service.endpoints.v0.base_endpoints import router as base_router +from dump_things_service.endpoints.v0.curated import router as curated_router +from dump_things_service.endpoints.v0.incoming import router as incoming_router +from dump_things_service.endpoints.v0.collection_endpoints import router as collection_router +from dump_things_service.endpoints.v0.token_endpoints import ( hash_matcher, router as token_router, ) - - -class MaintenanceRequest(BaseModel): - collection: str - active: bool - - -class ServerCollectionResponse(BaseModel): - name: str - schema_location: str = Field(alias='schema') - classes: list[str] - - -class ServerCollectionCountedResponse(ServerCollectionResponse): - records: int - - -class ServerResponse(BaseModel): - version: str - collections: list[ServerCollectionResponse | ServerCollectionCountedResponse] +from dump_things_service.instance_state import create_instance_state, InstanceState logging.basicConfig(level=logging.WARNING) diff --git a/dump_things_service/tests/fixtures.py b/dump_things_service/tests/fixtures.py index 0f1ce9e..f8000da 100644 --- a/dump_things_service/tests/fixtures.py +++ b/dump_things_service/tests/fixtures.py @@ -26,7 +26,8 @@ from dump_things_service.backends.sqlite import ( from dump_things_service.backends.sqlite import ( record_file_name as sqlite_db_filename, ) -from dump_things_service.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.instance_state import get_mapping_function_by_name from dump_things_service.model import get_model_for_schema from dump_things_service.resolve_curie import resolve_curie @@ -38,7 +39,6 @@ from dump_things_service.tests.create_store import ( test_record_curated, test_record_trr, ) -from dump_things_service.token_endpoints import TokenRequest # String representation of curated- and incoming-path curated = 'curated' diff --git a/dump_things_service/tests/test_collection_administration.py b/dump_things_service/tests/test_collection_administration.py index cfb749d..6a36a30 100644 --- a/dump_things_service/tests/test_collection_administration.py +++ b/dump_things_service/tests/test_collection_administration.py @@ -18,12 +18,12 @@ from dump_things_service.abstract_config import ( TokenModes, hash_token_representation, ) -from dump_things_service.collection_endpoints import CollectionRequest -from dump_things_service.instance_state import get_instance_state -from dump_things_service.token_endpoints import ( +from dump_things_service.endpoints.v0.collection_endpoints import CollectionRequest +from dump_things_service.endpoints.v0.token_endpoints import ( AdminTokenRequest, TokenRequest, ) +from dump_things_service.instance_state import get_instance_state # String representation of curated- and incoming-path curated = 'admin_test_curated' diff --git a/dump_things_service/tests/test_config.py b/dump_things_service/tests/test_config.py index b37190c..58c4410 100644 --- a/dump_things_service/tests/test_config.py +++ b/dump_things_service/tests/test_config.py @@ -22,10 +22,10 @@ from dump_things_service.abstract_config import ( get_config_backends, read_config, ) -from dump_things_service.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.exceptions import ConfigError from dump_things_service.tests import schema_file -from dump_things_service.token_endpoints import TokenRequest reference_config_file = Path(__file__).parent / 'assets' / 'reference_config.yaml' diff --git a/dump_things_service/tests/test_paths.py b/dump_things_service/tests/test_paths.py index aac8296..24dbe56 100644 --- a/dump_things_service/tests/test_paths.py +++ b/dump_things_service/tests/test_paths.py @@ -4,7 +4,7 @@ from pathlib import ( ) from dump_things_service import HTTP_406_NOT_ACCEPTABLE -from dump_things_service.collection_endpoints import CollectionRequest +from dump_things_service.endpoints.v0.collection_endpoints import CollectionRequest # Path to a local simple test schema test_schema_location = str((Path(__file__).parent / 'testschema.yaml').absolute()) -- 2.54.1 From 38a9fa6c13a368cd7eabf48eda5c07cc18936af4 Mon Sep 17 00:00:00 2001 From: Christian Monch Date: Tue, 6 Oct 2026 17:19:59 +0200 Subject: [PATCH 08/20] refactor: replace auto-generated validate endpoints --- dump_things_service/collection.py | 40 +----------- .../{ => endpoints/v0}/validate.py | 64 ++++++++++++++++--- dump_things_service/main.py | 3 + dump_things_service/tests/test_validate.py | 2 +- 4 files changed, 61 insertions(+), 48 deletions(-) rename dump_things_service/{ => endpoints/v0}/validate.py (60%) diff --git a/dump_things_service/collection.py b/dump_things_service/collection.py index 0308338..0b5a8b0 100644 --- a/dump_things_service/collection.py +++ b/dump_things_service/collection.py @@ -88,32 +88,10 @@ from dump_things_service.utils import ( var_escape, wrap_http_exception, ) -from dump_things_service.validate import ( - validate_record, # noqa: F401 -- used by autogenerated code -) + logger = logging.getLogger('dump_things_service') -_endpoint_template = """ -def {name}( - data: {model_var_name}.{class_name} | Annotated[str, Body(media_type='text/plain')], - api_key: str = Depends(api_key_header_scheme), - add_submission_tag: bool = False, - format: Format = Format.json, -) -> JSONResponse | PlainTextResponse: - logger.info('{name}(%s, %s, %s, %s, %s)', repr(data), repr('{class_name}'), repr({model_var_name}), repr(add_submission_tag), repr(format)) - return {handler}('{collection}', data, '{class_name}', {model_var_name}, format, api_key, add_submission_tag=add_submission_tag) -""" - -_endpoint_validate_template = """ -def {name}( - data: {model_var_name}.{class_name} | Annotated[str, Body(media_type='text/plain')], - api_key: str = Depends(api_key_header_scheme), - format: Format = Format.json, -) -> JSONResponse | PlainTextResponse: - logger.info('{name}(%s, %s, %s, %s)', repr(data), repr('{class_name}'), repr({model_var_name}), repr(format)) - return {handler}('{collection}', data, '{class_name}', {model_var_name}, format, api_key) -""" _endpoint_curated_template = """ def {name}( @@ -540,22 +518,6 @@ def create_endpoints_for_collection( tag_group, tag_name, ) in ( - #( - # 'store', - # 'record', - # _endpoint_template, - # 'store_record', - # 'write', - # f'Write records to collection "{collection_name}"', - #), - ( - 'validate', - 'validate/record', - _endpoint_validate_template, - 'validate_record', - 'validate', - f'Validate records for collection "{collection_name}"', - ), ( 'curated', 'curated/record', diff --git a/dump_things_service/validate.py b/dump_things_service/endpoints/v0/validate.py similarity index 60% rename from dump_things_service/validate.py rename to dump_things_service/endpoints/v0/validate.py index 450677a..fdd0ba4 100644 --- a/dump_things_service/validate.py +++ b/dump_things_service/endpoints/v0/validate.py @@ -1,6 +1,8 @@ +import logging from typing import Any from fastapi import ( + APIRouter, Depends, HTTPException, ) @@ -25,6 +27,7 @@ from dump_things_service.abstract_config import ( from dump_things_service.api_key import api_key_header_scheme 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 ( get_token_store, join_default_token_permissions, @@ -32,23 +35,63 @@ from dump_things_service.utils import ( ) +logger = logging.getLogger('dump_things_service') + +router = APIRouter() + + +_endpoint_validate_template = """ +def {name}( + data: {model_var_name}.{class_name} | Annotated[str, Body(media_type='text/plain')], + api_key: str = Depends(api_key_header_scheme), + format: Format = Format.json, +) -> JSONResponse | PlainTextResponse: + logger.info('{name}(%s, %s, %s, %s)', repr(data), repr('{class_name}'), repr({model_var_name}), repr(format)) + return {handler}('{collection}', data, '{class_name}', {model_var_name}, format, api_key) +""" + + +@router.post( + '/{collection}/validate/record/{class_name}', + tags=['Validate records'], + name='Validate record of class {class_name} for collection {collection}', + openapi_extra={ + "requestBody": { + "required": True, + "content": { + "application/json": { + "schema": { + "type": "object" + } + }, + "text/turtle": { + "schema": { + "type": "string" + } + }, + }, + } + }, +) def validate_record( + body: dict | str, collection: str, - data: BaseModel | str, class_name: str, - model: Any, - input_format: Format, + format: Format = Format.json, api_key: str | None = Depends(api_key_header_scheme), ) -> JSONResponse: + + logger.info('validate_record(%s, %s, %s)', repr(body), repr(class_name), repr(format)) + instance_state = get_instance_state() abstract_config = get_config() - if input_format == Format.json and isinstance(data, str): + if format == Format.json and isinstance(body, str): raise HTTPException( status_code=HTTP_400_BAD_REQUEST, detail='Invalid JSON data provided.' ) - if input_format == Format.ttl and not isinstance(data, str): + if format == Format.ttl and not isinstance(body, str): raise HTTPException( status_code=HTTP_400_BAD_REQUEST, detail='Invalid ttl data provided.' ) @@ -78,7 +121,11 @@ def validate_record( detail=f"Not authorized to validate records for collection '{collection}'.", ) - if input_format == Format.ttl: + model = get_model_for_schema( + abstract_config.collections[collection].schema_location + )[0] + + if format == Format.ttl: with wrap_http_exception( ValueError, status_code=HTTP_422_UNPROCESSABLE_CONTENT, @@ -88,7 +135,7 @@ def validate_record( abstract_config.collections[collection].schema_location, input_format=Format.ttl, output_format=Format.json, - ).convert(data, class_name) + ).convert(body, class_name) with wrap_http_exception( ValidationError, status_code=HTTP_422_UNPROCESSABLE_CONTENT, @@ -103,6 +150,7 @@ def validate_record( status_code=HTTP_422_UNPROCESSABLE_CONTENT, header='Validation error', ): - instance_state.validators[collection].validate(data) + pydantic_object = getattr(model, class_name)(**body) + instance_state.validators[collection].validate(pydantic_object) return JSONResponse(True) diff --git a/dump_things_service/main.py b/dump_things_service/main.py index df6ec6d..720fc31 100644 --- a/dump_things_service/main.py +++ b/dump_things_service/main.py @@ -36,6 +36,7 @@ from dump_things_service.endpoints.v0.token_endpoints import ( hash_matcher, router as token_router, ) +from dump_things_service.endpoints.v0.validate import router as validate_router from dump_things_service.instance_state import create_instance_state, InstanceState @@ -164,6 +165,8 @@ app = FastAPI( app.include_router(curated_router) app.include_router(incoming_router) + +app.include_router(validate_router) app.include_router(token_router) app.include_router(collection_router) app.include_router(base_router) diff --git a/dump_things_service/tests/test_validate.py b/dump_things_service/tests/test_validate.py index d6c3e10..9f26da1 100644 --- a/dump_things_service/tests/test_validate.py +++ b/dump_things_service/tests/test_validate.py @@ -60,6 +60,6 @@ def test_validate_record(fastapi_client_simple): response = test_client.post( '/collection_1/validate/record/Person?format=ttl', headers={'x-dumpthings-token': 'token-1'}, - json=record, + data=record, ) assert response.status_code == expected_status -- 2.54.1 From e09dc13eae6b4e44d31c25e1cde89f6845349d5b Mon Sep 17 00:00:00 2001 From: Christian Monch Date: Tue, 6 Oct 2026 21:12:07 +0200 Subject: [PATCH 09/20] refactor: consolidate dict -> BaseModel conversion --- .../endpoints/v0/base_endpoints.py | 18 ++---------- dump_things_service/utils.py | 28 ++++++++++++++++++- 2 files changed, 30 insertions(+), 16 deletions(-) diff --git a/dump_things_service/endpoints/v0/base_endpoints.py b/dump_things_service/endpoints/v0/base_endpoints.py index 3f69b1d..6df11d9 100644 --- a/dump_things_service/endpoints/v0/base_endpoints.py +++ b/dump_things_service/endpoints/v0/base_endpoints.py @@ -73,7 +73,7 @@ from dump_things_service.utils import ( order_dict, process_token, simple_process_token, - wrap_http_exception, + wrap_http_exception, dict_to_base_model, ) if TYPE_CHECKING: @@ -292,9 +292,6 @@ async def store_record( detail=f"Not authorized to submit to collection '{collection}'.", ) - model, classes, model_var_name = get_model_for_schema( - configuration.collections[collection].schema_location - ) if class_name not in instance_state.collections[collection].active_classes: raise HTTPException( status_code=HTTP_404_NOT_FOUND, @@ -315,15 +312,7 @@ async def store_record( else: json_object = body - with wrap_http_exception( - ValidationError, - status_code=HTTP_422_UNPROCESSABLE_CONTENT, - header='Validation error', - ): - record = TypeAdapter(getattr(model, class_name)).validate_python( - json_object - ) - + record = dict_to_base_model(json_object, class_name, collection) with wrap_http_exception( ValueError, status_code=HTTP_422_UNPROCESSABLE_CONTENT, @@ -331,10 +320,9 @@ async def store_record( ): instance_state.validators[collection].validate(record) - sorted_record = order_dict(record) with wrap_http_exception(CurieResolutionError): stored_records = store.store_object( - obj=sorted_record, + obj=record, submitter=user_id if add_submission_tag else None, ) diff --git a/dump_things_service/utils.py b/dump_things_service/utils.py index 39fd7c7..331623e 100644 --- a/dump_things_service/utils.py +++ b/dump_things_service/utils.py @@ -21,7 +21,13 @@ from typing import ( import fsspec import yaml from fastapi import HTTPException +from pydantic import ( + BaseModel, + TypeAdapter, + ValidationError, +) from rdflib import Graph +from starlette.status import HTTP_422_UNPROCESSABLE_CONTENT from dump_things_service import ( HTTP_400_BAD_REQUEST, @@ -44,6 +50,7 @@ from dump_things_service.auth import ( AuthenticationError, AuthenticationInfo, ) +from dump_things_service.model import get_model_for_schema if TYPE_CHECKING: from pathlib import Path @@ -99,7 +106,7 @@ def combine_ttl(documents: list[str]) -> str: @contextmanager def wrap_http_exception( - exception_class: type[Exception] = ValueError, + exception_class: type[Exception] | tuple[type[Exception]] = ValueError, status_code: int = HTTP_400_BAD_REQUEST, header: str = '', ): @@ -627,3 +634,22 @@ def _order_dict( if isinstance(d, list): return [order_dict(e) for e in d] return d + + +def dict_to_base_model( + data: dict, + class_name: str, + collection_name: str, +) -> BaseModel: + from dump_things_service.abstract_config import get_config + + configuration = get_config() + model = get_model_for_schema( + configuration.collections[collection_name].schema_location + )[0] + with wrap_http_exception( + ValidationError, + status_code=HTTP_422_UNPROCESSABLE_CONTENT, + header='Validation error', + ): + return TypeAdapter(getattr(model, class_name)).validate_python(data) -- 2.54.1 From 514b8283cea7e61177b0f630eda5a23649d06f04 Mon Sep 17 00:00:00 2001 From: Christian Monch Date: Tue, 6 Oct 2026 21:14:16 +0200 Subject: [PATCH 10/20] refactor: improve validate endpoint --- dump_things_service/endpoints/v0/validate.py | 28 ++++++-------------- 1 file changed, 8 insertions(+), 20 deletions(-) diff --git a/dump_things_service/endpoints/v0/validate.py b/dump_things_service/endpoints/v0/validate.py index fdd0ba4..9ed1cc4 100644 --- a/dump_things_service/endpoints/v0/validate.py +++ b/dump_things_service/endpoints/v0/validate.py @@ -1,5 +1,4 @@ import logging -from typing import Any from fastapi import ( APIRouter, @@ -7,7 +6,6 @@ from fastapi import ( HTTPException, ) from pydantic import ( - BaseModel, TypeAdapter, ValidationError, ) @@ -29,28 +27,17 @@ 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 ( + dict_to_base_model, get_token_store, join_default_token_permissions, wrap_http_exception, ) - logger = logging.getLogger('dump_things_service') router = APIRouter() -_endpoint_validate_template = """ -def {name}( - data: {model_var_name}.{class_name} | Annotated[str, Body(media_type='text/plain')], - api_key: str = Depends(api_key_header_scheme), - format: Format = Format.json, -) -> JSONResponse | PlainTextResponse: - logger.info('{name}(%s, %s, %s, %s)', repr(data), repr('{class_name}'), repr({model_var_name}), repr(format)) - return {handler}('{collection}', data, '{class_name}', {model_var_name}, format, api_key) -""" - - @router.post( '/{collection}/validate/record/{class_name}', tags=['Validate records'], @@ -81,7 +68,7 @@ def validate_record( api_key: str | None = Depends(api_key_header_scheme), ) -> JSONResponse: - logger.info('validate_record(%s, %s, %s)', repr(body), repr(class_name), repr(format)) + logger.info('validate_record(%s, %s, %s, %s, *)', repr(body), collection, repr(class_name), repr(format)) instance_state = get_instance_state() abstract_config = get_config() @@ -121,10 +108,6 @@ def validate_record( detail=f"Not authorized to validate records for collection '{collection}'.", ) - model = get_model_for_schema( - abstract_config.collections[collection].schema_location - )[0] - if format == Format.ttl: with wrap_http_exception( ValueError, @@ -136,6 +119,11 @@ def validate_record( input_format=Format.ttl, output_format=Format.json, ).convert(body, class_name) + + model = get_model_for_schema( + abstract_config.collections[collection].schema_location + )[0] + with wrap_http_exception( ValidationError, status_code=HTTP_422_UNPROCESSABLE_CONTENT, @@ -150,7 +138,7 @@ def validate_record( status_code=HTTP_422_UNPROCESSABLE_CONTENT, header='Validation error', ): - pydantic_object = getattr(model, class_name)(**body) + pydantic_object = dict_to_base_model(body, class_name, collection) instance_state.validators[collection].validate(pydantic_object) return JSONResponse(True) -- 2.54.1 From b846da13d1f22b4e2b4a39c6b543bc247880838c Mon Sep 17 00:00:00 2001 From: Christian Monch Date: Wed, 7 Oct 2026 01:03:27 +0200 Subject: [PATCH 11/20] refactor: use non-generated curator-endpoint --- dump_things_service/collection.py | 40 ++++------------- dump_things_service/endpoints/v0/curated.py | 48 ++++++++++++++++++--- 2 files changed, 49 insertions(+), 39 deletions(-) diff --git a/dump_things_service/collection.py b/dump_things_service/collection.py index 0b5a8b0..ead4c1e 100644 --- a/dump_things_service/collection.py +++ b/dump_things_service/collection.py @@ -59,9 +59,6 @@ from dump_things_service.auth.config import ConfigAuthenticationSource from dump_things_service.auth.forgejo import ForgejoAuthenticationSource from dump_things_service.backends.record_dir_index import index_file_name from dump_things_service.converter import FormatConverter -from dump_things_service.endpoints.v0.curated import ( - store_curated_record, # noqa: F401 -- used by autogenerated code -) from dump_things_service.endpoints.v0.incoming import ( store_incoming_record, # noqa: F401 -- used by autogenerated code ) @@ -93,27 +90,6 @@ from dump_things_service.utils import ( logger = logging.getLogger('dump_things_service') -_endpoint_curated_template = """ -def {name}( - data: {model_var_name}.{class_name}, - author_id: str | None = None, - api_key: str = Depends(api_key_header_scheme), -) -> JSONResponse: - logger.info( - '{name}(%s, %s, %s)', - repr(data), - repr(author_id), - repr({model_var_name}), - ) - return store_curated_record( - '{collection}', - data, - '{class_name}', - author_id, - api_key, - ) -""" - _endpoint_incoming_template = """ async def {name}( data: {model_var_name}.{class_name}, @@ -518,14 +494,14 @@ def create_endpoints_for_collection( tag_group, tag_name, ) in ( - ( - 'curated', - 'curated/record', - _endpoint_curated_template, - 'store_curated_record', - 'curated_write', - f'Curated area: store records in curated area of collection "{collection_name}"', - ), +# ( +# 'curated', +# 'curated/record', +# _endpoint_curated_template, +# 'store_curated_record', +# 'curated_write', +# f'Curated area: store records in curated area of collection "{collection_name}"', +# ), ( 'incoming', 'incoming/{label}/record', diff --git a/dump_things_service/endpoints/v0/curated.py b/dump_things_service/endpoints/v0/curated.py index 7046678..6b1743b 100644 --- a/dump_things_service/endpoints/v0/curated.py +++ b/dump_things_service/endpoints/v0/curated.py @@ -37,7 +37,7 @@ from dump_things_service.utils import ( check_bounds, cleaned_json, order_dict, - wrap_http_exception, + wrap_http_exception, dict_to_base_model, ) if TYPE_CHECKING: @@ -302,18 +302,52 @@ def _get_store_and_backend( return model_store, backend, auth_info +@router.post( + '/{collection}/curated/record/{class_name}', + tags=['Store record in curated area'], + name='Curated area: store record of class {class_name} in curated area of collection {collection}', + openapi_extra={ + "requestBody": { + "required": True, + "content": { + "application/json": { + "schema": { + "type": "object" + } + }, + "text/turtle": { + "schema": { + "type": "string" + } + }, + }, + } + }, +) def store_curated_record( + body: dict | str, collection: str, - data: BaseModel, class_name: str, - author_id: str | None, - api_key: str | None, + author_id: str | None = None, + api_key: str | None = Depends(api_key_header_scheme), ): + logger.info( + 'store_curated_record(%s, %s, %s, %s, *)', + repr(body), + collection, + class_name, + repr(author_id), + ) + instance_state = get_instance_state() + data = dict_to_base_model(body, class_name, collection) + + # Ensure convertibility to TTL, this will validate additional schema + # constraints, e.g., prefixes. with wrap_http_exception( - ValueError, - status_code=HTTP_422_UNPROCESSABLE_CONTENT, - header='Validation error', + ValueError, + status_code=HTTP_422_UNPROCESSABLE_CONTENT, + header='Validation error', ): instance_state.validators[collection].validate(data) -- 2.54.1 From 53a9026c80386cfa246dcc6071223ee6557b7af6 Mon Sep 17 00:00:00 2001 From: Christian Monch Date: Wed, 7 Oct 2026 01:48:01 +0200 Subject: [PATCH 12/20] refactor: use non-generated incoming endpoints --- dump_things_service/collection.py | 38 ++++------------ dump_things_service/endpoints/v0/incoming.py | 43 +++++++++++++++++-- .../tests/test_collection_administration.py | 9 ---- 3 files changed, 48 insertions(+), 42 deletions(-) diff --git a/dump_things_service/collection.py b/dump_things_service/collection.py index ead4c1e..2f6aeea 100644 --- a/dump_things_service/collection.py +++ b/dump_things_service/collection.py @@ -90,28 +90,6 @@ from dump_things_service.utils import ( logger = logging.getLogger('dump_things_service') -_endpoint_incoming_template = """ -async def {name}( - data: {model_var_name}.{class_name}, - label: str, - api_key: str = Depends(api_key_header_scheme), -) -> JSONResponse: - logger.info( - '{name}(%s, %s, %s)', - repr(data), - repr(label), - repr({model_var_name}), - ) - return await store_incoming_record( - '{collection}', - label, - data, - '{class_name}', - api_key, - ) -""" - - def create_collection( instance_state: InstanceState, configuration: Configuration, @@ -502,14 +480,14 @@ def create_endpoints_for_collection( # 'curated_write', # f'Curated area: store records in curated area of collection "{collection_name}"', # ), - ( - 'incoming', - 'incoming/{label}/record', - _endpoint_incoming_template, - 'store_incoming_record', - 'incoming_write', - f'Incoming area: store records in incoming area "{{label}}" of collection "{collection_name}"', - ), +# ( +# 'incoming', +# 'incoming/{label}/record', +# _endpoint_incoming_template, +# 'store_incoming_record', +# 'incoming_write', +# f'Incoming area: store records in incoming area "{{label}}" of collection "{collection_name}"', +# ), ): create_endpoint( operation_name=operation_name, diff --git a/dump_things_service/endpoints/v0/incoming.py b/dump_things_service/endpoints/v0/incoming.py index 4aaf471..8eb7554 100644 --- a/dump_things_service/endpoints/v0/incoming.py +++ b/dump_things_service/endpoints/v0/incoming.py @@ -1,5 +1,6 @@ from __future__ import annotations +import logging from typing import TYPE_CHECKING, Annotated from fastapi import ( @@ -12,6 +13,7 @@ from fastapi_pagination import ( add_pagination, paginate, ) +from starlette.responses import JSONResponse from starlette.status import HTTP_403_FORBIDDEN from dump_things_service import ( @@ -41,7 +43,7 @@ from dump_things_service.utils import ( create_token_store, get_on_disk_labels, order_dict, - wrap_http_exception, + wrap_http_exception, dict_to_base_model, ) if TYPE_CHECKING: @@ -52,6 +54,8 @@ if TYPE_CHECKING: from dump_things_service.store.model_store import _ModelStore +logger = logging.getLogger('dump_things_service') + router = APIRouter() add_pagination(router) @@ -357,13 +361,46 @@ async def authorize_zones( ) +@router.post( + '/{collection}/incoming/{label}/record/{class_name}', + tags=['Store record in an incoming area'], + name='Incoming area: store a record of class {class_name} in incoming area {label} of collection {collection_name}', + openapi_extra={ + "requestBody": { + "required": True, + "content": { + "application/json": { + "schema": { + "type": "object" + } + }, + "text/turtle": { + "schema": { + "type": "string" + } + }, + }, + } + }, +) async def store_incoming_record( + body: dict | str, collection: str, label: str, - data: BaseModel, class_name: str, - api_key: str | None, + api_key: str | None = Depends(api_key_header_scheme), ): + + logger.info( + 'store_incoming_record(%s, %s, %s, %s, *)', + repr(body), + collection, + label, + class_name, + ) + + data = dict_to_base_model(body, class_name, collection) + instance_state = get_instance_state() with wrap_http_exception( ValueError, diff --git a/dump_things_service/tests/test_collection_administration.py b/dump_things_service/tests/test_collection_administration.py index 6a36a30..151afd3 100644 --- a/dump_things_service/tests/test_collection_administration.py +++ b/dump_things_service/tests/test_collection_administration.py @@ -82,7 +82,6 @@ def test_collection_adding(fastapi_client_simple): headers={'x-dumpthings-token': admin_token}, ) assert response.status_code == HTTP_404_NOT_FOUND - assert not _name_in_openapi_paths(test_client, new_collection_name) # Add a new collection to the configuration response = test_client.post( @@ -92,9 +91,6 @@ def test_collection_adding(fastapi_client_simple): ) assert response.status_code == HTTP_201_CREATED - # Check that the collection endpoints exist in the open API document - assert _name_in_openapi_paths(test_client, new_collection_name) - # Read back the new collection and compare it response = test_client.get( f'/collections/{new_collection_name}', @@ -179,9 +175,6 @@ def test_collection_adding(fastapi_client_simple): ) assert response.status_code == HTTP_404_NOT_FOUND - # Check that the openapi document is adjusted - assert not _name_in_openapi_paths(test_client, new_collection_name) - def test_collection_putting(fastapi_client_simple, tmp_path): test_client, _, admin_token = fastapi_client_simple @@ -215,7 +208,6 @@ def test_collection_putting(fastapi_client_simple, tmp_path): headers={'x-dumpthings-token': admin_token}, ) assert response.status_code == HTTP_404_NOT_FOUND - assert not _name_in_openapi_paths(test_client, put_collection_name) # Add the first version of the collection response = test_client.post( @@ -224,7 +216,6 @@ def test_collection_putting(fastapi_client_simple, tmp_path): json=put_collection_request_orig.model_dump(mode='json', by_alias=True), ) assert response.status_code == HTTP_201_CREATED - assert _name_in_openapi_paths(test_client, put_collection_name) audit_files = tuple(tmp_path.iterdir()) assert len(audit_files) == 0 -- 2.54.1 From a5ba6508e89cec02d4be1a0b71d11fa8487f96f9 Mon Sep 17 00:00:00 2001 From: Christian Monch Date: Wed, 7 Oct 2026 01:50:10 +0200 Subject: [PATCH 13/20] refactor: remove endpoint generation and deletion --- dump_things_service/collection.py | 144 ------------------------------ dump_things_service/manifest.py | 6 +- 2 files changed, 1 insertion(+), 149 deletions(-) diff --git a/dump_things_service/collection.py b/dump_things_service/collection.py index 2f6aeea..1c4357a 100644 --- a/dump_things_service/collection.py +++ b/dump_things_service/collection.py @@ -400,150 +400,6 @@ def check_git_audit_compatibility( return -def create_endpoint( - operation_name: str, - operation_path: str, - instance_state: InstanceState, - collection_name: str, - collection_config: CollectionConfig, - template: str, - handler: str, - tag_group: str, - tag_name: str, - app: FastAPI, -): - logger.info( - 'Creating %s-endpoints for collection: "%s"', - operation_name, - collection_name, - ) - - instance_state.collections[collection_name].tag_info[tag_group] = tag_name - - # TODO: get schema_info from instance_state!? - model, _classes, model_var_name = get_model_for_schema( - collection_config.schema_location - ) - globals()[model_var_name] = model - - active_classes = instance_state.collections[collection_name].active_classes - for class_name in active_classes: - endpoint_name = ( - f'_endpoint_{var_escape(collection_name)}_{operation_name}_{class_name}' - ) - endpoint_source = template.format( - name=endpoint_name, - model_var_name=model_var_name, - class_name=class_name, - collection=collection_name, - info=f"'{operation_name} {collection_name}/{class_name} objects'", - handler=handler, - ) - exec(endpoint_source, globals()) # noqa: S102 - - # Create an API route for the endpoint - app.add_api_route( - path=f'/{collection_name}/{operation_path}/{class_name}', - endpoint=globals()[endpoint_name], - methods=['POST'], - name=f'{operation_name} "{class_name}" object (schema: {model.linkml_meta["id"]})', - response_model=None, - tags=[tag_name], - ) - - logger.info( - 'Creation of %d %s-endpoints completed.', - len(active_classes), - operation_name, - ) - - -def create_endpoints_for_collection( - instance_state: InstanceState, - collection_name: str, - collection_config: CollectionConfig, - app: FastAPI, -): - for ( - operation_name, - operation_path, - template, - handler, - tag_group, - tag_name, - ) in ( -# ( -# 'curated', -# 'curated/record', -# _endpoint_curated_template, -# 'store_curated_record', -# 'curated_write', -# f'Curated area: store records in curated area of collection "{collection_name}"', -# ), -# ( -# 'incoming', -# 'incoming/{label}/record', -# _endpoint_incoming_template, -# 'store_incoming_record', -# 'incoming_write', -# f'Incoming area: store records in incoming area "{{label}}" of collection "{collection_name}"', -# ), - ): - create_endpoint( - operation_name=operation_name, - operation_path=operation_path, - instance_state=instance_state, - collection_name=collection_name, - collection_config=collection_config, - template=template, - handler=handler, - tag_group=tag_group, - tag_name=tag_name, - app=app, - ) - - -def delete_endpoints_for_collection( - instance_state: InstanceState, - collection_name: str, -): - active_classes = instance_state.collections[collection_name].active_classes - - for operation_path in ( - 'record', - 'validate/record', - 'curated/record', - 'incoming/{label}/record', - ): - delete_endpoint( - collection_name=collection_name, - active_classes=active_classes, - operation_path=operation_path, - app=instance_state.fastapi_app, - ) - - -def delete_endpoint( - collection_name: str, - active_classes: set[str], - operation_path: str, - app: FastAPI, -): - remove_paths_set = { - f'/{collection_name}/{operation_path}/{class_name}' - for class_name in active_classes - } - - remove_indices = [ - index - for index, api_route in enumerate(app.router.routes) - if not isinstance(api_route, _IncludedRouter) # skip included router - and api_route.path in remove_paths_set - ] - for index in sorted(remove_indices, reverse=True): - del app.router.routes[index] - - def store_record( collection: str, data: BaseModel | str, diff --git a/dump_things_service/manifest.py b/dump_things_service/manifest.py index 528f0fb..2b80737 100644 --- a/dump_things_service/manifest.py +++ b/dump_things_service/manifest.py @@ -7,10 +7,7 @@ from dump_things_service.abstract_config import ( Configuration, TokenConfig, ) -from dump_things_service.collection import ( - create_collection, - delete_endpoints_for_collection, -) +from dump_things_service.collection import create_collection from dump_things_service.instance_state import InstanceState logger = logging.getLogger('dump_things_service') @@ -116,7 +113,6 @@ def manifest_configuration( # configuration (we do not delete the collection from token-objects here # because token-objects are all re-created below). for collection_name in deleted_collection_names: - delete_endpoints_for_collection(instance_state, collection_name) delete_collection_from_instance_state(instance_state, collection_name) # Create the internal representation objects for collections that have been -- 2.54.1 From eaed7a2793d801f3c56d4e66a78d336f002b85af Mon Sep 17 00:00:00 2001 From: Christian Monch Date: Wed, 7 Oct 2026 02:05:31 +0200 Subject: [PATCH 14/20] refactor: remove unused code, simplify expressions --- dump_things_service/collection.py | 171 +----------------- .../endpoints/v0/base_endpoints.py | 3 +- 2 files changed, 4 insertions(+), 170 deletions(-) diff --git a/dump_things_service/collection.py b/dump_things_service/collection.py index 1c4357a..379a967 100644 --- a/dump_things_service/collection.py +++ b/dump_things_service/collection.py @@ -6,41 +6,14 @@ import shutil import fsspec from pathlib import Path -# This following lines are required for dynamic endpoint generation -from typing import ( - Annotated, # noqa: F401 -- used by autogenerated code - Any, -) - from datalad_core.runners import ( CommandError, call_git_oneline, ) -from fastapi import ( - Body, # noqa: F401 -- used by autogenerated code - Depends, - FastAPI, - HTTPException, -) -from fastapi.routing import _IncludedRouter -from pydantic import ( - BaseModel, - TypeAdapter, - ValidationError, -) -from starlette.responses import ( - JSONResponse, - PlainTextResponse, -) +from pydantic import ValidationError -from dump_things_service import ( - HTTP_400_BAD_REQUEST, - HTTP_403_FORBIDDEN, - HTTP_422_UNPROCESSABLE_CONTENT, - Format, -) +from dump_things_service import Format from dump_things_service.abstract_config import ( - CollectionConfig, ConfigAuthSpec, Configuration, ForgejoAuthSpec, @@ -48,43 +21,24 @@ from dump_things_service.abstract_config import ( PolicyMapping, RecordDirBackendConfig, SQLiteBackendConfig, - check_collection, - read_config, -) -from dump_things_service.api_key import ( - api_key_header_scheme, ) from dump_things_service.audit.gitaudit import GitAuditBackend from dump_things_service.auth.config import ConfigAuthenticationSource from dump_things_service.auth.forgejo import ForgejoAuthenticationSource from dump_things_service.backends.record_dir_index import index_file_name from dump_things_service.converter import FormatConverter -from dump_things_service.endpoints.v0.incoming import ( - store_incoming_record, # noqa: F401 -- used by autogenerated code -) from dump_things_service.exceptions import ( ConfigCollisionError, ConfigError, - CurieResolutionError, ) from dump_things_service.instance_state import ( InstanceState, InstanceStateCollectionInfo, - get_instance_state, get_record_dir_config, get_schema_info, record_dir_config_file_name, ) -from dump_things_service.model import get_model_for_schema -from dump_things_service.utils import ( - combine_ttl, - create_store, - get_token_store, - join_default_token_permissions, - order_dict, - var_escape, - wrap_http_exception, -) +from dump_things_service.utils import create_store logger = logging.getLogger('dump_things_service') @@ -246,15 +200,6 @@ def create_collection( ) ) - # Create the dynamic endpoints for record storing & validation, for - # inbox-storing, and for curated area storing. - create_endpoints_for_collection( - instance_state, - collection_name, - collection_configuration, - instance_state.fastapi_app, - ) - def create_authentication_source( abstract_configuration: Configuration, @@ -400,116 +345,6 @@ def check_git_audit_compatibility( return -def store_record( - collection: str, - data: BaseModel | str, - class_name: str, - model: Any, - input_format: Format, - api_key: str | None = Depends(api_key_header_scheme), - *, - add_submission_tag: bool, -) -> JSONResponse | PlainTextResponse: - if input_format == Format.json and isinstance(data, str): - raise HTTPException( - status_code=HTTP_400_BAD_REQUEST, detail='Invalid JSON data provided.' - ) - - if input_format == Format.ttl and not isinstance(data, str): - raise HTTPException( - status_code=HTTP_400_BAD_REQUEST, detail='Invalid ttl data provided.' - ) - - instance_state = get_instance_state() - abstract_config = read_config(instance_state.store_path) - check_collection(abstract_config, collection) - - # Get the token permissions and extend them by the default permissions. - # This call will also convert plaintext tokens into the hashed version of - # the token, if the token is hashed. This is necessary because we do not - # store the plaintext token, so all token-information is associated with - # the hashed representation of the token. - token_representation = ( - abstract_config.collections[collection].default_token - if api_key is None - else api_key - ) - store, token_permissions, user_info = get_token_store( - abstract_config, - instance_state, - collection, - token_representation, - is_token_name=api_key is None, - ) - final_permissions = join_default_token_permissions( - abstract_config, - token_permissions, - collection, - ) - if not final_permissions.incoming_write: - raise HTTPException( - status_code=HTTP_403_FORBIDDEN, - detail=f"Not authorized to submit to collection '{collection}'.", - ) - - if input_format == Format.ttl: - with wrap_http_exception( - ValueError, - status_code=HTTP_422_UNPROCESSABLE_CONTENT, - header='Conversion error', - ): - json_object = FormatConverter( - abstract_config.collections[collection].schema_location, - input_format=Format.ttl, - output_format=Format.json, - ).convert(data, class_name) - with wrap_http_exception( - ValidationError, - status_code=HTTP_422_UNPROCESSABLE_CONTENT, - header='Validation error', - ): - record = TypeAdapter(getattr(model, class_name)).validate_python( - json_object - ) - else: - record = data - - with wrap_http_exception( - ValueError, - status_code=HTTP_422_UNPROCESSABLE_CONTENT, - header='Validation error', - ): - instance_state.validators[collection].validate(record) - - sorted_record = order_dict(record) - with wrap_http_exception(CurieResolutionError): - stored_records = store.store_object( - obj=sorted_record, - submitter=user_info[1] if add_submission_tag else None, - ) - - if input_format == Format.ttl: - format_converter = FormatConverter( - abstract_config.collections[collection].schema_location, - input_format=Format.json, - output_format=Format.ttl, - ) - with wrap_http_exception(ValueError, header='Conversion error'): - return PlainTextResponse( - combine_ttl( - [ - format_converter.convert( - record, - class_name, - ) - for class_name, record in stored_records - ] - ), - media_type='text/turtle', - ) - return JSONResponse([order_dict(record) for _, record in stored_records]) - - def load_policy_info( abstract_configuration: Configuration, collection_name: str, diff --git a/dump_things_service/endpoints/v0/base_endpoints.py b/dump_things_service/endpoints/v0/base_endpoints.py index 6df11d9..573b114 100644 --- a/dump_things_service/endpoints/v0/base_endpoints.py +++ b/dump_things_service/endpoints/v0/base_endpoints.py @@ -250,8 +250,7 @@ async def store_record( configuration = get_config() - if format == Format.json: - if isinstance(body, str): + if format == Format.json and isinstance(body, str): raise HTTPException( status_code=HTTP_400_BAD_REQUEST, detail='Invalid JSON data provided.' ) -- 2.54.1 From 39ff76894626c9f1be02a819ba16e8b9868ad534 Mon Sep 17 00:00:00 2001 From: Christian Monch Date: Wed, 7 Oct 2026 02:09:30 +0200 Subject: [PATCH 15/20] chore: format with hatch fmt --- dump_things_service/collection.py | 19 +- .../endpoints/v0/base_endpoints.py | 166 +++++++++--------- dump_things_service/endpoints/v0/curated.py | 29 ++- dump_things_service/endpoints/v0/incoming.py | 25 +-- dump_things_service/endpoints/v0/validate.py | 27 ++- dump_things_service/main.py | 4 +- dump_things_service/tests/fixtures.py | 2 +- dump_things_service/utils.py | 6 +- 8 files changed, 127 insertions(+), 151 deletions(-) diff --git a/dump_things_service/collection.py b/dump_things_service/collection.py index 379a967..1a38047 100644 --- a/dump_things_service/collection.py +++ b/dump_things_service/collection.py @@ -139,17 +139,18 @@ def create_collection( collection_name, ) # If there is a local configuration, issue a warning - if (collection_configuration.default_policy + if ( + collection_configuration.default_policy or collection_configuration.policy_mapping or collection_configuration.policy_annotation_tag ): logger.warning( "Collection '%s' specifies policy information in its " - "configuration (via `policy_annotation_tag`, `default_policy`, " - "and `policy_mapping`) as well as in an external source (via " - "`policy_info_location`). The policy information specified in " - "the configuration will be ignored and the externally sourced " - "policy information will be used.", + 'configuration (via `policy_annotation_tag`, `default_policy`, ' + 'and `policy_mapping`) as well as in an external source (via ' + '`policy_info_location`). The policy information specified in ' + 'the configuration will be ignored and the externally sourced ' + 'policy information will be used.', collection_name, ) else: @@ -160,9 +161,9 @@ def create_collection( if not policy_annotation_tag and (default_policy or policy_mapping): logger.warning( "Collection '%s' specifies policy information in its configuration " - "(via `default_policy` and/or `policy_mapping`) but does not specify " - "a `policy_annotation_tag`. The policy information will be ignored " - "and no policy enforcement will be performed.", + '(via `default_policy` and/or `policy_mapping`) but does not specify ' + 'a `policy_annotation_tag`. The policy information will be ignored ' + 'and no policy enforcement will be performed.', collection_name, ) diff --git a/dump_things_service/endpoints/v0/base_endpoints.py b/dump_things_service/endpoints/v0/base_endpoints.py index 573b114..3a97529 100644 --- a/dump_things_service/endpoints/v0/base_endpoints.py +++ b/dump_things_service/endpoints/v0/base_endpoints.py @@ -27,8 +27,6 @@ from fastapi_pagination import ( from pydantic import ( BaseModel, Field, - TypeAdapter, - ValidationError, ) from starlette.responses import ( JSONResponse, @@ -61,7 +59,6 @@ from dump_things_service.lazy_list import ( ModifierList, ) from dump_things_service.model import ( - get_model_for_schema, get_subclasses, ) from dump_things_service.utils import ( @@ -73,7 +70,8 @@ from dump_things_service.utils import ( order_dict, process_token, simple_process_token, - wrap_http_exception, dict_to_base_model, + wrap_http_exception, + dict_to_base_model, ) if TYPE_CHECKING: @@ -135,9 +133,9 @@ async def server() -> ServerResponse: name='reload policy information from configured location ', ) async def reload_configured_policy( - collection: str, - api_key: Annotated[str | None, Depends(api_key_header_scheme)], - url: str | None = None, + collection: str, + api_key: Annotated[str | None, Depends(api_key_header_scheme)], + url: str | None = None, ): configuration = get_config() instance_state = get_instance_state() @@ -179,8 +177,8 @@ async def reload_configured_policy( name='put a collection in maintenance mode', ) async def maintenance( - body: MaintenanceRequest, - api_key: Annotated[str | None, Depends(api_key_header_scheme)], + body: MaintenanceRequest, + api_key: Annotated[str | None, Depends(api_key_header_scheme)], ): if api_key is None: raise HTTPException( @@ -201,9 +199,9 @@ async def maintenance( permissions = auth_info.token_permission if not ( - permissions.curated_write - and permissions.curated_read - and permissions.zones_access + permissions.curated_write + and permissions.curated_read + and permissions.zones_access ): raise HTTPException( status_code=HTTP_400_BAD_REQUEST, @@ -221,39 +219,39 @@ async def maintenance( tags=['Store records'], name='Write record of class {class_name} to collection {collection}', openapi_extra={ - "requestBody": { - "required": True, - "content": { - "application/json": { - "schema": { - "type": "object" - } - }, - "text/turtle": { - "schema": { - "type": "string" - } - }, + 'requestBody': { + 'required': True, + 'content': { + 'application/json': {'schema': {'type': 'object'}}, + 'text/turtle': {'schema': {'type': 'string'}}, }, } }, ) async def store_record( - body: dict | str, - collection: str, - class_name: str, - api_key: str = Depends(api_key_header_scheme), - add_submission_tag: bool = False, - format: Format = Format.json, + body: dict | str, + collection: str, + class_name: str, + api_key: str = Depends(api_key_header_scheme), + add_submission_tag: bool = False, + format: Format = Format.json, ): - logger.info('store_record(%s, %s, %s, %s, %s, %s)', type(body), repr(body), repr(collection), repr(class_name), repr(add_submission_tag), repr(format)) + logger.info( + 'store_record(%s, %s, %s, %s, %s, %s)', + type(body), + repr(body), + repr(collection), + repr(class_name), + repr(add_submission_tag), + repr(format), + ) configuration = get_config() if format == Format.json and isinstance(body, str): - raise HTTPException( - status_code=HTTP_400_BAD_REQUEST, detail='Invalid JSON data provided.' - ) + raise HTTPException( + status_code=HTTP_400_BAD_REQUEST, detail='Invalid JSON data provided.' + ) if format == Format.ttl and not isinstance(body, str): raise HTTPException( @@ -299,9 +297,9 @@ async def store_record( if format == Format.ttl: with wrap_http_exception( - ValueError, - status_code=HTTP_422_UNPROCESSABLE_CONTENT, - header='Conversion error', + ValueError, + status_code=HTTP_422_UNPROCESSABLE_CONTENT, + header='Conversion error', ): json_object = FormatConverter( configuration.collections[collection].schema_location, @@ -313,9 +311,9 @@ async def store_record( record = dict_to_base_model(json_object, class_name, collection) with wrap_http_exception( - ValueError, - status_code=HTTP_422_UNPROCESSABLE_CONTENT, - header='Validation error', + ValueError, + status_code=HTTP_422_UNPROCESSABLE_CONTENT, + header='Validation error', ): instance_state.validators[collection].validate(record) @@ -353,10 +351,10 @@ async def store_record( name='Read the record with the given PID from the given collection', ) async def read_record_with_pid( - collection: str, - pid: str, - api_key: Annotated[str, Depends(api_key_header_scheme)], - format: Format = Format.json, # noqa: A002 + collection: str, + pid: str, + api_key: Annotated[str, Depends(api_key_header_scheme)], + format: Format = Format.json, # noqa: A002 ): configuration = get_config() instance_state = get_instance_state() @@ -408,9 +406,9 @@ async def read_record_with_pid( def _get_policy_information( - instance_state: InstanceState, - collection_name: str, - user_info: tuple[str, str], + instance_state: InstanceState, + collection_name: str, + user_info: tuple[str, str], ) -> tuple[str | None, str | None, set[str] | None]: from itertools import chain @@ -441,10 +439,10 @@ def _get_policy_information( name='Read all records from the given collection', ) async def read_all_records( - collection: str, - api_key: Annotated[str, Depends(api_key_header_scheme)], - matching: str | None = None, - format: Format = Format.json, # noqa: A002 + collection: str, + api_key: Annotated[str, Depends(api_key_header_scheme)], + matching: str | None = None, + format: Format = Format.json, # noqa: A002 ): return await _read_all_records( collection=collection, @@ -464,10 +462,10 @@ async def read_all_records( name='Read all records from the given collection with pagination', ) async def read_all_records_paginated( - collection: str, - api_key: Annotated[str, Depends(api_key_header_scheme)], - matching: str | None = None, - format: Format = Format.json, # noqa: A002 + collection: str, + api_key: Annotated[str, Depends(api_key_header_scheme)], + matching: str | None = None, + format: Format = Format.json, # noqa: A002 ) -> Page[dict | str]: result_list = await _read_all_records( collection=collection, @@ -485,11 +483,11 @@ async def read_all_records_paginated( name='Read records of the given class (or subclass) from the given collection', ) async def read_records_of_type( - collection: str, - class_name: str, - api_key: Annotated[str, Depends(api_key_header_scheme)], - matching: str | None = None, - format: Format = Format.json, # noqa: A002 + collection: str, + class_name: str, + api_key: Annotated[str, Depends(api_key_header_scheme)], + matching: str | None = None, + format: Format = Format.json, # noqa: A002 ): return await _read_records_of_type( collection=collection, @@ -510,11 +508,11 @@ async def read_records_of_type( name='Read records of the given class (or subclass) from the given collection with pagination', ) async def read_records_of_type_paginated( - collection: str, - class_name: str, - api_key: Annotated[str, Depends(api_key_header_scheme)], - matching: str | None = None, - format: Format = Format.json, # noqa: A002 + collection: str, + class_name: str, + api_key: Annotated[str, Depends(api_key_header_scheme)], + matching: str | None = None, + format: Format = Format.json, # noqa: A002 ) -> Page[dict | str]: result_list = await _read_records_of_type( collection=collection, @@ -528,11 +526,11 @@ async def read_records_of_type_paginated( async def _read_all_records( - collection: str, - matching: str | None = None, - format: Format = Format.json, # noqa: A002 - api_key: str = Depends(api_key_header_scheme), - bound: int | None = None, + collection: str, + matching: str | None = None, + format: Format = Format.json, # noqa: A002 + api_key: str = Depends(api_key_header_scheme), + bound: int | None = None, ) -> LazyList: def convert_to_http_exception(e: BaseException): raise HTTPException( @@ -565,9 +563,7 @@ async def _read_all_records( result_list.add_list(token_store_list) if final_permissions.curated_read: - curated_store_list = instance_state.curated_stores[ - collection - ].get_all_objects( + curated_store_list = instance_state.curated_stores[collection].get_all_objects( matching=matching, policy_annotation_tag=policy_annotation_tag, default_policy=default_policy, @@ -597,12 +593,12 @@ async def _read_all_records( async def _read_records_of_type( - collection: str, - class_name: str, - matching: str | None = None, - format: Format = Format.json, # noqa: A002 - api_key: str = Depends(api_key_header_scheme), - bound: int | None = None, + collection: str, + class_name: str, + matching: str | None = None, + format: Format = Format.json, # noqa: A002 + api_key: str = Depends(api_key_header_scheme), + bound: int | None = None, ) -> LazyList: def convert_to_http_exception(e: BaseException): raise HTTPException( @@ -691,9 +687,9 @@ async def _read_records_of_type( name='Delete record with the given pid from the given collection', ) async def delete_record( - collection: str, - pid: str, - api_key: Annotated[str, Depends(api_key_header_scheme)], + collection: str, + pid: str, + api_key: Annotated[str, Depends(api_key_header_scheme)], ): configuration = get_config() instance_state = get_instance_state() @@ -714,7 +710,7 @@ async def delete_record( raise HTTPException( status_code=HTTP_404_NOT_FOUND, detail=f"Could not remove record with PID '{pid}' from the " - 'token associated incoming area of collection ' - f"'{collection}'.", + 'token associated incoming area of collection ' + f"'{collection}'.", ) return True diff --git a/dump_things_service/endpoints/v0/curated.py b/dump_things_service/endpoints/v0/curated.py index 6b1743b..1855a62 100644 --- a/dump_things_service/endpoints/v0/curated.py +++ b/dump_things_service/endpoints/v0/curated.py @@ -37,12 +37,11 @@ from dump_things_service.utils import ( check_bounds, cleaned_json, order_dict, - wrap_http_exception, dict_to_base_model, + wrap_http_exception, + dict_to_base_model, ) if TYPE_CHECKING: - from pydantic import BaseModel - from dump_things_service.auth import AuthenticationInfo from dump_things_service.backends import StorageBackend from dump_things_service.lazy_list import LazyList @@ -307,19 +306,11 @@ def _get_store_and_backend( tags=['Store record in curated area'], name='Curated area: store record of class {class_name} in curated area of collection {collection}', openapi_extra={ - "requestBody": { - "required": True, - "content": { - "application/json": { - "schema": { - "type": "object" - } - }, - "text/turtle": { - "schema": { - "type": "string" - } - }, + 'requestBody': { + 'required': True, + 'content': { + 'application/json': {'schema': {'type': 'object'}}, + 'text/turtle': {'schema': {'type': 'string'}}, }, } }, @@ -345,9 +336,9 @@ def store_curated_record( # Ensure convertibility to TTL, this will validate additional schema # constraints, e.g., prefixes. with wrap_http_exception( - ValueError, - status_code=HTTP_422_UNPROCESSABLE_CONTENT, - header='Validation error', + ValueError, + status_code=HTTP_422_UNPROCESSABLE_CONTENT, + header='Validation error', ): instance_state.validators[collection].validate(data) diff --git a/dump_things_service/endpoints/v0/incoming.py b/dump_things_service/endpoints/v0/incoming.py index 8eb7554..2ab0f2e 100644 --- a/dump_things_service/endpoints/v0/incoming.py +++ b/dump_things_service/endpoints/v0/incoming.py @@ -13,7 +13,6 @@ from fastapi_pagination import ( add_pagination, paginate, ) -from starlette.responses import JSONResponse from starlette.status import HTTP_403_FORBIDDEN from dump_things_service import ( @@ -43,12 +42,11 @@ from dump_things_service.utils import ( create_token_store, get_on_disk_labels, order_dict, - wrap_http_exception, dict_to_base_model, + wrap_http_exception, + dict_to_base_model, ) if TYPE_CHECKING: - from pydantic import BaseModel - from dump_things_service.backends import StorageBackend from dump_things_service.lazy_list import LazyList from dump_things_service.store.model_store import _ModelStore @@ -366,19 +364,11 @@ async def authorize_zones( tags=['Store record in an incoming area'], name='Incoming area: store a record of class {class_name} in incoming area {label} of collection {collection_name}', openapi_extra={ - "requestBody": { - "required": True, - "content": { - "application/json": { - "schema": { - "type": "object" - } - }, - "text/turtle": { - "schema": { - "type": "string" - } - }, + 'requestBody': { + 'required': True, + 'content': { + 'application/json': {'schema': {'type': 'object'}}, + 'text/turtle': {'schema': {'type': 'string'}}, }, } }, @@ -390,7 +380,6 @@ async def store_incoming_record( class_name: str, api_key: str | None = Depends(api_key_header_scheme), ): - logger.info( 'store_incoming_record(%s, %s, %s, %s, *)', repr(body), diff --git a/dump_things_service/endpoints/v0/validate.py b/dump_things_service/endpoints/v0/validate.py index 9ed1cc4..0f5455a 100644 --- a/dump_things_service/endpoints/v0/validate.py +++ b/dump_things_service/endpoints/v0/validate.py @@ -43,19 +43,11 @@ router = APIRouter() tags=['Validate records'], name='Validate record of class {class_name} for collection {collection}', openapi_extra={ - "requestBody": { - "required": True, - "content": { - "application/json": { - "schema": { - "type": "object" - } - }, - "text/turtle": { - "schema": { - "type": "string" - } - }, + 'requestBody': { + 'required': True, + 'content': { + 'application/json': {'schema': {'type': 'object'}}, + 'text/turtle': {'schema': {'type': 'string'}}, }, } }, @@ -67,8 +59,13 @@ def validate_record( format: Format = Format.json, 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)) + logger.info( + 'validate_record(%s, %s, %s, %s, *)', + repr(body), + collection, + repr(class_name), + repr(format), + ) instance_state = get_instance_state() abstract_config = get_config() diff --git a/dump_things_service/main.py b/dump_things_service/main.py index 720fc31..bf41dbe 100644 --- a/dump_things_service/main.py +++ b/dump_things_service/main.py @@ -31,7 +31,9 @@ from dump_things_service.abstract_config import ( from dump_things_service.endpoints.v0.base_endpoints import router as base_router from dump_things_service.endpoints.v0.curated import router as curated_router from dump_things_service.endpoints.v0.incoming import router as incoming_router -from dump_things_service.endpoints.v0.collection_endpoints import router as collection_router +from dump_things_service.endpoints.v0.collection_endpoints import ( + router as collection_router, +) from dump_things_service.endpoints.v0.token_endpoints import ( hash_matcher, router as token_router, diff --git a/dump_things_service/tests/fixtures.py b/dump_things_service/tests/fixtures.py index f8000da..5254aef 100644 --- a/dump_things_service/tests/fixtures.py +++ b/dump_things_service/tests/fixtures.py @@ -99,7 +99,7 @@ g_default_collections.append( 'test_user_8_default_policy', ], ), - ] + ], ) ) diff --git a/dump_things_service/utils.py b/dump_things_service/utils.py index 331623e..03a21a1 100644 --- a/dump_things_service/utils.py +++ b/dump_things_service/utils.py @@ -648,8 +648,8 @@ def dict_to_base_model( configuration.collections[collection_name].schema_location )[0] with wrap_http_exception( - ValidationError, - status_code=HTTP_422_UNPROCESSABLE_CONTENT, - header='Validation error', + ValidationError, + status_code=HTTP_422_UNPROCESSABLE_CONTENT, + header='Validation error', ): return TypeAdapter(getattr(model, class_name)).validate_python(data) -- 2.54.1 From af84bdcb2dfb75331ffa75c2c8ef78a52e2f9d74 Mon Sep 17 00:00:00 2001 From: Christian Monch Date: Wed, 7 Oct 2026 14:17:41 +0200 Subject: [PATCH 16/20] feat: allow collection names with `/` Endpoint declarations are changed to support `/` in collection names. Together with the removal of autogenerated methods, this allows collection names that contain `/`-characters. --- .../endpoints/v0/base_endpoints.py | 16 ++++++------- .../endpoints/v0/collection_endpoints.py | 10 ++++---- dump_things_service/endpoints/v0/curated.py | 14 +++++------ dump_things_service/endpoints/v0/incoming.py | 16 ++++++------- .../endpoints/v0/token_endpoints.py | 6 ++--- dump_things_service/endpoints/v0/validate.py | 2 +- .../tests/test_collection_administration.py | 24 +++++++------------ dump_things_service/utils.py | 12 ++++++++++ 8 files changed, 52 insertions(+), 48 deletions(-) diff --git a/dump_things_service/endpoints/v0/base_endpoints.py b/dump_things_service/endpoints/v0/base_endpoints.py index 3a97529..6815131 100644 --- a/dump_things_service/endpoints/v0/base_endpoints.py +++ b/dump_things_service/endpoints/v0/base_endpoints.py @@ -128,7 +128,7 @@ async def server() -> ServerResponse: @router.get( - '/management/reload/policy_info/{collection}', + '/management/reload/policy_info/{collection:path}', tags=['Server management'], name='reload policy information from configured location ', ) @@ -215,7 +215,7 @@ async def maintenance( @router.post( - '/{collection}/record/{class_name}', + '/{collection:path}/record/{class_name}', tags=['Store records'], name='Write record of class {class_name} to collection {collection}', openapi_extra={ @@ -346,7 +346,7 @@ async def store_record( @router.get( - '/{collection}/record', + '/{collection:path}/record', tags=['Read records'], name='Read the record with the given PID from the given collection', ) @@ -434,7 +434,7 @@ def _get_policy_information( @router.get( - '/{collection}/records/', + '/{collection:path}/records/', tags=['Read records'], name='Read all records from the given collection', ) @@ -457,7 +457,7 @@ async def read_all_records( @router.get( - '/{collection}/records/p/', + '/{collection:path}/records/p/', tags=['Read records'], name='Read all records from the given collection with pagination', ) @@ -478,7 +478,7 @@ async def read_all_records_paginated( @router.get( - '/{collection}/records/{class_name}', + '/{collection:path}/records/{class_name}', tags=['Read records'], name='Read records of the given class (or subclass) from the given collection', ) @@ -503,7 +503,7 @@ async def read_records_of_type( @router.get( - '/{collection}/records/p/{class_name}', + '/{collection:path}/records/p/{class_name}', tags=['Read records'], name='Read records of the given class (or subclass) from the given collection with pagination', ) @@ -682,7 +682,7 @@ async def _read_records_of_type( @router.delete( - '/{collection}/record', + '/{collection:path}/record', tags=['Delete records'], name='Delete record with the given pid from the given collection', ) diff --git a/dump_things_service/endpoints/v0/collection_endpoints.py b/dump_things_service/endpoints/v0/collection_endpoints.py index 8445dcc..6175995 100644 --- a/dump_things_service/endpoints/v0/collection_endpoints.py +++ b/dump_things_service/endpoints/v0/collection_endpoints.py @@ -4,7 +4,7 @@ from pathlib import ( PurePosixPath, ) from typing import Annotated, Literal -from urllib.parse import quote +from urllib.parse import quote_plus from fastapi import ( APIRouter, @@ -75,7 +75,7 @@ async def create_collection( ): with wrap_http_exception(DumpThingsError): await create_or_replace_collection(body, api_key, allow_replace=False) - response.headers['Location'] = f'/collections/{quote(body.name)}' + response.headers['Location'] = f'/collections/{quote_plus(body.name)}' @router.put( @@ -91,7 +91,7 @@ async def replace_collection( ): with wrap_http_exception(DumpThingsError): await create_or_replace_collection(body, api_key, allow_replace=True) - response.headers['Location'] = f'/collections/{quote(body.name)}' + response.headers['Location'] = f'/collections/{quote_plus(body.name)}' async def create_or_replace_collection( @@ -189,7 +189,7 @@ async def get_collections( @router.get( - '/collections/{collection_name}', + '/collections/{collection_name:path}', tags=['Administration interface'], name='Get existing collection by name', ) @@ -212,7 +212,7 @@ async def get_collection_with_name( @router.delete( - '/collections/{collection_name}', + '/collections/{collection_name:path}', tags=['Administration interface'], name='Delete collection with name', ) diff --git a/dump_things_service/endpoints/v0/curated.py b/dump_things_service/endpoints/v0/curated.py index 1855a62..41a3a22 100644 --- a/dump_things_service/endpoints/v0/curated.py +++ b/dump_things_service/endpoints/v0/curated.py @@ -76,7 +76,7 @@ add_pagination(router) @router.get( - '/{collection}/curated/records/{class_name}', + '/{collection:path}/curated/records/{class_name}', tags=['Curated area: read records'], name='Read all records of the given class from the curated area', ) @@ -105,7 +105,7 @@ async def read_curated_records_of_type( @router.get( - '/{collection}/curated/records/p/{class_name}', + '/{collection:path}/curated/records/p/{class_name}', tags=['Curated area: read records'], name='Read all records of the given class from the curated area with pagination', ) @@ -134,7 +134,7 @@ async def read_curated_records_of_type_paginated( @router.get( - '/{collection}/curated/records/', + '/{collection:path}/curated/records/', tags=['Curated area: read records'], name='Read all records from the curated area', ) @@ -154,7 +154,7 @@ async def read_curated_all_records( @router.get( - '/{collection}/curated/records/p/', + '/{collection:path}/curated/records/p/', tags=['Curated area: read records'], name='Read all records from the curated area with pagination', ) @@ -175,7 +175,7 @@ async def read_curated_all_records_paginated( @router.get( - '/{collection}/curated/record', + '/{collection:path}/curated/record', tags=['Curated area: read records'], name='Read the record with the given pid from the curated area', ) @@ -193,7 +193,7 @@ async def read_curated_record_with_pid( @router.delete( - '/{collection}/curated/record', + '/{collection:path}/curated/record', tags=['Curated area: delete records'], name='Delete the record with the given pid from the curated area of the given collection', ) @@ -302,7 +302,7 @@ def _get_store_and_backend( @router.post( - '/{collection}/curated/record/{class_name}', + '/{collection:path}/curated/record/{class_name}', tags=['Store record in curated area'], name='Curated area: store record of class {class_name} in curated area of collection {collection}', openapi_extra={ diff --git a/dump_things_service/endpoints/v0/incoming.py b/dump_things_service/endpoints/v0/incoming.py index 2ab0f2e..26f9d0d 100644 --- a/dump_things_service/endpoints/v0/incoming.py +++ b/dump_things_service/endpoints/v0/incoming.py @@ -59,7 +59,7 @@ add_pagination(router) @router.get( - '/{collection}/incoming/', + '/{collection:path}/incoming/', tags=['Incoming area: read labels'], name='Get all incoming labels for the given collection', ) @@ -79,7 +79,7 @@ async def incoming_read_labels( @router.get( - '/{collection}/incoming/{label}/records/{class_name}', + '/{collection:path}/incoming/{label}/records/{class_name}', tags=['Incoming area: read records'], name='Read all records of the given class from the given incoming area', ) @@ -105,7 +105,7 @@ async def incoming_read_records_of_type( @router.get( - '/{collection}/incoming/{label}/records/p/{class_name}', + '/{collection:path}/incoming/{label}/records/p/{class_name}', tags=['Incoming area: read records'], name='Read all records of the given class from the given incoming area with pagination', ) @@ -145,7 +145,7 @@ def _check_collection_and_class( @router.get( - '/{collection}/incoming/{label}/records/', + '/{collection:path}/incoming/{label}/records/', tags=['Incoming area: read records'], name='Read all records from the given incoming area', ) @@ -167,7 +167,7 @@ async def incoming_read_all_records( @router.get( - '/{collection}/incoming/{label}/records/p/', + '/{collection:path}/incoming/{label}/records/p/', tags=['Incoming area: read records'], name='Read all records from the given incoming area with pagination', ) @@ -190,7 +190,7 @@ async def incoming_read_all_records_paginated( @router.get( - '/{collection}/incoming/{label}/record', + '/{collection:path}/incoming/{label}/record', tags=['Incoming area: read records'], name='Read the record with the given PID from the given incoming area', ) @@ -210,7 +210,7 @@ async def incoming_read_record_with_pid( @router.delete( - '/{collection}/incoming/{label}/record', + '/{collection:path}/incoming/{label}/record', tags=['Incoming area: delete records'], name='Delete the record with the given PID from the given incoming area', ) @@ -360,7 +360,7 @@ async def authorize_zones( @router.post( - '/{collection}/incoming/{label}/record/{class_name}', + '/{collection:path}/incoming/{label}/record/{class_name}', tags=['Store record in an incoming area'], name='Incoming area: store a record of class {class_name} in incoming area {label} of collection {collection_name}', openapi_extra={ diff --git a/dump_things_service/endpoints/v0/token_endpoints.py b/dump_things_service/endpoints/v0/token_endpoints.py index 79d362b..0f8852d 100644 --- a/dump_things_service/endpoints/v0/token_endpoints.py +++ b/dump_things_service/endpoints/v0/token_endpoints.py @@ -2,7 +2,7 @@ import logging import re import secrets from typing import Annotated -from urllib.parse import quote +from urllib.parse import quote_plus from fastapi import ( APIRouter, @@ -75,7 +75,7 @@ async def create_token( api_key: Annotated[str, Depends(api_key_header_scheme)], ) -> TokenRequest: token_request = create_or_replace_token(body, api_key, allow_replace=False) - response.headers['Location'] = f'/tokens/{quote(body.name)}' + response.headers['Location'] = f'/tokens/{quote_plus(body.name)}' return token_request @@ -91,7 +91,7 @@ async def replace_token( api_key: Annotated[str, Depends(api_key_header_scheme)], ) -> TokenRequest: token_request = create_or_replace_token(body, api_key, allow_replace=True) - response.headers['Location'] = f'/tokens/{quote(body.name)}' + response.headers['Location'] = f'/tokens/{quote_plus(body.name)}' return token_request diff --git a/dump_things_service/endpoints/v0/validate.py b/dump_things_service/endpoints/v0/validate.py index 0f5455a..ba9a813 100644 --- a/dump_things_service/endpoints/v0/validate.py +++ b/dump_things_service/endpoints/v0/validate.py @@ -39,7 +39,7 @@ router = APIRouter() @router.post( - '/{collection}/validate/record/{class_name}', + '/{collection:path}/validate/record/{class_name}', tags=['Validate records'], name='Validate record of class {class_name} for collection {collection}', openapi_extra={ diff --git a/dump_things_service/tests/test_collection_administration.py b/dump_things_service/tests/test_collection_administration.py index 151afd3..985a967 100644 --- a/dump_things_service/tests/test_collection_administration.py +++ b/dump_things_service/tests/test_collection_administration.py @@ -2,8 +2,7 @@ from pathlib import ( Path, PurePosixPath, ) - -from starlette.testclient import TestClient +from urllib.parse import quote_plus from dump_things_service import ( HTTP_200_OK, @@ -32,7 +31,8 @@ incoming = 'admin_test_incoming' # Path to a local simple test schema test_schema_location = str((Path(__file__).parent / 'testschema.yaml').absolute()) -new_collection_name = 'admin_test_collection' +new_collection_name = 'admin@example.com/base/test_collection' + new_token_name = 'admin_test_token' new_token_representation = 'admin_test_token' new_collection_request = CollectionRequest( @@ -64,15 +64,6 @@ new_admin_token_request = AdminTokenRequest( ) -def _name_in_openapi_paths( - test_client: TestClient, - name: str, -) -> bool: - response = test_client.get('/openapi.json') - open_api = response.json() - return any(name in path for path in open_api['paths']) - - def test_collection_adding(fastapi_client_simple): test_client, _, admin_token = fastapi_client_simple @@ -179,7 +170,8 @@ def test_collection_adding(fastapi_client_simple): def test_collection_putting(fastapi_client_simple, tmp_path): test_client, _, admin_token = fastapi_client_simple - put_collection_name = 'test_put_collection' + put_collection_name = 'admin@example.com/base/test_put_collection' + url_encoded_put_collection_name = quote_plus(put_collection_name) put_collection_request_orig = CollectionRequest( name=put_collection_name, default_token='test_default_token', @@ -204,7 +196,7 @@ def test_collection_putting(fastapi_client_simple, tmp_path): # Check that the collection does not yet exist response = test_client.get( - f'/collections/{put_collection_name}', + f'/collections/{url_encoded_put_collection_name}', headers={'x-dumpthings-token': admin_token}, ) assert response.status_code == HTTP_404_NOT_FOUND @@ -221,7 +213,7 @@ def test_collection_putting(fastapi_client_simple, tmp_path): assert len(audit_files) == 0 response = test_client.get( - f'/collections/{put_collection_name}', + f'/collections/{url_encoded_put_collection_name}', headers={'x-dumpthings-token': admin_token}, ) assert response.status_code == HTTP_200_OK @@ -241,7 +233,7 @@ def test_collection_putting(fastapi_client_simple, tmp_path): # Delete the collection again because we check for a known number of # collections in other tests. response = test_client.delete( - f'/collections/{put_collection_name}', + f'/collections/{url_encoded_put_collection_name}', headers={'x-dumpthings-token': admin_token}, ) assert response.status_code == HTTP_200_OK diff --git a/dump_things_service/utils.py b/dump_things_service/utils.py index 03a21a1..03d00c7 100644 --- a/dump_things_service/utils.py +++ b/dump_things_service/utils.py @@ -246,6 +246,18 @@ def get_default_token_auth_info( collection_name: str, token_name: str, ) -> AuthenticationInfo: + + # Because collections and tokens can be created in two separate steps, we + # allow a collection to refer to a default token that does not yet exist. + # In this case, we return an error message that the default token for + # the collection does not exist. + if token_name not in abstract_config.tokens: + detail = f"Default token not valid for collection '{collection_name}' (configured token does not exist)." + raise HTTPException( + status_code=HTTP_401_UNAUTHORIZED, + detail=detail, + ) + token_config = abstract_config.tokens[token_name] token_collection_config = token_config.collections.get(collection_name) if token_collection_config is None: -- 2.54.1 From 34f326867346b70b0dfe6af46bbbcbaa311af81f Mon Sep 17 00:00:00 2001 From: Christian Monch Date: Wed, 7 Oct 2026 14:46:55 +0200 Subject: [PATCH 17/20] tests: add tests for collection names with `/` --- dump_things_service/tests/common.py | 6 +++++ dump_things_service/tests/fixtures.py | 27 +++++++++++++++---- dump_things_service/tests/test_basic.py | 9 ++++--- .../tests/test_collection_administration.py | 2 +- 4 files changed, 34 insertions(+), 10 deletions(-) create mode 100644 dump_things_service/tests/common.py diff --git a/dump_things_service/tests/common.py b/dump_things_service/tests/common.py new file mode 100644 index 0000000..f4a18e0 --- /dev/null +++ b/dump_things_service/tests/common.py @@ -0,0 +1,6 @@ + +def get_std_collection_names() -> list[str]: + return [ + f'collection_{i}' + for i in range(1, 9) + ] + ['collection/with/slash/0'] diff --git a/dump_things_service/tests/fixtures.py b/dump_things_service/tests/fixtures.py index 5254aef..f30a89f 100644 --- a/dump_things_service/tests/fixtures.py +++ b/dump_things_service/tests/fixtures.py @@ -31,6 +31,7 @@ from dump_things_service.endpoints.v0.token_endpoints import TokenRequest from dump_things_service.instance_state import get_mapping_function_by_name from dump_things_service.model import get_model_for_schema from dump_things_service.resolve_curie import resolve_curie +from dump_things_service.tests.common import get_std_collection_names from dump_things_service.tests.create_store import ( pid, pid_curated, @@ -103,6 +104,15 @@ g_default_collections.append( ) ) +g_default_collections.append( + CollectionRequest( + name='collection/with/slash/0', + default_token='test_default_token', + curated=PurePosixPath(f'{curated}/collection_with_slash_0'), + schema=test_schema_location, + incoming=PurePosixPath(f'{incoming}/collection_with_slash_0'), + ), +) g_default_collections.extend( [ @@ -154,6 +164,11 @@ g_default_tokens = [ ) for i in range(1, 3) }, + **{ + 'collection/with/slash/0': TokenCollectionConfig( + mode=TokenModes.READ_CURATED, + ) + } }, ), TokenRequest( @@ -228,11 +243,11 @@ g_default_tokens = [ representation='token-all', collections={ **{ - f'collection_{i}': TokenCollectionConfig( + collection_name: TokenCollectionConfig( mode=TokenModes.WRITE_COLLECTION, incoming_label='token-all:user_all', ) - for i in range(1, 9) + for collection_name in get_std_collection_names() }, **{ f'collection_dlflatsocial-{i}': TokenCollectionConfig( @@ -374,10 +389,12 @@ g_default_tokens = [ ] g_default_entries = { - f'collection_{i}': [('Person', pid, test_record)] for i in range(1, 9) + collection_name: [('Person', pid, test_record)] + for collection_name in get_std_collection_names() } -for collection_id in range(1, 9): - g_default_entries[f'collection_{collection_id}'].extend( + +for collection_name in get_std_collection_names(): + g_default_entries[collection_name].extend( [ ('Person', pid_curated, test_record_curated), ( diff --git a/dump_things_service/tests/test_basic.py b/dump_things_service/tests/test_basic.py index d34f60c..99fcda1 100644 --- a/dump_things_service/tests/test_basic.py +++ b/dump_things_service/tests/test_basic.py @@ -1,3 +1,4 @@ +from .common import get_std_collection_names from .. import ( HTTP_200_OK, HTTP_400_BAD_REQUEST, @@ -35,9 +36,9 @@ unicode_record = { def test_search_by_pid(fastapi_client_simple): test_client, _, _ = fastapi_client_simple - for i in range(1, 9): + for collection_name in get_std_collection_names(): response = test_client.get( - f'/collection_{i}/record?pid={pid}', + f'/{collection_name}/record?pid={pid}', headers={'x-dumpthings-token': 'token-all'}, ) assert response.status_code == HTTP_200_OK @@ -393,11 +394,11 @@ def test_server(fastapi_client_simple): 'version': __version__, 'collections': [ { - 'name': f'collection_{i}', + 'name': collection_name, 'schema': str(schema_file), 'classes': test_schema_classes, } - for i in range(1, 9) + for collection_name in get_std_collection_names() ] + [ { diff --git a/dump_things_service/tests/test_collection_administration.py b/dump_things_service/tests/test_collection_administration.py index 985a967..302b68d 100644 --- a/dump_things_service/tests/test_collection_administration.py +++ b/dump_things_service/tests/test_collection_administration.py @@ -250,7 +250,7 @@ def test_collection_reading(fastapi_client_simple): assert response.status_code == HTTP_200_OK response_object = response.json() assert isinstance(response_object, list) - assert len(response_object) == 10 + assert len(response_object) == 11 def test_admin_token_management(fastapi_client_simple): -- 2.54.1 From 336d5857259d2eebf78d97fdd4d231c5c60f1cd9 Mon Sep 17 00:00:00 2001 From: Christian Monch Date: Wed, 7 Oct 2026 14:51:57 +0200 Subject: [PATCH 18/20] chore: format according to hatch fmt --- dump_things_service/tests/common.py | 6 +----- dump_things_service/tests/fixtures.py | 2 +- dump_things_service/utils.py | 1 - 3 files changed, 2 insertions(+), 7 deletions(-) diff --git a/dump_things_service/tests/common.py b/dump_things_service/tests/common.py index f4a18e0..c6f5e52 100644 --- a/dump_things_service/tests/common.py +++ b/dump_things_service/tests/common.py @@ -1,6 +1,2 @@ - def get_std_collection_names() -> list[str]: - return [ - f'collection_{i}' - for i in range(1, 9) - ] + ['collection/with/slash/0'] + return [f'collection_{i}' for i in range(1, 9)] + ['collection/with/slash/0'] diff --git a/dump_things_service/tests/fixtures.py b/dump_things_service/tests/fixtures.py index f30a89f..d0b2998 100644 --- a/dump_things_service/tests/fixtures.py +++ b/dump_things_service/tests/fixtures.py @@ -168,7 +168,7 @@ g_default_tokens = [ 'collection/with/slash/0': TokenCollectionConfig( mode=TokenModes.READ_CURATED, ) - } + }, }, ), TokenRequest( diff --git a/dump_things_service/utils.py b/dump_things_service/utils.py index 03d00c7..396126d 100644 --- a/dump_things_service/utils.py +++ b/dump_things_service/utils.py @@ -246,7 +246,6 @@ def get_default_token_auth_info( collection_name: str, token_name: str, ) -> AuthenticationInfo: - # Because collections and tokens can be created in two separate steps, we # allow a collection to refer to a default token that does not yet exist. # In this case, we return an error message that the default token for -- 2.54.1 From 4080370116ba4678160df5ca7fcf3763fc2f3b8c Mon Sep 17 00:00:00 2001 From: Christian Monch Date: Wed, 7 Oct 2026 15:24:23 +0200 Subject: [PATCH 19/20] tests: update backward compatibility test --- .../tests/test_backward_compatibility.py | 47 ++++++++++++++++++- 1 file changed, 46 insertions(+), 1 deletion(-) diff --git a/dump_things_service/tests/test_backward_compatibility.py b/dump_things_service/tests/test_backward_compatibility.py index 54571e3..77984c7 100644 --- a/dump_things_service/tests/test_backward_compatibility.py +++ b/dump_things_service/tests/test_backward_compatibility.py @@ -149,16 +149,61 @@ tokens: admin_tokens: {} """ +config_example_1 = """ +admin_tokens: {} +collections: + collection-2026: + audit_backends: [] + auth_sources: + - instance_id: cerebra + label_type: user + organization: collection-2026 + repository: null + team: collection-2026-participants + type: forgejo + url: https://example.com/api/v1 + - type: config + backend: + type: sqlite + curated: collection-2026/main/curated + default_token: noaccess + ignore_classes: [] + incoming: collection-2026/main/inboxes + schema: https://www.example.com/s/things/v2.yaml + submission_tags: + submission_time_tag: http://semanticscience.org/resource/SIO_001083 + submitter_id_tag: http://purl.obolibrary.org/obo/NCIT_C54269 + use_classes: [] +tokens: + john_doe: + collections: + collection-2026: + incoming_label: john_doe + mode: CURATOR + hashed: false + representation: abcdefg + user_id: john_doe + noaccess: + collections: {} + hashed: false + representation: abcdefg + user_id: noaccess +type: collections +version: 2 +""" + + all_configurations = [ config_version_1, config_version_2_inlined_only_policy, config_version_2_external_only_policy, config_version_2_inlined_and_external_policy, + config_example_1, ] # Check that old configurations can be read by the current Configuration class -def test_config_backward_compatiblity(): +def test_config_backward_compatibility(): from dump_things_service.abstract_config import Configuration from dump_things_service.commands.upload_config import convert_config_1_to_config_2 -- 2.54.1 From 8b06594a0fa1499a58e6a774f73e44ffffd08e4a Mon Sep 17 00:00:00 2001 From: Christian Monch Date: Wed, 7 Oct 2026 15:34:13 +0200 Subject: [PATCH 20/20] chore: update changelog --- CHANGELOG.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index caf4903..38531ec 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,15 @@ +# 6.6.2 (2026-10-07) + +## New features + +- Support generic store-endpoints and do not auto-generate endpoints. As a + result the swagger documentation is shorter and independent of the number + of collections or schemas. Due to the new structure, the classes that can + be stored are no longer represented in the swagger documentation. + +- Support collection names that contain '/'. + + # 6.6.1 (2026-10-06) ## Changes -- 2.54.1