diff --git a/sdk-actors/src/main/java/io/dapr/actors/runtime/ActorState.java b/sdk-actors/src/main/java/io/dapr/actors/runtime/ActorState.java new file mode 100644 index 0000000000..359ecead7f --- /dev/null +++ b/sdk-actors/src/main/java/io/dapr/actors/runtime/ActorState.java @@ -0,0 +1,88 @@ +/* + * Copyright 2026 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. +*/ + +package io.dapr.actors.runtime; + +import java.time.Instant; + +/** + * Represents a state change for an actor. + */ +final class ActorState { + + /** + * Name of the state being changed. + */ + private final String name; + + /** + * New value for the state being changed. + */ + private final T value; + + /** + * Expiration. + */ + private final Instant expiration; + + /** + * Creates a new instance of the metadata on actor state. + * + * @param name Name of the state being changed. + * @param value Value to be set. + */ + ActorState(String name, T value) { + this(name, value, null); + } + + /** + * Creates a new instance of the metadata on actor state. + * + * @param name Name of the state being changed. + * @param value Value to be set. + * @param expiration When the value is set to expire (recommended but accepts null). + */ + ActorState(String name, T value, Instant expiration) { + this.name = name; + this.value = value; + this.expiration = expiration; + } + + /** + * Gets the name of the state being changed. + * + * @return Name of the state. + */ + String getName() { + return name; + } + + /** + * Gets the new value of the state being changed. + * + * @return New value. + */ + T getValue() { + return value; + } + + /** + * Gets the expiration of the state. + * + * @return State expiration. + */ + Instant getExpiration() { + return expiration; + } + +} diff --git a/sdk-actors/src/main/java/io/dapr/actors/runtime/ActorStateChange.java b/sdk-actors/src/main/java/io/dapr/actors/runtime/ActorStateChange.java index 47ce28e2ee..cbbe7d6a3e 100644 --- a/sdk-actors/src/main/java/io/dapr/actors/runtime/ActorStateChange.java +++ b/sdk-actors/src/main/java/io/dapr/actors/runtime/ActorStateChange.java @@ -1,76 +1,60 @@ -/* - * Copyright 2021 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. -*/ - -package io.dapr.actors.runtime; - -/** - * Represents a state change for an actor. - */ -public final class ActorStateChange { - - /** - * Name of the state being changed. - */ - private final String stateName; - - /** - * New value for the state being changed. - */ - private final Object value; - - /** - * Type of change {@link ActorStateChangeKind}. - */ - private final ActorStateChangeKind changeKind; - - /** - * Creates an actor state change. - * - * @param stateName Name of the state being changed. - * @param value New value for the state being changed. - * @param changeKind Kind of change. - */ - ActorStateChange(String stateName, Object value, ActorStateChangeKind changeKind) { - this.stateName = stateName; - this.value = value; - this.changeKind = changeKind; - } - - /** - * Gets the name of the state being changed. - * - * @return Name of the state. - */ - String getStateName() { - return stateName; - } - - /** - * Gets the new value of the state being changed. - * - * @return New value. - */ - Object getValue() { - return value; - } - - /** - * Gets the kind of change. - * - * @return Kind of change. - */ - ActorStateChangeKind getChangeKind() { - return changeKind; - } - -} +/* + * Copyright 2021 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. +*/ + +package io.dapr.actors.runtime; + +/** + * Represents a state change for an actor. + */ +public final class ActorStateChange { + + /** + * State being changed. + */ + private final ActorState state; + + /** + * Type of change {@link ActorStateChangeKind}. + */ + private final ActorStateChangeKind changeKind; + + /** + * Creates an actor state change. + * + * @param state State being changed. + * @param changeKind Kind of change. + */ + ActorStateChange(ActorState state, ActorStateChangeKind changeKind) { + this.state = state; + this.changeKind = changeKind; + } + + /** + * Gets the state being changed. + * + * @return state. + */ + ActorState getState() { + return state; + } + + /** + * Gets the kind of change. + * + * @return Kind of change. + */ + ActorStateChangeKind getChangeKind() { + return changeKind; + } + +} diff --git a/sdk-actors/src/main/java/io/dapr/actors/runtime/ActorStateManager.java b/sdk-actors/src/main/java/io/dapr/actors/runtime/ActorStateManager.java index e530cde763..1d3703a432 100644 --- a/sdk-actors/src/main/java/io/dapr/actors/runtime/ActorStateManager.java +++ b/sdk-actors/src/main/java/io/dapr/actors/runtime/ActorStateManager.java @@ -17,6 +17,8 @@ import io.dapr.utils.TypeRef; import reactor.core.publisher.Mono; +import java.time.Duration; +import java.time.Instant; import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -77,6 +79,25 @@ public class ActorStateManager { * @return Asynchronous void operation. */ public Mono add(String stateName, T value) { + return this.add(stateName, value, null); + } + + /** + * Adds a given key/value to the Actor's state store's cache, with an expiration. + * The cached value is not served once it expires. + * + *

Actor state TTL is a preview feature in the Dapr runtime: saving a state with an + * expiration fails unless the ActorStateTTL feature is enabled. The cache only knows + * the expiration when the state store returns it (ttlExpireTime); stores that do not, + * such as Redis, keep serving the cached value until the store itself expires it. + * + * @param stateName Name of the state being added. + * @param value Value to be added. + * @param expiration When the state expires, or null for no expiration. + * @param Type of the object being added. + * @return Asynchronous void operation. + */ + public Mono add(String stateName, T value, Instant expiration) { return Mono.fromSupplier(() -> { if (stateName == null) { throw new IllegalArgumentException("State's name cannot be null."); @@ -89,7 +110,8 @@ public Mono add(String stateName, T value) { StateChangeMetadata metadata = this.stateChangeTracker.get(stateName); if (metadata.kind == ActorStateChangeKind.REMOVE) { - this.stateChangeTracker.put(stateName, new StateChangeMetadata(ActorStateChangeKind.UPDATE, value)); + this.stateChangeTracker.put( + stateName, new StateChangeMetadata(ActorStateChangeKind.UPDATE, value, expiration)); return true; } @@ -100,7 +122,8 @@ public Mono add(String stateName, T value) { throw new IllegalStateException("Duplicate state: " + stateName); } - this.stateChangeTracker.put(stateName, new StateChangeMetadata(ActorStateChangeKind.ADD, value)); + this.stateChangeTracker.put( + stateName, new StateChangeMetadata(ActorStateChangeKind.ADD, value, expiration)); return true; })) .then(); @@ -135,6 +158,10 @@ public Mono get(String stateName, TypeRef type) { if (this.stateChangeTracker.containsKey(stateName)) { StateChangeMetadata metadata = this.stateChangeTracker.get(stateName); + if (metadata.isExpired()) { + throw new NoSuchElementException("State is expired: " + stateName); + } + if (metadata.kind == ActorStateChangeKind.REMOVE) { throw new NoSuchElementException("State is marked for removal: " + stateName); } @@ -147,8 +174,9 @@ public Mono get(String stateName, TypeRef type) { this.stateProvider.load(this.actorTypeName, this.actorId, stateName, type) .switchIfEmpty(Mono.error(new NoSuchElementException("State not found: " + stateName))) .map(v -> { - this.stateChangeTracker.put(stateName, new StateChangeMetadata(ActorStateChangeKind.NONE, v)); - return (T) v; + this.stateChangeTracker.put( + stateName, new StateChangeMetadata(ActorStateChangeKind.NONE, v.getValue(), v.getExpiration())); + return (T) v.getValue(); })); } @@ -161,6 +189,26 @@ public Mono get(String stateName, TypeRef type) { * @return Asynchronous void result. */ public Mono set(String stateName, T value) { + return this.set(stateName, value, Duration.ZERO); + } + + /** + * Updates a given key/value pair in the state store's cache, with a time to live. + * A null, zero, or negative TTL stores the value with no expiration. + * Using a TTL is recommended to avoid state being left in the store forever. + * + *

Actor state TTL is a preview feature in the Dapr runtime: saving a state with a + * TTL fails unless the ActorStateTTL feature is enabled. The cache only knows the + * expiration when the state store returns it (ttlExpireTime); stores that do not, + * such as Redis, keep serving the cached value until the store itself expires it. + * + * @param stateName Name of the state being updated. + * @param value Value to be set for given state. + * @param ttl Time to live. + * @param Type of the value being set. + * @return Asynchronous void result. + */ + public Mono set(String stateName, T value, Duration ttl) { return Mono.fromSupplier(() -> { if (stateName == null) { throw new IllegalArgumentException("State's name cannot be null."); @@ -170,11 +218,12 @@ public Mono set(String stateName, T value) { StateChangeMetadata metadata = this.stateChangeTracker.get(stateName); ActorStateChangeKind kind = metadata.kind; - if ((kind == ActorStateChangeKind.NONE) || (kind == ActorStateChangeKind.REMOVE)) { + if (metadata.isExpired() || (kind == ActorStateChangeKind.NONE) || (kind == ActorStateChangeKind.REMOVE)) { kind = ActorStateChangeKind.UPDATE; } - this.stateChangeTracker.put(stateName, new StateChangeMetadata(kind, value)); + var expiration = buildExpiration(ttl); + this.stateChangeTracker.put(stateName, new StateChangeMetadata(kind, value, expiration)); return true; } @@ -182,8 +231,10 @@ public Mono set(String stateName, T value) { }).filter(x -> x) .switchIfEmpty(this.stateProvider.contains(this.actorTypeName, this.actorId, stateName) .map(exists -> { + var expiration = buildExpiration(ttl); this.stateChangeTracker.put(stateName, - new StateChangeMetadata(exists ? ActorStateChangeKind.UPDATE : ActorStateChangeKind.ADD, value)); + new StateChangeMetadata( + exists ? ActorStateChangeKind.UPDATE : ActorStateChangeKind.ADD, value, expiration)); return exists; })) .then(); @@ -213,7 +264,7 @@ public Mono remove(String stateName) { return true; } - this.stateChangeTracker.put(stateName, new StateChangeMetadata(ActorStateChangeKind.REMOVE, null)); + this.stateChangeTracker.put(stateName, new StateChangeMetadata(ActorStateChangeKind.REMOVE, null, null)); return true; } @@ -223,7 +274,7 @@ public Mono remove(String stateName) { .switchIfEmpty(this.stateProvider.contains(this.actorTypeName, this.actorId, stateName)) .filter(exists -> exists) .map(exists -> { - this.stateChangeTracker.put(stateName, new StateChangeMetadata(ActorStateChangeKind.REMOVE, null)); + this.stateChangeTracker.put(stateName, new StateChangeMetadata(ActorStateChangeKind.REMOVE, null, null)); return exists; }) .then(); @@ -244,7 +295,7 @@ public Mono contains(String stateName) { return this.stateChangeTracker.get(stateName); } ).map(metadata -> { - if (metadata.kind == ActorStateChangeKind.REMOVE) { + if (metadata.isExpired() || (metadata.kind == ActorStateChangeKind.REMOVE)) { return Boolean.FALSE; } @@ -275,7 +326,8 @@ public Mono save() { continue; } - changes.add(new ActorStateChange(tuple.getKey(), tuple.getValue().value, tuple.getValue().kind)); + var actorState = new ActorState<>(tuple.getKey(), tuple.getValue().value, tuple.getValue().expiration); + changes.add(new ActorStateChange(actorState, tuple.getValue().kind)); } return changes.toArray(new ActorStateChange[0]); @@ -306,12 +358,17 @@ private void flush() { if (tuple.getValue().kind == ActorStateChangeKind.REMOVE) { this.stateChangeTracker.remove(stateName); } else { - StateChangeMetadata metadata = new StateChangeMetadata(ActorStateChangeKind.NONE, tuple.getValue().value); + StateChangeMetadata metadata = + new StateChangeMetadata(ActorStateChangeKind.NONE, tuple.getValue().value, tuple.getValue().expiration); this.stateChangeTracker.put(stateName, metadata); } } } + private static Instant buildExpiration(Duration ttl) { + return (ttl != null) && !ttl.isNegative() && !ttl.isZero() ? Instant.now().plus(ttl) : null; + } + /** * Internal class to represent value and change kind. */ @@ -327,15 +384,26 @@ private static final class StateChangeMetadata { */ private final Object value; + /** + * Expiration. + */ + private final Instant expiration; + /** * Creates a new instance of the metadata on state change. * * @param kind Kind of change. * @param value Value to be set. + * @param expiration When the value is set to expire (recommended but accepts null). */ - private StateChangeMetadata(ActorStateChangeKind kind, Object value) { + private StateChangeMetadata(ActorStateChangeKind kind, Object value, Instant expiration) { this.kind = kind; this.value = value; + this.expiration = expiration; + } + + private boolean isExpired() { + return (this.expiration != null) && Instant.now().isAfter(this.expiration); } } } diff --git a/sdk-actors/src/main/java/io/dapr/actors/runtime/ActorStateOperation.java b/sdk-actors/src/main/java/io/dapr/actors/runtime/ActorStateOperation.java index 737815e664..4db588450a 100644 --- a/sdk-actors/src/main/java/io/dapr/actors/runtime/ActorStateOperation.java +++ b/sdk-actors/src/main/java/io/dapr/actors/runtime/ActorStateOperation.java @@ -25,28 +25,19 @@ final class ActorStateOperation { private String operationType; /** - * Key for the state to be persisted. + * State to be persisted. */ - private String key; - - /** - * Value of the state to be persisted. - */ - private Object value; + private ActorState state; /** * Instantiates a new Actor Timer. * * @param operationType Type of state operation. - * @param key Key to be persisted. - * @param value Value to be persisted. + * @param state Key to be persisted. */ - ActorStateOperation(String operationType, - String key, - Object value) { + ActorStateOperation(String operationType, ActorState state) { this.operationType = operationType; - this.key = key; - this.value = value; + this.state = state; } /** @@ -59,20 +50,12 @@ public String getOperationType() { } /** - * Gets the key to be persisted. + * Gets the state to be persisted. * - * @return Key to be persisted. + * @return State to be persisted. */ - public String getKey() { - return key; + public ActorState getState() { + return state; } - /** - * Gets the value to be persisted. - * - * @return Value to be persisted. - */ - public Object getValue() { - return value; - } } diff --git a/sdk-actors/src/main/java/io/dapr/actors/runtime/DaprClient.java b/sdk-actors/src/main/java/io/dapr/actors/runtime/DaprClient.java index f800d9acb3..e9a0d864f0 100644 --- a/sdk-actors/src/main/java/io/dapr/actors/runtime/DaprClient.java +++ b/sdk-actors/src/main/java/io/dapr/actors/runtime/DaprClient.java @@ -28,9 +28,9 @@ interface DaprClient { * @param actorType Type of actor. * @param actorId Actor Identifier. * @param keyName State name. - * @return Asynchronous result with current state value. + * @return Asynchronous result with current state. */ - Mono getState(String actorType, String actorId, String keyName); + Mono> getState(String actorType, String actorId, String keyName); /** * Saves state batch to Dapr. diff --git a/sdk-actors/src/main/java/io/dapr/actors/runtime/DaprClientImpl.java b/sdk-actors/src/main/java/io/dapr/actors/runtime/DaprClientImpl.java index 7010048f89..770b095bed 100644 --- a/sdk-actors/src/main/java/io/dapr/actors/runtime/DaprClientImpl.java +++ b/sdk-actors/src/main/java/io/dapr/actors/runtime/DaprClientImpl.java @@ -29,6 +29,7 @@ import java.io.IOException; import java.nio.charset.Charset; +import java.time.Instant; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutionException; @@ -79,7 +80,7 @@ class DaprClientImpl implements DaprClient { * {@inheritDoc} */ @Override - public Mono getState(String actorType, String actorId, String keyName) { + public Mono> getState(String actorType, String actorId, final String keyName) { DaprActorsProtos.GetActorStateRequest req = DaprActorsProtos.GetActorStateRequest.newBuilder() .setActorType(actorType) @@ -88,7 +89,14 @@ public Mono getState(String actorType, String actorId, String keyName) { .build(); return Mono.create(it -> - client.getActorState(req, createStreamObserver(it))).map(r -> r.getData().toByteArray()); + client.getActorState(req, createStreamObserver(it))).map(r -> { + var expirationStr = r.getMetadataOrDefault("ttlExpireTime", null); + Instant expiration = null; + if ((expirationStr != null) && !expirationStr.isEmpty()) { + expiration = Instant.parse(expirationStr); + } + return new ActorState<>(keyName, r.getData().toByteArray(), expiration); + }); } /** @@ -102,12 +110,26 @@ public Mono saveStateTransactionally( List grpcOps = new ArrayList<>(); for (ActorStateOperation op : operations) { String operationType = op.getOperationType(); - String key = op.getKey(); - Object value = op.getValue(); + String key = op.getState().getName(); + Object value = op.getState().getValue(); + Instant expiration = op.getState().getExpiration(); + Long ttlInSeconds = null; + if (expiration != null) { + ttlInSeconds = expiration.getEpochSecond() - Instant.now().getEpochSecond(); + } DaprActorsProtos.TransactionalActorStateOperation.Builder opBuilder = DaprActorsProtos.TransactionalActorStateOperation.newBuilder() .setOperationType(operationType) .setKey(key); + + if (ttlInSeconds != null) { + if (ttlInSeconds <= 0) { + // already expired, min is 1s. + ttlInSeconds = 1L; + } + opBuilder.putMetadata("ttlInSeconds", ttlInSeconds.toString()); + } + if (value != null) { if (value instanceof String) { opBuilder.setValue(Any.newBuilder().setValue(ByteString.copyFrom((String) value, CHARSET))); diff --git a/sdk-actors/src/main/java/io/dapr/actors/runtime/DaprStateAsyncProvider.java b/sdk-actors/src/main/java/io/dapr/actors/runtime/DaprStateAsyncProvider.java index fa481f371a..a73f5764ab 100644 --- a/sdk-actors/src/main/java/io/dapr/actors/runtime/DaprStateAsyncProvider.java +++ b/sdk-actors/src/main/java/io/dapr/actors/runtime/DaprStateAsyncProvider.java @@ -1,169 +1,170 @@ -/* - * Copyright 2021 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. -*/ - -package io.dapr.actors.runtime; - -import com.fasterxml.jackson.databind.ObjectMapper; -import io.dapr.actors.ActorId; -import io.dapr.config.Properties; -import io.dapr.serializer.DaprObjectSerializer; -import io.dapr.serializer.DefaultObjectSerializer; -import io.dapr.utils.TypeRef; -import reactor.core.publisher.Mono; - -import java.io.IOException; -import java.nio.charset.Charset; -import java.util.ArrayList; - -/** - * State Provider to interact with Dapr runtime to handle state. - */ -class DaprStateAsyncProvider { - - /** - * Dapr's charset. - */ - private static final Charset CHARSET = Properties.STRING_CHARSET.get(); - - /** - * Handles special serialization cases. - */ - private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); - - /** - * Dapr's client for Actor runtime. - */ - private final DaprClient daprClient; - - /** - * Serializer for state objects. - */ - private final DaprObjectSerializer stateSerializer; - - /** - * Flag determining if state serializer is the default serializer instead of user provided. - */ - private final boolean isStateSerializerDefault; - - /** - * Instantiates a new Actor's state provider. - * - * @param daprClient Dapr client for Actor runtime. - * @param stateSerializer Serializer for state objects. - */ - DaprStateAsyncProvider(DaprClient daprClient, DaprObjectSerializer stateSerializer) { - this.daprClient = daprClient; - this.stateSerializer = stateSerializer; - this.isStateSerializerDefault = stateSerializer.getClass() == DefaultObjectSerializer.class; - } - - Mono load(String actorType, ActorId actorId, String stateName, TypeRef type) { - Mono result = this.daprClient.getState(actorType, actorId.toString(), stateName); - - return result.flatMap(s -> { - try { - if (s == null) { - return Mono.empty(); - } - - T response = this.stateSerializer.deserialize(s, type); - if (this.isStateSerializerDefault && (response instanceof byte[])) { - if (s.length == 0) { - return Mono.empty(); - } - // Default serializer just passes through byte arrays, so we need to decode it here. - response = (T) OBJECT_MAPPER.readValue(s, byte[].class); - } - if (response == null) { - return Mono.empty(); - } - - return Mono.just(response); - } catch (IOException e) { - return Mono.error(new RuntimeException(e)); - } - }); - } - - Mono contains(String actorType, ActorId actorId, String stateName) { - Mono result = this.daprClient.getState(actorType, actorId.toString(), stateName); - return result.map(s -> s.length > 0).defaultIfEmpty(false); - } - - /** - * Saves state changes transactionally. - * [ - * { - * "operation": "upsert", - * "request": { - * "key": "key1", - * "value": "myData" - * } - * }, - * { - * "operation": "delete", - * "request": { - * "key": "key2" - * } - * } - * ] - * - * @param actorType Name of the actor being changed. - * @param actorId Identifier of the actor being changed. - * @param stateChanges Collection of changes to be performed transactionally. - * @return Void. - */ - Mono apply(String actorType, ActorId actorId, ActorStateChange... stateChanges) { - if ((stateChanges == null) || stateChanges.length == 0) { - return Mono.empty(); - } - - ArrayList operations = new ArrayList<>(stateChanges.length); - for (ActorStateChange stateChange : stateChanges) { - if ((stateChange == null) || (stateChange.getChangeKind() == null)) { - continue; - } - - String operationName = stateChange.getChangeKind().getDaprStateChangeOperation(); - if ((operationName == null) || (operationName.length() == 0)) { - continue; - } - - String key = stateChange.getStateName(); - Object value = null; - if ((stateChange.getChangeKind() == ActorStateChangeKind.UPDATE) - || (stateChange.getChangeKind() == ActorStateChangeKind.ADD)) { - try { - byte[] data = this.stateSerializer.serialize(stateChange.getValue()); - if (data != null) { - if (this.isStateSerializerDefault && !(stateChange.getValue() instanceof byte[])) { - // DefaultObjectSerializer is a JSON serializer, so we just pass it on. - value = new String(data, CHARSET); - } else { - // Custom serializer uses byte[]. - // DefaultObjectSerializer is just a passthrough for byte[], so we handle it here too. - value = data; - } - } - } catch (IOException e) { - return Mono.error(e); - } - } - - operations.add(new ActorStateOperation(operationName, key, value)); - } - - return this.daprClient.saveStateTransactionally(actorType, actorId.toString(), operations); - } - -} +/* + * Copyright 2021 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. +*/ + +package io.dapr.actors.runtime; + +import com.fasterxml.jackson.databind.ObjectMapper; +import io.dapr.actors.ActorId; +import io.dapr.config.Properties; +import io.dapr.serializer.DaprObjectSerializer; +import io.dapr.serializer.DefaultObjectSerializer; +import io.dapr.utils.TypeRef; +import reactor.core.publisher.Mono; + +import java.io.IOException; +import java.nio.charset.Charset; +import java.util.ArrayList; + +/** + * State Provider to interact with Dapr runtime to handle state. + */ +class DaprStateAsyncProvider { + + /** + * Dapr's charset. + */ + private static final Charset CHARSET = Properties.STRING_CHARSET.get(); + + /** + * Handles special serialization cases. + */ + private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); + + /** + * Dapr's client for Actor runtime. + */ + private final DaprClient daprClient; + + /** + * Serializer for state objects. + */ + private final DaprObjectSerializer stateSerializer; + + /** + * Flag determining if state serializer is the default serializer instead of user provided. + */ + private final boolean isStateSerializerDefault; + + /** + * Instantiates a new Actor's state provider. + * + * @param daprClient Dapr client for Actor runtime. + * @param stateSerializer Serializer for state objects. + */ + DaprStateAsyncProvider(DaprClient daprClient, DaprObjectSerializer stateSerializer) { + this.daprClient = daprClient; + this.stateSerializer = stateSerializer; + this.isStateSerializerDefault = stateSerializer.getClass() == DefaultObjectSerializer.class; + } + + Mono> load(String actorType, ActorId actorId, String stateName, TypeRef type) { + Mono> result = this.daprClient.getState(actorType, actorId.toString(), stateName); + + return result.flatMap(s -> { + try { + if (s == null) { + return Mono.empty(); + } + + T response = this.stateSerializer.deserialize(s.getValue(), type); + if (this.isStateSerializerDefault && (response instanceof byte[])) { + if ((s.getValue() == null) || (s.getValue().length == 0)) { + return Mono.empty(); + } + // Default serializer just passes through byte arrays, so we need to decode it here. + response = (T) OBJECT_MAPPER.readValue(s.getValue(), byte[].class); + } + if (response == null) { + return Mono.empty(); + } + + return Mono.just(new ActorState<>(s.getName(), response, s.getExpiration())); + } catch (IOException e) { + return Mono.error(new RuntimeException(e)); + } + }); + } + + Mono contains(String actorType, ActorId actorId, String stateName) { + var result = this.daprClient.getState(actorType, actorId.toString(), stateName); + return result.map(s -> (s.getValue() != null) && (s.getValue().length > 0)).defaultIfEmpty(false); + } + + /** + * Saves state changes transactionally. + * [ + * { + * "operation": "upsert", + * "request": { + * "key": "key1", + * "value": "myData" + * } + * }, + * { + * "operation": "delete", + * "request": { + * "key": "key2" + * } + * } + * ] + * + * @param actorType Name of the actor being changed. + * @param actorId Identifier of the actor being changed. + * @param stateChanges Collection of changes to be performed transactionally. + * @return Void. + */ + Mono apply(String actorType, ActorId actorId, ActorStateChange... stateChanges) { + if ((stateChanges == null) || stateChanges.length == 0) { + return Mono.empty(); + } + + ArrayList operations = new ArrayList<>(stateChanges.length); + for (ActorStateChange stateChange : stateChanges) { + if ((stateChange == null) || (stateChange.getChangeKind() == null)) { + continue; + } + + String operationName = stateChange.getChangeKind().getDaprStateChangeOperation(); + if ((operationName == null) || (operationName.length() == 0)) { + continue; + } + + var state = stateChange.getState(); + String key = state.getName(); + Object value = null; + if ((stateChange.getChangeKind() == ActorStateChangeKind.UPDATE) + || (stateChange.getChangeKind() == ActorStateChangeKind.ADD)) { + try { + byte[] data = this.stateSerializer.serialize(state.getValue()); + if (data != null) { + if (this.isStateSerializerDefault && !(state.getValue() instanceof byte[])) { + // DefaultObjectSerializer is a JSON serializer, so we just pass it on. + value = new String(data, CHARSET); + } else { + // Custom serializer uses byte[]. + // DefaultObjectSerializer is just a passthrough for byte[], so we handle it here too. + value = data; + } + } + } catch (IOException e) { + return Mono.error(e); + } + } + + operations.add(new ActorStateOperation(operationName, new ActorState(key, value, state.getExpiration()))); + } + + return this.daprClient.saveStateTransactionally(actorType, actorId.toString(), operations); + } + +} diff --git a/sdk-actors/src/test/java/io/dapr/actors/runtime/ActorManagerTest.java b/sdk-actors/src/test/java/io/dapr/actors/runtime/ActorManagerTest.java index 9476fb097f..3406beb8e4 100644 --- a/sdk-actors/src/test/java/io/dapr/actors/runtime/ActorManagerTest.java +++ b/sdk-actors/src/test/java/io/dapr/actors/runtime/ActorManagerTest.java @@ -317,7 +317,7 @@ Mono contains(String actorType, ActorId actorId, String stateName) { Mono apply(String actorType, ActorId actorId, ActorStateChange... stateChanges) { return Mono.fromRunnable(() -> { for (ActorStateChange change : stateChanges) { - this.saved.add(change.getStateName() + "=" + change.getValue()); + this.saved.add(change.getState().getName() + "=" + change.getState().getValue()); } }); } diff --git a/sdk-actors/src/test/java/io/dapr/actors/runtime/ActorRuntimeTest.java b/sdk-actors/src/test/java/io/dapr/actors/runtime/ActorRuntimeTest.java index 6fc0910b2b..05cf5088dd 100644 --- a/sdk-actors/src/test/java/io/dapr/actors/runtime/ActorRuntimeTest.java +++ b/sdk-actors/src/test/java/io/dapr/actors/runtime/ActorRuntimeTest.java @@ -708,8 +708,8 @@ public void callRunsOnTheActorItsActivationSettledOn() throws Exception { live.get(0).get(5, TimeUnit.SECONDS); Assertions.assertEquals(1, saved.size()); - Assertions.assertEquals("value", saved.get(0).getKey()); - Assertions.assertEquals("\"fresh\"", saved.get(0).getValue()); + Assertions.assertEquals("value", saved.get(0).getState().getName()); + Assertions.assertEquals("\"fresh\"", saved.get(0).getState().getValue()); ExecutionException e = assertThrows(ExecutionException.class, () -> late.get(5, TimeUnit.SECONDS)); Assertions.assertTrue(e.getCause() instanceof IllegalStateException, String.valueOf(e.getCause())); } diff --git a/sdk-actors/src/test/java/io/dapr/actors/runtime/ActorStatefulTest.java b/sdk-actors/src/test/java/io/dapr/actors/runtime/ActorStatefulTest.java index 88488d30c7..636cdbd837 100644 --- a/sdk-actors/src/test/java/io/dapr/actors/runtime/ActorStatefulTest.java +++ b/sdk-actors/src/test/java/io/dapr/actors/runtime/ActorStatefulTest.java @@ -68,6 +68,10 @@ public interface MyActor { Mono setMessage(String message); + Mono setMessageFor1s(String message); + + Mono setMessageAndWait(String message); + Mono getMessage(); Mono hasMessage(); @@ -205,6 +209,20 @@ public Mono setMessage(String message) { return super.getActorStateManager().set("message", message).thenReturn(executeSayMethod(message)); } + @Override + public Mono setMessageFor1s(String message) { + return super + .getActorStateManager().set("message", message, Duration.ofSeconds(1)) + .then(super.getActorStateManager().contains("message")); + } + + @Override + public Mono setMessageAndWait(String message) { + return super.getActorStateManager().set("message", message, Duration.ofSeconds(1)) + .then(Mono.delay(Duration.ofMillis(1100))) + .then(super.getActorStateManager().contains("message")); + } + @Override public Mono getMessage() { return super.getActorStateManager().get("message", String.class); @@ -298,23 +316,67 @@ public MyMethodContext setName(String name) { public void happyGetSetDeleteContains() { ActorProxy proxy = newActorProxy(); Assertions.assertEquals( - proxy.getActorId().toString(), proxy.invokeMethod("getIdString", String.class).block()); + proxy.getActorId().toString(), proxy.invokeMethod("getIdString", String.class).block()); Assertions.assertFalse(proxy.invokeMethod("hasMessage", Boolean.class).block()); proxy.invokeMethod("setMessage", "hello world").block(); Assertions.assertTrue(proxy.invokeMethod("hasMessage", Boolean.class).block()); Assertions.assertEquals( - "hello world", proxy.invokeMethod("getMessage", String.class).block()); + "hello world", proxy.invokeMethod("getMessage", String.class).block()); Assertions.assertEquals( - executeSayMethod("hello world"), - proxy.invokeMethod("setMessage", "hello world", String.class).block()); + executeSayMethod("hello world"), + proxy.invokeMethod("setMessage", "hello world", String.class).block()); proxy.invokeMethod("deleteMessage").block(); Assertions.assertFalse(proxy.invokeMethod("hasMessage", Boolean.class).block()); } + @Test + public void actorStateTTL() throws Exception { + ActorProxy proxy = newActorProxy(); + Assertions.assertEquals( + proxy.getActorId().toString(), proxy.invokeMethod("getIdString", String.class).block()); + Assertions.assertFalse(proxy.invokeMethod("hasMessage", Boolean.class).block()); + + Assertions.assertTrue( + proxy.invokeMethod("setMessageFor1s", "hello world expires in 1s", Boolean.class).block()); + Assertions.assertTrue(proxy.invokeMethod("hasMessage", Boolean.class).block()); + + Assertions.assertEquals( + "hello world expires in 1s", proxy.invokeMethod("getMessage", String.class).block()); + + Assertions.assertTrue(proxy.invokeMethod("hasMessage", Boolean.class).block()); + + Thread.sleep(1100); + + Assertions.assertFalse(proxy.invokeMethod("hasMessage", Boolean.class).block()); + } + + @Test + public void actorStateTTLExpiresInLocalCache() throws Exception { + ActorProxy proxy = newActorProxy(); + Assertions.assertEquals( + proxy.getActorId().toString(), proxy.invokeMethod("getIdString", String.class).block()); + Assertions.assertFalse(proxy.invokeMethod("hasMessage", Boolean.class).block()); + + //First, sets a message without TTL and checks it is saved. + proxy.invokeMethod("setMessage", "hello world").block(); + Assertions.assertTrue(proxy.invokeMethod("hasMessage", Boolean.class).block()); + Assertions.assertEquals( + "hello world", proxy.invokeMethod("getMessage", String.class).block()); + + // Now, sets a message that expires still in local cache, before it is sent to state store. + Assertions.assertFalse( + proxy.invokeMethod("setMessageAndWait", "expires while still in cache", Boolean.class).block()); + Assertions.assertFalse(proxy.invokeMethod("hasMessage", Boolean.class).block()); + + Thread.sleep(1100); + + Assertions.assertFalse(proxy.invokeMethod("hasMessage", Boolean.class).block()); + } + @Test public void lazyGet() { ActorProxy proxy = newActorProxy(); diff --git a/sdk-actors/src/test/java/io/dapr/actors/runtime/DaprGrpcClientTest.java b/sdk-actors/src/test/java/io/dapr/actors/runtime/DaprGrpcClientTest.java index 1e676f1e5d..90b68a9282 100644 --- a/sdk-actors/src/test/java/io/dapr/actors/runtime/DaprGrpcClientTest.java +++ b/sdk-actors/src/test/java/io/dapr/actors/runtime/DaprGrpcClientTest.java @@ -33,6 +33,7 @@ import java.io.IOException; import java.time.Duration; +import java.time.Instant; import java.util.Arrays; import java.util.List; import java.util.concurrent.ExecutionException; @@ -40,6 +41,8 @@ import static io.dapr.actors.TestUtils.assertThrowsDaprException; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -53,6 +56,8 @@ public class DaprGrpcClientTest { private static final String KEY = "MyKey"; + private static final String TTL_KEY = "MyKeyWithTtl"; + private static final String ACTOR_EXCEPTION = "1_exception"; private static final String REMINDER_NAME = "myreminder"; @@ -64,13 +69,15 @@ public class DaprGrpcClientTest { private static final byte[] RESPONSE_PAYLOAD = "\"hello world\"".getBytes(); private static final List OPERATIONS = Arrays.asList( - new ActorStateOperation("upsert", "mykey", "hello world".getBytes()), - new ActorStateOperation("delete", "mykey", null)); + new ActorStateOperation("upsert", new ActorState("mykey", "hello world".getBytes(), null)), + new ActorStateOperation("delete", new ActorState("mykey", null, null))); private final DaprGrpc.DaprImplBase serviceImpl = new CustomDaprClient(); private DaprClientImpl client; + private DaprActorsProtos.ExecuteActorStateTransactionRequest lastTransactionRequest; + @Rule public final GrpcCleanupRule grpcCleanup = new GrpcCleanupRule(); @@ -93,7 +100,7 @@ public void setup() throws IOException { @Test public void getActorStateException() { - Mono result = client.getState(ACTOR_TYPE, ACTOR_EXCEPTION, KEY); + Mono> result = client.getState(ACTOR_TYPE, ACTOR_EXCEPTION, KEY); assertThrowsDaprException( ExecutionException.class, "UNKNOWN", @@ -103,8 +110,23 @@ public void getActorStateException() { @Test public void getActorState() { - Mono result = client.getState(ACTOR_TYPE, ACTOR_ID, KEY); - assertArrayEquals(RESPONSE_PAYLOAD, result.block()); + Mono> result = client.getState(ACTOR_TYPE, ACTOR_ID, KEY); + assertArrayEquals(RESPONSE_PAYLOAD, result.block().getValue()); + } + + @Test + public void getActorStateWithTtlExpireTime() { + Mono> result = client.getState(ACTOR_TYPE, ACTOR_ID, TTL_KEY); + ActorState state = result.block(); + assertArrayEquals(RESPONSE_PAYLOAD, state.getValue()); + assertTrue(state.getExpiration().isAfter(Instant.now())); + assertTrue(state.getExpiration().isBefore(Instant.now().plusSeconds(3601))); + } + + @Test + public void getActorStateWithoutTtlExpireTimeHasNoExpiration() { + Mono> result = client.getState(ACTOR_TYPE, ACTOR_ID, KEY); + assertNull(result.block().getExpiration()); } @Test @@ -128,11 +150,32 @@ public void saveActorStateTransactionallyByteArray() { result.block(); } + @Test + public void saveActorStateTransactionallyWithTtl() { + List operations = Arrays.asList( + new ActorStateOperation("upsert", + new ActorState("mykey", "hello world".getBytes(), Instant.now().plusSeconds(3600))), + new ActorStateOperation("delete", new ActorState("mykey", null, null))); + + Mono result = client.saveStateTransactionally(ACTOR_TYPE, ACTOR_ID, operations); + result.block(); + + DaprActorsProtos.TransactionalActorStateOperation upsert = + this.lastTransactionRequest.getOperations(0); + assertTrue(upsert.getMetadataMap().containsKey("ttlInSeconds")); + long ttlInSeconds = Long.parseLong(upsert.getMetadataOrThrow("ttlInSeconds")); + assertTrue(ttlInSeconds >= 3590 && ttlInSeconds <= 3600); + + DaprActorsProtos.TransactionalActorStateOperation delete = + this.lastTransactionRequest.getOperations(1); + assertFalse(delete.getMetadataMap().containsKey("ttlInSeconds")); + } + @Test public void saveActorStateTransactionallyInvalidValueType() { ActorStateOperation[] operations = new ActorStateOperation[]{ - new ActorStateOperation("upsert", "mykey", 123), - new ActorStateOperation("delete", "mykey", null), + new ActorStateOperation("upsert", new ActorState("mykey", 123, null)), + new ActorStateOperation("delete", new ActorState("mykey", null, null)), }; Mono result = client.saveStateTransactionally(ACTOR_TYPE, ACTOR_ID, Arrays.asList(operations)); @@ -257,9 +300,9 @@ public boolean matches(DaprActorsProtos.ExecuteActorStateTransactionRequest argu for (ActorStateOperation operation : operations) { boolean found = false; for (DaprActorsProtos.TransactionalActorStateOperation grpcOperation : argument.getOperationsList()) { - if (operation.getKey().equals(grpcOperation.getKey()) + if (operation.getState().getName().equals(grpcOperation.getKey()) && operation.getOperationType().equals(grpcOperation.getOperationType()) - && nullableEquals(operation.getValue(), grpcOperation.getValue())) { + && nullableEquals(operation.getState().getValue(), grpcOperation.getValue())) { found = true; break; } @@ -280,12 +323,17 @@ private class CustomDaprClient extends DaprGrpc.DaprImplBase { public void getActorState(DaprActorsProtos.GetActorStateRequest request, StreamObserver responseObserver) { assertEquals(ACTOR_TYPE, request.getActorType()); - assertEquals(KEY, request.getKey()); + assertTrue(KEY.equals(request.getKey()) || TTL_KEY.equals(request.getKey())); assertEquals(ACTOR_ID, request.getActorId()); switch (request.getActorId()) { case ACTOR_ID: - populateObserver(responseObserver, DaprActorsProtos.GetActorStateResponse.newBuilder().setData(ByteString.copyFrom(RESPONSE_PAYLOAD)) - .build()); + DaprActorsProtos.GetActorStateResponse.Builder response = + DaprActorsProtos.GetActorStateResponse.newBuilder() + .setData(ByteString.copyFrom(RESPONSE_PAYLOAD)); + if (TTL_KEY.equals(request.getKey())) { + response.putMetadata("ttlExpireTime", Instant.now().plusSeconds(3600).toString()); + } + populateObserver(responseObserver, response.build()); return; case ACTOR_EXCEPTION: @@ -299,6 +347,7 @@ public void executeActorStateTransaction(DaprActorsProtos.ExecuteActorStateTrans io.grpc.stub.StreamObserver responseObserver) { assertEquals(ACTOR_TYPE, request.getActorType()); assertEquals(ACTOR_ID, request.getActorId()); + lastTransactionRequest = request; assertTrue(new OperationsMatcher(OPERATIONS).matches(request)); switch (request.getActorId()) { case ACTOR_ID: @@ -416,4 +465,5 @@ private void populateObserver(StreamObse responseObserver.onCompleted(); } } + } diff --git a/sdk-actors/src/test/java/io/dapr/actors/runtime/DaprInMemoryStateProvider.java b/sdk-actors/src/test/java/io/dapr/actors/runtime/DaprInMemoryStateProvider.java index 4f1c165d72..9c616f7842 100644 --- a/sdk-actors/src/test/java/io/dapr/actors/runtime/DaprInMemoryStateProvider.java +++ b/sdk-actors/src/test/java/io/dapr/actors/runtime/DaprInMemoryStateProvider.java @@ -1,87 +1,111 @@ -/* - * Copyright 2021 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. -*/ - -package io.dapr.actors.runtime; - -import io.dapr.actors.ActorId; -import io.dapr.serializer.DaprObjectSerializer; -import io.dapr.utils.TypeRef; -import reactor.core.publisher.Mono; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - -/** - * Fake state provider for tests in Actors - data is kept in memory only. - */ -public class DaprInMemoryStateProvider extends DaprStateAsyncProvider { - - private static final Map stateStore = new HashMap<>(); - - private final DaprObjectSerializer serializer; - - DaprInMemoryStateProvider(DaprObjectSerializer serializer) { - super(null, serializer /* just to avoid NPE */); - this.serializer = serializer; - } - - @Override - Mono load(String actorType, ActorId actorId, String stateName, TypeRef type) { - return Mono.fromSupplier(() -> { - try { - String stateId = this.buildId(actorType, actorId, stateName); - if (!stateStore.containsKey(stateId)) { - throw new IllegalStateException("State not found."); - } - - return this.serializer.deserialize(this.stateStore.get(stateId), type); - } catch (IOException e) { - throw new RuntimeException(e); - } - }); - } - - @Override - Mono contains(String actorType, ActorId actorId, String stateName) { - return Mono.fromSupplier(() -> stateStore.containsKey(this.buildId(actorType, actorId, stateName))); - } - - @Override - Mono apply(String actorType, ActorId actorId, ActorStateChange... stateChanges) { - return Mono.fromRunnable(() -> { - try { - for (ActorStateChange stateChange : stateChanges) { - String stateId = buildId(actorType, actorId, stateChange.getStateName()); - switch (stateChange.getChangeKind()) { - case REMOVE: - stateStore.remove(stateId); - break; - case ADD: - case UPDATE: - byte[] raw = this.serializer.serialize(stateChange.getValue()); - stateStore.put(stateId, raw); - break; - } - } - - } catch (Exception e) { - throw new RuntimeException(e); - } - }); - } - - private static final String buildId(String actorType, ActorId actorId, String stateName) { - return String.format("%s||%s||%s", actorType, actorId.toString(), stateName); - } -} +/* + * Copyright 2021 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. +*/ + +package io.dapr.actors.runtime; + +import io.dapr.actors.ActorId; +import io.dapr.serializer.DaprObjectSerializer; +import io.dapr.utils.TypeRef; +import reactor.core.publisher.Mono; + +import java.io.IOException; +import java.time.Instant; +import java.util.HashMap; +import java.util.Map; + +/** + * Fake state provider for tests in Actors - data is kept in memory only. + */ +public class DaprInMemoryStateProvider extends DaprStateAsyncProvider { + + private static final Map> stateStore = new HashMap<>(); + + private final DaprObjectSerializer serializer; + + DaprInMemoryStateProvider(DaprObjectSerializer serializer) { + super(null, serializer /* just to avoid NPE */); + this.serializer = serializer; + } + + @Override + Mono> load(String actorType, ActorId actorId, String stateName, TypeRef type) { + return Mono.fromSupplier(() -> { + try { + String stateId = this.buildId(actorType, actorId, stateName); + if (!stateStore.containsKey(stateId)) { + throw new IllegalStateException("State not found."); + } + + var state = this.stateStore.get(stateId); + if (state.getExpiration() != null) { + if (!state.getExpiration().isAfter(Instant.now())) { + throw new IllegalStateException("State expired."); + } + } + var v = this.serializer.deserialize(state.getValue(), type); + return new ActorState<>(stateName, v, state.getExpiration()); + } catch (IOException e) { + throw new RuntimeException(e); + } + }); + } + + private boolean contains(String stateId) { + if (!stateStore.containsKey(stateId)) { + return false; + } + + var state = this.stateStore.get(stateId); + if (state.getExpiration() != null) { + if (!state.getExpiration().isAfter(Instant.now())) { + return false; + } + } + + return true; + } + + @Override + Mono contains(String actorType, ActorId actorId, String stateName) { + return Mono.fromSupplier(() -> contains(this.buildId(actorType, actorId, stateName))); + } + + @Override + Mono apply(String actorType, ActorId actorId, ActorStateChange... stateChanges) { + return Mono.fromRunnable(() -> { + try { + for (ActorStateChange stateChange : stateChanges) { + String stateId = buildId(actorType, actorId, stateChange.getState().getName()); + switch (stateChange.getChangeKind()) { + case REMOVE: + stateStore.remove(stateId); + break; + case ADD: + case UPDATE: + byte[] raw = this.serializer.serialize(stateChange.getState().getValue()); + stateStore.put(stateId, + new ActorState<>(stateChange.getState().getName(), raw, stateChange.getState().getExpiration())); + break; + } + } + + } catch (Exception e) { + throw new RuntimeException(e); + } + }); + } + + private static final String buildId(String actorType, ActorId actorId, String stateName) { + return String.format("%s||%s||%s", actorType, actorId.toString(), stateName); + } +} diff --git a/sdk-actors/src/test/java/io/dapr/actors/runtime/DaprStateAsyncProviderTest.java b/sdk-actors/src/test/java/io/dapr/actors/runtime/DaprStateAsyncProviderTest.java index a24bf72719..b8a03759f3 100644 --- a/sdk-actors/src/test/java/io/dapr/actors/runtime/DaprStateAsyncProviderTest.java +++ b/sdk-actors/src/test/java/io/dapr/actors/runtime/DaprStateAsyncProviderTest.java @@ -110,13 +110,13 @@ public void happyCaseApply() { if (operation.getOperationType() == null) { return false; } - if (operation.getKey() == null) { + if (operation.getState().getName() == null) { return false; } String opName = operation.getOperationType(); - String key = operation.getKey(); - Object value = operation.getValue(); + String key = operation.getState().getName(); + Object value = operation.getState().getValue(); foundInsertName |= "upsert".equals(opName) && "name".equals(key) && @@ -153,58 +153,59 @@ public void happyCaseLoad() throws Exception { DaprClient daprClient = mock(DaprClient.class); when(daprClient .getState(any(), any(), eq("name"))) - .thenReturn(Mono.just(SERIALIZER.serialize("Jon Doe"))); + .thenReturn(Mono.just(new ActorState<>("name", SERIALIZER.serialize("Jon Doe")))); when(daprClient .getState(any(), any(), eq("zipcode"))) - .thenReturn(Mono.just(SERIALIZER.serialize(98021))); + .thenReturn(Mono.just(new ActorState<>("zipcode", SERIALIZER.serialize(98021)))); when(daprClient .getState(any(), any(), eq("goals"))) - .thenReturn(Mono.just(SERIALIZER.serialize(98))); + .thenReturn(Mono.just(new ActorState<>("goals", SERIALIZER.serialize(98)))); when(daprClient .getState(any(), any(), eq("balance"))) - .thenReturn(Mono.just(SERIALIZER.serialize(46.55))); + .thenReturn(Mono.just(new ActorState<>("balance", SERIALIZER.serialize(46.55)))); when(daprClient .getState(any(), any(), eq("active"))) - .thenReturn(Mono.just(SERIALIZER.serialize(true))); + .thenReturn(Mono.just(new ActorState<>("active", SERIALIZER.serialize(true)))); when(daprClient .getState(any(), any(), eq("customer"))) - .thenReturn(Mono.just("{ \"id\": 1000, \"name\": \"Roxane\"}".getBytes())); + .thenReturn(Mono.just(new ActorState<>("customer", "{ \"id\": 1000, \"name\": \"Roxane\"}".getBytes()))); when(daprClient .getState(any(), any(), eq("anotherCustomer"))) - .thenReturn(Mono.just("{ \"id\": 2000, \"name\": \"Max\"}".getBytes())); + .thenReturn(Mono.just(new ActorState<>("anotherCustomer", "{ \"id\": 2000, \"name\": \"Max\"}".getBytes()))); when(daprClient .getState(any(), any(), eq("nullCustomer"))) .thenReturn(Mono.empty()); when(daprClient .getState(any(), any(), eq("bytes"))) - .thenReturn(Mono.just("\"QQ==\"".getBytes())); + .thenReturn(Mono.just(new ActorState<>("bytes", "\"QQ==\"".getBytes()))); when(daprClient .getState(any(), any(), eq("emptyBytes"))) - .thenReturn(Mono.just(new byte[0])); + .thenReturn(Mono.just(new ActorState<>("emptyBytes", new byte[0]))); DaprStateAsyncProvider provider = new DaprStateAsyncProvider(daprClient, SERIALIZER); Assertions.assertEquals("Jon Doe", - provider.load("MyActor", new ActorId("123"), "name", TypeRef.STRING).block()); + provider.load("MyActor", new ActorId("123"), "name", TypeRef.STRING).block().getValue()); Assertions.assertEquals(98021, - (int) provider.load("MyActor", new ActorId("123"), "zipcode", TypeRef.INT).block()); + (int) provider.load("MyActor", new ActorId("123"), "zipcode", TypeRef.INT).block().getValue()); Assertions.assertEquals(98, - (int) provider.load("MyActor", new ActorId("123"), "goals", TypeRef.INT).block()); + (int) provider.load("MyActor", new ActorId("123"), "goals", TypeRef.INT).block().getValue()); Assertions.assertEquals(98, - (int) provider.load("MyActor", new ActorId("123"), "goals", TypeRef.INT).block()); + (int) provider.load("MyActor", new ActorId("123"), "goals", TypeRef.INT).block().getValue()); Assertions.assertEquals(46.55, - (double) provider.load("MyActor", new ActorId("123"), "balance", TypeRef.DOUBLE).block(), + (double) provider.load("MyActor", new ActorId("123"), "balance", TypeRef.DOUBLE).block().getValue(), EPSILON); Assertions.assertEquals(true, - (boolean) provider.load("MyActor", new ActorId("123"), "active", TypeRef.BOOLEAN).block()); + (boolean) provider.load("MyActor", new ActorId("123"), "active", TypeRef.BOOLEAN).block().getValue()); Assertions.assertEquals(new Customer().setId(1000).setName("Roxane"), - provider.load("MyActor", new ActorId("123"), "customer", TypeRef.get(Customer.class)).block()); + provider.load("MyActor", new ActorId("123"), "customer", TypeRef.get(Customer.class)).block().getValue()); Assertions.assertNotEquals(new Customer().setId(1000).setName("Roxane"), - provider.load("MyActor", new ActorId("123"), "anotherCustomer", TypeRef.get(Customer.class)).block()); + provider.load( + "MyActor", new ActorId("123"), "anotherCustomer", TypeRef.get(Customer.class)).block().getValue()); Assertions.assertNull( provider.load("MyActor", new ActorId("123"), "nullCustomer", TypeRef.get(Customer.class)).block()); Assertions.assertArrayEquals("A".getBytes(), - provider.load("MyActor", new ActorId("123"), "bytes", TypeRef.get(byte[].class)).block()); + provider.load("MyActor", new ActorId("123"), "bytes", TypeRef.get(byte[].class)).block().getValue()); Assertions.assertNull( provider.load("MyActor", new ActorId("123"), "emptyBytes", TypeRef.get(byte[].class)).block()); } @@ -216,22 +217,28 @@ public void happyCaseContains() { // Keys that exists. when(daprClient .getState(any(), any(), eq("name"))) - .thenReturn(Mono.just("Jon Doe".getBytes())); + .thenReturn(Mono.just( + new ActorState<>("name", "Jon Doe".getBytes()))); when(daprClient .getState(any(), any(), eq("zipcode"))) - .thenReturn(Mono.just("98021".getBytes())); + .thenReturn(Mono.just( + new ActorState<>("zipcode", "98021".getBytes()))); when(daprClient .getState(any(), any(), eq("goals"))) - .thenReturn(Mono.just("98".getBytes())); + .thenReturn(Mono.just( + new ActorState<>("goals", "98".getBytes()))); when(daprClient .getState(any(), any(), eq("balance"))) - .thenReturn(Mono.just("46.55".getBytes())); + .thenReturn(Mono.just( + new ActorState<>("balance", "46.55".getBytes()))); when(daprClient .getState(any(), any(), eq("active"))) - .thenReturn(Mono.just("true".getBytes())); + .thenReturn(Mono.just( + new ActorState<>("active", "true".getBytes()))); when(daprClient .getState(any(), any(), eq("customer"))) - .thenReturn(Mono.just("{ \"id\": \"3000\", \"name\": \"Ely\" }".getBytes())); + .thenReturn(Mono.just( + new ActorState<>("customer", "{ \"id\": \"3000\", \"name\": \"Ely\" }".getBytes()))); // Keys that do not exist. when(daprClient @@ -257,15 +264,15 @@ public void happyCaseContains() { Assertions.assertFalse(provider.contains("MyActor", new ActorId("123"), null).block()); } - private final ActorStateChange createInsertChange(String name, T value) { - return new ActorStateChange(name, value, ActorStateChangeKind.ADD); + private ActorStateChange createInsertChange(String name, T value) { + return new ActorStateChange(new ActorState(name, value), ActorStateChangeKind.ADD); } - private final ActorStateChange createUpdateChange(String name, T value) { - return new ActorStateChange(name, value, ActorStateChangeKind.UPDATE); + private ActorStateChange createUpdateChange(String name, T value) { + return new ActorStateChange(new ActorState(name, value), ActorStateChangeKind.UPDATE); } - private final ActorStateChange createDeleteChange(String name) { - return new ActorStateChange(name, null, ActorStateChangeKind.REMOVE); + private ActorStateChange createDeleteChange(String name) { + return new ActorStateChange(new ActorState(name, null), ActorStateChangeKind.REMOVE); } } diff --git a/sdk-tests/src/test/java/io/dapr/it/actors/ActorStateTtlIT.java b/sdk-tests/src/test/java/io/dapr/it/actors/ActorStateTtlIT.java new file mode 100644 index 0000000000..5c0e6a225a --- /dev/null +++ b/sdk-tests/src/test/java/io/dapr/it/actors/ActorStateTtlIT.java @@ -0,0 +1,125 @@ +/* + * Copyright 2026 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. +*/ + +package io.dapr.it.actors; + +import io.dapr.actors.ActorId; +import io.dapr.actors.client.ActorProxy; +import io.dapr.actors.client.ActorProxyBuilder; +import io.dapr.it.AppRun; +import io.dapr.it.actors.services.springboot.StatefulActorService; +import io.dapr.it.containers.BaseContainerIT; +import io.dapr.testcontainers.Configuration; +import io.dapr.testcontainers.DaprContainer; +import io.dapr.testcontainers.Feature; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.List; + +import static io.dapr.it.Retry.callWithRetry; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +/** + * Actor state TTL against a MySQL state store, with the ActorStateTTL + * preview feature enabled. Redis does not return the ttlExpireTime of a + * state key, so the other actor tests stay on Redis and only this test + * uses MySQL. + */ +public class ActorStateTtlIT extends BaseContainerIT { + + private static Logger logger = LoggerFactory.getLogger(ActorStateTtlIT.class); + + private static DaprContainer dapr; + private static AppRun app; + + @BeforeAll + public static void start() throws Exception { + var pair = startAppAndAttach( + "actor-state-ttl-it", + StatefulActorService.class, + AppRun.AppProtocol.HTTP, + appPort -> daprBuilder("actor-state-ttl-it") + .withAppPort(appPort) + .withAppChannelAddress("host.testcontainers.internal") + .withComponent(mysqlStateStore(STATE_STORE_NAME)) + .withConfiguration(new Configuration("actor-state-ttl", + null, null, null, null, null, null, null, null, null, + List.of(new Feature("ActorStateTTL", true))))); + dapr = pair.dapr(); + app = pair.app(); + waitForActorsReady(dapr); + } + + @Test + public void stateExpiresFromCacheAndStore() throws Exception { + ActorId actorId = new ActorId( + String.format("%d", System.currentTimeMillis())); + String actorType = "StatefulActorTest"; + ActorProxyBuilder proxyBuilder = + new ActorProxyBuilder(actorType, ActorProxy.class, newActorClient(dapr)); + ActorProxy proxy = proxyBuilder.build(actorId); + + // waiting for actor to be activated + Thread.sleep(5000); + + // The value is readable while its TTL has not elapsed. + callWithRetry(() -> { + logger.debug("Invoking writeMessageWithTtl ... "); + proxy.invokeMethod("writeMessageWithTtl", "expires soon").block(); + }, 5000); + + callWithRetry(() -> { + logger.debug("Invoking readMessage where data is still cached ... "); + String result = proxy.invokeMethod("readMessage", String.class).block(); + assertEquals("expires soon", result); + }, 5000); + + // Once the TTL elapses the cached value is no longer served. + Thread.sleep(3000); + + callWithRetry(() -> { + logger.debug("Invoking readMessage after the TTL elapsed ... "); + String result = proxy.invokeMethod("readMessage", String.class).block(); + assertNull(result); + }, 5000); + + // The store itself expires the key too: write again, wait out the TTL, + // then restart the app so the actor reloads from MySQL with a cold cache. + callWithRetry(() -> { + logger.debug("Invoking writeMessageWithTtl again ... "); + proxy.invokeMethod("writeMessageWithTtl", "expires soon").block(); + }, 5000); + + Thread.sleep(3000); + + logger.debug("Restarting app ..."); + restartApp(app); + + // Need new proxy builder because the proxy builder holds the channel. + proxyBuilder = new ActorProxyBuilder(actorType, ActorProxy.class, newActorClient(dapr)); + ActorProxy newProxy = proxyBuilder.build(actorId); + + // waiting for actor to be activated + Thread.sleep(2000); + + callWithRetry(() -> { + logger.debug("Invoking readMessage where data expired in the store ... "); + String result = newProxy.invokeMethod("readMessage", String.class).block(); + assertNull(result); + }, 5000); + } +} diff --git a/sdk-tests/src/test/java/io/dapr/it/actors/services/springboot/StatefulActor.java b/sdk-tests/src/test/java/io/dapr/it/actors/services/springboot/StatefulActor.java index 981a84dc0a..0c1aa8f9b2 100644 --- a/sdk-tests/src/test/java/io/dapr/it/actors/services/springboot/StatefulActor.java +++ b/sdk-tests/src/test/java/io/dapr/it/actors/services/springboot/StatefulActor.java @@ -17,6 +17,8 @@ public interface StatefulActor { void writeMessage(String something); + void writeMessageWithTtl(String something); + String readMessage(); void writeName(String something); diff --git a/sdk-tests/src/test/java/io/dapr/it/actors/services/springboot/StatefulActorImpl.java b/sdk-tests/src/test/java/io/dapr/it/actors/services/springboot/StatefulActorImpl.java index f37e69ca8c..b53d339f27 100644 --- a/sdk-tests/src/test/java/io/dapr/it/actors/services/springboot/StatefulActorImpl.java +++ b/sdk-tests/src/test/java/io/dapr/it/actors/services/springboot/StatefulActorImpl.java @@ -18,6 +18,8 @@ import io.dapr.actors.runtime.AbstractActor; import io.dapr.actors.runtime.ActorRuntimeContext; +import java.time.Duration; + @ActorType(name = "StatefulActorTest") public class StatefulActorImpl extends AbstractActor implements StatefulActor { @@ -30,6 +32,11 @@ public void writeMessage(String something) { super.getActorStateManager().set("message", something).block(); } + @Override + public void writeMessageWithTtl(String something) { + super.getActorStateManager().set("message", something, Duration.ofSeconds(2)).block(); + } + @Override public String readMessage() { if (super.getActorStateManager().contains("message").block()) { diff --git a/sdk-tests/src/test/java/io/dapr/it/containers/BaseContainerIT.java b/sdk-tests/src/test/java/io/dapr/it/containers/BaseContainerIT.java index 3298a0c0c5..9ff598251d 100644 --- a/sdk-tests/src/test/java/io/dapr/it/containers/BaseContainerIT.java +++ b/sdk-tests/src/test/java/io/dapr/it/containers/BaseContainerIT.java @@ -380,6 +380,20 @@ protected static Component mongoStateStore(String name) { )); } + /** + * MySQL-backed state store. Lazily starts the shared MySQL container before + * returning the component. Used only by the actor state TTL test: MySQL + * returns the ttlExpireTime of a state key, which Redis does not, so the + * other actor tests stay on Redis. + */ + protected static Component mysqlStateStore(String name) { + SharedTestInfra.mysql(); // ensure MySQL is up before DaprContainer needs it + return new Component(name, "state.mysql", "v1", Map.of( + "connectionString", SharedTestInfra.mysqlConnectionString(), + "actorStateStore", "true" + )); + } + /** * Kafka-backed input/output binding. Lazily starts the shared Kafka container * before returning the component. The {@code {appID}} placeholders in diff --git a/sdk-tests/src/test/java/io/dapr/it/containers/SharedTestInfra.java b/sdk-tests/src/test/java/io/dapr/it/containers/SharedTestInfra.java index 0fa55770b7..1ec60f922f 100644 --- a/sdk-tests/src/test/java/io/dapr/it/containers/SharedTestInfra.java +++ b/sdk-tests/src/test/java/io/dapr/it/containers/SharedTestInfra.java @@ -32,6 +32,7 @@ public final class SharedTestInfra { private static final String REDIS_NETWORK_ALIAS = "redis"; private static final String ZIPKIN_NETWORK_ALIAS = "zipkin"; private static final String MONGO_NETWORK_ALIAS = "mongo"; + private static final String MYSQL_NETWORK_ALIAS = "mysql"; private static final String KAFKA_NETWORK_ALIAS = "kafka"; private static final String PLACEMENT_NETWORK_ALIAS = "placement"; private static final String SCHEDULER_NETWORK_ALIAS = "scheduler"; @@ -40,6 +41,7 @@ public final class SharedTestInfra { private static volatile GenericContainer redis; private static volatile GenericContainer zipkin; private static volatile GenericContainer mongo; + private static volatile GenericContainer mysql; private static volatile org.testcontainers.kafka.KafkaContainer kafka; private static volatile DaprPlacementContainer placement; private static volatile DaprSchedulerContainer scheduler; @@ -101,6 +103,34 @@ public static String mongoInternalHost() { return MONGO_NETWORK_ALIAS + ":27017"; } + /** + * MySQL 8 shared by the actor state TTL test. Unlike Redis, MySQL returns + * the ttlExpireTime of a state key, which is what the actor state TTL + * support needs to know a cached value has expired. + */ + public static synchronized GenericContainer mysql() { + if (mysql == null) { + mysql = new GenericContainer<>(DockerImageName.parse("mysql:8")) + .withNetwork(network()) + .withNetworkAliases(MYSQL_NETWORK_ALIAS) + .withEnv("MYSQL_ROOT_PASSWORD", "dapr") + .withEnv("MYSQL_DATABASE", "dapr") + .withExposedPorts(3306) + .withReuse(true); + mysql.start(); + } + return mysql; + } + + public static String mysqlInternalHost() { + return MYSQL_NETWORK_ALIAS + ":3306"; + } + + /** Connection string for the shared MySQL, as the Dapr MySQL state store expects it. */ + public static String mysqlConnectionString() { + return "root:dapr@tcp(" + mysqlInternalHost() + ")/dapr"; + } + public static synchronized org.testcontainers.kafka.KafkaContainer kafka() { if (kafka == null) { kafka = new org.testcontainers.kafka.KafkaContainer("apache/kafka:3.8.0") diff --git a/testcontainers-dapr/src/main/java/io/dapr/testcontainers/Configuration.java b/testcontainers-dapr/src/main/java/io/dapr/testcontainers/Configuration.java index d2383f2821..d750925c8d 100644 --- a/testcontainers-dapr/src/main/java/io/dapr/testcontainers/Configuration.java +++ b/testcontainers-dapr/src/main/java/io/dapr/testcontainers/Configuration.java @@ -16,6 +16,8 @@ /** * Represents a Dapr component. */ +import java.util.List; + public class Configuration { private final String name; private final TracingConfigurationSettings tracing; @@ -27,6 +29,7 @@ public class Configuration { private final ComponentsConfigurationSettings components; private final SecretsConfigurationSettings secrets; private final HttpPipeline httpPipeline; + private final List features; /** * Creates a new configuration. @@ -204,6 +207,39 @@ public Configuration( ComponentsConfigurationSettings components, SecretsConfigurationSettings secrets, HttpPipeline httpPipeline + ) { + this(name, tracing, appHttpPipeline, mtls, logging, metrics, nameResolution, components, secrets, httpPipeline, + null); + } + + /** + * Creates a new configuration. + * + * @param name Configuration name. + * @param tracing TracingConfigParameters tracing configuration + * parameters. + * @param appHttpPipeline AppHttpPipeline middleware configuration. + * @param mtls MtlsConfigurationSettings mTLS configuration. + * @param logging LoggingConfigurationSettings logging configuration. + * @param metrics MetricsConfigurationSettings metrics configuration. + * @param nameResolution NameResolutionConfigurationSettings name resolution configuration. + * @param components ComponentsConfigurationSettings disallowed component types configuration. + * @param secrets SecretsConfigurationSettings secret store access configuration. + * @param httpPipeline HttpPipeline middleware configuration for incoming requests. + * @param features Preview feature flags. + */ + public Configuration( + String name, + TracingConfigurationSettings tracing, + AppHttpPipeline appHttpPipeline, + MtlsConfigurationSettings mtls, + LoggingConfigurationSettings logging, + MetricsConfigurationSettings metrics, + NameResolutionConfigurationSettings nameResolution, + ComponentsConfigurationSettings components, + SecretsConfigurationSettings secrets, + HttpPipeline httpPipeline, + List features ) { this.name = name; this.tracing = tracing; @@ -215,6 +251,7 @@ public Configuration( this.components = components; this.secrets = secrets; this.httpPipeline = httpPipeline; + this.features = features; } public String getName() { @@ -256,4 +293,8 @@ public SecretsConfigurationSettings getSecrets() { public HttpPipeline getHttpPipeline() { return httpPipeline; } + + public List getFeatures() { + return features; + } } diff --git a/testcontainers-dapr/src/main/java/io/dapr/testcontainers/Feature.java b/testcontainers-dapr/src/main/java/io/dapr/testcontainers/Feature.java new file mode 100644 index 0000000000..154d53d438 --- /dev/null +++ b/testcontainers-dapr/src/main/java/io/dapr/testcontainers/Feature.java @@ -0,0 +1,44 @@ +/* + * Copyright 2026 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. +*/ + +package io.dapr.testcontainers; + +/** + * A Dapr preview feature flag, as listed under {@code spec.features} of a + * Configuration resource. + */ +public class Feature { + private String name; + private Boolean enabled; + + public Feature(String name, Boolean enabled) { + this.name = name; + this.enabled = enabled; + } + + public String getName() { + return name; + } + + public Boolean getEnabled() { + return enabled; + } + + public void setName(String name) { + this.name = name; + } + + public void setEnabled(Boolean enabled) { + this.enabled = enabled; + } +} diff --git a/testcontainers-dapr/src/main/java/io/dapr/testcontainers/converter/ConfigurationYamlConverter.java b/testcontainers-dapr/src/main/java/io/dapr/testcontainers/converter/ConfigurationYamlConverter.java index 2e33064b7a..252373cfd7 100644 --- a/testcontainers-dapr/src/main/java/io/dapr/testcontainers/converter/ConfigurationYamlConverter.java +++ b/testcontainers-dapr/src/main/java/io/dapr/testcontainers/converter/ConfigurationYamlConverter.java @@ -17,6 +17,7 @@ import io.dapr.testcontainers.AppHttpPipeline; import io.dapr.testcontainers.ComponentsConfigurationSettings; import io.dapr.testcontainers.Configuration; +import io.dapr.testcontainers.Feature; import io.dapr.testcontainers.HttpMetricsConfigurationSettings; import io.dapr.testcontainers.HttpPipeline; import io.dapr.testcontainers.ListEntry; @@ -280,6 +281,20 @@ public String convert(Configuration configuration) { configurationSpec.put("secrets", secretsMap); } + List features = configuration.getFeatures(); + if (features != null && !features.isEmpty()) { + List> featuresList = new ArrayList<>(); + + for (Feature feature : features) { + Map featureMap = new LinkedHashMap<>(); + featureMap.put("name", feature.getName()); + putIfNotNull(featureMap, "enabled", feature.getEnabled()); + featuresList.add(featureMap); + } + + configurationSpec.put("features", featuresList); + } + configurationProps.put("spec", configurationSpec); return mapper.dumpAsMap(configurationProps); diff --git a/testcontainers-dapr/src/test/java/io/dapr/testcontainers/converter/ConfigurationYamlConverterTest.java b/testcontainers-dapr/src/test/java/io/dapr/testcontainers/converter/ConfigurationYamlConverterTest.java index 801bb1752a..f1d14e9c7f 100644 --- a/testcontainers-dapr/src/test/java/io/dapr/testcontainers/converter/ConfigurationYamlConverterTest.java +++ b/testcontainers-dapr/src/test/java/io/dapr/testcontainers/converter/ConfigurationYamlConverterTest.java @@ -18,6 +18,7 @@ import io.dapr.testcontainers.ComponentsConfigurationSettings; import io.dapr.testcontainers.Configuration; import io.dapr.testcontainers.DaprContainer; +import io.dapr.testcontainers.Feature; import io.dapr.testcontainers.HttpMetricsConfigurationSettings; import io.dapr.testcontainers.HttpPipeline; import io.dapr.testcontainers.ListEntry; @@ -174,6 +175,28 @@ public void testConfigurationWithMinimalMtlsToYaml() { assertEquals(expectedConfigurationYaml, configurationYaml); } + @Test + public void testConfigurationWithFeaturesToYaml() { + List features = new ArrayList<>(); + features.add(new Feature("ActorStateTTL", true)); + + Configuration configuration = new Configuration( + "my-config", null, null, null, null, null, null, null, null, null, features); + + String configurationYaml = converter.convert(configuration); + String expectedConfigurationYaml = + "apiVersion: dapr.io/v1alpha1\n" + + "kind: Configuration\n" + + "metadata:\n" + + " name: my-config\n" + + "spec:\n" + + " features:\n" + + " - name: ActorStateTTL\n" + + " enabled: true\n"; + + assertEquals(expectedConfigurationYaml, configurationYaml); + } + @Test public void testConfigurationWithMtlsWithoutTokenValidatorsToYaml() { MtlsConfigurationSettings mtls = new MtlsConfigurationSettings(