From 18ebe9371c326035d909404b71fa45a0403a37cc Mon Sep 17 00:00:00 2001 From: Francesco Del Re Date: Tue, 1 Sep 2026 14:28:04 +0200 Subject: [PATCH 1/7] chore(deps): update dependencies --- .../SharpConnector.Tests.csproj | 6 +++--- src/SharpConnector/SharpConnector.csproj | 20 +++++++++---------- 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/src/SharpConnector.Tests/SharpConnector.Tests.csproj b/src/SharpConnector.Tests/SharpConnector.Tests.csproj index 227dbb0..a045244 100644 --- a/src/SharpConnector.Tests/SharpConnector.Tests.csproj +++ b/src/SharpConnector.Tests/SharpConnector.Tests.csproj @@ -25,10 +25,10 @@ - + - - + + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/src/SharpConnector/SharpConnector.csproj b/src/SharpConnector/SharpConnector.csproj index 14387ec..a928309 100755 --- a/src/SharpConnector/SharpConnector.csproj +++ b/src/SharpConnector/SharpConnector.csproj @@ -19,20 +19,20 @@ - - - + + + - - - - + + + + - + - - + + From a16bd135e9c9c3f51032d7f44dab6788a8410696 Mon Sep 17 00:00:00 2001 From: Francesco Del Re Date: Fri, 9 Oct 2026 00:50:02 +0200 Subject: [PATCH 2/7] chore: update dependencies --- .../SharpConnector.Api.csproj | 2 +- .../SharpConnector.Tests.csproj | 10 ++++----- src/SharpConnector/SharpConnector.csproj | 22 +++++++++---------- 3 files changed, 17 insertions(+), 17 deletions(-) diff --git a/src/SharpConnector.Api/SharpConnector.Api.csproj b/src/SharpConnector.Api/SharpConnector.Api.csproj index 46db46f..ed4f1b6 100644 --- a/src/SharpConnector.Api/SharpConnector.Api.csproj +++ b/src/SharpConnector.Api/SharpConnector.Api.csproj @@ -42,7 +42,7 @@ - + diff --git a/src/SharpConnector.Tests/SharpConnector.Tests.csproj b/src/SharpConnector.Tests/SharpConnector.Tests.csproj index a045244..92bf6c9 100644 --- a/src/SharpConnector.Tests/SharpConnector.Tests.csproj +++ b/src/SharpConnector.Tests/SharpConnector.Tests.csproj @@ -25,11 +25,11 @@ - - - - - + + + + + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/src/SharpConnector/SharpConnector.csproj b/src/SharpConnector/SharpConnector.csproj index a928309..7059ab3 100755 --- a/src/SharpConnector/SharpConnector.csproj +++ b/src/SharpConnector/SharpConnector.csproj @@ -19,20 +19,20 @@ - - - - + + + + - - - - - - + + + + + + - + From 08e3f961c61202eb4435f0afb08a48836344f57d Mon Sep 17 00:00:00 2001 From: Francesco Del Re Date: Tue, 27 Oct 2026 23:10:13 +0100 Subject: [PATCH 3/7] chore: update dependencies --- .../SharpConnector.Api.csproj | 2 +- .../SharpConnector.Tests.csproj | 6 +++--- src/SharpConnector/SharpConnector.csproj | 18 +++++++++--------- 3 files changed, 13 insertions(+), 13 deletions(-) diff --git a/src/SharpConnector.Api/SharpConnector.Api.csproj b/src/SharpConnector.Api/SharpConnector.Api.csproj index ed4f1b6..0aa4ad8 100644 --- a/src/SharpConnector.Api/SharpConnector.Api.csproj +++ b/src/SharpConnector.Api/SharpConnector.Api.csproj @@ -42,7 +42,7 @@ - + diff --git a/src/SharpConnector.Tests/SharpConnector.Tests.csproj b/src/SharpConnector.Tests/SharpConnector.Tests.csproj index 92bf6c9..5a6c04e 100644 --- a/src/SharpConnector.Tests/SharpConnector.Tests.csproj +++ b/src/SharpConnector.Tests/SharpConnector.Tests.csproj @@ -25,10 +25,10 @@ - + - - + + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/src/SharpConnector/SharpConnector.csproj b/src/SharpConnector/SharpConnector.csproj index 7059ab3..c9c3e08 100755 --- a/src/SharpConnector/SharpConnector.csproj +++ b/src/SharpConnector/SharpConnector.csproj @@ -19,20 +19,20 @@ - + - - - - - - + + + + + + - - + + From 0c1b045efed8c4476d1256ab7e31886e596d32c4 Mon Sep 17 00:00:00 2001 From: Francesco Del Re Date: Tue, 27 Oct 2026 23:41:37 +0100 Subject: [PATCH 4/7] fix: correct Redis database selection, expiration handling and LiteDB/ArangoDB key lookup --- .../HighSeverityFixesTests.cs | 217 ++++++++++++++++++ .../Connectors/ArangoDb/ArangoDbWrapper.cs | 73 ++++-- .../Connectors/Couchbase/CouchbaseWrapper.cs | 4 + .../Connectors/DynamoDB/DynamoDbWrapper.cs | 21 +- .../Connectors/LiteDb/LiteDbAccess.cs | 2 + .../Connectors/LiteDb/LiteDbWrapper.cs | 21 +- .../Connectors/MongoDb/MongoDbWrapper.cs | 39 ++-- .../Connectors/RavenDb/RavenDbWrapper.cs | 39 ++-- .../Connectors/Redis/RedisWrapper.cs | 32 ++- .../Entities/ArangoConnectorEntity.cs | 35 +++ .../Entities/ConnectorEntity.cs | 13 ++ .../Operations/RedisOperations.cs | 46 ++-- src/SharpConnector/SharpConnector.csproj | 4 + .../Utilities/ExpirationHelper.cs | 38 +++ 14 files changed, 475 insertions(+), 109 deletions(-) create mode 100644 src/SharpConnector.Tests/HighSeverityFixesTests.cs create mode 100644 src/SharpConnector/Entities/ArangoConnectorEntity.cs create mode 100644 src/SharpConnector/Utilities/ExpirationHelper.cs diff --git a/src/SharpConnector.Tests/HighSeverityFixesTests.cs b/src/SharpConnector.Tests/HighSeverityFixesTests.cs new file mode 100644 index 0000000..68ca35e --- /dev/null +++ b/src/SharpConnector.Tests/HighSeverityFixesTests.cs @@ -0,0 +1,217 @@ +// (c) 2020 Francesco Del Re +// This code is licensed under MIT license (see LICENSE.txt for details) +using Microsoft.Extensions.Configuration; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using SharpConnector.Configuration; +using SharpConnector.Connectors.LiteDb; +using SharpConnector.Connectors.Redis; +using SharpConnector.Entities; +using SharpConnector.Utilities; +using StackExchange.Redis; +using System; +using System.Collections.Generic; +using System.Linq; + +namespace SharpConnector.Tests +{ + [TestClass] + public class HighSeverityFixesTests + { + #region Expiration + + [TestMethod] + public void ConnectorEntity_WithExpiration_SetsExpiresAt() + { + var before = DateTime.UtcNow; + var entity = new ConnectorEntity("k", "v", TimeSpan.FromMinutes(5)); + + Assert.IsNotNull(entity.ExpiresAt); + Assert.IsTrue(entity.ExpiresAt.Value >= before.AddMinutes(5)); + Assert.IsFalse(entity.IsExpired()); + } + + [TestMethod] + public void ConnectorEntity_WithoutExpiration_NeverExpires() + { + var entity = new ConnectorEntity("k", "v"); + + Assert.IsNull(entity.ExpiresAt); + Assert.IsFalse(entity.IsExpired()); + } + + [TestMethod] + public void IsExpired_PastExpiresAt_ReturnsTrue() + { + var entity = new ConnectorEntity("k", "v") { ExpiresAt = DateTime.UtcNow.AddSeconds(-1) }; + + Assert.IsTrue(entity.IsExpired()); + Assert.IsNull(entity.DiscardIfExpired()); + } + + [TestMethod] + public void WhereNotExpired_FiltersExpiredAndNull() + { + var valid = new ConnectorEntity("a", "v", TimeSpan.FromMinutes(1)); + var expired = new ConnectorEntity("b", "v") { ExpiresAt = DateTime.UtcNow.AddMinutes(-1) }; + var list = new List { valid, expired, null }; + + var result = list.WhereNotExpired().ToList(); + + Assert.HasCount(1, result); + Assert.AreEqual("a", result[0].Key); + } + + [TestMethod] + public void ExpiresAt_SurvivesJsonRoundTrip() + { + var entity = new ConnectorEntity("k", "v") { ExpiresAt = DateTime.UtcNow.AddSeconds(-5) }; + + var copy = JsonConvert.DeserializeObject(JsonConvert.SerializeObject(entity)); + + Assert.IsTrue(copy.IsExpired()); + } + + [TestMethod] + public void RemainingTimeToLive_NoExpiration_ReturnsNull() + { + Assert.IsNull(new ConnectorEntity("k", "v").RemainingTimeToLive()); + } + + [TestMethod] + public void RemainingTimeToLive_WithExpiration_ReturnsPositiveTtl() + { + var ttl = new ConnectorEntity("k", "v", TimeSpan.FromMinutes(10)).RemainingTimeToLive(); + + Assert.IsNotNull(ttl); + Assert.IsTrue(ttl.Value > TimeSpan.FromMinutes(9) && ttl.Value <= TimeSpan.FromMinutes(10)); + } + + [TestMethod] + public void RemainingTimeToLive_AlreadyExpired_ReturnsMinimalPositiveTtl() + { + var entity = new ConnectorEntity("k", "v") { ExpiresAt = DateTime.UtcNow.AddMinutes(-1) }; + + Assert.IsTrue(entity.RemainingTimeToLive() > TimeSpan.Zero); + } + + #endregion + + #region Redis + + [TestMethod] + public void Redis_IsWrongType_DetectsWrongTypeError() + { + var ex = new RedisServerException("WRONGTYPE Operation against a key holding the wrong kind of value"); + + Assert.IsTrue(RedisWrapper.IsWrongType(ex)); + } + + [TestMethod] + public void Redis_IsWrongType_IgnoresOtherErrors() + { + Assert.IsFalse(RedisWrapper.IsWrongType(new RedisServerException("ERR something else"))); + } + + [TestMethod] + public void Redis_TryDeserialize_InvalidPayload_ReturnsNull() + { + Assert.IsNull(RedisWrapper.TryDeserialize("not-json")); + } + + [TestMethod] + public void Redis_TryDeserialize_ValidPayload_ReturnsEntity() + { + var json = JsonConvert.SerializeObject(new ConnectorEntity("k", "v")); + + Assert.AreEqual("k", RedisWrapper.TryDeserialize(json).Key); + } + + [TestMethod] + public void RedisConfig_ReadsDatabaseNumber() + { + var config = new RedisConfig(BuildConfiguration(new() + { + ["connectionstring"] = "localhost:6379", + ["databasenumber"] = "3" + })); + + Assert.AreEqual(3, config.DatabaseNumber); + } + + #endregion + + #region ArangoDB + + [TestMethod] + public void ArangoConnectorEntity_SerializesKeyAsDocumentKey() + { + var entity = new ArangoConnectorEntity(new ConnectorEntity("my-key", "v")); + + var json = JObject.Parse(JsonConvert.SerializeObject(entity)); + + Assert.AreEqual("my-key", json["_key"]?.ToString()); + Assert.AreEqual("my-key", json["Key"]?.ToString()); + } + + [TestMethod] + public void ArangoConnectorEntity_CopiesExpiration() + { + var source = new ConnectorEntity("k", "v", TimeSpan.FromMinutes(1)); + + var entity = new ArangoConnectorEntity(source); + + Assert.AreEqual(source.Expiration, entity.Expiration); + Assert.AreEqual(source.ExpiresAt, entity.ExpiresAt); + } + + #endregion + + #region LiteDB (in-memory) + + private static LiteDbWrapper CreateLiteDbWrapper() => + new(new LiteDbConfig(BuildConfiguration(new() { ["connectionstring"] = ":memory:" }))); + + [TestMethod] + public void LiteDb_Update_ExistingKey_UpdatesPayload() + { + using var wrapper = CreateLiteDbWrapper(); + wrapper.Insert(new LiteDbConnectorEntity("k1", "old", null)); + + var updated = wrapper.Update(new LiteDbConnectorEntity("k1", "new", null)); + + Assert.IsTrue(updated); + Assert.AreEqual("new", wrapper.Get("k1").Payload); + Assert.HasCount(1, wrapper.GetAll()); + } + + [TestMethod] + public void LiteDb_Update_MissingKey_ReturnsFalse() + { + using var wrapper = CreateLiteDbWrapper(); + + Assert.IsFalse(wrapper.Update(new LiteDbConnectorEntity("missing", "v", null))); + } + + [TestMethod] + public void LiteDb_ExpiredEntity_IsNotReturned() + { + using var wrapper = CreateLiteDbWrapper(); + var expired = new LiteDbConnectorEntity("exp", "v", null) { ExpiresAt = DateTime.UtcNow.AddMinutes(-1) }; + wrapper.Insert(expired); + wrapper.Insert(new LiteDbConnectorEntity("ok", "v", TimeSpan.FromMinutes(5))); + + Assert.IsNull(wrapper.Get("exp")); + Assert.IsFalse(wrapper.Exists("exp")); + Assert.IsTrue(wrapper.Exists("ok")); + Assert.HasCount(1, wrapper.GetAll()); + Assert.HasCount(1, wrapper.Query(_ => true)); + } + + #endregion + + private static IConfiguration BuildConfiguration(Dictionary values) => + new ConfigurationBuilder().AddInMemoryCollection(values).Build(); + } +} diff --git a/src/SharpConnector/Connectors/ArangoDb/ArangoDbWrapper.cs b/src/SharpConnector/Connectors/ArangoDb/ArangoDbWrapper.cs index c0e56e2..02337b6 100644 --- a/src/SharpConnector/Connectors/ArangoDb/ArangoDbWrapper.cs +++ b/src/SharpConnector/Connectors/ArangoDb/ArangoDbWrapper.cs @@ -1,9 +1,11 @@ // (c) 2025 Francesco Del Re // This code is licensed under MIT license (see LICENSE.txt for details) +using ArangoDBNetStandard; using ArangoDBNetStandard.CollectionApi.Models; using ArangoDBNetStandard.CursorApi.Models; using SharpConnector.Configuration; using SharpConnector.Entities; +using SharpConnector.Utilities; using System; using System.Collections.Generic; using System.Linq; @@ -16,6 +18,7 @@ public class ArangoDbWrapper : IDisposable { private readonly ArangoDbAccess _arangoDbAccess; private readonly string _collectionName; + private const int DocumentNotFoundErrorNum = 1202; /// /// Initializes a new instance of the class. @@ -69,13 +72,27 @@ public async Task GetAsync(string key, CancellationToken ct = d { ct.ThrowIfCancellationRequested(); - var doc = await _arangoDbAccess.Client.Document - .GetDocumentAsync(_collectionName, key, token: ct) - .ConfigureAwait(false); + try + { + var doc = await _arangoDbAccess.Client.Document + .GetDocumentAsync(_collectionName, key, token: ct) + .ConfigureAwait(false); - return doc; + return doc.DiscardIfExpired(); + } + catch (ApiErrorException ex) when (IsNotFound(ex)) + { + return null; + } } + /// + /// Returns true when the ArangoDB error indicates a missing document. + /// + private static bool IsNotFound(ApiErrorException ex) => + ex.ApiError?.ErrorNum == DocumentNotFoundErrorNum || + ex.ApiError?.Code == System.Net.HttpStatusCode.NotFound; + /// /// Retrieve all documents (sync wrapper). /// @@ -121,7 +138,7 @@ public async Task> GetAllAsync(CancellationToken ct = defa hasMore = next.HasMore == true; } - return items; + return items.WhereNotExpired().ToList(); } /// @@ -145,7 +162,7 @@ public async Task InsertAsync(ConnectorEntity connectorEntity, Cancellatio ct.ThrowIfCancellationRequested(); var result = await _arangoDbAccess.Client.Document - .PostDocumentAsync(_collectionName, connectorEntity, token: ct) + .PostDocumentAsync(_collectionName, new ArangoConnectorEntity(connectorEntity), token: ct) .ConfigureAwait(false); return !string.IsNullOrEmpty(result._id); @@ -171,8 +188,10 @@ public async Task InsertManyAsync(List connectorEntities, { ct.ThrowIfCancellationRequested(); + var documents = connectorEntities.Select(e => new ArangoConnectorEntity(e)).ToList(); + var result = await _arangoDbAccess.Client.Document - .PostDocumentsAsync(_collectionName, connectorEntities, token: ct) + .PostDocumentsAsync(_collectionName, documents, token: ct) .ConfigureAwait(false); ct.ThrowIfCancellationRequested(); @@ -199,11 +218,17 @@ public async Task UpdateAsync(ConnectorEntity connectorEntity, Cancellatio { ct.ThrowIfCancellationRequested(); - await _arangoDbAccess.Client.Document - .PutDocumentAsync(_collectionName, connectorEntity.Key, connectorEntity, token: ct) - .ConfigureAwait(false); - - return true; + try + { + await _arangoDbAccess.Client.Document + .PutDocumentAsync(_collectionName, connectorEntity.Key, new ArangoConnectorEntity(connectorEntity), token: ct) + .ConfigureAwait(false); + return true; + } + catch (ApiErrorException ex) when (IsNotFound(ex)) + { + return false; + } } /// @@ -226,11 +251,17 @@ public async Task DeleteAsync(string key, CancellationToken ct = default) { ct.ThrowIfCancellationRequested(); - await _arangoDbAccess.Client.Document - .DeleteDocumentAsync(_collectionName, key, token: ct) - .ConfigureAwait(false); - - return true; + try + { + await _arangoDbAccess.Client.Document + .DeleteDocumentAsync(_collectionName, key, token: ct) + .ConfigureAwait(false); + return true; + } + catch (ApiErrorException ex) when (IsNotFound(ex)) + { + return false; + } } /// @@ -259,13 +290,7 @@ public bool Exists(string key) /// A token to cancel the asynchronous operation. public async Task ExistsAsync(string key, CancellationToken ct = default) { - ct.ThrowIfCancellationRequested(); - - var result = await _arangoDbAccess.Client.Document - .GetDocumentAsync(_collectionName, key, token: ct) - .ConfigureAwait(false); - - return result != null; + return await GetAsync(key, ct).ConfigureAwait(false) != null; } /// diff --git a/src/SharpConnector/Connectors/Couchbase/CouchbaseWrapper.cs b/src/SharpConnector/Connectors/Couchbase/CouchbaseWrapper.cs index 4b7bdc9..7ef5280 100644 --- a/src/SharpConnector/Connectors/Couchbase/CouchbaseWrapper.cs +++ b/src/SharpConnector/Connectors/Couchbase/CouchbaseWrapper.cs @@ -5,6 +5,7 @@ using Couchbase.Query; using SharpConnector.Configuration; using SharpConnector.Entities; +using SharpConnector.Utilities; using System; using System.Collections.Generic; using System.Linq; @@ -86,6 +87,9 @@ public async Task InsertAsync(ConnectorEntity entity, CancellationToken ct { var collection = await GetCollectionAsync(ct).ConfigureAwait(false); var options = new UpsertOptions().CancellationToken(ct); + var ttl = entity.RemainingTimeToLive(); + if (ttl.HasValue) + options = options.Expiry(ttl.Value); var result = await collection.UpsertAsync(entity.Key, entity, options).ConfigureAwait(false); return result is not null; } diff --git a/src/SharpConnector/Connectors/DynamoDB/DynamoDbWrapper.cs b/src/SharpConnector/Connectors/DynamoDB/DynamoDbWrapper.cs index ba88897..18146b5 100644 --- a/src/SharpConnector/Connectors/DynamoDB/DynamoDbWrapper.cs +++ b/src/SharpConnector/Connectors/DynamoDB/DynamoDbWrapper.cs @@ -4,6 +4,7 @@ using Newtonsoft.Json; using SharpConnector.Configuration; using SharpConnector.Entities; +using SharpConnector.Utilities; using System; using System.Collections.Generic; using System.Linq; @@ -40,7 +41,7 @@ public ConnectorEntity Get(string key) { var document = _table.GetItemAsync(key).GetAwaiter().GetResult(); return document != null - ? JsonConvert.DeserializeObject(document.ToJson()) + ? JsonConvert.DeserializeObject(document.ToJson()).DiscardIfExpired() : null; } @@ -53,7 +54,7 @@ public async Task GetAsync(string key, CancellationToken ct = d { var document = await _table.GetItemAsync(key, ct).ConfigureAwait(false); return document != null - ? JsonConvert.DeserializeObject(document.ToJson()) + ? JsonConvert.DeserializeObject(document.ToJson()).DiscardIfExpired() : null; } @@ -69,8 +70,9 @@ public IEnumerable GetAll() do { var documents = search.GetNextSetAsync().GetAwaiter().GetResult(); - result.AddRange(documents.Select(doc => - JsonConvert.DeserializeObject(doc.ToJson()))); + result.AddRange(documents + .Select(doc => JsonConvert.DeserializeObject(doc.ToJson())) + .WhereNotExpired()); } while (!search.IsDone); return result; @@ -90,8 +92,9 @@ public async Task> GetAllAsync(CancellationToken ct { ct.ThrowIfCancellationRequested(); var documents = await search.GetNextSetAsync(ct).ConfigureAwait(false); - result.AddRange(documents.Select(doc => - JsonConvert.DeserializeObject(doc.ToJson()))); + result.AddRange(documents + .Select(doc => JsonConvert.DeserializeObject(doc.ToJson())) + .WhereNotExpired()); } while (!search.IsDone); return result; @@ -222,8 +225,7 @@ public Task UpdateAsync(ConnectorEntity connectorEntity, CancellationToken /// The unique key of the item. public bool Exists(string key) { - var document = _table.GetItemAsync(key).GetAwaiter().GetResult(); - return document != null; + return Get(key) != null; } /// @@ -233,8 +235,7 @@ public bool Exists(string key) /// A token to cancel the asynchronous operation. public async Task ExistsAsync(string key, CancellationToken ct = default) { - var document = await _table.GetItemAsync(key, ct).ConfigureAwait(false); - return document != null; + return await GetAsync(key, ct).ConfigureAwait(false) != null; } /// diff --git a/src/SharpConnector/Connectors/LiteDb/LiteDbAccess.cs b/src/SharpConnector/Connectors/LiteDb/LiteDbAccess.cs index be87538..397664f 100755 --- a/src/SharpConnector/Connectors/LiteDb/LiteDbAccess.cs +++ b/src/SharpConnector/Connectors/LiteDb/LiteDbAccess.cs @@ -10,6 +10,7 @@ namespace SharpConnector.Connectors.LiteDb public class LiteDbAccess : IDisposable { public ILiteCollection Collection { get; } + public ILiteCollection RawCollection { get; } private readonly LiteDatabase _liteDatabase; private bool _disposed; @@ -28,6 +29,7 @@ public LiteDbAccess(LiteDbConfig liteDbConfig) _liteDatabase = new LiteDatabase(liteDbConfig.ConnectionString); var collectionName = liteDbConfig.CollectionName; Collection = _liteDatabase.GetCollection(collectionName); + RawCollection = _liteDatabase.GetCollection(Collection.Name); } /// diff --git a/src/SharpConnector/Connectors/LiteDb/LiteDbWrapper.cs b/src/SharpConnector/Connectors/LiteDb/LiteDbWrapper.cs index 76728ff..450b3e7 100755 --- a/src/SharpConnector/Connectors/LiteDb/LiteDbWrapper.cs +++ b/src/SharpConnector/Connectors/LiteDb/LiteDbWrapper.cs @@ -2,6 +2,7 @@ // This code is licensed under MIT license (see LICENSE.txt for details) using SharpConnector.Configuration; using SharpConnector.Entities; +using SharpConnector.Utilities; using System.Linq; using System.Threading.Tasks; using LiteDB; @@ -41,7 +42,8 @@ public LiteDbConnectorEntity Get(string key) { return _liteDbAccess.Collection .Find(LiteDB.Query.EQ("Key", new BsonValue(key))) - .FirstOrDefault(); + .FirstOrDefault() + .DiscardIfExpired(); } /// @@ -62,7 +64,7 @@ public Task GetAsync(string key, CancellationToken ct = d /// public IEnumerable GetAll() { - return _liteDbAccess.Collection.Find(_ => true).ToList(); + return _liteDbAccess.Collection.Find(_ => true).WhereNotExpired().ToList(); } /// @@ -151,7 +153,15 @@ public Task DeleteAsync(string key, CancellationToken ct = default) /// The entity to update. public bool Update(LiteDbConnectorEntity connectorEntity) { - return _liteDbAccess.Collection.Update(connectorEntity); + ArgumentNullException.ThrowIfNull(connectorEntity); + + // Entities are identified by Key, not by the LiteDB _id: resolve the _id from the Key field. + var keyExpr = LiteDB.Query.EQ("Key", new BsonValue(connectorEntity.Key)); + var existing = _liteDbAccess.RawCollection.FindOne(keyExpr); + if (existing == null) + return false; + + return _liteDbAccess.Collection.Update(existing["_id"], connectorEntity); } /// @@ -173,7 +183,7 @@ public Task UpdateAsync(LiteDbConnectorEntity connectorEntity, Cancellatio /// The unique key of the item. public bool Exists(string key) { - return _liteDbAccess.Collection.Exists(LiteDB.Query.EQ("Key", new BsonValue(key))); + return Get(key) != null; } /// @@ -196,8 +206,7 @@ public Task ExistsAsync(string key, CancellationToken ct = default) /// A list of filtered ConnectorEntity instances. public List Query(Func filter) { - return _liteDbAccess.Collection - .FindAll() + return GetAll() .Cast() .Where(filter) .ToList(); diff --git a/src/SharpConnector/Connectors/MongoDb/MongoDbWrapper.cs b/src/SharpConnector/Connectors/MongoDb/MongoDbWrapper.cs index faa86ec..934b5c9 100755 --- a/src/SharpConnector/Connectors/MongoDb/MongoDbWrapper.cs +++ b/src/SharpConnector/Connectors/MongoDb/MongoDbWrapper.cs @@ -3,6 +3,7 @@ using MongoDB.Driver; using SharpConnector.Configuration; using SharpConnector.Entities; +using SharpConnector.Utilities; using System; using System.Collections.Generic; using System.Linq; @@ -43,7 +44,8 @@ public MongoConnectorEntity Get(string key) return _mongoDbAccess.Collection .Find(filter) - .FirstOrDefault(); + .FirstOrDefault() + .DiscardIfExpired(); } /// @@ -55,10 +57,12 @@ public async Task GetAsync(string key, CancellationToken c { var filter = Builders.Filter.Eq(x => x.Key, key); - return await _mongoDbAccess.Collection + var entity = await _mongoDbAccess.Collection .Find(filter) .FirstOrDefaultAsync(ct) .ConfigureAwait(false); + + return entity.DiscardIfExpired(); } /// @@ -68,6 +72,8 @@ public List GetAll() { return _mongoDbAccess.Collection .Find(FilterDefinition.Empty) + .ToList() + .WhereNotExpired() .ToList(); } @@ -77,10 +83,12 @@ public List GetAll() /// A token to cancel the asynchronous operation. public async Task> GetAllAsync(CancellationToken ct = default) { - return await _mongoDbAccess.Collection + var entities = await _mongoDbAccess.Collection .Find(FilterDefinition.Empty) .ToListAsync(ct) .ConfigureAwait(false); + + return entities.WhereNotExpired().ToList(); } /// @@ -180,7 +188,8 @@ public bool Update(MongoConnectorEntity connectorEntity) var filter = Builders.Filter.Eq(x => x.Key, connectorEntity.Key); var update = Builders.Update .Set(x => x.Payload, connectorEntity.Payload) - .Set(x => x.Expiration, connectorEntity.Expiration); + .Set(x => x.Expiration, connectorEntity.Expiration) + .Set(x => x.ExpiresAt, connectorEntity.ExpiresAt); var result = _mongoDbAccess.Collection.UpdateOne(filter, update); return result.IsAcknowledged && result.ModifiedCount > 0; @@ -197,7 +206,8 @@ public async Task UpdateAsync(MongoConnectorEntity connectorEntity, Cancel var filter = Builders.Filter.Eq(x => x.Key, connectorEntity.Key); var update = Builders.Update .Set(x => x.Payload, connectorEntity.Payload) - .Set(x => x.Expiration, connectorEntity.Expiration); + .Set(x => x.Expiration, connectorEntity.Expiration) + .Set(x => x.ExpiresAt, connectorEntity.ExpiresAt); var result = await _mongoDbAccess.Collection .UpdateOneAsync(filter, update, options: null, ct) @@ -212,10 +222,7 @@ public async Task UpdateAsync(MongoConnectorEntity connectorEntity, Cancel /// The unique key of the item. public bool Exists(string key) { - var filter = Builders.Filter.Eq(x => x.Key, key); - return _mongoDbAccess.Collection - .Find(filter) - .Any(); + return Get(key) != null; } /// @@ -226,11 +233,7 @@ public bool Exists(string key) /// True if the item exists; otherwise, false. public async Task ExistsAsync(string key, CancellationToken ct = default) { - var filter = Builders.Filter.Eq(x => x.Key, key); - return await _mongoDbAccess.Collection - .Find(filter) - .AnyAsync(ct) - .ConfigureAwait(false); + return await GetAsync(key, ct).ConfigureAwait(false) != null; } /// @@ -240,8 +243,7 @@ public async Task ExistsAsync(string key, CancellationToken ct = default) /// A collection of filtered instances. public List Query(Func filter) { - return _mongoDbAccess.Collection - .AsQueryable() + return GetAll() .Where(filter) .ToList(); } @@ -254,10 +256,7 @@ public List Query(Func filter) /// A task whose result is a collection of filtered instances. public async Task> QueryAsync(Func filter, CancellationToken ct = default) { - var allDocuments = await _mongoDbAccess.Collection - .Find(FilterDefinition.Empty) - .ToListAsync(ct) - .ConfigureAwait(false); + var allDocuments = await GetAllAsync(ct).ConfigureAwait(false); return allDocuments .Where(filter) diff --git a/src/SharpConnector/Connectors/RavenDb/RavenDbWrapper.cs b/src/SharpConnector/Connectors/RavenDb/RavenDbWrapper.cs index 95aac72..b66cb44 100755 --- a/src/SharpConnector/Connectors/RavenDb/RavenDbWrapper.cs +++ b/src/SharpConnector/Connectors/RavenDb/RavenDbWrapper.cs @@ -3,6 +3,7 @@ using Raven.Client.Documents; using SharpConnector.Configuration; using SharpConnector.Entities; +using SharpConnector.Utilities; using System; using System.Collections.Generic; using System.Linq; @@ -41,7 +42,7 @@ public ConnectorEntity Get(string key) { using (var session = _ravenDbAccess.Store.OpenSession()) { - return session.Load(key); + return session.Load(key).DiscardIfExpired(); } } @@ -54,7 +55,8 @@ public async Task GetAsync(string key, CancellationToken ct = d { using (var session = _ravenDbAccess.Store.OpenAsyncSession()) { - return await session.LoadAsync(key, ct).ConfigureAwait(false); + var entity = await session.LoadAsync(key, ct).ConfigureAwait(false); + return entity.DiscardIfExpired(); } } @@ -68,6 +70,8 @@ public List GetAll() return session .Query() .Customize(cr => cr.WaitForNonStaleResults()) + .ToList() + .WhereNotExpired() .ToList(); } } @@ -81,11 +85,13 @@ public async Task> GetAllAsync(CancellationToken ct = defa { using (var session = _ravenDbAccess.Store.OpenAsyncSession()) { - return await session + var entities = await session .Query() .Customize(cr => cr.WaitForNonStaleResults()) .ToListAsync(ct) .ConfigureAwait(false); + + return entities.WhereNotExpired().ToList(); } } @@ -205,6 +211,7 @@ public bool Update(ConnectorEntity connectorEntity) if (entity == null) return false; entity.Payload = connectorEntity.Payload; entity.Expiration = connectorEntity.Expiration; + entity.ExpiresAt = connectorEntity.ExpiresAt; session.SaveChanges(); } return true; @@ -223,6 +230,7 @@ public async Task UpdateAsync(ConnectorEntity connectorEntity, Cancellatio if (entity == null) return false; entity.Payload = connectorEntity.Payload; entity.Expiration = connectorEntity.Expiration; + entity.ExpiresAt = connectorEntity.ExpiresAt; await session.SaveChangesAsync(ct).ConfigureAwait(false); } return true; @@ -238,7 +246,7 @@ public bool Exists(string key) using (var session = _ravenDbAccess.Store.OpenSession()) { var entity = session.Load(key); - return entity != null; + return entity.DiscardIfExpired() != null; } } @@ -253,7 +261,7 @@ public async Task ExistsAsync(string key, CancellationToken ct = default) using (var session = _ravenDbAccess.Store.OpenAsyncSession()) { var entity = await session.LoadAsync(key, ct).ConfigureAwait(false); - return entity != null; + return entity.DiscardIfExpired() != null; } } @@ -264,14 +272,7 @@ public async Task ExistsAsync(string key, CancellationToken ct = default) /// A collection of filtered instances. public IEnumerable Query(Func filter) { - using (var session = _ravenDbAccess.Store.OpenSession()) - { - return session - .Query() - .Customize(cr => cr.WaitForNonStaleResults()) - .Where(filter) - .ToList(); - } + return GetAll().Where(filter).ToList(); } /// @@ -282,16 +283,8 @@ public IEnumerable Query(Func filter) /// A task whose result is a collection of filtered instances. public async Task> QueryAsync(Func filter, CancellationToken ct = default) { - using (var session = _ravenDbAccess.Store.OpenAsyncSession()) - { - var allEntities = await session - .Query() - .Customize(cr => cr.WaitForNonStaleResults()) - .ToListAsync(ct) - .ConfigureAwait(false); - - return allEntities.Where(filter); - } + var allEntities = await GetAllAsync(ct).ConfigureAwait(false); + return allEntities.Where(filter); } } } \ No newline at end of file diff --git a/src/SharpConnector/Connectors/Redis/RedisWrapper.cs b/src/SharpConnector/Connectors/Redis/RedisWrapper.cs index edf960b..d61f1a4 100755 --- a/src/SharpConnector/Connectors/Redis/RedisWrapper.cs +++ b/src/SharpConnector/Connectors/Redis/RedisWrapper.cs @@ -101,7 +101,17 @@ public IEnumerable GetAll(int databaseNumber = 0) foreach (var key in keys) { - var value = database.StringGet(key); + RedisValue value; + try + { + value = database.StringGet(key); + } + catch (RedisServerException ex) when (IsWrongType(ex)) + { + // Key holds a non-string value not produced by SharpConnector; skip it. + continue; + } + if (!value.HasValue) continue; @@ -153,15 +163,29 @@ public async Task> GetAllAsync(int databaseNumber = private static async Task GetEntityAsync(IDatabase database, RedisKey key, CancellationToken ct) { ct.ThrowIfCancellationRequested(); - var value = await database.StringGetAsync(key).ConfigureAwait(false); - return value.HasValue ? TryDeserialize(value) : null; + try + { + var value = await database.StringGetAsync(key).ConfigureAwait(false); + return value.HasValue ? TryDeserialize(value) : null; + } + catch (RedisServerException ex) when (IsWrongType(ex)) + { + // Key holds a non-string value not produced by SharpConnector; skip it. + return null; + } } + /// + /// Returns true when the Redis error indicates an operation against a key holding the wrong kind of value. + /// + internal static bool IsWrongType(RedisServerException ex) => + ex?.Message != null && ex.Message.StartsWith("WRONGTYPE", StringComparison.Ordinal); + /// /// Attempts to deserialize a value into a . /// Returns null when the value is not a valid ConnectorEntity payload. /// - private static ConnectorEntity TryDeserialize(RedisValue value) + internal static ConnectorEntity TryDeserialize(RedisValue value) { try { diff --git a/src/SharpConnector/Entities/ArangoConnectorEntity.cs b/src/SharpConnector/Entities/ArangoConnectorEntity.cs new file mode 100644 index 0000000..01089c3 --- /dev/null +++ b/src/SharpConnector/Entities/ArangoConnectorEntity.cs @@ -0,0 +1,35 @@ +// (c) 2025 Francesco Del Re +// This code is licensed under MIT license (see LICENSE.txt for details) +using Newtonsoft.Json; +using System; + +namespace SharpConnector.Entities +{ + /// + /// An ArangoDB-specific wrapper for ConnectorEntity that maps + /// to the ArangoDB document key (_key), so documents can be addressed by Key. + /// + public class ArangoConnectorEntity : ConnectorEntity + { + public ArangoConnectorEntity() { } + + public ArangoConnectorEntity(ConnectorEntity source) + { + ArgumentNullException.ThrowIfNull(source); + Key = source.Key; + Payload = source.Payload; + Expiration = source.Expiration; + ExpiresAt = source.ExpiresAt; + } + + /// + /// The ArangoDB document key, always equal to . + /// + [JsonProperty("_key")] + public string DocumentKey + { + get => Key; + set => Key ??= value; + } + } +} diff --git a/src/SharpConnector/Entities/ConnectorEntity.cs b/src/SharpConnector/Entities/ConnectorEntity.cs index 5600aaf..ec5c54c 100755 --- a/src/SharpConnector/Entities/ConnectorEntity.cs +++ b/src/SharpConnector/Entities/ConnectorEntity.cs @@ -29,6 +29,18 @@ public class ConnectorEntity /// public TimeSpan? Expiration { get; set; } + /// + /// The absolute UTC instant after which the entity is considered expired. + /// Computed from when the entity is created. + /// + public DateTime? ExpiresAt { get; set; } + + /// + /// Returns true if the entity has an absolute expiration that is already elapsed. + /// + public bool IsExpired() => + ExpiresAt.HasValue && ExpiresAt.Value.ToUniversalTime() <= DateTime.UtcNow; + /// /// Default constructor for serialization purposes. /// @@ -55,6 +67,7 @@ public ConnectorEntity(string key, object payload, TimeSpan? expiration) Key = key; Payload = payload; Expiration = expiration; + ExpiresAt = expiration.HasValue ? DateTime.UtcNow.Add(expiration.Value) : null; } /// diff --git a/src/SharpConnector/Operations/RedisOperations.cs b/src/SharpConnector/Operations/RedisOperations.cs index 119de64..96af301 100755 --- a/src/SharpConnector/Operations/RedisOperations.cs +++ b/src/SharpConnector/Operations/RedisOperations.cs @@ -1,4 +1,4 @@ -// (c) 2020 Francesco Del Re +// (c) 2020 Francesco Del Re // This code is licensed under MIT license (see LICENSE.txt for details) using System; using System.Collections.Generic; @@ -15,6 +15,7 @@ namespace SharpConnector.Operations public class RedisOperations : Operations { private readonly RedisWrapper _redisWrapper; + private readonly int _databaseNumber; /// /// Create a new RedisOperations instance. @@ -23,6 +24,7 @@ public class RedisOperations : Operations public RedisOperations(RedisConfig redisConfig) { _redisWrapper = new RedisWrapper(redisConfig); + _databaseNumber = redisConfig.DatabaseNumber; } /// @@ -31,7 +33,7 @@ public RedisOperations(RedisConfig redisConfig) /// The key of the object. public override T Get(string key) { - var connectorEntity = _redisWrapper.Get(key); + var connectorEntity = _redisWrapper.Get(key, _databaseNumber); if (connectorEntity != null) return connectorEntity.ToPayloadObject(); return default; @@ -44,7 +46,7 @@ public override T Get(string key) /// A token to cancel the asynchronous operation. public override async Task GetAsync(string key, CancellationToken ct = default) { - var connectorEntity = await _redisWrapper.GetAsync(key, 0, ct).ConfigureAwait(false); + var connectorEntity = await _redisWrapper.GetAsync(key, _databaseNumber, ct).ConfigureAwait(false); if (connectorEntity != null) return connectorEntity.ToPayloadObject(); return default; @@ -55,7 +57,7 @@ public override async Task GetAsync(string key, CancellationToken ct = defaul /// public override IEnumerable GetAll() { - var connectorEntities = _redisWrapper.GetAll(); + var connectorEntities = _redisWrapper.GetAll(_databaseNumber); return connectorEntities?.ToPayloadList() ?? []; } @@ -67,7 +69,7 @@ public override IEnumerable GetAll() public override bool Insert(string key, T value) { var connectorEntity = new ConnectorEntity(key, value, null); - return _redisWrapper.Insert(connectorEntity); + return _redisWrapper.Insert(connectorEntity, _databaseNumber); } /// @@ -81,7 +83,7 @@ public override bool Insert(string key, T value, TimeSpan expiration) if (expiration <= TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(expiration), "Expiration must be greater than zero."); var connectorEntity = new ConnectorEntity(key, value, expiration); - return _redisWrapper.Insert(connectorEntity); + return _redisWrapper.Insert(connectorEntity, _databaseNumber); } /// @@ -94,7 +96,7 @@ public override async Task InsertAsync(string key, T value, CancellationTo { var connectorEntity = new ConnectorEntity(key, value, null); return await _redisWrapper - .InsertAsync(connectorEntity, 0, ct) + .InsertAsync(connectorEntity, _databaseNumber, ct) .ConfigureAwait(false); } @@ -111,7 +113,7 @@ public override async Task InsertAsync(string key, T value, TimeSpan expir throw new ArgumentOutOfRangeException(nameof(expiration), "Expiration must be greater than zero."); var connectorEntity = new ConnectorEntity(key, value, expiration); return await _redisWrapper - .InsertAsync(connectorEntity, 0, ct) + .InsertAsync(connectorEntity, _databaseNumber, ct) .ConfigureAwait(false); } @@ -121,7 +123,7 @@ public override async Task InsertAsync(string key, T value, TimeSpan expir /// The values to store. public override bool InsertMany(Dictionary values) { - return _redisWrapper.InsertMany(values.ToConnectorEntityList()); + return _redisWrapper.InsertMany(values.ToConnectorEntityList(), _databaseNumber); } /// @@ -131,7 +133,7 @@ public override bool InsertMany(Dictionary values) /// The expiration of the keys. public override bool InsertMany(Dictionary values, TimeSpan expiration) { - return _redisWrapper.InsertMany(values.ToConnectorEntityList(expiration)); + return _redisWrapper.InsertMany(values.ToConnectorEntityList(expiration), _databaseNumber); } /// @@ -147,7 +149,7 @@ public override async Task> InsertManyAsync(IEnumera ArgumentNullException.ThrowIfNull(values); var list = values.Select(v => new ConnectorEntity(Guid.NewGuid().ToString(), v, null)).ToList(); var success = await _redisWrapper - .InsertManyAsync(list, 0, ct) + .InsertManyAsync(list, _databaseNumber, ct) .ConfigureAwait(false); return success ? list.Select(e => e.Key).ToList().AsReadOnly() @@ -160,7 +162,7 @@ public override async Task> InsertManyAsync(IEnumera /// The key of the object. public override bool Delete(string key) { - return _redisWrapper.Delete(key); + return _redisWrapper.Delete(key, _databaseNumber); } /// @@ -171,7 +173,7 @@ public override bool Delete(string key) public override async Task DeleteAsync(string key, CancellationToken ct = default) { return await _redisWrapper - .DeleteAsync(key, 0, ct) + .DeleteAsync(key, _databaseNumber, ct) .ConfigureAwait(false); } @@ -183,7 +185,7 @@ public override async Task DeleteAsync(string key, CancellationToken ct = public override bool Update(string key, T value) { var connectorEntity = new ConnectorEntity(key, value, null); - return _redisWrapper.Update(connectorEntity); + return _redisWrapper.Update(connectorEntity, _databaseNumber); } /// @@ -196,7 +198,7 @@ public override async Task UpdateAsync(string key, T value, CancellationTo { var connectorEntity = new ConnectorEntity(key, value, null); return await _redisWrapper - .UpdateAsync(connectorEntity, 0, ct) + .UpdateAsync(connectorEntity, _databaseNumber, ct) .ConfigureAwait(false); } @@ -208,7 +210,7 @@ public override async Task UpdateAsync(string key, T value, CancellationTo public override async Task> GetAllAsync(CancellationToken ct = default) { var connectorEntities = await _redisWrapper - .GetAllAsync(0, ct) + .GetAllAsync(_databaseNumber, ct) .ConfigureAwait(false); return connectorEntities?.ToPayloadList() ?? []; @@ -220,7 +222,7 @@ public override async Task> GetAllAsync(CancellationToken ct = de /// The unique key of the item. public override bool Exists(string key) { - return _redisWrapper.Exists(key); + return _redisWrapper.Exists(key, _databaseNumber); } /// @@ -231,7 +233,7 @@ public override bool Exists(string key) public override async Task ExistsAsync(string key, CancellationToken ct = default) { return await _redisWrapper - .ExistsAsync(key, 0, ct) + .ExistsAsync(key, _databaseNumber, ct) .ConfigureAwait(false); } @@ -242,7 +244,7 @@ public override async Task ExistsAsync(string key, CancellationToken ct = public override IEnumerable Query(Func filter) { return _redisWrapper - .Query(e => filter(e.ToPayloadObject())) + .Query(e => filter(e.ToPayloadObject()), _databaseNumber) .Select(e => e.ToPayloadObject()); } @@ -254,7 +256,7 @@ public override IEnumerable Query(Func filter) public override async Task> QueryAsync(Func filter, CancellationToken ct = default) { var result = await _redisWrapper - .QueryAsync(e => filter(e.ToPayloadObject()), 0, ct) + .QueryAsync(e => filter(e.ToPayloadObject()), _databaseNumber, ct) .ConfigureAwait(false); return result.Select(e => e.ToPayloadObject()); @@ -278,7 +280,7 @@ public override async Task InsertManyAsync(Dictionary values, C { var entities = values.ToConnectorEntityList(); return await _redisWrapper - .InsertManyAsync(entities, 0, ct) + .InsertManyAsync(entities, _databaseNumber, ct) .ConfigureAwait(false); } @@ -303,7 +305,7 @@ public override async Task InsertManyAsync(Dictionary values, T { var entities = values.ToConnectorEntityList(expiration); return await _redisWrapper - .InsertManyAsync(entities, 0, ct) + .InsertManyAsync(entities, _databaseNumber, ct) .ConfigureAwait(false); } diff --git a/src/SharpConnector/SharpConnector.csproj b/src/SharpConnector/SharpConnector.csproj index c9c3e08..592f92b 100755 --- a/src/SharpConnector/SharpConnector.csproj +++ b/src/SharpConnector/SharpConnector.csproj @@ -35,6 +35,10 @@ + + + + True diff --git a/src/SharpConnector/Utilities/ExpirationHelper.cs b/src/SharpConnector/Utilities/ExpirationHelper.cs new file mode 100644 index 0000000..3f4740a --- /dev/null +++ b/src/SharpConnector/Utilities/ExpirationHelper.cs @@ -0,0 +1,38 @@ +// (c) 2020 Francesco Del Re +// This code is licensed under MIT license (see LICENSE.txt for details) +using SharpConnector.Entities; +using System; +using System.Collections.Generic; +using System.Linq; + +namespace SharpConnector.Utilities +{ + /// + /// Helpers for handling entity expiration consistently across connectors. + /// + public static class ExpirationHelper + { + /// + /// Returns null if the entity is expired; otherwise the entity itself. + /// + public static T DiscardIfExpired(this T entity) where T : ConnectorEntity => + entity == null || entity.IsExpired() ? null : entity; + + /// + /// Filters out null and expired entities. + /// + public static IEnumerable WhereNotExpired(this IEnumerable entities) where T : ConnectorEntity => + entities?.Where(e => e != null && !e.IsExpired()) ?? []; + + /// + /// Returns the TTL to apply to a native expiring store, or null when the entity never expires. + /// + public static TimeSpan? RemainingTimeToLive(this ConnectorEntity entity) + { + if (entity?.ExpiresAt == null) + return entity?.Expiration; + var remaining = entity.ExpiresAt.Value.ToUniversalTime() - DateTime.UtcNow; + return remaining > TimeSpan.Zero ? remaining : TimeSpan.FromMilliseconds(1); + } + } +} From ba1a00060871051e9f768f6a29d857c10db3e0a6 Mon Sep 17 00:00:00 2001 From: Francesco Del Re Date: Wed, 28 Oct 2026 00:13:37 +0100 Subject: [PATCH 5/7] fix!: align CRUD semantics across connectors and fix medium-severity issues --- README.md | 19 +- .../CassandraConfigTests.cs | 2 +- src/SharpConnector.Tests/ConverterTests.cs | 8 +- .../MediumSeverityFixesTests.cs | 195 ++++++++++++++++++ .../Configuration/ArangoDbConfig.cs | 4 +- .../Configuration/CassandraConfig.cs | 2 +- .../Configuration/CouchbaseConfig.cs | 4 +- .../Connectors/ArangoDb/ArangoDbWrapper.cs | 12 +- .../Connectors/Cassandra/CassandraAccess.cs | 96 ++++++--- .../Connectors/Cassandra/CassandraWrapper.cs | 113 ++++++---- .../Connectors/Couchbase/CouchbaseAccess.cs | 37 +++- .../Connectors/Couchbase/CouchbaseWrapper.cs | 23 ++- .../Connectors/DynamoDB/DynamoDbWrapper.cs | 44 +++- .../Connectors/LiteDb/LiteDbAccess.cs | 1 + .../Connectors/LiteDb/LiteDbWrapper.cs | 26 ++- .../Connectors/Memcached/MemcachedAccess.cs | 43 +++- .../Connectors/Memcached/MemcachedWrapper.cs | 14 +- .../Connectors/MongoDb/MongoDbAccess.cs | 5 + .../Connectors/MongoDb/MongoDbWrapper.cs | 40 +++- .../Connectors/Redis/RedisWrapper.cs | 23 ++- .../Entities/ConnectorEntity.cs | 4 +- src/SharpConnector/Interfaces/IOperations.cs | 23 +-- .../Interfaces/ISharpConnectorClient.cs | 24 +-- .../SharpConnectorServiceExtensions.cs | 16 +- .../Operations/ArangoDbOperations.cs | 16 +- .../Operations/CouchbaseOperations.cs | 16 +- .../Operations/DynamoDbOperations.cs | 8 +- .../Operations/LiteDbOperations.cs | 8 +- .../Operations/MemcachedOperations.cs | 8 +- .../Operations/MongoDbOperations.cs | 8 +- .../Operations/RavenDbOperations.cs | 8 +- .../Operations/RedisOperations.cs | 4 +- src/SharpConnector/Utilities/Converter.cs | 55 +++-- 33 files changed, 673 insertions(+), 236 deletions(-) create mode 100644 src/SharpConnector.Tests/MediumSeverityFixesTests.cs diff --git a/README.md b/README.md index db987d7..7c3cfa1 100755 --- a/README.md +++ b/README.md @@ -128,7 +128,7 @@ Then, add the specif `ConnectorConfig` node within your *appsettings.json* file: "ConnectionString": "couchbase://localhost", "Username": "Administrator", "Password": "password", - "BucketName": "example_bucket", + "BucketName": "example_bucket" } } ``` @@ -178,7 +178,7 @@ Then, add the specif `ConnectorConfig` node within your *appsettings.json* file: Once configured, create a new SharpConnector client, specifying the payload type (e.g., string): ```csharp -SharpConnectorClient client = new SharpConnectorClient() +SharpConnectorClient client = new SharpConnectorClient(); ``` Alternatively, you can integrate SharpConnector client using dependency injection. Here how to register the SharpConnector service with a simple string payload type: @@ -187,6 +187,7 @@ Alternatively, you can integrate SharpConnector client using dependency injectio // Register the SharpConnector services with string payload type. builder.Services.AddSharpConnectorServices(); ``` +`AddSharpConnectorServices()` registers the client as a singleton (recommended). `AddSharpConnectorServicesScoped()` is also available, but it opens a new database connection for every scope. This setup provides flexibility in working with different payload types and makes SharpConnector easy to use within dependency injection configurations. ## API Overview @@ -201,7 +202,9 @@ The main entry point is the generic `ISharpConnectorClient`: - `Task InsertAsync(string key, T value, TimeSpan expiration, CancellationToken ct = default)` - `bool InsertMany(Dictionary values)` - `bool InsertMany(Dictionary values, TimeSpan expiration)` -- `Task InsertManyAsync(IEnumerable values, CancellationToken ct = default)` +- `Task InsertManyAsync(Dictionary values)` +- `Task InsertManyAsync(Dictionary values, TimeSpan expiration)` +- `Task> InsertManyAsync(IEnumerable values, CancellationToken ct = default)` - `bool Update(string key, T value)` - `Task UpdateAsync(string key, T value, CancellationToken ct = default)` - `bool Delete(string key)` @@ -211,6 +214,16 @@ The main entry point is the generic `ISharpConnectorClient`: - `IEnumerable Query(Func filter)` - `Task> QueryAsync(Func filter, CancellationToken ct = default)` +### Operation semantics +- `Insert` / `InsertMany` behave as an upsert: an existing key is overwritten (MongoDB and LiteDB enforce a unique index on `Key`). +- `Update` only modifies existing keys and returns `false` when the key does not exist. +- `Delete` returns `true` only when an item was actually removed. +- `InsertMany` throws `ArgumentException` when a key is null/empty or a value is null. +- Expired items are never returned by `Get`, `GetAll`, `Exists` or `Query`, even on backends without native TTL. +- `Username` is trimmed, `Password` is used verbatim. +- Cassandra `ConnectionString` accepts a comma-separated list of contact points (`host`, `host:port`, `[IPv6]:port`); all ports must match. +- Memcached `ConnectionString` accepts a comma-separated list of `host:port` servers. + ## Contributing Thanks for considering a contribution! Please fork, branch, and open a PR. - Add unit tests for new features or connectors diff --git a/src/SharpConnector.Tests/CassandraConfigTests.cs b/src/SharpConnector.Tests/CassandraConfigTests.cs index 0359705..2b00627 100644 --- a/src/SharpConnector.Tests/CassandraConfigTests.cs +++ b/src/SharpConnector.Tests/CassandraConfigTests.cs @@ -59,7 +59,7 @@ public void Ctor_TrimsWhitespace() Assert.AreEqual("ks", config.DatabaseName); Assert.AreEqual("tbl", config.TableName); Assert.AreEqual("user", config.Username); - Assert.AreEqual("pwd", config.Password); + Assert.AreEqual(" pwd ", config.Password); } [TestMethod] diff --git a/src/SharpConnector.Tests/ConverterTests.cs b/src/SharpConnector.Tests/ConverterTests.cs index c8cbebd..e9cbe0c 100644 --- a/src/SharpConnector.Tests/ConverterTests.cs +++ b/src/SharpConnector.Tests/ConverterTests.cs @@ -143,8 +143,6 @@ public void ToConnectorEntityList_ValidDictionary_ReturnsCorrectList() { { "key1", "value1" }, { "key2", "value2" }, - { "", "value3" }, // This should be ignored - { "key3", null } // This should be ignored }; // Act @@ -210,8 +208,6 @@ public void ToLiteDbConnectorEntityList_ValidDictionary_ReturnsCorrectList() { { "key1", "value1" }, { "key2", "value2" }, - { "", "value3" }, // This should be ignored - { "key3", null } // This should be ignored }; // Act @@ -259,9 +255,7 @@ public void ToMongoDbConnectorEntityList_ValidDictionary_ReturnsCorrectList() var dictionary = new Dictionary { { "key1", "value1" }, - { "key2", "value2" }, - { "", "value3" }, - { "key3", null } + { "key2", "value2" } }; var result = dictionary.ToMongoDbConnectorEntityList(); diff --git a/src/SharpConnector.Tests/MediumSeverityFixesTests.cs b/src/SharpConnector.Tests/MediumSeverityFixesTests.cs new file mode 100644 index 0000000..8023552 --- /dev/null +++ b/src/SharpConnector.Tests/MediumSeverityFixesTests.cs @@ -0,0 +1,195 @@ +// (c) 2020 Francesco Del Re +// This code is licensed under MIT license (see LICENSE.txt for details) +using Microsoft.Extensions.Configuration; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using MongoDB.Driver; +using SharpConnector.Configuration; +using SharpConnector.Connectors.Cassandra; +using SharpConnector.Connectors.LiteDb; +using SharpConnector.Connectors.Memcached; +using SharpConnector.Connectors.MongoDb; +using SharpConnector.Entities; +using SharpConnector.Utilities; +using System; +using System.Collections.Generic; +using System.Linq; + +namespace SharpConnector.Tests +{ + [TestClass] + public class MediumSeverityFixesTests + { + #region Cassandra + + [TestMethod] + public void Cassandra_ParseContactPoints_HostsWithSamePort() + { + var (hosts, port) = CassandraAccess.ParseContactPoints("h1:9042, h2:9042"); + + CollectionAssert.AreEqual(new[] { "h1", "h2" }, hosts); + Assert.AreEqual(9042, port); + } + + [TestMethod] + public void Cassandra_ParseContactPoints_BracketedIPv6WithPort() + { + var (hosts, port) = CassandraAccess.ParseContactPoints("[::1]:9043"); + + CollectionAssert.AreEqual(new[] { "::1" }, hosts); + Assert.AreEqual(9043, port); + } + + [TestMethod] + public void Cassandra_ParseContactPoints_BareIPv6_NoPort() + { + var (hosts, port) = CassandraAccess.ParseContactPoints("fe80::1"); + + CollectionAssert.AreEqual(new[] { "fe80::1" }, hosts); + Assert.IsNull(port); + } + + [TestMethod] + public void Cassandra_ParseContactPoints_DifferentPorts_Throws() + { + Assert.ThrowsExactly(() => CassandraAccess.ParseContactPoints("h1:9042,h2:9043")); + } + + [TestMethod] + public void Cassandra_ParseContactPoints_InvalidPort_Throws() + { + Assert.ThrowsExactly(() => CassandraAccess.ParseContactPoints("h1:abc")); + } + + [TestMethod] + public void Cassandra_ParseContactPoints_Empty_Throws() + { + Assert.ThrowsExactly(() => CassandraAccess.ParseContactPoints(" ")); + } + + [TestMethod] + public void Cassandra_ToTtlSeconds_HandlesEdgeCases() + { + Assert.AreEqual(0, CassandraWrapper.ToTtlSeconds(null)); + Assert.AreEqual(0, CassandraWrapper.ToTtlSeconds(TimeSpan.Zero)); + Assert.AreEqual(0, CassandraWrapper.ToTtlSeconds(TimeSpan.FromSeconds(-5))); + Assert.AreEqual(1, CassandraWrapper.ToTtlSeconds(TimeSpan.FromMilliseconds(10))); + Assert.AreEqual(60, CassandraWrapper.ToTtlSeconds(TimeSpan.FromMinutes(1))); + } + + #endregion + + #region MongoDB + + [TestMethod] + public void MongoDb_BuildUpsertRequests_CreatesOneUpsertPerEntity() + { + var entities = new[] + { + new MongoConnectorEntity("a", "1", null), + new MongoConnectorEntity("b", "2", null) + }; + + var requests = MongoDbWrapper.BuildUpsertRequests(entities); + + Assert.HasCount(2, requests); + Assert.IsTrue(requests.All(r => r is ReplaceOneModel { IsUpsert: true })); + } + + #endregion + + #region LiteDB + + private static LiteDbWrapper CreateLiteDbWrapper() => + new(new LiteDbConfig(BuildConfiguration(new() { ["connectionstring"] = ":memory:" }))); + + [TestMethod] + public void LiteDb_InsertSameKeyTwice_DoesNotCreateDuplicates() + { + using var wrapper = CreateLiteDbWrapper(); + + Assert.IsTrue(wrapper.Insert(new LiteDbConnectorEntity("k", "v1", null))); + Assert.IsTrue(wrapper.Insert(new LiteDbConnectorEntity("k", "v2", null))); + + Assert.HasCount(1, wrapper.GetAll()); + Assert.AreEqual("v2", wrapper.Get("k").Payload); + } + + #endregion + + #region Memcached + + [TestMethod] + public void Memcached_ParseServers_ValidConnectionString() + { + var servers = MemcachedAccess.ParseServers("host1:11211, host2:11212"); + + Assert.HasCount(2, servers); + Assert.AreEqual("host1", servers[0].Address); + Assert.AreEqual(11212, servers[1].Port); + } + + [TestMethod] + [DataRow(null)] + [DataRow("")] + [DataRow(" , ")] + public void Memcached_ParseServers_EmptyConnectionString_Throws(string connectionString) + { + Assert.ThrowsExactly(() => MemcachedAccess.ParseServers(connectionString)); + } + + [TestMethod] + [DataRow("host")] + [DataRow("host:abc")] + [DataRow(":11211")] + public void Memcached_ParseServers_InvalidSegment_Throws(string connectionString) + { + Assert.ThrowsExactly(() => MemcachedAccess.ParseServers(connectionString)); + } + + #endregion + + #region Configuration + + [TestMethod] + public void Configs_DoNotTrimPassword() + { + var configuration = BuildConfiguration(new() + { + ["ConnectorConfig:connectionString"] = "localhost", + ["ConnectorConfig:username"] = " user ", + ["ConnectorConfig:password"] = " p@ss " + }); + var section = configuration.GetSection("ConnectorConfig"); + + Assert.AreEqual(" p@ss ", new CouchbaseConfig(section).Password); + Assert.AreEqual(" p@ss ", new ArangoDbConfig(section).Password); + } + + #endregion + + #region Converter + + [TestMethod] + public void Converter_NullValue_Throws() + { + var values = new Dictionary { ["a"] = "1", ["b"] = null }; + + Assert.ThrowsExactly(() => values.ToConnectorEntityList()); + Assert.ThrowsExactly(() => values.ToLiteDbConnectorEntityList()); + Assert.ThrowsExactly(() => values.ToMongoDbConnectorEntityList()); + } + + [TestMethod] + public void Converter_EmptyKey_Throws() + { + var values = new Dictionary { [""] = "1" }; + + Assert.ThrowsExactly(() => values.ToConnectorEntityList()); + } + + #endregion + + private static IConfiguration BuildConfiguration(Dictionary values) => + new ConfigurationBuilder().AddInMemoryCollection(values).Build(); + } +} diff --git a/src/SharpConnector/Configuration/ArangoDbConfig.cs b/src/SharpConnector/Configuration/ArangoDbConfig.cs index f1bf35d..583d383 100644 --- a/src/SharpConnector/Configuration/ArangoDbConfig.cs +++ b/src/SharpConnector/Configuration/ArangoDbConfig.cs @@ -1,4 +1,4 @@ -// (c) 2025 Francesco Del Re +// (c) 2025 Francesco Del Re // This code is licensed under MIT license (see LICENSE.txt for details) using Microsoft.Extensions.Configuration; using SharpConnector.Enums; @@ -36,7 +36,7 @@ public ArangoDbConfig(IConfiguration configuration) ConnectionString = configuration[AppConfigParameterEnums.connectionstring.ToString()]?.Trim(); CollectionName = configuration[AppConfigParameterEnums.collectionname.ToString()]?.Trim(); Username = configuration[AppConfigParameterEnums.username.ToString()]?.Trim(); - Password = configuration[AppConfigParameterEnums.password.ToString()]?.Trim(); + Password = configuration[AppConfigParameterEnums.password.ToString()]; } } } diff --git a/src/SharpConnector/Configuration/CassandraConfig.cs b/src/SharpConnector/Configuration/CassandraConfig.cs index 463a746..4b397e8 100644 --- a/src/SharpConnector/Configuration/CassandraConfig.cs +++ b/src/SharpConnector/Configuration/CassandraConfig.cs @@ -49,7 +49,7 @@ public CassandraConfig(IConfiguration configuration) throw new ArgumentException("Cassandra TableName is required but was not found in configuration."); Username = configuration[AppConfigParameterEnums.username.ToString()]?.Trim(); - Password = configuration[AppConfigParameterEnums.password.ToString()]?.Trim(); + Password = configuration[AppConfigParameterEnums.password.ToString()]; } } } diff --git a/src/SharpConnector/Configuration/CouchbaseConfig.cs b/src/SharpConnector/Configuration/CouchbaseConfig.cs index 7dc1c64..fa17896 100644 --- a/src/SharpConnector/Configuration/CouchbaseConfig.cs +++ b/src/SharpConnector/Configuration/CouchbaseConfig.cs @@ -1,4 +1,4 @@ -// (c) 2020 Francesco Del Re +// (c) 2020 Francesco Del Re // This code is licensed under MIT license (see LICENSE.txt for details) using Microsoft.Extensions.Configuration; using SharpConnector.Enums; @@ -39,7 +39,7 @@ public CouchbaseConfig(IConfiguration configuration) ConnectionString = configuration[AppConfigParameterEnums.connectionstring.ToString()]?.Trim(); BucketName = configuration[AppConfigParameterEnums.bucketname.ToString()]?.Trim(); Username = configuration[AppConfigParameterEnums.username.ToString()]?.Trim(); - Password = configuration[AppConfigParameterEnums.password.ToString()]?.Trim(); + Password = configuration[AppConfigParameterEnums.password.ToString()]; } } } diff --git a/src/SharpConnector/Connectors/ArangoDb/ArangoDbWrapper.cs b/src/SharpConnector/Connectors/ArangoDb/ArangoDbWrapper.cs index 02337b6..e97aeee 100644 --- a/src/SharpConnector/Connectors/ArangoDb/ArangoDbWrapper.cs +++ b/src/SharpConnector/Connectors/ArangoDb/ArangoDbWrapper.cs @@ -1,4 +1,4 @@ -// (c) 2025 Francesco Del Re +// (c) 2025 Francesco Del Re // This code is licensed under MIT license (see LICENSE.txt for details) using ArangoDBNetStandard; using ArangoDBNetStandard.CollectionApi.Models; @@ -42,7 +42,11 @@ public async Task EnsureCollectionExistsAsync(CancellationToken ct = default) .GetCollectionsAsync() .ConfigureAwait(false); - if (!collections.Result.Any(c => c.Name == _collectionName)) + if (collections.Error) + throw new InvalidOperationException( + $"Unable to list ArangoDB collections (HTTP {collections.Code})."); + + if (!(collections.Result ?? []).Any(c => c.Name == _collectionName)) { ct.ThrowIfCancellationRequested(); @@ -162,7 +166,7 @@ public async Task InsertAsync(ConnectorEntity connectorEntity, Cancellatio ct.ThrowIfCancellationRequested(); var result = await _arangoDbAccess.Client.Document - .PostDocumentAsync(_collectionName, new ArangoConnectorEntity(connectorEntity), token: ct) + .PostDocumentAsync(_collectionName, new ArangoConnectorEntity(connectorEntity), new ArangoDBNetStandard.DocumentApi.Models.PostDocumentsQuery { OverwriteMode = ArangoDBNetStandard.DocumentApi.Models.OverwriteModes.Replace }, token: ct) .ConfigureAwait(false); return !string.IsNullOrEmpty(result._id); @@ -191,7 +195,7 @@ public async Task InsertManyAsync(List connectorEntities, var documents = connectorEntities.Select(e => new ArangoConnectorEntity(e)).ToList(); var result = await _arangoDbAccess.Client.Document - .PostDocumentsAsync(_collectionName, documents, token: ct) + .PostDocumentsAsync(_collectionName, documents, new ArangoDBNetStandard.DocumentApi.Models.PostDocumentsQuery { OverwriteMode = ArangoDBNetStandard.DocumentApi.Models.OverwriteModes.Replace }, token: ct) .ConfigureAwait(false); ct.ThrowIfCancellationRequested(); diff --git a/src/SharpConnector/Connectors/Cassandra/CassandraAccess.cs b/src/SharpConnector/Connectors/Cassandra/CassandraAccess.cs index da14030..3cc72d6 100644 --- a/src/SharpConnector/Connectors/Cassandra/CassandraAccess.cs +++ b/src/SharpConnector/Connectors/Cassandra/CassandraAccess.cs @@ -46,50 +46,90 @@ public CassandraAccess(CassandraConfig cassandraConfig) Cluster = builder.Build(); - // Ensure keyspace exists, then connect to it. - using (var bootstrapSession = Cluster.Connect()) + try { - bootstrapSession.Execute( - $"CREATE KEYSPACE IF NOT EXISTS {Keyspace} " + - "WITH replication = {'class':'SimpleStrategy','replication_factor':1};"); - } + // Ensure keyspace exists, then connect to it. + using (var bootstrapSession = Cluster.Connect()) + { + bootstrapSession.Execute( + $"CREATE KEYSPACE IF NOT EXISTS {Keyspace} " + + "WITH replication = {'class':'SimpleStrategy','replication_factor':1};"); + } - Session = Cluster.Connect(Keyspace); + Session = Cluster.Connect(Keyspace); - // Ensure the storage table exists. - Session.Execute( - $"CREATE TABLE IF NOT EXISTS {TableName} (" + - "key text PRIMARY KEY, " + - "payload text, " + - "expiration bigint);"); + // Ensure the storage table exists. + Session.Execute( + $"CREATE TABLE IF NOT EXISTS {TableName} (" + + "key text PRIMARY KEY, " + + "payload text, " + + "expiration bigint);"); + } + catch + { + Session?.Dispose(); + Cluster.Dispose(); + throw; + } } /// - /// Parses the contact points string in the form "host1,host2:9042". + /// Parses the contact points string in the form "host1,host2:9042,[::1]:9042". + /// Bare IPv6 addresses (e.g. "fe80::1") are supported; a port must be specified using brackets. /// - private static (string[] hosts, int? port) ParseContactPoints(string connectionString) + /// Thrown when the string is empty, a contact point or port is invalid, or hosts declare different ports. + internal static (string[] hosts, int? port) ParseContactPoints(string connectionString) { + if (string.IsNullOrWhiteSpace(connectionString)) + throw new ArgumentException("Cassandra connection string cannot be null or empty.", nameof(connectionString)); + var tokens = connectionString - .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries) - .Select(t => t.Trim()) - .Where(t => !string.IsNullOrEmpty(t)) - .ToArray(); + .Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); int? parsedPort = null; - var hosts = tokens.Select(t => + var hosts = new string[tokens.Length]; + for (var i = 0; i < tokens.Length; i++) { - var idx = t.LastIndexOf(':'); - if (idx > 0 && int.TryParse(t.Substring(idx + 1), out var p)) - { - parsedPort = p; - return t.Substring(0, idx); - } - return t; - }).ToArray(); + var (host, port) = ParseHost(tokens[i]); + hosts[i] = host; + if (!port.HasValue) + continue; + if (parsedPort.HasValue && parsedPort.Value != port.Value) + throw new ArgumentException("All Cassandra contact points must use the same port.", nameof(connectionString)); + parsedPort = port; + } return (hosts, parsedPort); } + private static (string host, int? port) ParseHost(string token) + { + // [IPv6]:port or [IPv6] + if (token.StartsWith('[')) + { + var end = token.IndexOf(']'); + if (end < 0) + throw new ArgumentException($"Invalid contact point '{token}'."); + var host = token[1..end]; + var rest = token[(end + 1)..]; + if (rest.Length == 0) + return (host, null); + if (rest[0] == ':' && int.TryParse(rest[1..], out var p6)) + return (host, p6); + throw new ArgumentException($"Invalid contact point '{token}'."); + } + + // More than one ':' without brackets: bare IPv6 address, no port. + var first = token.IndexOf(':'); + if (first < 0 || first != token.LastIndexOf(':')) + return (token, null); + + if (int.TryParse(token[(first + 1)..], out var p)) + return (token[..first], p); + + throw new ArgumentException($"Invalid port in contact point '{token}'."); + } + /// /// Disposes the underlying Cassandra session and cluster. /// diff --git a/src/SharpConnector/Connectors/Cassandra/CassandraWrapper.cs b/src/SharpConnector/Connectors/Cassandra/CassandraWrapper.cs index 09755ed..44a4d37 100644 --- a/src/SharpConnector/Connectors/Cassandra/CassandraWrapper.cs +++ b/src/SharpConnector/Connectors/Cassandra/CassandraWrapper.cs @@ -34,21 +34,29 @@ public CassandraWrapper(CassandraConfig cassandraConfig) { _cassandraAccess = new CassandraAccess(cassandraConfig); - var table = _cassandraAccess.TableName; - _getStatement = _cassandraAccess.Session.Prepare( - $"SELECT key, payload, expiration FROM {table} WHERE key = ?;"); - _getAllStatement = _cassandraAccess.Session.Prepare( - $"SELECT key, payload, expiration FROM {table};"); - _insertStatement = _cassandraAccess.Session.Prepare( - $"INSERT INTO {table} (key, payload, expiration) VALUES (?, ?, ?);"); - _insertStatementWithTtl = _cassandraAccess.Session.Prepare( - $"INSERT INTO {table} (key, payload, expiration) VALUES (?, ?, ?) USING TTL ?;"); - _updateStatement = _cassandraAccess.Session.Prepare( - $"UPDATE {table} SET payload = ?, expiration = ? WHERE key = ?;"); - _deleteStatement = _cassandraAccess.Session.Prepare( - $"DELETE FROM {table} WHERE key = ?;"); - _existsStatement = _cassandraAccess.Session.Prepare( - $"SELECT key FROM {table} WHERE key = ?;"); + try + { + var table = _cassandraAccess.TableName; + _getStatement = _cassandraAccess.Session.Prepare( + $"SELECT key, payload, expiration FROM {table} WHERE key = ?;"); + _getAllStatement = _cassandraAccess.Session.Prepare( + $"SELECT key, payload, expiration FROM {table};"); + _insertStatement = _cassandraAccess.Session.Prepare( + $"INSERT INTO {table} (key, payload, expiration) VALUES (?, ?, ?);"); + _insertStatementWithTtl = _cassandraAccess.Session.Prepare( + $"INSERT INTO {table} (key, payload, expiration) VALUES (?, ?, ?) USING TTL ?;"); + _updateStatement = _cassandraAccess.Session.Prepare( + $"UPDATE {table} USING TTL ? SET payload = ?, expiration = ? WHERE key = ? IF EXISTS;"); + _deleteStatement = _cassandraAccess.Session.Prepare( + $"DELETE FROM {table} WHERE key = ? IF EXISTS;"); + _existsStatement = _cassandraAccess.Session.Prepare( + $"SELECT key FROM {table} WHERE key = ?;"); + } + catch + { + _cassandraAccess.Dispose(); + throw; + } } /// @@ -106,12 +114,24 @@ public async Task> GetAllAsync(CancellationToken ct = defa { ct.ThrowIfCancellationRequested(); var rowSet = await _cassandraAccess.Session - .ExecuteAsync(_getAllStatement.Bind()) + .ExecuteAsync(_getAllStatement.Bind().SetAutoPage(false)) .ConfigureAwait(false); - return rowSet - .Select(MapRow) - .Where(e => e != null) - .ToList(); + + var result = new List(); + while (true) + { + ct.ThrowIfCancellationRequested(); + var available = rowSet.GetAvailableWithoutFetching(); + result.AddRange(rowSet.Take(available).Select(MapRow).Where(e => e != null)); + + if (rowSet.PagingState == null) + break; + + rowSet = await _cassandraAccess.Session + .ExecuteAsync(_getAllStatement.Bind().SetAutoPage(false).SetPagingState(rowSet.PagingState)) + .ConfigureAwait(false); + } + return result; } /// @@ -185,12 +205,8 @@ await _cassandraAccess.Session /// The entity to update. public bool Update(ConnectorEntity connectorEntity) { - var payload = SerializePayload(connectorEntity.Payload); - var expirationTicks = connectorEntity.Expiration?.Ticks ?? 0L; - - _cassandraAccess.Session.Execute( - _updateStatement.Bind(payload, expirationTicks, connectorEntity.Key)); - return true; + var rowSet = _cassandraAccess.Session.Execute(BuildUpdateStatement(connectorEntity)); + return IsApplied(rowSet); } /// @@ -201,13 +217,10 @@ public bool Update(ConnectorEntity connectorEntity) public async Task UpdateAsync(ConnectorEntity connectorEntity, CancellationToken ct = default) { ct.ThrowIfCancellationRequested(); - var payload = SerializePayload(connectorEntity.Payload); - var expirationTicks = connectorEntity.Expiration?.Ticks ?? 0L; - - await _cassandraAccess.Session - .ExecuteAsync(_updateStatement.Bind(payload, expirationTicks, connectorEntity.Key)) + var rowSet = await _cassandraAccess.Session + .ExecuteAsync(BuildUpdateStatement(connectorEntity)) .ConfigureAwait(false); - return true; + return IsApplied(rowSet); } /// @@ -216,8 +229,7 @@ await _cassandraAccess.Session /// The key of the object. public bool Delete(string key) { - _cassandraAccess.Session.Execute(_deleteStatement.Bind(key)); - return true; + return IsApplied(_cassandraAccess.Session.Execute(_deleteStatement.Bind(key))); } /// @@ -228,10 +240,34 @@ public bool Delete(string key) public async Task DeleteAsync(string key, CancellationToken ct = default) { ct.ThrowIfCancellationRequested(); - await _cassandraAccess.Session + var rowSet = await _cassandraAccess.Session .ExecuteAsync(_deleteStatement.Bind(key)) .ConfigureAwait(false); - return true; + return IsApplied(rowSet); + } + + private BoundStatement BuildUpdateStatement(ConnectorEntity entity) + { + var payload = SerializePayload(entity.Payload); + var expirationTicks = entity.Expiration?.Ticks ?? 0L; + // TTL 0 means "no expiration" in Cassandra. + return _updateStatement.Bind(ToTtlSeconds(entity.Expiration), payload, expirationTicks, entity.Key); + } + + /// + /// Converts an optional expiration into a Cassandra TTL in seconds (0 = no expiration). + /// + internal static int ToTtlSeconds(TimeSpan? expiration) + { + if (!expiration.HasValue || expiration.Value <= TimeSpan.Zero) + return 0; + return (int)Math.Max(1, Math.Min(int.MaxValue, Math.Ceiling(expiration.Value.TotalSeconds))); + } + + private static bool IsApplied(RowSet rowSet) + { + var row = rowSet?.FirstOrDefault(); + return row != null && row.GetValue("[applied]"); } /// @@ -256,7 +292,7 @@ public async Task ExistsAsync(string key, CancellationToken ct = default) var rowSet = await _cassandraAccess.Session .ExecuteAsync(_existsStatement.Bind(key)) .ConfigureAwait(false); - return rowSet.Any(); + return rowSet.FirstOrDefault() != null; } /// @@ -287,8 +323,7 @@ private BoundStatement BuildInsertStatement(ConnectorEntity entity) if (entity.Expiration.HasValue && entity.Expiration.Value > TimeSpan.Zero) { - var ttlSeconds = (int)Math.Max(1, Math.Min(int.MaxValue, entity.Expiration.Value.TotalSeconds)); - return _insertStatementWithTtl.Bind(entity.Key, payload, expirationTicks, ttlSeconds); + return _insertStatementWithTtl.Bind(entity.Key, payload, expirationTicks, ToTtlSeconds(entity.Expiration)); } return _insertStatement.Bind(entity.Key, payload, expirationTicks); diff --git a/src/SharpConnector/Connectors/Couchbase/CouchbaseAccess.cs b/src/SharpConnector/Connectors/Couchbase/CouchbaseAccess.cs index 14b5027..2e848bb 100644 --- a/src/SharpConnector/Connectors/Couchbase/CouchbaseAccess.cs +++ b/src/SharpConnector/Connectors/Couchbase/CouchbaseAccess.cs @@ -14,7 +14,8 @@ public class CouchbaseAccess : IAsyncDisposable private readonly Lazy> _cluster; private readonly string _bucketName; private readonly SemaphoreSlim _bucketLock = new(1, 1); - private IBucket _bucket; + private volatile IBucket _bucket; + private int _disposed; public CouchbaseAccess(CouchbaseConfig config) { @@ -41,8 +42,11 @@ public async Task GetClusterAsync() public async Task GetBucketAsync() { - if (_bucket != null) - return _bucket; + ObjectDisposedException.ThrowIf(Volatile.Read(ref _disposed) != 0, this); + + var bucket = _bucket; + if (bucket != null) + return bucket; await _bucketLock.WaitAsync().ConfigureAwait(false); try @@ -72,19 +76,30 @@ public async Task GetDefaultCollectionAsync() public async ValueTask DisposeAsync() { - if (_bucket != null) + if (Interlocked.Exchange(ref _disposed, 1) != 0) + return; + + await _bucketLock.WaitAsync().ConfigureAwait(false); + try { - await _bucket.DisposeAsync(); + var bucket = _bucket; _bucket = null; + if (bucket != null) + await bucket.DisposeAsync().ConfigureAwait(false); } - - if (_cluster.IsValueCreated) + finally { - var cluster = await _cluster.Value; - await cluster.DisposeAsync(); + try + { + if (_cluster.IsValueCreated && _cluster.Value.IsCompletedSuccessfully) + await _cluster.Value.Result.DisposeAsync().ConfigureAwait(false); + } + finally + { + _bucketLock.Release(); + _bucketLock.Dispose(); + } } - - _bucketLock.Dispose(); } } } diff --git a/src/SharpConnector/Connectors/Couchbase/CouchbaseWrapper.cs b/src/SharpConnector/Connectors/Couchbase/CouchbaseWrapper.cs index 7ef5280..7189d84 100644 --- a/src/SharpConnector/Connectors/Couchbase/CouchbaseWrapper.cs +++ b/src/SharpConnector/Connectors/Couchbase/CouchbaseWrapper.cs @@ -134,13 +134,28 @@ public async Task DeleteAsync(string key, CancellationToken ct = default) } /// - /// Updates an entity in the Couchbase bucket asynchronously (Upsert). + /// Replaces an existing entity in the Couchbase bucket asynchronously. /// /// The entity to update. /// A token to cancel the asynchronous operation. - /// A task representing whether the update succeeded. - public Task UpdateAsync(ConnectorEntity entity, CancellationToken ct = default) => - InsertAsync(entity, ct); + /// True if the entity existed and was replaced; false if the key does not exist. + public async Task UpdateAsync(ConnectorEntity entity, CancellationToken ct = default) + { + try + { + var collection = await GetCollectionAsync(ct).ConfigureAwait(false); + var options = new ReplaceOptions().CancellationToken(ct); + var ttl = entity.RemainingTimeToLive(); + if (ttl.HasValue) + options = options.Expiry(ttl.Value); + var result = await collection.ReplaceAsync(entity.Key, entity, options).ConfigureAwait(false); + return result is not null; + } + catch (DocumentNotFoundException) + { + return false; + } + } /// /// Disposes the Couchbase connection asynchronously. diff --git a/src/SharpConnector/Connectors/DynamoDB/DynamoDbWrapper.cs b/src/SharpConnector/Connectors/DynamoDB/DynamoDbWrapper.cs index 18146b5..d834c0c 100644 --- a/src/SharpConnector/Connectors/DynamoDB/DynamoDbWrapper.cs +++ b/src/SharpConnector/Connectors/DynamoDB/DynamoDbWrapper.cs @@ -1,6 +1,7 @@ -// (c) 2024 Francesco Del Re +// (c) 2024 Francesco Del Re // This code is licensed under MIT license (see LICENSE.txt for details) using Amazon.DynamoDBv2.DocumentModel; +using Amazon.DynamoDBv2.Model; using Newtonsoft.Json; using SharpConnector.Configuration; using SharpConnector.Entities; @@ -186,8 +187,7 @@ public async Task InsertManyAsync(IEnumerable values, Can /// The key of the item to delete. public bool Delete(string key) { - _table.DeleteItemAsync(key).GetAwaiter().GetResult(); - return true; + return DeleteAsync(key).GetAwaiter().GetResult(); } /// @@ -197,18 +197,30 @@ public bool Delete(string key) /// A token to cancel the asynchronous operation. public async Task DeleteAsync(string key, CancellationToken ct = default) { - await _table.DeleteItemAsync(key, ct).ConfigureAwait(false); - return true; + var config = new DeleteItemOperationConfig { ReturnValues = ReturnValues.AllOldAttributes }; + var oldDocument = await _table.DeleteItemAsync(key, config, ct).ConfigureAwait(false); + return oldDocument != null && oldDocument.Count > 0; } + /// + /// Builds a PutItem configuration that succeeds only if the item already exists. + /// + private static PutItemOperationConfig ExistingItemOnlyConfig() => new() + { + ConditionalExpression = new Expression + { + ExpressionStatement = "attribute_exists(#k)", + ExpressionAttributeNames = new Dictionary { ["#k"] = "Key" } + } + }; + /// /// Update an existing item (sync). /// /// The entity to update. public bool Update(ConnectorEntity connectorEntity) { - // DynamoDB Put is an upsert; reuse Insert. - return Insert(connectorEntity); + return UpdateAsync(connectorEntity).GetAwaiter().GetResult(); } /// @@ -216,8 +228,20 @@ public bool Update(ConnectorEntity connectorEntity) /// /// The entity to update. /// A token to cancel the asynchronous operation. - public Task UpdateAsync(ConnectorEntity connectorEntity, CancellationToken ct = default) => - InsertAsync(connectorEntity, ct); + /// True if the item existed and was updated; otherwise, false. + public async Task UpdateAsync(ConnectorEntity connectorEntity, CancellationToken ct = default) + { + var document = Document.FromJson(JsonConvert.SerializeObject(connectorEntity)); + try + { + await _table.PutItemAsync(document, ExistingItemOnlyConfig(), ct).ConfigureAwait(false); + return true; + } + catch (ConditionalCheckFailedException) + { + return false; + } + } /// /// Check whether a key exists (sync). @@ -252,7 +276,7 @@ public List Query(Func filter) } /// - /// Asynchronously execute a filtered query (not supported in this wrapper). + /// Asynchronously execute a filtered query (evaluated in memory after a full table scan). /// public Task> QueryAsync(Func filter, CancellationToken ct = default) { diff --git a/src/SharpConnector/Connectors/LiteDb/LiteDbAccess.cs b/src/SharpConnector/Connectors/LiteDb/LiteDbAccess.cs index 397664f..ed5b8f9 100755 --- a/src/SharpConnector/Connectors/LiteDb/LiteDbAccess.cs +++ b/src/SharpConnector/Connectors/LiteDb/LiteDbAccess.cs @@ -30,6 +30,7 @@ public LiteDbAccess(LiteDbConfig liteDbConfig) var collectionName = liteDbConfig.CollectionName; Collection = _liteDatabase.GetCollection(collectionName); RawCollection = _liteDatabase.GetCollection(Collection.Name); + Collection.EnsureIndex(x => x.Key, unique: true); } /// diff --git a/src/SharpConnector/Connectors/LiteDb/LiteDbWrapper.cs b/src/SharpConnector/Connectors/LiteDb/LiteDbWrapper.cs index 450b3e7..4b0d66b 100755 --- a/src/SharpConnector/Connectors/LiteDb/LiteDbWrapper.cs +++ b/src/SharpConnector/Connectors/LiteDb/LiteDbWrapper.cs @@ -1,4 +1,4 @@ -// (c) 2021 Francesco Del Re +// (c) 2021 Francesco Del Re // This code is licensed under MIT license (see LICENSE.txt for details) using SharpConnector.Configuration; using SharpConnector.Entities; @@ -80,17 +80,22 @@ public Task> GetAllAsync(CancellationToken ct } /// - /// Insert (or upsert if configured) the specified entity. + /// Insert the specified entity, replacing any existing entity with the same key. /// /// The entity to store. public bool Insert(LiteDbConnectorEntity connectorEntity) { + ArgumentNullException.ThrowIfNull(connectorEntity); + + if (Update(connectorEntity)) + return true; + var result = _liteDbAccess.Collection.Insert(connectorEntity); return !result.IsNull; } /// - /// Asynchronously insert (or upsert if configured) the specified entity. + /// Asynchronously insert the specified entity, replacing any existing entity with the same key. /// /// LiteDB is synchronous; this method wraps the sync call. /// The entity to store. @@ -103,17 +108,24 @@ public Task InsertAsync(LiteDbConnectorEntity connectorEntity, Cancellatio } /// - /// Insert multiple entities in bulk. + /// Insert multiple entities one by one (upsert); continues on failure. /// /// Entities to store. public bool InsertMany(List connectorEntities) { - var insertedCount = _liteDbAccess.Collection.InsertBulk(connectorEntities); - return insertedCount == connectorEntities?.Count; + ArgumentNullException.ThrowIfNull(connectorEntities); + + var result = true; + foreach (var entity in connectorEntities) + { + if (!Insert(entity)) + result = false; + } + return result; } /// - /// Asynchronously insert multiple entities in bulk. + /// Asynchronously insert multiple entities one by one (upsert); continues on failure. /// /// LiteDB is synchronous; this method wraps the sync call. /// Entities to store. diff --git a/src/SharpConnector/Connectors/Memcached/MemcachedAccess.cs b/src/SharpConnector/Connectors/Memcached/MemcachedAccess.cs index 82ec6a0..3ec2b4c 100755 --- a/src/SharpConnector/Connectors/Memcached/MemcachedAccess.cs +++ b/src/SharpConnector/Connectors/Memcached/MemcachedAccess.cs @@ -21,12 +21,41 @@ public class MemcachedAccess : IDisposable /// The Memcached configuration. public MemcachedAccess(MemcachedConfig memcachedConfig) { + ArgumentNullException.ThrowIfNull(memcachedConfig); + + // Validate before allocating disposable resources. + var servers = ParseServers(memcachedConfig.ConnectionString); + _loggerFactory = new LoggerFactory(); + try + { + var options = new MemcachedClientOptions + { + Protocol = MemcachedProtocol.Text, + Servers = servers + }; + + var config = new MemcachedClientConfiguration(_loggerFactory, options); + MemcachedClient = new MemcachedClient(_loggerFactory, config); + } + catch + { + _loggerFactory.Dispose(); + throw; + } + } + + /// + /// Parses a connection string in the form "host1:port1,host2:port2". + /// + internal static List ParseServers(string connectionString) + { + if (string.IsNullOrWhiteSpace(connectionString)) + throw new ArgumentException("Memcached connection string cannot be null or empty.", nameof(connectionString)); var servers = new List(); - foreach (var part in memcachedConfig.ConnectionString.Split(',', StringSplitOptions.RemoveEmptyEntries)) + foreach (var trimmed in connectionString.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) { - var trimmed = part.Trim(); var idx = trimmed.LastIndexOf(':'); if (idx <= 0 || idx == trimmed.Length - 1) throw new FormatException($"Invalid Memcached connection string segment: '{trimmed}' (expected host:port)"); @@ -38,14 +67,10 @@ public MemcachedAccess(MemcachedConfig memcachedConfig) servers.Add(new Server { Address = host, Port = port }); } - var options = new MemcachedClientOptions - { - Protocol = MemcachedProtocol.Text, - Servers = servers - }; + if (servers.Count == 0) + throw new ArgumentException("Memcached connection string contains no servers.", nameof(connectionString)); - var config = new MemcachedClientConfiguration(_loggerFactory, options); - MemcachedClient = new MemcachedClient(_loggerFactory, config); + return servers; } /// diff --git a/src/SharpConnector/Connectors/Memcached/MemcachedWrapper.cs b/src/SharpConnector/Connectors/Memcached/MemcachedWrapper.cs index 5cc59fb..98e5c9c 100755 --- a/src/SharpConnector/Connectors/Memcached/MemcachedWrapper.cs +++ b/src/SharpConnector/Connectors/Memcached/MemcachedWrapper.cs @@ -83,7 +83,7 @@ public bool Insert(ConnectorEntity connectorEntity) ? (int)Math.Ceiling(connectorEntity.Expiration.Value.TotalSeconds) : 0; - return _memcachedAccess.MemcachedClient.Add( + return _memcachedAccess.MemcachedClient.Set( connectorEntity.Key, JsonConvert.SerializeObject(connectorEntity), seconds); @@ -102,7 +102,7 @@ public Task InsertAsync(ConnectorEntity connectorEntity, CancellationToken ? (int)Math.Ceiling(connectorEntity.Expiration.Value.TotalSeconds) : 0; - return _memcachedAccess.MemcachedClient.AddAsync( + return _memcachedAccess.MemcachedClient.SetAsync( connectorEntity.Key, JsonConvert.SerializeObject(connectorEntity), seconds); @@ -114,7 +114,15 @@ public Task InsertAsync(ConnectorEntity connectorEntity, CancellationToken /// The entities to store. public bool InsertMany(List connectorEntities) { - return connectorEntities.All(Insert); + ArgumentNullException.ThrowIfNull(connectorEntities); + + var result = true; + foreach (var entity in connectorEntities) + { + if (!Insert(entity)) + result = false; + } + return result; } /// diff --git a/src/SharpConnector/Connectors/MongoDb/MongoDbAccess.cs b/src/SharpConnector/Connectors/MongoDb/MongoDbAccess.cs index 94fb66f..d1fb8bf 100755 --- a/src/SharpConnector/Connectors/MongoDb/MongoDbAccess.cs +++ b/src/SharpConnector/Connectors/MongoDb/MongoDbAccess.cs @@ -26,6 +26,11 @@ public MongoDbAccess(MongoDbConfig mongoDbConfig) _client = new MongoClient(mongoDbConfig.ConnectionString); var database = _client.GetDatabase(mongoDbConfig.DatabaseName); Collection = database.GetCollection(mongoDbConfig.CollectionName); + + // Key identifies an entity: enforce uniqueness at the database level. + Collection.Indexes.CreateOne(new CreateIndexModel( + Builders.IndexKeys.Ascending(x => x.Key), + new CreateIndexOptions { Unique = true, Name = "ux_Key" })); } /// diff --git a/src/SharpConnector/Connectors/MongoDb/MongoDbWrapper.cs b/src/SharpConnector/Connectors/MongoDb/MongoDbWrapper.cs index 934b5c9..7f6fa52 100755 --- a/src/SharpConnector/Connectors/MongoDb/MongoDbWrapper.cs +++ b/src/SharpConnector/Connectors/MongoDb/MongoDbWrapper.cs @@ -1,4 +1,4 @@ -// (c) 2020 Francesco Del Re +// (c) 2020 Francesco Del Re // This code is licensed under MIT license (see LICENSE.txt for details) using MongoDB.Driver; using SharpConnector.Configuration; @@ -127,10 +127,26 @@ public async Task InsertAsync(MongoConnectorEntity connectorEntity, Cancel /// The entities to store. public bool InsertMany(List connectorEntities) { - var options = new InsertManyOptions { IsOrdered = false }; + var requests = BuildUpsertRequests(connectorEntities); + if (requests.Count == 0) + return true; - _mongoDbAccess.Collection.InsertMany(connectorEntities, options); - return true; + var result = _mongoDbAccess.Collection.BulkWrite(requests, new BulkWriteOptions { IsOrdered = false }); + return result.IsAcknowledged; + } + + /// + /// Builds one upsert (replace by Key) request per entity, so repeated keys never create duplicates. + /// + internal static List> BuildUpsertRequests(IEnumerable connectorEntities) + { + ArgumentNullException.ThrowIfNull(connectorEntities); + + return connectorEntities + .Select(e => (WriteModel)new ReplaceOneModel( + Builders.Filter.Eq(x => x.Key, e.Key), e) + { IsUpsert = true }) + .ToList(); } /// @@ -141,13 +157,15 @@ public bool InsertMany(List connectorEntities) /// True if the insert completed successfully; otherwise, false. public async Task InsertManyAsync(List connectorEntities, CancellationToken ct = default) { - var options = new InsertManyOptions { IsOrdered = false }; + var requests = BuildUpsertRequests(connectorEntities); + if (requests.Count == 0) + return true; - await _mongoDbAccess.Collection - .InsertManyAsync(connectorEntities, options, ct) + var result = await _mongoDbAccess.Collection + .BulkWriteAsync(requests, new BulkWriteOptions { IsOrdered = false }, ct) .ConfigureAwait(false); - return true; + return result.IsAcknowledged; } /// @@ -192,7 +210,7 @@ public bool Update(MongoConnectorEntity connectorEntity) .Set(x => x.ExpiresAt, connectorEntity.ExpiresAt); var result = _mongoDbAccess.Collection.UpdateOne(filter, update); - return result.IsAcknowledged && result.ModifiedCount > 0; + return result.IsAcknowledged && result.MatchedCount > 0; } /// @@ -200,7 +218,7 @@ public bool Update(MongoConnectorEntity connectorEntity) /// /// The entity to store. /// A token to cancel the asynchronous operation. - /// True if the update was acknowledged and modified a document; otherwise, false. + /// True if the update was acknowledged and matched a document; otherwise, false. public async Task UpdateAsync(MongoConnectorEntity connectorEntity, CancellationToken ct = default) { var filter = Builders.Filter.Eq(x => x.Key, connectorEntity.Key); @@ -213,7 +231,7 @@ public async Task UpdateAsync(MongoConnectorEntity connectorEntity, Cancel .UpdateOneAsync(filter, update, options: null, ct) .ConfigureAwait(false); - return result.IsAcknowledged && result.ModifiedCount > 0; + return result.IsAcknowledged && result.MatchedCount > 0; } /// diff --git a/src/SharpConnector/Connectors/Redis/RedisWrapper.cs b/src/SharpConnector/Connectors/Redis/RedisWrapper.cs index d61f1a4..7627bbf 100755 --- a/src/SharpConnector/Connectors/Redis/RedisWrapper.cs +++ b/src/SharpConnector/Connectors/Redis/RedisWrapper.cs @@ -298,8 +298,14 @@ public async Task DeleteAsync(string key, int databaseNumber = 0, Cancella /// /// The ConnectorEntity to update. /// The Redis database. - public bool Update(ConnectorEntity connectorEntity, int databaseNumber = 0) => - Insert(connectorEntity, databaseNumber); + public bool Update(ConnectorEntity connectorEntity, int databaseNumber = 0) + { + return GetDatabase(databaseNumber).StringSet( + connectorEntity.Key, + Serialize(connectorEntity), + ToExpiration(connectorEntity.Expiration), + When.Exists); + } /// /// Asynchronously updates the specified Key. @@ -307,8 +313,17 @@ public bool Update(ConnectorEntity connectorEntity, int databaseNumber = 0) => /// The ConnectorEntity to update. /// The Redis database. /// A token to cancel the asynchronous operation. - public Task UpdateAsync(ConnectorEntity connectorEntity, int databaseNumber = 0, CancellationToken ct = default) => - InsertAsync(connectorEntity, databaseNumber, ct); + public async Task UpdateAsync(ConnectorEntity connectorEntity, int databaseNumber = 0, CancellationToken ct = default) + { + ct.ThrowIfCancellationRequested(); + + return await GetDatabase(databaseNumber).StringSetAsync( + connectorEntity.Key, + Serialize(connectorEntity), + ToExpiration(connectorEntity.Expiration), + When.Exists) + .ConfigureAwait(false); + } /// /// Checks if an item exists by its key. diff --git a/src/SharpConnector/Entities/ConnectorEntity.cs b/src/SharpConnector/Entities/ConnectorEntity.cs index ec5c54c..4782351 100755 --- a/src/SharpConnector/Entities/ConnectorEntity.cs +++ b/src/SharpConnector/Entities/ConnectorEntity.cs @@ -1,4 +1,4 @@ -// (c) 2020 Francesco Del Re +// (c) 2020 Francesco Del Re // This code is licensed under MIT license (see LICENSE.txt for details) using Newtonsoft.Json; using System; @@ -86,7 +86,7 @@ public ConnectorEntity(string key, object payload) /// Determines whether the specified object is equal to the current ConnectorEntity instance. /// /// The object to compare with the current ConnectorEntity instance. - /// True if the specified object is a ConnectorEntity and has the same Payload hash code; otherwise, false. + /// True if the specified object is a ConnectorEntity and has the same Key, Payload and Expiration; otherwise, false. public override bool Equals(object obj) { return obj is ConnectorEntity other && diff --git a/src/SharpConnector/Interfaces/IOperations.cs b/src/SharpConnector/Interfaces/IOperations.cs index a61aebf..71c0797 100755 --- a/src/SharpConnector/Interfaces/IOperations.cs +++ b/src/SharpConnector/Interfaces/IOperations.cs @@ -1,4 +1,4 @@ -// (c) 2020 Francesco Del Re +// (c) 2020 Francesco Del Re // This code is licensed under MIT license (see LICENSE.txt for details) using System; using System.Collections.Generic; @@ -42,7 +42,7 @@ public interface IOperations : IDisposable Task> GetAllAsync(CancellationToken ct = default); /// - /// Inserts a new item with a specified key and value. + /// Inserts a new item with a specified key and value. Existing keys are overwritten. /// /// The key of the item to insert. /// The value (payload) of the item to insert. @@ -50,17 +50,16 @@ public interface IOperations : IDisposable bool Insert(string key, T value); /// - /// Inserts a new item with a specified key, value, and expiration time. + /// Inserts a new item with a specified key, value, and expiration time. Existing keys are overwritten. /// /// The key of the item to insert. /// The value (payload) of the item to insert. /// The expiration time for the item. - /// A token to cancel the asynchronous operation. /// True if the insertion was successful, otherwise false. bool Insert(string key, T value, TimeSpan expiration); /// - /// Asynchronously inserts a new item with a specified key and value. + /// Asynchronously inserts a new item with a specified key and value. Existing keys are overwritten. /// /// The key of the item to insert. /// The value (payload) of the item to insert. @@ -69,7 +68,7 @@ public interface IOperations : IDisposable Task InsertAsync(string key, T value, CancellationToken ct = default); /// - /// Asynchronously inserts a new item with a specified key, value, and expiration time. + /// Asynchronously inserts a new item with a specified key, value, and expiration time. Existing keys are overwritten. /// /// The key of the item to insert. /// The value (payload) of the item to insert. @@ -79,14 +78,14 @@ public interface IOperations : IDisposable Task InsertAsync(string key, T value, TimeSpan expiration, CancellationToken ct = default); /// - /// Inserts multiple items at once. + /// Inserts multiple items at once. Existing keys are overwritten. /// /// A dictionary containing keys and their corresponding payloads to insert. /// True if all insertions were successful, otherwise false. bool InsertMany(Dictionary values); /// - /// Inserts multiple items at once with an expiration time. + /// Inserts multiple items at once with an expiration time. Existing keys are overwritten. /// /// A dictionary containing keys and their corresponding payloads to insert. /// The expiration time for the items. @@ -94,7 +93,7 @@ public interface IOperations : IDisposable bool InsertMany(Dictionary values, TimeSpan expiration); /// - /// Inserts multiple items with a specified expiration time. + /// Asynchronously inserts multiple items. Existing keys are overwritten. /// /// A dictionary of items to insert, keyed by their unique keys. /// A token to cancel the asynchronous operation. @@ -102,7 +101,7 @@ public interface IOperations : IDisposable Task InsertManyAsync(Dictionary values, CancellationToken ct = default); /// - /// Inserts multiple items with a specified expiration time. + /// Inserts multiple items with a specified expiration time. Existing keys are overwritten. /// /// A dictionary of items to insert, keyed by their unique keys. /// The time after which the items expire. @@ -126,7 +125,7 @@ public interface IOperations : IDisposable /// Deletes an item by its key. /// /// The key of the item to delete. - /// True if the deletion was successful, otherwise false. + /// True if the item existed and was removed; otherwise, false. bool Delete(string key); /// @@ -142,7 +141,7 @@ public interface IOperations : IDisposable /// /// The key of the item to update. /// The new value to set for the item. - /// True if the update was successful, otherwise false. + /// True if the item existed and was updated; false if the key does not exist. bool Update(string key, T value); /// diff --git a/src/SharpConnector/Interfaces/ISharpConnectorClient.cs b/src/SharpConnector/Interfaces/ISharpConnectorClient.cs index f6c325a..4b304a0 100755 --- a/src/SharpConnector/Interfaces/ISharpConnectorClient.cs +++ b/src/SharpConnector/Interfaces/ISharpConnectorClient.cs @@ -1,4 +1,4 @@ -// (c) 2020 Francesco Del Re +// (c) 2020 Francesco Del Re // This code is licensed under MIT license (see LICENSE.txt for details) using System; using System.Collections.Generic; @@ -42,7 +42,7 @@ public interface ISharpConnectorClient : IDisposable Task> GetAllAsync(CancellationToken ct = default); /// - /// Inserts an item with a specified key. + /// Inserts an item with a specified key. Existing keys are overwritten. /// /// The unique key for the item. /// The item to insert. @@ -51,7 +51,7 @@ public interface ISharpConnectorClient : IDisposable bool Insert(string key, T value); /// - /// Inserts an item with a specified key and expiration time. + /// Inserts an item with a specified key and expiration time. Existing keys are overwritten. /// /// The unique key for the item. /// The item to insert. @@ -61,7 +61,7 @@ public interface ISharpConnectorClient : IDisposable bool Insert(string key, T value, TimeSpan expiration); /// - /// Asynchronously inserts an item with a specified key. + /// Asynchronously inserts an item with a specified key. Existing keys are overwritten. /// /// The unique key for the item. /// The item to insert. @@ -69,7 +69,7 @@ public interface ISharpConnectorClient : IDisposable Task InsertAsync(string key, T value, CancellationToken ct = default); /// - /// Asynchronously inserts an item with a specified key and expiration time. + /// Asynchronously inserts an item with a specified key and expiration time. Existing keys are overwritten. /// /// The unique key for the item. /// The item to insert. @@ -78,7 +78,7 @@ public interface ISharpConnectorClient : IDisposable Task InsertAsync(string key, T value, TimeSpan expiration, CancellationToken ct = default); /// - /// Inserts multiple items. + /// Inserts multiple items. Existing keys are overwritten. /// /// A dictionary of items to insert, keyed by their unique keys. /// True if all items were inserted successfully, false otherwise. @@ -86,7 +86,7 @@ public interface ISharpConnectorClient : IDisposable bool InsertMany(Dictionary values); /// - /// Inserts multiple items with a specified expiration time. + /// Inserts multiple items with a specified expiration time. Existing keys are overwritten. /// /// A dictionary of items to insert, keyed by their unique keys. /// The time after which the items expire. @@ -95,14 +95,14 @@ public interface ISharpConnectorClient : IDisposable bool InsertMany(Dictionary values, TimeSpan expiration); /// - /// Inserts multiple items with a specified expiration time. + /// Asynchronously inserts multiple items. Existing keys are overwritten. /// /// A dictionary of items to insert, keyed by their unique keys. /// True if all items were inserted successfully, false otherwise. Task InsertManyAsync(Dictionary values); /// - /// Inserts multiple items with a specified expiration time. + /// Inserts multiple items with a specified expiration time. Existing keys are overwritten. /// /// A dictionary of items to insert, keyed by their unique keys. /// The time after which the items expire. @@ -110,7 +110,7 @@ public interface ISharpConnectorClient : IDisposable Task InsertManyAsync(Dictionary values, TimeSpan expiration); /// - /// Asynchronously inserts multiple items, generating a unique key for each value. + /// Asynchronously inserts multiple items, generating a unique key for each value. /// /// A collection of items to insert. /// A token to cancel the asynchronous operation. @@ -124,7 +124,7 @@ public interface ISharpConnectorClient : IDisposable /// Deletes an item by its key. /// /// The unique key of the item to delete. - /// True if deletion was successful, false otherwise. + /// True if the item existed and was removed; otherwise, false. [Obsolete("Use DeleteAsync instead.")] bool Delete(string key); @@ -140,7 +140,7 @@ public interface ISharpConnectorClient : IDisposable /// /// The unique key of the item to update. /// The new item value. - /// True if the update was successful, false otherwise. + /// True if the item existed and was updated; false if the key does not exist. [Obsolete("Use UpdateAsync instead.")] bool Update(string key, T value); diff --git a/src/SharpConnector/Middleware/SharpConnectorServiceExtensions.cs b/src/SharpConnector/Middleware/SharpConnectorServiceExtensions.cs index e6388bb..b37b342 100644 --- a/src/SharpConnector/Middleware/SharpConnectorServiceExtensions.cs +++ b/src/SharpConnector/Middleware/SharpConnectorServiceExtensions.cs @@ -1,4 +1,4 @@ -// (c) 2020 Francesco Del Re +// (c) 2020 Francesco Del Re // This code is licensed under MIT license (see LICENSE.txt for details) using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; @@ -9,9 +9,13 @@ namespace SharpConnector.Middleware public static class SharpConnectorServiceExtensions { /// - /// Registers the ISharpConnectorClient as a scoped service in the dependency injection container. - /// This means that a new instance of ISharpConnectorClient will be created for each HTTP request. + /// Registers the as a scoped service in the dependency injection container. + /// This means that a new instance of will be created for each HTTP request. /// Typically used for services that are request-specific and need to be disposed at the end of each request. + /// + /// Warning: each scope opens a new connection to the underlying store, which is expensive for + /// most drivers (Redis, MongoDB, Couchbase, Cassandra). Prefer . + /// /// /// The type of the payload used by the SharpConnectorClient. /// The IServiceCollection where the service will be registered. @@ -35,8 +39,8 @@ public static IServiceCollection AddSharpConnectorServicesScoped(this IServic } /// - /// Registers the ISharpConnectorClient as a singleton service in the dependency injection container. - /// This means that only a single instance of ISharpConnectorClient will be used throughout the entire application's lifetime. + /// Registers the as a singleton service in the dependency injection container. + /// This means that only a single instance of will be used throughout the entire application's lifetime. /// Typically used for services that do not require multiple instances and can share state across the entire application. /// /// The type of the payload used by the SharpConnectorClient. @@ -61,7 +65,7 @@ public static IServiceCollection AddSharpConnectorServicesSingleton(this ISer } /// - /// A default registration method for ISharpConnectorClient that registers it as a Singleton. + /// A default registration method for that registers it as a Singleton. /// This is provided for backward compatibility with existing codebases that may have previously registered services as Singletons. /// Developers can still choose to change the lifetime to Scoped by using the AddSharpConnectorServicesScoped method. /// diff --git a/src/SharpConnector/Operations/ArangoDbOperations.cs b/src/SharpConnector/Operations/ArangoDbOperations.cs index c8287f1..5f3ad5b 100644 --- a/src/SharpConnector/Operations/ArangoDbOperations.cs +++ b/src/SharpConnector/Operations/ArangoDbOperations.cs @@ -1,4 +1,4 @@ -// (c) 2025 Francesco Del Re +// (c) 2025 Francesco Del Re // This code is licensed under MIT license (see LICENSE.txt for details) using SharpConnector.Configuration; using SharpConnector.Connectors.ArangoDb; @@ -44,7 +44,7 @@ public override bool Delete(string key) /// /// The key of the object to delete. /// A token to cancel the asynchronous operation. - /// A task that represents the asynchronous operation. The task result indicates success. + /// The keys generated for each inserted value, in input order; an empty collection if the insertion failed. public override Task DeleteAsync(string key, CancellationToken ct = default) { return _arangoDbWrapper.DeleteAsync(key, ct); @@ -129,7 +129,7 @@ public override bool Insert(string key, T value, TimeSpan expiration) /// The key of the object to insert. /// The value to insert into the object. /// A token to cancel the asynchronous operation. - /// A task that represents the asynchronous operation. The task result indicates success. + /// The keys generated for each inserted value, in input order; an empty collection if the insertion failed. public override Task InsertAsync(string key, T value, CancellationToken ct = default) { var connectorEntity = new ConnectorEntity(key, value, null); @@ -143,7 +143,7 @@ public override Task InsertAsync(string key, T value, CancellationToken ct /// The value to insert into the object. /// The expiration time for the object. /// A token to cancel the asynchronous operation. - /// A task that represents the asynchronous operation. The task result indicates success. + /// The keys generated for each inserted value, in input order; an empty collection if the insertion failed. public override Task InsertAsync(string key, T value, TimeSpan expiration, CancellationToken ct = default) { var connectorEntity = new ConnectorEntity(key, value, expiration); @@ -176,7 +176,7 @@ public override bool InsertMany(Dictionary values, TimeSpan expiratio /// /// A collection of objects to insert. /// A token to cancel the asynchronous operation. - /// A task that represents the asynchronous operation. The task result indicates success. + /// The keys generated for each inserted value, in input order; an empty collection if the insertion failed. public override async Task> InsertManyAsync(IEnumerable values, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(values); @@ -205,7 +205,7 @@ public override bool Update(string key, T value) /// The key of the object to update. /// The new value to update in the object. /// A token to cancel the asynchronous operation. - /// A task that represents the asynchronous operation. The task result indicates success. + /// The keys generated for each inserted value, in input order; an empty collection if the insertion failed. public override Task UpdateAsync(string key, T value, CancellationToken ct = default) { var connectorEntity = new ConnectorEntity(key, value, null); @@ -271,7 +271,7 @@ public override async Task> QueryAsync(Func filter, Canc /// A task that represents the asynchronous operation. The task result is /// true if all items were inserted successfully; otherwise, false. /// - /// Thrown when is null. + /// Thrown when a key is null or empty, or a value is null. public override async Task InsertManyAsync(Dictionary values, CancellationToken ct = default) { var entities = values.ToConnectorEntityList(); @@ -296,7 +296,7 @@ public override async Task InsertManyAsync(Dictionary values, C /// A task that represents the asynchronous operation. The task result is /// true if all items were inserted successfully; otherwise, false. /// - /// Thrown when is null. + /// Thrown when a key is null or empty, or a value is null. public override async Task InsertManyAsync(Dictionary values, TimeSpan expiration, CancellationToken ct = default) { var entities = values.ToConnectorEntityList(expiration); diff --git a/src/SharpConnector/Operations/CouchbaseOperations.cs b/src/SharpConnector/Operations/CouchbaseOperations.cs index 0ae7b2a..54a54b1 100644 --- a/src/SharpConnector/Operations/CouchbaseOperations.cs +++ b/src/SharpConnector/Operations/CouchbaseOperations.cs @@ -1,4 +1,4 @@ -// (c) 2020 Francesco Del Re +// (c) 2020 Francesco Del Re // This code is licensed under MIT license (see LICENSE.txt for details) using System; using System.Collections.Generic; @@ -76,7 +76,7 @@ public override async Task> GetAllAsync(CancellationToken ct = de } /// - /// Insert a new object into the Couchbase bucket. + /// Insert or replace an object into the Couchbase bucket. /// (Uses async wrapper under the hood.) /// /// The key of the object. @@ -91,7 +91,7 @@ public override bool Insert(string key, T value) } /// - /// Insert a new object with an expiration time into the Couchbase bucket. + /// Insert or replace an object with an expiration time into the Couchbase bucket. /// (Uses async wrapper under the hood.) /// /// The key of the object. @@ -107,7 +107,7 @@ public override bool Insert(string key, T value, TimeSpan expiration) } /// - /// Asynchronously insert a new object into the Couchbase bucket. + /// Asynchronously insert or replace an object into the Couchbase bucket. /// /// The key of the object. /// The value to store. @@ -119,7 +119,7 @@ public override Task InsertAsync(string key, T value, CancellationToken ct } /// - /// Asynchronously insert a new object with an expiration time into the Couchbase bucket. + /// Asynchronously insert or replace an object with an expiration time into the Couchbase bucket. /// /// The key of the object. /// The value to store. @@ -163,7 +163,7 @@ public override bool InsertMany(Dictionary values, TimeSpan expiratio /// /// The values to store. /// A token to cancel the asynchronous operation. - /// True if all insertions succeeded; otherwise, false. + /// The keys generated for each inserted value, in input order; an empty collection if the insertion failed. public override async Task> InsertManyAsync(IEnumerable values, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(values); @@ -294,7 +294,7 @@ public override async Task> QueryAsync(Func filter, Canc /// A task that represents the asynchronous operation. The task result is /// true if all items were inserted successfully; otherwise, false. /// - /// Thrown when is null. + /// Thrown when a key is null or empty, or a value is null. /// Thrown if the operation is canceled. public override async Task InsertManyAsync(Dictionary values, CancellationToken ct = default) { @@ -322,7 +322,7 @@ public override async Task InsertManyAsync(Dictionary values, C /// A task that represents the asynchronous operation. The task result is /// true if all items were inserted successfully; otherwise, false. /// - /// Thrown when is null. + /// Thrown when a key is null or empty, or a value is null. /// Thrown if the operation is canceled. public override async Task InsertManyAsync(Dictionary values, TimeSpan expiration, CancellationToken ct = default) { diff --git a/src/SharpConnector/Operations/DynamoDbOperations.cs b/src/SharpConnector/Operations/DynamoDbOperations.cs index cdd2650..161fde2 100644 --- a/src/SharpConnector/Operations/DynamoDbOperations.cs +++ b/src/SharpConnector/Operations/DynamoDbOperations.cs @@ -1,4 +1,4 @@ -// (c) 2024 Francesco Del Re +// (c) 2024 Francesco Del Re // This code is licensed under MIT license (see LICENSE.txt for details) using SharpConnector.Configuration; using SharpConnector.Connectors.DynamoDb; @@ -131,7 +131,7 @@ public override bool InsertMany(Dictionary values) /// /// A collection of values to store. /// A token to cancel the asynchronous operation. - /// True if all insertions succeeded; otherwise, false. + /// The keys generated for each inserted value, in input order; an empty collection if the insertion failed. public override async Task> InsertManyAsync(IEnumerable values, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(values); @@ -257,7 +257,7 @@ public override async Task> QueryAsync(Func filter, Canc /// A task that represents the asynchronous operation. The task result is /// true if all items were inserted successfully; otherwise, false. /// - /// Thrown when is null. + /// Thrown when a key is null or empty, or a value is null. public override async Task InsertManyAsync(Dictionary values, CancellationToken ct = default) { var entities = values.ToConnectorEntityList(); @@ -282,7 +282,7 @@ public override async Task InsertManyAsync(Dictionary values, C /// A task that represents the asynchronous operation. The task result is /// true if all items were inserted successfully; otherwise, false. /// - /// Thrown when is null. + /// Thrown when a key is null or empty, or a value is null. public override async Task InsertManyAsync(Dictionary values, TimeSpan expiration, CancellationToken ct = default) { var entities = values.ToConnectorEntityList(expiration); diff --git a/src/SharpConnector/Operations/LiteDbOperations.cs b/src/SharpConnector/Operations/LiteDbOperations.cs index 54f76d6..e7013a8 100755 --- a/src/SharpConnector/Operations/LiteDbOperations.cs +++ b/src/SharpConnector/Operations/LiteDbOperations.cs @@ -1,4 +1,4 @@ -// (c) 2020 Francesco Del Re +// (c) 2020 Francesco Del Re // This code is licensed under MIT license (see LICENSE.txt for details) using SharpConnector.Connectors.LiteDb; using System; @@ -228,7 +228,7 @@ public override IEnumerable Query(Func filter) } /// - /// Asynchronously execute a filtered query. (Not supported in this operations class) + /// Asynchronously execute a filtered query (evaluated in memory). /// /// Predicate that selects items of type T. /// A token to cancel the asynchronous operation. @@ -254,7 +254,7 @@ public override async Task> QueryAsync(Func filter, Canc /// A task that represents the asynchronous operation. The task result is /// true if all items were inserted successfully; otherwise, false. /// - /// Thrown when is null. + /// Thrown when a key is null or empty, or a value is null. public override async Task InsertManyAsync(Dictionary values, CancellationToken ct = default) { var entities = values.ToLiteDbConnectorEntityList(); @@ -279,7 +279,7 @@ public override async Task InsertManyAsync(Dictionary values, C /// A task that represents the asynchronous operation. The task result is /// true if all items were inserted successfully; otherwise, false. /// - /// Thrown when is null. + /// Thrown when a key is null or empty, or a value is null. public override async Task InsertManyAsync(Dictionary values, TimeSpan expiration, CancellationToken ct = default) { var entities = values.ToLiteDbConnectorEntityList(expiration); diff --git a/src/SharpConnector/Operations/MemcachedOperations.cs b/src/SharpConnector/Operations/MemcachedOperations.cs index 6539eb0..a732f29 100755 --- a/src/SharpConnector/Operations/MemcachedOperations.cs +++ b/src/SharpConnector/Operations/MemcachedOperations.cs @@ -1,4 +1,4 @@ -// (c) 2020 Francesco Del Re +// (c) 2020 Francesco Del Re // This code is licensed under MIT license (see LICENSE.txt for details) using System; using System.Collections.Generic; @@ -187,7 +187,7 @@ public override Task> GetAllAsync(CancellationToken ct = default) /// /// The values to store. /// A token to cancel the asynchronous operation. - /// True if all insertions were successful; otherwise, false. + /// The keys generated for each inserted value, in input order; an empty collection if the insertion failed. public override async Task> InsertManyAsync(IEnumerable values, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(values); @@ -255,7 +255,7 @@ public override Task> QueryAsync(Func filter, Cancellati /// A task that represents the asynchronous operation. The task result is /// true if all items were inserted successfully; otherwise, false. /// - /// Thrown when is null. + /// Thrown when a key is null or empty, or a value is null. /// Thrown if the operation is canceled. public override async Task InsertManyAsync(Dictionary values, CancellationToken ct = default) { @@ -283,7 +283,7 @@ public override async Task InsertManyAsync(Dictionary values, C /// A task that represents the asynchronous operation. The task result is /// true if all items were inserted successfully; otherwise, false. /// - /// Thrown when is null. + /// Thrown when a key is null or empty, or a value is null. /// Thrown if the operation is canceled. public override async Task InsertManyAsync(Dictionary values, TimeSpan expiration, CancellationToken ct = default) { diff --git a/src/SharpConnector/Operations/MongoDbOperations.cs b/src/SharpConnector/Operations/MongoDbOperations.cs index 386d21b..559fdcb 100755 --- a/src/SharpConnector/Operations/MongoDbOperations.cs +++ b/src/SharpConnector/Operations/MongoDbOperations.cs @@ -1,4 +1,4 @@ -// (c) 2020 Francesco Del Re +// (c) 2020 Francesco Del Re // This code is licensed under MIT license (see LICENSE.txt for details) using System; using System.Collections.Generic; @@ -142,7 +142,7 @@ public override bool InsertMany(Dictionary values, TimeSpan expiratio /// /// The values to store as an enumerable. /// A token to cancel the asynchronous operation. - /// True if the insertion was successful; otherwise, false. + /// The keys generated for each inserted value, in input order; an empty collection if the insertion failed. public override async Task> InsertManyAsync(IEnumerable values, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(values); @@ -257,7 +257,7 @@ public override async Task> QueryAsync(Func filter, Canc /// A task that represents the asynchronous operation. The task result is /// true if all items were inserted successfully; otherwise, false. /// - /// Thrown when is null. + /// Thrown when a key is null or empty, or a value is null. public override async Task InsertManyAsync(Dictionary values, CancellationToken ct = default) { var entities = values.ToMongoDbConnectorEntityList(); @@ -282,7 +282,7 @@ public override async Task InsertManyAsync(Dictionary values, C /// A task that represents the asynchronous operation. The task result is /// true if all items were inserted successfully; otherwise, false. /// - /// Thrown when is null. + /// Thrown when a key is null or empty, or a value is null. public override async Task InsertManyAsync(Dictionary values, TimeSpan expiration, CancellationToken ct = default) { var entities = values.ToMongoDbConnectorEntityList(expiration); diff --git a/src/SharpConnector/Operations/RavenDbOperations.cs b/src/SharpConnector/Operations/RavenDbOperations.cs index 7e035e6..dd9e690 100755 --- a/src/SharpConnector/Operations/RavenDbOperations.cs +++ b/src/SharpConnector/Operations/RavenDbOperations.cs @@ -1,4 +1,4 @@ -// (c) 2021 Francesco Del Re +// (c) 2021 Francesco Del Re // This code is licensed under MIT license (see LICENSE.txt for details) using SharpConnector.Configuration; using SharpConnector.Connectors.RavenDb; @@ -152,7 +152,7 @@ public override bool InsertMany(Dictionary values, TimeSpan expiratio /// /// The values to store. /// A token to cancel the asynchronous operation. - /// True if all insertions were successful; otherwise, false. + /// The keys generated for each inserted value, in input order; an empty collection if the insertion failed. public override async Task> InsertManyAsync(IEnumerable values, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(values); @@ -273,7 +273,7 @@ public override async Task> QueryAsync(Func filter, Canc /// A task that represents the asynchronous operation. The task result is /// true if all items were inserted successfully; otherwise, false. /// - /// Thrown when is null. + /// Thrown when a key is null or empty, or a value is null. public override async Task InsertManyAsync(Dictionary values, CancellationToken ct = default) { var entities = values.ToConnectorEntityList(); @@ -298,7 +298,7 @@ public override async Task InsertManyAsync(Dictionary values, C /// A task that represents the asynchronous operation. The task result is /// true if all items were inserted successfully; otherwise, false. /// - /// Thrown when is null. + /// Thrown when a key is null or empty, or a value is null. public override async Task InsertManyAsync(Dictionary values, TimeSpan expiration, CancellationToken ct = default) { var entities = values.ToConnectorEntityList(expiration); diff --git a/src/SharpConnector/Operations/RedisOperations.cs b/src/SharpConnector/Operations/RedisOperations.cs index 96af301..48d20c8 100755 --- a/src/SharpConnector/Operations/RedisOperations.cs +++ b/src/SharpConnector/Operations/RedisOperations.cs @@ -275,7 +275,7 @@ public override async Task> QueryAsync(Func filter, Canc /// A task that represents the asynchronous operation. The task result is /// true if all items were inserted successfully; otherwise, false. /// - /// Thrown when is null. + /// Thrown when a key is null or empty, or a value is null. public override async Task InsertManyAsync(Dictionary values, CancellationToken ct = default) { var entities = values.ToConnectorEntityList(); @@ -300,7 +300,7 @@ public override async Task InsertManyAsync(Dictionary values, C /// A task that represents the asynchronous operation. The task result is /// true if all items were inserted successfully; otherwise, false. /// - /// Thrown when is null. + /// Thrown when a key is null or empty, or a value is null. public override async Task InsertManyAsync(Dictionary values, TimeSpan expiration, CancellationToken ct = default) { var entities = values.ToConnectorEntityList(expiration); diff --git a/src/SharpConnector/Utilities/Converter.cs b/src/SharpConnector/Utilities/Converter.cs index 21ea881..25d1f57 100644 --- a/src/SharpConnector/Utilities/Converter.cs +++ b/src/SharpConnector/Utilities/Converter.cs @@ -1,4 +1,4 @@ -// (c) 2020 Francesco Del Re +// (c) 2020 Francesco Del Re // This code is licensed under MIT license (see LICENSE.txt for details) using SharpConnector.Entities; using Newtonsoft.Json; @@ -8,6 +8,9 @@ namespace SharpConnector.Utilities { + /// + /// Conversion helpers between user payloads and the connector entities persisted by each backend. + /// public static class Converter { /// @@ -15,7 +18,7 @@ public static class Converter /// /// The original object stored. /// The ConnectorEntity object to convert. - /// + /// The payload converted to , or default if the entity is null. public static T ToPayloadObject(this ConnectorEntity connectorEntity) { if (connectorEntity == null) @@ -28,7 +31,7 @@ public static T ToPayloadObject(this ConnectorEntity connectorEntity) /// /// The original object stored. /// The LiteDbConnectorEntity object to convert. - /// + /// The payload converted to , or default if the entity is null. public static T ToPayloadObject(this LiteDbConnectorEntity liteDbConnectorEntity) { if (liteDbConnectorEntity == null) @@ -41,7 +44,7 @@ public static T ToPayloadObject(this LiteDbConnectorEntity liteDbConnectorEnt /// /// The original object stored. /// The ConnectorEntity list to convert. - /// + /// The converted payloads; entities with a null payload are skipped. public static IEnumerable ToPayloadList(this IEnumerable connectorEntities) { var result = new List(); @@ -58,7 +61,7 @@ public static IEnumerable ToPayloadList(this IEnumerable /// /// The original object stored. /// The LiteDbConnectorEntity list to convert. - /// + /// The converted payloads; entities with a null payload are skipped. public static IEnumerable ToPayloadList(this IEnumerable connectorEntities) { var result = new List(); @@ -103,11 +106,13 @@ private static T ConvertPayload(object payload) } /// - /// Returns a list of ConnectorEntity. + /// Converts a dictionary of key/payload pairs into a list of ConnectorEntity. /// /// The generic type to store. - /// The dictionary with elements to store. - /// + /// The dictionary of key/payload pairs to store. A null dictionary yields an empty list. + /// Optional expiration applied to every entity. + /// The list of entities, in dictionary enumeration order. + /// ToConnectorEntityList(this Dictionary values, TimeSpan? expiration = null) { if (values == null) @@ -116,8 +121,10 @@ public static List ToConnectorEntityList(this Dictionary(); foreach (var entry in values) { - if (string.IsNullOrEmpty(entry.Key) || entry.Value == null) - continue; + if (string.IsNullOrEmpty(entry.Key)) + throw new ArgumentException("Keys cannot be null or empty.", nameof(values)); + if (entry.Value == null) + throw new ArgumentException($"Value for key '{entry.Key}' cannot be null.", nameof(values)); connectorEntities.Add(new ConnectorEntity(entry.Key, entry.Value, expiration)); } @@ -125,11 +132,13 @@ public static List ToConnectorEntityList(this Dictionary - /// Returns a list of LiteDbConnectorEntity. + /// Converts a dictionary of key/payload pairs into a list of LiteDbConnectorEntity. /// /// The generic type to store. - /// The dictionary with elements to store. - /// + /// The dictionary of key/payload pairs to store. A null dictionary yields an empty list. + /// Optional expiration applied to every entity. + /// The list of entities, in dictionary enumeration order. + /// ToLiteDbConnectorEntityList(this Dictionary values, TimeSpan? expiration = null) { if (values == null) @@ -138,8 +147,10 @@ public static List ToLiteDbConnectorEntityList(this Di var connectorEntities = new List(); foreach (var entry in values) { - if (string.IsNullOrEmpty(entry.Key) || entry.Value == null) - continue; + if (string.IsNullOrEmpty(entry.Key)) + throw new ArgumentException("Keys cannot be null or empty.", nameof(values)); + if (entry.Value == null) + throw new ArgumentException($"Value for key '{entry.Key}' cannot be null.", nameof(values)); connectorEntities.Add(new LiteDbConnectorEntity(entry.Key, entry.Value, expiration)); } @@ -147,11 +158,13 @@ public static List ToLiteDbConnectorEntityList(this Di } /// - /// Returns a list of MongoConnectorEntity. + /// Converts a dictionary of key/payload pairs into a list of MongoConnectorEntity. /// /// The generic type to store. - /// The dictionary with elements to store. - /// + /// The dictionary of key/payload pairs to store. A null dictionary yields an empty list. + /// Optional expiration applied to every entity. + /// The list of entities, in dictionary enumeration order. + /// Thrown when a key is null or empty, or a value is null. public static List ToMongoDbConnectorEntityList(this Dictionary values, TimeSpan? expiration = null) { if (values == null) @@ -160,8 +173,10 @@ public static List ToMongoDbConnectorEntityList(this Di var connectorEntities = new List(); foreach (var entry in values) { - if (string.IsNullOrEmpty(entry.Key) || entry.Value == null) - continue; + if (string.IsNullOrEmpty(entry.Key)) + throw new ArgumentException("Keys cannot be null or empty.", nameof(values)); + if (entry.Value == null) + throw new ArgumentException($"Value for key '{entry.Key}' cannot be null.", nameof(values)); connectorEntities.Add(new MongoConnectorEntity(entry.Key, entry.Value, expiration)); } From 6a36b6d036f5c7ed35f0b71b7aa4e006dd6831bd Mon Sep 17 00:00:00 2001 From: Francesco Del Re Date: Wed, 28 Oct 2026 00:25:56 +0100 Subject: [PATCH 6/7] fix: resolve remaining high and medium severity issues --- .github/workflows/dotnet.yml | 18 ++- .../RemainingFixesTests.cs | 144 ++++++++++++++++++ .../Configuration/DynamoDbConfig.cs | 7 + .../Configuration/RavenDbConfig.cs | 19 +++ .../Configuration/RedisConfig.cs | 6 + .../Connectors/ArangoDb/ArangoDbWrapper.cs | 32 +--- .../Connectors/Couchbase/CouchbaseAccess.cs | 11 +- .../Connectors/Couchbase/CouchbaseWrapper.cs | 8 +- .../Connectors/DynamoDB/DynamoDbWrapper.cs | 53 ++----- .../Connectors/RavenDb/RavenDbAccess.cs | 16 +- .../Connectors/Redis/RedisWrapper.cs | 65 ++++++-- .../Enums/AppConfigParameterEnums.cs | 5 +- .../SharpConnectorServiceExtensions.cs | 4 - .../Operations/CouchbaseOperations.cs | 2 +- src/SharpConnector/Utilities/AsyncHelper.cs | 32 ++++ 15 files changed, 314 insertions(+), 108 deletions(-) create mode 100644 src/SharpConnector.Tests/RemainingFixesTests.cs create mode 100644 src/SharpConnector/Utilities/AsyncHelper.cs diff --git a/.github/workflows/dotnet.yml b/.github/workflows/dotnet.yml index 802e580..534f608 100644 --- a/.github/workflows/dotnet.yml +++ b/.github/workflows/dotnet.yml @@ -17,6 +17,8 @@ jobs: steps: - uses: actions/checkout@v4 + with: + fetch-depth: 0 - name: Setup Node.js uses: actions/setup-node@v4 @@ -24,18 +26,24 @@ jobs: node-version: 20 - name: Install Commitlint dependencies - run: npm install --save-dev @commitlint/config-conventional + run: npm install --no-save @commitlint/cli @commitlint/config-conventional + + - name: Lint commit messages + if: github.event_name == 'pull_request' + run: npx commitlint --from ${{ github.event.pull_request.base.sha }} --to ${{ github.event.pull_request.head.sha }} --verbose - name: Setup .NET uses: actions/setup-dotnet@v4 with: - dotnet-version: 9.0.x + dotnet-version: | + 9.0.x + 10.0.x - name: Restore dependencies - run: dotnet restore src/SharpConnector/SharpConnector.csproj + run: dotnet restore src/SharpConnector/SharpConnector.sln - name: Build - run: dotnet build src/SharpConnector/SharpConnector.csproj --no-restore + run: dotnet build src/SharpConnector/SharpConnector.sln --no-restore --configuration Release - name: Test - run: dotnet test src/SharpConnector.Tests/SharpConnector.Tests.csproj --no-build --verbosity normal + run: dotnet test src/SharpConnector.Tests/SharpConnector.Tests.csproj --no-build --configuration Release --verbosity normal diff --git a/src/SharpConnector.Tests/RemainingFixesTests.cs b/src/SharpConnector.Tests/RemainingFixesTests.cs new file mode 100644 index 0000000..26af4a7 --- /dev/null +++ b/src/SharpConnector.Tests/RemainingFixesTests.cs @@ -0,0 +1,144 @@ +// (c) 2020 Francesco Del Re +// This code is licensed under MIT license (see LICENSE.txt for details) +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using SharpConnector.Configuration; +using SharpConnector.Connectors.Redis; +using SharpConnector.Connectors.RavenDb; +using SharpConnector.Middleware; +using SharpConnector.Utilities; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading.Tasks; + +namespace SharpConnector.Tests +{ + [TestClass] + public class RemainingFixesTests + { + private static IConfiguration BuildConfiguration(Dictionary values) => + new ConfigurationBuilder().AddInMemoryCollection(values).Build(); + + #region RavenDB + + [TestMethod] + public void RavenDbConfig_MissingUrl_Throws() => + Assert.ThrowsExactly(() => new RavenDbConfig(BuildConfiguration(new() { ["databasename"] = "db" }))); + + [TestMethod] + public void RavenDbConfig_InvalidUrl_Throws() => + Assert.ThrowsExactly(() => new RavenDbConfig(BuildConfiguration(new() { ["connectionstring"] = "not a url", ["databasename"] = "db" }))); + + [TestMethod] + public void RavenDbConfig_MissingDatabase_Throws() => + Assert.ThrowsExactly(() => new RavenDbConfig(BuildConfiguration(new() { ["connectionstring"] = "http://localhost:8080" }))); + + [TestMethod] + public void RavenDbConfig_ReadsCertificateSettings() + { + var config = new RavenDbConfig(BuildConfiguration(new() + { + ["connectionstring"] = "https://localhost:8080", + ["databasename"] = "db", + ["certificatepath"] = " cert.pfx ", + ["certificatepassword"] = " p@ss " + })); + + Assert.AreEqual("cert.pfx", config.CertificatePath); + Assert.AreEqual(" p@ss ", config.CertificatePassword); + } + + [TestMethod] + public void RavenDbAccess_LoadCertificate_NoPath_ReturnsNull() + { + var config = new RavenDbConfig(BuildConfiguration(new() { ["connectionstring"] = "http://localhost:8080", ["databasename"] = "db" })); + Assert.IsNull(RavenDbAccess.LoadCertificate(config)); + } + + [TestMethod] + public void RavenDbAccess_LoadCertificate_MissingFile_Throws() + { + var config = new RavenDbConfig(BuildConfiguration(new() + { + ["connectionstring"] = "https://localhost:8080", + ["databasename"] = "db", + ["certificatepath"] = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + ".pfx") + })); + Assert.ThrowsExactly(() => RavenDbAccess.LoadCertificate(config)); + } + + #endregion + + #region Redis + + [TestMethod] + public void RedisConfig_KeyPrefix_DefaultsToEmpty() + { + var config = new RedisConfig(BuildConfiguration(new() { ["connectionstring"] = "localhost:6379" })); + Assert.AreEqual(string.Empty, config.KeyPrefix); + } + + [TestMethod] + public void RedisConfig_KeyPrefix_IsRead() + { + var config = new RedisConfig(BuildConfiguration(new() { ["connectionstring"] = "localhost:6379", ["keyprefix"] = " app: " })); + Assert.AreEqual("app:", config.KeyPrefix); + } + + [TestMethod] + public void RedisWrapper_BuildScanPattern() + { + Assert.IsTrue(RedisWrapper.BuildScanPattern(string.Empty).IsNull); + Assert.AreEqual("app:*", (string)RedisWrapper.BuildScanPattern("app:")); + } + + #endregion + + #region DynamoDB + + [TestMethod] + public void DynamoDbConfig_MissingTable_Throws() => + Assert.ThrowsExactly(() => new DynamoDbConfig(BuildConfiguration(new() { ["region"] = "eu-west-1" }))); + + [TestMethod] + public void DynamoDbConfig_MissingRegionAndServiceUrl_Throws() => + Assert.ThrowsExactly(() => new DynamoDbConfig(BuildConfiguration(new() { ["tablename"] = "t" }))); + + [TestMethod] + public void DynamoDbConfig_InvalidServiceUrl_Throws() => + Assert.ThrowsExactly(() => new DynamoDbConfig(BuildConfiguration(new() { ["tablename"] = "t", ["serviceurl"] = "bad url" }))); + + [TestMethod] + public void DynamoDbConfig_Valid_DoesNotThrow() + { + var config = new DynamoDbConfig(BuildConfiguration(new() { ["tablename"] = "t", ["serviceurl"] = "http://localhost:8000" })); + Assert.AreEqual("t", config.TableName); + } + + #endregion + + #region Misc + + [TestMethod] + public void AddSharpConnectorServices_DoesNotRegisterMvc() + { + var services = new ServiceCollection(); + services.AddSharpConnectorServices(); + + Assert.IsFalse(services.Any(d => d.ServiceType.FullName?.StartsWith("Microsoft.AspNetCore.Mvc") == true)); + } + + [TestMethod] + public void AsyncHelper_RunSync_ReturnsResult() => + Assert.AreEqual(42, AsyncHelper.RunSync(async () => { await Task.Yield(); return 42; })); + + [TestMethod] + public void AsyncHelper_RunSync_PropagatesException() => + Assert.ThrowsExactly(() => AsyncHelper.RunSync(() => Task.FromException(new InvalidOperationException()))); + + #endregion + } +} diff --git a/src/SharpConnector/Configuration/DynamoDbConfig.cs b/src/SharpConnector/Configuration/DynamoDbConfig.cs index 669c3e6..d057021 100644 --- a/src/SharpConnector/Configuration/DynamoDbConfig.cs +++ b/src/SharpConnector/Configuration/DynamoDbConfig.cs @@ -43,6 +43,13 @@ public DynamoDbConfig(IConfiguration configuration) bool.TryParse(configuration[AppConfigParameterEnums.usehttp.ToString()], out var useHttp); UseHttp = useHttp; TableName = configuration[AppConfigParameterEnums.tablename.ToString()]?.Trim(); + + if (string.IsNullOrWhiteSpace(TableName)) + throw new ArgumentException("DynamoDB table name is required.", nameof(configuration)); + if (string.IsNullOrWhiteSpace(Region) && string.IsNullOrWhiteSpace(ServiceUrl)) + throw new ArgumentException("DynamoDB requires either a region or a service URL.", nameof(configuration)); + if (!string.IsNullOrWhiteSpace(ServiceUrl) && !Uri.TryCreate(ServiceUrl, UriKind.Absolute, out _)) + throw new ArgumentException($"DynamoDB service URL '{ServiceUrl}' is not a valid absolute URL.", nameof(configuration)); } } } diff --git a/src/SharpConnector/Configuration/RavenDbConfig.cs b/src/SharpConnector/Configuration/RavenDbConfig.cs index caf11f0..019f031 100755 --- a/src/SharpConnector/Configuration/RavenDbConfig.cs +++ b/src/SharpConnector/Configuration/RavenDbConfig.cs @@ -15,6 +15,16 @@ public class RavenDbConfig : IConnectorConfig public string ConnectionString { get; } public string DatabaseName { get; } + /// + /// Optional path to the client certificate (.pfx) used to authenticate against a secured RavenDB server. + /// + public string CertificatePath { get; } + + /// + /// Optional password protecting the client certificate. Used verbatim. + /// + public string CertificatePassword { get; } + #region NOT USED public string CollectionName { get; private set; } public int DatabaseNumber { get; private set; } @@ -38,6 +48,15 @@ public RavenDbConfig(IConfiguration configuration) ConnectionString = configuration[AppConfigParameterEnums.connectionstring.ToString()]?.Trim(); DatabaseName = configuration[AppConfigParameterEnums.databasename.ToString()]?.Trim(); + CertificatePath = configuration[AppConfigParameterEnums.certificatepath.ToString()]?.Trim(); + CertificatePassword = configuration[AppConfigParameterEnums.certificatepassword.ToString()]; + + if (string.IsNullOrWhiteSpace(ConnectionString)) + throw new ArgumentException("RavenDB connection string is required.", nameof(configuration)); + if (!Uri.TryCreate(ConnectionString, UriKind.Absolute, out _)) + throw new ArgumentException($"RavenDB connection string '{ConnectionString}' is not a valid absolute URL.", nameof(configuration)); + if (string.IsNullOrWhiteSpace(DatabaseName)) + throw new ArgumentException("RavenDB database name is required.", nameof(configuration)); } } } diff --git a/src/SharpConnector/Configuration/RedisConfig.cs b/src/SharpConnector/Configuration/RedisConfig.cs index e64be8d..f2cb5ed 100755 --- a/src/SharpConnector/Configuration/RedisConfig.cs +++ b/src/SharpConnector/Configuration/RedisConfig.cs @@ -15,6 +15,11 @@ public class RedisConfig : IConnectorConfig public string ConnectionString { get; } public int DatabaseNumber { get; } // 0 default + /// + /// Optional prefix applied to every key. When set, GetAll/Query only scan keys with this prefix. + /// + public string KeyPrefix { get; } + #region NOT USED public string DatabaseName { get; private set; } public string CollectionName { get; private set; } @@ -42,6 +47,7 @@ public RedisConfig(IConfiguration configuration) int.TryParse(configuration[AppConfigParameterEnums.databasenumber.ToString()], out var dbNumber); DatabaseNumber = dbNumber; + KeyPrefix = configuration[AppConfigParameterEnums.keyprefix.ToString()]?.Trim() ?? string.Empty; } } } diff --git a/src/SharpConnector/Connectors/ArangoDb/ArangoDbWrapper.cs b/src/SharpConnector/Connectors/ArangoDb/ArangoDbWrapper.cs index e97aeee..177091b 100644 --- a/src/SharpConnector/Connectors/ArangoDb/ArangoDbWrapper.cs +++ b/src/SharpConnector/Connectors/ArangoDb/ArangoDbWrapper.cs @@ -62,9 +62,7 @@ await _arangoDbAccess.Client.Collection /// The document key. public ConnectorEntity Get(string key) { - return GetAsync(key, CancellationToken.None) - .GetAwaiter() - .GetResult(); + return AsyncHelper.RunSync(() => GetAsync(key, CancellationToken.None)); } /// @@ -102,9 +100,7 @@ private static bool IsNotFound(ApiErrorException ex) => /// public List GetAll() { - return GetAllAsync(CancellationToken.None) - .GetAwaiter() - .GetResult(); + return AsyncHelper.RunSync(() => GetAllAsync(CancellationToken.None)); } /// @@ -151,9 +147,7 @@ public async Task> GetAllAsync(CancellationToken ct = defa /// The document to insert. public bool Insert(ConnectorEntity connectorEntity) { - return InsertAsync(connectorEntity, CancellationToken.None) - .GetAwaiter() - .GetResult(); + return AsyncHelper.RunSync(() => InsertAsync(connectorEntity, CancellationToken.None)); } /// @@ -178,9 +172,7 @@ public async Task InsertAsync(ConnectorEntity connectorEntity, Cancellatio /// The documents to insert. public bool InsertMany(List connectorEntities) { - return InsertManyAsync(connectorEntities, CancellationToken.None) - .GetAwaiter() - .GetResult(); + return AsyncHelper.RunSync(() => InsertManyAsync(connectorEntities, CancellationToken.None)); } /// @@ -208,9 +200,7 @@ public async Task InsertManyAsync(List connectorEntities, /// The document to update. public bool Update(ConnectorEntity connectorEntity) { - return UpdateAsync(connectorEntity, CancellationToken.None) - .GetAwaiter() - .GetResult(); + return AsyncHelper.RunSync(() => UpdateAsync(connectorEntity, CancellationToken.None)); } /// @@ -241,9 +231,7 @@ await _arangoDbAccess.Client.Document /// The key of the document to delete. public bool Delete(string key) { - return DeleteAsync(key, CancellationToken.None) - .GetAwaiter() - .GetResult(); + return AsyncHelper.RunSync(() => DeleteAsync(key, CancellationToken.None)); } /// @@ -282,9 +270,7 @@ public void Dispose() /// The document key. public bool Exists(string key) { - return ExistsAsync(key, CancellationToken.None) - .GetAwaiter() - .GetResult(); + return AsyncHelper.RunSync(() => ExistsAsync(key, CancellationToken.None)); } /// @@ -303,9 +289,7 @@ public async Task ExistsAsync(string key, CancellationToken ct = default) /// Predicate used to filter items. public List Query(Func filter) { - return QueryAsync(filter, CancellationToken.None) - .GetAwaiter() - .GetResult(); + return AsyncHelper.RunSync(() => QueryAsync(filter, CancellationToken.None)); } /// diff --git a/src/SharpConnector/Connectors/Couchbase/CouchbaseAccess.cs b/src/SharpConnector/Connectors/Couchbase/CouchbaseAccess.cs index 2e848bb..354ba95 100644 --- a/src/SharpConnector/Connectors/Couchbase/CouchbaseAccess.cs +++ b/src/SharpConnector/Connectors/Couchbase/CouchbaseAccess.cs @@ -27,17 +27,14 @@ public CouchbaseAccess(CouchbaseConfig config) private async Task ConnectClusterAsync(CouchbaseConfig config) { - var clusterOptions = new ClusterOptions - { - UserName = config.Username, - Password = config.Password - }; - return await Cluster.ConnectAsync(config.ConnectionString, clusterOptions); + var clusterOptions = new ClusterOptions() + .WithPasswordAuthentication(config.Username, config.Password); + return await Cluster.ConnectAsync(config.ConnectionString, clusterOptions).ConfigureAwait(false); } public async Task GetClusterAsync() { - return await _cluster.Value; + return await _cluster.Value.ConfigureAwait(false); } public async Task GetBucketAsync() diff --git a/src/SharpConnector/Connectors/Couchbase/CouchbaseWrapper.cs b/src/SharpConnector/Connectors/Couchbase/CouchbaseWrapper.cs index 7189d84..bf6aaa5 100644 --- a/src/SharpConnector/Connectors/Couchbase/CouchbaseWrapper.cs +++ b/src/SharpConnector/Connectors/Couchbase/CouchbaseWrapper.cs @@ -171,12 +171,8 @@ public async ValueTask DisposeAsync() /// /// The key of the entity to check. /// True if the entity exists; otherwise, false. - public bool Exists(string key) - { - var collection = GetCollectionAsync(CancellationToken.None).GetAwaiter().GetResult(); - var result = collection.ExistsAsync(key).GetAwaiter().GetResult(); - return result.Exists; - } + public bool Exists(string key) => + AsyncHelper.RunSync(() => ExistsAsync(key)); /// /// Checks whether an entity exists in the Couchbase bucket by its key asynchronously. diff --git a/src/SharpConnector/Connectors/DynamoDB/DynamoDbWrapper.cs b/src/SharpConnector/Connectors/DynamoDB/DynamoDbWrapper.cs index d834c0c..4bb0077 100644 --- a/src/SharpConnector/Connectors/DynamoDB/DynamoDbWrapper.cs +++ b/src/SharpConnector/Connectors/DynamoDB/DynamoDbWrapper.cs @@ -38,13 +38,8 @@ public DynamoDbWrapper(DynamoDbConfig dynamoDbConfig) /// Get an item by key (sync). /// /// The key of the item. - public ConnectorEntity Get(string key) - { - var document = _table.GetItemAsync(key).GetAwaiter().GetResult(); - return document != null - ? JsonConvert.DeserializeObject(document.ToJson()).DiscardIfExpired() - : null; - } + public ConnectorEntity Get(string key) => + AsyncHelper.RunSync(() => GetAsync(key)); /// /// Get an item by key (async). @@ -62,22 +57,8 @@ public async Task GetAsync(string key, CancellationToken ct = d /// /// Get all items in the table (sync). /// - public IEnumerable GetAll() - { - var scanConfig = new ScanOperationConfig(); - var search = _table.Scan(scanConfig); - - var result = new List(); - do - { - var documents = search.GetNextSetAsync().GetAwaiter().GetResult(); - result.AddRange(documents - .Select(doc => JsonConvert.DeserializeObject(doc.ToJson())) - .WhereNotExpired()); - } while (!search.IsDone); - - return result; - } + public IEnumerable GetAll() => + AsyncHelper.RunSync(() => GetAllAsync()); /// /// Get all items in the table (async). @@ -105,12 +86,8 @@ public async Task> GetAllAsync(CancellationToken ct /// Insert (Put) an item (sync). /// /// The entity to insert. - public bool Insert(ConnectorEntity connectorEntity) - { - var document = Document.FromJson(JsonConvert.SerializeObject(connectorEntity)); - _table.PutItemAsync(document).GetAwaiter().GetResult(); - return true; - } + public bool Insert(ConnectorEntity connectorEntity) => + AsyncHelper.RunSync(() => InsertAsync(connectorEntity)); /// /// Insert (Put) an item (async). @@ -128,18 +105,8 @@ public async Task InsertAsync(ConnectorEntity connectorEntity, Cancellatio /// Insert multiple items (sync). /// /// The entities to insert. - public bool InsertMany(List connectorEntities) - { - var batchWrite = _table.CreateBatchWrite(); - foreach (var entity in connectorEntities) - { - var document = Document.FromJson(JsonConvert.SerializeObject(entity)); - batchWrite.AddDocumentToPut(document); - } - - batchWrite.ExecuteAsync().GetAwaiter().GetResult(); - return true; - } + public bool InsertMany(List connectorEntities) => + AsyncHelper.RunSync(() => InsertManyAsync(connectorEntities)); /// /// Insert multiple items (async). @@ -187,7 +154,7 @@ public async Task InsertManyAsync(IEnumerable values, Can /// The key of the item to delete. public bool Delete(string key) { - return DeleteAsync(key).GetAwaiter().GetResult(); + return AsyncHelper.RunSync(() => DeleteAsync(key)); } /// @@ -220,7 +187,7 @@ public async Task DeleteAsync(string key, CancellationToken ct = default) /// The entity to update. public bool Update(ConnectorEntity connectorEntity) { - return UpdateAsync(connectorEntity).GetAwaiter().GetResult(); + return AsyncHelper.RunSync(() => UpdateAsync(connectorEntity)); } /// diff --git a/src/SharpConnector/Connectors/RavenDb/RavenDbAccess.cs b/src/SharpConnector/Connectors/RavenDb/RavenDbAccess.cs index 055d5db..915c408 100755 --- a/src/SharpConnector/Connectors/RavenDb/RavenDbAccess.cs +++ b/src/SharpConnector/Connectors/RavenDb/RavenDbAccess.cs @@ -3,6 +3,8 @@ using Raven.Client.Documents; using SharpConnector.Configuration; using System; +using System.IO; +using System.Security.Cryptography.X509Certificates; namespace SharpConnector.Connectors.RavenDb { @@ -21,7 +23,8 @@ public RavenDbAccess(RavenDbConfig ravenDbConfig) var documentStore = new DocumentStore { Urls = [ravenDbConfig.ConnectionString], - Database = ravenDbConfig.DatabaseName + Database = ravenDbConfig.DatabaseName, + Certificate = LoadCertificate(ravenDbConfig) }; documentStore.Initialize(); @@ -29,6 +32,17 @@ public RavenDbAccess(RavenDbConfig ravenDbConfig) }); } + internal static X509Certificate2 LoadCertificate(RavenDbConfig ravenDbConfig) + { + if (string.IsNullOrWhiteSpace(ravenDbConfig.CertificatePath)) + return null; + + if (!File.Exists(ravenDbConfig.CertificatePath)) + throw new FileNotFoundException("RavenDB client certificate not found.", ravenDbConfig.CertificatePath); + + return X509CertificateLoader.LoadPkcs12FromFile(ravenDbConfig.CertificatePath, ravenDbConfig.CertificatePassword); + } + /// /// Return the DocumentStore. /// diff --git a/src/SharpConnector/Connectors/Redis/RedisWrapper.cs b/src/SharpConnector/Connectors/Redis/RedisWrapper.cs index 7627bbf..994e057 100755 --- a/src/SharpConnector/Connectors/Redis/RedisWrapper.cs +++ b/src/SharpConnector/Connectors/Redis/RedisWrapper.cs @@ -1,10 +1,11 @@ -// (c) 2020 Francesco Del Re +// (c) 2020 Francesco Del Re // This code is licensed under MIT license (see LICENSE.txt for details) using System.Collections.Generic; using Newtonsoft.Json; using SharpConnector.Configuration; using SharpConnector.Entities; using StackExchange.Redis; +using StackExchange.Redis.KeyspaceIsolation; using System.Threading.Tasks; using System.Linq; using System.Threading; @@ -14,7 +15,9 @@ namespace SharpConnector.Connectors.Redis { public class RedisWrapper : IDisposable { + private const int ReadBatchSize = 256; private readonly RedisAccess _redisAccess; + private readonly string _keyPrefix; /// /// Create a new RedisWrapper instance. @@ -22,6 +25,7 @@ public class RedisWrapper : IDisposable /// The Redis connector config. public RedisWrapper(RedisConfig redisConfig) { + _keyPrefix = redisConfig.KeyPrefix ?? string.Empty; _redisAccess = new RedisAccess(redisConfig); } @@ -35,11 +39,28 @@ public void Dispose() } /// - /// Get a Redis database. + /// Get a Redis database; keys are transparently prefixed when a KeyPrefix is configured. /// - private IDatabase GetDatabase(int databaseNumber) => + private IDatabase GetDatabase(int databaseNumber) + { + var database = _redisAccess.Connection.GetDatabase(databaseNumber); + return _keyPrefix.Length == 0 + ? database + : database.WithKeyPrefix(_keyPrefix); + } + + /// + /// Get the raw (non-prefixed) database, used with fully-qualified keys returned by SCAN. + /// + private IDatabase GetRawDatabase(int databaseNumber) => _redisAccess.Connection.GetDatabase(databaseNumber); + /// + /// Pattern used to scan keys owned by this connector. + /// + internal static RedisValue BuildScanPattern(string keyPrefix) => + string.IsNullOrEmpty(keyPrefix) ? default : keyPrefix + "*"; + /// /// Serialize an object to JSON. /// @@ -87,7 +108,8 @@ public async Task GetAsync(string key, int databaseNumber = 0, public IEnumerable GetAll(int databaseNumber = 0) { var connection = _redisAccess.Connection; - var database = GetDatabase(databaseNumber); + var database = GetRawDatabase(databaseNumber); + var pattern = BuildScanPattern(_keyPrefix); var entities = new List(); foreach (var endpoint in connection.GetEndPoints()) @@ -97,7 +119,7 @@ public IEnumerable GetAll(int databaseNumber = 0) if (server.IsReplica) continue; - var keys = server.Keys(databaseNumber); + var keys = server.Keys(databaseNumber, pattern); foreach (var key in keys) { @@ -132,7 +154,8 @@ public IEnumerable GetAll(int databaseNumber = 0) public async Task> GetAllAsync(int databaseNumber = 0, CancellationToken ct = default) { var connection = _redisAccess.Connection; - var database = GetDatabase(databaseNumber); + var database = GetRawDatabase(databaseNumber); + var pattern = BuildScanPattern(_keyPrefix); var entities = new List(); foreach (var endpoint in connection.GetEndPoints()) @@ -144,22 +167,32 @@ public async Task> GetAllAsync(int databaseNumber = if (server.IsReplica) continue; - var keys = server.Keys(databaseNumber); - var tasks = new List>(); - - foreach (var key in keys) + var batch = new List>(ReadBatchSize); + await foreach (var key in server.KeysAsync(databaseNumber, pattern).WithCancellation(ct).ConfigureAwait(false)) { - ct.ThrowIfCancellationRequested(); - tasks.Add(GetEntityAsync(database, key, ct)); + batch.Add(GetEntityAsync(database, key, ct)); + if (batch.Count < ReadBatchSize) + continue; + + await FlushBatchAsync(batch, entities).ConfigureAwait(false); } - var results = await Task.WhenAll(tasks).ConfigureAwait(false); - entities.AddRange(results.Where(e => e != null)); + await FlushBatchAsync(batch, entities).ConfigureAwait(false); } return entities; } + private static async Task FlushBatchAsync(List> batch, List entities) + { + if (batch.Count == 0) + return; + + var results = await Task.WhenAll(batch).ConfigureAwait(false); + entities.AddRange(results.Where(e => e != null)); + batch.Clear(); + } + private static async Task GetEntityAsync(IDatabase database, RedisKey key, CancellationToken ct) { ct.ThrowIfCancellationRequested(); @@ -236,7 +269,7 @@ public async Task InsertAsync(ConnectorEntity connectorEntity, int databas /// A token to cancel the asynchronous operation. public async Task InsertManyAsync(List connectorEntities, int databaseNumber = 0, CancellationToken ct = default) { - var database = _redisAccess.Connection.GetDatabase(databaseNumber); + var database = GetDatabase(databaseNumber); var tasks = new List>(); foreach (var entity in connectorEntities) @@ -257,7 +290,7 @@ public async Task InsertManyAsync(List connectorEntities, public bool InsertMany(List connectorEntities, int databaseNumber = 0) { var result = true; - var database = _redisAccess.Connection.GetDatabase(databaseNumber); + var database = GetDatabase(databaseNumber); foreach (var entity in connectorEntities) { var currentResult = database.StringSet( diff --git a/src/SharpConnector/Enums/AppConfigParameterEnums.cs b/src/SharpConnector/Enums/AppConfigParameterEnums.cs index 870fc51..b4100ad 100755 --- a/src/SharpConnector/Enums/AppConfigParameterEnums.cs +++ b/src/SharpConnector/Enums/AppConfigParameterEnums.cs @@ -16,6 +16,9 @@ public enum AppConfigParameterEnums region, serviceurl, usehttp, - tablename + tablename, + keyprefix, + certificatepath, + certificatepassword } } diff --git a/src/SharpConnector/Middleware/SharpConnectorServiceExtensions.cs b/src/SharpConnector/Middleware/SharpConnectorServiceExtensions.cs index b37b342..77b198d 100644 --- a/src/SharpConnector/Middleware/SharpConnectorServiceExtensions.cs +++ b/src/SharpConnector/Middleware/SharpConnectorServiceExtensions.cs @@ -22,8 +22,6 @@ public static class SharpConnectorServiceExtensions /// The IServiceCollection with the added service. public static IServiceCollection AddSharpConnectorServicesScoped(this IServiceCollection services) { - // Adds MVC controllers to the service collection, necessary for handling HTTP requests. - services.AddControllers(); // Registers the ISharpConnectorClient as Scoped, meaning it will have a different instance for each HTTP request. services.AddScoped>(sp => @@ -48,8 +46,6 @@ public static IServiceCollection AddSharpConnectorServicesScoped(this IServic /// The IServiceCollection with the added service. public static IServiceCollection AddSharpConnectorServicesSingleton(this IServiceCollection services) { - // Adds MVC controllers to the service collection, necessary for handling HTTP requests. - services.AddControllers(); // Registers the ISharpConnectorClient as Singleton, meaning only one instance will exist for the entire application. services.AddSingleton>(sp => diff --git a/src/SharpConnector/Operations/CouchbaseOperations.cs b/src/SharpConnector/Operations/CouchbaseOperations.cs index 54a54b1..912132f 100644 --- a/src/SharpConnector/Operations/CouchbaseOperations.cs +++ b/src/SharpConnector/Operations/CouchbaseOperations.cs @@ -339,7 +339,7 @@ public override void Dispose() { // CouchbaseWrapper implements IAsyncDisposable; dispose synchronously here. if (_couchbaseWrapper != null) - _couchbaseWrapper.DisposeAsync().AsTask().GetAwaiter().GetResult(); + AsyncHelper.RunSync(() => _couchbaseWrapper.DisposeAsync().AsTask()); base.Dispose(); } } diff --git a/src/SharpConnector/Utilities/AsyncHelper.cs b/src/SharpConnector/Utilities/AsyncHelper.cs new file mode 100644 index 0000000..a31d8ff --- /dev/null +++ b/src/SharpConnector/Utilities/AsyncHelper.cs @@ -0,0 +1,32 @@ +// (c) 2025 Francesco Del Re +// This code is licensed under MIT license (see LICENSE.txt for details) +using System; +using System.Threading.Tasks; + +namespace SharpConnector.Utilities +{ + /// + /// Runs asynchronous delegates synchronously on the thread pool, so that a captured + /// SynchronizationContext cannot cause a deadlock when blocking on the result. + /// + internal static class AsyncHelper + { + /// + /// Executes the asynchronous function and blocks until it completes, returning its result. + /// + public static T RunSync(Func> func) + { + ArgumentNullException.ThrowIfNull(func); + return Task.Run(func).GetAwaiter().GetResult(); + } + + /// + /// Executes the asynchronous function and blocks until it completes. + /// + public static void RunSync(Func func) + { + ArgumentNullException.ThrowIfNull(func); + Task.Run(func).GetAwaiter().GetResult(); + } + } +} From 1caeb17aa14c0c299661591cc94b8fc83265492a Mon Sep 17 00:00:00 2001 From: Francesco Del Re Date: Wed, 28 Oct 2026 00:51:25 +0100 Subject: [PATCH 7/7] docs(readme): rewrite README for 5.0 with .NET 10/9 targets and new settings --- README.md | 560 ++++++++++++++--------- src/SharpConnector/SharpConnector.csproj | 7 +- 2 files changed, 339 insertions(+), 228 deletions(-) diff --git a/README.md b/README.md index 7c3cfa1..2af7e71 100755 --- a/README.md +++ b/README.md @@ -1,263 +1,373 @@ +
+ +SharpConnector logo + # SharpConnector -[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) -[![Nuget](https://img.shields.io/nuget/v/SharpConnector?style=plastic)](https://www.nuget.org/packages/SharpConnector) -![NuGet Downloads](https://img.shields.io/nuget/dt/SharpConnector) -[![issues - dotnet-design-patterns](https://img.shields.io/github/issues/engineering87/SharpConnector)](https://github.com/engineering87/SharpConnector/issues) -[![Build](https://github.com/engineering87/SharpConnector/actions/workflows/dotnet.yml/badge.svg)](https://github.com/engineering87/SharpConnector/actions/workflows/dotnet.yml) -[![stars - dotnet-design-patterns](https://img.shields.io/github/stars/engineering87/SharpConnector?style=social)](https://github.com/engineering87/SharpConnector) +**One API, nine NoSQL databases.** +A unified, DI-friendly .NET client for key-based CRUD across Redis, MongoDB, LiteDB, Memcached, RavenDB, Couchbase, DynamoDB, ArangoDB and Cassandra. - +[![NuGet](https://img.shields.io/nuget/v/SharpConnector?logo=nuget)](https://www.nuget.org/packages/SharpConnector) +[![NuGet Downloads](https://img.shields.io/nuget/dt/SharpConnector)](https://www.nuget.org/packages/SharpConnector) +[![Build](https://github.com/engineering87/SharpConnector/actions/workflows/dotnet.yml/badge.svg)](https://github.com/engineering87/SharpConnector/actions/workflows/dotnet.yml) +![.NET](https://img.shields.io/badge/.NET-10.0%20%7C%209.0-512BD4?logo=dotnet) +[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) +[![Issues](https://img.shields.io/github/issues/engineering87/SharpConnector)](https://github.com/engineering87/SharpConnector/issues) +[![Stars](https://img.shields.io/github/stars/engineering87/SharpConnector?style=social)](https://github.com/engineering87/SharpConnector) -SharpConnector is a .NET library designed to streamline integration with NoSQL databases. It provides a unified interface that simplifies database operations, eliminating the need to develop custom logic for each specific database connector. Since each NoSQL database has its own unique characteristics, such as being document-oriented or key-value-based, SharpConnector abstracts these differences, providing a consistent and simplified access layer to accelerate development. +
-✅ Now targeting .NET 9. +--- ## Table of Contents -- [Features](#features) +- [Why SharpConnector](#why-sharpconnector) +- [Supported databases](#supported-databases) +- [Requirements](#requirements) - [Installation](#installation) - - [How it works](#how-it-works) - - [How to use it](#how-to-use-it) -- [API Overview](#api-overview) -- [Contributing](#contributing) +- [Quick start](#quick-start) +- [Configuration](#configuration) +- [API overview](#api-overview) +- [Operation semantics](#operation-semantics) +- [Upgrading from 4.x to 5.0](#upgrading-from-4x-to-50) +- [Building from source](#building-from-source) - [Extending](#extending) +- [Contributing](#contributing) +- [Third-party licenses](#third-party-licenses) - [License](#license) -- [External References](#external-references) - [Contact](#contact) -## Features +## Why SharpConnector -- A single, generic client API for CRUD across multiple NoSQL engines -- Supported stores: - - Key–value: Redis, EnyimMemcached, DynamoDb - - Document: MongoDB, LiteDB, RavenDB, Couchbase - - Wide-column: Cassandra - - Multi-model: ArangoDB -- Simple configuration via `appsettings.json` and DI-friendly -- Sync and async operations (with CancellationToken support) -- Easy to extend: implement `IOperations` for new connectors +Every NoSQL engine has its own driver, data model and quirks. SharpConnector hides those differences behind a single generic interface, `ISharpConnectorClient`, so that you can: -## Installation +- switch database by changing **one line of configuration**; +- use the **same CRUD code** (sync and async, with `CancellationToken`) everywhere; +- get **consistent semantics** for upserts, updates, deletes and expiration on every backend; +- plug it into ASP.NET Core with a **single DI call**. + +## Supported databases + +| Database | `Instance` | Model | Driver | +|------------|-------------|--------------|-------------------------| +| Redis | `Redis` | Key-value | StackExchange.Redis | +| MongoDB | `MongoDb` | Document | MongoDB.Driver | +| LiteDB | `LiteDb` | Embedded doc | LiteDB | +| Memcached | `Memcached` | Key-value | EnyimMemcachedCore | +| RavenDB | `RavenDb` | Document | RavenDB.Client | +| Couchbase | `Couchbase` | Document | CouchbaseNetClient | +| DynamoDB | `DynamoDb` | Key-value | AWSSDK.DynamoDBv2 | +| ArangoDB | `ArangoDb` | Multi-model | ArangoDBNetStandard | +| Cassandra | `Cassandra` | Wide-column | CassandraCSharpDriver | + +## Requirements -You can install the library via the NuGet package manager with the following command: +- **.NET 10** or **.NET 9**: the package ships `net10.0` and `net9.0` assemblies, and NuGet automatically picks the best match for your project. + +## Installation ```bash dotnet add package SharpConnector ``` -### How it works -SharpConnector offers a unified interface for performing CRUD operations on various types of NoSQL databases. While NoSQL databases often differ in their internal structures (e.g., key-value stores, document databases), this library abstracts these distinctions, enabling streamlined key-value-based CRUD operations. -Through SharpConnector, you can use a consistent interface to perform Insert, Get, Delete, and Update operations across multiple NoSQL systems, currently supporting: - -* **Redis (key-value)** -* **MongoDB (key-value or document-oriented)** -* **LiteDB (embedded document database)** -* **EnyimMemcached (key-value)** -* **RavenDB (document-oriented)** -* **Couchbase (document-oriented)** -* **DynamoDb (key-value or document-oriented)** -* **ArangoDB (multi-model)** -* **Apache Cassandra (wide-column)** - -SharpConnector thus simplifies the development process, providing flexibility and compatibility across diverse NoSQL paradigms without the need to handle specific database implementations. - -### How to use it -To get started with SharpConnector, configure the connector *instance* type. -Then, add the specif `ConnectorConfig` node within your *appsettings.json* file: - -- Redis - ```json - { - "ConnectorConfig": { - "Instance": "Redis", - "DatabaseNumber": 0, - "ConnectionString": "redisServer:6380,password=password,ssl=True,abortConnect=False" - } - } - ``` -- MongoDb - ```json - { - "ConnectorConfig": { - "Instance": "MongoDb", - "DatabaseName": "test", - "CollectionName": "test", - "ConnectionString": "mongodb_connectionstring_here" - } - } - ``` - -- LiteDB - ```json - { - "ConnectorConfig": { - "Instance": "LiteDb", - "CollectionName": "test", - "ConnectionString": "LiteDbTest.db" - } - } - ``` - -- Memcached - ```json - { - "ConnectorConfig": { - "Instance": "Memcached", - "ConnectionString": "127.0.0.1:11211" - } - } - ``` - -- RavenDB - ```json - { - "ConnectorConfig": { - "Instance": "RavenDb", - "DatabaseName": "test", - "ConnectionString": "http://live-test.ravendb.net" - } - } - ``` - -- Couchbase - ```json - { - "ConnectorConfig": { - "Instance": "Couchbase", - "ConnectionString": "couchbase://localhost", - "Username": "Administrator", - "Password": "password", - "BucketName": "example_bucket" - } - } - ``` - -- DynamoDb - ```json - { - "ConnectorConfig": { - "Instance": "DynamoDb", - "AccessKey": "your-access-key-here", - "SecretKey": "your-secret-key-here", - "Region": "us-west-2", - "ServiceUrl": "https://dynamodb.us-west-2.amazonaws.com", - "UseHttp": false, - "TableName": "MyTableName" - } - } - ``` - -- ArangoDB - ```json - { - "ConnectorConfig": { - "Instance": "ArangoDb", - "ConnectionString": "http://localhost:8529", - "Username": "username", - "Password": "password", - "CollectionName": "test" - } - } - ``` - -- Cassandra - ```json - { - "ConnectorConfig": { - "Instance": "Cassandra", - "ConnectionString": "127.0.0.1:9042", - "DatabaseName": "sharpconnector", - "TableName": "items", - "Username": "cassandra", - "Password": "cassandra" - } - } - ``` - -Once configured, create a new SharpConnector client, specifying the payload type (e.g., string): +## Quick start -```csharp -SharpConnectorClient client = new SharpConnectorClient(); +**1. Add a `ConnectorConfig` section to `appsettings.json`** + +```json +{ + "ConnectorConfig": { + "Instance": "Redis", + "DatabaseNumber": 0, + "ConnectionString": "localhost:6379" + } +} ``` -Alternatively, you can integrate SharpConnector client using dependency injection. Here how to register the SharpConnector service with a simple string payload type: +**2a. Use it with dependency injection (recommended)** ```csharp -// Register the SharpConnector services with string payload type. builder.Services.AddSharpConnectorServices(); + +app.MapGet("/items/{key}", async (string key, ISharpConnectorClient client, CancellationToken ct) => + await client.GetAsync(key, ct) is { } value ? Results.Ok(value) : Results.NotFound()); ``` -`AddSharpConnectorServices()` registers the client as a singleton (recommended). `AddSharpConnectorServicesScoped()` is also available, but it opens a new database connection for every scope. -This setup provides flexibility in working with different payload types and makes SharpConnector easy to use within dependency injection configurations. - -## API Overview -The main entry point is the generic `ISharpConnectorClient`: -- `T Get(string key)` -- `Task GetAsync(string key, CancellationToken ct = default)` -- `IEnumerable GetAll()` -- `Task> GetAllAsync(CancellationToken ct = default)` -- `bool Insert(string key, T value)` -- `bool Insert(string key, T value, TimeSpan expiration)` -- `Task InsertAsync(string key, T value, CancellationToken ct = default)` -- `Task InsertAsync(string key, T value, TimeSpan expiration, CancellationToken ct = default)` -- `bool InsertMany(Dictionary values)` -- `bool InsertMany(Dictionary values, TimeSpan expiration)` -- `Task InsertManyAsync(Dictionary values)` -- `Task InsertManyAsync(Dictionary values, TimeSpan expiration)` -- `Task> InsertManyAsync(IEnumerable values, CancellationToken ct = default)` -- `bool Update(string key, T value)` -- `Task UpdateAsync(string key, T value, CancellationToken ct = default)` -- `bool Delete(string key)` -- `Task DeleteAsync(string key, CancellationToken ct = default)` -- `bool Exists(string key)` -- `Task ExistsAsync(string key, CancellationToken ct = default)` -- `IEnumerable Query(Func filter)` -- `Task> QueryAsync(Func filter, CancellationToken ct = default)` - -### Operation semantics -- `Insert` / `InsertMany` behave as an upsert: an existing key is overwritten (MongoDB and LiteDB enforce a unique index on `Key`). -- `Update` only modifies existing keys and returns `false` when the key does not exist. -- `Delete` returns `true` only when an item was actually removed. -- `InsertMany` throws `ArgumentException` when a key is null/empty or a value is null. -- Expired items are never returned by `Get`, `GetAll`, `Exists` or `Query`, even on backends without native TTL. -- `Username` is trimmed, `Password` is used verbatim. -- Cassandra `ConnectionString` accepts a comma-separated list of contact points (`host`, `host:port`, `[IPv6]:port`); all ports must match. -- Memcached `ConnectionString` accepts a comma-separated list of `host:port` servers. -## Contributing -Thanks for considering a contribution! Please fork, branch, and open a PR. -- Add unit tests for new features or connectors -- Keep third-party dependencies compatible with MIT and document their licenses -- Useful links: - - [Setting up Git](https://docs.github.com/en/get-started/getting-started-with-git/set-up-git) - - [Fork the repository](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/working-with-forks/fork-a-repo) - - [Open an issue](https://github.com/engineering87/SharpConnector/issues) if you encounter a bug or have a suggestion for improvements/features +**2b. Or create the client directly** + +```csharp +var client = new SharpConnectorClient(); // reads appsettings.json +// new SharpConnectorClient(configuration); // from an IConfiguration +// new SharpConnectorClient("connector.json"); // from a custom JSON file + +client.Insert("greeting", "hello"); +client.Insert("session", "abc", TimeSpan.FromMinutes(20)); // with expiration +var value = await client.GetAsync("greeting"); +``` + +### Registration lifetimes + +| Method | Lifetime | Notes | +|-------------------------------------------|-----------|---------------------------------------------------| +| `AddSharpConnectorServices()` | Singleton | Recommended: one connection shared by the app | +| `AddSharpConnectorServicesSingleton()` | Singleton | Same as above, explicit name | +| `AddSharpConnectorServicesScoped()` | Scoped | Opens a new database connection for every scope | + +> Starting from 5.0 these methods only register SharpConnector. If you use MVC controllers, call `builder.Services.AddControllers()` yourself. + +## Configuration + +All settings live under the `ConnectorConfig` section. Key names are case-insensitive. + +| Key | Used by | Description | +|---------------------------|----------------------------------------|---------------------------------------------------------| +| `Instance` | all | Connector type (see table above) | +| `ConnectionString` | all except DynamoDB | Server address / connection string / file path | +| `DatabaseNumber` | Redis | Logical database index | +| `KeyPrefix` | Redis | *Optional.* Prefix applied to every key, e.g. `app:` | +| `DatabaseName` | MongoDB, RavenDB, Cassandra (keyspace) | Database name | +| `CollectionName` | MongoDB, LiteDB, ArangoDB | Collection name | +| `TableName` | DynamoDB, Cassandra | Table name | +| `BucketName` | Couchbase | Bucket name | +| `Username` / `Password` | Couchbase, ArangoDB, Cassandra | Credentials (username is trimmed, password is verbatim) | +| `CertificatePath` | RavenDB | *Optional.* Path to a PFX client certificate | +| `CertificatePassword` | RavenDB | *Optional.* Password of the PFX certificate | +| `AccessKey` / `SecretKey` | DynamoDB | AWS credentials | +| `Region` | DynamoDB | AWS region (required if `ServiceUrl` is not set) | +| `ServiceUrl` | DynamoDB | Custom endpoint, e.g. DynamoDB Local | +| `UseHttp` | DynamoDB | Use HTTP instead of HTTPS | + +
+Redis + +```json +{ + "ConnectorConfig": { + "Instance": "Redis", + "DatabaseNumber": 0, + "KeyPrefix": "myapp:", + "ConnectionString": "redisServer:6380,password=password,ssl=True,abortConnect=False" + } +} +``` +
+ +
+MongoDB + +```json +{ + "ConnectorConfig": { + "Instance": "MongoDb", + "DatabaseName": "test", + "CollectionName": "test", + "ConnectionString": "mongodb://localhost:27017" + } +} +``` +
+ +
+LiteDB + +```json +{ + "ConnectorConfig": { + "Instance": "LiteDb", + "CollectionName": "test", + "ConnectionString": "LiteDbTest.db" + } +} +``` +
+ +
+Memcached + +`ConnectionString` accepts a comma-separated list of `host:port` servers. + +```json +{ + "ConnectorConfig": { + "Instance": "Memcached", + "ConnectionString": "127.0.0.1:11211" + } +} +``` +
+ +
+RavenDB + +`ConnectionString` must be an absolute URL and `DatabaseName` is required. The certificate settings are optional and needed only for secured servers. + +```json +{ + "ConnectorConfig": { + "Instance": "RavenDb", + "DatabaseName": "test", + "ConnectionString": "https://a.mycluster.ravendb.cloud", + "CertificatePath": "certs/client.pfx", + "CertificatePassword": "pfx-password" + } +} +``` +
+ +
+Couchbase + +```json +{ + "ConnectorConfig": { + "Instance": "Couchbase", + "ConnectionString": "couchbase://localhost", + "Username": "Administrator", + "Password": "password", + "BucketName": "example_bucket" + } +} +``` +
+ +
+DynamoDB + +`TableName` is required, together with either `Region` or `ServiceUrl`. The table must use a string hash key named `Key`. + +```json +{ + "ConnectorConfig": { + "Instance": "DynamoDb", + "AccessKey": "your-access-key-here", + "SecretKey": "your-secret-key-here", + "Region": "us-west-2", + "TableName": "MyTableName" + } +} +``` +
+ +
+ArangoDB + +```json +{ + "ConnectorConfig": { + "Instance": "ArangoDb", + "ConnectionString": "http://localhost:8529", + "Username": "username", + "Password": "password", + "CollectionName": "test" + } +} +``` +
+ +
+Cassandra + +`ConnectionString` accepts a comma-separated list of contact points (`host`, `host:port`, `[IPv6]:port`); all ports must match. `DatabaseName` is the keyspace. + +```json +{ + "ConnectorConfig": { + "Instance": "Cassandra", + "ConnectionString": "127.0.0.1:9042", + "DatabaseName": "sharpconnector", + "TableName": "items", + "Username": "cassandra", + "Password": "cassandra" + } +} +``` +
+ +## API overview + +The entry point is `ISharpConnectorClient`. Every operation has a sync and an async version; async methods accept a `CancellationToken`. + +| Operation | Methods | +|-----------|---------| +| Read | `Get(key)`, `GetAll()`, `Exists(key)`, `Query(Func filter)` | +| Insert | `Insert(key, value)`, `Insert(key, value, TimeSpan expiration)` | +| Bulk | `InsertMany(Dictionary)`, `InsertMany(Dictionary, TimeSpan expiration)` | +| Update | `Update(key, value)` | +| Delete | `Delete(key)` | + +`InsertManyAsync(IEnumerable values, CancellationToken ct)` is available in async form only: it generates the keys and returns them as `IReadOnlyCollection`. + +## Operation semantics + +The behavior is the same on every backend: + +- **Insert / InsertMany** are upserts: an existing key is overwritten. +- **Update** only changes existing keys and returns `false` when the key does not exist. +- **Delete** returns `true` only when an item was actually removed. +- **InsertMany** throws `ArgumentException` when a key is null/empty or a value is null. +- **Expiration**: expired items are never returned by `Get`, `GetAll`, `Exists` or `Query`, even on backends without native TTL. +- **Configuration** is validated when the client is created: invalid or incomplete settings throw `ArgumentException`. +- **Sync vs async**: prefer the async methods. The DynamoDB, ArangoDB and Couchbase drivers are async-only, so their sync methods run the async call on the thread pool. + +## Upgrading from 4.x to 5.0 + +5.0 contains breaking changes: + +1. **MVC is no longer registered.** `AddSharpConnectorServices*` no longer calls `AddControllers()`; add it to your host if you need controllers. +2. **Stricter configuration.** RavenDB (absolute URL + `DatabaseName`) and DynamoDB (`TableName` + `Region` or `ServiceUrl`) now throw `ArgumentException` when settings are missing or invalid. +3. **Consistent semantics.** `Update` returns `false` for missing keys and `Delete` returns `false` when nothing was removed, on every backend. + +New in 5.0: Redis `KeyPrefix` and RavenDB client certificate authentication. + +## Building from source + +Requires the **.NET 10 SDK**, which builds both the `net10.0` and `net9.0` targets. + +```bash +git clone https://github.com/engineering87/SharpConnector.git +cd SharpConnector/src/SharpConnector +dotnet build SharpConnector.sln -c Release +dotnet test SharpConnector.sln -c Release +``` ## Extending + To add a new connector: -- Implement `IOperations` for your backend. -- Provide a wrapper/access layer (connection management, collection/table handles). -- Add configuration binding under ConnectorConfig. -- Include unit tests. -## License -SharpConnector source code is available under MIT License, see license in the source. +1. Add a value to `ConnectorTypeEnums` and a configuration class implementing `IConnectorConfig`. +2. Implement an access layer (connection management) and a wrapper (CRUD on the native driver). +3. Implement `IOperations` on top of the wrapper. +4. Add unit tests. -### External References -The SharpConnector library relies on several third-party libraries to deliver advanced functionality. -Each of these libraries operates under a specific license, which governs its usage. To ensure transparency and compliance, the libraries and their licenses are listed in this repository: +## Contributing -* **StackExchange.Redis**, a General purpose redis client, see **license** [here](https://github.com/StackExchange/StackExchange.Redis/blob/main/LICENSE) -* **MongoDB.Driver**, the Official C# .NET Driver for MongoDB, see **license** [here](https://github.com/mongodb/mongo-csharp-driver/blob/main/LICENSE.md) -* **LiteDB**, a .NET NoSQL Document Store in a single data file, see **license** [here](https://github.com/mbdavid/LiteDB/blob/master/LICENSE) -* **EnyimMemcached**, a C# Memcached client, see **license** [here](https://github.com/enyim/EnyimMemcached/blob/develop/LICENSE) -* **RavenDB**, ACID Document Database, see **license** [here](https://github.com/ravendb/ravendb/blob/v6.2/LICENSE.txt) -* **Couchbase**, the official Couchbase SDK for .NET Core and Full Frameworks, see **license** [here](https://github.com/couchbase/couchbase-net-client/blob/master/LICENSE) -* **DynamoDb**, the official AWS SDK for .NET, see **license** [here](https://github.com/aws/aws-sdk-net/blob/main/License.txt) -* **ArangoDB**, a consistent, comprehensive, minimal driver for ArangoDB, see **license** [here](https://github.com/ArangoDB-Community/arangodb-net-standard/blob/master/LICENSE) -* **CassandraCSharpDriver**, the DataStax C# driver for Apache Cassandra, see **license** [here](https://github.com/datastax/csharp-driver/blob/master/LICENSE) +Contributions are welcome! Fork the repository, create a branch and open a pull request. -Each library is included to enhance the functionality of SharpConnector while adhering to its licensing terms. +- Add unit tests for new features or connectors. +- Use [Conventional Commits](https://www.conventionalcommits.org/): commit messages are checked by commitlint in CI. +- Keep third-party dependencies compatible with MIT. +- Found a bug or have an idea? [Open an issue](https://github.com/engineering87/SharpConnector/issues). + +## Third-party licenses + +SharpConnector relies on the following libraries, each under its own license: + +| Library | License | +|-----------------------|---------| +| StackExchange.Redis | [MIT](https://github.com/StackExchange/StackExchange.Redis/blob/main/LICENSE) | +| MongoDB.Driver | [Apache 2.0](https://github.com/mongodb/mongo-csharp-driver/blob/main/LICENSE.md) | +| LiteDB | [MIT](https://github.com/mbdavid/LiteDB/blob/master/LICENSE) | +| EnyimMemcachedCore | [Apache 2.0](https://github.com/cnblogs/EnyimMemcachedCore/blob/main/LICENSE) | +| RavenDB.Client | [See license](https://github.com/ravendb/ravendb/blob/v6.2/LICENSE.txt) | +| CouchbaseNetClient | [Apache 2.0](https://github.com/couchbase/couchbase-net-client/blob/master/LICENSE) | +| AWSSDK.DynamoDBv2 | [Apache 2.0](https://github.com/aws/aws-sdk-net/blob/main/License.txt) | +| ArangoDBNetStandard | [Apache 2.0](https://github.com/ArangoDB-Community/arangodb-net-standard/blob/master/LICENSE) | +| CassandraCSharpDriver | [Apache 2.0](https://github.com/datastax/csharp-driver/blob/master/LICENSE) | + +## License + +SharpConnector is released under the [MIT License](LICENSE). ## Contact -Please contact at francesco.delre[at]protonmail.com for any details. + +For any details, contact francesco.delre[at]protonmail.com. diff --git a/src/SharpConnector/SharpConnector.csproj b/src/SharpConnector/SharpConnector.csproj index 592f92b..bc1698e 100755 --- a/src/SharpConnector/SharpConnector.csproj +++ b/src/SharpConnector/SharpConnector.csproj @@ -9,9 +9,10 @@ A flexible solution that accelerates integrations with multiple NoSQL databases https://github.com/engineering87/SharpConnector true - 4.0.2 - 4.0.2 - 4.0.2 + 5.0.0 + 5.0.0 + 5.0.0 + 5.0.0 - BREAKING: AddSharpConnectorServices no longer registers MVC controllers (call AddControllers() in the host). RavenDB and DynamoDB configurations are now validated and throw ArgumentException when invalid. Update/Delete semantics aligned across connectors. New: Redis keyprefix, RavenDB client certificate authentication (certificatepath, certificatepassword). Fixes: expiration handling, upserts, Cassandra parsing/TTL/paging, Couchbase authentication and disposal, sync-over-async deadlock mitigation. logo.png README.md SharpConnector