From 485841def282cc743d60a1c796e67f40ae9183d7 Mon Sep 17 00:00:00 2001 From: Christian Monch Date: Thu, 8 Oct 2026 15:19:17 +0200 Subject: [PATCH 01/15] fix: handle configuration errors gracefully This commit fixes an issue where a faulty configuration that is submitted via the dynamic configuration endpoint bring the server down. --- dump_things_service/endpoints/v0/curated.py | 2 +- dump_things_service/manifest.py | 39 ++++++++++++-- dump_things_service/tests/test_config.py | 31 +++++++++++ .../tests/test_token_endpoints.py | 53 +++++++++++++++++-- 4 files changed, 116 insertions(+), 9 deletions(-) diff --git a/dump_things_service/endpoints/v0/curated.py b/dump_things_service/endpoints/v0/curated.py index 41a3a22..5e2e224 100644 --- a/dump_things_service/endpoints/v0/curated.py +++ b/dump_things_service/endpoints/v0/curated.py @@ -290,7 +290,7 @@ def _get_store_and_backend( if permissions.curated_write is False: raise HTTPException( status_code=HTTP_403_FORBIDDEN, - detail=f'no write access to curated area of collection `{collection}`', + detail=f'no curator-privilege access to collection `{collection}`', ) # Get the curated model store diff --git a/dump_things_service/manifest.py b/dump_things_service/manifest.py index 2b80737..8698404 100644 --- a/dump_things_service/manifest.py +++ b/dump_things_service/manifest.py @@ -8,6 +8,7 @@ from dump_things_service.abstract_config import ( TokenConfig, ) from dump_things_service.collection import create_collection +from dump_things_service.exceptions import ConfigError from dump_things_service.instance_state import InstanceState logger = logging.getLogger('dump_things_service') @@ -117,12 +118,26 @@ def manifest_configuration( # Create the internal representation objects for collections that have been # added to the configuration. + faulty_collections = set() + collection_errors = {} for collection_name in new_collection_names: - create_collection( - instance_state, - configuration, - collection_name, - ) + try: + create_collection( + instance_state, + configuration, + collection_name, + ) + # There are many possible errors that can occur when creating a + # collection. We catch all of them here and log them. + # The collection will be excluded from the list. + except Exception as e: + logger.error( + f'Error creating collection "{collection_name}" from configuration: {e}', + ) + faulty_collections.add(collection_name) + collection_errors[collection_name] = e + + new_collection_names -= faulty_collections # Delete all token objects and recreate the tokens. This ensures that # modified token scope and permissions are set for all tokens. @@ -154,6 +169,20 @@ def manifest_configuration( # Incoming areas are therefore created when a write request for a token # is authorized. + # If any collection could not be instantiated, we raise an error to + # indicate that the configuration is not fully valid. + if faulty_collections: + for collection in faulty_collections: + logger.info('removing fault-inducing configuration for collection "%s"', collection) + configuration.collections.pop(collection, None) + msg = ( + f'Collection creation errors occured:\n' + + '\n'.join( + f'"{collection_name}": {error}' + for collection_name, error in collection_errors.items() + ) + ) + raise ConfigError(msg) def create_token( instance_state: InstanceState, diff --git a/dump_things_service/tests/test_config.py b/dump_things_service/tests/test_config.py index 58c4410..910cfc0 100644 --- a/dump_things_service/tests/test_config.py +++ b/dump_things_service/tests/test_config.py @@ -6,6 +6,8 @@ from pathlib import ( import pytest import yaml +from starlette.status import HTTP_400_BAD_REQUEST, \ + HTTP_422_UNPROCESSABLE_CONTENT from dump_things_service import ( HTTP_200_OK, @@ -245,3 +247,32 @@ def test_config_structure(): with open(reference_config_file) as f: config_dict = yaml.safe_load(f) _ = Configuration(**config_dict) + + +def test_schema_location_error_detection(fastapi_client_simple): + test_client, _, admin_token = fastapi_client_simple + + faulty_schema_collection = CollectionRequest( + name='test_faulty_schema', + schema='http://example.com/does-not-exist', + default_token='test_default_token', + curated=PurePosixPath('curate_dir'), + incoming=PurePosixPath('incoming_dir'), + ) + response = test_client.post( + '/collections', + json=faulty_schema_collection.model_dump(mode='json', by_alias=True), + headers={'x-dumpthings-token': admin_token}, + ) + assert response.status_code == HTTP_400_BAD_REQUEST + + +def test_config_structure_error_detection(fastapi_client_simple): + test_client, _, admin_token = fastapi_client_simple + + response = test_client.post( + '/collections', + json={'some_crazy': 'content'}, + headers={'x-dumpthings-token': admin_token}, + ) + assert response.status_code == HTTP_422_UNPROCESSABLE_CONTENT diff --git a/dump_things_service/tests/test_token_endpoints.py b/dump_things_service/tests/test_token_endpoints.py index fd66941..e731a73 100644 --- a/dump_things_service/tests/test_token_endpoints.py +++ b/dump_things_service/tests/test_token_endpoints.py @@ -1,6 +1,11 @@ -from starlette.status import HTTP_406_NOT_ACCEPTABLE, HTTP_409_CONFLICT -from dump_things_service import HTTP_201_CREATED +from dump_things_service import ( + HTTP_201_CREATED, + HTTP_404_NOT_FOUND, + HTTP_406_NOT_ACCEPTABLE, + HTTP_409_CONFLICT, + HTTP_422_UNPROCESSABLE_CONTENT, +) def test_token_creation(fastapi_client_simple): @@ -21,7 +26,7 @@ def test_token_creation(fastapi_client_simple): headers={'x-dumpthings-token': admin_token}, json=json_record, ) - assert response.status_code == HTTP_201_CREATED + assert response.status_code == HTTP_201_CREATED, response.text # Try to create another token with name 'a', should result in a 4ß9-error response = test_client.post( @@ -51,3 +56,45 @@ def test_default_token_removal(fastapi_client_simple): headers={'x-dumpthings-token': admin_token}, ) assert response.status_code == HTTP_406_NOT_ACCEPTABLE + + +def test_token_mode_error_detection(fastapi_client_simple): + test_client, _, admin_token = fastapi_client_simple + + json_record = { + 'name': 'a/b/c', + 'user_id': 'u_a', + 'representation': '8bb6805ff10bcb1c2ca49dcd4bfef94d', + 'collections': { + 'collection_1': {'mode': 'ABC', 'incoming_label': 'i_a'}, + }, + } + + # Create a token with name 'a' + response = test_client.post( + '/tokens', + headers={'x-dumpthings-token': admin_token}, + json=json_record, + ) + assert response.status_code == HTTP_422_UNPROCESSABLE_CONTENT + + +def test_unknown_collection_error_detection(fastapi_client_simple): + test_client, _, admin_token = fastapi_client_simple + + json_record = { + 'name': 'a/b/c', + 'user_id': 'u_a', + 'representation': '8bb6805ff10bcb1c2ca49dcd4bfef94d', + 'collections': { + 'collection_abc': {'mode': 'READ_CURATED', 'incoming_label': 'i_a'}, + }, + } + + # Create a token with name 'a' + response = test_client.post( + '/tokens', + headers={'x-dumpthings-token': admin_token}, + json=json_record, + ) + assert response.status_code == HTTP_404_NOT_FOUND -- 2.54.1 From d832df1cd88695c06fc2af36909c70c6188b4fe2 Mon Sep 17 00:00:00 2001 From: Christian Monch Date: Thu, 8 Oct 2026 15:24:44 +0200 Subject: [PATCH 02/15] chore: update changelog --- CHANGELOG.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 527c5a9..eaec2df 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,16 @@ +# 6.6.5 (2026-xx-xx) + +# Bugfixes + +- Fixes an issue where a faulty configuration that is submitted via the + dynamic configuration endpoint would bring down the server. + +# Changes + +- Check that `incoming` and `curated`-paths of different collections + do not share the same directory tree. + + # 6.6.4 (2026-10-17) ## Security -- 2.54.1 From 5181901fb97ef327308a5510d034441019f18c5a Mon Sep 17 00:00:00 2001 From: Christian Monch Date: Thu, 8 Oct 2026 15:54:27 +0200 Subject: [PATCH 03/15] tests: add test for faulty policy location detection --- dump_things_service/tests/test_config.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/dump_things_service/tests/test_config.py b/dump_things_service/tests/test_config.py index 910cfc0..10058eb 100644 --- a/dump_things_service/tests/test_config.py +++ b/dump_things_service/tests/test_config.py @@ -267,6 +267,25 @@ def test_schema_location_error_detection(fastapi_client_simple): assert response.status_code == HTTP_400_BAD_REQUEST +def test_policy_location_error_detection(fastapi_client_simple): + test_client, _, admin_token = fastapi_client_simple + + faulty_schema_collection = CollectionRequest( + name='test_faulty_schema', + schema=str(schema_file), + policy_info_location='http://example.com/does-not-exist', + default_token='test_default_token', + curated=PurePosixPath('curate_dir'), + incoming=PurePosixPath('incoming_dir'), + ) + response = test_client.post( + '/collections', + json=faulty_schema_collection.model_dump(mode='json', by_alias=True), + headers={'x-dumpthings-token': admin_token}, + ) + assert response.status_code == HTTP_400_BAD_REQUEST + + def test_config_structure_error_detection(fastapi_client_simple): test_client, _, admin_token = fastapi_client_simple -- 2.54.1 From be7285188e95ec6f6d111a2f59f2c6c7615391a9 Mon Sep 17 00:00:00 2001 From: Christian Monch Date: Thu, 8 Oct 2026 17:47:05 +0200 Subject: [PATCH 04/15] refactor: remove unnecessary FastAPI re-initialization Since the dynamically generated endpoints are gone, there is no more need to re-initialize FastAPI. --- dump_things_service/main.py | 5 ----- dump_things_service/manifest.py | 9 --------- 2 files changed, 14 deletions(-) diff --git a/dump_things_service/main.py b/dump_things_service/main.py index bf41dbe..25ca2d6 100644 --- a/dump_things_service/main.py +++ b/dump_things_service/main.py @@ -279,11 +279,6 @@ manifest_configuration( ) -g_instance_state.fastapi_app.openapi_schema = None -g_instance_state.fastapi_app.setup() -add_pagination(g_instance_state.fastapi_app) - - def main(): uvicorn.run( app, diff --git a/dump_things_service/manifest.py b/dump_things_service/manifest.py index 8698404..7f72a9e 100644 --- a/dump_things_service/manifest.py +++ b/dump_things_service/manifest.py @@ -151,15 +151,6 @@ def manifest_configuration( token_configuration, ) - if new_collection_names or deleted_collection_names: - instance_state.fastapi_app.openapi_schema = None - instance_state.fastapi_app.openapi_tags = create_openapi_tags( - instance_state, - openapi_tags_template, - ) - instance_state.fastapi_app.setup() - add_pagination(instance_state.fastapi_app) - # We do not create any incoming areas for configuration-file tokens # here. The reason is that the configuration does not fully determine # the possible incoming areas because incoming areas come from -- 2.54.1 From e9a111a2be78588210c23113dd053afb3fecc037 Mon Sep 17 00:00:00 2001 From: Christian Monch Date: Thu, 8 Oct 2026 21:09:41 +0200 Subject: [PATCH 05/15] chore: improve comments and error messages --- dump_things_service/main.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/dump_things_service/main.py b/dump_things_service/main.py index 25ca2d6..2b516e2 100644 --- a/dump_things_service/main.py +++ b/dump_things_service/main.py @@ -11,7 +11,7 @@ from dump_things_service.commands.upload_config import convert_config_1_to_confi from dump_things_service.manifest import manifest_configuration # Perform the patching before importing any third-party libraries -from dump_things_service.patches import enabled # noqa: F401 -- used by generated code +from dump_things_service.patches import enabled # noqa: F401 -- side effects are required import yaml import uvicorn @@ -266,7 +266,8 @@ if ( ): print( # noqa T201 -- cli result output 'The server has an empty configuration and requires a bootstrap ' - 'token (use `--admin-token-hash` to provide one)', + 'token (use `--admin-token-hash` or the environment variable ' + '`DTS_ADMIN_TOKEN` to provide one).', file=sys.stderr, flush=True, ) -- 2.54.1 From 8a6abd11b8213ee14fc98c814f5af90b8180d668 Mon Sep 17 00:00:00 2001 From: Christian Monch Date: Fri, 16 Oct 2026 16:40:25 +0200 Subject: [PATCH 06/15] feat: ensure disjunct paths for collections Ensure that incoming-path and curated-path of different collections are disjunct. That means none of them is contained in any other path. Paths within the same collection, i.e., the incoming- and the curated-path don't have to be disjunct. This supports some old configurations. --- dump_things_service/abstract_config.py | 58 ++++++++++++++++++++++++ dump_things_service/tests/test_config.py | 54 +++++++++++++++++++++- 2 files changed, 111 insertions(+), 1 deletion(-) diff --git a/dump_things_service/abstract_config.py b/dump_things_service/abstract_config.py index 762cb88..6d5f57b 100644 --- a/dump_things_service/abstract_config.py +++ b/dump_things_service/abstract_config.py @@ -1,6 +1,7 @@ import enum import hashlib import logging +from collections import defaultdict from collections.abc import Callable, Iterable from functools import partial from pathlib import ( @@ -539,3 +540,60 @@ def get_policies_for_user( ) -> list[str]: collection_config = get_collection_config_by_name(abstract_config, collection_name) return collection_config.policy_mapping.get((auth_source_id, user_id), []) + + +def get_conflicting_paths( + abstract_config: Configuration, +) -> list[tuple[PurePosixPath, str, set[str], PurePosixPath, str, set[str]]]: + """Check that the incoming and curated areas of different collections + are disjunct subtrees.""" + + # Collect all paths. + all_paths = set() + usage_info = defaultdict(set) + for collection_name, collection_config in abstract_config.collections.items(): + # If incoming and curated paths are not disjunct, the containing path + # is added. + containing_path, _ = _get_containing_path( + collection_config.incoming, + collection_config.curated + ) + if containing_path: + all_paths.add((containing_path, collection_name)) + usage_info[containing_path].add(collection_name) + else: + all_paths.add((collection_config.incoming, collection_name)) + usage_info[collection_config.incoming].add(collection_name) + all_paths.add((collection_config.curated, collection_name)) + usage_info[collection_config.curated].add(collection_name) + + result = [] + while all_paths: + current_path, current_collection = all_paths.pop() + + for other_path, other_collection in all_paths: + containing_path, index = _get_containing_path(current_path, other_path) + if containing_path: + if index == 0: + result.append((current_path, current_collection, usage_info[current_path], other_path, other_collection, usage_info[other_path])) + else: + result.append((other_path, other_collection, usage_info[other_path], current_path, current_collection, usage_info[current_path])) + return result + + +def _get_containing_path( + path_0: PurePosixPath, + path_1: PurePosixPath, +) -> tuple[PurePosixPath | None, int | None]: + """Return the containing path if one of the paths is a subtree of the other.""" + + for container, contained, position in ( + (path_0, path_1, 0), + (path_1, path_0, 1), + ): + try: + contained.relative_to(container) + return container, position + except ValueError: + pass + return None, None diff --git a/dump_things_service/tests/test_config.py b/dump_things_service/tests/test_config.py index 10058eb..cf33585 100644 --- a/dump_things_service/tests/test_config.py +++ b/dump_things_service/tests/test_config.py @@ -22,7 +22,7 @@ from dump_things_service.abstract_config import ( dump_things_config_iri, dump_things_private_collection_name, get_config_backends, - read_config, + read_config, get_conflicting_paths, ) from dump_things_service.endpoints.v0.collection_endpoints import CollectionRequest from dump_things_service.endpoints.v0.token_endpoints import TokenRequest @@ -295,3 +295,55 @@ def test_config_structure_error_detection(fastapi_client_simple): headers={'x-dumpthings-token': admin_token}, ) assert response.status_code == HTTP_422_UNPROCESSABLE_CONTENT + + +def test_is_directory_configuration_valid(): + + setup_info = ( + ('c0.0', 'curated/c1', 'incoming/c1'), + ('c0.1', 'curated/c1/c2', 'incoming/c2'), + ('c0.2', 'curated', 'incoming'), + ('c0.3', 'curated_3', 'curated_3'), + ('c1.0', 'curated1', 'incoming1'), + ('c1.1', 'curated1/c1/c2', 'incoming1/c2'), + ('c1.2', 'curated1/c1/c2', 'incoming1/c3'), + ('c1.3', 'curated1', 'incoming_x'), + ('c2.0', 'curated1/c1/c2', 'curated1'), + ) + + abstract_config = Configuration( + type='collections', + version=2, + collections={ + collection_name: { + 'schema': '', + 'curated': PurePosixPath(curated), + 'incoming': PurePosixPath(incoming), + 'default_token': '', + } + for collection_name, curated, incoming in setup_info + } + ) + conflicts = get_conflicting_paths(abstract_config) + assert len(conflicts) == 17 + + setup_info = ( + ('c1', 'curated/c1', 'incoming/c1'), + ('c2', 'curated/c2', 'incoming/c2'), + ('c3', 'common', 'common'), + ) + + abstract_config = Configuration( + type='collections', + version=2, + collections={ + collection_name: { + 'schema': '', + 'curated': PurePosixPath(curated), + 'incoming': PurePosixPath(incoming), + 'default_token': '', + } + for collection_name, curated, incoming in setup_info + } + ) + assert not get_conflicting_paths(abstract_config) -- 2.54.1 From ced91342bc0fe5f9c952e4398f60e939bad7015a Mon Sep 17 00:00:00 2001 From: Christian Monch Date: Fri, 16 Oct 2026 22:39:11 +0200 Subject: [PATCH 07/15] feat: add directory test to configuration loading --- dump_things_service/abstract_config.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/dump_things_service/abstract_config.py b/dump_things_service/abstract_config.py index 6d5f57b..7f3779e 100644 --- a/dump_things_service/abstract_config.py +++ b/dump_things_service/abstract_config.py @@ -274,6 +274,16 @@ def read_config( msg = f'Faulty configuration at {config_backend.root}: {ve}' raise ConfigError(msg) from ve + path_conflicts = get_conflicting_paths(g_abstract_configuration) + if path_conflicts: + msg = ( + f'Incoming and curated paths of different collections are not disjunct:\n' + + '\n'.join( + f'path `{path_0}` from collection `{collection_0}` contains path `{path_1}` from collection `{collection_1}`' + for path_0, collection_0, usage_0, path_1, collection_1, usage_1 in path_conflicts + ) + ) + raise ConfigError(msg) return g_abstract_configuration -- 2.54.1 From f11fb786f11986739bc3a054fdf807df5736c96c Mon Sep 17 00:00:00 2001 From: Christian Monch Date: Tue, 3 Nov 2026 11:55:19 +0100 Subject: [PATCH 08/15] feat: catch config errors, fix openapi tag order --- dump_things_service/endpoints/v0/curated.py | 2 +- dump_things_service/endpoints/v0/incoming.py | 2 +- dump_things_service/main.py | 32 +++++++++++++++++--- dump_things_service/manifest.py | 6 +--- 4 files changed, 31 insertions(+), 11 deletions(-) diff --git a/dump_things_service/endpoints/v0/curated.py b/dump_things_service/endpoints/v0/curated.py index 5e2e224..cc973d3 100644 --- a/dump_things_service/endpoints/v0/curated.py +++ b/dump_things_service/endpoints/v0/curated.py @@ -303,7 +303,7 @@ def _get_store_and_backend( @router.post( '/{collection:path}/curated/record/{class_name}', - tags=['Store record in curated area'], + tags=['Curated area: store records'], name='Curated area: store record of class {class_name} in curated area of collection {collection}', openapi_extra={ 'requestBody': { diff --git a/dump_things_service/endpoints/v0/incoming.py b/dump_things_service/endpoints/v0/incoming.py index 26f9d0d..f7c24c6 100644 --- a/dump_things_service/endpoints/v0/incoming.py +++ b/dump_things_service/endpoints/v0/incoming.py @@ -361,7 +361,7 @@ async def authorize_zones( @router.post( '/{collection:path}/incoming/{label}/record/{class_name}', - tags=['Store record in an incoming area'], + tags=['Incoming area: store records'], name='Incoming area: store a record of class {class_name} in incoming area {label} of collection {collection_name}', openapi_extra={ 'requestBody': { diff --git a/dump_things_service/main.py b/dump_things_service/main.py index 2b516e2..28f5cb5 100644 --- a/dump_things_service/main.py +++ b/dump_things_service/main.py @@ -8,6 +8,7 @@ from pathlib import Path from dump_things_service.abstract_config import store_config from dump_things_service.commands.upload_config import convert_config_1_to_config_2 +from dump_things_service.exceptions import ConfigError from dump_things_service.manifest import manifest_configuration # Perform the patching before importing any third-party libraries @@ -159,10 +160,30 @@ if not store_path.exists(): disable_installed_extensions_check() +# Define the tag-order +openapi_tags = [ + {"name": 'default'}, + {"name": 'Read records'}, + {"name": 'Store records'}, + {"name": 'Validate records'}, + {"name": 'Delete records'}, + {"name": 'Curated area: read records'}, + {"name": 'Curated area: store records'}, + {"name": 'Curated area: delete records'}, + {"name": 'Incoming area: read records'}, + {"name": 'Incoming area: read labels'}, + {"name": 'Incoming area: store records'}, + {"name": 'Incoming area: delete records'}, + {"name": 'Server management'}, + {"name": 'Administration interface'}, +] + + app = FastAPI( title='Dump Things Service', description=description, version=__version__, + openapi_tags=openapi_tags, ) app.include_router(curated_router) @@ -274,10 +295,13 @@ if ( sys.exit(2) -manifest_configuration( - configuration=g_configuration, - instance_state=g_instance_state, -) +try: + manifest_configuration( + configuration=g_configuration, + instance_state=g_instance_state, + ) +except ConfigError as e: + logger.error("There were errors manifesting configuration: %s", e) def main(): diff --git a/dump_things_service/manifest.py b/dump_things_service/manifest.py index 7f72a9e..912c3dd 100644 --- a/dump_things_service/manifest.py +++ b/dump_things_service/manifest.py @@ -1,8 +1,6 @@ import logging from typing import cast -from fastapi_pagination import add_pagination - from dump_things_service.abstract_config import ( Configuration, TokenConfig, @@ -14,7 +12,6 @@ from dump_things_service.instance_state import InstanceState logger = logging.getLogger('dump_things_service') tag_groups = [ - 'write', 'validate', 'curated_write', 'incoming_write', @@ -29,7 +26,6 @@ openapi_tags_template: list[dict | str] = [ 'name': 'Read records', 'description': 'Read records from the given collection', }, - #'write', 'validate', { 'name': 'Delete records', @@ -169,7 +165,7 @@ def manifest_configuration( msg = ( f'Collection creation errors occured:\n' + '\n'.join( - f'"{collection_name}": {error}' + f'creating collection "{collection_name}" failed due to: {error}' for collection_name, error in collection_errors.items() ) ) -- 2.54.1 From 216bf7aa8c290ca2ea13e0d0431a9647f903e886 Mon Sep 17 00:00:00 2001 From: Christian Monch Date: Wed, 4 Nov 2026 08:56:48 +0100 Subject: [PATCH 09/15] feat: retry configurations with recoverable errors This commit adds periodically executed code that will try to manifest collection configurations that have recoverable errors. --- dump_things_service/abstract_config.py | 1 + dump_things_service/collection.py | 30 +++++++++++++++ .../endpoints/v0/base_endpoints.py | 6 ++- dump_things_service/exceptions.py | 4 ++ dump_things_service/main.py | 38 +++++++++++++++++++ dump_things_service/manifest.py | 25 ++++++++++-- dump_things_service/model.py | 8 +++- dump_things_service/periodic.py | 34 +++++++++++++++++ 8 files changed, 140 insertions(+), 6 deletions(-) create mode 100644 dump_things_service/periodic.py diff --git a/dump_things_service/abstract_config.py b/dump_things_service/abstract_config.py index 7f3779e..20ebc9f 100644 --- a/dump_things_service/abstract_config.py +++ b/dump_things_service/abstract_config.py @@ -37,6 +37,7 @@ from dump_things_service.exceptions import ConfigError logger = logging.getLogger('dump_things_service') g_abstract_configuration = None +g_recoverable_error = set() dump_things_config_iri = 'dump_things:config' dump_things_private_path = Path(dump_things_private_collection_name) diff --git a/dump_things_service/collection.py b/dump_things_service/collection.py index 1a38047..7858dae 100644 --- a/dump_things_service/collection.py +++ b/dump_things_service/collection.py @@ -2,6 +2,7 @@ import json import logging import os import shutil +from typing import Any import fsspec from pathlib import Path @@ -395,3 +396,32 @@ def reload_policy( instance_state.collections[ collection_name ].policy_annotation_tag = policy_annotation_tag + + +def refresh_collection_state( + a: int, +) -> tuple[tuple, dict] | None: + print('refresh_collection_state called with argument:', a) + if a % 100 >= 10: + return None + return (), dict(a=a+1) + + +def check_recoverable_errors( + abstract_configuration: Configuration, + instance_state: InstanceState, +): + from dump_things_service.abstract_config import g_recoverable_error + from dump_things_service.manifest import manifest_configuration + + if g_recoverable_error: + try: + manifest_configuration( + instance_state=instance_state, + configuration=abstract_configuration, + ) + except Exception as e: + logger.info( + f'Error recovery failed: {e}' + ) + return (abstract_configuration, instance_state), {} diff --git a/dump_things_service/endpoints/v0/base_endpoints.py b/dump_things_service/endpoints/v0/base_endpoints.py index 7ee5010..65963ca 100644 --- a/dump_things_service/endpoints/v0/base_endpoints.py +++ b/dump_things_service/endpoints/v0/base_endpoints.py @@ -7,7 +7,10 @@ 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.abstract_config import ( + get_config, + g_recoverable_error, +) from dump_things_service.collection import reload_policy from dump_things_service.instance_state import get_instance_state @@ -123,6 +126,7 @@ async def server() -> ServerResponse: ].classes, ) for collection_name in configuration.collections + if collection_name not in g_recoverable_error ], ) diff --git a/dump_things_service/exceptions.py b/dump_things_service/exceptions.py index c1a44b2..7ddd137 100644 --- a/dump_things_service/exceptions.py +++ b/dump_things_service/exceptions.py @@ -10,5 +10,9 @@ class ConfigCollisionError(ConfigError): pass +class RecoverableConfigError(ConfigError): + pass + + class CurieResolutionError(DumpThingsError): pass diff --git a/dump_things_service/main.py b/dump_things_service/main.py index 28f5cb5..84c1b0d 100644 --- a/dump_things_service/main.py +++ b/dump_things_service/main.py @@ -1,9 +1,11 @@ from __future__ import annotations # noqa: I001 -- the patches have to be imported early import argparse +import asyncio import logging import os import sys +from contextlib import asynccontextmanager from pathlib import Path from dump_things_service.abstract_config import store_config @@ -29,6 +31,7 @@ from dump_things_service.abstract_config import ( CONFIG_VERSION_1_ID, CONFIG_VERSION_2_ID, ) +from dump_things_service.collection import check_recoverable_errors 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 @@ -41,6 +44,10 @@ from dump_things_service.endpoints.v0.token_endpoints import ( ) from dump_things_service.endpoints.v0.validate import router as validate_router from dump_things_service.instance_state import create_instance_state, InstanceState +from dump_things_service.periodic import ( + add_task_to_queue, + periodic_worker, +) logging.basicConfig(level=logging.WARNING) @@ -89,6 +96,15 @@ parser.add_argument( '`/.dumpthings.yaml`. That means the configuration be empty ' 'collections and tokens are added via the API.', ) +parser.add_argument( + '--retry-interval', + type=int, + default=60, + help='Set the retry interval for recoverable errors in seconds. After the ' + 'retry interval, the server will try to manifest collections ' + 'configurations that have recoverable errors, e.g., failing URLs. ' + 'The default is 60 seconds.', +) parser.add_argument( 'store', help='The root of the data store, it should contain a global_store and token_stores.', @@ -179,11 +195,23 @@ openapi_tags = [ ] +@asynccontextmanager +async def lifespan(_app: FastAPI): + task = asyncio.create_action = asyncio.create_task(periodic_worker()) + yield + task.cancel() + try: + await task + except asyncio.CancelledError: + pass + + app = FastAPI( title='Dump Things Service', description=description, version=__version__, openapi_tags=openapi_tags, + lifespan=lifespan, ) app.include_router(curated_router) @@ -304,6 +332,16 @@ except ConfigError as e: logger.error("There were errors manifesting configuration: %s", e) +# Add a periodic task that tries to recover from recoverable errors in the +# configuration by re-manifesting the configuration. +add_task_to_queue( + interval=arguments.retry_interval, + callable_=check_recoverable_errors, + abstract_configuration=g_configuration, + instance_state=g_instance_state, +) + + def main(): uvicorn.run( app, diff --git a/dump_things_service/manifest.py b/dump_things_service/manifest.py index 912c3dd..dfaec6a 100644 --- a/dump_things_service/manifest.py +++ b/dump_things_service/manifest.py @@ -3,10 +3,13 @@ from typing import cast from dump_things_service.abstract_config import ( Configuration, - TokenConfig, + TokenConfig, g_recoverable_error, ) from dump_things_service.collection import create_collection -from dump_things_service.exceptions import ConfigError +from dump_things_service.exceptions import ( + ConfigError, + RecoverableConfigError, +) from dump_things_service.instance_state import InstanceState logger = logging.getLogger('dump_things_service') @@ -99,6 +102,8 @@ def manifest_configuration( is that a "default-token unknown" error might be created when accessing a collection. """ + from dump_things_service.abstract_config import g_recoverable_error + global g_recoverable_error # Determine the changes in collections. existing_collections = set(instance_state.collections) @@ -123,10 +128,21 @@ def manifest_configuration( configuration, collection_name, ) + g_recoverable_error -= {collection_name} + # There are many possible errors that can occur when creating a - # collection. We catch all of them here and log them. - # The collection will be excluded from the list. + # collection. Some might be recoverable, e.g., HTTP 404 errors. + # Configurations that create recoverable errors will be retried + # regularly. + except RecoverableConfigError as e: + logger.info( + f'Recoverable error creating collection "{collection_name}" from configuration: {e.__cause__}', + ) + g_recoverable_error.add(collection_name) + except Exception as e: + # We catch all remaining errors here and log them. The collection will + # be excluded from the list. logger.error( f'Error creating collection "{collection_name}" from configuration: {e}', ) @@ -171,6 +187,7 @@ def manifest_configuration( ) raise ConfigError(msg) + def create_token( instance_state: InstanceState, token_name: str, diff --git a/dump_things_service/model.py b/dump_things_service/model.py index 498f3b4..3adf2f2 100644 --- a/dump_things_service/model.py +++ b/dump_things_service/model.py @@ -9,6 +9,7 @@ from typing import ( TYPE_CHECKING, Any, ) +from urllib.error import HTTPError, URLError from urllib.parse import urlparse import annotated_types # noqa: F401 -- used by generated code @@ -23,6 +24,7 @@ from pydantic._internal._model_construction import ModelMetaclass # Ensure linkml is patched import dump_things_service.patches.enabled # noqa: F401 -- apply patches +from dump_things_service.exceptions import RecoverableConfigError if TYPE_CHECKING: from types import ModuleType @@ -139,4 +141,8 @@ def get_schema_model_for_schema( schema_location: str, ) -> ModuleType: lgr.info(f'Building python module for schema {schema_location}') - return PythonGenerator(schema_location).compile_module() + try: + return PythonGenerator(schema_location).compile_module() + except (HTTPError, URLError) as e: + # Enable retry on HTTPErrors + raise RecoverableConfigError from e diff --git a/dump_things_service/periodic.py b/dump_things_service/periodic.py new file mode 100644 index 0000000..8b2f866 --- /dev/null +++ b/dump_things_service/periodic.py @@ -0,0 +1,34 @@ +import asyncio +from collections import deque +from typing import Callable + + +g_task_list = [] + + +async def periodic_worker(): + global g_task_list + + while True: + g_task_list = [ + (max(counter - 1, 0), interval, callable_, args, kwargs) + for counter, interval, callable_, args, kwargs in g_task_list + ] + while g_task_list and g_task_list[0][0] <= 0: + task = g_task_list.pop(0) + _, interval, callable_, args, kwargs = task + next_round = callable_(*args, **kwargs) + if next_round: + args, kwargs = next_round + add_task_to_queue(interval, callable_, *args, **kwargs) + await asyncio.sleep(1) + + +def add_task_to_queue( + interval: int, + callable_: Callable, + *args, + **kwargs, +): + g_task_list.append((interval, interval, callable_, args, kwargs)) + g_task_list.sort(key=lambda x: x[0]) -- 2.54.1 From bef156af1bc0c1b1fe7bc29a6ac18c3fe42c8b54 Mon Sep 17 00:00:00 2001 From: Christian Monch Date: Wed, 4 Nov 2026 09:08:43 +0100 Subject: [PATCH 10/15] chore: update changelog --- CHANGELOG.md | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index eaec2df..8d95de8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,16 +1,28 @@ -# 6.6.5 (2026-xx-xx) +# 6.7.0 (2026-xx-xx) -# Bugfixes +## New features + +- Define recoverable errors for collection configurations. Recoverable errors + are errors that can be fixed by retrying the configuration. For example, if + a collection configuration contains a URL that is not reachable, this will + be considered a recoverable error. The server will retry to manifest the + collection configuration after a defined interval (default: 60 seconds). + +- Add the command line option `--retry-interval` to set the retry interval for + recoverable errors in seconds. After the retry interval, the server will try + to manifest collection configurations that have recoverable errors. + +## Bugfixes - Fixes an issue where a faulty configuration that is submitted via the dynamic configuration endpoint would bring down the server. -# Changes +## Changes - Check that `incoming` and `curated`-paths of different collections do not share the same directory tree. - + # 6.6.4 (2026-10-17) ## Security -- 2.54.1 From 64186e99c6ca89b289469496df24d1e90392527e Mon Sep 17 00:00:00 2001 From: Christian Monch Date: Wed, 4 Nov 2026 09:33:53 +0100 Subject: [PATCH 11/15] typo: fix typo --- dump_things_service/collection.py | 1 - dump_things_service/manifest.py | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/dump_things_service/collection.py b/dump_things_service/collection.py index 7858dae..eff4f5a 100644 --- a/dump_things_service/collection.py +++ b/dump_things_service/collection.py @@ -2,7 +2,6 @@ import json import logging import os import shutil -from typing import Any import fsspec from pathlib import Path diff --git a/dump_things_service/manifest.py b/dump_things_service/manifest.py index dfaec6a..37ef7a6 100644 --- a/dump_things_service/manifest.py +++ b/dump_things_service/manifest.py @@ -179,7 +179,7 @@ def manifest_configuration( logger.info('removing fault-inducing configuration for collection "%s"', collection) configuration.collections.pop(collection, None) msg = ( - f'Collection creation errors occured:\n' + f'Collection creation errors occurred:\n' + '\n'.join( f'creating collection "{collection_name}" failed due to: {error}' for collection_name, error in collection_errors.items() -- 2.54.1 From fe844c9db75ec2f14c09ef732b9034f02390f1fe Mon Sep 17 00:00:00 2001 From: Christian Monch Date: Wed, 4 Nov 2026 10:05:12 +0100 Subject: [PATCH 12/15] chore: fix linting errors --- dump_things_service/abstract_config.py | 2 +- dump_things_service/manifest.py | 2 +- dump_things_service/periodic.py | 1 - 3 files changed, 2 insertions(+), 3 deletions(-) diff --git a/dump_things_service/abstract_config.py b/dump_things_service/abstract_config.py index 20ebc9f..7e3f4a0 100644 --- a/dump_things_service/abstract_config.py +++ b/dump_things_service/abstract_config.py @@ -278,7 +278,7 @@ def read_config( path_conflicts = get_conflicting_paths(g_abstract_configuration) if path_conflicts: msg = ( - f'Incoming and curated paths of different collections are not disjunct:\n' + 'Incoming and curated paths of different collections are not disjunct:\n' + '\n'.join( f'path `{path_0}` from collection `{collection_0}` contains path `{path_1}` from collection `{collection_1}`' for path_0, collection_0, usage_0, path_1, collection_1, usage_1 in path_conflicts diff --git a/dump_things_service/manifest.py b/dump_things_service/manifest.py index 37ef7a6..beafd43 100644 --- a/dump_things_service/manifest.py +++ b/dump_things_service/manifest.py @@ -179,7 +179,7 @@ def manifest_configuration( logger.info('removing fault-inducing configuration for collection "%s"', collection) configuration.collections.pop(collection, None) msg = ( - f'Collection creation errors occurred:\n' + 'Collection creation errors occurred:\n' + '\n'.join( f'creating collection "{collection_name}" failed due to: {error}' for collection_name, error in collection_errors.items() diff --git a/dump_things_service/periodic.py b/dump_things_service/periodic.py index 8b2f866..2fbd795 100644 --- a/dump_things_service/periodic.py +++ b/dump_things_service/periodic.py @@ -1,5 +1,4 @@ import asyncio -from collections import deque from typing import Callable -- 2.54.1 From 241cc8772dc9a55ea956e3f365f3411fbb63cf6f Mon Sep 17 00:00:00 2001 From: Christian Monch Date: Wed, 4 Nov 2026 12:04:30 +0100 Subject: [PATCH 13/15] feat: report collection with recoverable error Collections with recoverable error are reported in `/server`-response with a class list with a single entry: `'??? (recoverable error in schema location)'`. --- dump_things_service/endpoints/v0/base_endpoints.py | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/dump_things_service/endpoints/v0/base_endpoints.py b/dump_things_service/endpoints/v0/base_endpoints.py index 65963ca..0a71330 100644 --- a/dump_things_service/endpoints/v0/base_endpoints.py +++ b/dump_things_service/endpoints/v0/base_endpoints.py @@ -121,12 +121,16 @@ async def server() -> ServerResponse: ServerCollectionResponse( name=collection_name, schema=configuration.collections[collection_name].schema_location, - classes=instance_state.schema_info[ + classes= + ( + instance_state.schema_info[ configuration.collections[collection_name].schema_location - ].classes, + ].classes + if collection_name not in g_recoverable_error + else ['??? (recoverable error in schema location)'] + ), ) for collection_name in configuration.collections - if collection_name not in g_recoverable_error ], ) -- 2.54.1 From 32accd081de22b9dc6016591af8f4539976a58d8 Mon Sep 17 00:00:00 2001 From: Christian Monch Date: Wed, 4 Nov 2026 12:08:22 +0100 Subject: [PATCH 14/15] fix: ensure that faulty URLs lead to recoverable error Make sure that faulty URLs are detected and lead to recoverable errors. --- dump_things_service/model.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/dump_things_service/model.py b/dump_things_service/model.py index 3adf2f2..b94d3f0 100644 --- a/dump_things_service/model.py +++ b/dump_things_service/model.py @@ -121,7 +121,11 @@ def get_model_for_schema( schema_location: str, ) -> tuple[ModuleType, list[str], str]: lgr.info(f'Building pydantic module for schema {schema_location}') - pydantic_generator = PydanticGenerator(schema_location) + try: + pydantic_generator = PydanticGenerator(schema_location) + except (HTTPError, URLError) as e: + # Enable retry on HTTPErrors + raise RecoverableConfigError from e model = compile_module_with_increasing_recursion_limit( pydantic_generator, schema_location, -- 2.54.1 From bfbbbb4ceaec1060ab69658993237728cb29dd9b Mon Sep 17 00:00:00 2001 From: Christian Monch Date: Wed, 4 Nov 2026 12:09:48 +0100 Subject: [PATCH 15/15] tests: add test for recoverable errors --- dump_things_service/tests/test_config.py | 46 ++++++++++++++++++++++-- 1 file changed, 44 insertions(+), 2 deletions(-) diff --git a/dump_things_service/tests/test_config.py b/dump_things_service/tests/test_config.py index cf33585..30a47cd 100644 --- a/dump_things_service/tests/test_config.py +++ b/dump_things_service/tests/test_config.py @@ -3,6 +3,7 @@ from pathlib import ( Path, PurePosixPath, ) +from shutil import copyfile import pytest import yaml @@ -22,14 +23,19 @@ from dump_things_service.abstract_config import ( dump_things_config_iri, dump_things_private_collection_name, get_config_backends, - read_config, get_conflicting_paths, + get_conflicting_paths, + read_config, ) +from dump_things_service.collection import check_recoverable_errors from dump_things_service.endpoints.v0.collection_endpoints import CollectionRequest from dump_things_service.endpoints.v0.token_endpoints import TokenRequest from dump_things_service.exceptions import ConfigError +from dump_things_service.instance_state import get_instance_state +from dump_things_service.manifest import g_recoverable_error from dump_things_service.tests import schema_file reference_config_file = Path(__file__).parent / 'assets' / 'reference_config.yaml' +test_schema_file = Path(__file__).parent / 'testschema.yaml' collection_request_pattern = CollectionRequest( name='', @@ -249,7 +255,43 @@ def test_config_structure(): _ = Configuration(**config_dict) -def test_schema_location_error_detection(fastapi_client_simple): +def test_schema_location_error_detection(fastapi_client_simple, tmp_path): + test_client, store_path, admin_token = fastapi_client_simple + + missing_file = f'{tmp_path}/does-not-exist.yaml' + collection_name = 'test_schema_location_error' + faulty_schema_location_collection = CollectionRequest( + name=collection_name, + schema=f'file:///{missing_file}', + default_token='test_default_token', + curated=PurePosixPath('curate_dir'), + incoming=PurePosixPath('incoming_dir'), + ) + response = test_client.post( + '/collections', + json=faulty_schema_location_collection.model_dump(mode='json', by_alias=True), + headers={'x-dumpthings-token': admin_token}, + ) + assert response.status_code == HTTP_201_CREATED + + # Check that the collection is in recoverable errors + assert collection_name in g_recoverable_error + + # Put a schema file in the location, perform the periodic activities and + # check that the collection is no longer in recoverable errors. + copyfile(test_schema_file, missing_file) + abstract_configuration = read_config(store_path) + instance_state = get_instance_state() + check_recoverable_errors( + abstract_configuration=abstract_configuration, + instance_state=instance_state, + ) + + # Check that the collection is no longer in recoverable errors + assert collection_name not in g_recoverable_error + + +def test_schema_content_error_detection(fastapi_client_simple): test_client, _, admin_token = fastapi_client_simple faulty_schema_collection = CollectionRequest( -- 2.54.1