Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Do not update ttl on reads for absolute expirations #16

Merged
merged 4 commits into from
Jan 4, 2020
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 61 additions & 17 deletions src/CosmosCache.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
namespace Microsoft.Extensions.Caching.Cosmos
{
using System;
using System.Collections.ObjectModel;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
Expand Down Expand Up @@ -99,6 +98,65 @@ public byte[] Get(string key)
return null;
}

// If using sliding expiration then replace item with itself in order to reset the ttl in Cosmos
if (cosmosCacheSessionResponse.Resource.IsSlidingExpiration.GetValueOrDefault())
{
try
{
await this.cosmosContainer.ReplaceItemAsync(
partitionKey: new PartitionKey(key),
id: key,
item: cosmosCacheSessionResponse.Resource,
requestOptions: new ItemRequestOptions()
{
IfMatchEtag = cosmosCacheSessionResponse.ETag,
},
cancellationToken: token).ConfigureAwait(false);
}
catch (CosmosException cosmosException) when (cosmosException.StatusCode == HttpStatusCode.PreconditionFailed)
{
// Race condition on replace, we need to get the latest version of the item
return await this.GetAsync(key, token).ConfigureAwait(false);
}
}

return cosmosCacheSessionResponse.Resource.Content;
}

/// <inheritdoc/>
public void Refresh(string key)
{
#pragma warning disable VSTHRD002 // Avoid problematic synchronous waits
this.RefreshAsync(key).GetAwaiter().GetResult();
#pragma warning restore VSTHRD002 // Avoid problematic synchronous waits
}

/// <inheritdoc/>
public async Task RefreshAsync(string key, CancellationToken token = default(CancellationToken))
{
token.ThrowIfCancellationRequested();

if (string.IsNullOrEmpty(key))
{
throw new ArgumentNullException(nameof(key));
}

await this.ConnectAsync();

ItemResponse<CosmosCacheSession> cosmosCacheSessionResponse;
try
{
cosmosCacheSessionResponse = await this.cosmosContainer.ReadItemAsync<CosmosCacheSession>(
partitionKey: new PartitionKey(key),
id: key,
requestOptions: null,
cancellationToken: token).ConfigureAwait(false);
}
catch (CosmosException ex) when (ex.StatusCode == HttpStatusCode.NotFound)
{
return;
}

try
{
await this.cosmosContainer.ReplaceItemAsync(
Expand All @@ -113,23 +171,8 @@ await this.cosmosContainer.ReplaceItemAsync(
}
catch (CosmosException cosmosException) when (cosmosException.StatusCode == HttpStatusCode.PreconditionFailed)
{
// Race condition on replace, we need to get the latest version of the item
return await this.GetAsync(key, token).ConfigureAwait(false);
// Race condition on replace, we do not need to refresh it
}

return cosmosCacheSessionResponse.Resource.Content;
}

/// <inheritdoc/>
public void Refresh(string key)
{
this.Get(key);
}

/// <inheritdoc/>
public Task RefreshAsync(string key, CancellationToken token = default(CancellationToken))
{
return this.GetAsync(key, token);
}

/// <inheritdoc/>
Expand Down Expand Up @@ -215,6 +258,7 @@ private static CosmosCacheSession BuildCosmosCacheSession(string key, byte[] con
SessionKey = key,
Content = content,
TimeToLive = timeToLive,
IsSlidingExpiration = timeToLive.HasValue ? options.SlidingExpiration.HasValue : (bool?)null,
krispenner marked this conversation as resolved.
Show resolved Hide resolved
};
}

Expand Down
10 changes: 10 additions & 0 deletions src/CosmosCacheSession.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace Microsoft.Extensions.Caching.Cosmos
{
using Microsoft.Extensions.Caching.Distributed;
using Newtonsoft.Json;

internal class CosmosCacheSession
Expand All @@ -16,5 +17,14 @@ internal class CosmosCacheSession

[JsonProperty("ttl")]
public long? TimeToLive { get; set; }

/// <summary>
/// Gets or sets a value indicating whether the <see cref="TimeToLive"/> is sliding or absolute.<br/>
/// True if <see cref="DistributedCacheEntryOptions.SlidingExpiration"/> was set and used for the TTL,
/// false if <see cref="DistributedCacheEntryOptions.AbsoluteExpiration"/> or <see cref="DistributedCacheEntryOptions.AbsoluteExpirationRelativeToNow"/> was set and used for the TTL;
/// otherwise null.
/// </summary>
[JsonProperty("isSlidingExpiration")]
public bool? IsSlidingExpiration { get; set; }
}
}
40 changes: 39 additions & 1 deletion tests/unit/CosmosCacheTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -66,12 +66,13 @@ public async Task ConnectAsyncThrowsIfContainerDoesNotExist()
}

