Handle configuration errors gracefully #284

Merged
cmo merged 15 commits from tolerate-configuration-errors into master 2026-11-04 13:10:55 +00:00
13 changed files with 499 additions and 39 deletions

View file

@ -1,3 +1,28 @@
# 6.7.0 (2026-xx-xx)
## 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
- Check that `incoming` and `curated`-paths of different collections
do not share the same directory tree.
# 6.6.4 (2026-10-17)
## Security

View file

@ -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 (
@ -36,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)
@ -273,6 +275,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 = (
'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
@ -539,3 +551,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

View file

@ -395,3 +395,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), {}

View file

@ -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
@ -118,9 +121,14 @@ 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
],

View file

@ -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
@ -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': {

View file

@ -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': {

View file

@ -10,5 +10,9 @@ class ConfigCollisionError(ConfigError):
pass
class RecoverableConfigError(ConfigError):
pass
class CurieResolutionError(DumpThingsError):
pass

View file

@ -1,17 +1,20 @@
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
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
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
@ -28,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
@ -40,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)
@ -88,6 +96,15 @@ parser.add_argument(
'`<store>/.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.',
@ -159,10 +176,42 @@ 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'},
]
@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)
@ -266,24 +315,33 @@ 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,
)
sys.exit(2)
manifest_configuration(
configuration=g_configuration,
try:
manifest_configuration(
configuration=g_configuration,
instance_state=g_instance_state,
)
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,
)
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,

View file

@ -1,19 +1,20 @@
import logging
from typing import cast
from fastapi_pagination import add_pagination
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,
RecoverableConfigError,
)
from dump_things_service.instance_state import InstanceState
logger = logging.getLogger('dump_things_service')
tag_groups = [
'write',
'validate',
'curated_write',
'incoming_write',
@ -28,7 +29,6 @@ openapi_tags_template: list[dict | str] = [
'name': 'Read records',
'description': 'Read records from the given collection',
},
#'write',
'validate',
{
'name': 'Delete records',
@ -102,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)
@ -117,12 +119,37 @@ 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,
)
g_recoverable_error -= {collection_name}
# There are many possible errors that can occur when creating a
# 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}',
)
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.
@ -136,15 +163,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
@ -154,6 +172,21 @@ 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 = (
'Collection creation errors occurred:\n'
+ '\n'.join(
f'creating collection "{collection_name}" failed due to: {error}'
for collection_name, error in collection_errors.items()
)
)
raise ConfigError(msg)
def create_token(
instance_state: InstanceState,

View file

@ -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
@ -119,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,
@ -139,4 +145,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

View file

@ -0,0 +1,33 @@
import asyncio
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])

View file

@ -3,9 +3,12 @@ from pathlib import (
Path,
PurePosixPath,
)
from shutil import copyfile
import pytest
import yaml
from starlette.status import HTTP_400_BAD_REQUEST, \
HTTP_422_UNPROCESSABLE_CONTENT
from dump_things_service import (
HTTP_200_OK,
@ -20,14 +23,19 @@ from dump_things_service.abstract_config import (
dump_things_config_iri,
dump_things_private_collection_name,
get_config_backends,
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='',
@ -245,3 +253,139 @@ 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, 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(
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_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
response = test_client.post(
'/collections',
json={'some_crazy': 'content'},
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)

View file

@ -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