dump-things-service/dump_things_service/endpoints/v0/base_endpoints.py
Christian Monch ba4a8d952c
Some checks failed
Codespell / Check for spelling errors (push) Successful in 25s
Ruff / Code linting (push) Failing after 28s
Test execution / Test-all (push) Successful in 1m2s
chore: reformat according to hatch check fmt
2026-11-13 15:13:36 +01:00

729 lines
22 KiB
Python

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,
g_recoverable_error,
)
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,
Request,
Response,
)
from fastapi_pagination import (
Page,
paginate,
)
from pydantic import (
BaseModel,
Field,
)
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_subclasses,
)
from dump_things_service.utils import (
authenticate_token,
check_bounds,
check_content_type,
combine_ttl,
get_token_store,
join_default_token_permissions,
order_dict,
process_token,
simple_process_token,
wrap_http_exception,
dict_to_base_model,
)
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
if collection_name not in g_recoverable_error
else ['??? (recoverable error in schema location)']
),
)
for collection_name in configuration.collections
],
)
@router.get(
'/management/reload/policy_info/{collection:path}',
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)],
):
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}.',
)
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}'.",
)
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:path}/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,
request: Request,
api_key: str = Depends(api_key_header_scheme),
add_submission_tag: bool = False,
format: Format | None = None,
):
format_, body = check_content_type(request, format, body)
configuration = get_config()
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}'.",
)
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
record = dict_to_base_model(json_object, class_name, collection)
with wrap_http_exception(
ValueError,
status_code=HTTP_422_UNPROCESSABLE_CONTENT,
header='Validation error',
):
instance_state.validators[collection].validate(record)
with wrap_http_exception(CurieResolutionError):
stored_records = store.store_object(
obj=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:path}/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,
):
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:path}/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,
):
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:path}/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,
) -> 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:path}/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,
):
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:path}/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,
) -> 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,
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,
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:path}/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, _ = 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