Skip to content

Commit

Permalink
Fix race condition #104 (#108)
Browse files Browse the repository at this point in the history
Add unit test
  • Loading branch information
johnml1135 authored Sep 5, 2023
1 parent 4a86bf6 commit 3f3ff10
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 9 deletions.
27 changes: 18 additions & 9 deletions src/Serval.DataFiles/Services/DataFileService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -103,19 +103,28 @@ await _deletedFiles.InsertAsync(

public override async Task<bool> DeleteAsync(string id, CancellationToken cancellationToken = default)
{
// return true if the deletion was successful, false if the file did not exist or was already deleted.
await _dataAccessContext.BeginTransactionAsync(cancellationToken);
DataFile? dataFile = await Entities.DeleteAsync(id, cancellationToken);
if (dataFile is not null)
{
await _deletedFiles.InsertAsync(
new DeletedFile
{
Id = id,
Filename = dataFile.Filename,
DeletedAt = DateTime.UtcNow
},
cancellationToken
);
try
{
await _deletedFiles.InsertAsync(
new DeletedFile
{
Id = id,
Filename = dataFile.Filename,
DeletedAt = DateTime.UtcNow
},
cancellationToken
);
}
catch (DuplicateKeyException)
{
// if it was already deleted, return false
return false;
}
}
await _mediator.Publish(new DataFileDeleted { DataFileId = id }, cancellationToken);
await _dataAccessContext.CommitTransactionAsync(CancellationToken.None);
Expand Down
28 changes: 28 additions & 0 deletions tests/Serval.DataFiles.Tests/Services/DataFileServiceTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,34 @@ public async Task DeleteAsync_DoesNotExist()
Assert.That(deleted, Is.False);
}

[Test]
public async Task DeleteAsync_Twice()
{
var env = new TestEnvironment();
env.DataFiles.Add(
new DataFile
{
Id = DATA_FILE_ID,
Name = "file1",
Filename = "file1.txt"
}
);
bool deleted = await env.Service.DeleteAsync(DATA_FILE_ID);
Assert.That(deleted, Is.True);
// The same file would not be added twice, but this is to check
env.DataFiles.Add(
new DataFile
{
Id = DATA_FILE_ID,
Name = "file1",
Filename = "file1.txt"
}
);
deleted = await env.Service.DeleteAsync(DATA_FILE_ID);
// The real condition is a race condition - trying to delete the same file twice (at the same time). One should fail.
Assert.That(deleted, Is.False);
}

private class TestEnvironment
{
public TestEnvironment()
Expand Down

0 comments on commit 3f3ff10

Please sign in to comment.