[Fact]
public async Task GetObtainsSessionAndUpdatesCache()
public async Task GetObtainsSessionAndUpdatesCacheForSlidingExpiration()
{
string etag = "etag";
CosmosCacheSession existingSession = new CosmosCacheSession();
existingSession.SessionKey = "key";
existingSession.Content = new byte[0];
existingSession.IsSlidingExpiration = true;
Mock<ItemResponse<CosmosCacheSession>> mockedItemResponse = new Mock<ItemResponse<CosmosCacheSession>>();
Mock<CosmosClient> mockedClient = new Mock<CosmosClient>();
Mock<Container> mockedContainer = new Mock<Container>();
Expand Down Expand Up @@ -100,6 +101,43 @@ public async Task GetObtainsSessionAndUpdatesCache()
mockedContainer.Verify(c => c.ReplaceItemAsync<CosmosCacheSession>(It.Is<CosmosCacheSession>(item => item == existingSession), It.Is<string>(id => id == "key"), It.IsAny<PartitionKey?>(), It.IsAny<ItemRequestOptions>(), It.IsAny<CancellationToken>()), Times.Once);
}

[Fact]
public async Task GetObtainsSessionAndDoesNotUpdatesCacheForAbsoluteExpiration()
{
string etag = "etag";
CosmosCacheSession existingSession = new CosmosCacheSession();
existingSession.SessionKey = "key";
existingSession.Content = new byte[0];
existingSession.IsSlidingExpiration = false;
Mock<ItemResponse<CosmosCacheSession>> mockedItemResponse = new Mock<ItemResponse<CosmosCacheSession>>();
Mock<CosmosClient> mockedClient = new Mock<CosmosClient>();
Mock<Container> mockedContainer = new Mock<Container>();
Mock<Database> mockedDatabase = new Mock<Database>();
Mock<ContainerResponse> mockedResponse = new Mock<ContainerResponse>();
mockedItemResponse.Setup(c => c.Resource).Returns(existingSession);
mockedItemResponse.Setup(c => c.ETag).Returns(etag);
mockedResponse.Setup(c => c.StatusCode).Returns(HttpStatusCode.OK);
mockedContainer.Setup(c => c.ReadContainerAsync(It.IsAny<ContainerRequestOptions>(), It.IsAny<CancellationToken>())).ReturnsAsync(mockedResponse.Object);
mockedContainer.Setup(c => c.ReadItemAsync<CosmosCacheSession>(It.Is<string>(id => id == "key"), It.IsAny<PartitionKey>(), It.IsAny<ItemRequestOptions>(), It.IsAny<CancellationToken>())).ReturnsAsync(mockedItemResponse.Object);
mockedContainer.Setup(c => c.ReplaceItemAsync<CosmosCacheSession>(It.Is<CosmosCacheSession>(item => item == existingSession), It.Is<string>(id => id == "key"), It.IsAny<PartitionKey?>(), It.IsAny<ItemRequestOptions>(), It.IsAny<CancellationToken>())).ReturnsAsync(mockedItemResponse.Object);
mockedClient.Setup(c => c.GetContainer(It.IsAny<string>(), It.IsAny<string>())).Returns(mockedContainer.Object);
mockedClient.Setup(c => c.GetDatabase(It.IsAny<string>())).Returns(mockedDatabase.Object);
mockedClient.Setup(x => x.Endpoint).Returns(new Uri("http://localhost"));
CosmosCache cache = new CosmosCache(Options.Create(new CosmosCacheOptions()
{
DatabaseName = "something",
ContainerName = "something",
CreateIfNotExists = true,
CosmosClient = mockedClient.Object
}));

Assert.Same(existingSession.Content, await cache.GetAsync("key"));
// Checks for Db existence due to CreateIfNotExists
mockedClient.Verify(c => c.CreateDatabaseIfNotExistsAsync(It.IsAny<string>(), It.IsAny<int?>(), It.IsAny<RequestOptions>(), It.IsAny<CancellationToken>()), Times.Once);
mockedContainer.Verify(c => c.ReadItemAsync<CosmosCacheSession>(It.Is<string>(id => id == "key"), It.IsAny<PartitionKey>(), It.IsAny<ItemRequestOptions>(), It.IsAny<CancellationToken>()), Times.Once);
mockedContainer.Verify(c => c.ReplaceItemAsync<CosmosCacheSession>(It.Is<CosmosCacheSession>(item => item == existingSession), It.Is<string>(id => id == "key"), It.IsAny<PartitionKey?>(), It.IsAny<ItemRequestOptions>(), It.IsAny<CancellationToken>()), Times.Never);
}

[Fact]
public async Task GetReturnsNullIfKeyDoesNotExist()
{
Expand Down