Skip to content

Commit

Permalink
delete object from S3 if database save fails
Browse files Browse the repository at this point in the history
  • Loading branch information
jschlyter committed Nov 12, 2024
1 parent 5b3fee4 commit 28dc319
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 3 deletions.
13 changes: 10 additions & 3 deletions aggrec/aggregates.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

import bson
import pendulum
import pymongo
from bson.objectid import ObjectId
from fastapi import APIRouter, Header, HTTPException, Request, Response, status
from fastapi.responses import StreamingResponse
Expand Down Expand Up @@ -299,9 +300,15 @@ async def create_aggregate(
)
logger.info("Object created: %s", metadata.s3_object_key)

with tracer.start_as_current_span("mongodb.insert"):
metadata.save()
logger.info("Metadata saved: %s", metadata.id)
with tracer.start_as_current_span("mongodb.insert"):
try:
with pymongo.timeout(2):
metadata.save(request.app.settings.mongodb.timeout)
logger.info("Metadata saved: %s", metadata.id)
except Exception as exc:
logger.error("Failed to save metadata, deleting object %s", metadata.s3_object_key, exc_info=exc)
await s3_client.delete_object(Bucket=s3_bucket, Key=metadata.s3_object_key)
raise HTTPException(status.HTTP_502_BAD_GATEWAY, "Database error") from exc

aggregates_counter.add(1, {"aggregate_type": aggregate_type.value})

Expand Down
1 change: 1 addition & 0 deletions aggrec/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ class MqttSettings(BaseModel):

class MongoDB(BaseModel):
server: MongodbUrl | None = Field(default="mongodb://localhost/aggregates")
timeout: int = Field(default=5)


class S3(BaseModel):
Expand Down

0 comments on commit 28dc319

Please sign in to comment.