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

Fix underflow possibility on ColumnFamilyDbStore (#5975) #6023

Merged
merged 3 commits into from
Feb 1, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ public Task IterateBatch(int batchSize, Func<byte[], byte[], Task> callback, Can
return this.IterateBatch(iterator => iterator.SeekToFirst(), batchSize, callback, cancellationToken);
}

public Task<ulong> Count() => Task.FromResult((ulong)Interlocked.Read(ref this.count));
public Task<ulong> Count() => Task.FromResult((ulong)Math.Max(Interlocked.Read(ref this.count), 0));

public Task<ulong> GetCountFromOffset(byte[] offset)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
namespace Microsoft.Azure.Devices.Edge.Storage.RocksDb.Test
{
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Devices.Edge.Util;
using Microsoft.Azure.Devices.Edge.Util.Test.Common;
Expand Down Expand Up @@ -103,5 +104,37 @@ public async Task MessageCountTest()
Assert.Equal(0ul, await columnFamilyDbStore.Count());
}
}

[Fact]
public async Task MessageCountUnderflowTest()
{
using (IDbStore columnFamilyDbStore = this.rocksDbStoreProvider.GetDbStore("test"))
{
Assert.Equal(0ul, await columnFamilyDbStore.Count());

for (int i = 0; i < 10; i++)
{
string key = $"key{i}";
string value = "$value{i}";
await columnFamilyDbStore.Put(key.ToBytes(), value.ToBytes());
}

Assert.Equal(10ul, await columnFamilyDbStore.Count());
}

using (IDbStore columnFamilyDbStore = this.rocksDbStoreProvider.GetDbStore("test"))
{
Assert.Equal(10ul, await columnFamilyDbStore.Count());

// Using 11 (10 + 1) to make sure underflow is caught.
for (int i = 0; i < 11; i++)
{
string key = $"key{i}";
await columnFamilyDbStore.Remove(key.ToBytes());
}

Assert.Equal(0ul, await columnFamilyDbStore.Count());
}
}
}
}