Skip to content
Draft
Show file tree
Hide file tree
Changes from all 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
33 changes: 30 additions & 3 deletions src/Dapr.Actors/Runtime/ActorStateManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,29 @@ internal ActorStateManager(Actor actor)
this.defaultTracker = new Dictionary<string, StateMetadata>();
}

public Task UnloadStateAsync(string stateName, UnloadStateOptions options = null, CancellationToken cancellationToken = default)
{
ArgumentVerifier.ThrowIfNull(stateName, nameof(stateName));
EnsureStateProviderInitialized();

var stateChangeTracker = GetContextualStateTracker();
if (!stateChangeTracker.ContainsKey(stateName))
{
// Nothing to unload from memory
return Task.CompletedTask;
}

var stateMetadata = stateChangeTracker[stateName];
bool isModified = stateMetadata.ChangeKind == StateChangeKind.Add || stateMetadata.ChangeKind == StateChangeKind.Update || stateMetadata.ChangeKind == StateChangeKind.Remove;
if (isModified && (options == null || !options.AllowUnloadingWhenStateModified))
{
throw new InvalidOperationException($"Cannot unload state '{stateName}' because it has been modified and not yet persisted. Set AllowUnloadingWhenStateModified to true to override.");
}

stateChangeTracker.Remove(stateName);
return Task.CompletedTask;
}

public async Task AddStateAsync<T>(string stateName, T value, CancellationToken cancellationToken)
{
EnsureStateProviderInitialized();
Expand Down Expand Up @@ -543,12 +566,16 @@ private StateMetadata(object value, Type type, StateChangeKind changeKind, DateT
this.Type = type;
this.ChangeKind = changeKind;

if (ttlExpireTime.HasValue && ttl.HasValue) {
if (ttlExpireTime.HasValue && ttl.HasValue)
{
throw new ArgumentException("Cannot specify both TTLExpireTime and TTL");
}
if (ttl.HasValue) {
if (ttl.HasValue)
{
this.TTLExpireTime = DateTimeOffset.UtcNow.Add(ttl.Value);
} else {
}
else
{
this.TTLExpireTime = ttlExpireTime;
}
}
Expand Down
9 changes: 9 additions & 0 deletions src/Dapr.Actors/Runtime/IActorStateManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,15 @@ namespace Dapr.Actors.Runtime;
/// </summary>
public interface IActorStateManager
{
/// <summary>
/// Unloads the specified state from the in-memory cache/tracker, but does not remove it from the underlying store.
/// </summary>
/// <param name="stateName">Name of the actor state to unload.</param>
/// <param name="options">Options for unloading state (e.g., allow unloading modified state).</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
/// <returns>A task that represents the asynchronous unload operation.</returns>
/// <exception cref="InvalidOperationException">Thrown if the state is modified and not yet persisted, unless allowed by options.</exception>
Task UnloadStateAsync(string stateName, UnloadStateOptions options = null, CancellationToken cancellationToken = default);
/// <summary>
/// Adds an actor state with given state name.
/// </summary>
Expand Down
14 changes: 14 additions & 0 deletions src/Dapr.Actors/Runtime/UnloadStateOptions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// Options for UnloadStateAsync operation
namespace Dapr.Actors.Runtime
{
/// <summary>
/// Options for the UnloadStateAsync operation on ActorStateManager.
/// </summary>
public class UnloadStateOptions
{
/// <summary>
/// If true, allows unloading state even if it is modified and not yet persisted.
/// </summary>
public bool AllowUnloadingWhenStateModified { get; set; } = false;
}
}
85 changes: 85 additions & 0 deletions test/Dapr.Actors.Test/ActorStateManagerUnloadStateTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
// ------------------------------------------------------------------------
// Copyright 2023 The Dapr Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ------------------------------------------------------------------------

using System;
using System.Threading;
using System.Threading.Tasks;
using Dapr.Actors.Runtime;
using Dapr.Actors.Communication;
using Moq;
using Xunit;

namespace Dapr.Actors.Test
{
public class ActorStateManagerUnloadStateTest
{
[Fact]
public async Task UnloadState_RemovesFromMemoryButNotStore()
{
var interactor = new Moq.Mock<TestDaprInteractor>();
// Simulate state existence only after SaveStateAsync
bool stateSaved = false;
interactor.Setup(d => d.GetStateAsync(
Moq.It.IsAny<string>(),
Moq.It.IsAny<string>(),
Moq.It.Is<string>(key => key == "big-data"),
Moq.It.IsAny<CancellationToken>()))
.ReturnsAsync(() =>
stateSaved
? new Dapr.Actors.Communication.ActorStateResponse<string>("\"payload\"", null)
: new Dapr.Actors.Communication.ActorStateResponse<string>("", null));
var host = ActorHost.CreateForTest<TestActor>();
host.StateProvider = new DaprStateProvider(interactor.Object, new System.Text.Json.JsonSerializerOptions());
var mngr = new ActorStateManager(new TestActor(host));
var token = new CancellationToken();

// Add and save state
await mngr.AddStateAsync("big-data", "payload", token);
await mngr.SaveStateAsync(token);
stateSaved = true;
Assert.Equal("payload", await mngr.GetStateAsync<string>("big-data", token));

// Unload from memory
await mngr.UnloadStateAsync("big-data");

// Should reload from store
interactor.Setup(d => d.GetStateAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(new Dapr.Actors.Communication.ActorStateResponse<string>("\"payload\"", null));
Assert.Equal("payload", await mngr.GetStateAsync<string>("big-data", token));
}

[Fact]
public async Task UnloadState_ThrowsIfModifiedUnlessAllowed()
{
var interactor = new Moq.Mock<TestDaprInteractor>();
// Default: state does not exist
interactor.Setup(d => d.GetStateAsync(
Moq.It.IsAny<string>(),
Moq.It.IsAny<string>(),
Moq.It.IsAny<string>(),
Moq.It.IsAny<CancellationToken>()))
.ReturnsAsync(new Dapr.Actors.Communication.ActorStateResponse<string>("", null));
var host = ActorHost.CreateForTest<TestActor>();
host.StateProvider = new DaprStateProvider(interactor.Object, new System.Text.Json.JsonSerializerOptions());
var mngr = new ActorStateManager(new TestActor(host));
var token = new CancellationToken();

await mngr.AddStateAsync("key", "value", token);
// Not yet saved, so is modified
await Assert.ThrowsAsync<InvalidOperationException>(() => mngr.UnloadStateAsync("key"));

// Should not throw if allowed
await mngr.UnloadStateAsync("key", new UnloadStateOptions { AllowUnloadingWhenStateModified = true });
}
}
}
Loading