Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dsegog 271 handling failed ingestion #148

Merged
merged 25 commits into from
Feb 4, 2025
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
6a190a3
Added function decorator to handle db issues
moonraker595 Nov 29, 2024
50273e9
Created function decorator to handle db issues
moonraker595 Nov 29, 2024
f9f491a
Added test to check that a db error is caught and returned
moonraker595 Nov 29, 2024
c974569
Wrapped the upload in a try/catch and return the failed channel if ne…
moonraker595 Jan 20, 2025
cbd62c5
Added a function to remove a channel from the record. Used when the c…
moonraker595 Jan 20, 2025
63d2366
Wrapped the upload in a try/catch and return the failed channel if ne…
moonraker595 Jan 20, 2025
b89d078
Updated versions
moonraker595 Jan 20, 2025
2270606
Black formatting
moonraker595 Jan 20, 2025
ce92c48
Added to list of aliases
moonraker595 Jan 20, 2025
eb73d4d
Linting
moonraker595 Jan 20, 2025
18ad3b6
Added to list of aliases
moonraker595 Jan 20, 2025
2f6bd61
Created a way to monitor the result of the echo uploads and remove th…
moonraker595 Jan 21, 2025
1a4dd98
added tests to check various db and echo related failures
moonraker595 Jan 21, 2025
b89d73a
Linting
moonraker595 Jan 21, 2025
f7c53a4
Update vulnerable dependencies
moonraker595 Jan 21, 2025
2d623db
Added error handling around the query_to_list function
moonraker595 Jan 30, 2025
5da3e01
Removing redundant KeyError
moonraker595 Jan 30, 2025
b65af8e
Added passthrough for DatabaseErrors
moonraker595 Jan 31, 2025
f048abc
Updated to fix ingest boto issue
moonraker595 Jan 31, 2025
6d07ad4
Updated tests for coverage
moonraker595 Feb 3, 2025
abfe6fd
Updated test to cover for propagated db errors.
moonraker595 Feb 3, 2025
6cce922
Merge branch 'main' into DSEGOG-271-Handling-Failed-Ingestion
moonraker595 Feb 3, 2025
fdc7309
updated to working versions
moonraker595 Feb 3, 2025
1dea424
testing downgrading of certify
moonraker595 Feb 4, 2025
70bbd4e
testing upgrade of certify
moonraker595 Feb 4, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 13 additions & 2 deletions operationsgateway_api/src/mongo/interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
from operationsgateway_api.src.config import Config
from operationsgateway_api.src.exceptions import DatabaseError
from operationsgateway_api.src.mongo.connection import ConnectionInstance
from operationsgateway_api.src.mongo.mongo_error_handling import mongodb_error_handling

log = logging.getLogger()
ProjectionAlias = Optional[Union[Mapping[str, Any], Iterable[str]]]
Expand All @@ -22,16 +23,17 @@
class MongoDBInterface:
"""
An implementation of various PyMongo and Motor functions that suit our specific
database and colllection names
database and collection names
Motor doesn't support type annotations (see
https://jira.mongodb.org/browse/MOTOR-331 for any updates) so type annotations are
used from PyMongo which from a user perspective, acts almost identically (exlcuding
used from PyMongo which from a user perspective, acts almost identically (excluding
async support of course). This means the type hinting can actually be useful for
developers of this repo
"""

@staticmethod
@mongodb_error_handling("get_collection_object")
def get_collection_object(collection_name: str) -> Collection:
"""
Simple getter function which gets a particular collection so it can be
Expand All @@ -44,6 +46,7 @@ def get_collection_object(collection_name: str) -> Collection:
raise DatabaseError("Invalid collection name given") from exc

@staticmethod
@mongodb_error_handling("find")
patrick-austin marked this conversation as resolved.
Show resolved Hide resolved
def find(
collection_name: str = "images",
filter_: dict = None,
Expand Down Expand Up @@ -99,6 +102,7 @@ async def query_to_list(query: Cursor) -> List[Dict[str, Any]]:
return await query.to_list(length=Config.config.mongodb.max_documents)

@staticmethod
@mongodb_error_handling("find_one")
async def find_one(
collection_name: str,
filter_: Dict[str, Any] = None,
Expand All @@ -120,6 +124,7 @@ async def find_one(
return await collection.find_one(filter_, sort=sort, projection=projection)

@staticmethod
@mongodb_error_handling("update_one")
async def update_one(
collection_name: str,
filter_: Dict[str, Any] = None,
Expand Down Expand Up @@ -153,6 +158,7 @@ async def update_one(
) from exc

@staticmethod
@mongodb_error_handling("update_many")
async def update_many(
collection_name: str,
filter_: Dict[str, Any] = {}, # noqa: B006
Expand All @@ -177,6 +183,7 @@ async def update_many(
) from exc

@staticmethod
@mongodb_error_handling("insert_one")
async def insert_one(collection_name: str, data: Dict[str, Any]) -> InsertOneResult:
"""
Using the input data, insert a single document into a given collection
Expand All @@ -194,6 +201,7 @@ async def insert_one(collection_name: str, data: Dict[str, Any]) -> InsertOneRes
) from exc

