❔ how do i make blob and entity deletion atomic?
{
public async Task<IResult> Handle(DeleteImageCommand request, CancellationToken cancellationToken)
{
var photo = await _dbContext.ListingPhotos.FindAsync(request.Id);
if(photo is not null)
{
await DeleteBlob(photo.BlobName, containerName);
_dbContext.ListingPhotos.Remove(photo);
}
return Results.Ok();
}
private async Task DeleteBlob(string blobName, string containerName)
{
var containerClient = _blobServiceClient.GetBlobContainerClient(containerName);
if (!await containerClient.ExistsAsync())
throw new ApplicationException($"Unable to upload blobs to container {containerName} as the container does not exist.");
var blobClient = containerClient.GetBlobClient(blobName);
if (!await blobClient.ExistsAsync())
throw new ApplicationException($"Unable to delete blob {blobName} in container '{containerName}' as no blob with this name exists in this container");
var response = await blobClient.DeleteAsync();
if (response.Status != 200)
{
throw new ApplicationException($"Failed to delete blob {blobName} in container '{containerName}' with status code {response.Status}");
}
}{
public async Task<IResult> Handle(DeleteImageCommand request, CancellationToken cancellationToken)
{
var photo = await _dbContext.ListingPhotos.FindAsync(request.Id);
if(photo is not null)
{
await DeleteBlob(photo.BlobName, containerName);
_dbContext.ListingPhotos.Remove(photo);
}
return Results.Ok();
}
private async Task DeleteBlob(string blobName, string containerName)
{
var containerClient = _blobServiceClient.GetBlobContainerClient(containerName);
if (!await containerClient.ExistsAsync())
throw new ApplicationException($"Unable to upload blobs to container {containerName} as the container does not exist.");
var blobClient = containerClient.GetBlobClient(blobName);
if (!await blobClient.ExistsAsync())
throw new ApplicationException($"Unable to delete blob {blobName} in container '{containerName}' as no blob with this name exists in this container");
var response = await blobClient.DeleteAsync();
if (response.Status != 200)
{
throw new ApplicationException($"Failed to delete blob {blobName} in container '{containerName}' with status code {response.Status}");
}
}In this code, what if blob removal is successful but listingphotos.remove somehow fails?
1. Is it something to worry about?
2. Should I do retries?
3. Compensating transaction of some kind? if removal of the entity fails > restore the deleted blob?