@staticmethod
@mongodb_error_handling("insert_many")
async def insert_many(
collection_name: str,
data: List[Dict[str, Any]],
Expand All @@ -215,6 +223,7 @@ async def insert_many(
) from exc

@staticmethod
@mongodb_error_handling("delete_one")
async def delete_one(
collection_name: str,
filter_: Dict[str, Any] = None,
Expand Down Expand Up @@ -245,6 +254,7 @@ async def delete_one(
) from exc

@staticmethod
@mongodb_error_handling("count_documents")
async def count_documents(
collection_name: str,
filter_: Dict[str, Any] = None,
Expand Down Expand Up @@ -273,6 +283,7 @@ async def count_documents(
) from exc

@staticmethod
@mongodb_error_handling("aggregate")
async def aggregate(
collection_name: str,
pipeline,
Expand Down
39 changes: 39 additions & 0 deletions operationsgateway_api/src/mongo/mongo_error_handling.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
from functools import wraps
from inspect import iscoroutinefunction

from operationsgateway_api.src.exceptions import DatabaseError


def mongodb_error_handling(operation: str):
"""
Decorator for consistent error handling in MongoDB operations, supporting both
sync and async functions.
"""

def decorator(func):
if iscoroutinefunction(func): # Check if the function is async

@wraps(func)
async def async_wrapper(*args, **kwargs):
try:
return await func(*args, **kwargs)
except Exception as exc:
raise DatabaseError(
f"Database operation failed during {operation}",
) from exc
patrick-austin marked this conversation as resolved.
Show resolved Hide resolved

return async_wrapper
else: # Handle synchronous functions

@wraps(func)
def sync_wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as exc:
raise DatabaseError(
f"Database operation failed during {operation}",
) from exc
patrick-austin marked this conversation as resolved.
Show resolved Hide resolved

return sync_wrapper

return decorator
48 changes: 48 additions & 0 deletions test/mongo/test_mongo_error_handling.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
from unittest.mock import AsyncMock, patch

from fastapi.testclient import TestClient
import pytest


class TestMongoDBErrorHandling:
@pytest.mark.asyncio
@pytest.mark.parametrize(
"record_id, expected_status_code, expected_response",
[
pytest.param(
"20230605100000",
500,
{"detail": "Database operation failed during find_one"},
id="Simulated error during find_one",
),
],
)
# This test simulates an exception being raised in the collection.find_one call
# (within interface.py), which the decorator should handle and produce a
# DatabaseError, ultimately flowing this back up to the user in the endpoint,
# producing a 500
async def test_find_one_exception_in_interface(
patrick-austin marked this conversation as resolved.
Show resolved Hide resolved
self,
test_app: TestClient,
login_and_get_token,
record_id,
expected_status_code,
expected_response,
):
with patch(
"operationsgateway_api.src.mongo.interface.MongoDBInterface.get_collection_object",
) as mock_get_collection_object:
# Mock the `collection.find_one` to raise an exception
mock_collection = AsyncMock()
mock_collection.find_one.side_effect = Exception("Simulated exception")
mock_get_collection_object.return_value = mock_collection

# Make the GET request to the endpoint
response = test_app.get(
f"/records/{record_id}",
headers={"Authorization": f"Bearer {login_and_get_token}"},
)

# Assert the status code and responseAsyncMock
assert response.status_code == expected_status_code
assert response.json() == expected_response